Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(chat): add Chat's flag, its core tables and the events a run streams (#1758)
Cihan713107624211
diff --git a/server/.env.example b/server/.env.exampleindex b658f6544..65f71df99 100644--- a/server/.env.example+++ b/server/.env.example@@ -75,6 +75,14 @@ COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview# ACTION_TASKS_AI=# The model that writes them. Falls back to IMPROVE_SUGGESTION_MODEL.# ACTION_TASKS_MODEL=+# Chat: the new Chat (Drive Chat specs, CHAT-00…25), off unless "true"; a+# change applies when the server starts again (a restart or a new+# deployment). Off, today's agent stays as it is. Set the web's+# CHAT_AGENTIC and CHAT_AGENTIC_ORGS to the same values.+# CHAT_AGENTIC_ORGS: with Chat on, only these organizations (ids,+# comma-separated); empty = every organization.+# CHAT_AGENTIC=+# CHAT_AGENTIC_ORGS=# Content Editor Quality (Drive quality spec): which phase is live on the# server, 0 (unset) for none, as the web's NEXT_PUBLIC_CONTENT_QUALITY_PHASE.# 2 tells the Content Agent the brand's site type (CE-056), and turns on thediff --git a/server/src/lib/chat-flag.js b/server/src/lib/chat-flag.jsnew file mode 100644index 000000000..6a1cd5c7a--- /dev/null+++ b/server/src/lib/chat-flag.js@@ -0,0 +1,28 @@+/**+ * The new Chat (the Drive Chat specs, CHAT-00…25) behind CHAT_AGENTIC.+ *+ * Read from the environment each time it is asked; the process sees a change+ * when it starts again (a restart or a new deployment). Off unless+ * "true", so a self-hosted install — or the cloud with it unset — keeps+ * today's agent and sees nothing new. With it on, CHAT_AGENTIC_ORGS+ * (organization ids, comma-separated) narrows it to those workspaces; unset+ * or empty, it is on for every one. The web's lib/chat/flag.ts reads the same+ * two variables the same way.+ *+ * @param {string | null | undefined} [organizationId]+ * @returns {boolean}+ */+export function chatAgenticEnabled(organizationId) {+ if (process.env.CHAT_AGENTIC !== 'true') return false;+ const orgs = chatAgenticOrgs();+ if (orgs.length === 0) return true;+ return !!organizationId && orgs.includes(String(organizationId).trim().toLowerCase());+}++/** CHAT_AGENTIC_ORGS as a list: trimmed, lower-cased, blanks dropped. */+function chatAgenticOrgs() {+ return (process.env.CHAT_AGENTIC_ORGS ?? '')+ .split(',')+ .map((id) => id.trim().toLowerCase())+ .filter(Boolean);+}diff --git a/server/src/lib/chat-flag.test.js b/server/src/lib/chat-flag.test.jsnew file mode 100644index 000000000..094145228--- /dev/null+++ b/server/src/lib/chat-flag.test.js@@ -0,0 +1,63 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { chatAgenticEnabled } from './chat-flag.js';++/** The new Chat's switch: CHAT_AGENTIC, narrowed by CHAT_AGENTIC_ORGS. */++const ORG_A = '22222222-2222-4222-8222-222222222222';+const ORG_B = '33333333-3333-4333-8333-333333333333';++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('chatAgenticEnabled', () => {+ it('is off when CHAT_AGENTIC is unset, so a self-hosted install sees nothing new', () => {+ vi.stubEnv('CHAT_AGENTIC', undefined);+ vi.stubEnv('CHAT_AGENTIC_ORGS', undefined);+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ expect(chatAgenticEnabled()).toBe(false);+ });++ it('is off for anything but "true"', () => {+ for (const value of ['', 'false', '1', 'yes', 'TRUE', ' true']) {+ vi.stubEnv('CHAT_AGENTIC', value);+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ }+ });++ it('is on for every organization when CHAT_AGENTIC_ORGS is unset or empty', () => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ for (const orgs of [undefined, '', ' , ,']) {+ vi.stubEnv('CHAT_AGENTIC_ORGS', orgs);+ expect(chatAgenticEnabled(ORG_A)).toBe(true);+ expect(chatAgenticEnabled(ORG_B)).toBe(true);+ expect(chatAgenticEnabled()).toBe(true);+ }+ });++ it('is on only for the listed organizations when CHAT_AGENTIC_ORGS is set', () => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ vi.stubEnv(+ 'CHAT_AGENTIC_ORGS',+ ` ${ORG_A.toUpperCase()} , 44444444-4444-4444-8444-444444444444`,+ );+ expect(chatAgenticEnabled(ORG_A)).toBe(true);+ expect(chatAgenticEnabled(` ${ORG_A} `)).toBe(true);+ expect(chatAgenticEnabled(ORG_B)).toBe(false);+ expect(chatAgenticEnabled(null)).toBe(false);+ expect(chatAgenticEnabled()).toBe(false);+ });++ it("doesn't turn Chat on with CHAT_AGENTIC_ORGS alone", () => {+ vi.stubEnv('CHAT_AGENTIC', undefined);+ vi.stubEnv('CHAT_AGENTIC_ORGS', ORG_A);+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ });++ it('reads the variables when asked, not when loaded', () => {+ vi.stubEnv('CHAT_AGENTIC', 'false');+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ vi.stubEnv('CHAT_AGENTIC', 'true');+ expect(chatAgenticEnabled(ORG_A)).toBe(true);+ });+});diff --git a/supabase/migrations/00400_chat_core.sql b/supabase/migrations/00400_chat_core.sqlnew file mode 100644index 000000000..9856eb0c0--- /dev/null+++ b/supabase/migrations/00400_chat_core.sql@@ -0,0 +1,366 @@+-- ============================================================================+-- 00400: Chat's core — chats, their messages, runs and steps, and each+-- person's Chat settings+-- ============================================================================+-- The new Chat (the Drive Chat specs, CHAT-00…25), behind CHAT_AGENTIC:+-- nothing reads these tables while the flag is off, and agent_conversations+-- and agent_messages (00009) keep serving today's /dashboard/agent as they do.+--+-- * chat_conversations: one chat. Private to its author (CHAT-20 §16c):+-- only they read it, admins included; the server writes it. brand_id is+-- the brand it is about, null for the workspace as a whole (a Help+-- question). A deleted brand leaves its chats with their author, then+-- about the workspace, as agent_conversations does (00009).+-- * chat_messages: the person's messages and Chat's answers. An answer+-- holds the answer only, never a tool's output (content_md; CHAT-03 item+-- 23), and when it was made: generated_at, the newest data it read+-- (data_as_of) and the time zone it was shown in (CHAT-06 items 38–42).+-- * chat_runs: the work behind one answer (one run, one answer: CHAT-00):+-- its status, the model and effort it ran with, and its times. Its chat+-- is kept equal to its answer's by the foreign key.+-- * chat_run_steps: a run's steps in order (CHAT-03). What the person sees+-- (kind, label, detail, scope in names, row count, status) and, for the+-- server and staff only, the tool that ran and its debug record: members+-- are granted every column but those two (the grants below).+-- * chat_step_kinds: the kinds a step can be. A table, not a check: a new+-- kind (CHAT-03 added `execute`; the Content Editor and images add more)+-- is a row a later migration inserts, with no constraint to rewrite and+-- no scan of the steps. Kinds aren't taken away: a step keeps its kind+-- (the key refuses deleting one in use, and finding out reads every step,+-- with no index on kind). The web's CHAT_STEP_KINDS (lib/chat/events.ts)+-- lists the same kinds; its test reads them from the migrations.+-- * chat_user_prefs: a person's Chat settings, on the server so they follow+-- them to every device (DECISIONS N3): the chat menu open or closed+-- (CHAT-01 9a–9f), where pages open (CHAT-25 §12), what Chat focuses on+-- (CHAT-24 §3), and their model and effort (CHAT-16; null = the+-- workspace's default, Auto and Normal). Theirs to write; the server+-- checks the model against its catalog before a run uses it.+--+-- Messages, runs and steps are readable where their chat is (they follow its+-- policies), so sharing a chat with the team is one more policy on+-- chat_conversations later. Approvals, the activity log with Undo, and AI+-- budget metering bring their own tables and columns in later migrations.++-- ─── Step kinds ─────────────────────────────────────────────────────────────++create table if not exists public.chat_step_kinds (+ kind text primary key check (kind ~ '^[a-z][a-z_]{1,39}$')+);++-- CHAT-03 "Labels by kind", and `execute` (CHAT-03 v2) for a step that waits+-- on the person's click.+insert into public.chat_step_kinds (kind) values+ ('thinking'), ('read'), ('open_page'), ('skill'), ('check'),+ ('write'), ('ask'), ('schedule'), ('image'), ('execute')+on conflict (kind) do nothing;++-- The server's list: members read a step's kind on the step itself.+alter table public.chat_step_kinds enable row level security;+revoke all on table public.chat_step_kinds from anon, authenticated;+grant all on table public.chat_step_kinds to service_role;++comment on table public.chat_step_kinds is+ 'Chat (00400): the kinds a run step can be (CHAT-03). A new kind is a row a later migration inserts; web lib/chat/events.ts CHAT_STEP_KINDS lists the same.';++-- ─── Chats ──────────────────────────────────────────────────────────────────++create table if not exists public.chat_conversations (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ user_id uuid not null references auth.users(id) on delete cascade,+ -- Null: about the workspace as a whole, not one brand.+ brand_id uuid references public.brands(id) on delete set null,+ -- Null until Chat names it from the first message (CHAT-01 item 8); the+ -- web shows "New chat" meanwhile.+ title text check (char_length(title) between 1 and 200),+ -- The full Chat page or the side panel on another page (CHAT-01).+ origin text not null default 'page' check (origin in ('page', 'panel')),+ -- The route it was started on, for "Back to {page}" (CHAT-01).+ origin_page text check (char_length(origin_page) between 1 and 500),+ pinned_at timestamptz,+ archived_at timestamptz,+ -- Recents' order: the last message, not a rename or a pin. Kept by the+ -- trigger on chat_messages below.+ last_message_at timestamptz not null default now(),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists chat_conversations_user_recent_idx+ on public.chat_conversations (user_id, last_message_at desc);+create index if not exists chat_conversations_organization_idx+ on public.chat_conversations (organization_id);+create index if not exists chat_conversations_brand_idx+ on public.chat_conversations (brand_id) where brand_id is not null;++drop trigger if exists trg_chat_conversations_updated_at on public.chat_conversations;+create trigger trg_chat_conversations_updated_at+ before update on public.chat_conversations+ for each row execute function public.handle_updated_at();++comment on table public.chat_conversations is+ 'Chat (00400): one chat, private to its author (CHAT-20 §16c): only they read it, admins included. Written by the server.';++-- ─── Messages ───────────────────────────────────────────────────────────────++create table if not exists public.chat_messages (+ id uuid primary key default gen_random_uuid(),+ conversation_id uuid not null references public.chat_conversations(id) on delete cascade,+ role text not null check (role in ('user', 'assistant')),+ -- The message, or the answer only: a tool's output never goes here. Up to+ -- 200,000 characters: the server cuts or refuses a longer one first.+ content_md text not null default '' check (char_length(content_md) <= 200000),+ -- An answer's "Generated …" (UTC), the newest data it read ("Data as of",+ -- null when it read none) and the IANA time zone both were shown in.+ generated_at timestamptz,+ data_as_of timestamptz,+ timezone text check (char_length(timezone) between 1 and 64),+ -- clock_timestamp(): a question and its answer written in one statement+ -- still come in order.+ created_at timestamptz not null default clock_timestamp(),+ -- For chat_runs' key: a run's chat is its answer's.+ unique (id, conversation_id)+);++create index if not exists chat_messages_conversation_created_idx+ on public.chat_messages (conversation_id, created_at);++comment on table public.chat_messages is+ 'Chat (00400): a chat''s messages and answers. An answer holds the answer only, with when it was made and the newest data it read (CHAT-06 38–42). Written by the server.';++-- A new message moves its chat up Recents (last_message_at). Security+-- definer, so the update reaches the chat whoever writes the message: today+-- only the server does (service role), and members may not update chats.+-- greatest(): a message written late never moves its chat back. Not covered+-- by a test (the repository has no database tests); nothing else sets+-- last_message_at.+create or replace function public.chat_touch_last_message()+returns trigger+language plpgsql+security definer+set search_path = ''+as $$+begin+ update public.chat_conversations+ set last_message_at = greatest(last_message_at, new.created_at)+ where id = new.conversation_id;+ return new;+end;+$$;++drop trigger if exists trg_chat_messages_touch_conversation on public.chat_messages;+create trigger trg_chat_messages_touch_conversation+ after insert on public.chat_messages+ for each row execute function public.chat_touch_last_message();++-- ─── Runs ───────────────────────────────────────────────────────────────────++create table if not exists public.chat_runs (+ id uuid primary key default gen_random_uuid(),+ -- The answer this run writes, and that answer's chat.+ message_id uuid not null unique,+ conversation_id uuid not null,+ -- queued: waiting for a free run (CHAT-20 §14); waiting: on the person (a+ -- question, an approval, a click, a plan's Start); paused: paused by the+ -- person; paused_cap: the month's AI limit is used (CHAT-04).+ status text not null default 'queued' check (+ status in (+ 'queued', 'running', 'waiting', 'paused', 'paused_cap', 'done', 'error', 'stopped'+ )+ ),+ -- 'auto' or the model the person picked (CHAT-16).+ model text not null default 'auto' check (char_length(model) between 1 and 200),+ effort text not null default 'normal' check (effort in ('normal', 'high', 'max')),+ -- A standard result code (CHAT-20 §11a: 'failed', 'timeout'…) when it ended in error.+ error text check (error ~ '^[a-z_]{1,40}$'),+ created_at timestamptz not null default now(),+ started_at timestamptz,+ finished_at timestamptz,+ foreign key (message_id, conversation_id)+ references public.chat_messages (id, conversation_id) on delete cascade+);++create index if not exists chat_runs_conversation_created_idx+ on public.chat_runs (conversation_id, created_at desc);+-- The runs under way, oldest first: the queue, the runs tray, the sweeps.+create index if not exists chat_runs_open_idx+ on public.chat_runs (created_at)+ where status in ('queued', 'running', 'waiting', 'paused', 'paused_cap');++comment on table public.chat_runs is+ 'Chat (00400): the work behind one answer (CHAT-00: one run, one answer), with its status, model, effort and times. Written by the server.';++-- ─── Steps ──────────────────────────────────────────────────────────────────++create table if not exists public.chat_run_steps (+ id uuid primary key default gen_random_uuid(),+ run_id uuid not null references public.chat_runs(id) on delete cascade,+ -- Its place in the run, from 1: how a question or an approval names it to+ -- the browser, which gets no ids.+ position smallint not null check (position >= 1),+ kind text not null references public.chat_step_kinds(kind) on update cascade,+ -- pending: in a plan, not started; waiting: on the person.+ status text not null default 'running' check (+ status in ('pending', 'running', 'waiting', 'done', 'error', 'skipped')+ ),+ -- The label registry's words (CHAT-03): "Read Citations".+ label text not null check (char_length(label) between 1 and 200),+ -- "Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows", or an+ -- error's plain reason.+ detail text check (char_length(detail) between 1 and 500),+ -- What a read covered, in names only (subject, date range, platforms,+ -- brand): never ids. The tool's own arguments are in debug_json.+ scope_json jsonb check (+ scope_json is null+ or (jsonb_typeof(scope_json) = 'object' and octet_length(scope_json::text) <= 8000)+ ),+ row_count integer check (row_count >= 0),+ -- A read's newest data (CHAT-20 §15a); the answer's "Data as of" is the newest of them.+ data_as_of timestamptz,+ started_at timestamptz,+ finished_at timestamptz,+ -- Server and staff only (members aren't granted them): the registry name+ -- of the tool that ran, and what the staff Debug view shows (CHAT-03 items+ -- 25–26: input, output, model, tokens, latency). Up to 1 MB as text: the+ -- server shortens a large tool output before it keeps it here.+ tool text check (char_length(tool) between 1 and 100),+ debug_json jsonb check (+ debug_json is null+ or (jsonb_typeof(debug_json) = 'object' and octet_length(debug_json::text) <= 1000000)+ ),+ unique (run_id, position)+);++comment on table public.chat_run_steps is+ 'Chat (00400): a run''s steps in order (CHAT-03). Members read every column but tool and debug_json, which stay with the server and staff. Written by the server.';+comment on column public.chat_run_steps.scope_json is+ 'What a read covered, in names only (subject, dateRange, platforms, brand): never ids. Members read it.';+comment on column public.chat_run_steps.debug_json is+ 'The staff Debug view (CHAT-03 25–26): the tool''s input and output, model, tokens, latency. Never granted to members.';++-- ─── A person's Chat settings ───────────────────────────────────────────────++-- Whether a list has no value twice: a check can't hold a subquery.+create or replace function public.chat_text_array_distinct(p_values text[])+returns boolean+language sql+immutable+set search_path = ''+as $$+ select count(*) = count(distinct v) from unnest(p_values) as t(v);+$$;++create table if not exists public.chat_user_prefs (+ user_id uuid primary key references auth.users(id) on delete cascade,+ -- The chat menu beside the conversation (CHAT-01 9a–9f); open by default.+ menu_open boolean not null default true,+ -- Where a page Chat writes opens (CHAT-25 §12): ask each time, keep working+ -- in chat, the editor inside Chat, or the Content Editor.+ page_open text not null default 'ask' check (page_open in ('ask', 'chat', 'here', 'editor')),+ -- What Chat focuses on (CHAT-24 §2), in the order picked: the first one+ -- leads Home. Null: not asked yet (the picker shows once); empty: skipped,+ -- or none picked. Each area once.+ focus text[] check (+ focus <@ array['lead', 'comp', 'growth', 'seo', 'content', 'brand', 'pd', 'bd']::text[]+ and cardinality(focus) <= 8+ and public.chat_text_array_distinct(focus)+ ),+ -- Null: the workspace's default (Auto). Only its length is checked here:+ -- the server checks it against the model catalog and the plan before a+ -- run uses it (CHAT-16; the price sync and the engine, C1 and C3).+ model text check (char_length(model) between 1 and 200),+ -- Null: the workspace's default (Normal). CHAT-16 §E: Normal, High, Max.+ effort text check (effort in ('normal', 'high', 'max')),+ updated_at timestamptz not null default now()+);++drop trigger if exists trg_chat_user_prefs_updated_at on public.chat_user_prefs;+create trigger trg_chat_user_prefs_updated_at+ before update on public.chat_user_prefs+ for each row execute function public.handle_updated_at();++comment on table public.chat_user_prefs is+ 'Chat (00400): a person''s Chat settings, on the server so they follow them to every device (DECISIONS N3): chat menu, where pages open, focus areas, model and effort. Theirs to read and write.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_conversations enable row level security;+alter table public.chat_messages enable row level security;+alter table public.chat_runs enable row level security;+alter table public.chat_run_steps enable row level security;+alter table public.chat_user_prefs enable row level security;++revoke all on table public.chat_conversations from anon, authenticated;+revoke all on table public.chat_messages from anon, authenticated;+revoke all on table public.chat_runs from anon, authenticated;+revoke all on table public.chat_run_steps from anon, authenticated;+revoke all on table public.chat_user_prefs from anon, authenticated;++grant select on table public.chat_conversations to authenticated;+grant select on table public.chat_messages to authenticated;+grant select on table public.chat_runs to authenticated;+-- Every column but the tool and the debug record (CHAT-03 item 22).+grant select (+ id, run_id, position, kind, status, label, detail, scope_json, row_count,+ data_as_of, started_at, finished_at+) on table public.chat_run_steps to authenticated;+grant select, insert, update on table public.chat_user_prefs to authenticated;++grant all on table public.chat_conversations to service_role;+grant all on table public.chat_messages to service_role;+grant all on table public.chat_runs to service_role;+grant all on table public.chat_run_steps to service_role;+grant all on table public.chat_user_prefs to service_role;++-- The author reads their chat while they belong to its organization: a+-- member who left, or moved to another, doesn't.+drop policy if exists "chat_conversations: author select" on public.chat_conversations;+create policy "chat_conversations: author select"+ on public.chat_conversations+ for select+ using (+ user_id = auth.uid()+ and organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++-- Messages, runs and steps follow their chat's policies.+drop policy if exists "chat_messages: chat select" on public.chat_messages;+create policy "chat_messages: chat select"+ on public.chat_messages+ for select+ using (conversation_id in (select c.id from public.chat_conversations c));++drop policy if exists "chat_runs: chat select" on public.chat_runs;+create policy "chat_runs: chat select"+ on public.chat_runs+ for select+ using (conversation_id in (select c.id from public.chat_conversations c));++drop policy if exists "chat_run_steps: chat select" on public.chat_run_steps;+create policy "chat_run_steps: chat select"+ on public.chat_run_steps+ for select+ using (run_id in (select r.id from public.chat_runs r));++drop policy if exists "chat_user_prefs: own select" on public.chat_user_prefs;+create policy "chat_user_prefs: own select"+ on public.chat_user_prefs+ for select+ using (user_id = auth.uid());++drop policy if exists "chat_user_prefs: own insert" on public.chat_user_prefs;+create policy "chat_user_prefs: own insert"+ on public.chat_user_prefs+ for insert+ with check (user_id = auth.uid());++drop policy if exists "chat_user_prefs: own update" on public.chat_user_prefs;+create policy "chat_user_prefs: own update"+ on public.chat_user_prefs+ for update+ using (user_id = auth.uid())+ with check (user_id = auth.uid());++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 9460b94d0..1f18ca146 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -43166,3 +43166,373 @@ update public.profiles set work_areas_asked_at = now() where work_areas_asked_atnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00400_chat_core.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00400: Chat's core — chats, their messages, runs and steps, and each+-- person's Chat settings+-- ============================================================================+-- The new Chat (the Drive Chat specs, CHAT-00…25), behind CHAT_AGENTIC:+-- nothing reads these tables while the flag is off, and agent_conversations+-- and agent_messages (00009) keep serving today's /dashboard/agent as they do.+--+-- * chat_conversations: one chat. Private to its author (CHAT-20 §16c):+-- only they read it, admins included; the server writes it. brand_id is+-- the brand it is about, null for the workspace as a whole (a Help+-- question). A deleted brand leaves its chats with their author, then+-- about the workspace, as agent_conversations does (00009).+-- * chat_messages: the person's messages and Chat's answers. An answer+-- holds the answer only, never a tool's output (content_md; CHAT-03 item+-- 23), and when it was made: generated_at, the newest data it read+-- (data_as_of) and the time zone it was shown in (CHAT-06 items 38–42).+-- * chat_runs: the work behind one answer (one run, one answer: CHAT-00):+-- its status, the model and effort it ran with, and its times. Its chat+-- is kept equal to its answer's by the foreign key.+-- * chat_run_steps: a run's steps in order (CHAT-03). What the person sees+-- (kind, label, detail, scope in names, row count, status) and, for the+-- server and staff only, the tool that ran and its debug record: members+-- are granted every column but those two (the grants below).+-- * chat_step_kinds: the kinds a step can be. A table, not a check: a new+-- kind (CHAT-03 added `execute`; the Content Editor and images add more)+-- is a row a later migration inserts, with no constraint to rewrite and+-- no scan of the steps. Kinds aren't taken away: a step keeps its kind+-- (the key refuses deleting one in use, and finding out reads every step,+-- with no index on kind). The web's CHAT_STEP_KINDS (lib/chat/events.ts)+-- lists the same kinds; its test reads them from the migrations.+-- * chat_user_prefs: a person's Chat settings, on the server so they follow+-- them to every device (DECISIONS N3): the chat menu open or closed+-- (CHAT-01 9a–9f), where pages open (CHAT-25 §12), what Chat focuses on+-- (CHAT-24 §3), and their model and effort (CHAT-16; null = the+-- workspace's default, Auto and Normal). Theirs to write; the server+-- checks the model against its catalog before a run uses it.+--+-- Messages, runs and steps are readable where their chat is (they follow its+-- policies), so sharing a chat with the team is one more policy on+-- chat_conversations later. Approvals, the activity log with Undo, and AI+-- budget metering bring their own tables and columns in later migrations.++-- ─── Step kinds ─────────────────────────────────────────────────────────────++create table if not exists public.chat_step_kinds (+ kind text primary key check (kind ~ '^[a-z][a-z_]{1,39}$')+);++-- CHAT-03 "Labels by kind", and `execute` (CHAT-03 v2) for a step that waits+-- on the person's click.+insert into public.chat_step_kinds (kind) values+ ('thinking'), ('read'), ('open_page'), ('skill'), ('check'),+ ('write'), ('ask'), ('schedule'), ('image'), ('execute')+on conflict (kind) do nothing;++-- The server's list: members read a step's kind on the step itself.+alter table public.chat_step_kinds enable row level security;+revoke all on table public.chat_step_kinds from anon, authenticated;+grant all on table public.chat_step_kinds to service_role;++comment on table public.chat_step_kinds is+ 'Chat (00400): the kinds a run step can be (CHAT-03). A new kind is a row a later migration inserts; web lib/chat/events.ts CHAT_STEP_KINDS lists the same.';++-- ─── Chats ──────────────────────────────────────────────────────────────────++create table if not exists public.chat_conversations (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ user_id uuid not null references auth.users(id) on delete cascade,+ -- Null: about the workspace as a whole, not one brand.+ brand_id uuid references public.brands(id) on delete set null,+ -- Null until Chat names it from the first message (CHAT-01 item 8); the+ -- web shows "New chat" meanwhile.+ title text check (char_length(title) between 1 and 200),+ -- The full Chat page or the side panel on another page (CHAT-01).+ origin text not null default 'page' check (origin in ('page', 'panel')),+ -- The route it was started on, for "Back to {page}" (CHAT-01).+ origin_page text check (char_length(origin_page) between 1 and 500),+ pinned_at timestamptz,+ archived_at timestamptz,+ -- Recents' order: the last message, not a rename or a pin. Kept by the+ -- trigger on chat_messages below.+ last_message_at timestamptz not null default now(),+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create index if not exists chat_conversations_user_recent_idx+ on public.chat_conversations (user_id, last_message_at desc);+create index if not exists chat_conversations_organization_idx+ on public.chat_conversations (organization_id);+create index if not exists chat_conversations_brand_idx+ on public.chat_conversations (brand_id) where brand_id is not null;++drop trigger if exists trg_chat_conversations_updated_at on public.chat_conversations;+create trigger trg_chat_conversations_updated_at+ before update on public.chat_conversations+ for each row execute function public.handle_updated_at();++comment on table public.chat_conversations is+ 'Chat (00400): one chat, private to its author (CHAT-20 §16c): only they read it, admins included. Written by the server.';++-- ─── Messages ───────────────────────────────────────────────────────────────++create table if not exists public.chat_messages (+ id uuid primary key default gen_random_uuid(),+ conversation_id uuid not null references public.chat_conversations(id) on delete cascade,+ role text not null check (role in ('user', 'assistant')),+ -- The message, or the answer only: a tool's output never goes here. Up to+ -- 200,000 characters: the server cuts or refuses a longer one first.+ content_md text not null default '' check (char_length(content_md) <= 200000),+ -- An answer's "Generated …" (UTC), the newest data it read ("Data as of",+ -- null when it read none) and the IANA time zone both were shown in.+ generated_at timestamptz,+ data_as_of timestamptz,+ timezone text check (char_length(timezone) between 1 and 64),+ -- clock_timestamp(): a question and its answer written in one statement+ -- still come in order.+ created_at timestamptz not null default clock_timestamp(),+ -- For chat_runs' key: a run's chat is its answer's.+ unique (id, conversation_id)+);++create index if not exists chat_messages_conversation_created_idx+ on public.chat_messages (conversation_id, created_at);++comment on table public.chat_messages is+ 'Chat (00400): a chat''s messages and answers. An answer holds the answer only, with when it was made and the newest data it read (CHAT-06 38–42). Written by the server.';++-- A new message moves its chat up Recents (last_message_at). Security+-- definer, so the update reaches the chat whoever writes the message: today+-- only the server does (service role), and members may not update chats.+-- greatest(): a message written late never moves its chat back. Not covered+-- by a test (the repository has no database tests); nothing else sets+-- last_message_at.+create or replace function public.chat_touch_last_message()+returns trigger+language plpgsql+security definer+set search_path = ''+as $$+begin+ update public.chat_conversations+ set last_message_at = greatest(last_message_at, new.created_at)+ where id = new.conversation_id;+ return new;+end;+$$;++drop trigger if exists trg_chat_messages_touch_conversation on public.chat_messages;+create trigger trg_chat_messages_touch_conversation+ after insert on public.chat_messages+ for each row execute function public.chat_touch_last_message();++-- ─── Runs ───────────────────────────────────────────────────────────────────++create table if not exists public.chat_runs (+ id uuid primary key default gen_random_uuid(),+ -- The answer this run writes, and that answer's chat.+ message_id uuid not null unique,+ conversation_id uuid not null,+ -- queued: waiting for a free run (CHAT-20 §14); waiting: on the person (a+ -- question, an approval, a click, a plan's Start); paused: paused by the+ -- person; paused_cap: the month's AI limit is used (CHAT-04).+ status text not null default 'queued' check (+ status in (+ 'queued', 'running', 'waiting', 'paused', 'paused_cap', 'done', 'error', 'stopped'+ )+ ),+ -- 'auto' or the model the person picked (CHAT-16).+ model text not null default 'auto' check (char_length(model) between 1 and 200),+ effort text not null default 'normal' check (effort in ('normal', 'high', 'max')),+ -- A standard result code (CHAT-20 §11a: 'failed', 'timeout'…) when it ended in error.+ error text check (error ~ '^[a-z_]{1,40}$'),+ created_at timestamptz not null default now(),+ started_at timestamptz,+ finished_at timestamptz,+ foreign key (message_id, conversation_id)+ references public.chat_messages (id, conversation_id) on delete cascade+);++create index if not exists chat_runs_conversation_created_idx+ on public.chat_runs (conversation_id, created_at desc);+-- The runs under way, oldest first: the queue, the runs tray, the sweeps.+create index if not exists chat_runs_open_idx+ on public.chat_runs (created_at)+ where status in ('queued', 'running', 'waiting', 'paused', 'paused_cap');++comment on table public.chat_runs is+ 'Chat (00400): the work behind one answer (CHAT-00: one run, one answer), with its status, model, effort and times. Written by the server.';++-- ─── Steps ──────────────────────────────────────────────────────────────────++create table if not exists public.chat_run_steps (+ id uuid primary key default gen_random_uuid(),+ run_id uuid not null references public.chat_runs(id) on delete cascade,+ -- Its place in the run, from 1: how a question or an approval names it to+ -- the browser, which gets no ids.+ position smallint not null check (position >= 1),+ kind text not null references public.chat_step_kinds(kind) on update cascade,+ -- pending: in a plan, not started; waiting: on the person.+ status text not null default 'running' check (+ status in ('pending', 'running', 'waiting', 'done', 'error', 'skipped')+ ),+ -- The label registry's words (CHAT-03): "Read Citations".+ label text not null check (char_length(label) between 1 and 200),+ -- "Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows", or an+ -- error's plain reason.+ detail text check (char_length(detail) between 1 and 500),+ -- What a read covered, in names only (subject, date range, platforms,+ -- brand): never ids. The tool's own arguments are in debug_json.+ scope_json jsonb check (+ scope_json is null+ or (jsonb_typeof(scope_json) = 'object' and octet_length(scope_json::text) <= 8000)+ ),+ row_count integer check (row_count >= 0),+ -- A read's newest data (CHAT-20 §15a); the answer's "Data as of" is the newest of them.+ data_as_of timestamptz,+ started_at timestamptz,+ finished_at timestamptz,+ -- Server and staff only (members aren't granted them): the registry name+ -- of the tool that ran, and what the staff Debug view shows (CHAT-03 items+ -- 25–26: input, output, model, tokens, latency). Up to 1 MB as text: the+ -- server shortens a large tool output before it keeps it here.+ tool text check (char_length(tool) between 1 and 100),+ debug_json jsonb check (+ debug_json is null+ or (jsonb_typeof(debug_json) = 'object' and octet_length(debug_json::text) <= 1000000)+ ),+ unique (run_id, position)+);++comment on table public.chat_run_steps is+ 'Chat (00400): a run''s steps in order (CHAT-03). Members read every column but tool and debug_json, which stay with the server and staff. Written by the server.';+comment on column public.chat_run_steps.scope_json is+ 'What a read covered, in names only (subject, dateRange, platforms, brand): never ids. Members read it.';+comment on column public.chat_run_steps.debug_json is+ 'The staff Debug view (CHAT-03 25–26): the tool''s input and output, model, tokens, latency. Never granted to members.';++-- ─── A person's Chat settings ───────────────────────────────────────────────++-- Whether a list has no value twice: a check can't hold a subquery.+create or replace function public.chat_text_array_distinct(p_values text[])+returns boolean+language sql+immutable+set search_path = ''+as $$+ select count(*) = count(distinct v) from unnest(p_values) as t(v);+$$;++create table if not exists public.chat_user_prefs (+ user_id uuid primary key references auth.users(id) on delete cascade,+ -- The chat menu beside the conversation (CHAT-01 9a–9f); open by default.+ menu_open boolean not null default true,+ -- Where a page Chat writes opens (CHAT-25 §12): ask each time, keep working+ -- in chat, the editor inside Chat, or the Content Editor.+ page_open text not null default 'ask' check (page_open in ('ask', 'chat', 'here', 'editor')),+ -- What Chat focuses on (CHAT-24 §2), in the order picked: the first one+ -- leads Home. Null: not asked yet (the picker shows once); empty: skipped,+ -- or none picked. Each area once.+ focus text[] check (+ focus <@ array['lead', 'comp', 'growth', 'seo', 'content', 'brand', 'pd', 'bd']::text[]+ and cardinality(focus) <= 8+ and public.chat_text_array_distinct(focus)+ ),+ -- Null: the workspace's default (Auto). Only its length is checked here:+ -- the server checks it against the model catalog and the plan before a+ -- run uses it (CHAT-16; the price sync and the engine, C1 and C3).+ model text check (char_length(model) between 1 and 200),+ -- Null: the workspace's default (Normal). CHAT-16 §E: Normal, High, Max.+ effort text check (effort in ('normal', 'high', 'max')),+ updated_at timestamptz not null default now()+);++drop trigger if exists trg_chat_user_prefs_updated_at on public.chat_user_prefs;+create trigger trg_chat_user_prefs_updated_at+ before update on public.chat_user_prefs+ for each row execute function public.handle_updated_at();++comment on table public.chat_user_prefs is+ 'Chat (00400): a person''s Chat settings, on the server so they follow them to every device (DECISIONS N3): chat menu, where pages open, focus areas, model and effort. Theirs to read and write.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_conversations enable row level security;+alter table public.chat_messages enable row level security;+alter table public.chat_runs enable row level security;+alter table public.chat_run_steps enable row level security;+alter table public.chat_user_prefs enable row level security;++revoke all on table public.chat_conversations from anon, authenticated;+revoke all on table public.chat_messages from anon, authenticated;+revoke all on table public.chat_runs from anon, authenticated;+revoke all on table public.chat_run_steps from anon, authenticated;+revoke all on table public.chat_user_prefs from anon, authenticated;++grant select on table public.chat_conversations to authenticated;+grant select on table public.chat_messages to authenticated;+grant select on table public.chat_runs to authenticated;+-- Every column but the tool and the debug record (CHAT-03 item 22).+grant select (+ id, run_id, position, kind, status, label, detail, scope_json, row_count,+ data_as_of, started_at, finished_at+) on table public.chat_run_steps to authenticated;+grant select, insert, update on table public.chat_user_prefs to authenticated;++grant all on table public.chat_conversations to service_role;+grant all on table public.chat_messages to service_role;+grant all on table public.chat_runs to service_role;+grant all on table public.chat_run_steps to service_role;+grant all on table public.chat_user_prefs to service_role;++-- The author reads their chat while they belong to its organization: a+-- member who left, or moved to another, doesn't.+drop policy if exists "chat_conversations: author select" on public.chat_conversations;+create policy "chat_conversations: author select"+ on public.chat_conversations+ for select+ using (+ user_id = auth.uid()+ and organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++-- Messages, runs and steps follow their chat's policies.+drop policy if exists "chat_messages: chat select" on public.chat_messages;+create policy "chat_messages: chat select"+ on public.chat_messages+ for select+ using (conversation_id in (select c.id from public.chat_conversations c));++drop policy if exists "chat_runs: chat select" on public.chat_runs;+create policy "chat_runs: chat select"+ on public.chat_runs+ for select+ using (conversation_id in (select c.id from public.chat_conversations c));++drop policy if exists "chat_run_steps: chat select" on public.chat_run_steps;+create policy "chat_run_steps: chat select"+ on public.chat_run_steps+ for select+ using (run_id in (select r.id from public.chat_runs r));++drop policy if exists "chat_user_prefs: own select" on public.chat_user_prefs;+create policy "chat_user_prefs: own select"+ on public.chat_user_prefs+ for select+ using (user_id = auth.uid());++drop policy if exists "chat_user_prefs: own insert" on public.chat_user_prefs;+create policy "chat_user_prefs: own insert"+ on public.chat_user_prefs+ for insert+ with check (user_id = auth.uid());++drop policy if exists "chat_user_prefs: own update" on public.chat_user_prefs;+create policy "chat_user_prefs: own update"+ on public.chat_user_prefs+ for update+ using (user_id = auth.uid())+ with check (user_id = auth.uid());++notify pgrst, 'reload schema';+diff --git a/web/.env.example b/web/.env.exampleindex ea420ca61..f5d4ecd8a 100644--- a/web/.env.example+++ b/web/.env.example@@ -69,6 +69,19 @@ NEXT_PUBLIC_ACTION_TASKS_AI=# -----------------------------------------------------------------------------NEXT_PUBLIC_CONTENT_QUALITY_PHASE=+# -----------------------------------------------------------------------------+# Chat: the new Chat (Drive Chat specs, CHAT-00…25), off unless "true".+# Off, today's /dashboard/agent stays as it is. Read by server code at+# request time (not NEXT_PUBLIC_, so never in the browser's code); a change+# applies once the app starts again: a restart when self-hosted, a new+# deployment on Vercel. Set the server's CHAT_AGENTIC and CHAT_AGENTIC_ORGS+# to the same values.+# CHAT_AGENTIC_ORGS: with Chat on, only these organizations (ids,+# comma-separated); empty = every organization.+# -----------------------------------------------------------------------------+CHAT_AGENTIC=+CHAT_AGENTIC_ORGS=+# -----------------------------------------------------------------------------# AEO Server (backend API)# -----------------------------------------------------------------------------diff --git a/web/src/lib/chat/events.test.ts b/web/src/lib/chat/events.test.tsnew file mode 100644index 000000000..66f992792--- /dev/null+++ b/web/src/lib/chat/events.test.ts@@ -0,0 +1,323 @@+// @vitest-environment node+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, expectTypeOf, it } from 'vitest';+import {+ CHAT_EVENT_TYPES,+ CHAT_STEP_KINDS,+ chatEvent,+ clientEventProblems,+ isChatEventType,+ isChatHref,+ maskIds,+ type ChatDeliverable,+ type ChatEvent,+ type ChatEventPayloads,+ type ChatEventType,+ type ChatForbiddenKey,+ type ChatHref,+ type ChatStep,+} from './events';++/**+ * Chat's streamed events: one of every type goes to the browser; none of+ * them carries a tool's name, a debug record, an id field, money or a link+ * out of the app, and a uuid in their text shows as "…".+ */++const UUID = '7d3f2c1a-9b8e-4c6d-a5f4-3e2d1c0b9a87';+const UUID_ANYWHERE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;+const EDITOR: ChatHref = `/dashboard/content/editor/${UUID}`;++const STEP: ChatStep = {+ n: 2,+ kind: 'read',+ status: 'done',+ label: 'Read Citations',+ detail: 'Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows',+ scope: {+ subject: 'Pricing prompts',+ dateRange: 'Last 30 days',+ platforms: ['ChatGPT', 'Perplexity'],+ },+ rowCount: 42,+ dataAsOf: '2026-10-29T06:00:00.000Z',+};++const SUMMARY = {+ workingMs: 72_000,+ stepCount: 7,+ sources: [+ { label: 'Citations', count: 42 },+ { label: 'Prompts', count: 12 },+ ],+};++const DELIVERABLE: ChatDeliverable = {+ title: 'Pricing FAQ',+ type: 'document',+ formats: ['md', 'docx'],+ status: 'draft',+ href: EDITOR,+};++/** One of every type, as the stream would send it. */+const SAMPLES: { [K in ChatEventType]: () => Extract<ChatEvent, { type: K }> } = {+ 'step.started': () => chatEvent('step.started', 1, { step: { ...STEP, status: 'running' } }),+ 'step.updated': () => chatEvent('step.updated', 2, { step: { ...STEP, status: 'running' } }),+ 'step.finished': () => chatEvent('step.finished', 3, { step: STEP }),+ 'text.delta': () => chatEvent('text.delta', 4, { text: 'Citations on Perplexity fell **18%**' }),+ 'ask.created': () =>+ chatEvent('ask.created', 5, {+ n: 3,+ question: 'Which pages should I check?',+ options: [+ { label: '/pricing', detail: 'Lost 6 citations', recommended: true },+ { label: 'Generate an image', costMultiplier: 2 },+ ],+ allowOther: true,+ multi: false,+ }),+ 'deliverable.created': () => chatEvent('deliverable.created', 6, DELIVERABLE),+ 'confirm.required': () =>+ chatEvent('confirm.required', 7, {+ n: 4,+ action: 'Add 12 prompts to tracking',+ target: 'Pricing · Northwind CRM',+ }),+ next_moves: () =>+ chatEvent('next_moves', 8, {+ moves: [{ label: 'Turn this into actions', prompt: 'Turn these findings into actions' }],+ }),+ 'usage.updated': () => chatEvent('usage.updated', 9, { percentUsed: 44, runPercent: 0.3 }),+ 'run.finished': () =>+ chatEvent('run.finished', 10, {+ ...SUMMARY,+ generatedAt: '2026-10-29T09:14:00.000Z',+ dataAsOf: '2026-10-29T06:00:00.000Z',+ }),+ 'run.error': () => chatEvent('run.error', 11, { ...SUMMARY, code: 'timeout' }),+ 'run.paused_cap': () => chatEvent('run.paused_cap', 12, SUMMARY),+ 'deliverable.updated': () => chatEvent('deliverable.updated', 13, { ...DELIVERABLE, version: 2 }),+ 'suggestion.created': () => chatEvent('suggestion.created', 14, { count: 3 }),+ 'suggestion.resolved': () => chatEvent('suggestion.resolved', 15, { count: 1 }),+ 'page.opened': () => chatEvent('page.opened', 16, { where: 'here', href: EDITOR }),+};++/** Every key in a type, at any depth. */+type KeysDeep<T> = T extends readonly (infer U)[]+ ? KeysDeep<U>+ : T extends object+ ? { [K in keyof T]-?: K | KeysDeep<T[K]> }[keyof T]+ : never;++/** Builds a step event with one key the types don't allow, as loose code could. */+const stepWith = (key: string, value: unknown = 'x') =>+ chatEvent('step.finished', 1, { step: { ...STEP, [key]: value } as ChatStep });++/** The keys a payload may never have, each as loose code could spell it. */+const FORBIDDEN = {+ tool: [+ 'tool',+ 'tools',+ 'toolName',+ 'tool_name',+ 'toolCall',+ 'toolInput',+ 'toolOutput',+ 'toolResult',+ ],+ raw: ['input', 'output', 'args', 'arguments', 'params'],+ debug: ['debug', 'debug_json', 'debugJson', 'tokens', 'tokensIn', 'promptTokens', 'latencyMs'],+ money: ['usd', 'costUsd', 'cost_usd', 'dollars', 'price', 'priceCents', 'amount', 'spend'],+ cost: ['cost', 'runCost', 'run_cost', 'cents', 'run_cents'],+ id: ['id', 'ids', 'brandId', 'brand_id', 'promptIds', 'citation_ids'],+};++describe('chat events', () => {+ it('lists every type once, and builds each one for the browser', () => {+ expect([...CHAT_EVENT_TYPES].sort()).toEqual(Object.keys(SAMPLES).sort());+ for (const type of CHAT_EVENT_TYPES) {+ const event = SAMPLES[type]();+ expect(event.type).toBe(type);+ expect(clientEventProblems(event)).toEqual([]);+ }+ });++ it('sends no tool, debug, id or money field, and no uuid outside a link', () => {+ const events = CHAT_EVENT_TYPES.map((type) => SAMPLES[type]());+ const wire = JSON.stringify(events, (key, value) => (key === 'href' ? undefined : value));+ expect(wire).not.toMatch(/"tools?([A-Z_]\w*)?":|"(input|output|args|arguments|params)":/);+ expect(wire).not.toMatch(/"[^"]*(debug|token|latency|usd|dollar|price|amount|spend)[^"]*":/i);+ expect(wire).not.toMatch(/"(\w*_)?(cost|cents?)":|"\w*[a-z0-9](Cost|Cents?)":/);+ expect(wire).not.toMatch(/"(\w*_ids?|\w*[a-z]Ids?|ids?)":/);+ expect(wire).not.toMatch(UUID_ANYWHERE);+ });++ it('has no forbidden key in any payload type', () => {+ type PayloadKey = KeysDeep<ChatEventPayloads[ChatEventType]>;+ expectTypeOf<Extract<PayloadKey, ChatForbiddenKey>>().toBeNever();+ });++ it('names every forbidden key in the type too', () => {+ // Each spelling the run-time check refuses is a ChatForbiddenKey…+ expectTypeOf<+ 'toolInput' | 'toolOutput' | 'toolResult' | 'params'+ >().toExtend<ChatForbiddenKey>();+ expectTypeOf<'tokensIn' | 'latencyMs' | 'debugJson'>().toExtend<ChatForbiddenKey>();+ expectTypeOf<+ 'costUsd' | 'priceCents' | 'runCost' | 'run_cost' | 'amount'+ >().toExtend<ChatForbiddenKey>();+ expectTypeOf<'brandId' | 'brand_id' | 'promptIds'>().toExtend<ChatForbiddenKey>();+ // …and the keys a payload has, or may, aren't.+ expectTypeOf<+ Extract<+ 'tooltip' | 'costMultiplier' | 'runPercent' | 'percentUsed' | 'href',+ ChatForbiddenKey+ >+ >().toBeNever();+ });++ it("refuses a tool's name, even when the types are got around", () => {+ expect(() =>+ chatEvent('step.started', 1, {+ step: {+ n: 1,+ kind: 'read',+ status: 'running',+ label: 'Read Citations',+ // @ts-expect-error a step has no tool: the browser never gets one+ tool: 'list_citations',+ },+ }),+ ).toThrow(/event\.data\.step\.tool: a tool or its input or output/);+ for (const key of [...FORBIDDEN.tool, ...FORBIDDEN.raw]) {+ expect(() => stepWith(key), key).toThrow(`step.${key}: a tool or its input or output`);+ }+ });++ it('refuses a debug record, tokens or latency', () => {+ for (const key of FORBIDDEN.debug) {+ expect(() => stepWith(key, { brand: 'Northwind' }), key).toThrow(+ `step.${key}: a debug record`,+ );+ }+ });++ it('refuses money: usage is a percent of the monthly limit', () => {+ for (const key of [...FORBIDDEN.money, ...FORBIDDEN.cost]) {+ const usage = { percentUsed: 44, [key]: 0.04 } as { percentUsed: number };+ expect(() => chatEvent('usage.updated', 1, usage), key).toThrow(`data.${key}: money`);+ }+ });++ it('refuses an id field, by any name', () => {+ for (const key of FORBIDDEN.id) {+ const step = { ...STEP, scope: { ...STEP.scope, [key]: 'x' } } as ChatStep;+ expect(() => chatEvent('step.finished', 1, { step }), key).toThrow(`scope.${key}: an id`);+ }+ });++ it('lets through the keys that only look alike', () => {+ for (const key of ['tooltip', 'costMultiplier', 'runPercent', 'percentUsed', 'stepCount']) {+ expect(() => stepWith(key), key).not.toThrow();+ }+ });++ it('shows a uuid in the text as "…" instead of stopping the run', () => {+ const step = chatEvent('step.finished', 1, {+ step: {+ ...STEP,+ label: `Opened /products/${UUID}`,+ scope: { platforms: ['ChatGPT', UUID.toUpperCase()] },+ },+ }).data.step;+ expect(step.label).toBe('Opened /products/…');+ expect(step.scope?.platforms).toEqual(['ChatGPT', '…']);++ const confirm = chatEvent('confirm.required', 1, {+ n: 1,+ action: 'Archive 3 prompts',+ target: `See https://example.com/a/${UUID}?b=${UUID}`,+ }).data;+ expect(confirm.target).toBe('See https://example.com/a/…?b=…');+ expect(maskIds('no ids here')).toBe('no ids here');+ });++ it("doesn't change what it's given", () => {+ const step = { ...STEP, label: `Read prompt ${UUID}` };+ chatEvent('step.finished', 1, { step });+ expect(step.label).toBe(`Read prompt ${UUID}`);+ });++ it("leaves the answer's text to the engine, but not its keys", () => {+ const delta = chatEvent('text.delta', 1, { text: `You asked about ${UUID}` });+ expect(delta.data.text).toBe(`You asked about ${UUID}`);+ const text = { text: 'ok', brand_id: UUID } as { text: string };+ expect(() => chatEvent('text.delta', 1, text)).toThrow(/event\.data\.brand_id: an id/);+ });++ it("keeps an app link whole, ids and all, so a card's Open works", () => {+ expect(SAMPLES['deliverable.created']().data.href).toBe(EDITOR);+ expect(SAMPLES['deliverable.updated']().data.href).toBe(EDITOR);+ expect(SAMPLES['page.opened']().data.href).toBe(EDITOR);+ const plain = chatEvent('deliverable.created', 1, { ...DELIVERABLE, href: undefined });+ expect(clientEventProblems(plain)).toEqual([]);+ });++ it('refuses a link out of the app, a query or a step out of /dashboard/', () => {+ const bad = [+ 'https://example.com/dashboard/x',+ '//example.com/dashboard/x',+ 'javascript:alert(1)',+ '/dashboard/content?draft=1',+ '/dashboard/content#top',+ '/dashboard//example.com',+ '/dashboard/../admin',+ '/dashboard/%2e%2e/admin',+ '/dashboard/a\\b',+ ' /dashboard/x',+ '/settings',+ '/dashboard',+ ];+ for (const href of bad) {+ expect(isChatHref(href), href).toBe(false);+ const page = { where: 'editor', href } as ChatEventPayloads['page.opened'];+ expect(() => chatEvent('page.opened', 1, page), href).toThrow(+ 'event.data.href: not a path in the app',+ );+ }+ expect(isChatHref('/dashboard/content/library')).toBe(true);+ expect(isChatHref(`/dashboard/chat/files/${UUID}`)).toBe(true);+ // @ts-expect-error an href is a path under /dashboard/+ const outside: ChatHref = 'https://example.com';+ expect(isChatHref(outside)).toBe(false);+ });++ it("knows its own types, so the browser can skip a newer server's", () => {+ expect(isChatEventType('step.started')).toBe(true);+ expect(isChatEventType('page.opened')).toBe(true);+ expect(isChatEventType('click.required')).toBe(false);+ expect(isChatEventType('toString')).toBe(false);+ expect(isChatEventType(undefined)).toBe(false);+ });+});++describe('step kinds', () => {+ it('match the kinds the migrations put in chat_step_kinds', () => {+ const dir = fileURLToPath(new URL('../../../../supabase/migrations', import.meta.url));+ const seeded = new Set<string>();+ for (const file of readdirSync(dir)+ .filter((f) => f.endsWith('.sql'))+ .sort()) {+ const sql = readFileSync(`${dir}/${file}`, 'utf8').replace(/--[^\n]*/g, '');+ const inserts = sql.matchAll(+ /insert\s+into\s+(?:public\.)?chat_step_kinds\s*\(\s*kind\s*\)\s*values([^;]*);/gi,+ );+ for (const [, values] of inserts) {+ for (const [, kind] of values.matchAll(/\(\s*'([a-z_]+)'\s*\)/g)) seeded.add(kind);+ }+ }+ expect([...seeded].sort()).toEqual([...CHAT_STEP_KINDS].sort());+ });+});diff --git a/web/src/lib/chat/events.ts b/web/src/lib/chat/events.tsnew file mode 100644index 000000000..cb4e5a47f--- /dev/null+++ b/web/src/lib/chat/events.ts@@ -0,0 +1,382 @@+/**+ * The events a Chat run streams to the browser (CHAT-00 "Streaming events",+ * CHAT-03, CHAT-25 §12). One run writes one answer; the browser draws its+ * steps, text, cards and end from these events only.+ *+ * What a customer's browser never gets (CHAT-00 principle 3, CHAT-03 items+ * 22–23, DECISIONS R), held twice: by the payload types below, which have no+ * field for any of it (ChatForbiddenKey), and by chatEvent(), which every+ * event the stream sends goes through. It refuses+ * - a tool's name, its input, output or result, a debug record, tokens or+ * latency;+ * - an id field (`id`, `…Id`, `…_id`);+ * - a money field: usage is a percent of the monthly AI limit;+ * - a link that isn't a plain path in the app (`href`, ChatHref);+ * and shows a uuid in any other text as "…" (an id is never shown, CHAT-03+ * item 5), so a page path or a link the person pasted never stops the run.+ * A step is named by its place in the run (`n`, from 1), which is also how a+ * question or an approval points at its step; a reconnect resumes after the+ * last event's `seq`.+ *+ * Adding an event is one entry in ChatEventPayloads and one in EVENT_TYPES+ * (the compiler asks for both). The browser skips a type it doesn't know+ * (isChatEventType), so a newer server never breaks an open page.+ */++// ─── Steps ──────────────────────────────────────────────────────────────────++/**+ * What a step does (CHAT-03 "Labels by kind"; `execute`, CHAT-03 v2, waits on+ * the person's click). The database lists the same kinds in chat_step_kinds+ * (00400); a new kind goes in both.+ */+export const CHAT_STEP_KINDS = [+ 'thinking',+ 'read',+ 'open_page',+ 'skill',+ 'check',+ 'write',+ 'ask',+ 'schedule',+ 'image',+ 'execute',+] as const;+export type ChatStepKind = (typeof CHAT_STEP_KINDS)[number];++/** pending: in a plan, not started; waiting: on the person (chat_run_steps.status). */+export const CHAT_STEP_STATUSES = [+ 'pending',+ 'running',+ 'waiting',+ 'done',+ 'error',+ 'skipped',+] as const;+export type ChatStepStatus = (typeof CHAT_STEP_STATUSES)[number];++/** What a read covered, in the app's words: never ids (CHAT-03 item 5). */+export interface ChatStepScope {+ /** "Pricing prompts" */+ subject?: string;+ /** "Last 30 days", "1–15 Oct", "All time" */+ dateRange?: string;+ /** Display names: "ChatGPT", "Perplexity". */+ platforms?: string[];+ /** Only when the read isn't for the chat's brand. */+ brand?: string;+}++/** A step as the browser sees it: the label registry's words, never the tool. */+export interface ChatStep {+ /** Its place in the run, from 1. */+ n: number;+ kind: ChatStepKind;+ status: ChatStepStatus;+ /** "Read Citations" */+ label: string;+ /** "Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows", or an error's plain reason. */+ detail?: string;+ scope?: ChatStepScope;+ rowCount?: number;+ /** The newest data the read used, ISO (CHAT-20 §15a). */+ dataAsOf?: string;+}++// ─── Cards ──────────────────────────────────────────────────────────────────++/**+ * Where a card's Open goes: a path in the app, under /dashboard/, with no+ * host, query or fragment ("/dashboard/content/editor/{draft}"). The one+ * field that may name a record, since the app's own routes do; checked by+ * chatEvent().+ */+export type ChatHref = `/dashboard/${string}`;++/** One choice on a question card (CHAT-00 `ask`, CHAT-07). */+export interface ChatAskOption {+ label: string;+ detail?: string;+ recommended?: boolean;+ /** A model's multiplier against Auto (1, 2, 4): never a price. */+ costMultiplier?: number;+}++/** A question card; the run waits on it (CHAT-07). */+export interface ChatAsk {+ /** The step that waits for the answer. */+ n: number;+ question: string;+ options: ChatAskOption[];+ allowOther: boolean;+ multi: boolean;+}++/**+ * A change waiting for the person's OK (CHAT-00 `confirm.required`). The+ * spec's "tool" is the action in words here: the browser never gets a+ * tool's name.+ */+export interface ChatConfirm {+ /** The step that waits for the OK. */+ n: number;+ /** "Add 12 prompts to tracking" */+ action: string;+ /** "Pricing · Northwind CRM" */+ target: string;+}++/** What Chat made (CHAT-00 `file`, CHAT-06). */+export interface ChatDeliverable {+ title: string;+ type: 'document' | 'table' | 'code' | 'image' | 'report';+ /** "md", "docx", "pdf", "csv", "xlsx"… */+ formats: string[];+ status: 'draft' | 'attached' | 'done';+ /** Its card's Open (CHAT-06): the file, or the page's draft in the editor. */+ href?: ChatHref;+}++/** A next move: a chip that fills the composer (CHAT-07). In rank order. */+export interface ChatNextMove {+ label: string;+ prompt: string;+}++/** The workspace's monthly AI usage, as a percent of its limit (CHAT-04, DECISIONS R). */+export interface ChatUsage {+ percentUsed: number;+ /** This run's share of the monthly limit. */+ runPercent?: number;+}++/** A run's end, for the collapsed step header (CHAT-03 items 9–12). */+export interface ChatRunSummary {+ workingMs: number;+ stepCount: number;+ /** The "Data used" chips: "Citations · 42". */+ sources: { label: string; count: number }[];+}++/** Where a page Chat writes was opened (CHAT-25 §3). */+export type ChatPageWhere = 'chat' | 'here' | 'editor';++// ─── Events ─────────────────────────────────────────────────────────────────++/** Each event's payload, by type. */+export interface ChatEventPayloads {+ 'step.started': { step: ChatStep };+ 'step.updated': { step: ChatStep };+ 'step.finished': { step: ChatStep };+ /** A chunk of the answer's markdown. */+ 'text.delta': { text: string };+ 'ask.created': ChatAsk;+ 'deliverable.created': ChatDeliverable;+ 'confirm.required': ChatConfirm;+ next_moves: { moves: ChatNextMove[] };+ 'usage.updated': ChatUsage;+ /** generatedAt and dataAsOf: the answer's "Generated …" and "Data as of …" (CHAT-06 38–39). */+ 'run.finished': ChatRunSummary & { generatedAt: string; dataAsOf: string | null };+ /** code: a standard result code (CHAT-20 §11a); the browser shows its words. */+ 'run.error': ChatRunSummary & { code: 'failed' | 'timeout' };+ 'run.paused_cap': ChatRunSummary;+ // Editor in Chat (CHAT-25 §12, Phase 4): payloads grow with it.+ /** A new version card of a page Chat writes. */+ 'deliverable.updated': ChatDeliverable & { version: number };+ /** Suggestions Chat made on the open page, for the editor to show. */+ 'suggestion.created': { count: number };+ 'suggestion.resolved': { count: number };+ /** href: the page's draft, in the editor beside the chat or the Content Editor. */+ 'page.opened': { where: ChatPageWhere; href?: ChatHref };+}++export type ChatEventType = keyof ChatEventPayloads;++/** One event on the wire: `seq` counts up within the run, from 1. */+export type ChatEvent = {+ [K in ChatEventType]: { type: K; seq: number; data: ChatEventPayloads[K] };+}[ChatEventType];++/** Every type, once: a type missing here, or one that doesn't exist, doesn't compile. */+const EVENT_TYPES: Record<ChatEventType, true> = {+ 'step.started': true,+ 'step.updated': true,+ 'step.finished': true,+ 'text.delta': true,+ 'ask.created': true,+ 'deliverable.created': true,+ 'confirm.required': true,+ next_moves: true,+ 'usage.updated': true,+ 'run.finished': true,+ 'run.error': true,+ 'run.paused_cap': true,+ 'deliverable.updated': true,+ 'suggestion.created': true,+ 'suggestion.resolved': true,+ 'page.opened': true,+};++export const CHAT_EVENT_TYPES = Object.keys(EVENT_TYPES) as ChatEventType[];++/** Whether the browser knows this type; it skips one it doesn't. */+export function isChatEventType(type: unknown): type is ChatEventType {+ return typeof type === 'string' && Object.hasOwn(EVENT_TYPES, type);+}++// ─── What never goes to the browser ─────────────────────────────────────────++type Upper =+ | 'A'+ | 'B'+ | 'C'+ | 'D'+ | 'E'+ | 'F'+ | 'G'+ | 'H'+ | 'I'+ | 'J'+ | 'K'+ | 'L'+ | 'M'+ | 'N'+ | 'O'+ | 'P'+ | 'Q'+ | 'R'+ | 'S'+ | 'T'+ | 'U'+ | 'V'+ | 'W'+ | 'X'+ | 'Y'+ | 'Z';+type LowerOrDigit = Lowercase<Upper> | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';+type AnyCase<W extends string> = W | Capitalize<W> | Uppercase<W>;++/**+ * The keys no payload may have, as the types see them; chatEvent() refuses+ * the same at run time (FORBIDDEN_KEYS).+ */+export type ChatForbiddenKey =+ // A tool, its call, input, output or result: tool, tools, toolName, tool_name…+ | 'tool'+ | 'tools'+ | `tool${Upper | '_'}${string}`+ | `tools${Upper | '_'}${string}`+ | 'input'+ | 'output'+ | 'args'+ | 'arguments'+ | 'params'+ // A debug record and what it measures.+ | `${string}${AnyCase<'debug' | 'token' | 'latency'>}${string}`+ // Money: dollars, prices, amounts, spend, cost, cents (a cost multiplier is fine).+ | `${string}${AnyCase<'usd' | 'dollar' | 'price' | 'amount' | 'spend'>}${string}`+ | 'cost'+ | 'cent'+ | 'cents'+ | `${string}_${'cost' | 'cent' | 'cents'}`+ | `${string}${LowerOrDigit}${'Cost' | 'Cent' | 'Cents'}`+ // An id.+ | 'id'+ | 'ids'+ | `${string}_${'id' | 'ids'}`+ | `${string}${LowerOrDigit}${'Id' | 'Ids'}`;++/** ChatForbiddenKey at run time: each with what it is. */+const FORBIDDEN_KEYS: [RegExp, string][] = [+ [/^tools?($|[A-Z_])|^(input|output|args|arguments|params)$/, 'a tool or its input or output'],+ [/debug|token|latency/i, 'a debug record'],+ [/usd|dollar|price|amount|spend/i, 'money'],+ [/(^|_)(cost|cents?)$|[a-z0-9](Cost|Cents?)$/, 'money'],+ [/^ids?$|_ids?$|[a-z0-9]Ids?$/, 'an id'],+];++/** A path in the app: /dashboard/ and path characters only — no host, query or fragment. */+const APP_PATH = /^\/dashboard\/[A-Za-z0-9\-._~%/]*$/;++/**+ * Whether an href is a plain path in the app (ChatHref): no `//`, and no+ * `.` or `..` part, written out or encoded, that could step out of /dashboard/.+ */+export function isChatHref(href: unknown): href is ChatHref {+ return (+ typeof href === 'string' &&+ APP_PATH.test(href) &&+ !href.includes('//') &&+ !href+ .split('/')+ .map((part) => part.replace(/%2e/gi, '.'))+ .some((part) => part === '.' || part === '..')+ );+}++const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;++/** Text with every uuid in it shown as "…": "/products/…" (CHAT-03 item 5). */+export function maskIds(text: string): string {+ return text.replace(UUID, '…');+}++/**+ * Why this event can't go to a customer's browser: every forbidden key, and+ * every href that isn't a plain path in the app, by path. Empty when it can.+ * A uuid in text isn't a reason: chatEvent() shows it as "…".+ */+export function clientEventProblems(event: ChatEvent): string[] {+ const problems: string[] = [];+ const walk = (value: unknown, path: string) => {+ if (Array.isArray(value)) {+ value.forEach((item, i) => walk(item, `${path}[${i}]`));+ } else if (value && typeof value === 'object') {+ for (const [key, item] of Object.entries(value)) {+ const at = `${path}.${key}`;+ const forbidden = FORBIDDEN_KEYS.find(([pattern]) => pattern.test(key));+ if (forbidden) problems.push(`${at}: ${forbidden[1]}`);+ else if (key === 'href' && item !== undefined && !isChatHref(item)) {+ problems.push(`${at}: not a path in the app`);+ }+ walk(item, at);+ }+ }+ };+ walk(event, 'event');+ return problems;+}++/** A copy with every uuid in its text shown as "…", but for links (href). */+function masked(value: unknown, key?: string): unknown {+ if (typeof value === 'string') return key === 'href' ? value : maskIds(value);+ if (Array.isArray(value)) return value.map((item) => masked(item));+ if (value && typeof value === 'object') {+ return Object.fromEntries(Object.entries(value).map(([k, item]) => [k, masked(item, k)]));+ }+ return value;+}++/**+ * An event for the stream to send, made safe: throws on anything+ * clientEventProblems finds — a tool's name, an id field, money, a link out+ * of the app — even from a payload built loosely, and shows every uuid in+ * the text as "…".+ *+ * The answer's own text (`text.delta`) is sent as it is: it is the model's+ * words, which may quote what the person wrote, and a uuid can be split+ * across two chunks, so a chunk can't tell. Keeping ids out of the answer is+ * the engine's, on the whole text.+ */+export function chatEvent<K extends ChatEventType>(+ type: K,+ seq: number,+ data: ChatEventPayloads[K],+): Extract<ChatEvent, { type: K }> {+ const problems = clientEventProblems({ type, seq, data } as ChatEvent);+ if (problems.length > 0) {+ throw new Error(`Chat event "${type}" can't go to the browser: ${problems.join('; ')}`);+ }+ const safe = type === 'text.delta' ? data : masked(data);+ return { type, seq, data: safe } as Extract<ChatEvent, { type: K }>;+}diff --git a/web/src/lib/chat/flag.test.ts b/web/src/lib/chat/flag.test.tsnew file mode 100644index 000000000..4da1a312c--- /dev/null+++ b/web/src/lib/chat/flag.test.ts@@ -0,0 +1,63 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { chatAgenticEnabled } from './flag';++/** The new Chat's switch: CHAT_AGENTIC, narrowed by CHAT_AGENTIC_ORGS. */++const ORG_A = '22222222-2222-4222-8222-222222222222';+const ORG_B = '33333333-3333-4333-8333-333333333333';++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('chatAgenticEnabled', () => {+ it('is off when CHAT_AGENTIC is unset, so a self-hosted install sees nothing new', () => {+ vi.stubEnv('CHAT_AGENTIC', undefined);+ vi.stubEnv('CHAT_AGENTIC_ORGS', undefined);+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ expect(chatAgenticEnabled()).toBe(false);+ });++ it('is off for anything but "true"', () => {+ for (const value of ['', 'false', '1', 'yes', 'TRUE', ' true']) {+ vi.stubEnv('CHAT_AGENTIC', value);+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ }+ });++ it('is on for every organization when CHAT_AGENTIC_ORGS is unset or empty', () => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ for (const orgs of [undefined, '', ' , ,']) {+ vi.stubEnv('CHAT_AGENTIC_ORGS', orgs);+ expect(chatAgenticEnabled(ORG_A)).toBe(true);+ expect(chatAgenticEnabled(ORG_B)).toBe(true);+ expect(chatAgenticEnabled()).toBe(true);+ }+ });++ it('is on only for the listed organizations when CHAT_AGENTIC_ORGS is set', () => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ vi.stubEnv(+ 'CHAT_AGENTIC_ORGS',+ ` ${ORG_A.toUpperCase()} , 44444444-4444-4444-8444-444444444444`,+ );+ expect(chatAgenticEnabled(ORG_A)).toBe(true);+ expect(chatAgenticEnabled(` ${ORG_A} `)).toBe(true);+ expect(chatAgenticEnabled(ORG_B)).toBe(false);+ expect(chatAgenticEnabled(null)).toBe(false);+ expect(chatAgenticEnabled()).toBe(false);+ });++ it("doesn't turn Chat on with CHAT_AGENTIC_ORGS alone", () => {+ vi.stubEnv('CHAT_AGENTIC', undefined);+ vi.stubEnv('CHAT_AGENTIC_ORGS', ORG_A);+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ });++ it('reads the variables when asked, not when loaded', () => {+ vi.stubEnv('CHAT_AGENTIC', 'false');+ expect(chatAgenticEnabled(ORG_A)).toBe(false);+ vi.stubEnv('CHAT_AGENTIC', 'true');+ expect(chatAgenticEnabled(ORG_A)).toBe(true);+ });+});diff --git a/web/src/lib/chat/flag.ts b/web/src/lib/chat/flag.tsnew file mode 100644index 000000000..0216b6c93--- /dev/null+++ b/web/src/lib/chat/flag.ts@@ -0,0 +1,34 @@+/**+ * The new Chat (the Drive Chat specs, CHAT-00…25) behind CHAT_AGENTIC.+ *+ * Off unless "true", so a self-hosted install — or the cloud with it unset —+ * keeps today's /dashboard/agent and sees nothing new. With it on,+ * CHAT_AGENTIC_ORGS (organization ids, comma-separated) narrows it to those+ * workspaces; unset or empty, it is on for every one. The API server's+ * lib/chat-flag.js reads the same two variables the same way.+ *+ * Read from the process's environment each time it is asked: not a+ * NEXT_PUBLIC_ variable, so nothing is written into the browser's code.+ * The process sees a change only when it starts again: self-hosted, a+ * restart; on Vercel, a new deployment (a changed environment variable+ * applies to the next deployment, not the running one).+ *+ * Dynamic server code only — route handlers, server actions, and pages and+ * layouts rendered per request. A page rendered at build time would keep the+ * build's value in its HTML; in the browser both variables are missing, so+ * there it is off.+ */+export function chatAgenticEnabled(organizationId?: string | null): boolean {+ if (process.env.CHAT_AGENTIC !== 'true') return false;+ const orgs = chatAgenticOrgs();+ if (orgs.length === 0) return true;+ return !!organizationId && orgs.includes(organizationId.trim().toLowerCase());+}++/** CHAT_AGENTIC_ORGS as a list: trimmed, lower-cased, blanks dropped. */+function chatAgenticOrgs(): string[] {+ return (process.env.CHAT_AGENTIC_ORGS ?? '')+ .split(',')+ .map((id) => id.trim().toLowerCase())+ .filter(Boolean);+}diff --git a/web/src/lib/chat/steps.test.ts b/web/src/lib/chat/steps.test.tsnew file mode 100644index 000000000..6a527ff7f--- /dev/null+++ b/web/src/lib/chat/steps.test.ts@@ -0,0 +1,152 @@+// @vitest-environment node+import { readdirSync, readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';+import type { Database } from '@/types/supabase';+import { chatEvent } from './events';+import {+ CHAT_RUN_STEP_MEMBER_COLUMNS,+ CHAT_RUN_STEP_SELECT,+ toClientStep,+ type ChatRunStepMemberRow,+} from './steps';++/**+ * Stored steps as the browser gets them: the columns a member may read, and+ * the one function that turns a row into a step — never with its tool or+ * debug record, even from a row the server read in full.+ */++type StepRow = Database['public']['Tables']['chat_run_steps']['Row'];++const UUID = '7d3f2c1a-9b8e-4c6d-a5f4-3e2d1c0b9a87';++/** A step as the server reads it with the service role: every column. */+const FULL_ROW: StepRow = {+ id: UUID,+ run_id: '0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d',+ position: 2,+ kind: 'read',+ status: 'done',+ label: 'Read Citations',+ detail: 'Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows',+ scope_json: {+ subject: 'Pricing prompts',+ dateRange: 'Last 30 days',+ platforms: ['ChatGPT', 'Perplexity'],+ brandId: UUID,+ },+ row_count: 42,+ data_as_of: '2026-10-29T06:00:00+00:00',+ started_at: '2026-10-29T09:13:50+00:00',+ finished_at: '2026-10-29T09:13:52+00:00',+ tool: 'list_citations',+ debug_json: { input: { brand_id: UUID }, tokens: 1200, latencyMs: 840 },+};++/** The columns 00400 grants members on chat_run_steps, read from the migrations. */+function grantedColumns(): string[] {+ const dir = fileURLToPath(new URL('../../../../supabase/migrations', import.meta.url));+ let columns: string[] = [];+ for (const file of readdirSync(dir)+ .filter((f) => f.endsWith('.sql'))+ .sort()) {+ const sql = readFileSync(`${dir}/${file}`, 'utf8').replace(/--[^\n]*/g, '');+ const grants = sql.matchAll(+ /grant\s+select\s*\(([^)]*)\)\s*on\s+(?:table\s+)?(?:public\.)?chat_run_steps\s+to\s+authenticated/gi,+ );+ for (const [, list] of grants) columns = list.split(',').map((c) => c.trim());+ }+ return columns;+}++describe('chat run step columns', () => {+ it('are the ones the migrations grant members, without the tool and its debug record', () => {+ expect([...CHAT_RUN_STEP_MEMBER_COLUMNS].sort()).toEqual(grantedColumns().sort());+ expect(CHAT_RUN_STEP_MEMBER_COLUMNS).not.toContain('tool');+ expect(CHAT_RUN_STEP_MEMBER_COLUMNS).not.toContain('debug_json');+ });++ it('cover every other column of the table', () => {+ const others = Object.keys(FULL_ROW).filter((c) => c !== 'tool' && c !== 'debug_json');+ expect([...CHAT_RUN_STEP_MEMBER_COLUMNS].sort()).toEqual(others.sort());+ });++ it('make a select list, so a member never asks for *', () => {+ expect(CHAT_RUN_STEP_SELECT).toBe(CHAT_RUN_STEP_MEMBER_COLUMNS.join(', '));+ expect(CHAT_RUN_STEP_SELECT).not.toContain('*');+ });+});++describe('toClientStep', () => {+ it("gives the browser the step, never the tool or its debug record, from the server's full row", () => {+ const step = toClientStep(FULL_ROW);+ expect(step).toEqual({+ n: 2,+ kind: 'read',+ status: 'done',+ label: 'Read Citations',+ detail: 'Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows',+ scope: {+ subject: 'Pricing prompts',+ dateRange: 'Last 30 days',+ platforms: ['ChatGPT', 'Perplexity'],+ },+ rowCount: 42,+ dataAsOf: '2026-10-29T06:00:00.000Z',+ });+ const wire = JSON.stringify(step);+ expect(wire).not.toMatch(/list_citations|debug|tokens|latency|tool/i);+ expect(wire).not.toContain(UUID);+ });++ it('goes out as a step event as it is', () => {+ const step = toClientStep(FULL_ROW);+ expect(step).not.toBeNull();+ expect(chatEvent('step.finished', 1, { step: step! }).data.step).toEqual(step);+ });++ it('takes a row read with the member columns only', () => {+ const memberRow: ChatRunStepMemberRow = {+ id: UUID,+ run_id: UUID,+ position: 1,+ kind: 'thinking',+ status: 'running',+ label: 'Thinking',+ detail: null,+ scope_json: null,+ row_count: null,+ data_as_of: null,+ started_at: null,+ finished_at: null,+ };+ expect(toClientStep(memberRow)).toEqual({+ n: 1,+ kind: 'thinking',+ status: 'running',+ label: 'Thinking',+ });+ });++ it('shows a uuid in its words as "…" and keeps only the names in its scope', () => {+ const step = toClientStep({+ ...FULL_ROW,+ label: `Opened /products/${UUID}`,+ detail: `Prompt ${UUID}`,+ scope_json: { platforms: ['ChatGPT', 7, '', UUID], brand: 'Acme', prompt_ids: [UUID] },+ });+ expect(step?.label).toBe('Opened /products/…');+ expect(step?.detail).toBe('Prompt …');+ expect(step?.scope).toEqual({ platforms: ['ChatGPT', '…'], brand: 'Acme' });+ });++ it('leaves out a data time it cannot read', () => {+ expect(toClientStep({ ...FULL_ROW, data_as_of: 'soon' })).not.toHaveProperty('dataAsOf');+ });++ it("skips a kind or a status this build doesn't know (a newer server's)", () => {+ expect(toClientStep({ ...FULL_ROW, kind: 'navigate' })).toBeNull();+ expect(toClientStep({ ...FULL_ROW, status: 'archived' })).toBeNull();+ });+});diff --git a/web/src/lib/chat/steps.ts b/web/src/lib/chat/steps.tsnew file mode 100644index 000000000..d6bba780a--- /dev/null+++ b/web/src/lib/chat/steps.ts@@ -0,0 +1,91 @@+import type { Database } from '@/types/supabase';+import {+ CHAT_STEP_KINDS,+ CHAT_STEP_STATUSES,+ maskIds,+ type ChatStep,+ type ChatStepKind,+ type ChatStepScope,+ type ChatStepStatus,+} from './events';++type StepRow = Database['public']['Tables']['chat_run_steps']['Row'];++/**+ * chat_run_steps' columns a member may read: every one but `tool` and+ * `debug_json`, which stay with the server and staff (00400's grants;+ * CHAT-03 item 22). As a member, select these by name: `select('*')` asks+ * for the two others too and is refused (42501).+ */+export const CHAT_RUN_STEP_MEMBER_COLUMNS = [+ 'id',+ 'run_id',+ 'position',+ 'kind',+ 'status',+ 'label',+ 'detail',+ 'scope_json',+ 'row_count',+ 'data_as_of',+ 'started_at',+ 'finished_at',+] as const satisfies readonly (keyof StepRow)[];++/** The member columns as a PostgREST select list. */+export const CHAT_RUN_STEP_SELECT = CHAT_RUN_STEP_MEMBER_COLUMNS.join(', ');++/** A step row as a member reads it; a server's full row is one too. */+export type ChatRunStepMemberRow = Pick<StepRow, (typeof CHAT_RUN_STEP_MEMBER_COLUMNS)[number]>;++const isKind = (kind: string): kind is ChatStepKind =>+ (CHAT_STEP_KINDS as readonly string[]).includes(kind);+const isStatus = (status: string): status is ChatStepStatus =>+ (CHAT_STEP_STATUSES as readonly string[]).includes(status);++const text = (value: unknown) =>+ typeof value === 'string' && value !== '' ? maskIds(value) : undefined;++/** scope_json's names (subject, dateRange, platforms, brand), and nothing else it may hold. */+function scopeOf(json: unknown): ChatStepScope | undefined {+ if (!json || typeof json !== 'object' || Array.isArray(json)) return undefined;+ const raw = json as Record<string, unknown>;+ const scope: ChatStepScope = {};+ const subject = text(raw.subject);+ const dateRange = text(raw.dateRange);+ const brand = text(raw.brand);+ const platforms = Array.isArray(raw.platforms)+ ? raw.platforms.map(text).filter((name): name is string => !!name)+ : [];+ if (subject) scope.subject = subject;+ if (dateRange) scope.dateRange = dateRange;+ if (platforms.length > 0) scope.platforms = platforms;+ if (brand) scope.brand = brand;+ return Object.keys(scope).length > 0 ? scope : undefined;+}++/**+ * A stored step as the browser gets it — for the conversation API and a+ * reload (CHAT-03 items 1 and 21) — the one way steps leave the server.+ * Built field by field, never spread from the row, so a row read with the+ * service role gives up its `tool` and `debug_json` here too; a uuid in its+ * words shows as "…". Null for a kind or status this build doesn't know (a+ * newer server's), which the browser skips, as it skips an unknown event.+ */+export function toClientStep(row: ChatRunStepMemberRow): ChatStep | null {+ if (!isKind(row.kind) || !isStatus(row.status)) return null;+ const step: ChatStep = {+ n: row.position,+ kind: row.kind,+ status: row.status,+ label: maskIds(row.label),+ };+ const detail = text(row.detail);+ const scope = scopeOf(row.scope_json);+ if (detail) step.detail = detail;+ if (scope) step.scope = scope;+ if (row.row_count !== null) step.rowCount = row.row_count;+ const dataAsOf = row.data_as_of ? Date.parse(row.data_as_of) : NaN;+ if (!Number.isNaN(dataAsOf)) step.dataAsOf = new Date(dataAsOf).toISOString();+ return step;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 5153c9590..a27418eee 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1364,6 +1364,262 @@ export type Database = {},]}+ chat_conversations: {+ Row: {+ archived_at: string | null+ brand_id: string | null+ created_at: string+ id: string+ last_message_at: string+ organization_id: string+ origin: string+ origin_page: string | null+ pinned_at: string | null+ title: string | null+ updated_at: string+ user_id: string+ }+ Insert: {+ archived_at?: string | null+ brand_id?: string | null+ created_at?: string+ id?: string+ last_message_at?: string+ organization_id: string+ origin?: string+ origin_page?: string | null+ pinned_at?: string | null+ title?: string | null+ updated_at?: string+ user_id: string+ }+ Update: {+ archived_at?: string | null+ brand_id?: string | null+ created_at?: string+ id?: string+ last_message_at?: string+ organization_id?: string+ origin?: string+ origin_page?: string | null+ pinned_at?: string | null+ title?: string | null+ updated_at?: string+ user_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "chat_conversations_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_conversations_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ ]+ }+ chat_messages: {+ Row: {+ content_md: string+ conversation_id: string+ created_at: string+ data_as_of: string | null+ generated_at: string | null+ id: string+ role: string+ timezone: string | null+ }+ Insert: {+ content_md?: string+ conversation_id: string+ created_at?: string+ data_as_of?: string | null+ generated_at?: string | null+ id?: string+ role: string+ timezone?: string | null+ }+ Update: {+ content_md?: string+ conversation_id?: string+ created_at?: string+ data_as_of?: string | null+ generated_at?: string | null+ id?: string+ role?: string+ timezone?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "chat_messages_conversation_id_fkey"+ columns: ["conversation_id"]+ isOneToOne: false+ referencedRelation: "chat_conversations"+ referencedColumns: ["id"]+ },+ ]+ }+ chat_run_steps: {+ Row: {+ data_as_of: string | null+ debug_json: Json | null+ detail: string | null+ finished_at: string | null+ id: string+ kind: string+ label: string+ position: number+ row_count: number | null+ run_id: string+ scope_json: Json | null+ started_at: string | null+ status: string+ tool: string | null+ }+ Insert: {+ data_as_of?: string | null+ debug_json?: Json | null+ detail?: string | null+ finished_at?: string | null+ id?: string+ kind: string+ label: string+ position: number+ row_count?: number | null+ run_id: string+ scope_json?: Json | null+ started_at?: string | null+ status?: string+ tool?: string | null+ }+ Update: {+ data_as_of?: string | null+ debug_json?: Json | null+ detail?: string | null+ finished_at?: string | null+ id?: string+ kind?: string+ label?: string+ position?: number+ row_count?: number | null+ run_id?: string+ scope_json?: Json | null+ started_at?: string | null+ status?: string+ tool?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "chat_run_steps_kind_fkey"+ columns: ["kind"]+ isOneToOne: false+ referencedRelation: "chat_step_kinds"+ referencedColumns: ["kind"]+ },+ {+ foreignKeyName: "chat_run_steps_run_id_fkey"+ columns: ["run_id"]+ isOneToOne: false+ referencedRelation: "chat_runs"+ referencedColumns: ["id"]+ },+ ]+ }+ chat_runs: {+ Row: {+ conversation_id: string+ created_at: string+ effort: string+ error: string | null+ finished_at: string | null+ id: string+ message_id: string+ model: string+ started_at: string | null+ status: string+ }+ Insert: {+ conversation_id: string+ created_at?: string+ effort?: string+ error?: string | null+ finished_at?: string | null+ id?: string+ message_id: string+ model?: string+ started_at?: string | null+ status?: string+ }+ Update: {+ conversation_id?: string+ created_at?: string+ effort?: string+ error?: string | null+ finished_at?: string | null+ id?: string+ message_id?: string+ model?: string+ started_at?: string | null+ status?: string+ }+ Relationships: [+ {+ foreignKeyName: "chat_runs_message_id_conversation_id_fkey"+ columns: ["message_id", "conversation_id"]+ isOneToOne: false+ referencedRelation: "chat_messages"+ referencedColumns: ["id", "conversation_id"]+ },+ ]+ }+ chat_step_kinds: {+ Row: {+ kind: string+ }+ Insert: {+ kind: string+ }+ Update: {+ kind?: string+ }+ Relationships: []+ }+ chat_user_prefs: {+ Row: {+ effort: string | null+ focus: string[] | null+ menu_open: boolean+ model: string | null+ page_open: string+ updated_at: string+ user_id: string+ }+ Insert: {+ effort?: string | null+ focus?: string[] | null+ menu_open?: boolean+ model?: string | null+ page_open?: string+ updated_at?: string+ user_id: string+ }+ Update: {+ effort?: string | null+ focus?: string[] | null+ menu_open?: boolean+ model?: string | null+ page_open?: string+ updated_at?: string+ user_id?: string+ }+ Relationships: []+ }citation_urls: {Row: {domain: string@@ -4906,6 +5162,10 @@ export type Database = {Args: { p_brand_id: string; p_days?: number }Returns: Json}+ chat_text_array_distinct: {+ Args: { p_values: string[] }+ Returns: boolean+ }citation_competitor_sources: {Args: {p_brand_domains: string[]