feat: add organization scoping to chats (#23827)

Fixes https://github.com/coder/internal/issues/1436

* Adds organization_id to chats with backfill (workspace org → user org membership → default org)
* No support yet for ACLs (follow-up issue)
- Cross-org workspace binding rejected (both in `CreateChatRequest` and in `create_workspace` tool
- Adds `OrganizationAutocomplete` to `AgentCreateForm`
- Docs updated with `organization_id` in chats-api.md

> 🤖 Written by a Coder Agent. Reviewed by many humans and many agents.

---------

Co-authored-by: Mathias Fredriksson <mafredri@gmail.com>
This commit is contained in:
Cian Johnston
2026-04-13 12:31:25 +01:00
committed by GitHub
co-authored by Mathias Fredriksson
parent cb0b84a2d3
commit 22062ec52e
58 changed files with 1533 additions and 581 deletions
@@ -0,0 +1 @@
ALTER TABLE chats DROP COLUMN organization_id;
@@ -0,0 +1,20 @@
-- Step 1: Add nullable column with FK.
ALTER TABLE chats
ADD COLUMN organization_id UUID REFERENCES organizations(id) ON DELETE CASCADE;
-- Step 2: Backfill from workspace org (primary path). Fall back to
-- user's oldest org membership, then default org for rows where
-- workspace_id was NULLed out by ON DELETE SET NULL or never set.
UPDATE chats c
SET organization_id = COALESCE(
(SELECT w.organization_id FROM workspaces w WHERE w.id = c.workspace_id),
(SELECT om.organization_id FROM organization_members om
WHERE om.user_id = c.owner_id ORDER BY om.created_at ASC LIMIT 1),
(SELECT id FROM organizations WHERE is_default = true LIMIT 1)
);
-- Step 3: Enforce NOT NULL going forward.
ALTER TABLE chats ALTER COLUMN organization_id SET NOT NULL;
-- Step 4: Index for efficient lookups by organization.
CREATE INDEX idx_chats_organization_id ON chats (organization_id);