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): log every change Chat makes, with Undo and no duplicates (#1786)
Cihana8925f0cb3c6
diff --git a/supabase/migrations/00402_chat_activity.sql b/supabase/migrations/00402_chat_activity.sqlnew file mode 100644index 000000000..9b1a86d03--- /dev/null+++ b/supabase/migrations/00402_chat_activity.sql@@ -0,0 +1,181 @@+-- ============================================================================+-- 00402: Chat's activity log with Undo, and its idempotency keys+-- ============================================================================+-- Every change Chat makes is visible and, where possible, undoable (CHAT-20+-- §2 principle 6, §10), and a double click never makes it twice (§11c).+-- Behind CHAT_AGENTIC: nothing writes these tables while the flag is off.+--+-- * chat_activity_log: one row per WRITE or EXECUTE Chat ran (§10a layer 2,+-- mockup #g-activity): who, from which surface, in which chat, run and+-- step; the tool by its label key (never its name, CHAT-03 item 22), its+-- class, the run's mode and how it was approved; the target (type and+-- id), and the summary in the person's words (a messages/en.json key+-- under chatActivity.summary, with its values). kind says which row:+-- - change: a WRITE or EXECUTE that ran;+-- - undo: an Undo (approval 'run', undoes_id pointing at the change it+-- undid, which turns 'undone');+-- - access.denied: a call the precedence refused (§4c, §10a "Denied+-- requests appear as access.denied rows"), with its reason+-- (denial_code, denial_json: what the denial.ts answer is built+-- from) and no approval, target or Undo. A read's denial too.+-- A person reads their own rows; an Admin reads the workspace's (§10a+-- "Members see their own rows; Admins see all"). Only the server writes.+-- Rows stay when the chat, the run or the member goes (§16c: Activity+-- log rows stay).+-- - undo_json: what Undo restores and what it checks first (the before+-- state, and the after state a conflict is measured against). Server+-- only: members are granted every column but this one.+-- - undo_until: the end of the tool's Undo window (CHAT-20 §9: 7 or 30+-- days), null when there is no Undo (an EXECUTE, §10b).+-- - status: done; undone; undo_conflict when an Undo found the target+-- changed since ("This changed since. Open it to undo by hand.").+-- An Undo may be tried again from undo_conflict.+-- * chat_idempotency_keys: a WRITE's or EXECUTE's key (§9's column) for 24+-- hours per workspace, with the first call's result: a double-clicked+-- approval, a reconnect or a retry gets that result back and makes+-- nothing new. A key is claimed (pending) before the change runs and+-- holds its result once it ran; a call that failed gives its key back.+-- request_hash is what the key was claimed for (the tool and its input):+-- the same key with another request is an approval mismatch. Server+-- only: no member reads or writes it.++-- ─── The activity log ───────────────────────────────────────────────────────++create table if not exists public.chat_activity_log (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ -- The person Chat acted as (§2 principle 1). Null once their account is+ -- deleted: the row stays, for the workspace's Admins.+ user_id uuid references auth.users(id) on delete set null,+ brand_id uuid references public.brands(id) on delete set null,+ -- Where it ran. A deleted chat, run or step leaves its rows.+ conversation_id uuid references public.chat_conversations(id) on delete set null,+ run_id uuid references public.chat_runs(id) on delete set null,+ step_id uuid references public.chat_run_steps(id) on delete set null,+ -- §10a's sources: Chat, an agent (CHAT-21), MCP, a schedule (CHAT-12), a watch rule (CHAT-22).+ surface text not null check (surface in ('chat', 'agent', 'mcp', 'schedule', 'watch_rule')),+ -- change, undo or access.denied (above).+ kind text not null default 'change' check (kind in ('change', 'undo', 'access.denied')),+ -- The tool's label key (chat_settings.tool_policies' keys), never its name.+ tool_key text not null check (tool_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ -- A read only in an access.denied row.+ class text not null check (class in ('read', 'write', 'execute')),+ -- The run's mode (CHAT-02); null for the person's own action (an Undo) and a denial.+ mode text check (mode in ('ask_first', 'auto', 'full_auto')),+ -- ask: approved on its card; click: an EXECUTE the person clicked; auto:+ -- ran without a card (auto_via says why); run: the person's own action,+ -- which needs no card (Undo, §10b). Null for a denial: nothing ran.+ approval_kind text check (approval_kind in ('run', 'ask', 'click', 'auto')),+ auto_via text check (auto_via in ('always', 'full_auto', 'dont_ask_again')),+ -- What it changed: 'content_draft', 'content_opportunity', 'prompt_suggestion'…+ -- Null for a denial.+ target_type text check (target_type ~ '^[a-z][a-z_]{1,39}$'),+ target_id text check (char_length(target_id) between 1 and 200),+ -- A denial's reason, the precedence's code (no_access, brand_scope,+ -- forbidden_role, plan_locked…), and the rest of it ({role, roles},+ -- {needs}, {group}): what the out-of-permission answer is built from.+ denial_code text check (denial_code ~ '^[a-z_]{1,40}$'),+ denial_json jsonb check (denial_json is null or jsonb_typeof(denial_json) = 'object'),+ -- chatActivity.summary.{summary_key} in messages/en.json, and its values.+ summary_key text not null check (summary_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ summary_params jsonb not null default '{}'::jsonb check (jsonb_typeof(summary_params) = 'object'),+ -- Server only (not granted to members): what Undo restores and checks.+ undo_json jsonb check (undo_json is null or jsonb_typeof(undo_json) = 'object'),+ undo_until timestamptz,+ -- This row is the Undo of that one.+ undoes_id uuid references public.chat_activity_log(id) on delete set null,+ status text not null default 'done' check (status in ('done', 'undone', 'undo_conflict')),+ undone_at timestamptz,+ undone_by uuid references auth.users(id) on delete set null,+ created_at timestamptz not null default now(),+ -- What each kind holds: a change and an Undo were approved and have a+ -- target; a denial has a reason, and neither.+ check ((kind = 'access.denied') = (approval_kind is null)),+ check ((kind = 'access.denied') = (denial_code is not null)),+ check (kind = 'access.denied' or (target_type is not null and class <> 'read')),+ -- Only an Undo points at the change it undid.+ check (kind = 'undo' or undoes_id is null),+ -- auto_via only, and always, on a change that ran without a card.+ check ((auto_via is not null) = (approval_kind is not distinct from 'auto')),+ -- Undo only on a WRITE that ran (§10b: an EXECUTE has none); with what it restores.+ check (undo_until is null or (kind = 'change' and class = 'write')),+ check (undo_until is null or undo_json is not null),+ check ((status = 'undone') = (undone_at is not null)),+ check (status = 'done' or kind = 'change')+);++-- Admins: the workspace's log, newest first. Members: their own.+create index if not exists chat_activity_log_organization_created_idx+ on public.chat_activity_log (organization_id, created_at desc);+create index if not exists chat_activity_log_user_created_idx+ on public.chat_activity_log (user_id, created_at desc);+create index if not exists chat_activity_log_undoes_idx+ on public.chat_activity_log (undoes_id) where undoes_id is not null;++comment on table public.chat_activity_log is+ 'Chat (00402): one row per WRITE or EXECUTE Chat ran, per Undo and per access.denied (CHAT-20 §10a): actor, surface, tool label key, class, mode, approval, target, summary (en.json key + values), Undo window and status, or a denial''s reason. A person reads their own rows, an Admin the workspace''s; the server writes.';+comment on column public.chat_activity_log.undo_json is+ 'What Undo restores and the state it checks first (CHAT-20 §10b). Server only: never granted to members.';+comment on column public.chat_activity_log.summary_key is+ 'The key under chatActivity.summary in web messages/en.json; summary_params holds its values.';++-- ─── Idempotency keys ───────────────────────────────────────────────────────++create table if not exists public.chat_idempotency_keys (+ organization_id uuid not null references public.organizations(id) on delete cascade,+ key text not null check (key ~ '^[a-z][A-Za-z0-9]{1,63}:[0-9a-f]{64}$'),+ -- The tool and input the key was claimed for (sha-256, hex).+ request_hash text not null check (request_hash ~ '^[0-9a-f]{64}$'),+ -- pending: the change is running; done: result_json is its result.+ status text not null default 'pending' check (status in ('pending', 'done')),+ result_json jsonb,+ -- The log row the change wrote, for a repeat to point at the same one.+ activity_id uuid references public.chat_activity_log(id) on delete set null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null default (now() + interval '24 hours'),+ primary key (organization_id, key),+ check (status = 'pending' or result_json is not null)+);++-- The sweep of expired keys.+create index if not exists chat_idempotency_keys_expires_idx+ on public.chat_idempotency_keys (expires_at);++comment on table public.chat_idempotency_keys is+ 'Chat (00402): a WRITE''s or EXECUTE''s idempotency key for 24 hours per workspace (CHAT-20 §11c), with the first call''s result. Server only.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_activity_log enable row level security;+alter table public.chat_idempotency_keys enable row level security;++revoke all on table public.chat_activity_log from anon, authenticated;+revoke all on table public.chat_idempotency_keys from anon, authenticated;++-- Every column but undo_json.+grant select (+ id, organization_id, user_id, brand_id, conversation_id, run_id, step_id, surface, kind,+ tool_key, class, mode, approval_kind, auto_via, target_type, target_id, denial_code,+ denial_json, summary_key, summary_params, undo_until, undoes_id, status, undone_at,+ undone_by, created_at+) on table public.chat_activity_log to authenticated;++grant all on table public.chat_activity_log to service_role;+grant all on table public.chat_idempotency_keys to service_role;++-- A person's own rows, and every row of the workspace for its Admins, while+-- they belong to it: one who left, or moved to another, reads none.+drop policy if exists "chat_activity_log: own or admin select" on public.chat_activity_log;+create policy "chat_activity_log: own or admin select"+ on public.chat_activity_log+ for select+ using (+ organization_id in (+ select p.organization_id+ from public.profiles p+ where p.id = auth.uid()+ and (p.role = 'admin' or chat_activity_log.user_id = auth.uid())+ )+ );++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex e7fac9278..e0cebc8d5 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -44200,6 +44200,191 @@ create policy "chat_auto_choices: own delete"notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00402_chat_activity.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00402: Chat's activity log with Undo, and its idempotency keys+-- ============================================================================+-- Every change Chat makes is visible and, where possible, undoable (CHAT-20+-- §2 principle 6, §10), and a double click never makes it twice (§11c).+-- Behind CHAT_AGENTIC: nothing writes these tables while the flag is off.+--+-- * chat_activity_log: one row per WRITE or EXECUTE Chat ran (§10a layer 2,+-- mockup #g-activity): who, from which surface, in which chat, run and+-- step; the tool by its label key (never its name, CHAT-03 item 22), its+-- class, the run's mode and how it was approved; the target (type and+-- id), and the summary in the person's words (a messages/en.json key+-- under chatActivity.summary, with its values). kind says which row:+-- - change: a WRITE or EXECUTE that ran;+-- - undo: an Undo (approval 'run', undoes_id pointing at the change it+-- undid, which turns 'undone');+-- - access.denied: a call the precedence refused (§4c, §10a "Denied+-- requests appear as access.denied rows"), with its reason+-- (denial_code, denial_json: what the denial.ts answer is built+-- from) and no approval, target or Undo. A read's denial too.+-- A person reads their own rows; an Admin reads the workspace's (§10a+-- "Members see their own rows; Admins see all"). Only the server writes.+-- Rows stay when the chat, the run or the member goes (§16c: Activity+-- log rows stay).+-- - undo_json: what Undo restores and what it checks first (the before+-- state, and the after state a conflict is measured against). Server+-- only: members are granted every column but this one.+-- - undo_until: the end of the tool's Undo window (CHAT-20 §9: 7 or 30+-- days), null when there is no Undo (an EXECUTE, §10b).+-- - status: done; undone; undo_conflict when an Undo found the target+-- changed since ("This changed since. Open it to undo by hand.").+-- An Undo may be tried again from undo_conflict.+-- * chat_idempotency_keys: a WRITE's or EXECUTE's key (§9's column) for 24+-- hours per workspace, with the first call's result: a double-clicked+-- approval, a reconnect or a retry gets that result back and makes+-- nothing new. A key is claimed (pending) before the change runs and+-- holds its result once it ran; a call that failed gives its key back.+-- request_hash is what the key was claimed for (the tool and its input):+-- the same key with another request is an approval mismatch. Server+-- only: no member reads or writes it.++-- ─── The activity log ───────────────────────────────────────────────────────++create table if not exists public.chat_activity_log (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ -- The person Chat acted as (§2 principle 1). Null once their account is+ -- deleted: the row stays, for the workspace's Admins.+ user_id uuid references auth.users(id) on delete set null,+ brand_id uuid references public.brands(id) on delete set null,+ -- Where it ran. A deleted chat, run or step leaves its rows.+ conversation_id uuid references public.chat_conversations(id) on delete set null,+ run_id uuid references public.chat_runs(id) on delete set null,+ step_id uuid references public.chat_run_steps(id) on delete set null,+ -- §10a's sources: Chat, an agent (CHAT-21), MCP, a schedule (CHAT-12), a watch rule (CHAT-22).+ surface text not null check (surface in ('chat', 'agent', 'mcp', 'schedule', 'watch_rule')),+ -- change, undo or access.denied (above).+ kind text not null default 'change' check (kind in ('change', 'undo', 'access.denied')),+ -- The tool's label key (chat_settings.tool_policies' keys), never its name.+ tool_key text not null check (tool_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ -- A read only in an access.denied row.+ class text not null check (class in ('read', 'write', 'execute')),+ -- The run's mode (CHAT-02); null for the person's own action (an Undo) and a denial.+ mode text check (mode in ('ask_first', 'auto', 'full_auto')),+ -- ask: approved on its card; click: an EXECUTE the person clicked; auto:+ -- ran without a card (auto_via says why); run: the person's own action,+ -- which needs no card (Undo, §10b). Null for a denial: nothing ran.+ approval_kind text check (approval_kind in ('run', 'ask', 'click', 'auto')),+ auto_via text check (auto_via in ('always', 'full_auto', 'dont_ask_again')),+ -- What it changed: 'content_draft', 'content_opportunity', 'prompt_suggestion'…+ -- Null for a denial.+ target_type text check (target_type ~ '^[a-z][a-z_]{1,39}$'),+ target_id text check (char_length(target_id) between 1 and 200),+ -- A denial's reason, the precedence's code (no_access, brand_scope,+ -- forbidden_role, plan_locked…), and the rest of it ({role, roles},+ -- {needs}, {group}): what the out-of-permission answer is built from.+ denial_code text check (denial_code ~ '^[a-z_]{1,40}$'),+ denial_json jsonb check (denial_json is null or jsonb_typeof(denial_json) = 'object'),+ -- chatActivity.summary.{summary_key} in messages/en.json, and its values.+ summary_key text not null check (summary_key ~ '^[a-z][A-Za-z0-9]{1,63}$'),+ summary_params jsonb not null default '{}'::jsonb check (jsonb_typeof(summary_params) = 'object'),+ -- Server only (not granted to members): what Undo restores and checks.+ undo_json jsonb check (undo_json is null or jsonb_typeof(undo_json) = 'object'),+ undo_until timestamptz,+ -- This row is the Undo of that one.+ undoes_id uuid references public.chat_activity_log(id) on delete set null,+ status text not null default 'done' check (status in ('done', 'undone', 'undo_conflict')),+ undone_at timestamptz,+ undone_by uuid references auth.users(id) on delete set null,+ created_at timestamptz not null default now(),+ -- What each kind holds: a change and an Undo were approved and have a+ -- target; a denial has a reason, and neither.+ check ((kind = 'access.denied') = (approval_kind is null)),+ check ((kind = 'access.denied') = (denial_code is not null)),+ check (kind = 'access.denied' or (target_type is not null and class <> 'read')),+ -- Only an Undo points at the change it undid.+ check (kind = 'undo' or undoes_id is null),+ -- auto_via only, and always, on a change that ran without a card.+ check ((auto_via is not null) = (approval_kind is not distinct from 'auto')),+ -- Undo only on a WRITE that ran (§10b: an EXECUTE has none); with what it restores.+ check (undo_until is null or (kind = 'change' and class = 'write')),+ check (undo_until is null or undo_json is not null),+ check ((status = 'undone') = (undone_at is not null)),+ check (status = 'done' or kind = 'change')+);++-- Admins: the workspace's log, newest first. Members: their own.+create index if not exists chat_activity_log_organization_created_idx+ on public.chat_activity_log (organization_id, created_at desc);+create index if not exists chat_activity_log_user_created_idx+ on public.chat_activity_log (user_id, created_at desc);+create index if not exists chat_activity_log_undoes_idx+ on public.chat_activity_log (undoes_id) where undoes_id is not null;++comment on table public.chat_activity_log is+ 'Chat (00402): one row per WRITE or EXECUTE Chat ran, per Undo and per access.denied (CHAT-20 §10a): actor, surface, tool label key, class, mode, approval, target, summary (en.json key + values), Undo window and status, or a denial''s reason. A person reads their own rows, an Admin the workspace''s; the server writes.';+comment on column public.chat_activity_log.undo_json is+ 'What Undo restores and the state it checks first (CHAT-20 §10b). Server only: never granted to members.';+comment on column public.chat_activity_log.summary_key is+ 'The key under chatActivity.summary in web messages/en.json; summary_params holds its values.';++-- ─── Idempotency keys ───────────────────────────────────────────────────────++create table if not exists public.chat_idempotency_keys (+ organization_id uuid not null references public.organizations(id) on delete cascade,+ key text not null check (key ~ '^[a-z][A-Za-z0-9]{1,63}:[0-9a-f]{64}$'),+ -- The tool and input the key was claimed for (sha-256, hex).+ request_hash text not null check (request_hash ~ '^[0-9a-f]{64}$'),+ -- pending: the change is running; done: result_json is its result.+ status text not null default 'pending' check (status in ('pending', 'done')),+ result_json jsonb,+ -- The log row the change wrote, for a repeat to point at the same one.+ activity_id uuid references public.chat_activity_log(id) on delete set null,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null default (now() + interval '24 hours'),+ primary key (organization_id, key),+ check (status = 'pending' or result_json is not null)+);++-- The sweep of expired keys.+create index if not exists chat_idempotency_keys_expires_idx+ on public.chat_idempotency_keys (expires_at);++comment on table public.chat_idempotency_keys is+ 'Chat (00402): a WRITE''s or EXECUTE''s idempotency key for 24 hours per workspace (CHAT-20 §11c), with the first call''s result. Server only.';++-- ─── Who reads and writes ───────────────────────────────────────────────────++alter table public.chat_activity_log enable row level security;+alter table public.chat_idempotency_keys enable row level security;++revoke all on table public.chat_activity_log from anon, authenticated;+revoke all on table public.chat_idempotency_keys from anon, authenticated;++-- Every column but undo_json.+grant select (+ id, organization_id, user_id, brand_id, conversation_id, run_id, step_id, surface, kind,+ tool_key, class, mode, approval_kind, auto_via, target_type, target_id, denial_code,+ denial_json, summary_key, summary_params, undo_until, undoes_id, status, undone_at,+ undone_by, created_at+) on table public.chat_activity_log to authenticated;++grant all on table public.chat_activity_log to service_role;+grant all on table public.chat_idempotency_keys to service_role;++-- A person's own rows, and every row of the workspace for its Admins, while+-- they belong to it: one who left, or moved to another, reads none.+drop policy if exists "chat_activity_log: own or admin select" on public.chat_activity_log;+create policy "chat_activity_log: own or admin select"+ on public.chat_activity_log+ for select+ using (+ organization_id in (+ select p.organization_id+ from public.profiles p+ where p.id = auth.uid()+ and (p.role = 'admin' or chat_activity_log.user_id = auth.uid())+ )+ );++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00404_chat_model_prices.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 97102e35c..510eed9d6 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3229,6 +3229,28 @@"demo": "No one: the demo brand keeps its sample data."}},+ "chatActivity": {+ "summary": {+ "saveDraft": "Saved the draft “{title}”",+ "saveDraftUndo": "Moved the draft “{title}” to the archive",+ "opportunityStatus": "{status, select, dismissed {Dismissed} other {Marked reviewed}} the opportunity “{title}”",+ "opportunityStatusUndo": "Put the opportunity “{title}” back as it was",+ "dismissSuggestion": "Dismissed the prompt suggestion “{text}”",+ "dismissSuggestionUndo": "Brought back the prompt suggestion “{text}”",+ "accessDenied": "Not allowed: {tool}"+ },+ "undo": {+ "ok": "Undone.",+ "changed": "This changed since. Open it to undo by hand.",+ "gone": "This was deleted since, so there's nothing to undo.",+ "expired": "Undo is no longer available for this change. Change it by hand instead.",+ "notUndoable": "This change can't be undone here.",+ "alreadyUndone": "This was already undone.",+ "inProgress": "Undo is already on its way.",+ "notFound": "I couldn't find that change.",+ "failed": "Something went wrong, so nothing was undone. Try again."+ }+ },"audit": {"title": "Site Audit","description": "Score any page against the 48-signal AEO/GEO",diff --git a/web/src/lib/chat/activity.ts b/web/src/lib/chat/activity.tsnew file mode 100644index 000000000..b9ed748ed--- /dev/null+++ b/web/src/lib/chat/activity.ts@@ -0,0 +1,192 @@+import { createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { Json } from '@/types/supabase';+import type { ChatMode, ChatSurface, ToolDecision, ToolDenial } from './precedence';+import type { ChatTool, ToolClass } from './registry/define-tool';++/**+ * The Activity log (CHAT-20 §10a layer 2; chat_activity_log, 00402): one row+ * for each WRITE or EXECUTE Chat ran (kind `change`), each Undo (`undo`) and+ * each call the precedence refused (`access.denied`, §4c). Written by the+ * server, never by the model. A row names its tool by the+ * label key and says what changed in the person's words: a key under+ * chatActivity.summary in messages/en.json and its values. A person reads+ * their own rows, an Admin the workspace's (00402's policy); what Undo+ * restores (undo_json) stays with the server. Server only.+ */++/**+ * How a change was approved: `ask` its card's OK, `click` an EXECUTE's+ * click, `auto` it ran without a card (via Always, Full auto or the person's+ * "Don't ask again"), `run` the person's own action, which needs no card+ * (an Undo, §10b).+ */+export type ActivityApproval =+ | { kind: 'ask' }+ | { kind: 'click' }+ | { kind: 'auto'; via: 'always' | 'full_auto' | 'dont_ask_again' }+ | { kind: 'run' };++/**+ * The approval a decision leads to once it is acted on: a card the person+ * approved, an EXECUTE they clicked, or a WRITE that ran by itself. Null for+ * what isn't logged: a read, or a refusal.+ */+export function approvalFor(decision: ToolDecision): ActivityApproval | null {+ switch (decision.kind) {+ case 'run':+ return decision.via === 'read' ? null : { kind: 'auto', via: decision.via };+ case 'ask':+ return { kind: 'ask' };+ case 'click':+ return { kind: 'click' };+ default:+ return null;+ }+}++/** Where the row points: the chat, run and step the change was made in, when there was one. */+export interface ActivityPlace {+ conversationId: string | null;+ runId: string | null;+ stepId: string | null;+}++/** One row to write. */+export interface ActivityEntry {+ organizationId: string;+ /** The person Chat acted as, or who undid. */+ userId: string;+ brandId: string | null;+ place: ActivityPlace;+ surface: ChatSurface;+ tool: Pick<ChatTool, 'labelKey' | 'class'>;+ /** The run's mode; null for an Undo. */+ mode: ChatMode | null;+ approval: ActivityApproval;+ target: { type: string; id: string | null };+ /** A key under chatActivity.summary, and its values. */+ summary: { key: string; params: Record<string, string> };+ /** What Undo restores and checks, and until when; null without an Undo. */+ undo: { data: { [key: string]: Json }; until: Date } | null;+ /** The change this row undoes. */+ undoesId?: string;+}++/** Writes a change's row, or an Undo's (undoesId), and returns its id. */+export async function logActivity(entry: ActivityEntry): Promise<string> {+ if (entry.tool.class === 'read') throw new Error('A read is not logged');+ if (entry.tool.class === 'execute' && (entry.undo || entry.approval.kind !== 'click')) {+ throw new Error('An EXECUTE runs on a click and has no Undo');+ }+ const { data, error } = await supabaseAdmin+ .from('chat_activity_log')+ .insert({+ organization_id: entry.organizationId,+ user_id: entry.userId,+ brand_id: entry.brandId,+ conversation_id: entry.place.conversationId,+ run_id: entry.place.runId,+ step_id: entry.place.stepId,+ surface: entry.surface,+ kind: entry.undoesId ? 'undo' : 'change',+ tool_key: entry.tool.labelKey,+ class: entry.tool.class,+ mode: entry.mode,+ approval_kind: entry.approval.kind,+ auto_via: entry.approval.kind === 'auto' ? entry.approval.via : null,+ target_type: entry.target.type,+ target_id: entry.target.id,+ summary_key: entry.summary.key,+ summary_params: entry.summary.params,+ undo_json: entry.undo?.data ?? null,+ undo_until: entry.undo?.until.toISOString() ?? null,+ undoes_id: entry.undoesId ?? null,+ })+ .select('id')+ .single();+ if (error) throw new Error(`Could not write the activity log: ${error.message}`);+ return (data as { id: string }).id;+}++/**+ * A call the precedence refused (§4c, §10a): the shape access-log.ts's+ * accessDeniedEvent builds, so recordAccessDenied writes its row with+ * `recordActivity(accessDeniedEvent(ctx, denial))`. No approval, target or+ * Undo: nothing ran. brandId is null for a brand out of the person's scope.+ */+export interface AccessDeniedActivity {+ kind: 'access.denied';+ userId: string;+ organizationId: string;+ brandId: string | null;+ /** The row's label key, never the tool's name. */+ toolKey: string;+ toolClass: ToolClass;+ surface: ChatSurface;+ /** The denial's code (precedence.ts ToolDenial). */+ reason: ToolDenial['code'];+ /** The rest of the denial: { role, roles }, { needs }, { group }, or nothing. */+ detail: Record<string, unknown>;+ conversationId: string | null;+ runId: string | null;+}++/** Any row: a change or an Undo (logActivity's entry), or a denial. */+export type ActivityRecord = ({ kind: 'change' } & ActivityEntry) | AccessDeniedActivity;++const toolT = createTranslator({ locale: 'en', messages, namespace: 'chatTools' });++/** A tool's name in Settings' words, by label key; '' for a key with no words. */+function toolName(key: string): string {+ return Object.hasOwn(messages.chatTools, key)+ ? toolT(`${key as keyof (typeof messages)['chatTools']}.name`)+ : '';+}++/** Writes one row of any kind and returns its id. */+export async function recordActivity(record: ActivityRecord): Promise<string> {+ if (record.kind === 'change') return logActivity(record);+ const { data, error } = await supabaseAdmin+ .from('chat_activity_log')+ .insert({+ organization_id: record.organizationId,+ user_id: record.userId,+ brand_id: record.brandId,+ conversation_id: record.conversationId,+ run_id: record.runId,+ surface: record.surface,+ kind: 'access.denied',+ tool_key: record.toolKey,+ class: record.toolClass,+ denial_code: record.reason,+ denial_json: JSON.parse(JSON.stringify(record.detail ?? {})) as Json,+ summary_key: 'accessDenied',+ summary_params: { tool: toolName(record.toolKey) },+ })+ .select('id')+ .single();+ if (error) throw new Error(`Could not write the activity log: ${error.message}`);+ return (data as { id: string }).id;+}++const summaryT = createTranslator({ locale: 'en', messages, namespace: 'chatActivity.summary' });++type SummaryKey = keyof (typeof messages)['chatActivity']['summary'];++/** Whether chatActivity.summary has this key. */+export function isSummaryKey(key: string): key is SummaryKey {+ return Object.hasOwn(messages.chatActivity.summary, key);+}++/** A row's summary in words: "Saved the draft “Pricing FAQ”". */+export function activitySummary(key: string, params: Record<string, string>): string {+ return isSummaryKey(key) ? summaryT(key, params) : '';+}++/** A value for a summary: the text, on one line, at most 120 characters. */+export function summaryValue(value: unknown): string {+ const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';+ return text.length > 120 ? `${text.slice(0, 119)}…` : text;+}diff --git a/web/src/lib/chat/idempotency.test.ts b/web/src/lib/chat/idempotency.test.tsnew file mode 100644index 000000000..a713a7778--- /dev/null+++ b/web/src/lib/chat/idempotency.test.ts@@ -0,0 +1,228 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { FakeSupabase } from './testing/fake-supabase';++/**+ * One change per key for 24 hours (CHAT-20 §11b, §11c): a repeat gets the+ * first result, two calls at once make one change, a failure gives the key+ * back, and the same key with another request is a mismatch.+ */++vi.mock('@/lib/supabase/admin', async () => ({+ supabaseAdmin: (await import('@/lib/chat/testing/fake-supabase')).createFakeSupabase(),+}));++const { supabaseAdmin } = await import('@/lib/supabase/admin');+const db = supabaseAdmin as unknown as FakeSupabase;+const {+ IDEMPOTENCY_TTL_MS,+ STALE_CLAIM_MS,+ canonicalJson,+ idempotencyKey,+ requestHash,+ sweepExpiredKeys,+ withIdempotencyKey,+} = await import('./idempotency');++const ORG = '11111111-1111-4111-8111-111111111111';+const STEP = '33333333-3333-4333-8333-333333333333';+const req = {+ organizationId: ORG,+ key: idempotencyKey('saveDraft', [STEP]),+ requestHash: requestHash('saveDraft', { title: 'Pricing FAQ' }),+};+const noWait = { sleep: async () => {}, waitMs: 0 };++beforeEach(() => {+ db.tables = { chat_idempotency_keys: [] };+ db.unique = { chat_idempotency_keys: [['organization_id', 'key']] };+ db.defaults = { chat_idempotency_keys: () => ({ created_at: new Date().toISOString() }) };+ db.failures = {};+});++describe('keys', () => {+ it('names a key by its scope and hashes the approval, in the shape 00402 checks', () => {+ expect(req.key).toMatch(/^saveDraft:[0-9a-f]{64}$/);+ expect(idempotencyKey('saveDraft', [STEP])).toBe(req.key);+ expect(idempotencyKey('saveDraft', ['another-step'])).not.toBe(req.key);+ expect(idempotencyKey('undo', [STEP])).not.toBe(req.key);+ expect(() => idempotencyKey('save_draft', [STEP])).toThrow();+ expect(() => idempotencyKey('saveDraft', [])).toThrow();+ expect(() => idempotencyKey('saveDraft', [''])).toThrow();+ });++ it('hashes a request the same whatever the order of its fields', () => {+ expect(canonicalJson({ b: 1, a: { d: 2, c: [3, { f: 1, e: 0 }] } })).toBe(+ '{"a":{"c":[3,{"e":0,"f":1}],"d":2},"b":1}',+ );+ expect(requestHash('saveDraft', { a: 1, b: 2 })).toBe(requestHash('saveDraft', { b: 2, a: 1 }));+ expect(requestHash('saveDraft', { a: 1 })).not.toBe(requestHash('opportunityStatus', { a: 1 }));+ expect(requestHash('saveDraft', { a: 1 })).not.toBe(requestHash('saveDraft', { a: 2 }));+ });+});++describe('withIdempotencyKey', () => {+ it('runs once and keeps the result for 24 hours; a repeat gets it back', async () => {+ const work = vi.fn(async () => ({ result: { draft: 'd1' }, activityId: 'a1' }));+ const first = await withIdempotencyKey(req, work);+ expect(first).toEqual({ kind: 'ran', result: { draft: 'd1' }, activityId: 'a1' });+ const [row] = db.tables.chat_idempotency_keys;+ expect(row).toMatchObject({ organization_id: ORG, key: req.key, status: 'done' });+ const ttl = Date.parse(row.expires_at as string) - Date.now();+ expect(ttl).toBeGreaterThan(IDEMPOTENCY_TTL_MS - 60_000);+ expect(ttl).toBeLessThanOrEqual(IDEMPOTENCY_TTL_MS);++ const again = await withIdempotencyKey(req, work);+ expect(again).toEqual({ kind: 'repeat', result: { draft: 'd1' }, activityId: 'a1' });+ expect(work).toHaveBeenCalledTimes(1);+ });++ it('makes one change for two calls at once with the same key', async () => {+ let made = 0;+ let finish!: () => void;+ const gate = new Promise<void>((resolve) => (finish = resolve));+ const work = async () => {+ made += 1;+ await gate;+ return { result: { draft: `d${made}` }, activityId: `a${made}` };+ };+ const both = Promise.all([+ withIdempotencyKey(req, work, { pollMs: 1 }),+ withIdempotencyKey(req, work, { pollMs: 1 }),+ ]);+ // Let both reach the key before the first finishes.+ await new Promise((resolve) => setTimeout(resolve, 20));+ finish();+ const [a, b] = await both;+ expect(made).toBe(1);+ expect([a.kind, b.kind].sort()).toEqual(['ran', 'repeat']);+ expect(a).toMatchObject({ result: { draft: 'd1' }, activityId: 'a1' });+ expect(b).toMatchObject({ result: { draft: 'd1' }, activityId: 'a1' });+ expect(db.tables.chat_idempotency_keys).toHaveLength(1);+ });++ it('keeps keys per workspace', async () => {+ const work = vi.fn(async () => ({ result: 1, activityId: null }));+ await withIdempotencyKey(req, work);+ await withIdempotencyKey(+ { ...req, organizationId: '99999999-9999-4999-8999-999999999999' },+ work,+ );+ expect(work).toHaveBeenCalledTimes(2);+ });++ it('answers a mismatch for the same key with another request, and never the old result', async () => {+ await withIdempotencyKey(req, async () => ({ result: 1, activityId: null }));+ const work = vi.fn(async () => ({ result: 2, activityId: null }));+ const other = { ...req, requestHash: requestHash('saveDraft', { title: 'Other' }) };+ expect(await withIdempotencyKey(other, work)).toEqual({ kind: 'mismatch' });+ expect(work).not.toHaveBeenCalled();+ });++ it('gives the key back when the change fails, so a retry runs again', async () => {+ await expect(+ withIdempotencyKey(req, async () => {+ throw new Error('server down');+ }),+ ).rejects.toThrow('server down');+ expect(db.tables.chat_idempotency_keys).toHaveLength(0);+ const retry = await withIdempotencyKey(req, async () => ({ result: 'ok', activityId: null }));+ expect(retry.kind).toBe('ran');+ });++ it('gives the key back for a result it is told not to keep', async () => {+ const out = await withIdempotencyKey(+ req,+ async () => ({ result: 'conflict', activityId: null }),+ {+ keep: (r) => r !== 'conflict',+ },+ );+ expect(out.kind).toBe('ran');+ expect(db.tables.chat_idempotency_keys).toHaveLength(0);+ });++ it('runs the waiting call itself when the first one fails meanwhile', async () => {+ let fail!: () => void;+ const gate = new Promise<void>((_resolve, reject) => (fail = () => reject(new Error('boom'))));+ const first = withIdempotencyKey(req, async () => {+ await gate;+ return { result: 0, activityId: null };+ });+ await new Promise((resolve) => setTimeout(resolve, 5));+ const second = withIdempotencyKey(req, async () => ({ result: 2, activityId: null }), {+ pollMs: 1,+ });+ await new Promise((resolve) => setTimeout(resolve, 5));+ fail();+ await expect(first).rejects.toThrow('boom');+ expect(await second).toEqual({ kind: 'ran', result: 2, activityId: null });+ });++ it('answers busy when the first call is still running after the wait', async () => {+ db.tables.chat_idempotency_keys.push({+ organization_id: ORG,+ key: req.key,+ request_hash: req.requestHash,+ status: 'pending',+ result_json: null,+ activity_id: null,+ created_at: new Date().toISOString(),+ expires_at: new Date(Date.now() + IDEMPOTENCY_TTL_MS).toISOString(),+ });+ const work = vi.fn(async () => ({ result: 1, activityId: null }));+ expect(await withIdempotencyKey(req, work, noWait)).toEqual({ kind: 'busy' });+ expect(work).not.toHaveBeenCalled();+ });++ it('takes over a claim left by a server that stopped, and a key past its 24 hours', async () => {+ const stale = {+ organization_id: ORG,+ key: req.key,+ request_hash: req.requestHash,+ status: 'pending',+ result_json: null,+ activity_id: null,+ created_at: new Date(Date.now() - STALE_CLAIM_MS - 1000).toISOString(),+ expires_at: new Date(Date.now() + IDEMPOTENCY_TTL_MS).toISOString(),+ };+ db.tables.chat_idempotency_keys.push(stale);+ const work = vi.fn(async () => ({ result: 1, activityId: null }));+ expect((await withIdempotencyKey(req, work, noWait)).kind).toBe('ran');++ db.tables.chat_idempotency_keys = [+ {+ ...stale,+ status: 'done',+ result_json: 0,+ created_at: new Date(Date.now() - IDEMPOTENCY_TTL_MS - 1000).toISOString(),+ expires_at: new Date(Date.now() - 1000).toISOString(),+ },+ ];+ expect(await withIdempotencyKey(req, work, noWait)).toMatchObject({ kind: 'ran', result: 1 });+ expect(work).toHaveBeenCalledTimes(2);+ });++ it("doesn't make the change twice when its result can't be kept", async () => {+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const work = vi.fn(async () => {+ db.failures.chat_idempotency_keys = { message: 'write failed' };+ return { result: 1, activityId: null };+ });+ expect((await withIdempotencyKey(req, work)).kind).toBe('ran');+ expect(errors).toHaveBeenCalled();+ errors.mockRestore();+ });++ it('sweeps only the workspace’s expired keys', async () => {+ const past = new Date(Date.now() - 1000).toISOString();+ const future = new Date(Date.now() + 1000).toISOString();+ db.tables.chat_idempotency_keys = [+ { organization_id: ORG, key: 'a', expires_at: past },+ { organization_id: ORG, key: 'b', expires_at: future },+ { organization_id: 'other', key: 'c', expires_at: past },+ ];+ await sweepExpiredKeys(ORG);+ expect(db.tables.chat_idempotency_keys.map((row) => row.key)).toEqual(['b', 'c']);+ });+});diff --git a/web/src/lib/chat/idempotency.ts b/web/src/lib/chat/idempotency.tsnew file mode 100644index 000000000..25e4f2b86--- /dev/null+++ b/web/src/lib/chat/idempotency.ts@@ -0,0 +1,227 @@+import { createHash } from 'node:crypto';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { Json } from '@/types/supabase';++/**+ * A change Chat makes runs once per key (CHAT-20 §11c): a double-clicked+ * approval, a reconnect or a retry (§11b) gets the first call's result back+ * and makes nothing new. Keys live 24 hours per workspace in+ * chat_idempotency_keys (00402), written with the service role. Server only.+ *+ * A key is claimed before the change runs (the table's primary key lets one+ * call claim it), so of two calls at once one makes the change and the other+ * waits for its result. A call that fails gives its key back: nothing was+ * made, and a retry with the key runs again. A claim left by a server that+ * stopped mid-change is taken over after STALE_CLAIM_MS.+ *+ * Chat's key is the approval's: its tool's label key and the run step that+ * asks for the change (the card the person clicks, or the step that ran it+ * without one), so one approval makes one change. What the key was claimed+ * for is kept too (requestHash: the tool and its input), and the same key+ * with another request is an approval mismatch (§11a), never the old result.+ */++export const IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1000;+/** A claim this old whose change never finished is taken over. */+export const STALE_CLAIM_MS = 5 * 60 * 1000;+/** How long a repeat waits for the first call to finish, and how often it looks. */+const WAIT_MS = 15_000;+const POLL_MS = 250;+/** Claims tried before giving up, when keys keep expiring or freeing meanwhile. */+const CLAIM_ATTEMPTS = 3;++const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');++/** JSON with object keys sorted at every level, so equal values write equal text. */+export function canonicalJson(value: unknown): string {+ return JSON.stringify(value, (_key, inner: unknown) =>+ inner && typeof inner === 'object' && !Array.isArray(inner)+ ? Object.fromEntries(+ Object.entries(inner as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : 1)),+ )+ : inner,+ );+}++/**+ * A key: what it is for (a tool's label key, or `undo`) and the parts that+ * make it one approval (the run step), hashed: `saveDraft:{sha-256}`.+ */+export function idempotencyKey(scope: string, parts: readonly string[]): string {+ if (!/^[a-z][A-Za-z0-9]{1,63}$/.test(scope)) throw new Error(`Not a key scope: ${scope}`);+ if (parts.length === 0 || parts.some((part) => part === '')) {+ throw new Error('A key needs the approval it is for');+ }+ return `${scope}:${sha256(JSON.stringify(parts))}`;+}++/** What a key is claimed for: the tool, by label key, and its input. */+export function requestHash(toolKey: string, input: unknown): string {+ return sha256(canonicalJson([toolKey, input ?? null]));+}++export interface IdempotentRequest {+ organizationId: string;+ key: string;+ requestHash: string;+}++/** What the change returns: its result (kept as JSON) and the log row it wrote. */+export interface IdempotentWork<T extends Json> {+ result: T;+ activityId: string | null;+}++export type IdempotentOutcome<T extends Json> =+ /** This call made the change. */+ | ({ kind: 'ran' } & IdempotentWork<T>)+ /** A call before it with the key did: its result, nothing new made. */+ | ({ kind: 'repeat' } & IdempotentWork<T>)+ /** The key was claimed for another request: approval_mismatch (§11a). */+ | { kind: 'mismatch' }+ /** The first call is still running after the wait. */+ | { kind: 'busy' };++export interface IdempotencyOptions<T extends Json> {+ /** Keep this result for repeats; otherwise the key goes back, as after a failure. Default: keep. */+ keep?: (result: T) => boolean;+ waitMs?: number;+ pollMs?: number;+ sleep?: (ms: number) => Promise<void>;+}++interface KeyRow {+ request_hash: string;+ status: string;+ result_json: Json | null;+ activity_id: string | null;+ created_at: string;+ expires_at: string;+}++const KEY_COLUMNS = 'request_hash, status, result_json, activity_id, created_at, expires_at';++const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));++function keys() {+ return supabaseAdmin.from('chat_idempotency_keys');+}++async function readKey(req: IdempotentRequest): Promise<KeyRow | null> {+ const { data, error } = await keys()+ .select(KEY_COLUMNS)+ .eq('organization_id', req.organizationId)+ .eq('key', req.key)+ .maybeSingle();+ if (error) throw new Error(`Could not read an idempotency key: ${error.message}`);+ return data as KeyRow | null;+}++/** A key past its 24 hours, or a claim whose change stopped: free to take. */+function isFree(row: KeyRow, now: number): boolean {+ return (+ Date.parse(row.expires_at) <= now ||+ (row.status === 'pending' && Date.parse(row.created_at) <= now - STALE_CLAIM_MS)+ );+}++/** Claims the key, or returns the row that holds it. */+async function claim(req: IdempotentRequest): Promise<'claimed' | KeyRow> {+ for (let attempt = 0; attempt < CLAIM_ATTEMPTS; attempt++) {+ const { error } = await keys().insert({+ organization_id: req.organizationId,+ key: req.key,+ request_hash: req.requestHash,+ status: 'pending',+ expires_at: new Date(Date.now() + IDEMPOTENCY_TTL_MS).toISOString(),+ });+ if (!error) return 'claimed';+ if (error.code !== '23505')+ throw new Error(`Could not claim an idempotency key: ${error.message}`);+ const row = await readKey(req);+ if (!row) continue; // Given back meanwhile: claim again.+ if (!isFree(row, Date.now())) return row;+ // Only the row that was read: another call may have taken it over already.+ const { error: freeError } = await keys()+ .delete()+ .eq('organization_id', req.organizationId)+ .eq('key', req.key)+ .eq('created_at', row.created_at);+ if (freeError) throw new Error(`Could not free an idempotency key: ${freeError.message}`);+ }+ throw new Error('Could not claim an idempotency key');+}++/** Gives a claimed key back: its change failed, or made nothing to keep. */+async function release(req: IdempotentRequest): Promise<void> {+ const { error } = await keys()+ .delete()+ .eq('organization_id', req.organizationId)+ .eq('key', req.key)+ .eq('status', 'pending');+ if (error) console.error('Could not give an idempotency key back:', error.message);+}++function settled<T extends Json>(row: KeyRow): IdempotentOutcome<T> {+ return { kind: 'repeat', result: row.result_json as T, activityId: row.activity_id };+}++/**+ * Runs `work` once for the key. A repeat gets the first result; a call made+ * while the first still runs waits for it (up to WAIT_MS), and runs itself+ * if the first failed and gave the key back.+ */+export async function withIdempotencyKey<T extends Json>(+ req: IdempotentRequest,+ work: () => Promise<IdempotentWork<T>>,+ options: IdempotencyOptions<T> = {},+): Promise<IdempotentOutcome<T>> {+ const { keep = () => true, waitMs = WAIT_MS, pollMs = POLL_MS, sleep = wait } = options;+ const deadline = Date.now() + waitMs;++ for (;;) {+ const held = await claim(req);+ if (held === 'claimed') break;+ if (held.request_hash !== req.requestHash) return { kind: 'mismatch' };+ if (held.status === 'done') return settled(held);+ // The first call is still running: wait for its result.+ let row: KeyRow | null = held;+ while (row?.status === 'pending' && Date.now() < deadline && !isFree(row, Date.now())) {+ await sleep(pollMs);+ row = await readKey(req);+ }+ if (row?.status === 'done') {+ return row.request_hash === req.requestHash ? settled(row) : { kind: 'mismatch' };+ }+ if (row && !isFree(row, Date.now())) return { kind: 'busy' };+ // Given back or stale: claim it for this call.+ }++ let done: IdempotentWork<T>;+ try {+ done = await work();+ } catch (err) {+ await release(req);+ throw err;+ }+ if (!keep(done.result)) {+ await release(req);+ return { kind: 'ran', ...done };+ }+ const { error } = await keys()+ .update({ status: 'done', result_json: done.result, activity_id: done.activityId })+ .eq('organization_id', req.organizationId)+ .eq('key', req.key);+ // The change is made: a key that can't be closed is logged, never a second change.+ if (error) console.error('Could not keep an idempotency key’s result:', error.message);+ return { kind: 'ran', ...done };+}++/** Removes the workspace's keys past their 24 hours. */+export async function sweepExpiredKeys(organizationId: string): Promise<void> {+ const { error } = await keys()+ .delete()+ .eq('organization_id', organizationId)+ .lt('expires_at', new Date().toISOString());+ if (error) console.error('Could not sweep idempotency keys:', error.message);+}diff --git a/web/src/lib/chat/testing/chat-fixtures.ts b/web/src/lib/chat/testing/chat-fixtures.tsnew file mode 100644index 000000000..9be266847--- /dev/null+++ b/web/src/lib/chat/testing/chat-fixtures.ts@@ -0,0 +1,121 @@+import { fakeId, type FakeSupabase } from './fake-supabase';++/**+ * A workspace for the activity log, Undo and idempotency tests: two+ * organizations, people in each role, a brand, an opportunity and a prompt+ * suggestion, and stand-ins for the server actions Chat's WRITE rows call,+ * writing to the same tables. Tests only.+ */++export const ORG = '11111111-1111-4111-8111-111111111111';+export const OTHER_ORG = '99999999-9999-4999-8999-999999999999';+export const BRAND = '22222222-2222-4222-8222-222222222222';+export const OPPORTUNITY = '44444444-4444-4444-8444-444444444444';+export const SUGGESTION = '55555555-5555-4555-8555-555555555555';++export const PEOPLE = {+ admin: 'aaaaaaaa-0000-4000-8000-000000000001',+ manager: 'aaaaaaaa-0000-4000-8000-000000000002',+ analyst: 'aaaaaaaa-0000-4000-8000-000000000003',+ otherManager: 'aaaaaaaa-0000-4000-8000-000000000004',+} as const;++const iso = () => new Date().toISOString();++export function seedWorkspace(db: FakeSupabase): void {+ db.failures = {};+ db.log = [];+ db.unique = { chat_idempotency_keys: [['organization_id', 'key']] };+ db.defaults = {+ chat_activity_log: () => ({+ status: 'done',+ undone_at: null,+ undone_by: null,+ undoes_id: null,+ created_at: iso(),+ }),+ chat_idempotency_keys: () => ({ created_at: iso() }),+ };+ db.tables = {+ profiles: [+ { id: PEOPLE.admin, role: 'admin', organization_id: ORG },+ { id: PEOPLE.manager, role: 'manager', organization_id: ORG },+ { id: PEOPLE.analyst, role: 'analyst', organization_id: ORG },+ { id: PEOPLE.otherManager, role: 'manager', organization_id: ORG },+ ],+ organizations: [+ { id: ORG, plan: 'growth', subscription_status: 'active', plan_overrides: null },+ { id: OTHER_ORG, plan: 'growth', subscription_status: 'active', plan_overrides: null },+ ],+ brands: [{ id: BRAND, organization_id: ORG }],+ chat_settings: [],+ chat_auto_choices: [],+ chat_activity_log: [],+ chat_idempotency_keys: [],+ content_drafts: [],+ content_opportunities: [+ {+ id: OPPORTUNITY,+ brand_id: BRAND,+ title: 'Pricing page for teams',+ status: 'new',+ source_data: { volume: 1200 },+ updated_at: '2026-10-28T10:00:00.000Z',+ },+ ],+ prompt_suggestions: [+ {+ id: SUGGESTION,+ brand_id: BRAND,+ suggested_text: 'best crm for startups',+ status: 'new',+ updated_at: '2026-10-28T10:00:00.000Z',+ },+ ],+ };+}++const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/** createContentDraft: a new draft row, after a moment, as the real one takes. */+export function fakeCreateDraft(db: FakeSupabase) {+ return async (brandId: string, start: { title: string }) => {+ await sleep(5);+ const id = fakeId();+ db.tables.content_drafts.push({+ id,+ brand_id: brandId,+ title: start.title,+ body_html: `<h1>${start.title}</h1>`,+ status: 'draft',+ archived_at: null,+ updated_at: iso(),+ });+ return id;+ };+}++/** updateOpportunityStatus: the server's PATCH, reason in source_data. */+export function fakeUpdateOpportunity(db: FakeSupabase) {+ return async (id: string, status: string, reason?: string) => {+ const row = db.tables.content_opportunities.find((r) => r.id === id);+ if (!row) throw new Error('Opportunity not found');+ const rest = { ...(row.source_data as Record<string, unknown>) };+ delete rest.dismissReason;+ row.status = status;+ row.source_data = status === 'dismissed' && reason ? { ...rest, dismissReason: reason } : rest;+ row.updated_at = iso();+ return { ...row };+ };+}++/** dismissSuggestion: the server's POST …/dismiss. */+export function fakeDismissSuggestion(db: FakeSupabase) {+ return async (id: string) => {+ const row = db.tables.prompt_suggestions.find((r) => r.id === id);+ if (!row) throw new Error('Not found');+ row.status = 'dismissed';+ row.updated_at = iso();+ return { success: true };+ };+}diff --git a/web/src/lib/chat/testing/fake-supabase.ts b/web/src/lib/chat/testing/fake-supabase.tsnew file mode 100644index 000000000..d6c1a8c1e--- /dev/null+++ b/web/src/lib/chat/testing/fake-supabase.ts@@ -0,0 +1,164 @@+/**+ * An in-memory stand-in for the service-role Supabase client, for Chat's+ * tests: tables of plain rows, the filters and statements the activity log,+ * Undo and the idempotency keys use, and unique keys that refuse a second+ * row as Postgres does (23505). Each statement runs whole at once, after a+ * turn of the event loop, so two calls started together interleave between+ * statements as two requests would. Tests only.+ */++type Row = Record<string, unknown>;+type Filter = (row: Row) => boolean;+type Result = { data: unknown; error: { code?: string; message: string } | null };++export interface FakeSupabase {+ tables: Record<string, Row[]>;+ /** Columns that are unique together, per table. */+ unique: Record<string, string[][]>;+ /** Defaults a new row gets, per table, computed at insert. */+ defaults: Record<string, () => Row>;+ /** A table whose next statements fail with this error. */+ failures: Record<string, { code?: string; message: string }>;+ /** Every statement, in order: [table, kind]. */+ log: [string, string][];+ from(table: string): Builder;+}++interface Builder extends PromiseLike<Result> {+ select(columns?: string): Builder;+ insert(rows: Row | Row[]): Builder;+ update(patch: Row): Builder;+ delete(): Builder;+ eq(column: string, value: unknown): Builder;+ neq(column: string, value: unknown): Builder;+ in(column: string, values: unknown[]): Builder;+ is(column: string, value: null): Builder;+ lt(column: string, value: string): Builder;+ maybeSingle(): Promise<Result>;+ single(): Promise<Result>;+}++let counter = 0;+/** A fresh uuid-shaped id. */+export const fakeId = () => {+ counter += 1;+ return `00000000-0000-4000-8000-${String(counter).padStart(12, '0')}`;+};++const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++export function createFakeSupabase(): FakeSupabase {+ const fake: FakeSupabase = {+ tables: {},+ unique: {},+ defaults: {},+ failures: {},+ log: [],+ from(table) {+ let kind: 'select' | 'insert' | 'update' | 'delete' = 'select';+ let payload: Row | Row[] | null = null;+ let returning = false;+ const filters: Filter[] = [];++ const rows = () => (fake.tables[table] ??= []);+ const clash = (row: Row, others: Row[]) =>+ (fake.unique[table] ?? []).some((columns) =>+ others.some((other) => other !== row && columns.every((c) => other[c] === row[c])),+ );++ const run = async (): Promise<Result> => {+ await tick();+ fake.log.push([table, kind]);+ const failure = fake.failures[table];+ if (failure) return { data: null, error: failure };+ const matching = rows().filter((row) => filters.every((f) => f(row)));+ if (kind === 'select') return { data: matching.map((row) => ({ ...row })), error: null };+ if (kind === 'delete') {+ fake.tables[table] = rows().filter((row) => !matching.includes(row));+ return { data: returning ? matching : null, error: null };+ }+ if (kind === 'update') {+ const patched = matching.map((row) => ({ ...row, ...(payload as Row) }));+ const after = rows().map((row) => patched[matching.indexOf(row)] ?? row);+ if (patched.some((row) => clash(row, after))) {+ return { data: null, error: { code: '23505', message: 'duplicate key' } };+ }+ fake.tables[table] = after;+ return { data: returning ? patched.map((row) => ({ ...row })) : null, error: null };+ }+ const added = (Array.isArray(payload) ? payload : [payload!]).map((row) => ({+ id: fakeId(),+ ...(fake.defaults[table]?.() ?? {}),+ ...row,+ }));+ const after = [...rows(), ...added];+ if (added.some((row) => clash(row, after))) {+ return { data: null, error: { code: '23505', message: 'duplicate key' } };+ }+ fake.tables[table] = after;+ return { data: returning ? added.map((row) => ({ ...row })) : null, error: null };+ };++ const one = async (strict: boolean): Promise<Result> => {+ const result = await run();+ if (result.error) return result;+ const list = (result.data as Row[] | null) ?? [];+ if (list.length > 1) return { data: null, error: { message: 'more than one row' } };+ if (strict && list.length === 0) return { data: null, error: { message: 'no rows' } };+ return { data: list[0] ?? null, error: null };+ };++ const builder: Builder = {+ select() {+ if (kind !== 'select') returning = true;+ return builder;+ },+ insert(rowsIn) {+ kind = 'insert';+ payload = rowsIn;+ return builder;+ },+ update(patch) {+ kind = 'update';+ payload = patch;+ return builder;+ },+ delete() {+ kind = 'delete';+ return builder;+ },+ eq(column, value) {+ filters.push((row) => row[column] === value);+ return builder;+ },+ neq(column, value) {+ filters.push((row) => row[column] !== value);+ return builder;+ },+ in(column, values) {+ filters.push((row) => values.includes(row[column]));+ return builder;+ },+ is(column, value) {+ filters.push((row) => (row[column] ?? null) === value);+ return builder;+ },+ lt(column, value) {+ filters.push(+ (row) =>+ typeof row[column] === 'string' &&+ Date.parse(row[column] as string) < Date.parse(value),+ );+ return builder;+ },+ maybeSingle: () => one(false),+ single: () => one(true),+ then(resolve, reject) {+ return run().then(resolve, reject);+ },+ };+ return builder;+ },+ };+ return fake;+}diff --git a/web/src/lib/chat/undo.test.ts b/web/src/lib/chat/undo.test.tsnew file mode 100644index 000000000..866417f73--- /dev/null+++ b/web/src/lib/chat/undo.test.ts@@ -0,0 +1,422 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import type { FakeSupabase } from './testing/fake-supabase';+import {+ BRAND,+ OPPORTUNITY,+ ORG,+ OTHER_ORG,+ PEOPLE,+ SUGGESTION,+ fakeCreateDraft,+ fakeDismissSuggestion,+ fakeUpdateOpportunity,+ seedWorkspace,+} from './testing/chat-fixtures';++/**+ * Undo (CHAT-20 §10b, §21 "Undo restores the before state or explains the+ * conflict"): each WRITE row's inverse within its §9 window, for the person+ * Chat acted as and Admins, through the same precedence as the tool, with+ * nothing overwritten when the target changed since.+ */++vi.mock('@/lib/supabase/admin', async () => ({+ supabaseAdmin: (await import('@/lib/chat/testing/fake-supabase')).createFakeSupabase(),+}));+vi.mock('@/lib/actions/content-drafts', () => ({ createContentDraft: vi.fn() }));+vi.mock('@/lib/actions/content', () => ({ updateOpportunityStatus: vi.fn() }));+vi.mock('@/lib/actions/prompt-suggestions', () => ({ dismissSuggestion: vi.fn() }));++const { supabaseAdmin } = await import('@/lib/supabase/admin');+const db = supabaseAdmin as unknown as FakeSupabase;+const { createContentDraft } = await import('@/lib/actions/content-drafts');+const { updateOpportunityStatus } = await import('@/lib/actions/content');+const { dismissSuggestion } = await import('@/lib/actions/prompt-suggestions');+const { runLoggedWrite } = await import('./write');+const { undoChange, undoRule, UNDO_RULES } = await import('./undo');+const { chatTool, CHAT_TOOLS } = await import('./registry/tools');++const DAY = 24 * 60 * 60 * 1000;+let step = 0;++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ seedWorkspace(db);+ vi.mocked(createContentDraft).mockImplementation(fakeCreateDraft(db) as never);+ vi.mocked(updateOpportunityStatus).mockImplementation(fakeUpdateOpportunity(db) as never);+ vi.mocked(dismissSuggestion).mockImplementation(fakeDismissSuggestion(db) as never);+});+afterEach(() => vi.unstubAllEnvs());++/** A change Chat made for this person in Full auto; returns its log row. */+async function change(userId: string, name: string, input: unknown) {+ const outcome = await runLoggedWrite({+ tool: chatTool(name)!,+ input,+ ctx: {} as never,+ organizationId: ORG,+ userId,+ brandId: BRAND,+ surface: 'chat',+ mode: 'full_auto',+ approval: { kind: 'auto', via: 'full_auto' },+ place: { conversationId: null, runId: null, stepId: null },+ approvalKey: `step-${++step}`,+ });+ if (outcome.code !== 'ok' || !outcome.activityId) throw new Error('no change');+ return db.tables.chat_activity_log.find((row) => row.id === outcome.activityId)!;+}++const saveDraft = (userId: string = PEOPLE.manager) =>+ change(userId, 'create_draft', {+ brand_id: BRAND,+ title: 'Pricing FAQ',+ page_type: 'docs_faq',+ method: 'create',+ source: { kind: 'content' },+ });+const dismissOpportunity = (userId: string = PEOPLE.manager) =>+ change(userId, 'update_opportunity', {+ opportunity_id: OPPORTUNITY,+ status: 'dismissed',+ reason: 'wrong_angle',+ });+const dismissPromptSuggestion = (userId: string = PEOPLE.manager) =>+ change(userId, 'dismiss_prompt_suggestion', { suggestion_id: SUGGESTION });++const undo = (activityId: unknown, userId: string = PEOPLE.manager, organizationId: string = ORG) =>+ undoChange({ activityId: activityId as string, userId, organizationId, surface: 'chat' });++const draft = () => db.tables.content_drafts[0];+const opportunity = () => db.tables.content_opportunities[0];+const suggestion = () => db.tables.prompt_suggestions[0];+const logRow = (id: unknown) => db.tables.chat_activity_log.find((row) => row.id === id)!;++describe('every WRITE row has an Undo', () => {+ it('with its §9 window, and words for the change and its Undo', () => {+ const writes = CHAT_TOOLS.filter((tool) => tool.class === 'write');+ expect(writes.map((tool) => tool.name).sort()).toEqual(Object.keys(UNDO_RULES).sort());+ expect(UNDO_RULES.create_draft.windowMs).toBe(30 * DAY);+ expect(UNDO_RULES.update_opportunity.windowMs).toBe(7 * DAY);+ expect(UNDO_RULES.dismiss_prompt_suggestion.windowMs).toBe(7 * DAY);+ for (const tool of writes) {+ expect(undoRule(tool)).not.toBeNull();+ expect(messages.chatActivity.summary).toHaveProperty(tool.labelKey);+ expect(messages.chatActivity.summary).toHaveProperty(`${tool.labelKey}Undo`);+ }+ expect(undoRule(CHAT_TOOLS.find((tool) => tool.class === 'read')!)).toBeNull();+ });+});++describe('create_draft: archive the draft it saved', () => {+ it('archives it, marks the change undone and logs the Undo as the person’s own action', async () => {+ const row = await saveDraft();+ const result = await undo(row.id);+ expect(result).toMatchObject({ code: 'ok', message: 'Undone.' });+ expect(draft().archived_at).toEqual(expect.any(String));+ expect(logRow(row.id)).toMatchObject({ status: 'undone', undone_by: PEOPLE.manager });+ expect(logRow(row.id).undone_at).toEqual(expect.any(String));+ const undoRow = logRow(result.code === 'ok' && result.activityId);+ expect(undoRow).toMatchObject({+ undoes_id: row.id,+ tool_key: 'saveDraft',+ approval_kind: 'run',+ auto_via: null,+ mode: null,+ summary_key: 'saveDraftUndo',+ summary_params: { title: 'Pricing FAQ' },+ undo_json: null,+ undo_until: null,+ target_type: 'content_draft',+ target_id: draft().id,+ });+ // An Undo isn't undone in turn, and the change only once.+ expect(await undo(undoRow.id)).toMatchObject({ code: 'not_undoable' });+ expect(await undo(row.id)).toMatchObject({+ code: 'already_undone',+ message: 'This was already undone.',+ });+ });++ it('explains the conflict when the person changed the draft since, and overwrites nothing', async () => {+ const row = await saveDraft();+ draft().body_html = '<h1>Pricing FAQ</h1><p>My own words.</p>';+ draft().updated_at = new Date(Date.now() + 1000).toISOString();+ const result = await undo(row.id);+ expect(result).toEqual({+ code: 'conflict',+ reason: 'changed',+ href: `/dashboard/content/editor/${draft().id}`,+ message: 'This changed since. Open it to undo by hand.',+ });+ expect(draft().archived_at).toBeNull();+ expect(logRow(row.id).status).toBe('undo_conflict');+ expect(db.tables.chat_activity_log).toHaveLength(1);++ // Back as Chat left it: Undo may try again.+ draft().body_html = '<h1>Pricing FAQ</h1>';+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ expect(logRow(row.id).status).toBe('undone');+ });++ it.each([+ ['renamed', (d: Record<string, unknown>) => (d.title = 'Pricing questions')],+ ['marked ready', (d: Record<string, unknown>) => (d.status = 'ready')],+ [+ 'archived by someone',+ (d: Record<string, unknown>) => (d.archived_at = new Date().toISOString()),+ ],+ ])('a draft %s since is a conflict', async (_what, edit) => {+ const row = await saveDraft();+ edit(draft());+ expect(await undo(row.id)).toMatchObject({ code: 'conflict', reason: 'changed' });+ });++ it('a draft deleted since: nothing to undo, no link', async () => {+ const row = await saveDraft();+ db.tables.content_drafts = [];+ expect(await undo(row.id)).toEqual({+ code: 'conflict',+ reason: 'gone',+ href: null,+ message: "This was deleted since, so there's nothing to undo.",+ });+ });++ it('a draft written between the check and the archive is a conflict, not overwritten', async () => {+ const row = await saveDraft();+ const realFrom = db.from.bind(db);+ db.from = (table: string) => {+ const builder = realFrom(table);+ if (table !== 'content_drafts') return builder;+ const update = builder.update.bind(builder);+ // Someone saves the draft just before the archive's write.+ builder.update = (patch: Record<string, unknown>) => {+ draft().updated_at = new Date(Date.now() + 5000).toISOString();+ return update(patch);+ };+ return builder;+ };+ try {+ expect(await undo(row.id)).toMatchObject({ code: 'conflict', reason: 'changed' });+ } finally {+ db.from = realFrom;+ }+ expect(draft().archived_at).toBeNull();+ });++ it('an Analyst undoes the draft their own run saved, though the Library leaves archiving to Managers', async () => {+ const row = await saveDraft(PEOPLE.analyst);+ expect(await undo(row.id, PEOPLE.analyst)).toMatchObject({ code: 'ok' });+ expect(draft().archived_at).toEqual(expect.any(String));+ });+});++describe('update_opportunity: its status and reason before', () => {+ it('puts back the status and drops the dismiss reason, keeping the rest of source_data', async () => {+ const row = await dismissOpportunity();+ expect(opportunity()).toMatchObject({+ status: 'dismissed',+ source_data: { volume: 1200, dismissReason: 'wrong_angle' },+ });+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ expect(opportunity()).toMatchObject({ status: 'new', source_data: { volume: 1200 } });+ expect(opportunity().source_data).not.toHaveProperty('dismissReason');+ });++ it('puts back an earlier dismiss reason', async () => {+ Object.assign(opportunity(), {+ status: 'dismissed',+ source_data: { volume: 1200, dismissReason: 'not_relevant' },+ });+ const row = await change(PEOPLE.manager, 'update_opportunity', {+ opportunity_id: OPPORTUNITY,+ status: 'reviewed',+ });+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ expect(opportunity()).toMatchObject({+ status: 'dismissed',+ source_data: { volume: 1200, dismissReason: 'not_relevant' },+ });+ });++ it('is a conflict once someone set it again', async () => {+ const row = await dismissOpportunity();+ Object.assign(opportunity(), { status: 'in_progress', source_data: { volume: 1200 } });+ expect(await undo(row.id)).toMatchObject({+ code: 'conflict',+ reason: 'changed',+ href: `/dashboard/content/${OPPORTUNITY}`,+ });+ expect(opportunity().status).toBe('in_progress');+ });++ it('has no Undo when it changed nothing', async () => {+ Object.assign(opportunity(), { status: 'reviewed' });+ const row = await change(PEOPLE.manager, 'update_opportunity', {+ opportunity_id: OPPORTUNITY,+ status: 'reviewed',+ });+ expect(row).toMatchObject({ undo_json: null, undo_until: null });+ expect(await undo(row.id)).toMatchObject({+ code: 'not_undoable',+ message: "This change can't be undone here.",+ });+ });+});++describe('dismiss_prompt_suggestion: bring it back', () => {+ it('brings it back as it was', async () => {+ const row = await dismissPromptSuggestion();+ expect(suggestion().status).toBe('dismissed');+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ expect(suggestion().status).toBe('new');+ });++ it('is a conflict once it was added since', async () => {+ const row = await dismissPromptSuggestion();+ suggestion().status = 'added';+ expect(await undo(row.id)).toMatchObject({+ code: 'conflict',+ reason: 'changed',+ href: '/dashboard/prompts/suggestions',+ });+ expect(suggestion().status).toBe('added');+ });++ it('has no Undo for a suggestion that was dismissed already', async () => {+ suggestion().status = 'dismissed';+ const row = await dismissPromptSuggestion();+ expect(row.undo_until).toBeNull();+ expect(await undo(row.id)).toMatchObject({ code: 'not_undoable' });+ });+});++describe('the window', () => {+ it('is closed once it ended: nothing changes', async () => {+ const row = await dismissPromptSuggestion();+ row.undo_until = new Date(Date.now() - 1000).toISOString();+ expect(await undo(row.id)).toEqual({+ code: 'expired',+ message: 'Undo is no longer available for this change. Change it by hand instead.',+ });+ expect(suggestion().status).toBe('dismissed');+ expect(row.status).toBe('done');+ });++ it('is open until it ends', async () => {+ const row = await saveDraft();+ row.undo_until = new Date(Date.now() + 60_000).toISOString();+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ });+});++describe('who may undo', () => {+ it('the person Chat acted as and Admins; anyone else finds nothing', async () => {+ const row = await dismissPromptSuggestion();+ expect(await undo(row.id, PEOPLE.otherManager)).toEqual({+ code: 'not_found',+ message: "I couldn't find that change.",+ });+ expect(await undo(row.id, PEOPLE.analyst)).toMatchObject({ code: 'not_found' });+ expect(suggestion().status).toBe('dismissed');+ expect(await undo(row.id, PEOPLE.admin)).toMatchObject({ code: 'ok' });+ expect(logRow(row.id).undone_by).toBe(PEOPLE.admin);+ });++ it('not from another workspace, nor once the person left this one', async () => {+ const row = await dismissPromptSuggestion();+ expect(await undo(row.id, PEOPLE.manager, OTHER_ORG)).toMatchObject({ code: 'not_found' });+ db.tables.profiles.find((p) => p.id === PEOPLE.manager)!.organization_id = OTHER_ORG;+ expect(await undo(row.id)).toMatchObject({ code: 'not_found' });+ expect(suggestion().status).toBe('dismissed');+ });+});++describe('Undo passes the same precedence as the tool (A3)', () => {+ it('a read-only workspace refuses it', async () => {+ const row = await dismissPromptSuggestion();+ db.tables.organizations[0].subscription_status = 'canceled';+ const result = await undo(row.id);+ expect(result).toMatchObject({+ code: 'denied',+ denial: { code: 'subscription_inactive', status: 402 },+ });+ expect(result.message).toMatch(/read-only/);+ expect(suggestion().status).toBe('dismissed');+ });++ it('the live role: a Manager made an Analyst can no longer undo an opportunity change', async () => {+ const row = await dismissOpportunity();+ db.tables.profiles.find((p) => p.id === PEOPLE.manager)!.role = 'analyst';+ expect(await undo(row.id)).toMatchObject({+ code: 'denied',+ denial: { code: 'forbidden_role' },+ });+ expect(opportunity().status).toBe('dismissed');+ });++ it("an Admin's Never on the tool", async () => {+ const row = await dismissPromptSuggestion();+ db.tables.chat_settings = [+ {+ organization_id: ORG,+ tool_policies: { dismissSuggestion: 'never' },+ full_auto_for_members: true,+ dont_ask_again: true,+ manager_execute_off: [],+ },+ ];+ expect(await undo(row.id)).toMatchObject({ code: 'denied', denial: { code: 'policy_never' } });+ });++ it('needs no card, whatever the mode: an Ask policy still undoes', async () => {+ const row = await dismissPromptSuggestion();+ db.tables.chat_settings = [+ {+ organization_id: ORG,+ tool_policies: { dismissSuggestion: 'ask' },+ full_auto_for_members: false,+ dont_ask_again: false,+ manager_execute_off: [],+ },+ ];+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ });+});++describe('failures', () => {+ it("never throws: a read that fails is 'failed', and nothing is undone", async () => {+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const row = await dismissPromptSuggestion();+ db.failures.chat_activity_log = { message: 'connection reset' };+ expect(await undo(row.id)).toEqual({+ code: 'failed',+ message: 'Something went wrong, so nothing was undone. Try again.',+ });+ delete db.failures.chat_activity_log;+ expect(suggestion().status).toBe('dismissed');+ expect(await undo(row.id)).toMatchObject({ code: 'ok' });+ errors.mockRestore();+ });++ it('the brand is found again as the tool finds it: a target moved out of the workspace is refused', async () => {+ const row = await dismissPromptSuggestion();+ suggestion().brand_id = '77777777-7777-4777-8777-777777777777';+ expect(await undo(row.id)).toMatchObject({ code: 'denied', denial: { code: 'brand_scope' } });+ expect(suggestion().status).toBe('dismissed');+ });+});++describe('a double-clicked Undo', () => {+ it('undoes once and answers both clicks the same', async () => {+ const row = await saveDraft();+ const [a, b] = await Promise.all([undo(row.id), undo(row.id)]);+ expect(a).toMatchObject({ code: 'ok' });+ expect(b).toEqual(a);+ expect(db.tables.chat_activity_log.filter((r) => r.undoes_id === row.id)).toHaveLength(1);+ });+});diff --git a/web/src/lib/chat/undo.ts b/web/src/lib/chat/undo.tsnew file mode 100644index 000000000..8fb0b770a--- /dev/null+++ b/web/src/lib/chat/undo.ts@@ -0,0 +1,555 @@+import { createHash } from 'node:crypto';+import { createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import { supabaseAdmin } from '@/lib/supabase/admin';+import type { Json } from '@/types/supabase';+import { logActivity, summaryValue, type ActivityPlace } from './activity';+import { buildDenial, type ChatDenial } from './denial';+import type { ChatHref } from './events';+import { idempotencyKey, requestHash, withIdempotencyKey } from './idempotency';+import { decideToolCall, type ChatSurface } from './precedence';+import { readPrecedenceContext, readToolCall } from './precedence-context';+import type { ChatTool } from './registry/define-tool';+import { chatToolByKey } from './registry/tools';++/**+ * Undo (CHAT-20 §10b): the inverse of each WRITE, stored when it ran (the+ * state before, and the state after that Undo checks first), offered for the+ * tool's window (§9) to the person Chat acted as and to Admins.+ *+ * Undo is a WRITE of its own: it passes the same precedence as the tool+ * (the live role, a read-only workspace, the demo brand, an Admin's Never)+ * but needs no card, since it puts back what the person's run did; it is+ * logged (approval `run`), and the change it undid turns `undone`. When the+ * target changed since (someone edited the draft, set the opportunity+ * again, added the suggestion), nothing is overwritten: the change turns+ * `undo_conflict` and the answer says "This changed since. Open it to undo+ * by hand." with a link. A second click on Undo gets the first click's+ * answer (its own idempotency key).+ *+ * The inverses write with the service role, as the server's own routes for+ * these rows do (content.js, prompts.js), after the checks above: an+ * Analyst may save a draft but not archive one in the Library, and Undo+ * still takes back the draft their own run saved. Server only.+ */++const DAY_MS = 24 * 60 * 60 * 1000;++type Snapshot = { [key: string]: Json };++/**+ * What the log row records about a change, read after it ran. Its brand is+ * the call's, as the precedence found it (resolveCallBrand).+ */+export interface WriteRecord {+ target: { type: string; id: string | null };+ /** chatActivity.summary's values. */+ summaryParams: Record<string, string>;+ /** What Undo restores and checks; null when the change changed nothing. */+ undo: Snapshot | null;+}++/** How an inverse went: done, the target changed since, or it is gone. */+export type InverseResult = 'ok' | 'changed' | 'gone';++export interface UndoRule {+ /** The target's type in the log. */+ targetType: string;+ /** CHAT-20 §9's Undo window. */+ windowMs: number;+ /** Read just before the change: the state Undo restores. */+ before(input: unknown): Promise<Snapshot | null>;+ /** Read just after it: what the row records. */+ record(input: unknown, output: unknown, before: Snapshot | null): Promise<WriteRecord>;+ /** The inverse, once the target is as the change left it. */+ inverse(target: { id: string; brandId: string | null; data: Snapshot }): Promise<InverseResult>;+ /** Where the target opens, to undo by hand. */+ href(targetId: string): ChatHref;+}++const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');++const asObject = (value: unknown): Record<string, unknown> =>+ value && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : {};++const textOf = (value: unknown): string | null => (typeof value === 'string' ? value : null);++function check(error: { message: string } | null, what: string) {+ if (error) throw new Error(`Could not read ${what} for Undo: ${error.message}`);+}++// ─── create_draft: archive the draft it saved (§9: 30 days, "move to trash") ─++const DRAFT_COLUMNS = 'id, brand_id, title, body_html, status, archived_at, updated_at';++/** What a draft looks like to a person: its title, page and status. */+function draftState(row: Record<string, unknown>): Snapshot {+ return {+ title: textOf(row.title),+ bodyHash: sha256(textOf(row.body_html) ?? ''),+ status: textOf(row.status),+ };+}++const createDraft: UndoRule = {+ targetType: 'content_draft',+ windowMs: 30 * DAY_MS,+ async before() {+ return null; // Nothing to read: the draft is new.+ },+ async record(input, output) {+ const id = textOf(output);+ const { title } = asObject(input);+ if (!id) {+ return {+ target: { type: 'content_draft', id: null },+ summaryParams: { title: summaryValue(title) },+ undo: null,+ };+ }+ const { data, error } = await supabaseAdmin+ .from('content_drafts')+ .select(DRAFT_COLUMNS)+ .eq('id', id)+ .maybeSingle();+ check(error, 'the draft');+ return {+ target: { type: 'content_draft', id },+ summaryParams: { title: summaryValue(data?.title ?? title) },+ undo: data ? { after: draftState(data) } : null,+ };+ },+ async inverse({ id, brandId, data }) {+ let read = supabaseAdmin.from('content_drafts').select(DRAFT_COLUMNS).eq('id', id);+ if (brandId) read = read.eq('brand_id', brandId);+ const { data: draft, error } = await read.maybeSingle();+ check(error, 'the draft');+ if (!draft) return 'gone';+ // Edited, renamed, moved on, or archived by someone since: theirs to decide.+ const after = asObject(data.after);+ const now = draftState(draft);+ if (+ draft.archived_at ||+ now.title !== after.title ||+ now.bodyHash !== after.bodyHash ||+ now.status !== after.status+ ) {+ return 'changed';+ }+ const { data: archived, error: archiveError } = await supabaseAdmin+ .from('content_drafts')+ .update({ archived_at: new Date().toISOString() })+ .eq('id', id)+ .eq('updated_at', draft.updated_at)+ .is('archived_at', null)+ .select('id')+ .maybeSingle();+ if (archiveError) throw new Error(`Could not archive the draft: ${archiveError.message}`);+ return archived ? 'ok' : 'changed';+ },+ href: (id) => `/dashboard/content/editor/${id}`,+};++// ─── update_opportunity: its status and dismiss reason before (§9: 7 days) ──++const OPPORTUNITY_COLUMNS = 'id, brand_id, title, status, source_data, updated_at';++function opportunityState(row: Record<string, unknown>): Snapshot {+ return {+ status: textOf(row.status),+ dismissReason: textOf(asObject(row.source_data).dismissReason),+ };+}++async function readOpportunity(id: unknown) {+ if (typeof id !== 'string') return null;+ const { data, error } = await supabaseAdmin+ .from('content_opportunities')+ .select(OPPORTUNITY_COLUMNS)+ .eq('id', id)+ .maybeSingle();+ check(error, 'the opportunity');+ return data as Record<string, unknown> | null;+}++const updateOpportunity: UndoRule = {+ targetType: 'content_opportunity',+ windowMs: 7 * DAY_MS,+ async before(input) {+ const row = await readOpportunity(asObject(input).opportunity_id);+ return row ? { ...opportunityState(row), title: textOf(row.title) } : null;+ },+ async record(input, _output, before) {+ const { opportunity_id: id, status } = asObject(input);+ const row = await readOpportunity(id);+ const after = row ? opportunityState(row) : null;+ const changed =+ before &&+ after &&+ (before.status !== after.status || before.dismissReason !== after.dismissReason);+ return {+ target: { type: 'content_opportunity', id: textOf(id) },+ summaryParams: {+ title: summaryValue(before?.title ?? row?.title),+ status: summaryValue(status),+ },+ undo: changed+ ? {+ before: { status: before.status, dismissReason: before.dismissReason },+ after,+ }+ : null,+ };+ },+ async inverse({ id, brandId, data }) {+ const before = asObject(data.before);+ const after = asObject(data.after);+ let read = supabaseAdmin.from('content_opportunities').select(OPPORTUNITY_COLUMNS).eq('id', id);+ if (brandId) read = read.eq('brand_id', brandId);+ const { data: row, error } = await read.maybeSingle();+ check(error, 'the opportunity');+ if (!row) return 'gone';+ const now = opportunityState(row);+ if (now.status !== after.status || now.dismissReason !== after.dismissReason) return 'changed';++ // The reason rides in source_data, which other writers touch too: keep theirs.+ const sourceData: Record<string, unknown> = { ...asObject(row.source_data) };+ if (typeof before.dismissReason === 'string') sourceData.dismissReason = before.dismissReason;+ else delete sourceData.dismissReason;+ let update = supabaseAdmin+ .from('content_opportunities')+ .update({+ status: before.status,+ source_data: sourceData,+ updated_at: new Date().toISOString(),+ })+ .eq('id', id)+ .eq('status', now.status as string);+ update = row.updated_at+ ? update.eq('updated_at', row.updated_at)+ : update.is('updated_at', null);+ const { data: restored, error: restoreError } = await update.select('id').maybeSingle();+ if (restoreError) throw new Error(`Could not restore the opportunity: ${restoreError.message}`);+ return restored ? 'ok' : 'changed';+ },+ href: (id) => `/dashboard/content/${id}`,+};++// ─── dismiss_prompt_suggestion: bring it back (§9: 7 days) ──────────────────++const dismissSuggestion: UndoRule = {+ targetType: 'prompt_suggestion',+ windowMs: 7 * DAY_MS,+ async before(input) {+ const id = asObject(input).suggestion_id;+ if (typeof id !== 'string') return null;+ const { data, error } = await supabaseAdmin+ .from('prompt_suggestions')+ .select('id, suggested_text, status')+ .eq('id', id)+ .maybeSingle();+ check(error, 'the suggestion');+ return data ? { status: textOf(data.status), text: textOf(data.suggested_text) } : null;+ },+ async record(input, _output, before) {+ const id = textOf(asObject(input).suggestion_id);+ return {+ target: { type: 'prompt_suggestion', id },+ summaryParams: { text: summaryValue(before?.text) },+ // Already dismissed before: nothing changed, nothing to undo.+ undo:+ before && before.status !== 'dismissed'+ ? { before: { status: before.status }, after: { status: 'dismissed' } }+ : null,+ };+ },+ async inverse({ id, brandId, data }) {+ const before = asObject(data.before);+ // Back only from dismissed: added since, or brought back by hand, is someone else's.+ let update = supabaseAdmin+ .from('prompt_suggestions')+ .update({ status: before.status, updated_at: new Date().toISOString() })+ .eq('id', id)+ .eq('status', 'dismissed');+ if (brandId) update = update.eq('brand_id', brandId);+ const { data: restored, error } = await update.select('id').maybeSingle();+ if (error) throw new Error(`Could not bring the suggestion back: ${error.message}`);+ if (restored) return 'ok';+ const { data: row, error: readError } = await supabaseAdmin+ .from('prompt_suggestions')+ .select('id')+ .eq('id', id)+ .maybeSingle();+ check(readError, 'the suggestion');+ return row ? 'changed' : 'gone';+ },+ href: () => '/dashboard/prompts/suggestions',+};++/** Each WRITE row's Undo, by tool name. A WRITE without one has no Undo. */+export const UNDO_RULES: Readonly<Record<string, UndoRule>> = {+ create_draft: createDraft,+ update_opportunity: updateOpportunity,+ dismiss_prompt_suggestion: dismissSuggestion,+};++/** A tool's Undo, or null: a read or an EXECUTE has none (§10b). */+export function undoRule(tool: Pick<ChatTool, 'name' | 'class'>): UndoRule | null {+ return tool.class === 'write' && Object.hasOwn(UNDO_RULES, tool.name)+ ? UNDO_RULES[tool.name]+ : null;+}++// ─── Undo from the step, the result card or the Activity log ────────────────++export interface UndoRequest {+ /** The change's row in the Activity log. */+ activityId: string;+ /** Who clicked Undo. */+ userId: string;+ organizationId: string;+ surface: ChatSurface;+ /** Where Undo was clicked, when in a run. */+ place?: ActivityPlace;+}++export type UndoOutcome =+ /** activityId: the Undo's own row. */+ | { code: 'ok'; activityId: string | null }+ /** The target changed since, or is gone: nothing was overwritten. */+ | { code: 'conflict'; reason: 'changed' | 'gone'; href: ChatHref | null }+ | { code: 'expired' }+ | { code: 'not_undoable' }+ | { code: 'already_undone' }+ | { code: 'not_found' }+ | { code: 'in_progress' }+ | { code: 'denied'; denial: ChatDenial }+ /** Something failed on the way (a read, a write): nothing was undone, Undo may try again. */+ | { code: 'failed' };++/** An outcome, with what the person reads. */+export type UndoResult = UndoOutcome & { message: string };++const undoT = createTranslator({ locale: 'en', messages, namespace: 'chatActivity.undo' });++/** What Undo says: "Undone.", or why not, from messages/en.json. */+export function undoMessage(outcome: UndoOutcome): string {+ switch (outcome.code) {+ case 'ok':+ return undoT('ok');+ case 'conflict':+ return undoT(outcome.reason === 'gone' ? 'gone' : 'changed');+ case 'denied':+ return outcome.denial.rule.detail;+ case 'expired':+ return undoT('expired');+ case 'not_undoable':+ return undoT('notUndoable');+ case 'already_undone':+ return undoT('alreadyUndone');+ case 'in_progress':+ return undoT('inProgress');+ case 'failed':+ return undoT('failed');+ default:+ return undoT('notFound');+ }+}++const result = (outcome: UndoOutcome): UndoResult => ({+ ...outcome,+ message: undoMessage(outcome),+});++/** What a repeated click gets back: the first click's answer, kept as JSON. */+type StoredUndo = { code: 'ok'; activityId: string | null };++interface LogRow {+ id: string;+ kind: string;+ user_id: string | null;+ brand_id: string | null;+ tool_key: string;+ class: string;+ status: string;+ target_type: string | null;+ target_id: string | null;+ summary_params: Json;+ undo_json: Json | null;+ undo_until: string | null;+ undoes_id: string | null;+}++const LOG_COLUMNS =+ 'id, kind, user_id, brand_id, tool_key, class, status, target_type, target_id, summary_params, undo_json, undo_until, undoes_id';++/** chatActivity.summary's values, as stored. */+function paramsOf(json: Json): Record<string, string> {+ return Object.fromEntries(+ Object.entries(asObject(json)).filter(+ (entry): entry is [string, string] => typeof entry[1] === 'string',+ ),+ );+}++/**+ * The input the precedence finds the change's brand from (the row's+ * brandOf): the brand it was made on, or its target's id, whose brand is+ * read again now. resolveCallBrand checks either is the workspace's.+ */+function brandInput(tool: ChatTool, row: LogRow): Record<string, unknown> {+ const { brandOf } = tool;+ if (!brandOf) return {};+ return 'input' in brandOf+ ? { [brandOf.input]: row.brand_id }+ : { [brandOf.idField]: row.target_id };+}++/**+ * Undoes one change from the log, for the person who clicked Undo: the+ * person Chat acted as, or an Admin. A row they can't read is not found.+ * Never throws (a server action calls it): a failure on the way is `failed`.+ */+export async function undoChange(req: UndoRequest): Promise<UndoResult> {+ try {+ return await undo(req);+ } catch (err) {+ console.error('Chat could not undo a change:', err);+ return result({ code: 'failed' });+ }+}++async function undo(req: UndoRequest): Promise<UndoResult> {+ const ctx = await readPrecedenceContext({+ userId: req.userId,+ organizationId: req.organizationId,+ // Undo needs no card in any mode: only a refusal stops it.+ mode: 'auto',+ surface: req.surface,+ });+ if (!ctx) return result({ code: 'not_found' });++ const { data, error } = await supabaseAdmin+ .from('chat_activity_log')+ .select(LOG_COLUMNS)+ .eq('id', req.activityId)+ .eq('organization_id', req.organizationId)+ .maybeSingle();+ if (error) throw new Error(`Could not read the activity log: ${error.message}`);+ const row = data as LogRow | null;+ if (!row || (row.user_id !== req.userId && ctx.role !== 'admin')) {+ return result({ code: 'not_found' });+ }+ if (row.status === 'undone') return result({ code: 'already_undone' });++ const tool = chatToolByKey(row.tool_key);+ const rule = tool ? undoRule(tool) : null;+ if (+ row.kind !== 'change' ||+ !tool ||+ !rule ||+ !row.undo_until ||+ !row.undo_json ||+ !row.target_type ||+ !row.target_id+ ) {+ return result({ code: 'not_undoable' });+ }+ if (Date.parse(row.undo_until) <= Date.now()) return result({ code: 'expired' });++ // The same decision as the tool's, read now: the role, the plan, the policy, and the+ // brand found again as the tool's call finds it.+ const decision = decideToolCall(+ tool,+ ctx,+ await readToolCall(ctx, tool, brandInput(tool, row), false),+ );+ const params = paramsOf(row.summary_params);+ if (decision.kind === 'deny') {+ return result({+ code: 'denied',+ denial: buildDenial(decision.denial, {+ tool,+ role: ctx.role,+ plan: ctx.plan,+ target: params.title ?? params.text ?? null,+ }),+ });+ }++ const target = {+ id: row.target_id,+ brandId: row.brand_id,+ data: asObject(row.undo_json) as Snapshot,+ };+ const targetType = row.target_type;+ // Set inside the work: a conflict answers this click, and its key goes back.+ const found: { conflict: InverseResult | null } = { conflict: null };+ const outcome = await withIdempotencyKey<StoredUndo>(+ {+ organizationId: req.organizationId,+ key: idempotencyKey('undo', [row.id]),+ requestHash: requestHash('undo', row.id),+ },+ async () => {+ const inverse = await rule.inverse(target);+ if (inverse !== 'ok') {+ found.conflict = inverse;+ await markChange(row.id, { status: 'undo_conflict' });+ return { result: { code: 'ok', activityId: null }, activityId: null };+ }+ // Undone: what follows records it, and a failure there never undoes twice.+ await markChange(row.id, {+ status: 'undone',+ undone_at: new Date().toISOString(),+ undone_by: req.userId,+ });+ let activityId: string | null = null;+ try {+ activityId = await logActivity({+ organizationId: req.organizationId,+ userId: req.userId,+ brandId: row.brand_id,+ place: req.place ?? { conversationId: null, runId: null, stepId: null },+ surface: req.surface,+ tool,+ mode: null,+ approval: { kind: 'run' },+ target: { type: targetType, id: row.target_id },+ summary: { key: `${tool.labelKey}Undo`, params },+ undo: null,+ undoesId: row.id,+ });+ } catch (err) {+ console.error('Chat could not log an Undo:', err);+ }+ return { result: { code: 'ok', activityId }, activityId };+ },+ // A conflict isn't kept: once the target is back as it was, Undo may try again.+ { keep: () => found.conflict === null },+ );++ if (outcome.kind === 'mismatch' || outcome.kind === 'busy')+ return result({ code: 'in_progress' });+ const { conflict } = found;+ if (conflict && conflict !== 'ok') {+ return result({+ code: 'conflict',+ reason: conflict,+ href: conflict === 'gone' ? null : rule.href(row.target_id),+ });+ }+ return result(outcome.result);+}++/** Sets the undone change's status; logged, not thrown, once the inverse ran. */+async function markChange(id: string, patch: Record<string, string>): Promise<void> {+ const { error } = await supabaseAdmin+ .from('chat_activity_log')+ .update(patch)+ .eq('id', id)+ .in('status', ['done', 'undo_conflict']);+ if (error) console.error('Chat could not mark a change in the activity log:', error.message);+}diff --git a/web/src/lib/chat/write.test.ts b/web/src/lib/chat/write.test.tsnew file mode 100644index 000000000..2e7611739--- /dev/null+++ b/web/src/lib/chat/write.test.ts@@ -0,0 +1,468 @@+// @vitest-environment node+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { FakeSupabase } from './testing/fake-supabase';+import {+ BRAND,+ OPPORTUNITY,+ ORG,+ PEOPLE,+ SUGGESTION,+ fakeCreateDraft,+ fakeDismissSuggestion,+ fakeUpdateOpportunity,+ seedWorkspace,+} from './testing/chat-fixtures';++/**+ * A change Chat makes, logged once (CHAT-20 §10a, §11c, §21): every WRITE+ * that ran lands in the Activity log with its mode, approval and Undo; a+ * double-clicked approval makes one object.+ */++vi.mock('@/lib/supabase/admin', async () => ({+ supabaseAdmin: (await import('@/lib/chat/testing/fake-supabase')).createFakeSupabase(),+}));+vi.mock('@/lib/actions/content-drafts', () => ({ createContentDraft: vi.fn() }));+vi.mock('@/lib/actions/content', () => ({ updateOpportunityStatus: vi.fn() }));+vi.mock('@/lib/actions/prompt-suggestions', () => ({ dismissSuggestion: vi.fn() }));++const { supabaseAdmin } = await import('@/lib/supabase/admin');+const db = supabaseAdmin as unknown as FakeSupabase;+const { createContentDraft } = await import('@/lib/actions/content-drafts');+const { updateOpportunityStatus } = await import('@/lib/actions/content');+const { dismissSuggestion } = await import('@/lib/actions/prompt-suggestions');+const { runLoggedWrite } = await import('./write');+const { activitySummary, approvalFor, logActivity, recordActivity } = await import('./activity');+const { decideToolCall } = await import('./precedence');+const { readPrecedenceContext, readToolCall } = await import('./precedence-context');+const { chatTool, CHAT_TOOLS } = await import('./registry/tools');+const { UNDO_RULES } = await import('./undo');++type ChatMode = import('./precedence').ChatMode;+type ChatTool = import('./registry/define-tool').ChatTool;++const WRITES = CHAT_TOOLS.filter((tool) => tool.class === 'write');+const INPUTS: Record<string, unknown> = {+ create_draft: {+ brand_id: BRAND,+ title: 'Pricing FAQ',+ page_type: 'docs_faq',+ method: 'create',+ source: { kind: 'opportunity', id: OPPORTUNITY },+ },+ update_opportunity: { opportunity_id: OPPORTUNITY, status: 'dismissed', reason: 'not_relevant' },+ dismiss_prompt_suggestion: { suggestion_id: SUGGESTION },+};+const toolCtx = {} as never;+let step = 0;+const nextStep = () => `step-${++step}`;++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ seedWorkspace(db);+ vi.mocked(createContentDraft).mockImplementation(fakeCreateDraft(db) as never);+ vi.mocked(updateOpportunityStatus).mockImplementation(fakeUpdateOpportunity(db) as never);+ vi.mocked(dismissSuggestion).mockImplementation(fakeDismissSuggestion(db) as never);+});+afterEach(() => vi.unstubAllEnvs());++/** The engine's path: decide the call, act on the decision, run and log it. */+async function runAs(+ userId: string,+ tool: ChatTool,+ mode: ChatMode,+ options: { approvalKey?: string; input?: unknown; approved?: boolean } = {},+) {+ const input = (options.input ?? INPUTS[tool.name]) as Record<string, unknown>;+ const ctx = await readPrecedenceContext({ userId, organizationId: ORG, mode, surface: 'chat' });+ const call = await readToolCall(ctx!, tool, input, false);+ const decision = decideToolCall(tool, ctx!, call);+ if (decision.kind === 'ask' && !options.approved) return { decision, outcome: null };+ const approval = approvalFor(decision);+ if (!approval || approval.kind === 'run') return { decision, outcome: null };+ const outcome = await runLoggedWrite({+ tool,+ input,+ ctx: toolCtx,+ organizationId: ORG,+ userId,+ brandId: call.brandId,+ surface: 'chat',+ mode,+ approval,+ place: { conversationId: null, runId: null, stepId: null },+ approvalKey: options.approvalKey ?? nextStep(),+ });+ return { decision, outcome };+}++describe('every WRITE that ran is in the Activity log (§21)', () => {+ it.each(WRITES.map((tool) => [tool.name, tool] as const))(+ '%s in Full auto: mode, approval, Undo window, label key, target and summary',+ async (name, tool) => {+ const { decision, outcome } = await runAs(PEOPLE.admin, tool, 'full_auto');+ expect(decision).toEqual({ kind: 'run', via: 'full_auto' });+ expect(outcome).toMatchObject({ code: 'ok', repeated: false });++ const rows = db.tables.chat_activity_log;+ expect(rows).toHaveLength(1);+ const [row] = rows;+ expect(row).toMatchObject({+ organization_id: ORG,+ user_id: PEOPLE.admin,+ brand_id: BRAND,+ surface: 'chat',+ tool_key: tool.labelKey,+ class: 'write',+ mode: 'full_auto',+ approval_kind: 'auto',+ auto_via: 'full_auto',+ target_type: UNDO_RULES[name].targetType,+ summary_key: tool.labelKey,+ status: 'done',+ });+ // The label key, never the tool's name (CHAT-03 item 22).+ expect(JSON.stringify(row)).not.toContain(name);+ expect(row.target_id).toEqual(expect.any(String));+ expect(row.undo_json).toEqual(expect.any(Object));+ const window = Date.parse(row.undo_until as string) - Date.now();+ expect(window).toBeGreaterThan(UNDO_RULES[name].windowMs - 60_000);+ expect(window).toBeLessThanOrEqual(UNDO_RULES[name].windowMs);+ expect(outcome && 'activityId' in outcome && outcome.activityId).toBe(row.id);+ expect(activitySummary(row.summary_key as string, row.summary_params as never)).not.toBe('');+ },+ );++ it('records why a change ran without a card: Always, Full auto or "Don\'t ask again"', async () => {+ const tool = chatTool('dismiss_prompt_suggestion')!;+ db.tables.chat_auto_choices = [+ { user_id: PEOPLE.manager, organization_id: ORG, tool_key: tool.labelKey },+ ];+ await runAs(PEOPLE.manager, tool, 'auto');+ db.tables.prompt_suggestions[0].status = 'new';+ db.tables.chat_auto_choices = [];+ db.tables.chat_settings = [+ {+ organization_id: ORG,+ tool_policies: { [tool.labelKey]: 'always' },+ full_auto_for_members: true,+ dont_ask_again: true,+ manager_execute_off: [],+ },+ ];+ await runAs(PEOPLE.manager, tool, 'auto');+ expect(+ db.tables.chat_activity_log.map((row) => [row.mode, row.approval_kind, row.auto_via]),+ ).toEqual([+ ['auto', 'auto', 'dont_ask_again'],+ ['auto', 'auto', 'always'],+ ]);+ });++ it('records a change approved on its card as ask, in the mode it ran in', async () => {+ const tool = chatTool('create_draft')!;+ const first = await runAs(PEOPLE.manager, tool, 'ask_first');+ expect(first.decision.kind).toBe('ask');+ expect(db.tables.content_drafts).toHaveLength(0); // Nothing before the OK.+ await runAs(PEOPLE.manager, tool, 'ask_first', { approved: true });+ expect(db.tables.chat_activity_log[0]).toMatchObject({+ mode: 'ask_first',+ approval_kind: 'ask',+ auto_via: null,+ });+ });++ it('says what changed in words', () => {+ expect(activitySummary('saveDraft', { title: 'Pricing FAQ' })).toBe(+ 'Saved the draft “Pricing FAQ”',+ );+ expect(activitySummary('opportunityStatus', { title: 'Teams', status: 'dismissed' })).toBe(+ 'Dismissed the opportunity “Teams”',+ );+ expect(activitySummary('opportunityStatus', { title: 'Teams', status: 'reviewed' })).toBe(+ 'Marked reviewed the opportunity “Teams”',+ );+ expect(activitySummary('dismissSuggestionUndo', { text: 'best crm' })).toBe(+ 'Brought back the prompt suggestion “best crm”',+ );+ });+});++describe('a double-clicked approval creates one object (§21)', () => {+ it('two calls at once with the same approval save one draft and write one row', async () => {+ const tool = chatTool('create_draft')!;+ const [a, b] = await Promise.all([+ runAs(PEOPLE.manager, tool, 'auto', { approved: true, approvalKey: 'card-1' }),+ runAs(PEOPLE.manager, tool, 'auto', { approved: true, approvalKey: 'card-1' }),+ ]);+ expect(db.tables.content_drafts).toHaveLength(1);+ expect(db.tables.chat_activity_log).toHaveLength(1);+ expect(createContentDraft).toHaveBeenCalledTimes(1);+ expect(a.outcome).toMatchObject({ code: 'ok', output: db.tables.content_drafts[0].id });+ expect(b.outcome).toMatchObject({ code: 'ok', output: db.tables.content_drafts[0].id });+ expect([a.outcome, b.outcome].map((o) => o && 'repeated' in o && o.repeated).sort()).toEqual([+ false,+ true,+ ]);+ });++ it('a retry after the first call finished gets its result and log row back', async () => {+ const tool = chatTool('create_draft')!;+ const first = await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-2' });+ const again = await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-2' });+ expect(again.outcome).toEqual({ ...first.outcome, repeated: true });+ expect(db.tables.content_drafts).toHaveLength(1);+ });++ it('two approvals make two drafts', async () => {+ const tool = chatTool('create_draft')!;+ await runAs(PEOPLE.manager, tool, 'full_auto');+ await runAs(PEOPLE.manager, tool, 'full_auto');+ expect(db.tables.content_drafts).toHaveLength(2);+ expect(db.tables.chat_activity_log).toHaveLength(2);+ });++ it('an approval used for another change is a mismatch: nothing is made', async () => {+ const tool = chatTool('create_draft')!;+ await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-3' });+ const other = await runAs(PEOPLE.manager, tool, 'full_auto', {+ approvalKey: 'card-3',+ input: { ...(INPUTS.create_draft as object), title: 'Something else' },+ });+ expect(other.outcome).toEqual({ code: 'approval_mismatch' });+ expect(db.tables.content_drafts).toHaveLength(1);+ });+});++describe('failures', () => {+ it('a WRITE that failed is not logged, and its approval may be tried again', async () => {+ const tool = chatTool('create_draft')!;+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(createContentDraft).mockRejectedValueOnce(new Error('server down'));+ const failed = await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-4' });+ expect(failed.outcome).toEqual({ code: 'failed', reason: 'server down' });+ expect(db.tables.chat_activity_log).toHaveLength(0);+ errors.mockRestore();+ const retry = await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-4' });+ expect(retry.outcome).toMatchObject({ code: 'ok', repeated: false });+ expect(db.tables.content_drafts).toHaveLength(1);+ });++ it("a log row that can't be written never makes the change twice", async () => {+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const tool = chatTool('create_draft')!;+ db.failures.chat_activity_log = { message: 'insert failed' };+ const first = await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-5' });+ expect(first.outcome).toMatchObject({ code: 'ok', activityId: null });+ const again = await runAs(PEOPLE.manager, tool, 'full_auto', { approvalKey: 'card-5' });+ expect(again.outcome).toMatchObject({ code: 'ok', repeated: true });+ expect(db.tables.content_drafts).toHaveLength(1);+ errors.mockRestore();+ });++ it("logs a change without its Undo when what Undo needs can't be read", async () => {+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const tool = chatTool('update_opportunity')!;+ const realFrom = db.from.bind(db);+ let changed = false;+ const update = fakeUpdateOpportunity(db);+ vi.mocked(updateOpportunityStatus).mockImplementationOnce((async (+ ...args: Parameters<typeof update>+ ) => {+ const row = await update(...args);+ changed = true;+ return row;+ }) as never);+ db.from = (table: string) => {+ // The reads before the change work; the one after it fails.+ if (table === 'content_opportunities' && changed) throw new Error('read failed');+ return realFrom(table);+ };+ try {+ await runAs(PEOPLE.manager, tool, 'full_auto');+ } finally {+ db.from = realFrom;+ }+ expect(db.tables.chat_activity_log).toHaveLength(1);+ expect(db.tables.chat_activity_log[0]).toMatchObject({ undo_json: null, undo_until: null });+ errors.mockRestore();+ });+});++describe('what is logged', () => {+ it('a read is never logged, and an EXECUTE only on a click and without Undo', async () => {+ const read = CHAT_TOOLS.find((tool) => tool.class === 'read')!;+ await expect(+ runLoggedWrite({+ tool: read,+ input: {},+ ctx: toolCtx,+ organizationId: ORG,+ userId: PEOPLE.admin,+ brandId: BRAND,+ surface: 'chat',+ mode: 'full_auto',+ approval: { kind: 'auto', via: 'full_auto' },+ place: { conversationId: null, runId: null, stepId: null },+ approvalKey: 'x',+ }),+ ).rejects.toThrow();+ const execute = {+ ...chatTool('create_draft')!,+ class: 'execute' as const,+ labelKey: 'publishCms',+ };+ await expect(+ runLoggedWrite({+ tool: execute,+ input: {},+ ctx: toolCtx,+ organizationId: ORG,+ userId: PEOPLE.admin,+ brandId: BRAND,+ surface: 'chat',+ mode: 'full_auto',+ approval: { kind: 'auto', via: 'full_auto' },+ place: { conversationId: null, runId: null, stepId: null },+ approvalKey: 'x',+ }),+ ).rejects.toThrow("An EXECUTE runs on the person's click only");+ const entry = {+ organizationId: ORG,+ userId: PEOPLE.admin,+ brandId: BRAND,+ place: { conversationId: null, runId: null, stepId: null },+ surface: 'chat' as const,+ tool: execute,+ mode: 'auto' as const,+ approval: { kind: 'click' as const },+ target: { type: 'cms_item', id: 'item-1' },+ summary: { key: 'publishCms', params: {} },+ undo: null,+ };+ await expect(+ logActivity({ ...entry, undo: { data: {}, until: new Date() } }),+ ).rejects.toThrow();+ expect(await logActivity(entry)).toEqual(expect.any(String));+ });++ it('maps each decision to its approval', () => {+ expect(approvalFor({ kind: 'run', via: 'read' })).toBeNull();+ expect(approvalFor({ kind: 'run', via: 'always' })).toEqual({ kind: 'auto', via: 'always' });+ expect(approvalFor({ kind: 'ask', reason: 'mode', offerDontAskAgain: true })).toEqual({+ kind: 'ask',+ });+ expect(approvalFor({ kind: 'click' })).toEqual({ kind: 'click' });+ expect(approvalFor({ kind: 'deny', denial: { code: 'policy_never' } })).toBeNull();+ });+});++describe('access.denied rows (§4c, §10a)', () => {+ it("records a refusal in the person's log: its reason, no approval, target or Undo", async () => {+ const tool = chatTool('update_opportunity')!;+ const ctx = await readPrecedenceContext({+ userId: PEOPLE.analyst,+ organizationId: ORG,+ mode: 'auto',+ surface: 'chat',+ });+ const decision = decideToolCall(+ tool,+ ctx!,+ await readToolCall(ctx!, tool, INPUTS.update_opportunity as Record<string, unknown>, false),+ );+ expect(decision.kind).toBe('deny');+ if (decision.kind !== 'deny') return;+ // The shape access-log.ts's accessDeniedEvent builds.+ const { code, ...detail } = decision.denial;+ const id = await recordActivity({+ kind: 'access.denied',+ userId: PEOPLE.analyst,+ organizationId: ORG,+ brandId: BRAND,+ toolKey: tool.labelKey,+ toolClass: tool.class,+ surface: 'chat',+ reason: code,+ detail,+ conversationId: null,+ runId: null,+ });+ expect(db.tables.chat_activity_log).toEqual([+ expect.objectContaining({+ id,+ kind: 'access.denied',+ user_id: PEOPLE.analyst,+ brand_id: BRAND,+ tool_key: 'opportunityStatus',+ class: 'write',+ denial_code: 'forbidden_role',+ denial_json: { role: 'analyst', roles: ['admin', 'manager'] },+ summary_key: 'accessDenied',+ summary_params: { tool: 'Review or dismiss opportunities' },+ }),+ ]);+ // Nothing ran: no approval, target or Undo (00402 holds the same).+ for (const column of ['approval_kind', 'target_type', 'undo_json', 'undo_until']) {+ expect(db.tables.chat_activity_log[0][column] ?? null).toBeNull();+ }+ expect(activitySummary('accessDenied', { tool: 'Review or dismiss opportunities' })).toBe(+ 'Not allowed: Review or dismiss opportunities',+ );+ });++ it('a denial is never undone', async () => {+ const { undoChange } = await import('./undo');+ const id = await recordActivity({+ kind: 'access.denied',+ userId: PEOPLE.manager,+ organizationId: ORG,+ brandId: null,+ toolKey: 'saveDraft',+ toolClass: 'write',+ surface: 'mcp',+ reason: 'brand_scope',+ detail: {},+ conversationId: null,+ runId: null,+ });+ expect(+ await undoChange({+ activityId: id,+ userId: PEOPLE.manager,+ organizationId: ORG,+ surface: 'chat',+ }),+ ).toMatchObject({ code: 'not_undoable' });+ });+});++describe('00402', () => {+ const sql = readFileSync(+ path.resolve(__dirname, '../../../../supabase/migrations/00402_chat_activity.sql'),+ 'utf8',+ );++ it('lets a person read their own rows and an Admin the workspace’s; only the server writes', () => {+ expect(sql).toMatch(/alter table public\.chat_activity_log enable row level security/);+ expect(sql).toMatch(/alter table public\.chat_idempotency_keys enable row level security/);+ expect(sql).toMatch(/p\.role = 'admin' or chat_activity_log\.user_id = auth\.uid\(\)/);+ // No write grant or policy for members, and keys not readable at all.+ expect(sql).not.toMatch(/grant (insert|update|delete|all)[^;]*to authenticated/);+ expect(sql).not.toMatch(/for (insert|update|delete)/);+ expect(sql).not.toMatch(/grant[^;]*chat_idempotency_keys to authenticated/);+ });++ it('keeps undo_json from members', () => {+ const grant = sql.match(/grant select \(([^)]*)\) on table public\.chat_activity_log/);+ expect(grant).not.toBeNull();+ const columns = grant![1].split(',').map((column) => column.trim());+ expect(columns).not.toContain('undo_json');+ for (const column of ['tool_key', 'mode', 'approval_kind', 'undo_until', 'status']) {+ expect(columns).toContain(column);+ }+ });+});diff --git a/web/src/lib/chat/write.ts b/web/src/lib/chat/write.tsnew file mode 100644index 000000000..525a79c60--- /dev/null+++ b/web/src/lib/chat/write.ts@@ -0,0 +1,149 @@+import type { Json } from '@/types/supabase';+import { logActivity, type ActivityApproval, type ActivityPlace } from './activity';+import { idempotencyKey, requestHash, sweepExpiredKeys, withIdempotencyKey } from './idempotency';+import type { ChatMode, ChatSurface } from './precedence';+import type { ChatTool, ChatToolContext } from './registry/define-tool';+import { undoRule, type WriteRecord } from './undo';++/**+ * Runs a WRITE or an EXECUTE the precedence allowed (decideToolCall, then+ * the card's OK or the click when it asked for one), once per approval, and+ * logs it: the change runs under its idempotency key (idempotency.ts), the+ * state Undo needs is read around it (undo.ts), and the Activity log gets+ * its row (activity.ts) with the mode, the approval and the Undo window.+ * A repeat of the approval (a double click, a reconnect, a retry) returns+ * the first call's result and log row and changes nothing. Server only: the+ * engine (C3) calls it for each change a run makes.+ */++export interface WriteRequest {+ /** A WRITE or EXECUTE row of the registry. */+ tool: ChatTool;+ /** Its input, already parsed by the row's schema. */+ input: unknown;+ /** Who the tool acts as: the signed-in person. */+ ctx: ChatToolContext;+ organizationId: string;+ userId: string;+ /** The call's brand, as the precedence found it (readToolCall, resolveCallBrand). */+ brandId: string | null;+ surface: ChatSurface;+ mode: ChatMode;+ /** How it was approved: approvalFor(decision) once the card or the click came. */+ approval: Exclude<ActivityApproval, { kind: 'run' }>;+ place: ActivityPlace;+ /**+ * The approval it runs on: the run step that asked for it (the card the+ * person clicks, or the step that ran it without one). Its repeats share it.+ */+ approvalKey: string;+}++export type WriteOutcome =+ /** repeated: an earlier call with the approval made the change; this is its result. */+ | { code: 'ok'; output: Json; activityId: string | null; repeated: boolean }+ /** The approval was used for another change (§11a): show the card again. */+ | { code: 'approval_mismatch' }+ /** The first call with the approval is still running. */+ | { code: 'in_progress' }+ /**+ * The change failed, or its key couldn't be read: nothing was made and the+ * approval may be tried again (§11b). reason: for the server's log and the+ * step's debug record, never the person.+ */+ | { code: 'failed'; reason: string };++const toJson = (value: unknown): Json =>+ value === undefined ? null : (JSON.parse(JSON.stringify(value)) as Json);++/**+ * Never throws for a failure on the way (the engine and server actions call+ * it): `failed`. Only a call against the rules (a read, an EXECUTE without+ * its click) throws, before anything runs.+ */+export async function runLoggedWrite(req: WriteRequest): Promise<WriteOutcome> {+ const { tool } = req;+ if (tool.class === 'read') throw new Error('A read changes nothing to log');+ if (tool.class === 'execute' && req.approval.kind !== 'click') {+ throw new Error("An EXECUTE runs on the person's click only");+ }+ try {+ return await run(req);+ } catch (err) {+ console.error('Chat could not make a change:', err);+ return { code: 'failed', reason: err instanceof Error ? err.message : String(err) };+ }+}++async function run(req: WriteRequest): Promise<WriteOutcome> {+ const { tool } = req;+ const rule = undoRule(tool);++ const outcome = await withIdempotencyKey<Json>(+ {+ organizationId: req.organizationId,+ key: idempotencyKey(tool.labelKey, [req.approvalKey]),+ requestHash: requestHash(tool.labelKey, req.input),+ },+ async () => {+ const before = rule ? await rule.before(req.input) : null;+ const output = await tool.run(req.ctx, req.input as never);+ // The change is made: whatever happens to its log row, it isn't made again.+ let activityId: string | null = null;+ try {+ activityId = await logActivity(await activityOf(req, rule, before, output));+ } catch (err) {+ console.error('Chat could not log a change it made:', err);+ }+ return { result: toJson(output), activityId };+ },+ );++ if (outcome.kind === 'mismatch') return { code: 'approval_mismatch' };+ if (outcome.kind === 'busy') return { code: 'in_progress' };+ if (outcome.kind === 'ran') await sweepExpiredKeys(req.organizationId);+ return {+ code: 'ok',+ output: outcome.result,+ activityId: outcome.activityId,+ repeated: outcome.kind === 'repeat',+ };+}++/** The log row for a change: the rule's record, or the bare facts when it has none or fails. */+async function activityOf(+ req: WriteRequest,+ rule: ReturnType<typeof undoRule>,+ before: Awaited<ReturnType<NonNullable<ReturnType<typeof undoRule>>['before']>>,+ output: unknown,+) {+ let record: WriteRecord = {+ target: { type: rule?.targetType ?? req.tool.area, id: null },+ summaryParams: {},+ undo: null,+ };+ if (rule) {+ try {+ record = await rule.record(req.input, output, before);+ } catch (err) {+ // Logged without an Undo rather than not at all.+ console.error('Chat could not read what Undo needs:', err);+ }+ }+ return {+ organizationId: req.organizationId,+ userId: req.userId,+ brandId: req.brandId,+ place: req.place,+ surface: req.surface,+ tool: req.tool,+ mode: req.mode,+ approval: req.approval,+ target: record.target,+ summary: { key: req.tool.labelKey, params: record.summaryParams },+ undo:+ rule && record.undo+ ? { data: record.undo, until: new Date(Date.now() + rule.windowMs) }+ : null,+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex ed110140c..79c37343e 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1370,6 +1370,139 @@ export type Database = {},]}+ chat_activity_log: {+ Row: {+ approval_kind: string | null+ auto_via: string | null+ brand_id: string | null+ class: string+ conversation_id: string | null+ created_at: string+ denial_code: string | null+ denial_json: Json | null+ id: string+ kind: string+ mode: string | null+ organization_id: string+ run_id: string | null+ status: string+ step_id: string | null+ summary_key: string+ summary_params: Json+ surface: string+ target_id: string | null+ target_type: string | null+ tool_key: string+ undo_json: Json | null+ undo_until: string | null+ undoes_id: string | null+ undone_at: string | null+ undone_by: string | null+ user_id: string | null+ }+ Insert: {+ approval_kind?: string | null+ auto_via?: string | null+ brand_id?: string | null+ class: string+ conversation_id?: string | null+ created_at?: string+ denial_code?: string | null+ denial_json?: Json | null+ id?: string+ kind?: string+ mode?: string | null+ organization_id: string+ run_id?: string | null+ status?: string+ step_id?: string | null+ summary_key: string+ summary_params?: Json+ surface: string+ target_id?: string | null+ target_type?: string | null+ tool_key: string+ undo_json?: Json | null+ undo_until?: string | null+ undoes_id?: string | null+ undone_at?: string | null+ undone_by?: string | null+ user_id?: string | null+ }+ Update: {+ approval_kind?: string | null+ auto_via?: string | null+ brand_id?: string | null+ class?: string+ conversation_id?: string | null+ created_at?: string+ denial_code?: string | null+ denial_json?: Json | null+ id?: string+ kind?: string+ mode?: string | null+ organization_id?: string+ run_id?: string | null+ status?: string+ step_id?: string | null+ summary_key?: string+ summary_params?: Json+ surface?: string+ target_id?: string | null+ target_type?: string | null+ tool_key?: string+ undo_json?: Json | null+ undo_until?: string | null+ undoes_id?: string | null+ undone_at?: string | null+ undone_by?: string | null+ user_id?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "chat_activity_log_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_activity_log_conversation_id_fkey"+ columns: ["conversation_id"]+ isOneToOne: false+ referencedRelation: "chat_conversations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_activity_log_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_activity_log_run_id_fkey"+ columns: ["run_id"]+ isOneToOne: false+ referencedRelation: "chat_runs"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_activity_log_step_id_fkey"+ columns: ["step_id"]+ isOneToOne: false+ referencedRelation: "chat_run_steps"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_activity_log_undoes_id_fkey"+ columns: ["undoes_id"]+ isOneToOne: false+ referencedRelation: "chat_activity_log"+ referencedColumns: ["id"]+ },+ ]+ }chat_auto_choices: {Row: {created_at: string@@ -1459,6 +1592,54 @@ export type Database = {},]}+ chat_idempotency_keys: {+ Row: {+ activity_id: string | null+ created_at: string+ expires_at: string+ key: string+ organization_id: string+ request_hash: string+ result_json: Json | null+ status: string+ }+ Insert: {+ activity_id?: string | null+ created_at?: string+ expires_at?: string+ key: string+ organization_id: string+ request_hash: string+ result_json?: Json | null+ status?: string+ }+ Update: {+ activity_id?: string | null+ created_at?: string+ expires_at?: string+ key?: string+ organization_id?: string+ request_hash?: string+ result_json?: Json | null+ status?: string+ }+ Relationships: [+ {+ foreignKeyName: "chat_idempotency_keys_activity_id_fkey"+ columns: ["activity_id"]+ isOneToOne: false+ referencedRelation: "chat_activity_log"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "chat_idempotency_keys_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ ]+ }chat_messages: {Row: {content_md: string