Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(sharing): correct team sharing for calls (#6481)

Will Hutchinsonb7bc80e24765
diff --git a/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json b/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json
deleted file mode 100644
index f599ee3f78..0000000000
--- a/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT created_at, updated_at, deleted_at\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "created_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 1,
- "name": "updated_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 2,
- "name": "deleted_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- true
- ]
- },
- "hash": "02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a"
-}
diff --git a/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json b/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json
deleted file mode 100644
index 30b8a29f8c..0000000000
--- a/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM agent_session WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df"
-}
diff --git a/.sqlx/query-0912a0912bc058ca42843caa1595a4bb4198de7c4cb6d2f1e42fac2267a4866b.json b/.sqlx/query-0912a0912bc058ca42843caa1595a4bb4198de7c4cb6d2f1e42fac2267a4866b.json
deleted file mode 100644
index 65b21e4307..0000000000
--- a/.sqlx/query-0912a0912bc058ca42843caa1595a4bb4198de7c4cb6d2f1e42fac2267a4866b.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO document_sub_type (document_id, sub_type) SELECT id, 'task' FROM unnest($1::text[]) id ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "0912a0912bc058ca42843caa1595a4bb4198de7c4cb6d2f1e42fac2267a4866b"
-}
diff --git a/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json b/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json
deleted file mode 100644
index dd105edbe3..0000000000
--- a/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE entity SET deleted_at = $2 WHERE id = $1\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Timestamptz"
- ]
- },
- "nullable": []
- },
- "hash": "0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34"
-}
diff --git a/.sqlx/query-0a5e04dec89351bfaccb382653ec43e4526b7450c4e5b337937b1662d82fe4bd.json b/.sqlx/query-0a5e04dec89351bfaccb382653ec43e4526b7450c4e5b337937b1662d82fe4bd.json
new file mode 100644
index 0000000000..32ad924dd8
--- /dev/null
+++ b/.sqlx/query-0a5e04dec89351bfaccb382653ec43e4526b7450c4e5b337937b1662d82fe4bd.json
@@ -0,0 +1,140 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text AS source_id\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1 AS source_id\n ),\n visible_calls AS (\n SELECT\n c.id AS call_id,\n c.channel_id,\n c.room_name,\n c.created_by,\n c.created_at AS started_at,\n NULL::timestamptz AS ended_at,\n NULL::bigint AS duration_ms,\n c.egress_id,\n c.recording_key,\n c.preview_url,\n c.recording_started_at,\n NULL::text AS custom_name,\n NULL::text AS summary,\n c.share_with_team,\n sp.team_share_access_level,\n true AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_participants cp\n WHERE cp.call_id = c.id AND cp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = c.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM calls c\n JOIN \"SharePermission\" sp ON sp.id = c.share_permission_id\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = c.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR c.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR c.id = ANY($6))\n AND ($9::bool IS FALSE OR (\n ($11::bool IS FALSE AND EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = c.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND jsonb_exists_any(ep.values -> 'value', $10::text[])\n ))\n OR ($11::bool IS TRUE AND $10::text[] <@ (\n SELECT COALESCE(array_agg(elem), ARRAY[]::text[])\n FROM (\n SELECT values FROM entity_properties\n WHERE entity_id = c.id::text\n AND entity_type = 'CALL_RECORD'\n AND jsonb_typeof(values -> 'value') = 'array'\n ) ep\n CROSS JOIN LATERAL jsonb_array_elements_text(ep.values -> 'value') AS elem\n ))\n ))\n UNION ALL\n SELECT\n cr.id AS call_id,\n cr.channel_id,\n cr.room_name,\n cr.created_by,\n cr.started_at,\n cr.ended_at,\n cr.duration_ms,\n cr.egress_id,\n cr.recording_key,\n cr.preview_url,\n cr.recording_started_at,\n cr.custom_name,\n cr.summary,\n (sp.team_share_access_level IS NOT NULL) AS share_with_team,\n sp.team_share_access_level,\n false AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = cr.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM call_records cr\n JOIN \"SharePermission\" sp ON sp.id = cr.share_permission_id\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR cr.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR cr.id = ANY($6))\n AND ($9::bool IS FALSE OR (\n ($11::bool IS FALSE AND EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = cr.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND jsonb_exists_any(ep.values -> 'value', $10::text[])\n ))\n OR ($11::bool IS TRUE AND $10::text[] <@ (\n SELECT COALESCE(array_agg(elem), ARRAY[]::text[])\n FROM (\n SELECT values FROM entity_properties\n WHERE entity_id = cr.id::text\n AND entity_type = 'CALL_RECORD'\n AND jsonb_typeof(values -> 'value') = 'array'\n ) ep\n CROSS JOIN LATERAL jsonb_array_elements_text(ep.values -> 'value') AS elem\n ))\n ))\n )\n SELECT\n call_id as \"call_id!\",\n channel_id as \"channel_id!\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n started_at as \"started_at!\",\n ended_at,\n duration_ms,\n egress_id,\n recording_key,\n preview_url,\n recording_started_at,\n custom_name,\n summary,\n share_with_team as \"share_with_team!\",\n team_share_access_level as \"team_share_access_level?: AccessLevel\",\n is_active as \"is_active!\",\n status as \"status!\"\n FROM visible_calls\n WHERE ($7::bool IS FALSE OR status = ANY($8::text[]))\n ORDER BY \"started_at!\" DESC\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "call_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "room_name!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_by!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "started_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "ended_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "duration_ms",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 7,
+ "name": "egress_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "recording_key",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "preview_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "recording_started_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "custom_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "summary",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "share_with_team!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 14,
+ "name": "team_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 15,
+ "name": "is_active!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "status!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8",
+ "Bool",
+ "UuidArray",
+ "Bool",
+ "UuidArray",
+ "Bool",
+ "TextArray",
+ "Bool",
+ "TextArray",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "0a5e04dec89351bfaccb382653ec43e4526b7450c4e5b337937b1662d82fe4bd"
+}
diff --git a/.sqlx/query-1176d102637cc13aed0121feb6f0d3799e150c099bcccbf1b809b00d075338f1.json b/.sqlx/query-1176d102637cc13aed0121feb6f0d3799e150c099bcccbf1b809b00d075338f1.json
deleted file mode 100644
index 456df98e2d..0000000000
--- a/.sqlx/query-1176d102637cc13aed0121feb6f0d3799e150c099bcccbf1b809b00d075338f1.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id) SELECT id::uuid, 'document', 'macro|[email protected]', 'user', 'view', 'aaaaaaaa-ffff-ffff-ffff-ffffffffffff' FROM unnest($1::text[]) id ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "1176d102637cc13aed0121feb6f0d3799e150c099bcccbf1b809b00d075338f1"
-}
diff --git a/.sqlx/query-12bbf364a130b8f3af7e7bc7f8c64eb026124d2a66d2735b95ef387433cecd03.json b/.sqlx/query-12bbf364a130b8f3af7e7bc7f8c64eb026124d2a66d2735b95ef387433cecd03.json
deleted file mode 100644
index 8bcde4e677..0000000000
--- a/.sqlx/query-12bbf364a130b8f3af7e7bc7f8c64eb026124d2a66d2735b95ef387433cecd03.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT team_id\n FROM team_user\n WHERE user_id = $1\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "team_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "12bbf364a130b8f3af7e7bc7f8c64eb026124d2a66d2735b95ef387433cecd03"
-}
diff --git a/.sqlx/query-1c82e790d584a66621fce3191cb07d87e885c254bd4ef4d599511128a80a6f97.json b/.sqlx/query-1c82e790d584a66621fce3191cb07d87e885c254bd4ef4d599511128a80a6f97.json
deleted file mode 100644
index ceb4976bd6..0000000000
--- a/.sqlx/query-1c82e790d584a66621fce3191cb07d87e885c254bd4ef4d599511128a80a6f97.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO entity_access\n (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)\n VALUES ($1, $2, $3, 'team', 'edit', '20000000-0000-0000-0000-000000000001')",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "1c82e790d584a66621fce3191cb07d87e885c254bd4ef4d599511128a80a6f97"
-}
diff --git a/.sqlx/query-217acdbed6242ff0c4b45c2d2d20fabf7819587af3f045b0bbcd500b6f9c5107.json b/.sqlx/query-217acdbed6242ff0c4b45c2d2d20fabf7819587af3f045b0bbcd500b6f9c5107.json
deleted file mode 100644
index 32825ab260..0000000000
--- a/.sqlx/query-217acdbed6242ff0c4b45c2d2d20fabf7819587af3f045b0bbcd500b6f9c5107.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "ANALYZE",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": []
- },
- "nullable": []
- },
- "hash": "217acdbed6242ff0c4b45c2d2d20fabf7819587af3f045b0bbcd500b6f9c5107"
-}
diff --git a/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json b/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json
deleted file mode 100644
index 4ee3b36f55..0000000000
--- a/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT count(*) AS \"count!\"\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "count!",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5"
-}
diff --git a/.sqlx/query-29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559.json b/.sqlx/query-29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559.json
deleted file mode 100644
index bd3845876f..0000000000
--- a/.sqlx/query-29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT count(*) AS \"count!\" FROM codex_journal_input",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "count!",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- null
- ]
- },
- "hash": "29220fe53f53b9e4115cdfbfb8e7f33c640455ea42cba85759c8ab49f5c30559"
-}
diff --git a/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json b/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json
deleted file mode 100644
index de1be84b86..0000000000
--- a/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT deleted_at\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "deleted_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- true
- ]
- },
- "hash": "2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68"
-}
diff --git a/.sqlx/query-32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e.json b/.sqlx/query-32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e.json
deleted file mode 100644
index 2b0b8c1840..0000000000
--- a/.sqlx/query-32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO initiative (id, name, owner_user_id, share_permission_id)\n VALUES ($1, 'Test initiative', $2, $3)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "32829f5748c29623d263db1021e98216c9cea3186e3347d1b642681f4010a42e"
-}
diff --git a/.sqlx/query-33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a.json b/.sqlx/query-33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a.json
deleted file mode 100644
index 15ba714357..0000000000
--- a/.sqlx/query-33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE agent_session SET manager_fence = manager_fence + 1, pull_request_url = $2 WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "33fff12cd72c45f5eab2422f59bddd55ba85ed275f71feedd5eeda8727be9a3a"
-}
diff --git a/.sqlx/query-370a87eb4e8c69c5430716f06c0b23ec03e343c026d2e13ba7c4337fab85cd05.json b/.sqlx/query-370a87eb4e8c69c5430716f06c0b23ec03e343c026d2e13ba7c4337fab85cd05.json
deleted file mode 100644
index af1c40addb..0000000000
--- a/.sqlx/query-370a87eb4e8c69c5430716f06c0b23ec03e343c026d2e13ba7c4337fab85cd05.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM entity_access\n WHERE entity_id = $1\n AND entity_type = $2\n AND source_id = $3\n AND source_type = $4\n AND granted_from_project_id IS NULL\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- {
- "Custom": {
- "name": "entity_access_source_type",
- "kind": {
- "Enum": [
- "channel",
- "team",
- "user",
- "bot"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "370a87eb4e8c69c5430716f06c0b23ec03e343c026d2e13ba7c4337fab85cd05"
-}
diff --git a/.sqlx/query-3a1113165192ebbcfc408f47ac619aa213e32acb94b1d488e35a090e67c25cfa.json b/.sqlx/query-3a1113165192ebbcfc408f47ac619aa213e32acb94b1d488e35a090e67c25cfa.json
deleted file mode 100644
index 058e507bdb..0000000000
--- a/.sqlx/query-3a1113165192ebbcfc408f47ac619aa213e32acb94b1d488e35a090e67c25cfa.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO calendar_events (id, owner_id, source_link_id, ical_uid, title, starts_at, ends_at, canonical_source_kind) VALUES ($1, $2, $3, $4, 'calendar access', '2026-01-01', '2026-01-02', 'google') ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "3a1113165192ebbcfc408f47ac619aa213e32acb94b1d488e35a090e67c25cfa"
-}
diff --git a/.sqlx/query-3b2593c3b32464aeaf6a745998a2d899f543873636d1d45c69d5773f6722ab3c.json b/.sqlx/query-3b2593c3b32464aeaf6a745998a2d899f543873636d1d45c69d5773f6722ab3c.json
deleted file mode 100644
index 27f4d56242..0000000000
--- a/.sqlx/query-3b2593c3b32464aeaf6a745998a2d899f543873636d1d45c69d5773f6722ab3c.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values) VALUES ($1, $2, 'TASK', $3, $4) ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Uuid",
- "Jsonb"
- ]
- },
- "nullable": []
- },
- "hash": "3b2593c3b32464aeaf6a745998a2d899f543873636d1d45c69d5773f6722ab3c"
-}
diff --git a/.sqlx/query-3c24ed41ba475636af7da1ea9033cba24cfff815ba342cd53a2f3db3a4df775a.json b/.sqlx/query-3c24ed41ba475636af7da1ea9033cba24cfff815ba342cd53a2f3db3a4df775a.json
deleted file mode 100644
index ff4471fef2..0000000000
--- a/.sqlx/query-3c24ed41ba475636af7da1ea9033cba24cfff815ba342cd53a2f3db3a4df775a.json
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE calendar_events SET created_at = $1, updated_at = $2, last_reminder_fired_at = CASE WHEN id = $3 THEN $4::timestamptz ELSE NULL END WHERE id = ANY($5)",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Timestamptz",
- "Timestamptz",
- "Uuid",
- "Timestamptz",
- "UuidArray"
- ]
- },
- "nullable": []
- },
- "hash": "3c24ed41ba475636af7da1ea9033cba24cfff815ba342cd53a2f3db3a4df775a"
-}
diff --git a/.sqlx/query-42a7d2fb1eb1c98ae10f8375a262c48cb828e3c0ed342d0c2b090c2a69c62a2f.json b/.sqlx/query-42a7d2fb1eb1c98ae10f8375a262c48cb828e3c0ed342d0c2b090c2a69c62a2f.json
deleted file mode 100644
index 9335e3b082..0000000000
--- a/.sqlx/query-42a7d2fb1eb1c98ae10f8375a262c48cb828e3c0ed342d0c2b090c2a69c62a2f.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE call_records SET share_with_team = $2 WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Bool"
- ]
- },
- "nullable": []
- },
- "hash": "42a7d2fb1eb1c98ae10f8375a262c48cb828e3c0ed342d0c2b090c2a69c62a2f"
-}
diff --git a/.sqlx/query-44cc40d5175302af5445a34d4add1e7dc2d0cea3efa5b87c16cb2416b43fc098.json b/.sqlx/query-44cc40d5175302af5445a34d4add1e7dc2d0cea3efa5b87c16cb2416b43fc098.json
deleted file mode 100644
index 87ce24c182..0000000000
--- a/.sqlx/query-44cc40d5175302af5445a34d4add1e7dc2d0cea3efa5b87c16cb2416b43fc098.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- {
- "Custom": {
- "name": "entity_access_source_type",
- "kind": {
- "Enum": [
- "channel",
- "team",
- "user",
- "bot"
- ]
- }
- }
- },
- {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "44cc40d5175302af5445a34d4add1e7dc2d0cea3efa5b87c16cb2416b43fc098"
-}
diff --git a/.sqlx/query-4800f97cdff83b99d03f828d9498342b18aaa97974ac87cd3c68fd5bc90678c2.json b/.sqlx/query-4800f97cdff83b99d03f828d9498342b18aaa97974ac87cd3c68fd5bc90678c2.json
deleted file mode 100644
index 8f4416bf88..0000000000
--- a/.sqlx/query-4800f97cdff83b99d03f828d9498342b18aaa97974ac87cd3c68fd5bc90678c2.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT current_date::timestamptz + interval '12 hours' AS \"today!\"",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "today!",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- null
- ]
- },
- "hash": "4800f97cdff83b99d03f828d9498342b18aaa97974ac87cd3c68fd5bc90678c2"
-}
diff --git a/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json b/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json
deleted file mode 100644
index d45c527cb6..0000000000
--- a/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT created_at, updated_at\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "created_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 1,
- "name": "updated_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90"
-}
diff --git a/.sqlx/query-61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e.json b/.sqlx/query-61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e.json
deleted file mode 100644
index 7b5d1e14d2..0000000000
--- a/.sqlx/query-61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO agent_session (id, manager_replica_id, manager_fence) VALUES ($1, $2, 1)",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "61e0718ff0d4d5368e872a5bcd4a61f5786fdedc80a8acfb317e85efb74c1a3e"
-}
diff --git a/.sqlx/query-67548c84a432a8a3fc4b1da770f4fba29282314cae0933fc191f54b519220648.json b/.sqlx/query-67548c84a432a8a3fc4b1da770f4fba29282314cae0933fc191f54b519220648.json
deleted file mode 100644
index 145d7f3167..0000000000
--- a/.sqlx/query-67548c84a432a8a3fc4b1da770f4fba29282314cae0933fc191f54b519220648.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Document\" SET \"deletedAt\" = now() WHERE id = '11111111-0000-0000-0000-000000000000'",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": []
- },
- "nullable": []
- },
- "hash": "67548c84a432a8a3fc4b1da770f4fba29282314cae0933fc191f54b519220648"
-}
diff --git a/.sqlx/query-6f1e5783e442e0082571b5509505fe82f8b23f6f53c4bda18e9e656a6ca79c78.json b/.sqlx/query-6f1e5783e442e0082571b5509505fe82f8b23f6f53c4bda18e9e656a6ca79c78.json
deleted file mode 100644
index de099bf428..0000000000
--- a/.sqlx/query-6f1e5783e442e0082571b5509505fe82f8b23f6f53c4bda18e9e656a6ca79c78.json
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n cp.role::text as \"role?\",\n c.channel_type::text as \"channel_type!\",\n c.org_id as \"org_id?\",\n EXISTS (\n SELECT 1\n FROM team_user tu\n WHERE tu.user_id = $2 AND tu.team_id = c.team_id\n ) as \"is_team_member!\"\n FROM comms_channels c\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id AND cp.user_id = $2 AND cp.left_at IS NULL\n WHERE c.id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "role?",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "channel_type!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "org_id?",
- "type_info": "Int8"
- },
- {
- "ordinal": 3,
- "name": "is_team_member!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null,
- null,
- true,
- null
- ]
- },
- "hash": "6f1e5783e442e0082571b5509505fe82f8b23f6f53c4bda18e9e656a6ca79c78"
-}
diff --git a/.sqlx/query-70b4be41d99d2886193d0dbfd59ae89195b63a386a8e08891cc95afa4e7cd8cb.json b/.sqlx/query-70b4be41d99d2886193d0dbfd59ae89195b63a386a8e08891cc95afa4e7cd8cb.json
deleted file mode 100644
index e92ec7e950..0000000000
--- a/.sqlx/query-70b4be41d99d2886193d0dbfd59ae89195b63a386a8e08891cc95afa4e7cd8cb.json
+++ /dev/null
@@ -1,172 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": " \n WITH user_source_ids AS (\n SELECT cp.channel_id::text as source_id FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1\n ),\n UserAccessibleItems AS (\n SELECT DISTINCT\n ea.entity_id::text as item_id,\n ea.entity_type as item_type\n FROM entity_access ea\n WHERE ea.source_id = ANY(SELECT source_id FROM user_source_ids)\n ),\n Combined AS (\n SELECT\n 'document' as \"item_type!\",\n d.id as \"id!\",\n CAST(COALESCE(di.id, db.id) as TEXT) as \"document_version_id\",\n d.owner as \"user_id!\",\n d.name as \"name!\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"fileType\" as \"file_type\",\n d.\"createdAt\"::timestamptz as \"created_at!\",\n d.\"updatedAt\"::timestamptz as \"updated_at!\",\n d.\"projectId\" as \"project_id\",\n NULL as \"is_persistent\",\n NULL::text as \"model\",\n di.sha as \"sha\",\n dt.sub_type as \"sub_type?: DocumentSubType\",\n EXISTS (\n SELECT 1\n FROM document_email de\n WHERE de.document_id = d.id\n ) as \"is_email_attachment!\",\n (\n dt.sub_type IS DISTINCT FROM 'task'\n OR EXISTS (\n SELECT 1\n FROM entity_properties ep_assignees\n WHERE ep_assignees.entity_id = d.id\n AND ep_assignees.entity_type = 'TASK'\n AND ep_assignees.property_definition_id = $8\n AND ep_assignees.values->'value' @> jsonb_build_array(\n jsonb_build_object('entity_id', $1)\n )\n )\n ) as \"is_important!\",\n ARRAY(\n SELECT status_option_id::uuid\n FROM jsonb_array_elements_text(\n CASE\n WHEN jsonb_typeof(ep_status.values->'value') = 'array'\n THEN ep_status.values->'value'\n ELSE '[]'::jsonb\n END\n ) AS status_option_id\n ) as \"status_option_ids!: Vec<Uuid>\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", d.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN d.\"createdAt\"\n ELSE d.\"updatedAt\"\n END::timestamptz as \"sort_ts!\",\n CASE\n WHEN dt.sub_type = 'task'\n AND ep_status.values->'value' ? $6\n THEN true\n WHEN dt.sub_type = 'task'\n THEN false\n ELSE NULL\n END as \"is_completed\",\n d.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM \"Document\" d\n LEFT JOIN document_sub_type dt ON dt.document_id = d.id\n LEFT JOIN entity_properties ep_status\n ON dt.sub_type = 'task'\n AND ep_status.entity_id = d.id\n AND ep_status.entity_type = 'TASK'\n AND ep_status.property_definition_id = $7\n INNER JOIN UserAccessibleItems uai ON uai.item_id = d.id AND uai.item_type = 'document'\n -- This MUST be a LEFT JOIN to support all three sort methods\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = d.id AND uh.\"itemType\" = 'document' AND uh.\"userId\" = $1\n LEFT JOIN LATERAL (\n SELECT b.id\n FROM \"DocumentBom\" b\n WHERE b.\"documentId\" = d.id\n ORDER BY b.\"createdAt\" DESC\n LIMIT 1\n ) db ON true\n LEFT JOIN LATERAL (\n SELECT i.id, i.sha\n FROM \"DocumentInstance\" i\n WHERE i.\"documentId\" = d.id\n ORDER BY i.\"updatedAt\" DESC\n LIMIT 1\n ) di ON true\n WHERE d.\"deletedAt\" IS NULL\n\n UNION ALL\n\n SELECT\n 'chat' as \"item_type!\",\n c.id as \"id!\",\n NULL as \"document_version_id\",\n c.\"userId\" as \"user_id!\",\n c.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n c.\"createdAt\"::timestamptz as \"created_at!\",\n c.\"updatedAt\"::timestamptz as \"updated_at!\",\n c.\"projectId\" as \"project_id\",\n c.\"isPersistent\" as \"is_persistent\",\n c.model as \"model\",\n NULL as \"sha\",\n NULL as \"sub_type\",\n false as \"is_email_attachment!\",\n true as \"is_important!\",\n ARRAY[]::uuid[] as \"status_option_ids!: Vec<Uuid>\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", c.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN c.\"createdAt\"\n ELSE c.\"updatedAt\"\n END::timestamptz as \"sort_ts!\",\n NULL as \"is_completed\",\n c.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM \"Chat\" c\n INNER JOIN UserAccessibleItems uai ON uai.item_id = c.id AND uai.item_type = 'chat'\n LEFT JOIN \"UserHistory\" uh ON uh.\"itemId\" = c.id AND uh.\"itemType\" = 'chat' AND uh.\"userId\" = $1\n WHERE c.\"deletedAt\" IS NULL\n\n UNION ALL\n\n SELECT\n 'project' as \"item_type!\",\n p.id as \"id!\",\n NULL as \"document_version_id\",\n p.\"userId\" as \"user_id!\",\n p.name as \"name!\",\n NULL as \"branched_from_id\",\n NULL as \"branched_from_version_id\",\n NULL as \"document_family_id\",\n NULL as \"file_type\",\n p.\"createdAt\"::timestamptz as \"created_at!\",\n p.\"updatedAt\"::timestamptz as \"updated_at!\",\n p.\"parentId\" as \"project_id\",\n NULL as \"is_persistent\",\n NULL::text as \"model\",\n NULL as \"sha\",\n NULL as \"sub_type\",\n false as \"is_email_attachment!\",\n true as \"is_important!\",\n ARRAY[]::uuid[] as \"status_option_ids!: Vec<Uuid>\",\n uh.\"updatedAt\"::timestamptz as \"viewed_at\",\n CASE $2\n WHEN 'viewed_updated' THEN COALESCE(uh.\"updatedAt\", p.\"updatedAt\")\n WHEN 'viewed_at' THEN COALESCE(uh.\"updatedAt\", '1970-01-01 00:00:00+00')\n WHEN 'created_at' THEN p.\"createdAt\"\n ELSE p.\"updatedAt\"\n END::timestamptz as \"sort_ts!\",\n NULL as \"is_completed\",\n p.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM \"Project\" p\n INNER JOIN UserAccessibleItems uai\n ON uai.item_id = p.id\n AND uai.item_type = 'project'\n LEFT JOIN \"UserHistory\" uh\n ON uh.\"itemId\" = p.id\n AND uh.\"itemType\" = 'project'\n AND uh.\"userId\" = $1\n WHERE p.\"deletedAt\" IS NULL\n )\n SELECT Combined.* FROM Combined\n LEFT JOIN frecency_aggregates fa\n ON fa.entity_id = Combined.\"id!\"\n AND fa.entity_type = Combined.\"item_type!\"\n AND fa.user_id = $1\n WHERE fa.id IS NULL\n AND (\n ($4::timestamptz IS NULL)\n OR\n (Combined.\"sort_ts!\", Combined.\"id!\"::text) < ($4, $5)\n )\n ORDER BY Combined.\"sort_ts!\" DESC, Combined.\"id!\" DESC\n LIMIT $3\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "item_type!",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "id!",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "document_version_id",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "user_id!",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "name!",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "branched_from_id",
- "type_info": "Text"
- },
- {
- "ordinal": 6,
- "name": "branched_from_version_id",
- "type_info": "Int8"
- },
- {
- "ordinal": 7,
- "name": "document_family_id",
- "type_info": "Int8"
- },
- {
- "ordinal": 8,
- "name": "file_type",
- "type_info": "Text"
- },
- {
- "ordinal": 9,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 10,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 11,
- "name": "project_id",
- "type_info": "Text"
- },
- {
- "ordinal": 12,
- "name": "is_persistent",
- "type_info": "Bool"
- },
- {
- "ordinal": 13,
- "name": "model",
- "type_info": "Text"
- },
- {
- "ordinal": 14,
- "name": "sha",
- "type_info": "Text"
- },
- {
- "ordinal": 15,
- "name": "sub_type?: DocumentSubType",
- "type_info": {
- "Custom": {
- "name": "document_sub_type_value",
- "kind": {
- "Enum": [
- "task",
- "snippet",
- "skill"
- ]
- }
- }
- }
- },
- {
- "ordinal": 16,
- "name": "is_email_attachment!",
- "type_info": "Bool"
- },
- {
- "ordinal": 17,
- "name": "is_important!",
- "type_info": "Bool"
- },
- {
- "ordinal": 18,
- "name": "status_option_ids!: Vec<Uuid>",
- "type_info": "UuidArray"
- },
- {
- "ordinal": 19,
- "name": "viewed_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 20,
- "name": "sort_ts!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 21,
- "name": "is_completed",
- "type_info": "Bool"
- },
- {
- "ordinal": 22,
- "name": "deleted_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- "Int8",
- "Timestamptz",
- "Text",
- "Text",
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": [
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- ]
- },
- "hash": "70b4be41d99d2886193d0dbfd59ae89195b63a386a8e08891cc95afa4e7cd8cb"
-}
diff --git a/.sqlx/query-723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795.json b/.sqlx/query-723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795.json
deleted file mode 100644
index aa861305c0..0000000000
--- a/.sqlx/query-723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM entity_access WHERE entity_id = $1 AND source_id = 'channel'",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "723a35fb821b13c6a8d7f15a01c76d56dbe82baead3caa1b2221eebf38b60795"
-}
diff --git a/.sqlx/query-779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4.json b/.sqlx/query-779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4.json
deleted file mode 100644
index e027d61cf3..0000000000
--- a/.sqlx/query-779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'agent_session', 'owner', 'user', 'owner'),\n ($1, 'agent_session', 'channel', 'channel', 'view'),\n ($2, 'chat', 'channel', 'channel', 'view')\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "779de4a7cc33804f8284f0760483d2caebcd6d0711656d5f87f2d9133e249bf4"
-}
diff --git a/.sqlx/query-77b9642e3ce72202c80aacda76790b7a1e1eee80d0b7388c2ad68e8ce5a996c7.json b/.sqlx/query-77b9642e3ce72202c80aacda76790b7a1e1eee80d0b7388c2ad68e8ce5a996c7.json
deleted file mode 100644
index ce6db4c49c..0000000000
--- a/.sqlx/query-77b9642e3ce72202c80aacda76790b7a1e1eee80d0b7388c2ad68e8ce5a996c7.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT created_by as \"created_by!\"\n FROM (\n SELECT created_by FROM calls WHERE id = $1\n UNION ALL\n SELECT created_by FROM call_records WHERE id = $1\n ) t\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "created_by!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "77b9642e3ce72202c80aacda76790b7a1e1eee80d0b7388c2ad68e8ce5a996c7"
-}
diff --git a/.sqlx/query-35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38.json b/.sqlx/query-7a8672111c0c887bf1c2c873a478615fc42fed6f7769515edc0e025cc5c6d493.json
similarity index 64%
rename from .sqlx/query-35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38.json
rename to .sqlx/query-7a8672111c0c887bf1c2c873a478615fc42fed6f7769515edc0e025cc5c6d493.json
index 81582bc4ad..65bd7c0d9a 100644
--- a/.sqlx/query-35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38.json
+++ b/.sqlx/query-7a8672111c0c887bf1c2c873a478615fc42fed6f7769515edc0e025cc5c6d493.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, custom_name, summary, share_with_team\n FROM call_records\n WHERE id = $1\n ",
+ "query": "\n SELECT cr.id, cr.channel_id, cr.room_name, cr.created_by, cr.started_at, cr.ended_at, cr.duration_ms, cr.egress_id, cr.recording_key, cr.preview_url, cr.recording_started_at, cr.custom_name, cr.summary,\n sp.team_share_access_level AS \"team_share_access_level?: AccessLevel\"\n FROM call_records cr\n JOIN \"SharePermission\" sp ON sp.id = cr.share_permission_id\n WHERE cr.id = $1\n ",
"describe": {
"columns": [
{
@@ -70,8 +70,20 @@
},
{
"ordinal": 13,
- "name": "share_with_team",
- "type_info": "Bool"
+ "name": "team_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
}
],
"parameters": {
@@ -93,8 +105,8 @@
true,
true,
true,
- false
+ true
]
},
- "hash": "35d32d2785c724360d20f94c8f10207caec56d853493823994679a4b081a1c38"
+ "hash": "7a8672111c0c887bf1c2c873a478615fc42fed6f7769515edc0e025cc5c6d493"
}
diff --git a/.sqlx/query-7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724.json b/.sqlx/query-7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724.json
deleted file mode 100644
index e12c519a75..0000000000
--- a/.sqlx/query-7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM codex_journal_input WHERE agent_session_id = $1 AND sequence = 1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "7f8df32bcd378cdfce8fd1a1ae4ee44329f9729a9519f0cc6e24069978033724"
-}
diff --git a/.sqlx/query-87b606e8880ffd99d09bee637fa4b2942a6734ad3225b9104222cd930969cb8f.json b/.sqlx/query-87b606e8880ffd99d09bee637fa4b2942a6734ad3225b9104222cd930969cb8f.json
deleted file mode 100644
index 5bea1a5384..0000000000
--- a/.sqlx/query-87b606e8880ffd99d09bee637fa4b2942a6734ad3225b9104222cd930969cb8f.json
+++ /dev/null
@@ -1,118 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n i.id,\n i.name,\n i.description,\n i.owner_user_id,\n i.created_at,\n i.updated_at,\n i.share_permission_id,\n COALESCE(\n array_agg(DISTINCT m.user_id) FILTER (WHERE m.user_id IS NOT NULL),\n '{}'::text[]\n ) AS \"member_ids!\",\n COALESCE(\n array_agg(DISTINCT t.task_id) FILTER (WHERE t.task_id IS NOT NULL),\n '{}'::text[]\n ) AS \"task_ids!\",\n sp.\"linkShare\" AS \"link_share?\",\n sp.\"linkShareAccessLevel\" AS \"link_share_access_level?: AccessLevel\",\n sp.team_share_access_level AS \"team_share_access_level?: AccessLevel\",\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', channel.\"channel_id\",\n 'access_level', channel.\"access_level\"\n )) FILTER (WHERE channel.\"channel_id\" IS NOT NULL),\n '[]'\n ) AS \"channel_share_permissions?\"\n FROM initiative i\n JOIN \"SharePermission\" sp ON sp.id = i.share_permission_id\n LEFT JOIN initiative_member m ON m.initiative_id = i.id\n LEFT JOIN task_initiative t ON t.initiative_id = i.id\n LEFT JOIN \"ChannelSharePermission\" channel\n ON channel.\"share_permission_id\" = sp.id\n WHERE i.id = $1\n GROUP BY\n i.id,\n i.name,\n i.description,\n i.owner_user_id,\n i.created_at,\n i.updated_at,\n i.share_permission_id,\n sp.\"linkShare\",\n sp.\"linkShareAccessLevel\",\n sp.team_share_access_level\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "description",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "owner_user_id",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "created_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "updated_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "share_permission_id",
- "type_info": "Text"
- },
- {
- "ordinal": 7,
- "name": "member_ids!",
- "type_info": "TextArray"
- },
- {
- "ordinal": 8,
- "name": "task_ids!",
- "type_info": "TextArray"
- },
- {
- "ordinal": 9,
- "name": "link_share?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "link_share_access_level?: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- },
- {
- "ordinal": 11,
- "name": "team_share_access_level?: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- },
- {
- "ordinal": 12,
- "name": "channel_share_permissions?",
- "type_info": "Json"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- null,
- null,
- true,
- true,
- true,
- null
- ]
- },
- "hash": "87b606e8880ffd99d09bee637fa4b2942a6734ad3225b9104222cd930969cb8f"
-}
diff --git a/.sqlx/query-8dd1c5a77b6178a5b5378aa462c00edcbb4e00d28e4ad53db3eb66fafc20e337.json b/.sqlx/query-8dd1c5a77b6178a5b5378aa462c00edcbb4e00d28e4ad53db3eb66fafc20e337.json
deleted file mode 100644
index 4a7fa822e4..0000000000
--- a/.sqlx/query-8dd1c5a77b6178a5b5378aa462c00edcbb4e00d28e4ad53db3eb66fafc20e337.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider) VALUES ($1, $2, $2, $3, 'GMAIL') ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Varchar"
- ]
- },
- "nullable": []
- },
- "hash": "8dd1c5a77b6178a5b5378aa462c00edcbb4e00d28e4ad53db3eb66fafc20e337"
-}
diff --git a/.sqlx/query-8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda.json b/.sqlx/query-8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda.json
deleted file mode 100644
index de4402c04a..0000000000
--- a/.sqlx/query-8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO initiative_member (initiative_id, user_id)\n VALUES ($1, $2)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "8f46bd0e859d168c1886db023f992787e118795ab8d73238eb26de5d5d7a0dda"
-}
diff --git a/.sqlx/query-90832c95920a9b40329509f4ee611f765a6c10025c1b519f4a5d76ccfd64fb75.json b/.sqlx/query-90832c95920a9b40329509f4ee611f765a6c10025c1b519f4a5d76ccfd64fb75.json
deleted file mode 100644
index 696addd983..0000000000
--- a/.sqlx/query-90832c95920a9b40329509f4ee611f765a6c10025c1b519f4a5d76ccfd64fb75.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'document', $2, 'team', $3)\n ON CONFLICT DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "90832c95920a9b40329509f4ee611f765a6c10025c1b519f4a5d76ccfd64fb75"
-}
diff --git a/.sqlx/query-94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf.json b/.sqlx/query-94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf.json
deleted file mode 100644
index fc0bdcea7c..0000000000
--- a/.sqlx/query-94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE agent_session SET manager_fence = 2 WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "94d013b1e825cde114d7aaa34a70aa8df67805c659d3e694b1802064542800bf"
-}
diff --git a/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json b/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json
deleted file mode 100644
index 13f1afb64b..0000000000
--- a/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT now() AS \"now!\"",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "now!",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- null
- ]
- },
- "hash": "9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab"
-}
diff --git a/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json b/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json
deleted file mode 100644
index 61f2382a73..0000000000
--- a/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT owner_type AS \"owner_type: OwnerType\", owner_id, entity_type\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "owner_type: OwnerType",
- "type_info": {
- "Custom": {
- "name": "entity_owner_type",
- "kind": {
- "Enum": [
- "user",
- "bot",
- "team"
- ]
- }
- }
- }
- },
- {
- "ordinal": 1,
- "name": "owner_id",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "entity_type",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- false
- ]
- },
- "hash": "a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3"
-}
diff --git a/.sqlx/query-ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c.json b/.sqlx/query-ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c.json
deleted file mode 100644
index 9b16994f4d..0000000000
--- a/.sqlx/query-ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO \"SharePermission\" (\n \"id\",\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES ($1, $2, $3, NOW(), NOW())\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Text",
- {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- ]
- },
- "nullable": []
- },
- "hash": "ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c"
-}
diff --git a/.sqlx/query-b135b9523b42eab1c92a7d5cc4a425a6ce84d6f64b77cd1143d6a5ec4a3bd920.json b/.sqlx/query-b135b9523b42eab1c92a7d5cc4a425a6ce84d6f64b77cd1143d6a5ec4a3bd920.json
deleted file mode 100644
index 2062217e5a..0000000000
--- a/.sqlx/query-b135b9523b42eab1c92a7d5cc4a425a6ce84d6f64b77cd1143d6a5ec4a3bd920.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO \"DocumentInstance\" (id, \"documentId\", sha)\n SELECT 100 + ordinality, id, 'test' FROM unnest($1::text[]) WITH ORDINALITY AS ids(id, ordinality)\n ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "b135b9523b42eab1c92a7d5cc4a425a6ce84d6f64b77cd1143d6a5ec4a3bd920"
-}
diff --git a/.sqlx/query-b181eaf749c1a976dcde865659e0008923f4bc951a3de6cc02f8718246f244bf.json b/.sqlx/query-b181eaf749c1a976dcde865659e0008923f4bc951a3de6cc02f8718246f244bf.json
deleted file mode 100644
index 64c5ef09d8..0000000000
--- a/.sqlx/query-b181eaf749c1a976dcde865659e0008923f4bc951a3de6cc02f8718246f244bf.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT access_level AS \"access_level: AccessLevel\"\n FROM entity_access\n WHERE entity_id = $1 AND entity_type = $2 AND source_type = 'team'\n AND granted_from_project_id IS NOT NULL",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "b181eaf749c1a976dcde865659e0008923f4bc951a3de6cc02f8718246f244bf"
-}
diff --git a/.sqlx/query-b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05.json b/.sqlx/query-b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05.json
deleted file mode 100644
index 5e04a41879..0000000000
--- a/.sqlx/query-b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (\n entity_id,\n entity_type,\n source_id,\n source_type,\n access_level\n )\n VALUES ($1, 'initiative', $2, $3::text::entity_access_source_type, $4::text::\"AccessLevel\")\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "b3bbc6103dddd5d4842a8b17bea580471840667e2b3818f09c7415a0e499fb05"
-}
diff --git a/.sqlx/query-b451d4babb420eeec23aeb974b58046b8a0f612a3d6ea475c388bc7f4164d88a.json b/.sqlx/query-b451d4babb420eeec23aeb974b58046b8a0f612a3d6ea475c388bc7f4164d88a.json
new file mode 100644
index 0000000000..a88eb6d5b2
--- /dev/null
+++ b/.sqlx/query-b451d4babb420eeec23aeb974b58046b8a0f612a3d6ea475c388bc7f4164d88a.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"SharePermission\" (\n \"id\",\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES ($1, NULL, NULL, NOW(), NOW())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b451d4babb420eeec23aeb974b58046b8a0f612a3d6ea475c388bc7f4164d88a"
+}
diff --git a/.sqlx/query-b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952.json b/.sqlx/query-b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952.json
deleted file mode 100644
index 33bd537f50..0000000000
--- a/.sqlx/query-b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "WITH created AS (INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$3) RETURNING id) INSERT INTO \"User\" (\"id\", \"email\", \"macro_user_id\") SELECT $4,$2,id FROM created",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "b4b0e0ef222013f018def2ae2e765469b45bb25c99324b452533dabbf4ac2952"
-}
diff --git a/.sqlx/query-b55a16688355355ab26840343edf126c876002a8f90e4d6dc299f22a1a91e34c.json b/.sqlx/query-b55a16688355355ab26840343edf126c876002a8f90e4d6dc299f22a1a91e34c.json
deleted file mode 100644
index f9ec0a09c4..0000000000
--- a/.sqlx/query-b55a16688355355ab26840343edf126c876002a8f90e4d6dc299f22a1a91e34c.json
+++ /dev/null
@@ -1,122 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text AS source_id\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1 AS source_id\n ),\n visible_calls AS (\n SELECT\n c.id AS call_id,\n c.channel_id,\n c.room_name,\n c.created_by,\n c.created_at AS started_at,\n NULL::timestamptz AS ended_at,\n NULL::bigint AS duration_ms,\n c.egress_id,\n c.recording_key,\n c.preview_url,\n c.recording_started_at,\n NULL::text AS custom_name,\n NULL::text AS summary,\n c.share_with_team,\n true AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_participants cp\n WHERE cp.call_id = c.id AND cp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = c.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM calls c\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = c.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR c.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR c.id = ANY($6))\n AND ($9::bool IS FALSE OR (\n ($11::bool IS FALSE AND EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = c.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND jsonb_exists_any(ep.values -> 'value', $10::text[])\n ))\n OR ($11::bool IS TRUE AND $10::text[] <@ (\n SELECT COALESCE(array_agg(elem), ARRAY[]::text[])\n FROM (\n SELECT values FROM entity_properties\n WHERE entity_id = c.id::text\n AND entity_type = 'CALL_RECORD'\n AND jsonb_typeof(values -> 'value') = 'array'\n ) ep\n CROSS JOIN LATERAL jsonb_array_elements_text(ep.values -> 'value') AS elem\n ))\n ))\n UNION ALL\n SELECT\n cr.id AS call_id,\n cr.channel_id,\n cr.room_name,\n cr.created_by,\n cr.started_at,\n cr.ended_at,\n cr.duration_ms,\n cr.egress_id,\n cr.recording_key,\n cr.preview_url,\n cr.recording_started_at,\n cr.custom_name,\n cr.summary,\n cr.share_with_team,\n false AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = cr.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM call_records cr\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n )\n AND ($3::bool IS FALSE OR cr.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR cr.id = ANY($6))\n AND ($9::bool IS FALSE OR (\n ($11::bool IS FALSE AND EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = cr.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND jsonb_exists_any(ep.values -> 'value', $10::text[])\n ))\n OR ($11::bool IS TRUE AND $10::text[] <@ (\n SELECT COALESCE(array_agg(elem), ARRAY[]::text[])\n FROM (\n SELECT values FROM entity_properties\n WHERE entity_id = cr.id::text\n AND entity_type = 'CALL_RECORD'\n AND jsonb_typeof(values -> 'value') = 'array'\n ) ep\n CROSS JOIN LATERAL jsonb_array_elements_text(ep.values -> 'value') AS elem\n ))\n ))\n )\n SELECT\n call_id as \"call_id!\",\n channel_id as \"channel_id!\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n started_at as \"started_at!\",\n ended_at,\n duration_ms,\n egress_id,\n recording_key,\n preview_url,\n recording_started_at,\n custom_name,\n summary,\n share_with_team as \"share_with_team!\",\n is_active as \"is_active!\",\n status as \"status!\"\n FROM visible_calls\n WHERE ($7::bool IS FALSE OR status = ANY($8::text[]))\n ORDER BY \"started_at!\" DESC\n LIMIT $2\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "call_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "channel_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "room_name!",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "created_by!",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "started_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "ended_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "duration_ms",
- "type_info": "Int8"
- },
- {
- "ordinal": 7,
- "name": "egress_id",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "recording_key",
- "type_info": "Text"
- },
- {
- "ordinal": 9,
- "name": "preview_url",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "recording_started_at",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 11,
- "name": "custom_name",
- "type_info": "Text"
- },
- {
- "ordinal": 12,
- "name": "summary",
- "type_info": "Text"
- },
- {
- "ordinal": 13,
- "name": "share_with_team!",
- "type_info": "Bool"
- },
- {
- "ordinal": 14,
- "name": "is_active!",
- "type_info": "Bool"
- },
- {
- "ordinal": 15,
- "name": "status!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Int8",
- "Bool",
- "UuidArray",
- "Bool",
- "UuidArray",
- "Bool",
- "TextArray",
- "Bool",
- "TextArray",
- "Bool"
- ]
- },
- "nullable": [
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- ]
- },
- "hash": "b55a16688355355ab26840343edf126c876002a8f90e4d6dc299f22a1a91e34c"
-}
diff --git a/.sqlx/query-b792e97d62ad9366fb8d741745928f058306782e77dfc87af9ac77ea676a5692.json b/.sqlx/query-b792e97d62ad9366fb8d741745928f058306782e77dfc87af9ac77ea676a5692.json
deleted file mode 100644
index 093f305d25..0000000000
--- a/.sqlx/query-b792e97d62ad9366fb8d741745928f058306782e77dfc87af9ac77ea676a5692.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO \"Document\" (id, name, owner, \"createdAt\", \"updatedAt\")\n SELECT id, 'explain task', 'macro|[email protected]', '2026-01-01', '2026-01-02'\n FROM unnest($1::text[]) id ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "b792e97d62ad9366fb8d741745928f058306782e77dfc87af9ac77ea676a5692"
-}
diff --git a/.sqlx/query-cae308981be4bbd27dda7caa4ea5d737cc7c5a3215e01254f933a7acff92d3e4.json b/.sqlx/query-cae308981be4bbd27dda7caa4ea5d737cc7c5a3215e01254f933a7acff92d3e4.json
deleted file mode 100644
index c29c9ab7df..0000000000
--- a/.sqlx/query-cae308981be4bbd27dda7caa4ea5d737cc7c5a3215e01254f933a7acff92d3e4.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id) VALUES ('macro|[email protected]', 'macro|[email protected]', $1) ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "cae308981be4bbd27dda7caa4ea5d737cc7c5a3215e01254f933a7acff92d3e4"
-}
diff --git a/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json b/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json
deleted file mode 100644
index c0be316d98..0000000000
--- a/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity (id, entity_type, owner_type, owner_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, COALESCE($5::timestamptz, now()), COALESCE($6::timestamptz, now()))\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- {
- "Custom": {
- "name": "entity_owner_type",
- "kind": {
- "Enum": [
- "user",
- "bot",
- "team"
- ]
- }
- }
- },
- "Text",
- "Timestamptz",
- "Timestamptz"
- ]
- },
- "nullable": []
- },
- "hash": "d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e"
-}
diff --git a/.sqlx/query-df1f1d15d442789a5b9c81cdddf44d88d5748499cc48865023ddc1ff1587d0f6.json b/.sqlx/query-df1f1d15d442789a5b9c81cdddf44d88d5748499cc48865023ddc1ff1587d0f6.json
deleted file mode 100644
index 7fe6da3923..0000000000
--- a/.sqlx/query-df1f1d15d442789a5b9c81cdddf44d88d5748499cc48865023ddc1ff1587d0f6.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT version()",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "version",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- null
- ]
- },
- "hash": "df1f1d15d442789a5b9c81cdddf44d88d5748499cc48865023ddc1ff1587d0f6"
-}
diff --git a/.sqlx/query-e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7.json b/.sqlx/query-e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7.json
deleted file mode 100644
index 0a6d4630a5..0000000000
--- a/.sqlx/query-e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT count(*) AS \"count!\" FROM codex_cloud_sessions",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "count!",
- "type_info": "Int8"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- null
- ]
- },
- "hash": "e1341ead1be484ee3be0587914d7e0de341430b02176d966efa8af976ccdbbc7"
-}
diff --git a/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json b/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json
deleted file mode 100644
index a3ee67dabe..0000000000
--- a/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT owner_type AS \"owner_type: OwnerType\", owner_id\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "owner_type: OwnerType",
- "type_info": {
- "Custom": {
- "name": "entity_owner_type",
- "kind": {
- "Enum": [
- "user",
- "bot",
- "team"
- ]
- }
- }
- }
- },
- {
- "ordinal": 1,
- "name": "owner_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f"
-}
diff --git a/.sqlx/query-e313cb4b4f14331990417320890f6d1dcc9f4743dc4842edf3e3edd024678fce.json b/.sqlx/query-e313cb4b4f14331990417320890f6d1dcc9f4743dc4842edf3e3edd024678fce.json
deleted file mode 100644
index f19298e382..0000000000
--- a/.sqlx/query-e313cb4b4f14331990417320890f6d1dcc9f4743dc4842edf3e3edd024678fce.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO \"Document\" (id, name, owner, \"createdAt\", \"updatedAt\")\n SELECT id, 'pagination task', 'macro|[email protected]', '2026-01-01', '2026-01-02'\n FROM unnest($1::text[]) id ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "e313cb4b4f14331990417320890f6d1dcc9f4743dc4842edf3e3edd024678fce"
-}
diff --git a/.sqlx/query-e9e07eb22736f0e8855bc323cd978ad9132a45423ffd00ea0af27e6f191dfe95.json b/.sqlx/query-e9e07eb22736f0e8855bc323cd978ad9132a45423ffd00ea0af27e6f191dfe95.json
deleted file mode 100644
index 5bff4a9431..0000000000
--- a/.sqlx/query-e9e07eb22736f0e8855bc323cd978ad9132a45423ffd00ea0af27e6f191dfe95.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO frecency_aggregates (entity_id, entity_type, user_id, first_event) VALUES ($1, 'document', 'macro|[email protected]', now()) ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "e9e07eb22736f0e8855bc323cd978ad9132a45423ffd00ea0af27e6f191dfe95"
-}
diff --git a/.sqlx/query-c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785.json b/.sqlx/query-ee1117e0ccf274f7a2a3c3c69de2b4b414f926a97400e49ac990378a52cd7a4e.json
similarity index 58%
rename from .sqlx/query-c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785.json
rename to .sqlx/query-ee1117e0ccf274f7a2a3c3c69de2b4b414f926a97400e49ac990378a52cd7a4e.json
index 8a8e0cd1b2..4e3d1a86bd 100644
--- a/.sqlx/query-c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785.json
+++ b/.sqlx/query-ee1117e0ccf274f7a2a3c3c69de2b4b414f926a97400e49ac990378a52cd7a4e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, preview_url, recording_started_at, share_with_team\n FROM calls\n WHERE id = $1\n ",
+ "query": "\n SELECT c.id, c.channel_id, c.room_name, c.created_by, c.created_at, c.egress_id, c.recording_key, c.preview_url, c.recording_started_at,\n c.share_with_team,\n sp.team_share_access_level AS \"team_share_access_level?: AccessLevel\"\n FROM calls c\n JOIN \"SharePermission\" sp ON sp.id = c.share_permission_id\n WHERE c.id = $1\n ",
"describe": {
"columns": [
{
@@ -52,6 +52,23 @@
"ordinal": 9,
"name": "share_with_team",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 10,
+ "name": "team_share_access_level?: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
}
],
"parameters": {
@@ -69,8 +86,9 @@
true,
true,
true,
- false
+ false,
+ true
]
},
- "hash": "c30711e82376ca92d1e4e346334517c98cfa67d86663cd13575bec99ee24c785"
+ "hash": "ee1117e0ccf274f7a2a3c3c69de2b4b414f926a97400e49ac990378a52cd7a4e"
}
diff --git a/.sqlx/query-ee6275a42ff3150baf5cb1005548873c59f37658461064f986c0cd6369aa6119.json b/.sqlx/query-ee6275a42ff3150baf5cb1005548873c59f37658461064f986c0cd6369aa6119.json
deleted file mode 100644
index 5e3f43453d..0000000000
--- a/.sqlx/query-ee6275a42ff3150baf5cb1005548873c59f37658461064f986c0cd6369aa6119.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) SELECT id::uuid, 'document', 'macro|[email protected]', 'user', 'view' FROM unnest($1::text[]) id ON CONFLICT DO NOTHING",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": []
- },
- "hash": "ee6275a42ff3150baf5cb1005548873c59f37658461064f986c0cd6369aa6119"
-}
diff --git a/.sqlx/query-f4bf6e89d050cab822d5ff9a0ed992e69e9d253a5dc6440b0066dc542b8d7e07.json b/.sqlx/query-f4bf6e89d050cab822d5ff9a0ed992e69e9d253a5dc6440b0066dc542b8d7e07.json
deleted file mode 100644
index d68ac0ad08..0000000000
--- a/.sqlx/query-f4bf6e89d050cab822d5ff9a0ed992e69e9d253a5dc6440b0066dc542b8d7e07.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT access_level AS \"access_level: AccessLevel\"\n FROM entity_access\n WHERE entity_id = $1 AND entity_type = $2 AND source_type = 'team'\n AND source_id = $3 AND granted_from_project_id IS NULL\n ORDER BY access_level",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "f4bf6e89d050cab822d5ff9a0ed992e69e9d253a5dc6440b0066dc542b8d7e07"
-}
diff --git a/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json b/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json
deleted file mode 100644
index 1cb9540fe6..0000000000
--- a/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT entity_type\n FROM entity\n WHERE id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "entity_type",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c"
-}
diff --git a/.sqlx/query-fc0744ebeb842c69501102f111cb569a6f2b0c2fc0e62e5243a5857e054e61c7.json b/.sqlx/query-fc0744ebeb842c69501102f111cb569a6f2b0c2fc0e62e5243a5857e054e61c7.json
deleted file mode 100644
index d9a73c770f..0000000000
--- a/.sqlx/query-fc0744ebeb842c69501102f111cb569a6f2b0c2fc0e62e5243a5857e054e61c7.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT team_id\n FROM team_user\n WHERE user_id = $1\n LIMIT 1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "team_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "fc0744ebeb842c69501102f111cb569a6f2b0c2fc0e62e5243a5857e054e61c7"
-}
diff --git a/Cargo.lock b/Cargo.lock
index 1d397123b4..994c1ab5fd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3210,6 +3210,7 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
+ "share_permission_db_utils",
"sqlx",
"subtle",
"thiserror 2.0.18",
@@ -14916,6 +14917,7 @@ dependencies = [
"serde",
"serde_json",
"sha2 0.10.9",
+ "share_permission_db_utils",
"sqlx",
"sync_service_client",
"system_properties",
diff --git a/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx b/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx
index 8ff50965da..e13c18867b 100644
--- a/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx
+++ b/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx
@@ -5,11 +5,13 @@ import { SidePanel } from '@components/app/side-panel';
import { useBlockId } from '@core/block';
import { References } from '@core/component/References';
import { UserIcon } from '@core/component/UserIcon';
+import { useUserId } from '@core/context/user';
import { getDisplayName, tryMacroId } from '@core/user';
import { type DateValue, formatDate } from '@core/util/date';
import ClockIcon from '@phosphor/clock.svg';
import {
- useSetCallRecordShareWithTeamMutation,
+ isCallSharedWithTeam,
+ useSetCallRecordTeamShareMutation,
useToggleShareWithTeamMutation,
} from '@queries/call/call';
import { useAttachmentReferencesQuery } from '@queries/storage/attachment-references';
@@ -146,24 +148,30 @@ function DateValueDisplay(props: { value: DateValue }) {
function SharingSectionContent(props: { record: Accessor<CallRecord> }) {
const record = props.record;
const callCtx = useCallContextOptional();
- const toggleActiveShare = useToggleShareWithTeamMutation();
- const setArchivedShare = useSetCallRecordShareWithTeamMutation();
-
- const isShared = () => record().shareWithTeam;
- const isDisabled = () =>
- toggleActiveShare.isPending || setArchivedShare.isPending;
+ const userId = useUserId();
+ const toggleLiveShare = useToggleShareWithTeamMutation();
+ const setTeamShare = useSetCallRecordTeamShareMutation();
+
+ // While the call is live this is the pending toggle; once archived it is
+ // the canonical `SharePermission` team share (`view` or nothing).
+ const isShared = () => isCallSharedWithTeam(record());
+ // Any participant with edit access may flip the toggle during the call;
+ // once archived only the creator may change it (the backend enforces both).
+ const canEdit = () => record().isActive || record().createdBy === userId();
+ const isPending = () => toggleLiveShare.isPending || setTeamShare.isPending;
+ const isDisabled = () => isPending() || !canEdit();
const handleChange = async (checked: boolean) => {
const current = record();
try {
const newValue = current.isActive
- ? await toggleActiveShare.mutateAsync(current.callId)
+ ? await toggleLiveShare.mutateAsync(current.callId)
: (
- await setArchivedShare.mutateAsync({
+ await setTeamShare.mutateAsync({
callId: current.callId,
- shareWithTeam: checked,
+ shared: checked,
})
- ).shareWithTeam;
+ ).shared;
if (callCtx?.activeCallId() === current.callId) {
callCtx.setSharedWithTeam(newValue);
@@ -173,12 +181,25 @@ function SharingSectionContent(props: { record: Accessor<CallRecord> }) {
}
};
+ const description = () => {
+ if (record().isActive) {
+ return "Lets everyone on the creator's team view and search this call's transcript and AI summary once it ends.";
+ }
+ if (canEdit()) {
+ return "Lets everyone on your team view and search this call's transcript and AI summary.";
+ }
+ return isShared()
+ ? "Everyone on the creator's team can view and search this call's transcript and AI summary."
+ : "Only the call's creator can share it with their team.";
+ };
+
return (
<div class="flex flex-col gap-2 text-xs">
<button
type="button"
role="checkbox"
aria-checked={isShared()}
+ aria-readonly={!canEdit()}
disabled={isDisabled()}
onClick={() => void handleChange(!isShared())}
class={cn(
@@ -186,16 +207,14 @@ function SharingSectionContent(props: { record: Accessor<CallRecord> }) {
'border border-ink-muted/[0.08] bg-ink-muted/[0.025]',
'text-ink-muted/70 hover:text-ink hover:bg-ink-muted/[0.06]',
isShared() && 'text-ink',
- isDisabled() && 'pointer-events-none opacity-50'
+ isDisabled() && 'pointer-events-none',
+ isPending() && 'opacity-50'
)}
>
<InlineCheckbox checked={isShared()} />
<span class="whitespace-nowrap">Share with team</span>
</button>
- <p class="text-ink-muted leading-5">
- Lets everyone on your team view and search this call's transcript and AI
- summary.
- </p>
+ <p class="text-ink-muted leading-5">{description()}</p>
</div>
);
}
diff --git a/apps/web/src/features/channel/Call/CallContext.tsx b/apps/web/src/features/channel/Call/CallContext.tsx
index 8bd7e7dd7d..6f3e96d008 100644
--- a/apps/web/src/features/channel/Call/CallContext.tsx
+++ b/apps/web/src/features/channel/Call/CallContext.tsx
@@ -268,9 +268,10 @@ type CallStoreState = {
/** Which channel block has the Call tab selected (synced from channel UI). */
callPageChannelId: string | null;
backgroundEffect: BackgroundEffect;
- // Mirrors the call's `share_with_team` flag. Defaults to true to match the
- // server-side default for newly-created calls; synced from the toggle
- // endpoint's response on each flip.
+ // Mirrors the active call's pending share-with-team toggle (applied as
+ // canonical team sharing when the call is archived). Seeded from the call
+ // record once it loads and kept in sync by the
+ // `call_share_with_team_toggled` event and local toggles.
isSharedWithTeam: boolean;
};
@@ -295,7 +296,7 @@ const initialState: CallStoreState = {
joinError: null,
callPageChannelId: null,
backgroundEffect: { type: 'none' },
- isSharedWithTeam: true,
+ isSharedWithTeam: false,
};
// Persisted across reloads — background effect is a privacy preference users
@@ -431,9 +432,9 @@ export type CallState = {
backgroundEffect: () => BackgroundEffect;
/** Set the background effect (blur with intensity or image background) */
setBackgroundEffect: (effect: BackgroundEffect) => Promise<void>;
- /** Whether the call is currently shared with the creator's team */
+ /** Whether the active call is currently shared with the creator's team */
isSharedWithTeam: () => boolean;
- /** Update the locally-cached share-with-team flag (call after a toggle RPC) */
+ /** Update the locally-cached team-sharing flag (after a record load, an edit, or a sync event) */
setSharedWithTeam: (value: boolean) => void;
};
@@ -1207,7 +1208,6 @@ function createCallState() {
setRemoteParticipants: (participants) => {
setStore('remoteParticipants', participants);
},
- setSharedWithTeam: (value) => setStore('isSharedWithTeam', value),
clearOptimisticJoin: () => {
setStore('optimisticJoinChannelId', null);
setStore('joinError', null);
diff --git a/apps/web/src/features/channel/Call/CallControls/CallControlsPanelSmallRow.tsx b/apps/web/src/features/channel/Call/CallControls/CallControlsPanelSmallRow.tsx
index 749be06676..285455a2a3 100644
--- a/apps/web/src/features/channel/Call/CallControls/CallControlsPanelSmallRow.tsx
+++ b/apps/web/src/features/channel/Call/CallControls/CallControlsPanelSmallRow.tsx
@@ -10,7 +10,7 @@ import { Show } from 'solid-js';
import { match } from 'ts-pattern';
import { useCallContext } from '../CallContext';
import { CallDeviceList } from '../CallDeviceList';
-import { useToggleShareWithTeam } from '../use-toggle-share-with-team';
+import { useActiveCallTeamShare } from '../use-toggle-share-with-team';
import { MenuDivider, MenuLabel } from './CallMenuPrimitives';
const ITEM_ICON_CLASS = 'size-3.5 shrink-0 text-ink-muted';
@@ -18,7 +18,7 @@ const ITEM_ICON_CLASS = 'size-3.5 shrink-0 text-ink-muted';
export function CallControlsPanelSmallRow() {
const callCtx = useCallContext();
const isConnecting = () => callCtx.isConnecting();
- const handleToggleShareWithTeam = useToggleShareWithTeam();
+ const teamShare = useActiveCallTeamShare();
const noiseSuppressionModeLabel = () =>
match(callCtx.noiseSuppressionMode())
.with('krisp', () => 'Krisp')
@@ -144,7 +144,8 @@ export function CallControlsPanelSmallRow() {
<Dropdown.Item
closeOnSelect={false}
- onSelect={() => void handleToggleShareWithTeam()}
+ disabled={!teamShare.canToggle() || teamShare.isPending()}
+ onSelect={() => void teamShare.toggle()}
>
<InlineCheckbox checked={callCtx.isSharedWithTeam()} />
<span class="flex-1 truncate">Share with team</span>
diff --git a/apps/web/src/features/channel/Call/CallEventSync.tsx b/apps/web/src/features/channel/Call/CallEventSync.tsx
index 7b6cba3600..fc37198b6e 100644
--- a/apps/web/src/features/channel/Call/CallEventSync.tsx
+++ b/apps/web/src/features/channel/Call/CallEventSync.tsx
@@ -1,23 +1,26 @@
+import {
+ isCallSharedWithTeam,
+ setCallRecordTeamShareCache,
+ useCallRecordQuery,
+} from '@queries/call/call';
+import { createEffect } from 'solid-js';
import { useCallContext } from './CallContext';
import { createCallEventsEffect } from './call-events';
-/**
- * Applies connection-gateway events that mutate active-call state held in
- * `CallContext`. Must be rendered inside `<CallProvider />`.
- *
- * Handled events:
- * - `call_share_with_team_toggled` — keeps `isSharedWithTeam` in sync when
- * the flag is flipped by another participant (or by the same user on a
- * different device). Skipped when the payload's `call_id` does not match
- * the currently active call, since the flag is only tracked while the
- * user is in that call.
- */
export function CallEventSync() {
const callCtx = useCallContext();
+ const record = useCallRecordQuery(() => callCtx.activeCallId() ?? '');
+
+ createEffect(() => {
+ const current = record.data;
+ if (!current || current.callId !== callCtx.activeCallId()) return;
+ callCtx.setSharedWithTeam(isCallSharedWithTeam(current));
+ });
createCallEventsEffect({
onShareWithTeamToggled: ({ callId, shareWithTeam }) => {
if (callId !== callCtx.activeCallId()) return;
+ setCallRecordTeamShareCache(callId, shareWithTeam);
callCtx.setSharedWithTeam(shareWithTeam);
},
});
diff --git a/apps/web/src/features/channel/Call/CallOverlay.tsx b/apps/web/src/features/channel/Call/CallOverlay.tsx
index de80c9fa41..92fb5beed7 100644
--- a/apps/web/src/features/channel/Call/CallOverlay.tsx
+++ b/apps/web/src/features/channel/Call/CallOverlay.tsx
@@ -15,7 +15,7 @@ import {
import { LK_TRACK_SOURCE } from './livekit-loader';
import { MutedMicrophoneBadge } from './MutedMicrophoneBadge';
import { TrackView } from './TrackView';
-import { useToggleShareWithTeam } from './use-toggle-share-with-team';
+import { useActiveCallTeamShare } from './use-toggle-share-with-team';
function VideoTag(props: {
children: JSXElement;
@@ -224,7 +224,9 @@ export function CallOverlay(props: { onLeave: () => void }) {
const currentUserId = useUserId();
const currentUserName = useAuthor();
const isConnecting = () => callCtx.isConnecting();
- const handleToggleShareWithTeam = useToggleShareWithTeam();
+ const teamShare = useActiveCallTeamShare();
+ const teamShareLocked = () =>
+ isConnecting() || !teamShare.canToggle() || teamShare.isPending();
const splitPanel = useSplitPanel();
const panelWidth = () => splitPanel?.panelSize.width ?? Infinity;
@@ -354,14 +356,14 @@ export function CallOverlay(props: { onLeave: () => void }) {
placement="top"
label={
callCtx.isSharedWithTeam()
- ? 'Everyone can view the transcript and AI summary'
- : 'Let everyone view the transcript and AI summary'
+ ? "The creator's team can view the transcript and AI summary once the call ends"
+ : "Let the creator's team view the transcript and AI summary once the call ends"
}
>
<button
type="button"
- onClick={() => void handleToggleShareWithTeam()}
- disabled={isConnecting()}
+ onClick={() => void teamShare.toggle()}
+ disabled={teamShareLocked()}
role="checkbox"
aria-checked={callCtx.isSharedWithTeam()}
class={cn(
@@ -369,7 +371,7 @@ export function CallOverlay(props: { onLeave: () => void }) {
'border border-ink-muted/[0.08] bg-ink-muted/[0.025]',
'text-ink-muted/70 hover:text-ink hover:bg-ink-muted/[0.06]',
callCtx.isSharedWithTeam() && 'text-ink',
- isConnecting() && 'pointer-events-none opacity-50'
+ teamShareLocked() && 'pointer-events-none opacity-50'
)}
>
<InlineCheckbox checked={callCtx.isSharedWithTeam()} />
diff --git a/apps/web/src/features/channel/Call/LivekitJsCallController.ts b/apps/web/src/features/channel/Call/LivekitJsCallController.ts
index 0e9738e2d0..e47e1c26fe 100644
--- a/apps/web/src/features/channel/Call/LivekitJsCallController.ts
+++ b/apps/web/src/features/channel/Call/LivekitJsCallController.ts
@@ -32,7 +32,6 @@ type LivekitJsCallControllerOptions = {
setDuplicateConnectCallId: (callId: string) => void;
setInitialMediaState: () => void;
setRemoteParticipants: (participants: Map<string, RemoteParticipant>) => void;
- setSharedWithTeam: (value: boolean) => void;
clearOptimisticJoin: () => void;
bumpTrackVersion: () => void;
bumpSpeakerVersion: () => void;
@@ -152,7 +151,6 @@ export function createLivekitJsCallController(
attachRoomListeners(targetRoom);
options.setRoom(targetRoom);
options.setActiveCall(tokenResponse.channelId, tokenResponse.callId);
- options.setSharedWithTeam(true);
try {
await targetRoom.connect(tokenResponse.serverUrl, tokenResponse.token);
diff --git a/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx b/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx
index 4b04fbe916..ab2b0dc0a3 100644
--- a/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx
+++ b/apps/web/src/features/channel/Call/tests/call-overlay-muted.test.tsx
@@ -59,7 +59,11 @@ vi.mock('../TrackView', () => ({
}));
vi.mock('../use-toggle-share-with-team', () => ({
- useToggleShareWithTeam: () => () => undefined,
+ useActiveCallTeamShare: () => ({
+ toggle: () => Promise.resolve(),
+ canToggle: () => true,
+ isPending: () => false,
+ }),
}));
type MockTrackPublication = {
diff --git a/apps/web/src/features/channel/Call/use-toggle-share-with-team.ts b/apps/web/src/features/channel/Call/use-toggle-share-with-team.ts
index e1972852e7..d2d7809abf 100644
--- a/apps/web/src/features/channel/Call/use-toggle-share-with-team.ts
+++ b/apps/web/src/features/channel/Call/use-toggle-share-with-team.ts
@@ -2,17 +2,26 @@ import { useToggleShareWithTeamMutation } from '@queries/call/call';
import { useCallContext } from './CallContext';
/**
- * Returns a handler that flips the active call's `shared_with_team` flag and
- * mirrors the new value into the local call store. No-op when there's no
- * active call.
+ * Team sharing controls for the active call.
+ *
+ * `toggle` flips the live call's share-with-team toggle through
+ * `POST /call/record/{id}/share-with-team/toggle` and mirrors the new value
+ * into the local call store. Any participant with edit access may flip it;
+ * the toggle becomes canonical team sharing (view for the creator's team)
+ * when the call is archived. No-op when there's no active call.
*/
-export function useToggleShareWithTeam() {
+export function useActiveCallTeamShare() {
const callCtx = useCallContext();
const mutation = useToggleShareWithTeamMutation();
- return async () => {
+
+ const canToggle = () => callCtx.activeCallId() !== null;
+
+ const toggle = async () => {
const callId = callCtx.activeCallId();
if (!callId) return;
const newValue = await mutation.mutateAsync(callId);
callCtx.setSharedWithTeam(newValue);
};
+
+ return { toggle, canToggle, isPending: () => mutation.isPending };
}
diff --git a/apps/web/src/lib/queries/call/call.test.ts b/apps/web/src/lib/queries/call/call.test.ts
index 936191ab8a..27e306e5be 100644
--- a/apps/web/src/lib/queries/call/call.test.ts
+++ b/apps/web/src/lib/queries/call/call.test.ts
@@ -16,7 +16,14 @@ vi.mock('@core/component/Toast/Toast', () => ({
vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLS: true }));
import { queryClient } from '@queries/client';
-import { setActiveCallEndedCache, setActiveCallStartedCache } from './call';
+import type { CallRecord } from '@service-storage/generated/schemas/callRecord';
+import {
+ buildCallTeamSharePayload,
+ isCallSharedWithTeam,
+ setActiveCallEndedCache,
+ setActiveCallStartedCache,
+ setCallRecordTeamShareCache,
+} from './call';
import { callKeys } from './keys';
const summary = (over: Partial<ActiveCallSummary>): ActiveCallSummary => ({
@@ -85,3 +92,132 @@ describe('active call cache writers', () => {
).toBeNull();
});
});
+
+const record = (over: Partial<CallRecord>): CallRecord => ({
+ callId: 'call-1',
+ channelId: 'channel-1',
+ createdBy: 'macro|[email protected]',
+ isActive: false,
+ participants: [],
+ roomName: 'room',
+ startedAt: '2026-08-21T09:00:00.000Z',
+ transcript: [],
+ teamShareAccessLevel: null,
+ shareWithTeam: false,
+ ...over,
+});
+
+describe('call team sharing helpers', () => {
+ beforeEach(() => {
+ queryClient.clear();
+ });
+
+ it('buildCallTeamSharePayload maps the checkbox to view or an explicit clear', () => {
+ // Calls only ever share at `view`; `null` (not an omitted field) revokes.
+ expect(buildCallTeamSharePayload(true)).toEqual({
+ teamShareAccessLevel: 'view',
+ });
+ expect(buildCallTeamSharePayload(false)).toEqual({
+ teamShareAccessLevel: null,
+ });
+ });
+
+ it('isCallSharedWithTeam covers the live toggle and the archived canonical grant', () => {
+ // Live: the pending toggle, no canonical level yet.
+ expect(
+ isCallSharedWithTeam(
+ record({
+ isActive: true,
+ shareWithTeam: true,
+ teamShareAccessLevel: null,
+ })
+ )
+ ).toBe(true);
+ // Archived: the boolean mirrors the canonical level.
+ expect(
+ isCallSharedWithTeam(
+ record({
+ isActive: false,
+ shareWithTeam: true,
+ teamShareAccessLevel: 'view',
+ })
+ )
+ ).toBe(true);
+ expect(
+ isCallSharedWithTeam(
+ record({
+ isActive: false,
+ shareWithTeam: false,
+ teamShareAccessLevel: null,
+ })
+ )
+ ).toBe(false);
+ });
+
+ it('setCallRecordTeamShareCache updates the level and flag together for archived calls', () => {
+ const key = callKeys.record('call-1').queryKey;
+ queryClient.setQueryData(key, record({}));
+
+ setCallRecordTeamShareCache('call-1', true);
+ expect(queryClient.getQueryData<CallRecord>(key)).toMatchObject({
+ teamShareAccessLevel: 'view',
+ shareWithTeam: true,
+ });
+
+ setCallRecordTeamShareCache('call-1', false);
+ expect(queryClient.getQueryData<CallRecord>(key)).toMatchObject({
+ teamShareAccessLevel: null,
+ shareWithTeam: false,
+ });
+ });
+
+ it('setCallRecordTeamShareCache only flips the toggle for live calls', () => {
+ const key = callKeys.record('call-live').queryKey;
+ queryClient.setQueryData(
+ key,
+ record({ callId: 'call-live', isActive: true, shareWithTeam: false })
+ );
+
+ setCallRecordTeamShareCache('call-live', true);
+ expect(queryClient.getQueryData<CallRecord>(key)).toMatchObject({
+ shareWithTeam: true,
+ teamShareAccessLevel: null,
+ });
+ });
+
+ it('setCallRecordTeamShareCache leaves an unloaded record alone', () => {
+ setCallRecordTeamShareCache('missing', true);
+ expect(
+ queryClient.getQueryData(callKeys.record('missing').queryKey)
+ ).toBeUndefined();
+ });
+
+ it('setCallRecordTeamShareCache drops a late record fetch', async () => {
+ const key = callKeys.record('call-live').queryKey;
+ queryClient.setQueryData(
+ key,
+ record({ callId: 'call-live', isActive: true, shareWithTeam: false })
+ );
+
+ let resolveFetch: (value: CallRecord) => void = () => {};
+ const pending = new Promise<CallRecord>((resolve) => {
+ resolveFetch = resolve;
+ });
+ const fetchResult = queryClient.fetchQuery({
+ queryKey: key,
+ staleTime: 0,
+ retry: false,
+ queryFn: () => pending,
+ });
+
+ setCallRecordTeamShareCache('call-live', true);
+ resolveFetch(
+ record({ callId: 'call-live', isActive: true, shareWithTeam: false })
+ );
+ await fetchResult.catch(() => undefined);
+
+ expect(queryClient.getQueryData<CallRecord>(key)).toMatchObject({
+ shareWithTeam: true,
+ });
+ });
+});
diff --git a/apps/web/src/lib/queries/call/call.ts b/apps/web/src/lib/queries/call/call.ts
index ff07eca3f0..8759a121e7 100644
--- a/apps/web/src/lib/queries/call/call.ts
+++ b/apps/web/src/lib/queries/call/call.ts
@@ -5,6 +5,7 @@ import { queryClient } from '@queries/client';
import { type CallRecord, callServiceClient } from '@service-call/client';
import type { ActiveCallSummary } from '@service-storage/generated/schemas/activeCallSummary';
import type { CallActiveResponse } from '@service-storage/generated/schemas/callActiveResponse';
+import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { callKeys } from './keys';
@@ -145,6 +146,7 @@ export function useCallRecordQuery(callId: Accessor<string>) {
// primed record from triggering an immediate duplicate fetch on mount.
// Mutations still invalidate, so sharing edits stay reactive.
staleTime: 60_000,
+ enabled: callId().length > 0,
}));
}
@@ -160,16 +162,40 @@ export function fetchCallRecord(
});
}
-export function setCallRecordShareWithTeamCache(
- callId: string,
- shareWithTeam: boolean
-) {
- queryClient.setQueryData<CallRecord>(
- callKeys.record(callId).queryKey,
- (prev) => {
- if (!prev) return prev;
- return { ...prev, shareWithTeam };
- }
+/**
+ * Whether a call is shared with its creator's team: the pending toggle while
+ * the call is live, the canonical `view` grant once it is archived.
+ */
+export function isCallSharedWithTeam(record: CallRecord): boolean {
+ return record.shareWithTeam;
+}
+
+/** The `sharePermission` patch that shares a call with the team, or revokes it. */
+export function buildCallTeamSharePayload(
+ shared: boolean
+): Pick<UpdateSharePermissionRequestV2, 'teamShareAccessLevel'> {
+ return { teamShareAccessLevel: shared ? 'view' : null };
+}
+
+function patchCachedCallTeamShare(
+ record: CallRecord,
+ shared: boolean
+): CallRecord {
+ return {
+ ...record,
+ shareWithTeam: shared,
+ teamShareAccessLevel: record.isActive
+ ? record.teamShareAccessLevel
+ : buildCallTeamSharePayload(shared).teamShareAccessLevel,
+ };
+}
+
+export function setCallRecordTeamShareCache(callId: string, shared: boolean) {
+ const queryKey = callKeys.record(callId).queryKey;
+ // Drop in-flight GETs so a slower record response cannot overwrite this write.
+ void queryClient.cancelQueries({ queryKey });
+ queryClient.setQueryData<CallRecord>(queryKey, (prev) =>
+ prev ? patchCachedCallTeamShare(prev, shared) : prev
);
}
@@ -177,34 +203,48 @@ function invalidateCallRecord(callId: string) {
queryClient.invalidateQueries({ queryKey: callKeys.record(callId).queryKey });
}
-export function useSetCallRecordShareWithTeamMutation() {
+/**
+ * Flip the live call's share-with-team toggle. Any participant with edit
+ * access may do this; the toggle is applied as canonical team sharing when
+ * the call is archived.
+ */
+export function useToggleShareWithTeamMutation() {
return useMutation(() => ({
gcTime: 0,
- mutationFn: async (params: { callId: string; shareWithTeam: boolean }) => {
- await throwOnErr(() => callServiceClient.editCallRecord(params));
- return params;
- },
- onSuccess({ callId, shareWithTeam }) {
- setCallRecordShareWithTeamCache(callId, shareWithTeam);
+ mutationFn: (callId: string) =>
+ throwOnErr(() => callServiceClient.toggleShareWithTeam(callId)),
+ onSuccess(newValue, callId) {
+ setCallRecordTeamShareCache(callId, newValue);
invalidateCallRecord(callId);
},
onError(error: Error) {
- console.error('failed to set share with team', error);
+ console.error('failed to toggle share with team', error);
},
}));
}
-export function useToggleShareWithTeamMutation() {
+/**
+ * Share an archived call with the creator's team, or revoke it. Only the
+ * creator may change this; the backend answers 403 otherwise.
+ */
+export function useSetCallRecordTeamShareMutation() {
return useMutation(() => ({
gcTime: 0,
- mutationFn: (callId: string) =>
- throwOnErr(() => callServiceClient.toggleShareWithTeam(callId)),
- onSuccess(newValue, callId) {
- setCallRecordShareWithTeamCache(callId, newValue);
+ mutationFn: async (params: { callId: string; shared: boolean }) => {
+ await throwOnErr(() =>
+ callServiceClient.editCallRecord({
+ callId: params.callId,
+ sharePermission: buildCallTeamSharePayload(params.shared),
+ })
+ );
+ return params;
+ },
+ onSuccess({ callId, shared }) {
+ setCallRecordTeamShareCache(callId, shared);
invalidateCallRecord(callId);
},
onError(error: Error) {
- console.error('failed to toggle share with team', error);
+ console.error('failed to update call team sharing', error);
},
}));
}
diff --git a/apps/web/src/lib/service-clients/service-call/client.ts b/apps/web/src/lib/service-clients/service-call/client.ts
index 5d0dd4ff15..385810b462 100644
--- a/apps/web/src/lib/service-clients/service-call/client.ts
+++ b/apps/web/src/lib/service-clients/service-call/client.ts
@@ -5,7 +5,9 @@ import type { ActiveCallsResponse } from '@service-storage/generated/schemas/act
import type { CallActiveResponse } from '@service-storage/generated/schemas/callActiveResponse';
import type { CallRecord } from '@service-storage/generated/schemas/callRecord';
import type { CallTokenResponse } from '@service-storage/generated/schemas/callTokenResponse';
+import type { EditCallRecordRequest } from '@service-storage/generated/schemas/editCallRecordRequest';
import type { LeaveCallResponse } from '@service-storage/generated/schemas/leaveCallResponse';
+import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';
export type { CallRecord, CallTokenResponse };
@@ -65,6 +67,12 @@ export const callServiceClient = {
).map(() => undefined);
},
+ /**
+ * `POST /call/record/{id}/share-with-team/toggle`: flips the live call's
+ * share-with-team toggle and returns the new value. The toggle becomes
+ * canonical team sharing (view for the creator's team) when the call is
+ * archived; archived calls answer 409 and are edited via `editCallRecord`.
+ */
async toggleShareWithTeam(callId: string) {
// fetchWithToken requires T extends ObjectLike, but this endpoint returns a
// primitive JSON boolean. response.json() parses it correctly at runtime;
@@ -76,15 +84,21 @@ export const callServiceClient = {
return result.map((r) => r as unknown as boolean);
},
+ /**
+ * `PATCH /call/record/{id}`. Team sharing goes through
+ * `sharePermission.teamShareAccessLevel`, capped at `'view'` (`null`
+ * revokes). While the call is live it sets the pending toggle; once the
+ * call is archived the backend authorizes it against the call's creator.
+ */
async editCallRecord(params: {
callId: string;
customName?: string;
- shareWithTeam?: boolean;
+ sharePermission?: UpdateSharePermissionRequestV2;
}) {
- const body: { customName?: string; shareWithTeam?: boolean } = {};
+ const body: EditCallRecordRequest = {};
if (params.customName !== undefined) body.customName = params.customName;
- if (params.shareWithTeam !== undefined)
- body.shareWithTeam = params.shareWithTeam;
+ if (params.sharePermission !== undefined)
+ body.sharePermission = params.sharePermission;
return (
await fetchWithToken<Record<string, never>>(
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecord.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecord.ts
index ddb40bb124..daa0ac94e6 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecord.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecord.ts
@@ -15,6 +15,7 @@ import type { CallRecordRecordingStartedAt } from './callRecordRecordingStartedA
import type { CallRecordRecordingUrl } from './callRecordRecordingUrl';
import type { CallRecordStatus } from './callRecordStatus';
import type { CallRecordSummary } from './callRecordSummary';
+import type { CallRecordTeamShareAccessLevel } from './callRecordTeamShareAccessLevel';
import type { CallRecordTranscriptSegment } from './callRecordTranscriptSegment';
import type { CallRecordUserAccessLevel } from './callRecordUserAccessLevel';
@@ -55,7 +56,9 @@ this value when present, falling back to `started_at` otherwise. */
recordingUrl?: CallRecordRecordingUrl;
/** The RTC room name. */
roomName: string;
- /** Whether the call is shared with the creator's team. */
+ /** Whether the call is shared with the creator's team. While the call is
+live this is the pending toggle applied at archive; afterwards it
+mirrors `team_share_access_level`. */
shareWithTeam: boolean;
/** When the call started (created_at for active, started_at for archived). */
startedAt: string;
@@ -63,6 +66,7 @@ this value when present, falling back to `started_at` otherwise. */
/** AI-generated summary of the call. Only set on archived `call_records`
once summarization has run; active calls always return `None`. */
summary?: CallRecordSummary;
+ teamShareAccessLevel?: CallRecordTeamShareAccessLevel;
/** Transcript segments ordered by `sequence_num`. */
transcript: CallRecordTranscriptSegment[];
userAccessLevel?: CallRecordUserAccessLevel;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecordTeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecordTeamShareAccessLevel.ts
new file mode 100644
index 0000000000..5fc0096db0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/callRecordTeamShareAccessLevel.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AccessLevel } from './accessLevel';
+
+export type CallRecordTeamShareAccessLevel = null | AccessLevel;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequest.ts
index 8c80cf83f1..542bb7f852 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequest.ts
@@ -9,7 +9,7 @@ import type { EditCallRecordRequestSharePermission } from './editCallRecordReque
import type { EditCallRecordRequestShareWithTeam } from './editCallRecordRequestShareWithTeam';
/**
- * Edit call request
+ * Edit call request, as supplied by inbound callers.
*/
export interface EditCallRecordRequest {
/** Updated user-supplied display name for the call. `None` is a no-op;
@@ -19,8 +19,9 @@ this column — patching while the call is still active is a no-op for
this field. */
customName?: EditCallRecordRequestCustomName;
sharePermission?: EditCallRecordRequestSharePermission;
- /** If `Some(true)`, grant the creator's team View access on the call.
-If `Some(false)`, revoke the creator's team's access. `None` is a no-op.
+ /** Deprecated alias for `sharePermission.teamShareAccessLevel`:
+`Some(true)` behaves like `"view"`, `Some(false)` like `null`, and
+`None` is a no-op. Supplying both with disagreeing values is rejected.
The team is resolved from the call's `created_by`, not the acting user. */
shareWithTeam?: EditCallRecordRequestShareWithTeam;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequestShareWithTeam.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequestShareWithTeam.ts
index 9fae93610d..136eabb675 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequestShareWithTeam.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/editCallRecordRequestShareWithTeam.ts
@@ -6,8 +6,9 @@
*/
/**
- * If `Some(true)`, grant the creator's team View access on the call.
-If `Some(false)`, revoke the creator's team's access. `None` is a no-op.
+ * Deprecated alias for `sharePermission.teamShareAccessLevel`:
+`Some(true)` behaves like `"view"`, `Some(false)` like `null`, and
+`None` is a no-op. Supplying both with disagreeing values is rejected.
The team is resolved from the call's `created_by`, not the acting user.
*/
export type EditCallRecordRequestShareWithTeam = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index dcd252a117..6ad504d1fc 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -269,6 +269,7 @@ export * from './callRecordRecordingStartedAt';
export * from './callRecordRecordingUrl';
export * from './callRecordStatus';
export * from './callRecordSummary';
+export * from './callRecordTeamShareAccessLevel';
export * from './callRecordTranscriptSegment';
export * from './callRecordTranscriptSegmentDiarizedSpeakerId';
export * from './callRecordTranscriptSegmentEndedAt';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 946ebd1c86..768849f28c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -1932,7 +1932,9 @@ export const getCallRecordResponse = zod
roomName: zod.string().describe('The RTC room name.'),
shareWithTeam: zod
.boolean()
- .describe("Whether the call is shared with the creator's team."),
+ .describe(
+ "Whether the call is shared with the creator's team. While the call is\nlive this is the pending toggle applied at archive; afterwards it\nmirrors `team_share_access_level`."
+ ),
startedAt: zod.iso
.datetime({})
.describe(
@@ -1954,6 +1956,14 @@ export const getCallRecordResponse = zod
.describe(
'AI-generated summary of the call. Only set on archived `call_records`\nonce summarization has run; active calls always return `None`.'
),
+ teamShareAccessLevel: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ ])
+ .optional(),
transcript: zod
.array(
zod
@@ -2008,8 +2018,11 @@ export const deleteCallRecordParams = zod.object({
});
/**
- * Edits a call record — currently supports updating the record's share
-permissions. Access is validated via channel membership
+ * Edits a call record: link/channel share permissions, display name, and
+team sharing. Edit access (channel membership) is required for the request.
+`sharePermission.teamShareAccessLevel` only accepts `view` or `null`; while
+the call is live it sets the pending share-with-team toggle, and once the
+call is archived it is additionally authorized against the call's creator.
* @summary Handler for `PATCH /call/record/{call_id}`.
*/
export const editCallRecordParams = zod.object({
@@ -2082,14 +2095,16 @@ export const editCallRecordBody = zod
.boolean()
.nullish()
.describe(
- "If `Some(true)`, grant the creator's team View access on the call.\nIf `Some(false)`, revoke the creator's team's access. `None` is a no-op.\nThe team is resolved from the call's `created_by`, not the acting user."
+ 'Deprecated alias for `sharePermission.teamShareAccessLevel`:\n`Some(true)` behaves like `\"view\"`, `Some(false)` like `null`, and\n`None` is a no-op. Supplying both with disagreeing values is rejected.\nThe team is resolved from the call\'s `created_by`, not the acting user.'
),
})
- .describe('Edit call request');
+ .describe('Edit call request, as supplied by inbound callers.');
/**
- * Toggles the `share_with_team` flag on the active call. Returns the new
-value as the JSON body.
+ * Flips the live call's share-with-team toggle and returns the new value as
+the JSON body. The toggle is applied as canonical team sharing (View for
+the creator's team) when the call is archived; archived calls answer 409
+and are edited through `PATCH /call/record/{call_id}` instead.
* @summary Handler for `POST /call/record/{call_id}/share-with-team/toggle`.
*/
export const toggleShareWithTeamParams = zod.object({
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index b07e52951a..81265ff380 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -1314,7 +1314,7 @@
"patch": {
"tags": ["call::inbound::axum_router"],
"summary": "Handler for `PATCH /call/record/{call_id}`.",
- "description": "Edits a call record — currently supports updating the record's share\npermissions. Access is validated via channel membership",
+ "description": "Edits a call record: link/channel share permissions, display name, and\nteam sharing. Edit access (channel membership) is required for the request.\n`sharePermission.teamShareAccessLevel` only accepts `view` or `null`; while\nthe call is live it sets the pending share-with-team toggle, and once the\ncall is archived it is additionally authorized against the call's creator.",
"operationId": "edit_call_record",
"parameters": [
{
@@ -1342,6 +1342,16 @@
"204": {
"description": "Call record updated"
},
+ "400": {
+ "description": "Invalid team-share level, contradictory inputs, or the creator has no team",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
@@ -1352,6 +1362,16 @@
}
}
},
+ "403": {
+ "description": "Team sharing of an archived call may only be changed by its creator",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -1362,6 +1382,16 @@
}
}
},
+ "409": {
+ "description": "Team-sharing facts changed, or the call was archived mid-request; reload and retry",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -1379,7 +1409,7 @@
"post": {
"tags": ["call::inbound::axum_router"],
"summary": "Handler for `POST /call/record/{call_id}/share-with-team/toggle`.",
- "description": "Toggles the `share_with_team` flag on the active call. Returns the new\nvalue as the JSON body.",
+ "description": "Flips the live call's share-with-team toggle and returns the new value as\nthe JSON body. The toggle is applied as canonical team sharing (View for\nthe creator's team) when the call is archived; archived calls answer 409\nand are edited through `PATCH /call/record/{call_id}` instead.",
"operationId": "toggle_share_with_team",
"parameters": [
{
@@ -1395,7 +1425,7 @@
],
"responses": {
"200": {
- "description": "New value of share_with_team after toggle",
+ "description": "New value of the share-with-team toggle",
"content": {
"application/json": {
"schema": {
@@ -1424,6 +1454,16 @@
}
}
},
+ "409": {
+ "description": "The call is no longer active",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -16206,7 +16246,7 @@
},
"shareWithTeam": {
"type": "boolean",
- "description": "Whether the call is shared with the creator's team."
+ "description": "Whether the call is shared with the creator's team. While the call is\nlive this is the pending toggle applied at archive; afterwards it\nmirrors `team_share_access_level`."
},
"startedAt": {
"type": "string",
@@ -16228,6 +16268,17 @@
"type": ["string", "null"],
"description": "AI-generated summary of the call. Only set on archived `call_records`\nonce summarization has run; active calls always return `None`."
},
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The canonical access level granted to the creator's team, or `None`\nwhen the call is not shared with the team. Calls only ever grant\n`View`, and only once archived: while the call is live this is `None`\nand `share_with_team` carries the pending toggle."
+ }
+ ]
+ },
"transcript": {
"type": "array",
"items": {
@@ -20555,7 +20606,7 @@
},
"EditCallRecordRequest": {
"type": "object",
- "description": "Edit call request",
+ "description": "Edit call request, as supplied by inbound callers.",
"properties": {
"customName": {
"type": ["string", "null"],
@@ -20568,13 +20619,13 @@
},
{
"$ref": "#/components/schemas/UpdateSharePermissionRequestV2",
- "description": "Updated share permissions."
+ "description": "Updated share permissions. `teamShareAccessLevel` shares the call with\nthe creator's team and only accepts `view` or `null` (revoke). While\nthe call is live it sets the pending share-with-team toggle, which is\napplied when the call is archived; afterwards only the call's creator\nmay change it."
}
]
},
"shareWithTeam": {
"type": ["boolean", "null"],
- "description": "If `Some(true)`, grant the creator's team View access on the call.\nIf `Some(false)`, revoke the creator's team's access. `None` is a no-op.\nThe team is resolved from the call's `created_by`, not the acting user."
+ "description": "Deprecated alias for `sharePermission.teamShareAccessLevel`:\n`Some(true)` behaves like `\"view\"`, `Some(false)` like `null`, and\n`None` is a no-op. Supplying both with disagreeing values is rejected.\nThe team is resolved from the call's `created_by`, not the acting user."
}
}
},
diff --git a/crates/call/Cargo.toml b/crates/call/Cargo.toml
index 1d6cfe12b6..d52260bcb3 100644
--- a/crates/call/Cargo.toml
+++ b/crates/call/Cargo.toml
@@ -28,6 +28,7 @@ outbound = [
"dep:livekit-protocol",
"dep:macro_aws_config",
"dep:pgvector",
+ "dep:share_permission_db_utils",
"dep:sqlx",
"dep:urlencoding",
"ports",
@@ -78,6 +79,7 @@ rootcause = { workspace = true }
pgvector = { workspace = true, optional = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true }
+share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }
serde_json = { workspace = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
diff --git a/crates/call/src/domain/entity_mutation.rs b/crates/call/src/domain/entity_mutation.rs
index 2f2bb55484..a13331ba73 100644
--- a/crates/call/src/domain/entity_mutation.rs
+++ b/crates/call/src/domain/entity_mutation.rs
@@ -1,5 +1,8 @@
//! Unified entity-mutation capability impls for calls.
+#[cfg(test)]
+mod test;
+
use entity_access::domain::models::{
AccessError, EditAccessLevel, EntityAccessReceipt, ViewAccessLevel,
};
@@ -31,7 +34,10 @@ impl From<CallError> for EntityMutationErrorCode {
Self::forbidden(rootcause::report!(error))
}
error @ CallError::InvalidRequest(_) => Self::invalid(rootcause::report!(error)),
- error @ CallError::AlreadyInCall(_) => Self::conflict(rootcause::report!(error)),
+ error @ CallError::Forbidden(_) => Self::forbidden(rootcause::report!(error)),
+ error @ (CallError::AlreadyInCall(_) | CallError::Conflict(_)) => {
+ Self::conflict(rootcause::report!(error))
+ }
error @ CallError::Internal(_) => Self::internal(rootcause::report!(error)),
}
}
diff --git a/crates/call/src/domain/entity_mutation/test.rs b/crates/call/src/domain/entity_mutation/test.rs
new file mode 100644
index 0000000000..c57865a192
--- /dev/null
+++ b/crates/call/src/domain/entity_mutation/test.rs
@@ -0,0 +1,22 @@
+use entity_mutation::EntityMutationErrorCode;
+
+use crate::domain::models::CallError;
+
+#[test]
+fn maps_team_share_errors_to_mutation_codes() {
+ // A non-creator changing team sharing.
+ assert!(matches!(
+ EntityMutationErrorCode::from(CallError::Forbidden("not the creator".to_string())),
+ EntityMutationErrorCode::Forbidden(_)
+ ));
+ // Stale team-share facts.
+ assert!(matches!(
+ EntityMutationErrorCode::from(CallError::Conflict("stale".to_string())),
+ EntityMutationErrorCode::Conflict(_)
+ ));
+ // The view-only cap and contradictory legacy inputs.
+ assert!(matches!(
+ EntityMutationErrorCode::from(CallError::InvalidRequest("view only".to_string())),
+ EntityMutationErrorCode::InvalidInput(_)
+ ));
+}
diff --git a/crates/call/src/domain/models.rs b/crates/call/src/domain/models.rs
index c97e822fc0..47a644ed81 100644
--- a/crates/call/src/domain/models.rs
+++ b/crates/call/src/domain/models.rs
@@ -10,6 +10,9 @@ use item_filters::{
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Query, SimpleSortMethod};
use models_permissions::share_permission::access_level::AccessLevel;
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamSharePolicyError,
+};
use uuid::Uuid;
/// Represents an active call in a channel.
@@ -309,16 +312,21 @@ pub struct CallTranscriptCustomSpeakerResult {
pub custom_speaker: String,
}
-/// Edit call request
+/// Edit call request, as supplied by inbound callers.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct EditCallRecordRequest {
- /// Updated share permissions.
+ /// Updated share permissions. `teamShareAccessLevel` shares the call with
+ /// the creator's team and only accepts `view` or `null` (revoke). While
+ /// the call is live it sets the pending share-with-team toggle, which is
+ /// applied when the call is archived; afterwards only the call's creator
+ /// may change it.
pub share_permission:
Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,
- /// If `Some(true)`, grant the creator's team View access on the call.
- /// If `Some(false)`, revoke the creator's team's access. `None` is a no-op.
+ /// Deprecated alias for `sharePermission.teamShareAccessLevel`:
+ /// `Some(true)` behaves like `"view"`, `Some(false)` like `null`, and
+ /// `None` is a no-op. Supplying both with disagreeing values is rejected.
/// The team is resolved from the call's `created_by`, not the acting user.
pub share_with_team: Option<bool>,
/// Updated user-supplied display name for the call. `None` is a no-op;
@@ -329,6 +337,26 @@ pub struct EditCallRecordRequest {
pub custom_name: Option<String>,
}
+/// Arguments the domain service hands to the repository when editing a call.
+///
+/// Only the service can produce the authorized team-share command, so inbound
+/// callers cannot request a team grant the owner policy has not approved.
+#[derive(Debug)]
+pub struct EditCallRecordRepoArgs {
+ /// Share permission updates, if changing (link and channel sharing).
+ pub share_permission:
+ Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,
+ /// Display name update; see [`EditCallRecordRequest::custom_name`].
+ pub custom_name: Option<String>,
+ /// Creator-authorized canonical team-share write for an archived call,
+ /// present only when the request carried an explicit
+ /// `teamShareAccessLevel` or the legacy `shareWithTeam`.
+ pub team_share: Option<AuthorizedTeamShareCommand>,
+ /// Pending share-with-team intent for a call that is still live; applied
+ /// as canonical team sharing when the call is archived.
+ pub live_share_with_team: Option<bool>,
+}
+
/// One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].
///
/// `custom_speaker = None` clears any existing override for this
@@ -444,7 +472,14 @@ pub struct CallRecord {
/// AI-generated summary of the call. Only set on archived `call_records`
/// once summarization has run; active calls always return `None`.
pub summary: Option<String>,
- /// Whether the call is shared with the creator's team.
+ /// The canonical access level granted to the creator's team, or `None`
+ /// when the call is not shared with the team. Calls only ever grant
+ /// `View`, and only once archived: while the call is live this is `None`
+ /// and `share_with_team` carries the pending toggle.
+ pub team_share_access_level: Option<AccessLevel>,
+ /// Whether the call is shared with the creator's team. While the call is
+ /// live this is the pending toggle applied at archive; afterwards it
+ /// mirrors `team_share_access_level`.
pub share_with_team: bool,
/// Whether the call is currently active (from `calls` table).
pub is_active: bool,
@@ -590,7 +625,29 @@ pub enum CallError {
/// The request body violates an API contract (e.g. exceeds a size cap).
#[error("{0}")]
InvalidRequest(String),
+ /// The caller is authenticated but not allowed to perform this change
+ /// (for example, only the call's creator may change team sharing).
+ #[error("forbidden: {0}")]
+ Forbidden(String),
+ /// The requested change conflicts with the persisted state (for example a
+ /// stale team-share revision); the caller should reload and retry.
+ #[error("conflict: {0}")]
+ Conflict(String),
/// An internal error occurred.
#[error(transparent)]
Internal(#[from] anyhow::Error),
}
+
+impl From<TeamSharePolicyError> for CallError {
+ fn from(error: TeamSharePolicyError) -> Self {
+ match error {
+ TeamSharePolicyError::MissingActor | TeamSharePolicyError::NotOwner => {
+ Self::Forbidden(error.to_string())
+ }
+ TeamSharePolicyError::InvalidRevision => Self::Conflict(error.to_string()),
+ TeamSharePolicyError::MissingTeam
+ | TeamSharePolicyError::InvalidLevel
+ | TeamSharePolicyError::ContradictoryInputs => Self::InvalidRequest(error.to_string()),
+ }
+ }
+}
diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rs
index 7762ffa6a6..2f6b1a082a 100644
--- a/crates/call/src/domain/ports.rs
+++ b/crates/call/src/domain/ports.rs
@@ -12,9 +12,11 @@ use uuid::Uuid;
use item_filters::ast::{LiteralTree, call::CallLiteral};
use notification::domain::models::apple::VoipPushPayload;
+use models_permissions::share_permission::team_share::TeamShareFacts;
+
use crate::domain::models::{
- CustomSpeakerAssignment, DeletedCallRecordStorageKeys, EditCallRecordRequest,
- EditCallTranscriptRequest,
+ CustomSpeakerAssignment, DeletedCallRecordStorageKeys, EditCallRecordRepoArgs,
+ EditCallRecordRequest, EditCallTranscriptRequest,
};
use super::models::{
@@ -34,13 +36,16 @@ pub trait CallRepository: Send + Sync + 'static {
/// Create a new call record, or return `None` if one already exists for
/// this channel (unique-constraint conflict).
+ ///
+ /// The live `share_with_team` intent starts at its default (on); canonical
+ /// team sharing is only written when the call is archived.
fn create_call<'a>(
&self,
call_id: &Uuid,
channel_id: &Uuid,
room_name: &str,
created_by: MacroUserIdStr<'a>,
- ) -> impl Future<Output = Result<Option<Call>, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<Call>, CallError>> + Send;
/// Get an active call by channel ID.
fn get_call_by_channel_id(
@@ -133,20 +138,32 @@ pub trait CallRepository: Send + Sync + 'static {
egress_id: &str,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// Flip the `share_with_team` flag on an active call. Returns the new
- /// value along with the call's `channel_id`.
+ /// Load the canonical team-share facts (persisted creator, the creator's
+ /// team, current explicit grant, revision) the owner policy authorizes
+ /// against. Works for active and archived calls alike.
+ fn get_team_share_facts(
+ &self,
+ call_id: &Uuid,
+ ) -> impl Future<Output = Result<TeamShareFacts, CallError>> + Send;
+
+ /// Flip the live `share_with_team` intent on an active call. Returns the
+ /// new value along with the call's `channel_id`. Archived calls answer
+ /// [`CallError::Conflict`]: their team sharing is canonical and edited
+ /// through [`CallRepository::patch_call_record`].
fn toggle_share_with_team(
&self,
call_id: &Uuid,
- ) -> impl Future<Output = Result<(bool, Uuid), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<(bool, Uuid), CallError>> + Send;
/// Archive an active call to the permanent `call_records` and
/// `call_record_participants` tables, then delete the ephemeral rows.
+ /// The live `share_with_team` intent is translated into canonical team
+ /// sharing (View for the creator's current team) in the same transaction.
/// Returns facts committed by the archive transaction.
fn archive_call(
&self,
call_id: &Uuid,
- ) -> impl Future<Output = Result<ArchivedCall, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<ArchivedCall, CallError>> + Send;
/// Set the recording key on an archived call record.
fn set_recording_key(
@@ -272,12 +289,20 @@ pub trait CallRepository: Send + Sync + 'static {
call_record_id: &Uuid,
) -> impl Future<Output = Result<Option<DeletedCallRecordStorageKeys>, Self::Err>> + Send;
- /// Patches a call record.
+ /// Patches a call record (link/channel sharing, team sharing, display name)
+ /// in one transaction.
+ ///
+ /// `args.team_share` is the creator-authorized command for a canonical
+ /// team-share change on an archived call; the repository applies it
+ /// atomically with the rest of the patch and rejects a team level that
+ /// arrives without one. `args.live_share_with_team` instead sets the
+ /// pending intent on an active call and conflicts if the call has been
+ /// archived meanwhile.
fn patch_call_record(
&self,
call_record_id: &Uuid,
- request: &EditCallRecordRequest,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ args: &EditCallRecordRepoArgs,
+ ) -> impl Future<Output = Result<(), CallError>> + Send;
/// Apply a batch of per-diarized-speaker `custom_speaker` overrides to
/// the archived `call_record_transcripts` rows for `call_record_id`.
@@ -609,12 +634,29 @@ pub trait CallService: Send + Sync + 'static {
) -> impl Future<Output = Result<(), CallError>> + Send;
/// Edits a [`CallRecord`].
+ ///
+ /// Team sharing (`sharePermission.teamShareAccessLevel`, or the legacy
+ /// `shareWithTeam` alias) only accepts `view`. While the call is live it
+ /// sets the pending intent any Edit-level caller may toggle; once archived
+ /// it is authorized against the persisted creator, not the receipt's
+ /// effective access. Other fields keep requiring the receipt's Edit access.
fn edit_call_record(
&self,
receipt: EntityAccessReceipt<EditAccessLevel>,
request: EditCallRecordRequest,
) -> impl Future<Output = Result<(), CallError>> + Send;
+ /// Toggle the live `share_with_team` intent on the active call identified
+ /// by the receipt. Authorization is carried in the receipt produced by
+ /// `CallAccessLevelExtractor`; the entity on the receipt must be
+ /// `EntityType::Call` and its `entity_id` must be the call's UUID. The
+ /// intent becomes canonical team sharing when the call is archived.
+ /// Returns the new value; archived calls answer [`CallError::Conflict`].
+ fn toggle_share_with_team(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ ) -> impl Future<Output = Result<bool, CallError>> + Send;
+
/// Apply per-diarized-speaker `custom_speaker` overrides to a call's
/// transcript. Authorization is carried in the receipt; the entity must
/// be `EntityType::Call` and its `entity_id` must be the call's UUID.
@@ -626,16 +668,6 @@ pub trait CallService: Send + Sync + 'static {
request: EditCallTranscriptRequest,
) -> impl Future<Output = Result<(), CallError>> + Send;
- /// Toggle the `share_with_team` flag on the active call identified by the
- /// receipt. Authorization is carried in the receipt produced by
- /// `CallAccessLevelExtractor`; the entity on the receipt must be
- /// `EntityType::Call` and its `entity_id` must be the call's UUID.
- /// Returns the new value.
- fn toggle_share_with_team(
- &self,
- receipt: EntityAccessReceipt<EditAccessLevel>,
- ) -> impl Future<Output = Result<bool, CallError>> + Send;
-
/// Batch-fetch lightweight previews for a list of call ids.
///
/// Mirrors the `POST /documents/preview` endpoint in
diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rs
index fda197a4a5..e39790c388 100644
--- a/crates/call/src/domain/service.rs
+++ b/crates/call/src/domain/service.rs
@@ -12,6 +12,10 @@ use entity_access::domain::ports::EntityAccessService;
use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
+use models_permissions::share_permission::access_level::AccessLevel;
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamShareLevel, TeamShareRequest, authorize_team_share,
+};
use notification::domain::models::apple::VoipPushPayload;
use notification::domain::models::apple::{
APNSPushNotification, Alert, AlertDictionary, Aps, PushNotificationData,
@@ -33,7 +37,8 @@ use crate::domain::events::{
CallStartedMetadata,
};
use crate::domain::models::{
- EditCallRecordRequest, EditCallTranscriptRequest, VoipPushPayloadRequest,
+ EditCallRecordRepoArgs, EditCallRecordRequest, EditCallTranscriptRequest,
+ VoipPushPayloadRequest,
};
use super::models::{
@@ -230,6 +235,40 @@ impl<
publish_call_event(&self.event_broker, event);
}
+ /// Authorize an explicit (`teamShareAccessLevel`) or legacy (`shareWithTeam`)
+ /// canonical team-share change on an archived call against the persisted
+ /// creator.
+ ///
+ /// Returns `Ok(None)` without loading anything when the request carries
+ /// neither input, so renames and link changes never take the shared
+ /// team-share guard. Calls only share with the team at View, so any other
+ /// explicit level is rejected before facts load. Effective Edit (or even
+ /// Owner) access is not enough: only the call's actual creator may share it.
+ async fn authorize_call_team_share(
+ &self,
+ receipt: &EntityAccessReceipt<EditAccessLevel>,
+ call_id: &Uuid,
+ request: TeamShareRequest,
+ ) -> Result<Option<AuthorizedTeamShareCommand>, CallError> {
+ if request == TeamShareRequest::default() {
+ return Ok(None);
+ }
+ if let Some(Some(level)) = request.access_level
+ && level != AccessLevel::View
+ {
+ return Err(CallError::InvalidRequest(
+ "calls can only be shared with the team at view access".to_string(),
+ ));
+ }
+ let facts = self.repo.get_team_share_facts(call_id).await?;
+ Ok(authorize_team_share(
+ receipt.acting_user_id(),
+ &facts,
+ request,
+ TeamShareLevel::View,
+ )?)
+ }
+
fn publish_archived_call_event(
&self,
archived: &ArchivedCall,
@@ -386,6 +425,31 @@ fn resolve_ring_status(
}
}
+/// Normalize the team-share inputs of an edit on a live call into the pending
+/// share-with-team toggle: `Ok(None)` when neither input is present.
+///
+/// Calls only share at View, so any other explicit level is rejected, as are
+/// explicit and legacy inputs that disagree.
+fn live_share_intent(request: TeamShareRequest) -> Result<Option<bool>, CallError> {
+ let explicit = match request.access_level {
+ Some(Some(AccessLevel::View)) => Some(true),
+ Some(Some(_)) => {
+ return Err(CallError::InvalidRequest(
+ "calls can only be shared with the team at view access".to_string(),
+ ));
+ }
+ Some(None) => Some(false),
+ None => None,
+ };
+ match (explicit, request.legacy_enabled) {
+ (Some(explicit), Some(legacy)) if explicit != legacy => Err(CallError::InvalidRequest(
+ "legacy and explicit team-share inputs contradict each other".to_string(),
+ )),
+ (Some(explicit), _) => Ok(Some(explicit)),
+ (None, legacy) => Ok(legacy),
+ }
+}
+
fn event_actor_user_id(auth: &EntityAccessAuth) -> Option<MacroUserIdStr<'static>> {
match auth {
EntityAccessAuth::Authenticated(user_id) => Some(user_id.clone().into_owned()),
@@ -543,8 +607,7 @@ impl<
match self
.repo
.create_call(&call_id, channel_id, &room_name, user_id.copied())
- .await
- .map_err(|e| CallError::Internal(e.into()))?
+ .await?
{
Some(call) => {
// We are the creator — dispatch transcription agent (best-effort).
@@ -922,11 +985,7 @@ impl<
.map_err(|e| CallError::Internal(e.into()))?
{
tracing::info!(call_id = %call.id, room_name, "archiving call on room_finished");
- let archived = self
- .repo
- .archive_call(&call.id)
- .await
- .map_err(|e| CallError::Internal(e.into()))?;
+ let archived = self.repo.archive_call(&call.id).await?;
self.publish_archived_call_event(&archived, CallArchiveReason::RoomFinished);
// Fire-and-forget summarization now that the
@@ -1039,11 +1098,7 @@ impl<
if remaining == 0 {
tracing::info!(call_id = %call.id, room_name, "last participant left, archiving call");
let egress_id = call.egress_id.clone();
- let archived = self
- .repo
- .archive_call(&call.id)
- .await
- .map_err(|e| CallError::Internal(e.into()))?;
+ let archived = self.repo.archive_call(&call.id).await?;
self.publish_archived_call_event(
&archived,
CallArchiveReason::LastParticipantLeft,
@@ -1382,54 +1437,90 @@ impl<
let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
let actor_user_id = event_actor_user_id(receipt.auth());
- let custom_name = request.custom_name.clone();
- let share_with_team = request.share_with_team;
- let channel_id = self
+
+ let record = self
.repo
.get_call_record_by_call_id(&call_id)
.await
- .map_err(|e| CallError::Internal(e.into()))?
- .map(|record| record.channel_id);
+ .map_err(|e| CallError::Internal(e.into()))?;
+ let team_share_request = TeamShareRequest {
+ access_level: request
+ .share_permission
+ .as_ref()
+ .and_then(|p| p.team_share_access_level),
+ legacy_enabled: request.share_with_team,
+ };
+ let custom_name = request.custom_name.clone();
+ let mut share_permission = request.share_permission;
+
+ // While the call is live, team sharing is the pending toggle on the
+ // active call (any Edit-level caller may flip it, like the toggle
+ // endpoint); it becomes canonical state when the call is archived.
+ // Once archived, the change is authorized against the persisted
+ // creator before any write, so a rejected request publishes nothing.
+ let live_share_with_team = match &record {
+ Some(record) if record.is_active => live_share_intent(team_share_request)?,
+ _ => None,
+ };
+ let team_share = if live_share_with_team.is_some() {
+ // The repository refuses a team level without a command; the live
+ // intent is carried separately.
+ if let Some(permission) = share_permission.as_mut() {
+ permission.team_share_access_level = None;
+ }
+ None
+ } else {
+ self.authorize_call_team_share(&receipt, &call_id, team_share_request)
+ .await?
+ };
+ // Events report the committed team-share outcome, never the raw request.
+ let share_with_team = live_share_with_team.or_else(|| {
+ team_share
+ .as_ref()
+ .map(|command| command.target().is_some())
+ });
self.repo
- .patch_call_record(&call_id, &request)
- .await
- .map_err(|e| CallError::Internal(e.into()))?;
+ .patch_call_record(
+ &call_id,
+ &EditCallRecordRepoArgs {
+ share_permission,
+ custom_name: request.custom_name,
+ team_share,
+ live_share_with_team,
+ },
+ )
+ .await?;
- if let Some(channel_id) = channel_id {
- self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
- call_id,
- channel_id,
- actor_user_id,
- custom_name,
- share_with_team,
- }));
- }
+ let Some(record) = record else {
+ return Ok(());
+ };
- Ok(())
- }
+ self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
+ call_id,
+ channel_id: record.channel_id,
+ actor_user_id,
+ custom_name,
+ share_with_team,
+ }));
- #[tracing::instrument(err, skip(self, request), fields(num_assignments = request.assignments.len()))]
- async fn edit_call_transcript(
- &self,
- receipt: EntityAccessReceipt<EditAccessLevel>,
- request: EditCallTranscriptRequest,
- ) -> Result<(), CallError> {
- let entity = receipt.entity();
- if entity.entity_type != EntityType::Call {
- return Err(CallError::Internal(anyhow::anyhow!(
- "expected Call entity in receipt, got {:?}",
- entity.entity_type
- )));
+ // Participants of an in-progress call mirror the pending toggle in
+ // their call UI; tell them when it changed.
+ if let Some(share_with_team) = live_share_with_team {
+ self.send_call_participant_event(
+ &call_id,
+ "call_share_with_team_toggled",
+ &serde_json::json!({
+ "call_id": call_id,
+ "channel_id": record.channel_id,
+ "share_with_team": share_with_team,
+ "toggled_by": receipt.get_authenticated_user().ok(),
+ }),
+ )
+ .await;
}
- let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
- .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
-
- self.repo
- .patch_call_transcript_custom_speakers(&call_id, &request.assignments)
- .await
- .map_err(|e| CallError::Internal(e.into()))
+ Ok(())
}
#[tracing::instrument(err, skip(self))]
@@ -1449,11 +1540,7 @@ impl<
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
let actor_user_id = event_actor_user_id(receipt.auth());
- let (new_value, channel_id) = self
- .repo
- .toggle_share_with_team(&call_id)
- .await
- .map_err(|e| CallError::Internal(e.into()))?;
+ let (new_value, channel_id) = self.repo.toggle_share_with_team(&call_id).await?;
self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
call_id,
@@ -1478,6 +1565,29 @@ impl<
Ok(new_value)
}
+ #[tracing::instrument(err, skip(self, request), fields(num_assignments = request.assignments.len()))]
+ async fn edit_call_transcript(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ request: EditCallTranscriptRequest,
+ ) -> Result<(), CallError> {
+ let entity = receipt.entity();
+ if entity.entity_type != EntityType::Call {
+ return Err(CallError::Internal(anyhow::anyhow!(
+ "expected Call entity in receipt, got {:?}",
+ entity.entity_type
+ )));
+ }
+
+ let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
+ .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
+
+ self.repo
+ .patch_call_transcript_custom_speakers(&call_id, &request.assignments)
+ .await
+ .map_err(|e| CallError::Internal(e.into()))
+ }
+
#[tracing::instrument(err, skip(self, request, user_id), fields(num_call_ids = request.call_ids.len()))]
async fn get_batch_call_record_previews<'a>(
&self,
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index 5c83227ddd..21c5ac82b4 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -8,10 +8,15 @@ use connection::domain::models::{ConnectionError, InvalidationEvent};
use connection::domain::ports::ConnectionService;
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, EntityType};
use entity_access::domain::ports::NoOpEntityAccessService;
-use entity_mutation::DeleteEntityPermanently;
+use entity_mutation::{DeleteEntityPermanently, UpdateEntitySharePolicy};
use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+use models_permissions::share_permission::access_level::AccessLevel;
+use models_permissions::share_permission::team_share::{
+ TeamShareFacts, TeamShareGrant, TeamShareLevel,
+};
use notification::domain::models::apple::VoipPushPayload;
use notification::domain::service::NotificationIngress;
use serde_json::json;
@@ -921,9 +926,9 @@ async fn failed_archive_does_not_publish_archived_event() {
repo.expect_get_call_by_room_name()
.times(1)
.return_once(move |_| Box::pin(async move { Ok(Some(active_call)) }));
- repo.expect_archive_call()
- .times(1)
- .returning(|_| Box::pin(async { Err(anyhow::anyhow!("archive failed")) }));
+ repo.expect_archive_call().times(1).returning(|_| {
+ Box::pin(async { Err(CallError::Internal(anyhow::anyhow!("archive failed"))) })
+ });
let rtc_client = webhook_rtc_client("room_finished", None);
let event_broker = RecordingEventBroker::default();
@@ -1235,6 +1240,7 @@ fn call_record_for_mutation() -> CallRecord {
channel_name: None,
custom_name: None,
summary: None,
+ team_share_access_level: None,
share_with_team: false,
is_active: false,
status: None,
@@ -1272,7 +1278,9 @@ type BaseMutationCallService = CallServiceImpl<
fn build_mutation_service(
repo: MockCallRepository,
event_broker: RecordingEventBroker,
-) -> impl CallService + DeleteEntityPermanently<Receipt = EditAccessLevel> {
+) -> impl CallService
++ DeleteEntityPermanently<Receipt = EditAccessLevel>
++ UpdateEntitySharePolicy<Receipt = EditAccessLevel> {
let service: BaseMutationCallService = CallServiceImpl::new(
repo,
MockRtcClient::new(),
@@ -1393,12 +1401,13 @@ async fn get_active_calls_wraps_repo_error_as_internal() {
assert!(matches!(err, CallError::Internal(_)));
}
+/// Repo for edits that carry no team-share input: facts are never loaded
+/// (there is no `get_team_share_facts` expectation) and no command is forwarded.
fn mock_edit_repo(
record: Option<CallRecord>,
expected_custom_name: Option<&'static str>,
- expected_share_with_team: Option<bool>,
expect_share_permission: bool,
- patch_result: anyhow::Result<()>,
+ patch_result: Result<(), CallError>,
) -> MockCallRepository {
let mut repo = MockCallRepository::new();
repo.expect_get_call_record_by_call_id()
@@ -1409,11 +1418,12 @@ fn mock_edit_repo(
});
repo.expect_patch_call_record()
.times(1)
- .return_once(move |call_id, request| {
+ .return_once(move |call_id, args| {
assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
- assert_eq!(request.custom_name.as_deref(), expected_custom_name);
- assert_eq!(request.share_with_team, expected_share_with_team);
- assert_eq!(request.share_permission.is_some(), expect_share_permission);
+ assert_eq!(args.custom_name.as_deref(), expected_custom_name);
+ assert!(args.team_share.is_none());
+ assert!(args.live_share_with_team.is_none());
+ assert_eq!(args.share_permission.is_some(), expect_share_permission);
Box::pin(async move { patch_result })
});
repo
@@ -1424,7 +1434,6 @@ async fn edit_call_record_publishes_updated_event() {
let repo = mock_edit_repo(
Some(call_record_for_mutation()),
Some("Weekly sync"),
- None,
false,
Ok(()),
);
@@ -1453,13 +1462,7 @@ async fn edit_call_record_publishes_updated_event() {
#[tokio::test]
async fn edit_call_record_publishes_updated_event_when_name_is_cleared() {
- let repo = mock_edit_repo(
- Some(call_record_for_mutation()),
- Some(""),
- None,
- false,
- Ok(()),
- );
+ let repo = mock_edit_repo(Some(call_record_for_mutation()), Some(""), false, Ok(()));
let event_broker = RecordingEventBroker::default();
let service = build_mutation_service(repo, event_broker.clone());
@@ -1480,7 +1483,7 @@ async fn edit_call_record_publishes_updated_event_when_name_is_cleared() {
#[tokio::test]
async fn edit_call_record_publishes_updated_event_for_share_permission_only() {
- let repo = mock_edit_repo(Some(call_record_for_mutation()), None, None, true, Ok(()));
+ let repo = mock_edit_repo(Some(call_record_for_mutation()), None, true, Ok(()));
let event_broker = RecordingEventBroker::default();
let service = build_mutation_service(repo, event_broker.clone());
@@ -1519,7 +1522,6 @@ async fn edit_call_record_publishes_updated_event_without_an_internal_actor() {
let repo = mock_edit_repo(
Some(call_record_for_mutation()),
Some("Internal rename"),
- Some(false),
false,
Ok(()),
);
@@ -1531,19 +1533,19 @@ async fn edit_call_record_publishes_updated_event_without_an_internal_actor() {
internal_mutation_receipt(),
EditCallRecordRequest {
share_permission: None,
- share_with_team: Some(false),
+ share_with_team: None,
custom_name: Some("Internal rename".to_string()),
},
)
.await
.expect("internal edit succeeds");
- assert_updated_event(&event_broker, None, Some("Internal rename"), Some(false));
+ assert_updated_event(&event_broker, None, Some("Internal rename"), None);
}
#[tokio::test]
async fn edit_call_record_skips_updated_event_for_unknown_record() {
- let repo = mock_edit_repo(None, Some("Unknown"), None, false, Ok(()));
+ let repo = mock_edit_repo(None, Some("Unknown"), false, Ok(()));
let event_broker = RecordingEventBroker::default();
let service = build_mutation_service(repo, event_broker.clone());
@@ -1567,9 +1569,8 @@ async fn failed_edit_call_record_does_not_publish_updated_event() {
let repo = mock_edit_repo(
Some(call_record_for_mutation()),
Some("Failed rename"),
- None,
false,
- Err(anyhow::anyhow!("patch failed")),
+ Err(CallError::Internal(anyhow::anyhow!("patch failed"))),
);
let event_broker = RecordingEventBroker::default();
let service = build_mutation_service(repo, event_broker.clone());
@@ -1590,6 +1591,376 @@ async fn failed_edit_call_record_does_not_publish_updated_event() {
assert!(event_broker.events().is_empty());
}
+// -- team sharing -------------------------------------------------------------
+
+const CREATOR: &str = "macro|[email protected]";
+const CREATOR_TEAM_ID: Uuid = Uuid::from_u128(42);
+
+fn team_share_facts() -> TeamShareFacts {
+ TeamShareFacts {
+ entity: EntityType::Call.with_entity_string(MUTATED_EVENT_CALL_ID.to_string()),
+ owner: user("[email protected]"),
+ owner_team_id: Some(CREATOR_TEAM_ID),
+ current: None,
+ revision: 0,
+ }
+}
+
+/// The persisted creator, acting with the same effective Edit access the
+/// channel members in `authenticated_mutation_receipt` have.
+fn creator_mutation_receipt() -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ &MUTATED_EVENT_CALL_ID.to_string(),
+ EntityType::Call,
+ )
+}
+
+fn team_share_request(level: Option<AccessLevel>) -> UpdateSharePermissionRequestV2 {
+ UpdateSharePermissionRequestV2 {
+ link_share: None,
+ link_share_access_level: None,
+ team_share_access_level: Some(level),
+ channel_share_permissions: None,
+ }
+}
+
+fn team_edit(
+ share_permission: Option<UpdateSharePermissionRequestV2>,
+ share_with_team: Option<bool>,
+) -> EditCallRecordRequest {
+ EditCallRecordRequest {
+ share_permission,
+ share_with_team,
+ custom_name: None,
+ }
+}
+
+/// Repo that serves `facts` once, returns `record`, and asserts the command
+/// forwarded to `patch_call_record` targets `expected_target` (`None` = clear).
+fn mock_team_share_repo(
+ facts: TeamShareFacts,
+ record: CallRecord,
+ expected_target: Option<TeamShareLevel>,
+) -> MockCallRepository {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_team_share_facts()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ Box::pin(async move { Ok(facts) })
+ });
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .return_once(move |_| Box::pin(async move { Ok(Some(record)) }));
+ repo.expect_patch_call_record()
+ .times(1)
+ .returning(move |call_id, args| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ assert!(args.live_share_with_team.is_none());
+ let command = args
+ .team_share
+ .as_ref()
+ .expect("team-share command forwarded to the repository");
+ assert_eq!(command.target().map(|grant| grant.level), expected_target);
+ assert_eq!(command.next_revision(), 1);
+ Box::pin(async { Ok(()) })
+ });
+ repo
+}
+
+/// The archived record every canonical edit starts by loading.
+fn expect_archived_record(repo: &mut MockCallRepository) {
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Some(call_record_for_mutation())) }));
+}
+
+#[tokio::test]
+async fn creator_sets_team_view_and_publishes_committed_flag() {
+ // Archived record: no participant notification is sent (no
+ // `get_participants` expectation, so a call would panic).
+ let repo = mock_team_share_repo(
+ team_share_facts(),
+ call_record_for_mutation(),
+ Some(TeamShareLevel::View),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ creator_mutation_receipt(),
+ team_edit(Some(team_share_request(Some(AccessLevel::View))), None),
+ )
+ .await
+ .expect("the creator may share with the team");
+
+ assert_updated_event(&event_broker, Some(CREATOR), None, Some(true));
+}
+
+#[tokio::test]
+async fn creator_clears_team_share_with_explicit_null() {
+ let mut facts = team_share_facts();
+ facts.current = Some(TeamShareGrant {
+ team_id: CREATOR_TEAM_ID,
+ level: TeamShareLevel::View,
+ });
+ let repo = mock_team_share_repo(facts, call_record_for_mutation(), None);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ creator_mutation_receipt(),
+ team_edit(Some(team_share_request(None)), None),
+ )
+ .await
+ .expect("the creator may revoke team sharing");
+
+ assert_updated_event(&event_broker, Some(CREATOR), None, Some(false));
+}
+
+#[tokio::test]
+async fn legacy_share_with_team_alias_maps_to_view_and_clear() {
+ for (enabled, current, expected) in [
+ (true, None, Some(TeamShareLevel::View)),
+ (false, Some(TeamShareLevel::View), None),
+ ] {
+ let mut facts = team_share_facts();
+ facts.current = current.map(|level| TeamShareGrant {
+ team_id: CREATOR_TEAM_ID,
+ level,
+ });
+ let repo = mock_team_share_repo(facts, call_record_for_mutation(), expected);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(creator_mutation_receipt(), team_edit(None, Some(enabled)))
+ .await
+ .unwrap_or_else(|error| panic!("shareWithTeam={enabled}: {error}"));
+
+ assert_updated_event(&event_broker, Some(CREATOR), None, Some(enabled));
+ }
+}
+
+#[tokio::test]
+async fn team_share_rejects_non_view_levels_before_loading_facts() {
+ for level in [AccessLevel::Comment, AccessLevel::Edit, AccessLevel::Owner] {
+ // No facts or patch expectations: the view cap is checked before the
+ // canonical facts are loaded or anything is written.
+ let mut repo = MockCallRepository::new();
+ expect_archived_record(&mut repo);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ let error = service
+ .edit_call_record(
+ creator_mutation_receipt(),
+ team_edit(Some(team_share_request(Some(level))), None),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CallError::InvalidRequest(_)), "{level:?}");
+ assert!(event_broker.events().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn team_share_by_non_creator_is_forbidden_without_writes() {
+ // The editor receipt carries effective Edit access (a channel member) and
+ // the internal receipt has no acting user; neither may share the call,
+ // through the explicit level or the legacy alias.
+ for receipt in [
+ authenticated_mutation_receipt(),
+ internal_mutation_receipt(),
+ ] {
+ for request in [
+ team_edit(Some(team_share_request(Some(AccessLevel::View))), None),
+ team_edit(None, Some(true)),
+ ] {
+ let mut repo = MockCallRepository::new();
+ expect_archived_record(&mut repo);
+ repo.expect_get_team_share_facts()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ let error = service
+ .edit_call_record(receipt.clone(), request)
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CallError::Forbidden(_)));
+ assert!(event_broker.events().is_empty());
+ }
+ }
+}
+
+#[tokio::test]
+async fn team_share_rejects_missing_team_and_contradictory_inputs() {
+ // A creator without a team cannot enable sharing.
+ let mut repo = MockCallRepository::new();
+ expect_archived_record(&mut repo);
+ repo.expect_get_team_share_facts().times(1).returning(|_| {
+ let mut facts = team_share_facts();
+ facts.owner_team_id = None;
+ Box::pin(async move { Ok(facts) })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+ let error = service
+ .edit_call_record(
+ creator_mutation_receipt(),
+ team_edit(Some(team_share_request(Some(AccessLevel::View))), None),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(error, CallError::InvalidRequest(_)));
+ assert!(event_broker.events().is_empty());
+
+ // An explicit clear and the legacy enable disagree.
+ let mut repo = MockCallRepository::new();
+ expect_archived_record(&mut repo);
+ repo.expect_get_team_share_facts()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+ let error = service
+ .edit_call_record(
+ creator_mutation_receipt(),
+ team_edit(Some(team_share_request(None)), Some(true)),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(error, CallError::InvalidRequest(_)));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn team_share_repo_conflict_publishes_nothing() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_team_share_facts()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(team_share_facts()) }));
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Some(call_record_for_mutation())) }));
+ repo.expect_patch_call_record()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Err(CallError::Conflict("stale".to_string())) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ let error = service
+ .edit_call_record(
+ creator_mutation_receipt(),
+ team_edit(Some(team_share_request(Some(AccessLevel::View))), None),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CallError::Conflict(_)));
+ assert!(event_broker.events().is_empty());
+}
+
+// -- live calls: the pending toggle -------------------------------------------
+
+fn live_record() -> CallRecord {
+ let mut record = call_record_for_mutation();
+ record.is_active = true;
+ record
+}
+
+/// Repo for a live call: no canonical facts are loaded (there is no
+/// `get_team_share_facts` expectation) and the patch carries the pending
+/// toggle instead of a command.
+fn mock_live_edit_repo(expected_toggle: bool) -> MockCallRepository {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Some(live_record())) }));
+ repo.expect_patch_call_record()
+ .times(1)
+ .returning(move |call_id, args| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ assert!(args.team_share.is_none());
+ assert_eq!(args.live_share_with_team, Some(expected_toggle));
+ // The team level never reaches the canonical writer for a live call.
+ assert_eq!(
+ args.share_permission
+ .as_ref()
+ .and_then(|p| p.team_share_access_level),
+ None
+ );
+ Box::pin(async { Ok(()) })
+ });
+ // The realtime `call_share_with_team_toggled` message fans out to the
+ // active participants.
+ repo.expect_get_participants()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Vec::new()) }));
+ repo
+}
+
+#[tokio::test]
+async fn live_call_team_share_sets_pending_toggle_for_any_editor() {
+ // A channel member (not the creator) may flip the toggle while the call
+ // is live, through the explicit level or the legacy alias.
+ for (request, expected) in [
+ (
+ team_edit(Some(team_share_request(Some(AccessLevel::View))), None),
+ true,
+ ),
+ (team_edit(Some(team_share_request(None)), None), false),
+ (team_edit(None, Some(true)), true),
+ (team_edit(None, Some(false)), false),
+ ] {
+ let repo = mock_live_edit_repo(expected);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(authenticated_mutation_receipt(), request)
+ .await
+ .expect("live toggle succeeds");
+
+ assert_updated_event(
+ &event_broker,
+ Some(MUTATED_EVENT_ACTOR),
+ None,
+ Some(expected),
+ );
+ }
+}
+
+#[tokio::test]
+async fn live_call_team_share_rejects_non_view_levels_and_contradictions() {
+ for request in [
+ team_edit(Some(team_share_request(Some(AccessLevel::Edit))), None),
+ team_edit(Some(team_share_request(None)), Some(true)),
+ ] {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Some(live_record())) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ let error = service
+ .edit_call_record(authenticated_mutation_receipt(), request)
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, CallError::InvalidRequest(_)));
+ assert!(event_broker.events().is_empty());
+ }
+}
+
#[tokio::test]
async fn toggle_share_with_team_publishes_updated_event() {
let mut repo = MockCallRepository::new();
@@ -1615,20 +1986,52 @@ async fn toggle_share_with_team_publishes_updated_event() {
}
#[tokio::test]
-async fn failed_toggle_share_with_team_does_not_publish_updated_event() {
+async fn toggle_share_with_team_on_archived_call_conflicts_without_events() {
let mut repo = MockCallRepository::new();
repo.expect_toggle_share_with_team()
.times(1)
- .returning(|_| Box::pin(async { Err(anyhow::anyhow!("toggle failed")) }));
+ .returning(|_| Box::pin(async { Err(CallError::Conflict("archived".to_string())) }));
let event_broker = RecordingEventBroker::default();
let service = build_mutation_service(repo, event_broker.clone());
- assert!(
+ assert!(matches!(
service
.toggle_share_with_team(authenticated_mutation_receipt())
- .await
- .is_err()
- );
+ .await,
+ Err(CallError::Conflict(_))
+ ));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn graphql_team_sharing_still_rejects_active_calls() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .returning(|_| {
+ let mut record = call_record_for_mutation();
+ record.is_active = true;
+ Box::pin(async move { Ok(Some(record)) })
+ });
+ repo.expect_resolve_channel_name()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(None) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ let error = service
+ .update_share_policy(
+ EntityType::Call.with_entity_string(MUTATED_EVENT_CALL_ID.to_string()),
+ creator_mutation_receipt(),
+ team_share_request(Some(AccessLevel::View)),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ error,
+ entity_mutation::EntityMutationErrorCode::Conflict(_)
+ ));
assert!(event_broker.events().is_empty());
}
@@ -1832,6 +2235,7 @@ fn summarized_call_record(custom_name: Option<&str>) -> CallRecord {
channel_name: None,
custom_name: custom_name.map(str::to_string),
summary: None,
+ team_share_access_level: None,
share_with_team: false,
is_active: false,
status: None,
diff --git a/crates/call/src/inbound/axum_router.rs b/crates/call/src/inbound/axum_router.rs
index 1b559b7f0f..a744284792 100644
--- a/crates/call/src/inbound/axum_router.rs
+++ b/crates/call/src/inbound/axum_router.rs
@@ -7,6 +7,9 @@
//! - [`webhook_router`] — RTC provider webhook ingestion.
//! Does **not** require auth middleware (LiveKit signs requests itself).
+#[cfg(test)]
+mod test;
+
use std::borrow::Cow;
use std::sync::Arc;
@@ -97,10 +100,10 @@ impl<S, Svc, Auth> FromRef<CallRouterState<S, Svc, Auth>> for MacroAuthorization
/// - `GET /active` — list all active calls in channels the caller is a member of
/// - `DELETE /{channel_id}` — leave or end a call
/// - `GET /record/{call_id}` — get a full call record (transcript + participants)
-/// - `PATCH /record/{call_id}` — edit a call record (e.g. share permissions)
+/// - `PATCH /record/{call_id}` — edit a call record (share permissions, team sharing, name)
/// - `PATCH /record/{call_id}/transcript` — set per-diarized-speaker custom_speaker overrides
/// - `DELETE /record/{call_id}` — delete a call record
-/// - `POST /record/{call_id}/share-with-team/toggle` — flip the call's share_with_team flag
+/// - `POST /record/{call_id}/share-with-team/toggle` — flip the live call's share-with-team toggle
/// - `POST /record/preview` — batch-fetch lightweight previews for many call ids
pub fn call_router<S, Svc, Auth, T>(state: CallRouterState<S, Svc, Auth>) -> Router<T>
where
@@ -443,8 +446,11 @@ pub async fn delete_call_record_handler<
/// Handler for `PATCH /call/record/{call_id}`.
///
-/// Edits a call record — currently supports updating the record's share
-/// permissions. Access is validated via channel membership
+/// Edits a call record: link/channel share permissions, display name, and
+/// team sharing. Edit access (channel membership) is required for the request.
+/// `sharePermission.teamShareAccessLevel` only accepts `view` or `null`; while
+/// the call is live it sets the pending share-with-team toggle, and once the
+/// call is archived it is additionally authorized against the call's creator.
#[utoipa::path(
patch,
operation_id = "edit_call_record",
@@ -455,8 +461,11 @@ pub async fn delete_call_record_handler<
request_body = EditCallRecordRequest,
responses(
(status = 204, description = "Call record updated"),
+ (status = 400, description = "Invalid team-share level, contradictory inputs, or the creator has no team", body = ErrorResponse),
(status = 401, body = ErrorResponse),
+ (status = 403, description = "Team sharing of an archived call may only be changed by its creator", body = ErrorResponse),
(status = 404, body = ErrorResponse),
+ (status = 409, description = "Team-sharing facts changed, or the call was archived mid-request; reload and retry", body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
@@ -517,8 +526,10 @@ pub async fn edit_call_transcript_handler<
/// Handler for `POST /call/record/{call_id}/share-with-team/toggle`.
///
-/// Toggles the `share_with_team` flag on the active call. Returns the new
-/// value as the JSON body.
+/// Flips the live call's share-with-team toggle and returns the new value as
+/// the JSON body. The toggle is applied as canonical team sharing (View for
+/// the creator's team) when the call is archived; archived calls answer 409
+/// and are edited through `PATCH /call/record/{call_id}` instead.
#[utoipa::path(
post,
operation_id = "toggle_share_with_team",
@@ -527,9 +538,10 @@ pub async fn edit_call_transcript_handler<
("call_id" = Uuid, Path, description = "Call ID"),
),
responses(
- (status = 200, body = bool, content_type = "application/json", description = "New value of share_with_team after toggle"),
+ (status = 200, body = bool, content_type = "application/json", description = "New value of the share-with-team toggle"),
(status = 401, body = ErrorResponse),
(status = 404, body = ErrorResponse),
+ (status = 409, description = "The call is no longer active", body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
@@ -745,6 +757,8 @@ impl IntoResponse for CallError {
CallError::AlreadyInCall(_) => StatusCode::CONFLICT,
CallError::Auth => StatusCode::UNAUTHORIZED,
CallError::InvalidRequest(_) => StatusCode::BAD_REQUEST,
+ CallError::Forbidden(_) => StatusCode::FORBIDDEN,
+ CallError::Conflict(_) => StatusCode::CONFLICT,
CallError::Internal(_) => {
tracing::error!(error=?self, "internal server error");
StatusCode::INTERNAL_SERVER_ERROR
diff --git a/crates/call/src/inbound/axum_router/test.rs b/crates/call/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..092d2fed4e
--- /dev/null
+++ b/crates/call/src/inbound/axum_router/test.rs
@@ -0,0 +1,43 @@
+use axum::http::StatusCode;
+use axum::response::IntoResponse;
+
+use crate::domain::models::CallError;
+
+#[test]
+fn maps_domain_errors_to_status_codes() {
+ let cases = [
+ (
+ CallError::NotFound("call".to_string()),
+ StatusCode::NOT_FOUND,
+ ),
+ (CallError::NotInCall, StatusCode::BAD_REQUEST),
+ (
+ CallError::AlreadyInCall("channel".to_string()),
+ StatusCode::CONFLICT,
+ ),
+ (CallError::Auth, StatusCode::UNAUTHORIZED),
+ (
+ CallError::InvalidRequest("view only".to_string()),
+ StatusCode::BAD_REQUEST,
+ ),
+ // Team sharing by anyone but the call's creator.
+ (
+ CallError::Forbidden("not the creator".to_string()),
+ StatusCode::FORBIDDEN,
+ ),
+ // Stale team-share facts: reload and retry.
+ (
+ CallError::Conflict("stale".to_string()),
+ StatusCode::CONFLICT,
+ ),
+ (
+ CallError::Internal(anyhow::anyhow!("boom")),
+ StatusCode::INTERNAL_SERVER_ERROR,
+ ),
+ ];
+
+ for (error, status) in cases {
+ let description = format!("{error:?}");
+ assert_eq!(error.into_response().status(), status, "{description}");
+ }
+}
diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rs
index b944e7b415..781d60ef6d 100644
--- a/crates/call/src/outbound/pg_call_repo.rs
+++ b/crates/call/src/outbound/pg_call_repo.rs
@@ -1,6 +1,7 @@
//! Postgres-backed repository for call state.
mod edit;
+mod team_share;
#[cfg(test)]
mod test;
@@ -16,16 +17,15 @@ use item_filters::{
ast::{LiteralTree, call::CallLiteral, properties::PropertyMatchValue},
};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
-use models_permissions::share_permission::SharePermissionV2;
-use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;
+use models_permissions::share_permission::team_share::TeamShareFacts;
use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::models::{
- ActiveCallSummary, AddParticipantError, ArchivedCall, Call, CallParticipant, CallRecord,
- CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment,
- CustomSpeakerAssignment, DeletedCallRecordStorageKeys, EditCallRecordRequest,
- EnrichedCallTranscript, TranscriptSegmentRequest, WithCallId,
+ ActiveCallSummary, AddParticipantError, ArchivedCall, Call, CallError, CallParticipant,
+ CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData,
+ CallRecordTranscriptSegment, CustomSpeakerAssignment, DeletedCallRecordStorageKeys,
+ EditCallRecordRepoArgs, EnrichedCallTranscript, TranscriptSegmentRequest, WithCallId,
};
use crate::domain::ports::CallRepository;
@@ -306,28 +306,13 @@ impl CallRepository for PgCallRepo {
channel_id: &Uuid,
room_name: &str,
created_by: MacroUserIdStr<'_>,
- ) -> Result<Option<Call>, Self::Err> {
- // Create share permission. Call access is channel-based by design, so
- // the team default link-share preference intentionally does not apply:
- // link sharing is off and the channel gets an explicit edit grant.
- let share_permission_id = uuid::Uuid::now_v7();
- let share_permission = SharePermissionV2 {
- id: share_permission_id.to_string(),
- link_share: None,
- link_share_access_level: None,
- team_share_access_level: None,
- owner: created_by.to_string(),
- channel_share_permissions: Some(vec![ChannelSharePermission {
- channel_id: channel_id.to_string(),
- access_level: AccessLevel::Edit,
- }]),
- };
- let link_share = share_permission.link_share.map(|value| value.to_string());
- let link_share_access_level = share_permission.link_share_access_level;
-
+ ) -> Result<Option<Call>, CallError> {
let mut tx = self.pool.begin().await?;
- // insert share permission
+ // Create the share permission. Call access is channel-based by design,
+ // so the team default link-share preference intentionally does not
+ // apply: link sharing is off and the channel gets an explicit edit grant.
+ let share_permission_id = uuid::Uuid::now_v7().to_string();
sqlx::query!(
r#"
INSERT INTO "SharePermission" (
@@ -337,11 +322,9 @@ impl CallRepository for PgCallRepo {
"createdAt",
"updatedAt"
)
- VALUES ($1, $2, $3, NOW(), NOW())
+ VALUES ($1, NULL, NULL, NOW(), NOW())
"#,
- share_permission.id,
- link_share,
- link_share_access_level as _,
+ share_permission_id,
)
.execute(tx.as_mut())
.await?;
@@ -352,7 +335,7 @@ impl CallRepository for PgCallRepo {
INSERT INTO "ChannelSharePermission" ("share_permission_id", "channel_id", "access_level")
VALUES ($1, $2, $3)
"#,
- &share_permission.id,
+ share_permission_id,
&channel_id.to_string(),
AccessLevel::Edit as _,
)
@@ -380,6 +363,9 @@ impl CallRepository for PgCallRepo {
)
.await?;
+ // `share_with_team` keeps its column default (on): it is the pending
+ // intent participants toggle during the call, translated into
+ // canonical team sharing when the call is archived.
let row = sqlx::query!(
r#"
INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id)
@@ -391,26 +377,27 @@ impl CallRepository for PgCallRepo {
channel_id,
room_name,
created_by.as_ref(),
- &share_permission_id.to_string(),
+ share_permission_id,
)
.fetch_optional(tx.as_mut())
.await?;
- // only commit if there is a channel to create
- if let Some(r) = row {
- tx.commit().await?;
+ // Another request won the race: drop everything, including the
+ // provisional permission rows, by never committing.
+ let Some(r) = row else {
+ return Ok(None);
+ };
- Ok(Some(Call {
- id: r.id,
- channel_id: r.channel_id,
- room_name: r.room_name,
- created_by: r.created_by,
- created_at: r.created_at,
- egress_id: r.egress_id,
- }))
- } else {
- Ok(None)
- }
+ tx.commit().await?;
+
+ Ok(Some(Call {
+ id: r.id,
+ channel_id: r.channel_id,
+ room_name: r.room_name,
+ created_by: r.created_by,
+ created_at: r.created_at,
+ egress_id: r.egress_id,
+ }))
}
#[tracing::instrument(err, skip(self))]
@@ -736,7 +723,12 @@ impl CallRepository for PgCallRepo {
}
#[tracing::instrument(err, skip(self))]
- async fn toggle_share_with_team(&self, call_id: &Uuid) -> Result<(bool, Uuid), Self::Err> {
+ async fn get_team_share_facts(&self, call_id: &Uuid) -> Result<TeamShareFacts, CallError> {
+ team_share::get_team_share_facts(&self.pool, call_id).await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn toggle_share_with_team(&self, call_id: &Uuid) -> Result<(bool, Uuid), CallError> {
let row = sqlx::query!(
r#"
UPDATE calls
@@ -746,14 +738,18 @@ impl CallRepository for PgCallRepo {
"#,
call_id,
)
- .fetch_one(&self.pool)
- .await?;
+ .fetch_optional(&self.pool)
+ .await?
+ .ok_or_else(|| edit::archived_call_conflict(call_id))?;
Ok((row.share_with_team, row.channel_id))
}
#[tracing::instrument(err, skip(self))]
- async fn archive_call(&self, call_id: &Uuid) -> Result<ArchivedCall, Self::Err> {
+ async fn archive_call(&self, call_id: &Uuid) -> Result<ArchivedCall, CallError> {
let mut tx = self.pool.begin().await?;
+ // The live share-with-team intent is translated into canonical team
+ // sharing below, so take the shared guard before moving any rows.
+ share_permission_db_utils::team_share::acquire_guard(&mut tx).await?;
// Fetch and lock the active call so concurrent archive_call callers serialize.
let call = sqlx::query!(
@@ -767,35 +763,7 @@ impl CallRepository for PgCallRepo {
)
.fetch_optional(tx.as_mut())
.await?
- .ok_or(sqlx::Error::RowNotFound)?;
-
- // If the call opted in to team sharing, grant the creator's team View
- // access on the archived call. Silently skip if the creator has no team.
- if call.share_with_team {
- let team_id: Option<Uuid> = sqlx::query_scalar!(
- r#"
- SELECT team_id
- FROM team_user
- WHERE user_id = $1
- LIMIT 1
- "#,
- &call.created_by,
- )
- .fetch_optional(tx.as_mut())
- .await?;
-
- if let Some(team_id) = team_id {
- entity_access_db_utils::insert_entity_access_row(
- &mut tx,
- call_id,
- entity_access_db_utils::EntityType::Call,
- &team_id.to_string(),
- entity_access_db_utils::EntityAccessSourceType::Team,
- entity_access_db_utils::AccessLevel::View,
- )
- .await?;
- }
- }
+ .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;
let ended_at = Utc::now().trunc_subsecs(6);
let duration_ms = ended_at
@@ -805,6 +773,8 @@ impl CallRepository for PgCallRepo {
let has_recording = call.egress_id.is_some();
// Insert into call_records (including egress_id and any early recording keys).
// The record keeps the same id as the original call.
+ // The legacy column is still copied for older readers until it is
+ // dropped; new readers derive `share_with_team` from canonical state.
sqlx::query!(
r#"
INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, share_permission_id, share_with_team)
@@ -827,6 +797,10 @@ impl CallRepository for PgCallRepo {
.execute(tx.as_mut())
.await?;
+ // Translate the live intent into canonical team sharing: View for the
+ // creator's current team when the toggle was on, nothing otherwise.
+ team_share::translate_live_share_with_team(&mut tx, call_id, call.share_with_team).await?;
+
// Copy all lifetime-distinct participants (including soft-deleted) to
// call_record_participants. Each inserted row represents one participant.
let participant_count = sqlx::query!(
@@ -1172,9 +1146,12 @@ impl CallRepository for PgCallRepo {
// Try active `calls` first.
if let Some(active) = sqlx::query!(
r#"
- SELECT id, channel_id, room_name, created_by, created_at, egress_id, recording_key, preview_url, recording_started_at, share_with_team
- FROM calls
- WHERE id = $1
+ SELECT c.id, c.channel_id, c.room_name, c.created_by, c.created_at, c.egress_id, c.recording_key, c.preview_url, c.recording_started_at,
+ c.share_with_team,
+ sp.team_share_access_level AS "team_share_access_level?: AccessLevel"
+ FROM calls c
+ JOIN "SharePermission" sp ON sp.id = c.share_permission_id
+ WHERE c.id = $1
"#,
call_id,
)
@@ -1243,7 +1220,10 @@ impl CallRepository for PgCallRepo {
channel_name: None,
custom_name: None,
summary: None,
+ // Live calls report the pending toggle; canonical state is
+ // written when the call is archived.
share_with_team: active.share_with_team,
+ team_share_access_level: active.team_share_access_level,
is_active: true,
status: None,
participants,
@@ -1254,9 +1234,11 @@ impl CallRepository for PgCallRepo {
// Fall back to archived `call_records`.
let Some(archived) = sqlx::query!(
r#"
- SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, egress_id, recording_key, preview_url, recording_started_at, custom_name, summary, share_with_team
- FROM call_records
- WHERE id = $1
+ SELECT cr.id, cr.channel_id, cr.room_name, cr.created_by, cr.started_at, cr.ended_at, cr.duration_ms, cr.egress_id, cr.recording_key, cr.preview_url, cr.recording_started_at, cr.custom_name, cr.summary,
+ sp.team_share_access_level AS "team_share_access_level?: AccessLevel"
+ FROM call_records cr
+ JOIN "SharePermission" sp ON sp.id = cr.share_permission_id
+ WHERE cr.id = $1
"#,
call_id,
)
@@ -1329,7 +1311,8 @@ impl CallRepository for PgCallRepo {
channel_name: None,
custom_name: archived.custom_name,
summary: archived.summary,
- share_with_team: archived.share_with_team,
+ share_with_team: archived.team_share_access_level.is_some(),
+ team_share_access_level: archived.team_share_access_level,
is_active: false,
status: None,
participants,
@@ -1493,6 +1476,7 @@ impl CallRepository for PgCallRepo {
NULL::text AS custom_name,
NULL::text AS summary,
c.share_with_team,
+ sp.team_share_access_level,
true AS is_active,
CASE
WHEN EXISTS (
@@ -1508,6 +1492,7 @@ impl CallRepository for PgCallRepo {
ELSE 'UNATTENDED'::text
END AS status
FROM calls c
+ JOIN "SharePermission" sp ON sp.id = c.share_permission_id
WHERE EXISTS (
SELECT 1 FROM entity_access ea
JOIN user_source_ids u ON u.source_id = ea.source_id
@@ -1550,7 +1535,8 @@ impl CallRepository for PgCallRepo {
cr.recording_started_at,
cr.custom_name,
cr.summary,
- cr.share_with_team,
+ (sp.team_share_access_level IS NOT NULL) AS share_with_team,
+ sp.team_share_access_level,
false AS is_active,
CASE
WHEN EXISTS (
@@ -1566,6 +1552,7 @@ impl CallRepository for PgCallRepo {
ELSE 'UNATTENDED'::text
END AS status
FROM call_records cr
+ JOIN "SharePermission" sp ON sp.id = cr.share_permission_id
WHERE EXISTS (
SELECT 1 FROM entity_access ea
JOIN user_source_ids u ON u.source_id = ea.source_id
@@ -1609,6 +1596,7 @@ impl CallRepository for PgCallRepo {
custom_name,
summary,
share_with_team as "share_with_team!",
+ team_share_access_level as "team_share_access_level?: AccessLevel",
is_active as "is_active!",
status as "status!"
FROM visible_calls
@@ -1701,6 +1689,7 @@ impl CallRepository for PgCallRepo {
custom_name: row.custom_name,
summary: row.summary,
share_with_team: row.share_with_team,
+ team_share_access_level: row.team_share_access_level,
is_active: row.is_active,
status: Some(call_status_from_sql(&row.status)),
participants,
@@ -1815,23 +1804,33 @@ impl CallRepository for PgCallRepo {
}))
}
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip(self, args), err)]
async fn patch_call_record(
&self,
call_record_id: &Uuid,
- request: &EditCallRecordRequest,
- ) -> Result<(), Self::Err> {
+ args: &EditCallRecordRepoArgs,
+ ) -> Result<(), CallError> {
let mut tx = self.pool.begin().await?;
- if let Some(share_permission) = request.share_permission.as_ref() {
+ // Canonical team sharing first: it takes the shared guard before any
+ // `SharePermission` row lock and refuses an unauthorized team level.
+ team_share::apply_team_share(
+ &mut tx,
+ call_record_id,
+ args.share_permission.as_ref(),
+ args.team_share.as_ref(),
+ )
+ .await?;
+
+ if let Some(share_permission) = args.share_permission.as_ref() {
edit::update_share_permission(&mut tx, call_record_id, share_permission).await?;
}
- if let Some(share_with_team) = request.share_with_team {
- edit::set_share_with_team(&mut tx, call_record_id, share_with_team).await?;
+ if let Some(share) = args.live_share_with_team {
+ edit::set_live_share_with_team(&mut tx, call_record_id, share).await?;
}
- if let Some(custom_name) = request.custom_name.as_deref() {
+ if let Some(custom_name) = args.custom_name.as_deref() {
let custom_name = if custom_name.is_empty() {
None
} else {
diff --git a/crates/call/src/outbound/pg_call_repo/edit.rs b/crates/call/src/outbound/pg_call_repo/edit.rs
index 4a9cb95c25..b6f6b5089b 100644
--- a/crates/call/src/outbound/pg_call_repo/edit.rs
+++ b/crates/call/src/outbound/pg_call_repo/edit.rs
@@ -1,19 +1,21 @@
//! SQL operations for editing call-record share permissions.
-use entity_access_db_utils::{AccessLevel, EntityAccessSourceType};
+use entity_access_db_utils::AccessLevel;
use model_entity::EntityType;
use models_permissions::share_permission::UpdateSharePermissionRequestV2;
use models_permissions::share_permission::channel_share_permission::UpdateOperation;
use sqlx::{Postgres, QueryBuilder, Transaction};
use uuid::Uuid;
-use crate::domain::models::CustomSpeakerAssignment;
+use crate::domain::models::{CallError, CustomSpeakerAssignment};
-/// Update share permissions for a call record.
+/// Update link and channel share permissions for a call record.
///
/// Looks up the call's share permission ID from either the active `calls`
/// table or the archived `call_records` table (both carry `share_permission_id`),
/// then updates the `SharePermission` and `ChannelSharePermission` tables.
+/// Team sharing is not handled here: `team_share::apply_team_share` runs
+/// first in the same transaction and owns the `team_share_*` columns.
pub(super) async fn update_share_permission(
transaction: &mut Transaction<'_, Postgres>,
call_id: &Uuid,
@@ -51,99 +53,32 @@ pub(super) async fn update_share_permission(
Ok(())
}
-/// Grant or revoke the call creator's team's View access on the call.
-///
-/// The team is resolved from the call's `created_by` in either the active
-/// `calls` table or the archived `call_records` table — not from the acting
-/// user. If the creator has no team, this is a no-op. Also keeps the
-/// `calls.share_with_team` and `call_records.share_with_team` flags in sync so
-/// reads and future archiving reflect the latest choice.
-pub(super) async fn set_share_with_team(
+/// The conflict returned when a live-call operation reaches a call that has
+/// been archived meanwhile: its team sharing is canonical now.
+pub(super) fn archived_call_conflict(call_id: &Uuid) -> CallError {
+ CallError::Conflict(format!(
+ "call {call_id} is no longer active; edit team sharing through sharePermission.teamShareAccessLevel"
+ ))
+}
+
+/// Set the pending share-with-team intent on an active call. The intent is
+/// translated into canonical team sharing when the call is archived.
+pub(super) async fn set_live_share_with_team(
transaction: &mut Transaction<'_, Postgres>,
call_id: &Uuid,
share: bool,
-) -> Result<(), sqlx::Error> {
- let created_by: String = sqlx::query_scalar!(
- r#"
- SELECT created_by as "created_by!"
- FROM (
- SELECT created_by FROM calls WHERE id = $1
- UNION ALL
- SELECT created_by FROM call_records WHERE id = $1
- ) t
- LIMIT 1
- "#,
- call_id,
- )
- .fetch_one(transaction.as_mut())
- .await?;
-
- sqlx::query!(
+) -> Result<(), CallError> {
+ let updated = sqlx::query!(
r#"UPDATE calls SET share_with_team = $2 WHERE id = $1"#,
call_id,
share,
)
.execute(transaction.as_mut())
- .await?;
-
- sqlx::query!(
- r#"UPDATE call_records SET share_with_team = $2 WHERE id = $1"#,
- call_id,
- share,
- )
- .execute(transaction.as_mut())
- .await?;
-
- let team_id: Option<Uuid> = sqlx::query_scalar!(
- r#"
- SELECT team_id
- FROM team_user
- WHERE user_id = $1
- LIMIT 1
- "#,
- &created_by,
- )
- .fetch_optional(transaction.as_mut())
- .await?;
-
- let Some(team_id) = team_id else {
- return Ok(());
- };
-
- if share {
- sqlx::query!(
- r#"
- INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
- VALUES ($1, $2, $3, $4, $5)
- ON CONFLICT DO NOTHING
- "#,
- call_id,
- EntityType::Call.as_ref(),
- &team_id.to_string(),
- EntityAccessSourceType::Team as _,
- AccessLevel::View as _,
- )
- .execute(transaction.as_mut())
- .await?;
- } else {
- sqlx::query!(
- r#"
- DELETE FROM entity_access
- WHERE entity_id = $1
- AND entity_type = $2
- AND source_id = $3
- AND source_type = $4
- AND granted_from_project_id IS NULL
- "#,
- call_id,
- EntityType::Call.as_ref(),
- &team_id.to_string(),
- EntityAccessSourceType::Team as _,
- )
- .execute(transaction.as_mut())
- .await?;
+ .await?
+ .rows_affected();
+ if updated == 0 {
+ return Err(archived_call_conflict(call_id));
}
-
Ok(())
}
@@ -223,7 +158,10 @@ pub(super) async fn set_custom_speakers(
Ok(())
}
-/// Update the SharePermission row.
+/// Update the link-share columns of the SharePermission row.
+///
+/// `team_share_access_level` is deliberately ignored: the canonical team-share
+/// command has already been validated and applied by `apply_team_share`.
#[allow(
clippy::disallowed_methods,
reason = "the optional fields require a dynamic SET clause; identifiers are trusted and values are bound"
diff --git a/crates/call/src/outbound/pg_call_repo/team_share.rs b/crates/call/src/outbound/pg_call_repo/team_share.rs
new file mode 100644
index 0000000000..825484b86c
--- /dev/null
+++ b/crates/call/src/outbound/pg_call_repo/team_share.rs
@@ -0,0 +1,200 @@
+//! Canonical team-share persistence for calls.
+//!
+//! While a call is live, "share with team" is a pending intent on the active
+//! `calls` row (`share_with_team`), toggled by participants. Archiving
+//! translates that intent into the shared `SharePermission.team_share_*` state
+//! and the `entity_access` team grant managed by `share_permission_db_utils`;
+//! from then on the creator edits it through the canonical path. Active and
+//! archived calls share one `SharePermission` row (and one call id), so the
+//! same state serves both tables. This module only adapts the shared helpers
+//! to the call repository's error type.
+
+#[cfg(test)]
+mod test;
+
+use entity_access_db_utils::team_share::direct_level;
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+use models_permissions::share_permission::access_level::AccessLevel;
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamShareCreation, TeamShareFacts, TeamShareGrant, TeamShareLevel,
+};
+use share_permission_db_utils::team_share::{self, TeamShareError};
+use sqlx::{PgPool, Postgres, Transaction};
+use uuid::Uuid;
+
+use crate::domain::models::CallError;
+
+// Repository operations that carry domain outcomes (conflicts, forbidden team
+// levels) return `CallError`; plain database failures fold into `Internal`.
+impl From<sqlx::Error> for CallError {
+ fn from(error: sqlx::Error) -> Self {
+ Self::Internal(error.into())
+ }
+}
+
+/// Map a canonical team-share failure onto the call domain error.
+///
+/// Stale or unexplained state surfaces as a conflict so the creator can reload
+/// and retry instead of receiving a 500.
+pub(super) fn map_team_share_error(
+ call_id: &Uuid,
+ error: rootcause::Report<TeamShareError>,
+) -> CallError {
+ match error.current_context() {
+ TeamShareError::NotFound => CallError::NotFound(call_id.to_string()),
+ TeamShareError::ChangedFacts | TeamShareError::UntrackedGrant => {
+ CallError::Conflict(error.to_string())
+ }
+ TeamShareError::InvalidAdoption
+ | TeamShareError::InvalidEntity
+ | TeamShareError::InvalidState
+ | TeamShareError::Infrastructure => CallError::Internal(error.into()),
+ }
+}
+
+fn call_entity(call_id: &Uuid) -> Entity<'static> {
+ EntityType::Call.with_entity_string(call_id.to_string())
+}
+
+/// A direct View grant for the creator's team beside NULL canonical state.
+/// That is what the previous archive code and `shareWithTeam` edits wrote,
+/// including an old writer that re-inserted the row after a canonical clear.
+/// Adopting it lets the creator's next edit succeed instead of conflicting
+/// with an untracked grant. Grants at any other level are not adopted (calls
+/// only share at View) and keep conflicting.
+async fn legacy_view_grant(
+ transaction: &mut Transaction<'_, Postgres>,
+ call_id: &Uuid,
+ facts: &TeamShareFacts,
+) -> Result<Option<TeamShareGrant>, CallError> {
+ if facts.current.is_some() {
+ return Ok(None);
+ }
+ let Some(team_id) = facts.owner_team_id else {
+ return Ok(None);
+ };
+ let level = direct_level(transaction.as_mut(), call_id, EntityType::Call, team_id).await?;
+ Ok(
+ (level == Some(AccessLevel::View)).then_some(TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::View,
+ }),
+ )
+}
+
+/// Read the authoritative facts in one guarded snapshot, adopting a legacy
+/// View grant for the creator's team first (see [`legacy_view_grant`]).
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn get_team_share_facts(
+ pool: &PgPool,
+ call_id: &Uuid,
+) -> Result<TeamShareFacts, CallError> {
+ let entity = call_entity(call_id);
+ let mut transaction = pool.begin().await?;
+ let mut facts = team_share::load_facts(&mut transaction, &entity)
+ .await
+ .map_err(|error| map_team_share_error(call_id, error))?;
+ if let Some(legacy) = legacy_view_grant(&mut transaction, call_id, &facts).await? {
+ team_share::adopt(&mut transaction, &facts, legacy)
+ .await
+ .map_err(|error| map_team_share_error(call_id, error))?;
+ facts = team_share::load_facts(&mut transaction, &entity)
+ .await
+ .map_err(|error| map_team_share_error(call_id, error))?;
+ }
+ transaction.commit().await?;
+ Ok(facts)
+}
+
+/// Translate the live `share_with_team` intent into canonical team sharing
+/// while archiving, inside the archive transaction (which must already hold
+/// the shared guard).
+///
+/// An intent of `true` grants View to the creator's current team, adopting a
+/// legacy View grant an older archive left behind; a creator without a team
+/// promises nothing. Canonical state that already exists (revision above zero)
+/// is left alone: it was decided through the canonical path and outranks the
+/// intent. A legacy grant at another level is left for review rather than
+/// failing the archive.
+#[tracing::instrument(err, skip(transaction))]
+pub(super) async fn translate_live_share_with_team(
+ transaction: &mut Transaction<'_, Postgres>,
+ call_id: &Uuid,
+ share_with_team: bool,
+) -> Result<(), CallError> {
+ let entity = call_entity(call_id);
+ let facts = team_share::load_facts(transaction, &entity)
+ .await
+ .map_err(|error| map_team_share_error(call_id, error))?;
+ if facts.current.is_some() || facts.revision != 0 || !share_with_team {
+ return Ok(());
+ }
+ let Some(team_id) = facts.owner_team_id else {
+ return Ok(());
+ };
+ match direct_level(transaction.as_mut(), call_id, EntityType::Call, team_id).await? {
+ None => team_share::initialize(transaction, &entity, TeamShareCreation::Call)
+ .await
+ .map_err(|error| map_team_share_error(call_id, error)),
+ Some(AccessLevel::View) => team_share::adopt(
+ transaction,
+ &facts,
+ TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::View,
+ },
+ )
+ .await
+ .map_err(|error| map_team_share_error(call_id, error)),
+ Some(level) => {
+ tracing::warn!(
+ %call_id,
+ %team_id,
+ ?level,
+ "archived call has an untracked team grant above view; leaving team sharing unset"
+ );
+ Ok(())
+ }
+ }
+}
+
+/// Apply the creator-authorized canonical team-share command inside the patch
+/// transaction, or refuse a requested team level that arrived without one.
+///
+/// The command must target this call, and when the share-permission patch
+/// names a level it must be exactly the command's target; a command produced
+/// from the legacy `shareWithTeam` alias carries no level in the patch.
+/// Callers run this before other `SharePermission` writes so the shared guard
+/// is acquired before any row locks, matching the chat and document repositories.
+#[tracing::instrument(err, skip(transaction, share_permission, team_share))]
+pub(super) async fn apply_team_share(
+ transaction: &mut Transaction<'_, Postgres>,
+ call_id: &Uuid,
+ share_permission: Option<&UpdateSharePermissionRequestV2>,
+ team_share: Option<&AuthorizedTeamShareCommand>,
+) -> Result<(), CallError> {
+ let requested_level = share_permission.and_then(|p| p.team_share_access_level);
+ match team_share {
+ Some(command) => {
+ let expected = &command.expected().entity;
+ let target_level = command.target().map(|grant| AccessLevel::from(grant.level));
+ let level_matches = requested_level.is_none_or(|level| level == target_level);
+ if expected.entity_type != EntityType::Call
+ || expected.entity_id != call_id.to_string()
+ || !level_matches
+ {
+ return Err(CallError::InvalidRequest(
+ "team-share command does not match patch".to_string(),
+ ));
+ }
+ team_share::apply(transaction, command)
+ .await
+ .map_err(|error| map_team_share_error(call_id, error))
+ }
+ None if requested_level.is_some() => Err(CallError::Forbidden(
+ "only the call's creator may change team sharing".to_string(),
+ )),
+ None => Ok(()),
+ }
+}
diff --git a/crates/call/src/outbound/pg_call_repo/team_share/test.rs b/crates/call/src/outbound/pg_call_repo/team_share/test.rs
new file mode 100644
index 0000000000..edf0052ee2
--- /dev/null
+++ b/crates/call/src/outbound/pg_call_repo/team_share/test.rs
@@ -0,0 +1,868 @@
+//! Team sharing for calls: the live toggle, its translation into canonical
+//! state at archive, creator edits on archived records, and reads.
+
+use std::ops::Deref;
+
+use entity_access_db_utils::team_share::direct_level;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::cowlike::CowLike;
+use model_entity::EntityType;
+use models_permissions::share_permission::access_level::AccessLevel;
+use models_permissions::share_permission::team_share::{
+ AuthorizedTeamShareCommand, TeamShareFacts, TeamShareGrant, TeamShareLevel, TeamShareRequest,
+ authorize_team_share,
+};
+use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use super::super::test::{
+ CALL_ARCHIVED, CALL1, CH1, CH2, USER_A, give_user_a_team, repo, team_entity_access_count,
+};
+use crate::domain::models::{CallError, EditCallRecordRepoArgs};
+use crate::domain::ports::CallRepository;
+use crate::outbound::pg_call_repo::PgCallRepo;
+
+const TEAM_ID: Uuid = Uuid::from_u128(0x7ea3_0000_0000_0000_0000_0000_0000_0001);
+
+fn level_request(level: Option<AccessLevel>) -> UpdateSharePermissionRequestV2 {
+ UpdateSharePermissionRequestV2 {
+ link_share: None,
+ link_share_access_level: None,
+ team_share_access_level: Some(level),
+ channel_share_permissions: None,
+ }
+}
+
+fn args(
+ share_permission: Option<UpdateSharePermissionRequestV2>,
+ team_share: Option<AuthorizedTeamShareCommand>,
+) -> EditCallRecordRepoArgs {
+ EditCallRecordRepoArgs {
+ share_permission,
+ custom_name: None,
+ team_share,
+ live_share_with_team: None,
+ }
+}
+
+fn live_args(share: bool, custom_name: Option<&str>) -> EditCallRecordRepoArgs {
+ EditCallRecordRepoArgs {
+ share_permission: None,
+ custom_name: custom_name.map(str::to_string),
+ team_share: None,
+ live_share_with_team: Some(share),
+ }
+}
+
+/// Authorize `level` exactly as the domain service would for the persisted creator.
+fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeamShareCommand {
+ authorize_team_share(
+ Some(&facts.owner),
+ facts,
+ TeamShareRequest {
+ access_level: Some(level),
+ legacy_enabled: None,
+ },
+ TeamShareLevel::View,
+ )
+ .unwrap()
+ .unwrap()
+}
+
+/// Authorize the deprecated `shareWithTeam` alias as the domain service would.
+fn legacy_command(facts: &TeamShareFacts, enabled: bool) -> AuthorizedTeamShareCommand {
+ authorize_team_share(
+ Some(&facts.owner),
+ facts,
+ TeamShareRequest {
+ access_level: None,
+ legacy_enabled: Some(enabled),
+ },
+ TeamShareLevel::View,
+ )
+ .unwrap()
+ .unwrap()
+}
+
+async fn set_team_share(
+ repo: &PgCallRepo,
+ call_id: Uuid,
+ level: Option<AccessLevel>,
+) -> Result<(), CallError> {
+ let facts = repo.get_team_share_facts(&call_id).await?;
+ repo.patch_call_record(
+ &call_id,
+ &args(Some(level_request(level)), Some(command(&facts, level))),
+ )
+ .await
+}
+
+#[derive(Debug, PartialEq, Eq)]
+struct StoredTeamShare {
+ level: Option<String>,
+ team_id: Option<Uuid>,
+ revision: i64,
+}
+
+async fn stored_team_share(pool: &Pool<Postgres>, call_id: Uuid) -> StoredTeamShare {
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ sp.team_share_access_level::text AS "level?",
+ sp.team_share_team_id AS "team_id?",
+ sp.team_share_revision AS revision
+ FROM "SharePermission" sp
+ WHERE sp.id = (
+ SELECT share_permission_id FROM calls WHERE id = $1
+ UNION ALL
+ SELECT share_permission_id FROM call_records WHERE id = $1
+ LIMIT 1
+ )
+ "#,
+ call_id,
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap();
+ StoredTeamShare {
+ level: row.level,
+ team_id: row.team_id,
+ revision: row.revision,
+ }
+}
+
+fn unshared() -> StoredTeamShare {
+ StoredTeamShare {
+ level: None,
+ team_id: None,
+ revision: 0,
+ }
+}
+
+fn shared_view(revision: i64) -> StoredTeamShare {
+ StoredTeamShare {
+ level: Some("view".to_string()),
+ team_id: Some(TEAM_ID),
+ revision,
+ }
+}
+
+async fn team_row_level(pool: &Pool<Postgres>, call_id: Uuid) -> Option<AccessLevel> {
+ let mut connection = pool.acquire().await.unwrap();
+ direct_level(&mut connection, &call_id, EntityType::Call, TEAM_ID)
+ .await
+ .unwrap()
+}
+
+async fn live_toggle(pool: &Pool<Postgres>, call_id: Uuid) -> bool {
+ sqlx::query_scalar!(
+ r#"SELECT share_with_team FROM calls WHERE id = $1"#,
+ call_id
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+async fn permission_count(pool: &Pool<Postgres>) -> i64 {
+ sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM "SharePermission""#)
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+async fn stored_custom_name(pool: &Pool<Postgres>, call_id: Uuid) -> Option<String> {
+ sqlx::query_scalar!(
+ r#"SELECT custom_name FROM call_records WHERE id = $1"#,
+ call_id
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+/// What the previous archive code and `shareWithTeam` edits wrote: a direct
+/// team grant with no canonical state behind it.
+async fn insert_legacy_team_row(
+ pool: &Pool<Postgres>,
+ call_id: Uuid,
+ level: AccessLevel,
+) -> anyhow::Result<()> {
+ let mut tx = pool.begin().await?;
+ entity_access_db_utils::insert_entity_access_row(
+ &mut tx,
+ &call_id,
+ EntityType::Call,
+ &TEAM_ID.to_string(),
+ entity_access_db_utils::EntityAccessSourceType::Team,
+ level,
+ )
+ .await?;
+ tx.commit().await?;
+ Ok(())
+}
+
+// -- facts --------------------------------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn get_team_share_facts_reads_creator_team_and_null_state(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+
+ for call_id in [CALL1, CALL_ARCHIVED] {
+ let facts = repo.get_team_share_facts(&call_id).await?;
+ assert_eq!(
+ facts.entity,
+ EntityType::Call.with_entity_string(call_id.to_string())
+ );
+ assert_eq!(facts.owner.as_ref(), USER_A.as_ref());
+ assert_eq!(facts.owner_team_id, Some(TEAM_ID));
+ assert_eq!(facts.current, None);
+ assert_eq!(facts.revision, 0);
+ }
+
+ assert!(matches!(
+ repo.get_team_share_facts(&Uuid::now_v7()).await,
+ Err(CallError::NotFound(_))
+ ));
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn get_team_share_facts_adopts_legacy_view_grant_but_not_other_levels(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ insert_legacy_team_row(&pool, CALL_ARCHIVED, AccessLevel::View).await?;
+ insert_legacy_team_row(&pool, CALL1, AccessLevel::Edit).await?;
+
+ // A View grant for the creator's team becomes explicit consent.
+ let adopted = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ assert_eq!(
+ adopted.current,
+ Some(TeamShareGrant {
+ team_id: TEAM_ID,
+ level: TeamShareLevel::View,
+ })
+ );
+ assert_eq!(adopted.revision, 1);
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(1)
+ );
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 1);
+
+ // Calls only share at View: any other level stays untracked.
+ let untouched = repo.get_team_share_facts(&CALL1).await?;
+ assert_eq!(untouched.current, None);
+ assert_eq!(untouched.revision, 0);
+ assert_eq!(team_row_level(&pool, CALL1).await, Some(AccessLevel::Edit));
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn get_team_share_facts_adopts_legacy_view_grant_after_canonical_clear(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+
+ // Canonical clear leaves NULL/rev 2. An old writer then inserts the View
+ // grant without touching SharePermission. Adopt that row so the creator
+ // can revoke it instead of hitting UntrackedGrant forever.
+ sqlx::query!(
+ r#"
+ UPDATE "SharePermission"
+ SET team_share_access_level = NULL,
+ team_share_team_id = NULL,
+ team_share_revision = 2
+ WHERE id = (SELECT share_permission_id FROM call_records WHERE id = $1)
+ "#,
+ CALL_ARCHIVED,
+ )
+ .execute(&pool)
+ .await?;
+ insert_legacy_team_row(&pool, CALL_ARCHIVED, AccessLevel::View).await?;
+
+ let adopted = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ assert_eq!(
+ adopted.current,
+ Some(TeamShareGrant {
+ team_id: TEAM_ID,
+ level: TeamShareLevel::View,
+ })
+ );
+ assert_eq!(adopted.revision, 3);
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(3)
+ );
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 1);
+
+ set_team_share(&repo, CALL_ARCHIVED, None).await?;
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ StoredTeamShare {
+ level: None,
+ team_id: None,
+ revision: 4,
+ }
+ );
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 0);
+ Ok(())
+}
+
+// -- create_call --------------------------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn create_call_starts_with_toggle_on_and_no_canonical_state(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ let id = Uuid::now_v7();
+
+ repo.create_call(&id, &CH2, "room-ch2", USER_A.copied())
+ .await?
+ .expect("call created");
+
+ // The pending toggle defaults to on; nothing is granted until archive.
+ assert!(live_toggle(&pool, id).await);
+ assert_eq!(stored_team_share(&pool, id).await, unshared());
+ assert_eq!(team_entity_access_count(&pool, id).await?, 0);
+ let record = repo.get_call_record_by_call_id(&id).await?.unwrap();
+ assert!(record.share_with_team);
+ assert_eq!(record.team_share_access_level, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn create_call_lost_race_leaves_no_permission_or_grant_rows(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ let permissions_before = permission_count(&pool).await;
+ let id = Uuid::now_v7();
+
+ // CH1 already has an active call (the fixture's CALL1).
+ let created = repo
+ .create_call(&id, &CH1, "room-dup", USER_A.copied())
+ .await?;
+
+ assert!(created.is_none());
+ assert_eq!(permission_count(&pool).await, permissions_before);
+ let grants = sqlx::query_scalar!(
+ r#"SELECT COUNT(*) AS "count!" FROM entity_access WHERE entity_id = $1"#,
+ id
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(grants, 0);
+ Ok(())
+}
+
+// -- the live toggle ----------------------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn toggle_share_with_team_flips_live_call_and_conflicts_once_archived(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+
+ assert_eq!(repo.toggle_share_with_team(&CALL1).await?, (false, CH1));
+ assert!(!live_toggle(&pool, CALL1).await);
+ assert!(
+ !repo
+ .get_call_record_by_call_id(&CALL1)
+ .await?
+ .unwrap()
+ .share_with_team
+ );
+
+ assert_eq!(repo.toggle_share_with_team(&CALL1).await?, (true, CH1));
+ assert!(live_toggle(&pool, CALL1).await);
+ // Flipping the toggle never touches canonical state or grants.
+ assert_eq!(stored_team_share(&pool, CALL1).await, unshared());
+ assert_eq!(team_entity_access_count(&pool, CALL1).await?, 0);
+
+ assert!(matches!(
+ repo.toggle_share_with_team(&CALL_ARCHIVED).await,
+ Err(CallError::Conflict(_))
+ ));
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_live_share_with_team_sets_toggle_and_conflicts_once_archived(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+
+ repo.patch_call_record(&CALL1, &live_args(false, None))
+ .await?;
+ assert!(!live_toggle(&pool, CALL1).await);
+ assert_eq!(stored_team_share(&pool, CALL1).await, unshared());
+
+ repo.patch_call_record(&CALL1, &live_args(true, None))
+ .await?;
+ assert!(live_toggle(&pool, CALL1).await);
+
+ // The call was archived between the service's read and the write: the
+ // whole patch rolls back and the caller retries through the canonical path.
+ let result = repo
+ .patch_call_record(&CALL_ARCHIVED, &live_args(true, Some("must not persist")))
+ .await;
+ assert!(matches!(result, Err(CallError::Conflict(_))));
+ assert_eq!(stored_custom_name(&pool, CALL_ARCHIVED).await, None);
+ assert_eq!(stored_team_share(&pool, CALL_ARCHIVED).await, unshared());
+ Ok(())
+}
+
+// -- archive_call -------------------------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn archive_translates_toggle_on_into_canonical_view(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ assert!(live_toggle(&pool, CALL1).await);
+
+ repo.archive_call(&CALL1).await?;
+
+ assert_eq!(stored_team_share(&pool, CALL1).await, shared_view(1));
+ assert_eq!(team_row_level(&pool, CALL1).await, Some(AccessLevel::View));
+ assert_eq!(team_entity_access_count(&pool, CALL1).await?, 1);
+ let record = repo.get_call_record_by_call_id(&CALL1).await?.unwrap();
+ assert!(!record.is_active);
+ assert_eq!(record.team_share_access_level, Some(AccessLevel::View));
+ assert!(record.share_with_team);
+
+ // The creator can now edit the canonical state the archive produced.
+ set_team_share(&repo, CALL1, None).await?;
+ assert_eq!(stored_team_share(&pool, CALL1).await.revision, 2);
+ assert_eq!(team_entity_access_count(&pool, CALL1).await?, 0);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn archive_translates_toggle_off_into_unshared(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ repo.toggle_share_with_team(&CALL1).await?;
+ assert!(!live_toggle(&pool, CALL1).await);
+
+ repo.archive_call(&CALL1).await?;
+
+ assert_eq!(stored_team_share(&pool, CALL1).await, unshared());
+ assert_eq!(team_entity_access_count(&pool, CALL1).await?, 0);
+ let record = repo.get_call_record_by_call_id(&CALL1).await?.unwrap();
+ assert_eq!(record.team_share_access_level, None);
+ assert!(!record.share_with_team);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn archive_with_toggle_on_but_no_team_shares_nothing(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ assert!(live_toggle(&pool, CALL1).await);
+
+ repo.archive_call(&CALL1).await?;
+
+ assert_eq!(stored_team_share(&pool, CALL1).await, unshared());
+ assert_eq!(team_entity_access_count(&pool, CALL1).await?, 0);
+ // Once archived, the boolean mirrors canonical state, not the old toggle.
+ let record = repo.get_call_record_by_call_id(&CALL1).await?.unwrap();
+ assert!(!record.share_with_team);
+ assert_eq!(record.team_share_access_level, None);
+
+ // Joining a team afterwards does not reshare the archived record.
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ assert_eq!(repo.get_team_share_facts(&CALL1).await?.current, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn archive_adopts_legacy_view_grant_and_leaves_other_levels(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+
+ // An older archive (or `shareWithTeam` edit) already wrote the View row.
+ let adopted = Uuid::now_v7();
+ repo.create_call(&adopted, &CH2, "adopted", USER_A.copied())
+ .await?
+ .expect("call created");
+ insert_legacy_team_row(&pool, adopted, AccessLevel::View).await?;
+ repo.archive_call(&adopted).await?;
+ assert_eq!(stored_team_share(&pool, adopted).await, shared_view(1));
+ assert_eq!(team_entity_access_count(&pool, adopted).await?, 1);
+
+ // A grant above View is left for review; the archive itself still succeeds.
+ insert_legacy_team_row(&pool, CALL1, AccessLevel::Edit).await?;
+ repo.archive_call(&CALL1).await?;
+ assert_eq!(stored_team_share(&pool, CALL1).await, unshared());
+ assert_eq!(team_row_level(&pool, CALL1).await, Some(AccessLevel::Edit));
+ Ok(())
+}
+
+// -- creator edits on archived calls ------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_applies_view_command_on_archived_call(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+
+ set_team_share(&repo, CALL_ARCHIVED, Some(AccessLevel::View)).await?;
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(1)
+ );
+ assert_eq!(
+ team_row_level(&pool, CALL_ARCHIVED).await,
+ Some(AccessLevel::View)
+ );
+ let record = repo
+ .get_call_record_by_call_id(&CALL_ARCHIVED)
+ .await?
+ .unwrap();
+ assert_eq!(record.team_share_access_level, Some(AccessLevel::View));
+ assert!(record.share_with_team);
+
+ // Re-selecting the same level is a supplied operation: it advances the
+ // revision without adding a second grant.
+ set_team_share(&repo, CALL_ARCHIVED, Some(AccessLevel::View)).await?;
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(2)
+ );
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 1);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_clear_removes_team_row_and_bumps_revision(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ set_team_share(&repo, CALL_ARCHIVED, Some(AccessLevel::View)).await?;
+
+ set_team_share(&repo, CALL_ARCHIVED, None).await?;
+
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ StoredTeamShare {
+ level: None,
+ team_id: None,
+ revision: 2,
+ }
+ );
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 0);
+ let record = repo
+ .get_call_record_by_call_id(&CALL_ARCHIVED)
+ .await?
+ .unwrap();
+ assert_eq!(record.team_share_access_level, None);
+ assert!(!record.share_with_team);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_legacy_alias_command_enables_view_and_clears(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+
+ // `shareWithTeam: true` carries no level in the share-permission patch.
+ let facts = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ repo.patch_call_record(
+ &CALL_ARCHIVED,
+ &args(None, Some(legacy_command(&facts, true))),
+ )
+ .await?;
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(1)
+ );
+ assert_eq!(
+ team_row_level(&pool, CALL_ARCHIVED).await,
+ Some(AccessLevel::View)
+ );
+
+ let facts = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ repo.patch_call_record(
+ &CALL_ARCHIVED,
+ &args(None, Some(legacy_command(&facts, false))),
+ )
+ .await?;
+ assert_eq!(stored_team_share(&pool, CALL_ARCHIVED).await.revision, 2);
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 0);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_with_team_level_but_no_command_is_forbidden_and_rolls_back(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+
+ let result = repo
+ .patch_call_record(
+ &CALL_ARCHIVED,
+ &EditCallRecordRepoArgs {
+ share_permission: Some(level_request(Some(AccessLevel::View))),
+ custom_name: Some("must not persist".to_string()),
+ team_share: None,
+ live_share_with_team: None,
+ },
+ )
+ .await;
+
+ assert!(matches!(result, Err(CallError::Forbidden(_))));
+ assert_eq!(stored_team_share(&pool, CALL_ARCHIVED).await, unshared());
+ assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 0);
+ // The whole patch is rolled back, not just the team share.
+ assert_eq!(stored_custom_name(&pool, CALL_ARCHIVED).await, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_rejects_command_for_other_call_or_mismatched_level(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ let facts = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ let other_facts = repo.get_team_share_facts(&CALL1).await?;
+
+ let wrong_call = repo
+ .patch_call_record(
+ &CALL_ARCHIVED,
+ &args(
+ Some(level_request(Some(AccessLevel::View))),
+ Some(command(&other_facts, Some(AccessLevel::View))),
+ ),
+ )
+ .await;
+ assert!(matches!(wrong_call, Err(CallError::InvalidRequest(_))));
+
+ // The patch asks to clear while the command grants View.
+ let wrong_level = repo
+ .patch_call_record(
+ &CALL_ARCHIVED,
+ &args(
+ Some(level_request(None)),
+ Some(command(&facts, Some(AccessLevel::View))),
+ ),
+ )
+ .await;
+ assert!(matches!(wrong_level, Err(CallError::InvalidRequest(_))));
+
+ assert_eq!(stored_team_share(&pool, CALL_ARCHIVED).await, unshared());
+ assert_eq!(stored_team_share(&pool, CALL1).await, unshared());
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_stale_command_returns_conflict(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ let facts = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ let stale = command(&facts, Some(AccessLevel::View));
+
+ set_team_share(&repo, CALL_ARCHIVED, Some(AccessLevel::View)).await?;
+
+ let replay = repo
+ .patch_call_record(
+ &CALL_ARCHIVED,
+ &args(Some(level_request(Some(AccessLevel::View))), Some(stale)),
+ )
+ .await;
+
+ assert!(matches!(replay, Err(CallError::Conflict(_))));
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(1)
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_untracked_legacy_grant_returns_conflict_without_partial_writes(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ // A grant above View is never adopted, so it stays an untracked conflict.
+ insert_legacy_team_row(&pool, CALL_ARCHIVED, AccessLevel::Edit).await?;
+ let facts = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+ assert_eq!(facts.current, None);
+
+ let result = repo
+ .patch_call_record(
+ &CALL_ARCHIVED,
+ &EditCallRecordRepoArgs {
+ share_permission: Some(level_request(Some(AccessLevel::View))),
+ custom_name: Some("must not persist".to_string()),
+ team_share: Some(command(&facts, Some(AccessLevel::View))),
+ live_share_with_team: None,
+ },
+ )
+ .await;
+
+ assert!(matches!(result, Err(CallError::Conflict(_))));
+ assert_eq!(stored_team_share(&pool, CALL_ARCHIVED).await, unshared());
+ assert_eq!(stored_custom_name(&pool, CALL_ARCHIVED).await, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_team_share_link_share_and_name_in_one_call_persist_together(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ let facts = repo.get_team_share_facts(&CALL_ARCHIVED).await?;
+
+ repo.patch_call_record(
+ &CALL_ARCHIVED,
+ &EditCallRecordRepoArgs {
+ share_permission: Some(UpdateSharePermissionRequestV2 {
+ link_share: Some(Some(LinkShare::Public)),
+ link_share_access_level: None,
+ team_share_access_level: Some(Some(AccessLevel::View)),
+ channel_share_permissions: None,
+ }),
+ custom_name: Some("Q4 sync".to_string()),
+ team_share: Some(command(&facts, Some(AccessLevel::View))),
+ live_share_with_team: None,
+ },
+ )
+ .await?;
+
+ assert_eq!(
+ stored_team_share(&pool, CALL_ARCHIVED).await,
+ shared_view(1)
+ );
+ let link_share = sqlx::query_scalar!(
+ r#"
+ SELECT sp."linkShare" AS "link_share?"
+ FROM "SharePermission" sp
+ JOIN call_records cr ON cr.share_permission_id = sp.id
+ WHERE cr.id = $1
+ "#,
+ CALL_ARCHIVED,
+ )
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(link_share.as_deref(), Some("PUBLIC"));
+ assert_eq!(
+ stored_custom_name(&pool, CALL_ARCHIVED).await.as_deref(),
+ Some("Q4 sync")
+ );
+ Ok(())
+}
+
+// -- reads --------------------------------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn list_read_reports_live_toggle_and_canonical_state(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+ give_user_a_team(&pool, USER_A.as_ref(), &TEAM_ID).await?;
+ repo.toggle_share_with_team(&CALL1).await?;
+ set_team_share(&repo, CALL_ARCHIVED, Some(AccessLevel::View)).await?;
+
+ let records = repo
+ .get_call_records_by_user(USER_A.deref().copied(), 10, &None)
+ .await?;
+
+ // Live: the pending toggle (now off), no canonical level yet.
+ let active = records
+ .iter()
+ .find(|record| record.call_id == CALL1)
+ .expect("active call listed");
+ assert!(!active.share_with_team);
+ assert_eq!(active.team_share_access_level, None);
+
+ // Archived: canonical state.
+ let archived = records
+ .iter()
+ .find(|record| record.call_id == CALL_ARCHIVED)
+ .expect("archived call listed");
+ assert!(archived.share_with_team);
+ assert_eq!(archived.team_share_access_level, Some(AccessLevel::View));
+
+ Ok(())
+}
diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rs
index 5db322b9f4..81aed4ac61 100644
--- a/crates/call/src/outbound/pg_call_repo/test.rs
+++ b/crates/call/src/outbound/pg_call_repo/test.rs
@@ -2,7 +2,7 @@ use std::{ops::Deref, sync::Arc, sync::LazyLock};
use crate::domain::models::{
AddParticipantError, CallRecord, CallRecordPreview, CustomSpeakerAssignment,
- EditCallRecordRequest, TranscriptSegmentRequest,
+ EditCallRecordRepoArgs, TranscriptSegmentRequest,
};
use crate::domain::ports::CallRepository;
use crate::outbound::pg_call_repo::PgCallRepo;
@@ -96,24 +96,24 @@ fn call_ids_filter(ids: &[Uuid]) -> LiteralTree<CallLiteral> {
Some(Arc::new(expr))
}
-const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);
-const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);
-const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
+pub(super) const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);
+pub(super) const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);
+pub(super) const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
const CALL2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca220);
-const CALL_ARCHIVED: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca2ed);
+pub(super) const CALL_ARCHIVED: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca2ed);
const MACRO_USER_A: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaa1);
const MACRO_USER_B: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbb2);
const MACRO_USER_C: Uuid = Uuid::from_u128(0xcccccccc_cccc_cccc_cccc_ccccccccccc3);
-static USER_A: LazyLock<MacroUserIdStr<'static>> =
+pub(super) static USER_A: LazyLock<MacroUserIdStr<'static>> =
LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
-static USER_B: LazyLock<MacroUserIdStr<'static>> =
+pub(super) static USER_B: LazyLock<MacroUserIdStr<'static>> =
LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
static USER_C: LazyLock<MacroUserIdStr<'static>> =
LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
static USER_D: LazyLock<MacroUserIdStr<'static>> =
LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
-fn repo(pool: Pool<Postgres>) -> PgCallRepo {
+pub(super) fn repo(pool: Pool<Postgres>) -> PgCallRepo {
PgCallRepo::new(pool)
}
@@ -743,7 +743,7 @@ async fn archive_call_returns_no_result_when_call_is_missing(
/// Test helper: give `user_id` a brand new team owned by that user. Inserts
/// the parent `macro_user` and `User` rows that the `team_user` FK requires.
-async fn give_user_a_team(
+pub(super) async fn give_user_a_team(
pool: &Pool<Postgres>,
user_id: &str,
team_id: &Uuid,
@@ -782,19 +782,10 @@ async fn give_user_a_team(
Ok(())
}
-async fn stored_call_record_share_with_team(
+pub(super) async fn team_entity_access_count(
pool: &Pool<Postgres>,
call_id: Uuid,
-) -> anyhow::Result<bool> {
- Ok(sqlx::query_scalar!(
- r#"SELECT share_with_team FROM call_records WHERE id = $1"#,
- call_id,
- )
- .fetch_one(pool)
- .await?)
-}
-
-async fn team_entity_access_count(pool: &Pool<Postgres>, call_id: Uuid) -> anyhow::Result<i64> {
+) -> anyhow::Result<i64> {
Ok(sqlx::query_scalar!(
r#"SELECT COUNT(*) as "count!" FROM entity_access WHERE entity_id = $1 AND source_type = 'team'"#,
call_id,
@@ -803,83 +794,8 @@ async fn team_entity_access_count(pool: &Pool<Postgres>, call_id: Uuid) -> anyho
.await?)
}
-// -- archive_call grants team view access when share_with_team is true -------
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn archive_call_grants_team_view_access_when_share_with_team_true(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- use sqlx::Row as _;
-
- let repo = repo(pool.clone());
- let team_id: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaaa);
-
- give_user_a_team(&pool, USER_A.as_ref(), &team_id).await?;
-
- // share_with_team defaults to TRUE on the fixture call.
- repo.archive_call(&CALL1).await?;
-
- let row = sqlx::query(
- r#"
- SELECT entity_id, entity_type, source_id, access_level
- FROM entity_access
- WHERE entity_id = $1 AND source_type = 'team'
- "#,
- )
- .bind(CALL1)
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(row.get::<Uuid, _>("entity_id"), CALL1);
- assert_eq!(row.get::<String, _>("entity_type"), "call");
- assert_eq!(row.get::<String, _>("source_id"), team_id.to_string());
- assert_eq!(row.get::<AccessLevel, _>("access_level"), AccessLevel::View);
- assert!(stored_call_record_share_with_team(&pool, CALL1).await?);
-
- Ok(())
-}
-
-// -- archive_call skips team grant when share_with_team is false -------------
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn archive_call_skips_team_grant_when_share_with_team_false(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- use sqlx::Row as _;
-
- let repo = repo(pool.clone());
- let team_id: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbbb);
-
- // USER_A is on a team, but the call opted out of team sharing — so no
- // team-scoped entity_access row should be created at archive time.
- give_user_a_team(&pool, USER_A.as_ref(), &team_id).await?;
-
- sqlx::query(r#"UPDATE calls SET share_with_team = false WHERE id = $1"#)
- .bind(CALL1)
- .execute(&pool)
- .await?;
-
- repo.archive_call(&CALL1).await?;
-
- let count: i64 = sqlx::query(
- r#"SELECT COUNT(*) AS count FROM entity_access WHERE entity_id = $1 AND source_type = 'team'"#,
- )
- .bind(CALL1)
- .map(|r: sqlx::postgres::PgRow| r.get::<i64, _>("count"))
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(count, 0);
- assert!(!stored_call_record_share_with_team(&pool, CALL1).await?);
-
- Ok(())
-}
+// Team sharing across archive is covered in `team_share/test.rs`: archive
+// neither grants nor revokes anything; canonical state simply carries over.
// -- archive_call preserves id and share_permission_id ------------------------
@@ -1467,13 +1383,6 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Re
let repo = repo(pool.clone());
let now = Utc::now();
- sqlx::query!(
- r#"UPDATE calls SET share_with_team = false WHERE id = $1"#,
- CALL1,
- )
- .execute(&pool)
- .await?;
-
// Ingest two transcript segments into the active call.
repo.create_transcript_segment(
&CALL1,
@@ -1516,7 +1425,10 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Re
assert_eq!(record.call_id, CALL1);
assert_eq!(record.channel_id, CH1);
assert!(record.is_active);
- assert!(!record.share_with_team);
+ // Live calls report the pending toggle (on by default); canonical state
+ // is only written when the call is archived.
+ assert_eq!(record.team_share_access_level, None);
+ assert!(record.share_with_team);
assert_eq!(record.status, None);
assert!(record.ended_at.is_none());
assert!(record.duration_ms.is_none());
@@ -1554,13 +1466,6 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Re
async fn get_call_record_returns_archived_call(pool: Pool<Postgres>) -> anyhow::Result<()> {
let repo = repo(pool.clone());
- sqlx::query!(
- r#"UPDATE call_records SET share_with_team = false WHERE id = $1"#,
- CALL_ARCHIVED,
- )
- .execute(&pool)
- .await?;
-
let record = repo
.get_call_record_by_call_id(&CALL_ARCHIVED)
.await?
@@ -1569,6 +1474,7 @@ async fn get_call_record_returns_archived_call(pool: Pool<Postgres>) -> anyhow::
assert_eq!(record.call_id, CALL_ARCHIVED);
assert_eq!(record.channel_id, CH1);
assert!(!record.is_active);
+ assert_eq!(record.team_share_access_level, None);
assert!(!record.share_with_team);
assert_eq!(record.status, None);
assert!(record.ended_at.is_some());
@@ -2051,43 +1957,6 @@ async fn get_call_records_by_user_returns_archived_summary(
Ok(())
}
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn get_call_records_by_user_returns_share_with_team(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
-
- sqlx::query!(
- r#"UPDATE call_records SET share_with_team = false WHERE id = $1"#,
- CALL_ARCHIVED,
- )
- .execute(&pool)
- .await?;
-
- let records = repo
- .get_call_records_by_user(USER_A.deref().copied(), 10, &None)
- .await?;
-
- let active = records
- .iter()
- .find(|r| r.call_id == CALL1)
- .expect("active call missing");
- assert!(active.is_active);
- assert!(active.share_with_team);
-
- let archived = records
- .iter()
- .find(|r| r.call_id == CALL_ARCHIVED)
- .expect("archived call missing");
- assert!(!archived.is_active);
- assert!(!archived.share_with_team);
-
- Ok(())
-}
-
// -- delete_call_record -------------------------------------------------------
#[sqlx::test(
@@ -2223,14 +2092,15 @@ async fn patch_call_record_sets_public_link_and_defaults_level_to_view(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Public)),
link_share_access_level: None,
team_share_access_level: None,
channel_share_permissions: None,
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2253,14 +2123,15 @@ async fn patch_call_record_sets_team_link_and_explicit_level(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(Some(LinkShare::Team)),
link_share_access_level: Some(Some(AccessLevel::Edit)),
team_share_access_level: None,
channel_share_permissions: None,
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2284,14 +2155,15 @@ async fn patch_call_record_explicit_null_disables_link_sharing(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: Some(None),
link_share_access_level: Some(Some(AccessLevel::Edit)),
team_share_access_level: None,
channel_share_permissions: None,
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2320,14 +2192,15 @@ async fn patch_call_record_level_only_update_updates_link_share_access_level(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: Some(Some(AccessLevel::Comment)),
team_share_access_level: None,
channel_share_permissions: None,
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2354,7 +2227,7 @@ async fn patch_call_record_adds_channel_share_permission(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
@@ -2365,7 +2238,8 @@ async fn patch_call_record_adds_channel_share_permission(
access_level: Some(AccessLevel::View),
}]),
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2430,7 +2304,7 @@ async fn patch_call_record_removes_channel_share_permission(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
@@ -2441,7 +2315,8 @@ async fn patch_call_record_removes_channel_share_permission(
access_level: None,
}]),
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2475,14 +2350,15 @@ async fn patch_call_record_empty_share_permission_update_is_noop(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: Some(UpdateSharePermissionRequestV2 {
link_share: None,
link_share_access_level: None,
team_share_access_level: None,
channel_share_permissions: None,
}),
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2506,9 +2382,10 @@ async fn patch_call_record_sets_custom_name_on_archived_record(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: None,
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: Some("Q4 sync".to_string()),
},
)
@@ -2549,9 +2426,10 @@ async fn patch_call_record_custom_name_overwrites_existing(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: None,
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: Some("New name".to_string()),
},
)
@@ -2586,9 +2464,10 @@ async fn patch_call_record_custom_name_empty_string_clears_existing(
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: None,
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: Some(String::new()),
},
)
@@ -2621,9 +2500,10 @@ async fn patch_call_record_custom_name_none_is_noop(pool: Pool<Postgres>) -> any
repo.patch_call_record(
&CALL_ARCHIVED,
- &EditCallRecordRequest {
+ &EditCallRecordRepoArgs {
share_permission: None,
- share_with_team: None,
+ team_share: None,
+ live_share_with_team: None,
custom_name: None,
},
)
@@ -2639,286 +2519,6 @@ async fn patch_call_record_custom_name_none_is_noop(pool: Pool<Postgres>) -> any
Ok(())
}
-// -- patch_call_record: share_with_team ---------------------------------------
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_record_share_with_team_true_grants_team_access_on_active_call(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
- let team_id: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaa001);
-
- // The active call's created_by is USER_A — that's the team we should grant.
- give_user_a_team(&pool, USER_A.as_ref(), &team_id).await?;
-
- repo.patch_call_record(
- &CALL1,
- &EditCallRecordRequest {
- share_permission: None,
- share_with_team: Some(true),
- custom_name: None,
- },
- )
- .await?;
-
- let row = sqlx::query!(
- r#"
- SELECT source_id, access_level::text as "access_level"
- FROM entity_access
- WHERE entity_id = $1 AND entity_type = 'call' AND source_type = 'team'
- "#,
- CALL1,
- )
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(row.source_id, team_id.to_string());
- assert_eq!(row.access_level.as_deref(), Some("view"));
-
- let flag = sqlx::query_scalar!(r#"SELECT share_with_team FROM calls WHERE id = $1"#, CALL1,)
- .fetch_one(&pool)
- .await?;
- assert!(flag);
-
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_record_share_with_team_false_removes_team_access(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
- let team_id: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaa002);
-
- give_user_a_team(&pool, USER_A.as_ref(), &team_id).await?;
-
- // Pre-seed a team entity_access row so we can observe the deletion.
- sqlx::query(
- r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
- VALUES ($1, 'call', $2, 'team', 'view')"#,
- )
- .bind(CALL1)
- .bind(team_id.to_string())
- .execute(&pool)
- .await?;
-
- repo.patch_call_record(
- &CALL1,
- &EditCallRecordRequest {
- share_permission: None,
- share_with_team: Some(false),
- custom_name: None,
- },
- )
- .await?;
-
- let count = sqlx::query_scalar!(
- r#"SELECT COUNT(*) as "count!" FROM entity_access
- WHERE entity_id = $1 AND source_type = 'team'"#,
- CALL1,
- )
- .fetch_one(&pool)
- .await?;
- assert_eq!(count, 0);
-
- let flag = sqlx::query_scalar!(r#"SELECT share_with_team FROM calls WHERE id = $1"#, CALL1,)
- .fetch_one(&pool)
- .await?;
- assert!(!flag);
-
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_record_share_with_team_works_on_archived_record(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
- let team_id: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaa003);
-
- // CALL_ARCHIVED was created by USER_A; its team should get View.
- give_user_a_team(&pool, USER_A.as_ref(), &team_id).await?;
-
- repo.patch_call_record(
- &CALL_ARCHIVED,
- &EditCallRecordRequest {
- share_permission: None,
- share_with_team: Some(true),
- custom_name: None,
- },
- )
- .await?;
-
- let row = sqlx::query!(
- r#"
- SELECT source_id, access_level::text as "access_level"
- FROM entity_access
- WHERE entity_id = $1 AND entity_type = 'call' AND source_type = 'team'
- "#,
- CALL_ARCHIVED,
- )
- .fetch_one(&pool)
- .await?;
-
- assert_eq!(row.source_id, team_id.to_string());
- assert_eq!(row.access_level.as_deref(), Some("view"));
- assert!(stored_call_record_share_with_team(&pool, CALL_ARCHIVED).await?);
-
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_record_share_with_team_false_updates_archived_record_and_removes_team_access(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
- let team_id: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaa013);
-
- give_user_a_team(&pool, USER_A.as_ref(), &team_id).await?;
-
- sqlx::query!(
- r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
- VALUES ($1, 'call', $2, 'team', 'view')"#,
- CALL_ARCHIVED,
- team_id.to_string(),
- )
- .execute(&pool)
- .await?;
-
- repo.patch_call_record(
- &CALL_ARCHIVED,
- &EditCallRecordRequest {
- share_permission: None,
- share_with_team: Some(false),
- custom_name: None,
- },
- )
- .await?;
-
- assert_eq!(team_entity_access_count(&pool, CALL_ARCHIVED).await?, 0);
- assert!(!stored_call_record_share_with_team(&pool, CALL_ARCHIVED).await?);
-
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_record_share_with_team_ignores_non_creator_teams(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
- let creator_team: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaa004);
- let other_team: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbb004);
- let other_macro_user_id = Uuid::now_v7();
-
- // USER_A (the call creator) is on `creator_team`.
- give_user_a_team(&pool, USER_A.as_ref(), &creator_team).await?;
-
- // Seed a second team whose owner is a different user (USER_B). The repo
- // must not grant access to this team — the lookup keys off the call's
- // created_by (USER_A), not off any other user's team membership.
- sqlx::query(
- r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, $4)"#,
- )
- .bind(other_macro_user_id)
- .bind(USER_B.as_ref())
- .bind("cus_other")
- .execute(&pool)
- .await?;
- sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#)
- .bind(USER_B.as_ref())
- .bind(other_macro_user_id)
- .execute(&pool)
- .await?;
- sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)
- .bind(other_team)
- .bind("unrelated team")
- .bind(USER_B.as_ref())
- .execute(&pool)
- .await?;
- sqlx::query(r#"INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'owner')"#)
- .bind(USER_B.as_ref())
- .bind(other_team)
- .execute(&pool)
- .await?;
-
- repo.patch_call_record(
- &CALL1,
- &EditCallRecordRequest {
- share_permission: None,
- share_with_team: Some(true),
- custom_name: None,
- },
- )
- .await?;
-
- let source_ids: Vec<String> = sqlx::query_scalar!(
- r#"SELECT source_id FROM entity_access
- WHERE entity_id = $1 AND source_type = 'team'"#,
- CALL1,
- )
- .fetch_all(&pool)
- .await?;
-
- assert_eq!(source_ids, vec![creator_team.to_string()]);
-
- Ok(())
-}
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_record_share_with_team_true_noop_when_creator_has_no_team(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
-
- // USER_A is the creator and has no team — the call should succeed but
- // not create any team entity_access rows.
- repo.patch_call_record(
- &CALL1,
- &EditCallRecordRequest {
- share_permission: None,
- share_with_team: Some(true),
- custom_name: None,
- },
- )
- .await?;
-
- let count = sqlx::query_scalar!(
- r#"SELECT COUNT(*) as "count!" FROM entity_access
- WHERE entity_id = $1 AND source_type = 'team'"#,
- CALL1,
- )
- .fetch_one(&pool)
- .await?;
- assert_eq!(count, 0);
-
- let flag = sqlx::query_scalar!(r#"SELECT share_with_team FROM calls WHERE id = $1"#, CALL1,)
- .fetch_one(&pool)
- .await?;
- assert!(flag);
-
- Ok(())
-}
-
// -- set_custom_name_if_null --------------------------------------------------
#[sqlx::test(
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs
index ae88a7038f..9064a93689 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs
@@ -383,6 +383,102 @@ async fn preserves_user_channel_and_team_entity_access(pool: PgPool) -> anyhow::
Ok(())
}
+/// A canonical team share: the `entity_access` row
+/// `share_permission_db_utils::team_share` writes for the creator's team on a
+/// call (calls only ever grant `view`).
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn explicit_team_grant_allows_team_members_only(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER_WITH_TEAM).await?;
+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;
+
+ let anonymous = SourceIds(vec![]);
+ let other_team = SourceIds(vec![REQUESTER.to_string(), OTHER_TEAM.to_string()]);
+ let same_team = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);
+
+ for call_table in CallTable::ALL {
+ let call_id =
+ insert_link_shared_call(&pool, call_table, OWNER_WITH_TEAM, None, None).await?;
+ insert_entity_access(
+ &pool,
+ call_id,
+ &OWNER_TEAM.to_string(),
+ "team",
+ AccessLevel::View,
+ )
+ .await?;
+
+ assert_eq!(
+ get_call_access(&pool, &call_id, &anonymous).await?,
+ None,
+ "anonymous access for {call_table:?}"
+ );
+ assert_eq!(
+ get_call_access(&pool, &call_id, &other_team).await?,
+ None,
+ "other-team access for {call_table:?}"
+ );
+ assert_eq!(
+ get_call_access(&pool, &call_id, &same_team).await?,
+ Some(AccessLevel::View),
+ "same-team access for {call_table:?}"
+ );
+ }
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn takes_maximum_of_explicit_team_grant_and_link(pool: PgPool) -> anyhow::Result<()> {
+ insert_user(&pool, OWNER_WITH_TEAM).await?;
+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;
+ let same_team = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);
+
+ for call_table in CallTable::ALL {
+ // Team grant (view) below a public edit link: the link wins.
+ let link_wins = insert_link_shared_call(
+ &pool,
+ call_table,
+ OWNER_WITH_TEAM,
+ Some("PUBLIC"),
+ Some("edit"),
+ )
+ .await?;
+ insert_entity_access(
+ &pool,
+ link_wins,
+ &OWNER_TEAM.to_string(),
+ "team",
+ AccessLevel::View,
+ )
+ .await?;
+
+ // Team grant (view) with no link at all: the grant is the whole answer.
+ let grant_only =
+ insert_link_shared_call(&pool, call_table, OWNER_WITH_TEAM, None, None).await?;
+ insert_entity_access(
+ &pool,
+ grant_only,
+ &OWNER_TEAM.to_string(),
+ "team",
+ AccessLevel::View,
+ )
+ .await?;
+
+ assert_eq!(
+ get_call_access(&pool, &link_wins, &same_team).await?,
+ Some(AccessLevel::Edit),
+ "link beats team grant for {call_table:?}"
+ );
+ assert_eq!(
+ get_call_access(&pool, &grant_only, &same_team).await?,
+ Some(AccessLevel::View),
+ "team grant alone for {call_table:?}"
+ );
+ }
+
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn returns_highest_link_or_explicit_access(pool: PgPool) -> anyhow::Result<()> {
insert_user(&pool, OWNER_WITHOUT_TEAM).await?;
diff --git a/crates/macro_db_client/migrations/20260915231631_backfill_call_team_share.down.sql b/crates/macro_db_client/migrations/20260915231631_backfill_call_team_share.down.sql
new file mode 100644
index 0000000000..5ee1fde844
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260915231631_backfill_call_team_share.down.sql
@@ -0,0 +1,6 @@
+-- Intentionally a no-op: the backfill only records existing legacy grants as
+-- canonical state (and grants active calls what their flag promised). Once
+-- canonical writers run, their edits are indistinguishable from backfilled
+-- rows, so reversing would discard real consent. Neither direction changes
+-- the legacy share_with_team semantics for older readers.
+SELECT 1;
diff --git a/crates/macro_db_client/migrations/20260915231631_backfill_call_team_share.up.sql b/crates/macro_db_client/migrations/20260915231631_backfill_call_team_share.up.sql
new file mode 100644
index 0000000000..0e1fade70f
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260915231631_backfill_call_team_share.up.sql
@@ -0,0 +1,73 @@
+-- Backfill canonical team sharing for archived calls from the legacy
+-- `call_records.share_with_team` flag and the direct team grants the old
+-- archive code wrote.
+--
+-- Live calls are untouched: `calls.share_with_team` stays the pending toggle
+-- and is translated into canonical state when the call is archived.
+-- Canonical state lives on "SharePermission" (team_share_access_level,
+-- team_share_team_id, team_share_revision) plus a managed entity_access team
+-- row. Every step only touches SharePermission rows the canonical writers have
+-- never seen (NULL level, revision 0), so the migration is idempotent and can
+-- be re-run once older service pods have drained.
+
+-- 1. Archived records: adopt exactly one existing team View grant.
+-- Joining a team after a call was archived must not reshare the record, so
+-- no grant is created here. Records with several team rows or a non-view
+-- team row are left untouched for manual review.
+WITH team_grants AS (
+ SELECT
+ ea.entity_id,
+ ea.source_id,
+ COUNT(*) OVER (PARTITION BY ea.entity_id) AS grant_count,
+ bool_and(ea.access_level = 'view') OVER (PARTITION BY ea.entity_id) AS all_view
+ FROM entity_access ea
+ WHERE ea.entity_type = 'call'
+ AND ea.source_type = 'team'
+ AND ea.granted_from_project_id IS NULL
+),
+adoptable AS (
+ SELECT cr.share_permission_id, tg.source_id::uuid AS team_id
+ FROM call_records cr
+ JOIN team_grants tg ON tg.entity_id = cr.id
+ WHERE cr.share_with_team
+ AND tg.grant_count = 1
+ AND tg.all_view
+ AND NOT EXISTS (SELECT 1 FROM calls c WHERE c.id = cr.id)
+)
+UPDATE "SharePermission" sp
+SET team_share_access_level = 'view',
+ team_share_team_id = a.team_id,
+ team_share_revision = 1,
+ "updatedAt" = NOW()
+FROM adoptable a
+WHERE sp.id = a.share_permission_id
+ AND sp.team_share_access_level IS NULL
+ AND sp.team_share_revision = 0;
+
+-- 2. Flag FALSE but a legacy team View row still exists for the creator's
+-- team (only set_share_with_team, archive_call and the seed tool ever wrote
+-- call team rows). The canonical writer would treat that row as an
+-- untracked grant and refuse every later change, and the archive
+-- translation would leave it granting access the toggle revoked, so remove
+-- it. Only permissions the canonical writers have never touched are affected.
+DELETE FROM entity_access ea
+USING (
+ SELECT c.id AS call_id, c.created_by, c.share_permission_id
+ FROM calls c
+ WHERE NOT c.share_with_team
+ UNION ALL
+ SELECT cr.id, cr.created_by, cr.share_permission_id
+ FROM call_records cr
+ WHERE NOT cr.share_with_team
+ AND NOT EXISTS (SELECT 1 FROM calls c WHERE c.id = cr.id)
+) off_calls
+JOIN team_user tu ON tu.user_id = off_calls.created_by
+JOIN "SharePermission" sp ON sp.id = off_calls.share_permission_id
+WHERE ea.entity_id = off_calls.call_id
+ AND ea.entity_type = 'call'
+ AND ea.source_type = 'team'
+ AND ea.source_id = tu.team_id::text
+ AND ea.access_level = 'view'
+ AND ea.granted_from_project_id IS NULL
+ AND sp.team_share_access_level IS NULL
+ AND sp.team_share_revision = 0;
diff --git a/crates/models_soup/src/call_record/test.rs b/crates/models_soup/src/call_record/test.rs
index 8de1b8434d..f2aef3aed1 100644
--- a/crates/models_soup/src/call_record/test.rs
+++ b/crates/models_soup/src/call_record/test.rs
@@ -25,6 +25,7 @@ fn record_with_participants(user_ids: &[&str]) -> CallRecord {
channel_name: None,
custom_name: None,
summary: None,
+ team_share_access_level: None,
share_with_team: true,
is_active: true,
status: None,
diff --git a/crates/share_permission_db_utils/src/team_share/test.rs b/crates/share_permission_db_utils/src/team_share/test.rs
index 1d7f3d51f7..d7382eb6c2 100644
--- a/crates/share_permission_db_utils/src/team_share/test.rs
+++ b/crates/share_permission_db_utils/src/team_share/test.rs
@@ -15,6 +15,14 @@ fn chat() -> Entity<'static> {
EntityType::Chat.with_entity_string("20000000-0000-0000-0000-000000000003".to_string())
}
+fn active_call() -> Entity<'static> {
+ EntityType::Call.with_entity_string("20000000-0000-0000-0000-000000000005".to_string())
+}
+
+fn archived_call() -> Entity<'static> {
+ EntityType::Call.with_entity_string("20000000-0000-0000-0000-000000000006".to_string())
+}
+
fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeamShareCommand {
authorize_team_share(
Some(&facts.owner),
@@ -138,6 +146,87 @@ async fn apply_inserts_updates_and_deletes_direct_team_entity_access_for_chat(
apply_comment_view_and_clear(&mut tx, &chat()).await
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("team_share"))
+)]
+async fn apply_inserts_updates_and_deletes_direct_team_entity_access_for_calls(
+ pool: PgPool,
+) -> rootcause::Result<()> {
+ let mut tx = pool.begin().await?;
+ apply_comment_view_and_clear(&mut tx, &active_call()).await?;
+ apply_comment_view_and_clear(&mut tx, &archived_call()).await
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("team_share"))
+)]
+async fn load_facts_prefers_active_call_over_archived_record_with_same_id(
+ pool: PgPool,
+) -> rootcause::Result<()> {
+ let mut tx = pool.begin().await?;
+ // Model the archive hand-off: an archived row with the active call's id and
+ // permission, but a different creator, exists at the same time.
+ sqlx::query!(
+ r#"INSERT INTO call_records
+ (id, channel_id, room_name, created_by, started_at, duration_ms, share_permission_id)
+ VALUES ('20000000-0000-0000-0000-000000000005', '40000000-0000-0000-0000-000000000001',
+ 'active', 'macro|[email protected]', now(), 0, 'active-call')"#
+ )
+ .execute(tx.as_mut())
+ .await?;
+
+ let facts = load_facts(&mut tx, &active_call()).await?;
+
+ assert_eq!(facts.owner.as_ref(), "macro|[email protected]");
+ assert_eq!(facts.current, None);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("team_share"))
+)]
+async fn initialize_call_grants_view_to_creator_team_or_nothing(
+ pool: PgPool,
+) -> rootcause::Result<()> {
+ let mut tx = pool.begin().await?;
+
+ // A creator on a team: View, attributed to that team, revision 1.
+ let entity = active_call();
+ let uuid = Uuid::parse_str(&entity.entity_id)?;
+ let team_id = load_facts(&mut tx, &entity)
+ .await?
+ .owner_team_id
+ .expect("fixture owner belongs to a team");
+ initialize(&mut tx, &entity, TeamShareCreation::Call).await?;
+ let facts = load_facts(&mut tx, &entity).await?;
+ assert_eq!(
+ facts.current,
+ Some(TeamShareGrant {
+ team_id,
+ level: TeamShareLevel::View,
+ })
+ );
+ assert_eq!(facts.revision, 1);
+ assert_eq!(
+ direct_team_rows(&mut tx, &uuid, EntityType::Call, team_id).await?,
+ vec![AccessLevel::View]
+ );
+
+ // A creator without a team: nothing is promised, revision stays 0.
+ sqlx::query!("DELETE FROM team_user WHERE user_id = 'macro|[email protected]'")
+ .execute(tx.as_mut())
+ .await?;
+ let entity = archived_call();
+ initialize(&mut tx, &entity, TeamShareCreation::Call).await?;
+ let facts = load_facts(&mut tx, &entity).await?;
+ assert_eq!(facts.current, None);
+ assert_eq!(facts.revision, 0);
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../fixtures", scripts("team_share"))
diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rs
index 1a0162a1e5..b730133871 100644
--- a/crates/soup/src/domain/service/tests.rs
+++ b/crates/soup/src/domain/service/tests.rs
@@ -231,6 +231,7 @@ fn call_record(
channel_name: None,
custom_name: None,
summary: None,
+ team_share_access_level: None,
share_with_team: false,
is_active: true,
status: None,
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 1cfed0ce14..e2136ea789 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -498,6 +498,18 @@ and summaries appear here; empty state notes "Calls are available to agents."
On phones, recorded call headers omit the **Call Again** action.
+### Sharing a call
+
+A call's side panel has a `Sharing` section with one `Share with team` checkbox, and the in-call
+controls carry the same checkbox while a call is live. It is canonical team sharing (the same
+`Team access` model documents and AI chats use), fixed at **view**. While the call is **live**
+the checkbox is a pending toggle (on by default) that any participant with edit access can flip;
+other participants see it update live. When the call ends it is applied: with the toggle on,
+everyone on the creator's team can open the recorded call, read the transcript and AI summary,
+and find it under Calls and in search; off means nothing is shared. Afterwards only the call's
+**creator** can change it — everyone else sees the checkbox read-only with a note saying so.
+Team sharing is independent of channel access and of link sharing.
+
## Customers (CRM) — `/app/component/companies`
The 216px local sidebar uses the same navigation primitives as Email and Tasks.
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index 3bf8d3b7bc..03d831aed6 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -296,8 +296,11 @@ export class Sdk extends HeyApiClient {
/**
* Handler for `PATCH /call/record/{call_id}`.
*
- * Edits a call record — currently supports updating the record's share
- * permissions. Access is validated via channel membership
+ * Edits a call record: link/channel share permissions, display name, and
+ * team sharing. Edit access (channel membership) is required for the request.
+ * `sharePermission.teamShareAccessLevel` only accepts `view` or `null`; while
+ * the call is live it sets the pending share-with-team toggle, and once the
+ * call is archived it is additionally authorized against the call's creator.
*/
public editCallRecord<ThrowOnError extends boolean = false>(options: Options<EditCallRecordData, ThrowOnError>): RequestResult<EditCallRecordResponses, EditCallRecordErrors, ThrowOnError> {
return (options.client ?? this.client).patch<EditCallRecordResponses, EditCallRecordErrors, ThrowOnError>({
@@ -313,8 +316,10 @@ export class Sdk extends HeyApiClient {
/**
* Handler for `POST /call/record/{call_id}/share-with-team/toggle`.
*
- * Toggles the `share_with_team` flag on the active call. Returns the new
- * value as the JSON body.
+ * Flips the live call's share-with-team toggle and returns the new value as
+ * the JSON body. The toggle is applied as canonical team sharing (View for
+ * the creator's team) when the call is archived; archived calls answer 409
+ * and are edited through `PATCH /call/record/{call_id}` instead.
*/
public toggleShareWithTeam<ThrowOnError extends boolean = false>(options: Options<ToggleShareWithTeamData, ThrowOnError>): RequestResult<ToggleShareWithTeamResponses, ToggleShareWithTeamErrors, ThrowOnError> {
return (options.client ?? this.client).post<ToggleShareWithTeamResponses, ToggleShareWithTeamErrors, ThrowOnError>({ url: '/call/record/{call_id}/share-with-team/toggle', ...options });
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index f927c2470c..0ab4fe053e 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -1947,7 +1947,9 @@ export type CallRecord = {
*/
roomName: string;
/**
- * Whether the call is shared with the creator's team.
+ * Whether the call is shared with the creator's team. While the call is
+ * live this is the pending toggle applied at archive; afterwards it
+ * mirrors `team_share_access_level`.
*/
shareWithTeam: boolean;
/**
@@ -1960,6 +1962,7 @@ export type CallRecord = {
* once summarization has run; active calls always return `None`.
*/
summary?: string | null;
+ teamShareAccessLevel?: null | AccessLevel;
/**
* Transcript segments ordered by `sequence_num`.
*/
@@ -4900,7 +4903,7 @@ export type EditAnchorResponse = Anchor & {
};
/**
- * Edit call request
+ * Edit call request, as supplied by inbound callers.
*/
export type EditCallRecordRequest = {
/**
@@ -4913,8 +4916,9 @@ export type EditCallRecordRequest = {
customName?: string | null;
sharePermission?: null | UpdateSharePermissionRequestV2;
/**
- * If `Some(true)`, grant the creator's team View access on the call.
- * If `Some(false)`, revoke the creator's team's access. `None` is a no-op.
+ * Deprecated alias for `sharePermission.teamShareAccessLevel`:
+ * `Some(true)` behaves like `"view"`, `Some(false)` like `null`, and
+ * `None` is a no-op. Supplying both with disagreeing values is rejected.
* The team is resolved from the call's `created_by`, not the acting user.
*/
shareWithTeam?: boolean | null;
@@ -10483,8 +10487,20 @@ export type EditCallRecordData = {
};
export type EditCallRecordErrors = {
+ /**
+ * Invalid team-share level, contradictory inputs, or the creator has no team
+ */
+ 400: ErrorResponse;
401: ErrorResponse;
+ /**
+ * Team sharing of an archived call may only be changed by its creator
+ */
+ 403: ErrorResponse;
404: ErrorResponse;
+ /**
+ * Team-sharing facts changed, or the call was archived mid-request; reload and retry
+ */
+ 409: ErrorResponse;
500: ErrorResponse;
};
@@ -10514,6 +10530,10 @@ export type ToggleShareWithTeamData = {
export type ToggleShareWithTeamErrors = {
401: ErrorResponse;
404: ErrorResponse;
+ /**
+ * The call is no longer active
+ */
+ 409: ErrorResponse;
500: ErrorResponse;
};
@@ -10521,7 +10541,7 @@ export type ToggleShareWithTeamError = ToggleShareWithTeamErrors[keyof ToggleSha
export type ToggleShareWithTeamResponses = {
/**
- * New value of share_with_team after toggle
+ * New value of the share-with-team toggle
*/
200: boolean;
};
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index b07e52951a..81265ff380 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -1314,7 +1314,7 @@
"patch": {
"tags": ["call::inbound::axum_router"],
"summary": "Handler for `PATCH /call/record/{call_id}`.",
- "description": "Edits a call record — currently supports updating the record's share\npermissions. Access is validated via channel membership",
+ "description": "Edits a call record: link/channel share permissions, display name, and\nteam sharing. Edit access (channel membership) is required for the request.\n`sharePermission.teamShareAccessLevel` only accepts `view` or `null`; while\nthe call is live it sets the pending share-with-team toggle, and once the\ncall is archived it is additionally authorized against the call's creator.",
"operationId": "edit_call_record",
"parameters": [
{
@@ -1342,6 +1342,16 @@
"204": {
"description": "Call record updated"
},
+ "400": {
+ "description": "Invalid team-share level, contradictory inputs, or the creator has no team",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"401": {
"description": "",
"content": {
@@ -1352,6 +1362,16 @@
}
}
},
+ "403": {
+ "description": "Team sharing of an archived call may only be changed by its creator",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"404": {
"description": "",
"content": {
@@ -1362,6 +1382,16 @@
}
}
},
+ "409": {
+ "description": "Team-sharing facts changed, or the call was archived mid-request; reload and retry",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -1379,7 +1409,7 @@
"post": {
"tags": ["call::inbound::axum_router"],
"summary": "Handler for `POST /call/record/{call_id}/share-with-team/toggle`.",
- "description": "Toggles the `share_with_team` flag on the active call. Returns the new\nvalue as the JSON body.",
+ "description": "Flips the live call's share-with-team toggle and returns the new value as\nthe JSON body. The toggle is applied as canonical team sharing (View for\nthe creator's team) when the call is archived; archived calls answer 409\nand are edited through `PATCH /call/record/{call_id}` instead.",
"operationId": "toggle_share_with_team",
"parameters": [
{
@@ -1395,7 +1425,7 @@
],
"responses": {
"200": {
- "description": "New value of share_with_team after toggle",
+ "description": "New value of the share-with-team toggle",
"content": {
"application/json": {
"schema": {
@@ -1424,6 +1454,16 @@
}
}
},
+ "409": {
+ "description": "The call is no longer active",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -16206,7 +16246,7 @@
},
"shareWithTeam": {
"type": "boolean",
- "description": "Whether the call is shared with the creator's team."
+ "description": "Whether the call is shared with the creator's team. While the call is\nlive this is the pending toggle applied at archive; afterwards it\nmirrors `team_share_access_level`."
},
"startedAt": {
"type": "string",
@@ -16228,6 +16268,17 @@
"type": ["string", "null"],
"description": "AI-generated summary of the call. Only set on archived `call_records`\nonce summarization has run; active calls always return `None`."
},
+ "teamShareAccessLevel": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "The canonical access level granted to the creator's team, or `None`\nwhen the call is not shared with the team. Calls only ever grant\n`View`, and only once archived: while the call is live this is `None`\nand `share_with_team` carries the pending toggle."
+ }
+ ]
+ },
"transcript": {
"type": "array",
"items": {
@@ -20555,7 +20606,7 @@
},
"EditCallRecordRequest": {
"type": "object",
- "description": "Edit call request",
+ "description": "Edit call request, as supplied by inbound callers.",
"properties": {
"customName": {
"type": ["string", "null"],
@@ -20568,13 +20619,13 @@
},
{
"$ref": "#/components/schemas/UpdateSharePermissionRequestV2",
- "description": "Updated share permissions."
+ "description": "Updated share permissions. `teamShareAccessLevel` shares the call with\nthe creator's team and only accepts `view` or `null` (revoke). While\nthe call is live it sets the pending share-with-team toggle, which is\napplied when the call is archived; afterwards only the call's creator\nmay change it."
}
]
},
"shareWithTeam": {
"type": ["boolean", "null"],
- "description": "If `Some(true)`, grant the creator's team View access on the call.\nIf `Some(false)`, revoke the creator's team's access. `None` is a no-op.\nThe team is resolved from the call's `created_by`, not the acting user."
+ "description": "Deprecated alias for `sharePermission.teamShareAccessLevel`:\n`Some(true)` behaves like `\"view\"`, `Some(false)` like `null`, and\n`None` is a no-op. Supplying both with disagreeing values is rejected.\nThe team is resolved from the call's `created_by`, not the acting user."
}
}
},
diff --git a/packages/sdk/src/entities/calls/call-record.ts b/packages/sdk/src/entities/calls/call-record.ts
index f329b127f7..4dd048d7b9 100644
--- a/packages/sdk/src/entities/calls/call-record.ts
+++ b/packages/sdk/src/entities/calls/call-record.ts
@@ -67,7 +67,18 @@ export class CallRecord extends FavoritableEntity<CallRecordDetail> {
/** Participants, both active and historic. */
readonly participants = this.field('participants');
- /** Whether the recording is shared with the team. */
+ /**
+ * The canonical access level granted to the creator's team once the call is
+ * archived, or null when it is not shared. Calls only ever grant `'view'`;
+ * while the call is live this is null and {@link CallRecord.shareWithTeam}
+ * carries the pending toggle.
+ */
+ readonly teamShareAccessLevel = this.field('teamShareAccessLevel');
+
+ /**
+ * Whether the call is shared with the creator's team: the pending toggle
+ * while the call is live, the canonical grant once it is archived.
+ */
readonly shareWithTeam = this.field('shareWithTeam');
/** URL of the call recording, once available. */
@@ -89,6 +100,23 @@ export class CallRecord extends FavoritableEntity<CallRecordDetail> {
);
}
+ /**
+ * Share the call with the creator's team (view access), or unshare it.
+ * While the call is live this sets the pending toggle any participant with
+ * edit access may change; once archived only the call's creator may change
+ * it and the API answers 403 otherwise.
+ */
+ async setTeamShare(shared: boolean): Promise<void> {
+ await this.mutate((c) =>
+ c.storage.editCallRecord({
+ path: { call_id: this.id },
+ body: {
+ sharePermission: { teamShareAccessLevel: shared ? 'view' : null },
+ },
+ }),
+ );
+ }
+
/** Delete the call record. */
async delete(): Promise<void> {
await this.mutate((c) =>
diff --git a/packages/sdk/tests/team-share.test.ts b/packages/sdk/tests/team-share.test.ts
index 1491b078da..060dd8d87c 100644
--- a/packages/sdk/tests/team-share.test.ts
+++ b/packages/sdk/tests/team-share.test.ts
@@ -1,9 +1,13 @@
import { describe, expect, test } from 'bun:test';
import { createClient } from '../generated/storage/client';
import { Sdk } from '../generated/storage/sdk.gen';
-import type { EditDocumentData } from '../generated/storage/types.gen';
+import type {
+ EditCallRecordData,
+ EditDocumentData,
+} from '../generated/storage/types.gen';
const documentId = '0198a4cc-e138-7670-a308-a6b766602700';
+const callId = '0198a4cc-e138-7670-a308-a6b766602701';
const baseUrl = 'https://api.example.test';
function recordingSdk() {
@@ -75,6 +79,44 @@ describe('document edit team-share serialization', () => {
});
});
+// Calls share with the creator's team through the same `sharePermission`
+// patch; the backend only accepts `view` (or `null` to revoke).
+const callEditCases: Array<{
+ name: string;
+ body: EditCallRecordData['body'];
+ serializedBody: string;
+}> = [
+ {
+ name: 'view shares the call with the team',
+ body: { sharePermission: { teamShareAccessLevel: 'view' } },
+ serializedBody: '{"sharePermission":{"teamShareAccessLevel":"view"}}',
+ },
+ {
+ name: 'explicit null revokes team sharing',
+ body: { sharePermission: { teamShareAccessLevel: null } },
+ serializedBody: '{"sharePermission":{"teamShareAccessLevel":null}}',
+ },
+ {
+ name: 'a rename alone never touches team sharing',
+ body: { customName: 'Weekly sync' },
+ serializedBody: '{"customName":"Weekly sync"}',
+ },
+];
+
+describe('call record team-share serialization', () => {
+ test.each(callEditCases)('$name', async ({ body, serializedBody }) => {
+ const { sdk, requests } = recordingSdk();
+
+ await sdk.editCallRecord({ path: { call_id: callId }, body });
+
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ expect(request.url).toBe(`${baseUrl}/call/record/${callId}`);
+ expect(request.method).toBe('PATCH');
+ expect(await request.text()).toBe(serializedBody);
+ });
+});
+
describe('legacy document team-share toggle', () => {
test.each([true, false])('shareWithTeam=%p', async (shareWithTeam) => {
const { sdk, requests } = recordingSdk();
diff --git a/tooling/seed_cli/Cargo.toml b/tooling/seed_cli/Cargo.toml
index 9e27935fed..feeaaa041f 100644
--- a/tooling/seed_cli/Cargo.toml
+++ b/tooling/seed_cli/Cargo.toml
@@ -41,6 +41,7 @@ serde_json = { workspace = true }
properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }
roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false }
sha2 = { workspace = true }
+share_permission_db_utils = { path = "../../crates/share_permission_db_utils" }
sqlx = { workspace = true }
sync_service_client = { path = "../../crates/sync_service_client" }
system_properties = { path = "../../crates/system_properties" }
diff --git a/tooling/seed_cli/src/entity/scenario/apply.rs b/tooling/seed_cli/src/entity/scenario/apply.rs
index 4548f5ff45..8624b20710 100644
--- a/tooling/seed_cli/src/entity/scenario/apply.rs
+++ b/tooling/seed_cli/src/entity/scenario/apply.rs
@@ -869,13 +869,6 @@ async fn seed_calls(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result
));
let started_at = ended_at - duration;
- let creator_team = if call.share_with_team {
- spec.team_of(&call.created_by)
- .map(|team| spec.team_id(team))
- } else {
- None
- };
-
let participants: Vec<(String, DateTime<Utc>, DateTime<Utc>)> = spec
.call_participants(key)
.iter()
@@ -910,7 +903,6 @@ async fn seed_calls(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result
share_permission_id: share_permission_id.to_string(),
share_with_team: call.share_with_team,
custom_name: call.name.clone(),
- team_id: creator_team,
participants,
transcripts,
})
diff --git a/tooling/seed_cli/src/service/db.rs b/tooling/seed_cli/src/service/db.rs
index ffa4574c26..7a1832b259 100644
--- a/tooling/seed_cli/src/service/db.rs
+++ b/tooling/seed_cli/src/service/db.rs
@@ -21,6 +21,7 @@ use model::document::DocumentMetadata;
use models_email::email::service;
use models_permissions::share_permission::SharePermissionV2;
use models_permissions::share_permission::access_level::AccessLevel;
+use models_permissions::share_permission::team_share::TeamShareCreation;
use uuid::Uuid;
/// Everything needed to seed one scenario user.
@@ -59,12 +60,12 @@ pub struct InsertCallRecordArgs {
pub ended_at: DateTime<Utc>,
/// Pre-derived share permission id.
pub share_permission_id: String,
- /// Whether the creator's team gets view access.
+ /// Whether the creator's current team gets canonical View access (the
+ /// same initialization `create_call` performs); no-op for a creator
+ /// without a team.
pub share_with_team: bool,
/// Optional custom display name.
pub custom_name: Option<String>,
- /// The creator's team, when `share_with_team` applies.
- pub team_id: Option<Uuid>,
/// Participants as (user id, joined_at, left_at).
pub participants: Vec<(String, DateTime<Utc>, DateTime<Utc>)>,
/// Transcript segments as (speaker id, content, started_at, ended_at).
@@ -501,17 +502,6 @@ impl SeedDb {
entity_access_db_utils::AccessLevel::Edit,
)
.await?;
- if let Some(team_id) = args.team_id {
- entity_access_db_utils::insert_entity_access_row(
- &mut transaction,
- &args.call_id,
- entity_access_db_utils::EntityType::Call,
- &team_id.to_string(),
- entity_access_db_utils::EntityAccessSourceType::Team,
- entity_access_db_utils::AccessLevel::View,
- )
- .await?;
- }
let duration_ms = (args.ended_at - args.started_at).num_milliseconds().max(0);
sqlx::query!(
@@ -533,6 +523,22 @@ impl SeedDb {
.execute(transaction.as_mut())
.await?;
+ // Canonical team sharing, exactly as `create_call` initializes it: View
+ // for the creator's current team when the scenario shares the call,
+ // nothing otherwise. The legacy column above is only kept until it is
+ // dropped; readers derive `shareWithTeam` from this state.
+ share_permission_db_utils::team_share::initialize(
+ &mut transaction,
+ &model_entity::EntityType::Call.with_entity_string(args.call_id.to_string()),
+ if args.share_with_team {
+ TeamShareCreation::Call
+ } else {
+ TeamShareCreation::Unshared
+ },
+ )
+ .await
+ .map_err(anyhow::Error::from)?;
+
for (user_id, joined_at, left_at) in &args.participants {
sqlx::query!(
r#"INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)