Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(calls): add persistent chat to video calls (#7344)
Eric Hayesf8932dcb05bc
diff --git a/.sqlx/query-04b42857e868e30b1b3b17c2fb247686e5a2cc9b29f8ce9f541d720c9cd38802.json b/.sqlx/query-04b42857e868e30b1b3b17c2fb247686e5a2cc9b29f8ce9f541d720c9cd38802.jsonnew file mode 100644index 0000000000..97ca570a23--- /dev/null+++ b/.sqlx/query-04b42857e868e30b1b3b17c2fb247686e5a2cc9b29f8ce9f541d720c9cd38802.json@@ -0,0 +1,25 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT to_jsonb(m) AS \"message!: Json<StoredMessage>\" FROM comms_messages m\n WHERE client_message_id = $1 AND parent_entity_type = $2\n AND parent_entity_id = $3 AND sender_id = $4",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message!: Json<StoredMessage>",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "04b42857e868e30b1b3b17c2fb247686e5a2cc9b29f8ce9f541d720c9cd38802"+}diff --git a/.sqlx/query-0a63473ef29af52f3e30835fb227e9540122683b44522e60ba5973626b3c4bd4.json b/.sqlx/query-0a63473ef29af52f3e30835fb227e9540122683b44522e60ba5973626b3c4bd4.jsondeleted file mode 100644index f8f5a762ad..0000000000--- a/.sqlx/query-0a63473ef29af52f3e30835fb227e9540122683b44522e60ba5973626b3c4bd4.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n SELECT c.id, 'call', p.user_id, 'user', 'view'\n FROM calls c JOIN call_participants p ON p.call_id = c.id\n WHERE c.id = $1 AND c.channel_id IS NULL AND p.user_id = $2 AND p.left_at IS NULL\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO NOTHING",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": []- },- "hash": "0a63473ef29af52f3e30835fb227e9540122683b44522e60ba5973626b3c4bd4"-}diff --git a/.sqlx/query-10c975ec9d47e99c1b6416719688e500f90ac0af1a95e50abb44b781f329f859.json b/.sqlx/query-10c975ec9d47e99c1b6416719688e500f90ac0af1a95e50abb44b781f329f859.jsonnew file mode 100644index 0000000000..71f8d909c5--- /dev/null+++ b/.sqlx/query-10c975ec9d47e99c1b6416719688e500f90ac0af1a95e50abb44b781f329f859.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_message_threads SET deleted_at = NOW() WHERE root_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "10c975ec9d47e99c1b6416719688e500f90ac0af1a95e50abb44b781f329f859"+}diff --git a/.sqlx/query-169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c.json b/.sqlx/query-169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c.jsonnew file mode 100644index 0000000000..3aaadcab92--- /dev/null+++ b/.sqlx/query-169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT EXISTS(SELECT 1 FROM calls WHERE id = $1 UNION ALL SELECT 1 FROM call_records WHERE id = $1) AS \"exists!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "169aff669342e0bcf9bee8306009716589d4671ade11f841d0cbcf2c5986ce5c"+}diff --git a/.sqlx/query-22e88df8834a54db1440f0da2867f0f76d755f29d6f880f56dfb20505fcab7ae.json b/.sqlx/query-22e88df8834a54db1440f0da2867f0f76d755f29d6f880f56dfb20505fcab7ae.jsonnew file mode 100644index 0000000000..0c59f9ac2a--- /dev/null+++ b/.sqlx/query-22e88df8834a54db1440f0da2867f0f76d755f29d6f880f56dfb20505fcab7ae.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id)\n VALUES ($1, $2::uuid, $2::uuid::text, $3, $4)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "22e88df8834a54db1440f0da2867f0f76d755f29d6f880f56dfb20505fcab7ae"+}diff --git a/.sqlx/query-31ba74a23ea4aaa29be1ee3cea7e20e4e93a41aa9027a28b96feb070185ce758.json b/.sqlx/query-31ba74a23ea4aaa29be1ee3cea7e20e4e93a41aa9027a28b96feb070185ce758.jsonnew file mode 100644index 0000000000..62eda5b337--- /dev/null+++ b/.sqlx/query-31ba74a23ea4aaa29be1ee3cea7e20e4e93a41aa9027a28b96feb070185ce758.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE agent_session SET thread_id = $1 WHERE id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "31ba74a23ea4aaa29be1ee3cea7e20e4e93a41aa9027a28b96feb070185ce758"+}diff --git a/.sqlx/query-4b3dad3dbb00432113ba9aaeeb70576ff24ab960b1ac5bfe5ca8a3d7dc42d3d5.json b/.sqlx/query-4b3dad3dbb00432113ba9aaeeb70576ff24ab960b1ac5bfe5ca8a3d7dc42d3d5.jsonnew file mode 100644index 0000000000..1dff5996b9--- /dev/null+++ b/.sqlx/query-4b3dad3dbb00432113ba9aaeeb70576ff24ab960b1ac5bfe5ca8a3d7dc42d3d5.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_channels (id, name, channel_type, owner_id)\n VALUES ($1, 'Call chat test', 'public', $2)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4b3dad3dbb00432113ba9aaeeb70576ff24ab960b1ac5bfe5ca8a3d7dc42d3d5"+}diff --git a/.sqlx/query-59963658076b29580661b870d083b9f8ec834860f1707b4fbb50e458905a3e00.json b/.sqlx/query-59963658076b29580661b870d083b9f8ec834860f1707b4fbb50e458905a3e00.jsonnew file mode 100644index 0000000000..051df18422--- /dev/null+++ b/.sqlx/query-59963658076b29580661b870d083b9f8ec834860f1707b4fbb50e458905a3e00.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE entity_access SET access_level = $3::text::\"AccessLevel\"\n WHERE entity_id = $1 AND entity_type = 'call'\n AND source_id = $2 AND source_type = 'channel'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "59963658076b29580661b870d083b9f8ec834860f1707b4fbb50e458905a3e00"+}diff --git a/.sqlx/query-607dccef6a8b083509bbd391184c7ac131c66ff783bf333b53474be0084ffb4f.json b/.sqlx/query-607dccef6a8b083509bbd391184c7ac131c66ff783bf333b53474be0084ffb4f.jsonnew file mode 100644index 0000000000..d486dbf99d--- /dev/null+++ b/.sqlx/query-607dccef6a8b083509bbd391184c7ac131c66ff783bf333b53474be0084ffb4f.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT m.parent_entity_type, m.parent_entity_id FROM agent_session s\n JOIN comms_messages m ON m.id = s.thread_id\n JOIN comms_message_threads t ON t.root_id = m.id\n WHERE s.id = $1 AND m.parent_entity_type IN ('document', 'call')\n AND t.deleted_at IS NULL",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "parent_entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "parent_entity_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "607dccef6a8b083509bbd391184c7ac131c66ff783bf333b53474be0084ffb4f"+}diff --git a/.sqlx/query-65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129.json b/.sqlx/query-65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129.jsondeleted file mode 100644index c304074bf5..0000000000--- a/.sqlx/query-65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT m.parent_entity_id FROM agent_session s\n JOIN comms_messages m ON m.id = s.thread_id\n JOIN comms_message_threads t ON t.root_id = m.id\n WHERE s.id = $1 AND m.parent_entity_type = 'document' AND t.deleted_at IS NULL",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "parent_entity_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "65715e1ea022117872fa028427720c27b87a1da078ff2e114083e4cf7a176129"-}diff --git a/.sqlx/query-9924e5cdd3a8c652db0f119fd4ae7ed05d20360b5e1f4b64ea60f43351cfca10.json b/.sqlx/query-7cd6a4226fe26b78cdedf29763afb19a0c6a3248ae9783d88705e96cfc6f06a2.jsonsimilarity index 63%rename from .sqlx/query-9924e5cdd3a8c652db0f119fd4ae7ed05d20360b5e1f4b64ea60f43351cfca10.jsonrename to .sqlx/query-7cd6a4226fe26b78cdedf29763afb19a0c6a3248ae9783d88705e96cfc6f06a2.jsonindex aeb0e85706..5156fcaffd 100644--- a/.sqlx/query-9924e5cdd3a8c652db0f119fd4ae7ed05d20360b5e1f4b64ea60f43351cfca10.json+++ b/.sqlx/query-7cd6a4226fe26b78cdedf29763afb19a0c6a3248ae9783d88705e96cfc6f06a2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "INSERT INTO comms_messages(id, parent_entity_type, parent_entity_id, thread_id,\n sender_id, triggered_by_user_id, content)\n VALUES ($1, $2, $3, $4, $5, $6, $7)",+ "query": "INSERT INTO comms_messages(id, parent_entity_type, parent_entity_id, thread_id,\n sender_id, triggered_by_user_id, content, client_message_id)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)","describe": {"columns": [],"parameters": {@@ -11,10 +11,11 @@"Uuid","Text","Text",- "Text"+ "Text",+ "Uuid"]},"nullable": []},- "hash": "9924e5cdd3a8c652db0f119fd4ae7ed05d20360b5e1f4b64ea60f43351cfca10"+ "hash": "7cd6a4226fe26b78cdedf29763afb19a0c6a3248ae9783d88705e96cfc6f06a2"}diff --git a/.sqlx/query-7ed2dc20b31dab0735c2ef2e95ac47a2766ae79f71fea5dbfd68e3a921bdbeb0.json b/.sqlx/query-7ed2dc20b31dab0735c2ef2e95ac47a2766ae79f71fea5dbfd68e3a921bdbeb0.jsonnew file mode 100644index 0000000000..106487f46a--- /dev/null+++ b/.sqlx/query-7ed2dc20b31dab0735c2ef2e95ac47a2766ae79f71fea5dbfd68e3a921bdbeb0.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)\n VALUES ($1, $2, $3, 'macro|[email protected]', 'Agent invocation')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "7ed2dc20b31dab0735c2ef2e95ac47a2766ae79f71fea5dbfd68e3a921bdbeb0"+}diff --git a/.sqlx/query-8be1555d39091c5f68e7bb5e1716e1a0671a6defb484def3c49e8e4f1d224dcc.json b/.sqlx/query-8be1555d39091c5f68e7bb5e1716e1a0671a6defb484def3c49e8e4f1d224dcc.jsonnew file mode 100644index 0000000000..21fc16f35d--- /dev/null+++ b/.sqlx/query-8be1555d39091c5f68e7bb5e1716e1a0671a6defb484def3c49e8e4f1d224dcc.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO call_meetings (id, share_token, user_id, title, scheduled_start, scheduled_end, active_call_id)\n VALUES ($1, $1::uuid::text, $2, 'Standalone chat', $3, $4, $5)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "8be1555d39091c5f68e7bb5e1716e1a0671a6defb484def3c49e8e4f1d224dcc"+}diff --git a/.sqlx/query-8c07ff56e780f6956bce6168ec76a62ab94cb7bc56286a33cfa1607862de5e7a.json b/.sqlx/query-8c07ff56e780f6956bce6168ec76a62ab94cb7bc56286a33cfa1607862de5e7a.jsonnew file mode 100644index 0000000000..0e3dae331c--- /dev/null+++ b/.sqlx/query-8c07ff56e780f6956bce6168ec76a62ab94cb7bc56286a33cfa1607862de5e7a.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))::text AS lock",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "lock",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "8c07ff56e780f6956bce6168ec76a62ab94cb7bc56286a33cfa1607862de5e7a"+}diff --git a/.sqlx/query-bb6e269e362363da01521d8661e5d5b259f68bf65d4160850649229e69e0b1a9.json b/.sqlx/query-bb6e269e362363da01521d8661e5d5b259f68bf65d4160850649229e69e0b1a9.jsonnew file mode 100644index 0000000000..defc645547--- /dev/null+++ b/.sqlx/query-bb6e269e362363da01521d8661e5d5b259f68bf65d4160850649229e69e0b1a9.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n SELECT c.id, 'call', p.user_id, 'user', 'comment'\n FROM calls c JOIN call_participants p ON p.call_id = c.id\n WHERE c.id = $1 AND c.channel_id IS NULL AND p.user_id = $2 AND p.left_at IS NULL\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = now()\n WHERE entity_access.access_level = 'view'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "bb6e269e362363da01521d8661e5d5b259f68bf65d4160850649229e69e0b1a9"+}diff --git a/.sqlx/query-c9e69cce3bdaa2b2b4f5213d17097bc26ffe40d6b65e193d9b509da30966d8b7.json b/.sqlx/query-c9e69cce3bdaa2b2b4f5213d17097bc26ffe40d6b65e193d9b509da30966d8b7.jsonnew file mode 100644index 0000000000..c5c5a738b9--- /dev/null+++ b/.sqlx/query-c9e69cce3bdaa2b2b4f5213d17097bc26ffe40d6b65e193d9b509da30966d8b7.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_messages SET deleted_at = NOW() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "c9e69cce3bdaa2b2b4f5213d17097bc26ffe40d6b65e193d9b509da30966d8b7"+}diff --git a/.sqlx/query-ca03a6bc69bdb551dd89abdc6e2276c61a6ca8f234877fa7996f71612aefa2b5.json b/.sqlx/query-ca03a6bc69bdb551dd89abdc6e2276c61a6ca8f234877fa7996f71612aefa2b5.jsonnew file mode 100644index 0000000000..605cb1a40b--- /dev/null+++ b/.sqlx/query-ca03a6bc69bdb551dd89abdc6e2276c61a6ca8f234877fa7996f71612aefa2b5.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT count(*) FROM comms_entity_mentions WHERE source_entity_type = 'message' AND source_entity_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "ca03a6bc69bdb551dd89abdc6e2276c61a6ca8f234877fa7996f71612aefa2b5"+}diff --git a/.sqlx/query-ceacf2d4ea9c71c75f3056a720ade0184737a46716f0380606aec173d9769f32.json b/.sqlx/query-ceacf2d4ea9c71c75f3056a720ade0184737a46716f0380606aec173d9769f32.jsonnew file mode 100644index 0000000000..592db635a6--- /dev/null+++ b/.sqlx/query-ceacf2d4ea9c71c75f3056a720ade0184737a46716f0380606aec173d9769f32.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT EXISTS(SELECT 1 FROM comms_message_threads\n WHERE root_id = $1 AND parent_entity_type = $2 AND parent_entity_id = $3) AS \"exists!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "ceacf2d4ea9c71c75f3056a720ade0184737a46716f0380606aec173d9769f32"+}diff --git a/.sqlx/query-cef68a830ecef3ff486ad5c4a82edf67c7bf0917356a564acb7d2f0e8fded674.json b/.sqlx/query-cef68a830ecef3ff486ad5c4a82edf67c7bf0917356a564acb7d2f0e8fded674.jsonnew file mode 100644index 0000000000..3a9af54e0f--- /dev/null+++ b/.sqlx/query-cef68a830ecef3ff486ad5c4a82edf67c7bf0917356a564acb7d2f0e8fded674.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE calls SET channel_id = NULL, meeting_id = $2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "cef68a830ecef3ff486ad5c4a82edf67c7bf0917356a564acb7d2f0e8fded674"+}diff --git a/.sqlx/query-ea1966f2a67b47a0a4c713e86148360ade75fce0b032ef5c7b5daec480710c6b.json b/.sqlx/query-ea1966f2a67b47a0a4c713e86148360ade75fce0b032ef5c7b5daec480710c6b.jsonnew file mode 100644index 0000000000..bd6375f590--- /dev/null+++ b/.sqlx/query-ea1966f2a67b47a0a4c713e86148360ade75fce0b032ef5c7b5daec480710c6b.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, duration_ms, share_permission_id, meeting_id)\n SELECT id, channel_id, room_name, created_by, created_at, 1000, share_permission_id, meeting_id FROM calls WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "ea1966f2a67b47a0a4c713e86148360ade75fce0b032ef5c7b5daec480710c6b"+}diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex a3814d5088..3f39f06561 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -183,7 +183,10 @@ function migrateLegacySearch({})).with('call-detail', 'drive-call', () => ({namespace: 'call-detail',- fields: [[CALL_URL_PARAMS.transcriptId, 'transcriptId']] as const,+ fields: [+ [CALL_URL_PARAMS.transcriptId, 'transcriptId'],+ [CALL_URL_PARAMS.messageId, 'messageId'],+ ] as const,})).otherwise(() => undefined);diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.tsindex e7aa801036..82f4148689 100644--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts@@ -1665,6 +1665,23 @@ describe('layoutManager', () => {}});+ it('restores a call chat target from old and Drive links', async () => {+ for (const path of [+ '/call/call-1?call_message_id=message-1',+ '/drive/call/call-1?call_message_id=message-1',+ ]) {+ const { manager, location, router, dispose } = ingressRouter(path);+ await router.settled();+ const split = manager.splits()[0];+ expect(router.search(split.id, 'call-detail')).toEqual({+ messageId: ['message-1'],+ });+ expect(location.read().pathname).toBe('/drive/call/call-1');+ router.dispose();+ dispose();+ }+ });+it('preserves canonical transcript search when upgrading an old call link', async () => {const { manager, location, router, dispose } = ingressRouter('/call/call-1?s0.call-detail.transcriptId=segment-3&referral_code=code#focus'diff --git a/apps/web/src/features/block-call/call-route.ts b/apps/web/src/features/block-call/call-route.tsindex f1313156d0..c6d6762c98 100644--- a/apps/web/src/features/block-call/call-route.ts+++ b/apps/web/src/features/block-call/call-route.ts@@ -3,8 +3,12 @@ import { z } from 'zod';export const callDetailSearch = {namespace: 'call-detail',- schema: z.object({ transcriptId: z.string(), seek: z.string() }),- defaults: { transcriptId: '', seek: '' },+ schema: z.object({+ transcriptId: z.string(),+ messageId: z.string(),+ seek: z.string(),+ }),+ defaults: { transcriptId: '', messageId: '', seek: '' },};export const callDetailSearchCodec = createSearchParamsCodec(callDetailSearch);diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsxindex 09c0d8b732..c222f28d6d 100644--- a/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.test.tsx@@ -1,16 +1,17 @@import type { CallBlockProps } from '@block-call/constants';-import { cleanup, render } from '@solidjs/testing-library';+import { cleanup, fireEvent, render } from '@solidjs/testing-library';import { createStore } from 'solid-js/store';import { afterEach, expect, it, vi } from 'vitest';import { CallBlockAdapter } from './CallBlockAdapter';const state = vi.hoisted(() => ({- search: {} as { transcriptId: string; seek: string },+ search: {} as { transcriptId: string; messageId?: string; seek: string },+ setSearch: vi.fn(),navigate: (_params: CallBlockProps) => {},}));vi.mock('@app/lib/split-router', async (importOriginal) => ({...(await importOriginal<typeof import('@app/lib/split-router')>()),- createSearchParams: () => [state.search],+ createSearchParams: () => [state.search, state.setSearch],}));vi.mock('@app/signal/splitLayout', () => ({globalSplitManager: () => undefined,@@ -46,9 +47,26 @@ vi.mock('./sidepanel/CallSidePanelSections', () => ({vi.mock('./CallRecording/CallRecordingBody', () => ({CallRecordingBody: (props: {transcriptTarget?: { transcriptId: string; gen: number };- }) => <output>{JSON.stringify(props.transcriptTarget)}</output>,+ messageTarget?: string;+ messageTargetRequestKey?: string | number;+ onClearMessageTarget?: () => void;+ }) => (+ <>+ <output>{JSON.stringify(props.transcriptTarget)}</output>+ <output+ data-message-target+ data-request-key={props.messageTargetRequestKey}+ >+ {props.messageTarget}+ </output>+ <button onClick={props.onClearMessageTarget}>Clear message target</button>+ </>+ ),}));-afterEach(cleanup);+afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});it('delivers and clears transcript requests in the legacy call body', () => {const [search, setSearch] = createStore({@@ -90,3 +108,99 @@ it('preserves an imperative transcript target across Home route cleanup', () =>setSearch({ transcriptId: '', seek: '' });expect(view.container.querySelector('output')!.textContent).toBe('');});++it('delivers updated route message targets and clears them without remounting', () => {+ const [search, setSearch] = createStore({+ transcriptId: '',+ messageId: 'route-message',+ seek: 'first',+ });+ state.search = search;+ const view = render(() => <CallBlockAdapter call_message_id="old-message" />);+ const target = () =>+ view.container.querySelector('[data-message-target]')!.textContent;++ expect(target()).toBe('route-message');+ setSearch({ messageId: 'another-message', seek: 'next' });+ expect(target()).toBe('another-message');+ setSearch({ messageId: '', seek: '' });+ expect(target()).toBe('');+ setSearch({ messageId: 'route-message', seek: 'reopen' });+ expect(target()).toBe('route-message');+});++it('preserves imperative message targets during route cleanup and clears on untargeted navigation', () => {+ const [search, setSearch] = createStore({+ transcriptId: '',+ messageId: 'route-message',+ seek: 'first',+ });+ state.search = search;+ const view = render(() => <CallBlockAdapter />);+ const target = () =>+ view.container.querySelector('[data-message-target]')!.textContent;++ state.navigate({ call_message_id: 'linked-message' });+ setSearch({ messageId: '', seek: '' });+ expect(target()).toBe('linked-message');+ state.navigate({});+ expect(target()).toBe('');+ state.navigate({ call_message_id: 'linked-message' });+ state.navigate({ call_transcript_id: 'segment' });+ expect(target()).toBe('');+ setSearch({ messageId: 'another-message', seek: 'next' });+ expect(target()).toBe('another-message');+ setSearch({ messageId: '', seek: '' });+ expect(target()).toBe('');+});++it('reissues the same message target for repeated route and imperative navigation', () => {+ const [search, setSearch] = createStore({+ transcriptId: '',+ messageId: 'route-message',+ seek: 'first',+ });+ state.search = search;+ const view = render(() => <CallBlockAdapter />);+ const target = view.container.querySelector('[data-message-target]')!;+ const initialRequest = target.getAttribute('data-request-key');++ setSearch('seek', 'repeat');+ expect(target.textContent).toBe('route-message');+ expect(target.getAttribute('data-request-key')).not.toBe(initialRequest);+ const repeatedRequest = target.getAttribute('data-request-key');+ state.navigate({ call_message_id: 'route-message' });+ expect(target.getAttribute('data-request-key')).not.toBe(repeatedRequest);+ const imperativeRequest = target.getAttribute('data-request-key');+ setSearch({ messageId: '', seek: '' });+ expect(target.getAttribute('data-request-key')).toBe(imperativeRequest);+ state.navigate({ call_message_id: 'route-message' });+ expect(target.getAttribute('data-request-key')).not.toBe(imperativeRequest);+ expect(view.container.querySelector('[data-message-target]')).toBe(target);+});++it('clears the route message target when its highlight is released', () => {+ const [search, setSearch] = createStore({+ transcriptId: 'segment',+ messageId: 'route-message',+ seek: 'first',+ });+ state.search = search;+ state.setSearch.mockImplementation((patch) => {+ setSearch({ ...patch, messageId: patch.messageId ?? '' });+ });+ const view = render(() => <CallBlockAdapter />);++ fireEvent.click(view.getByRole('button', { name: 'Clear message target' }));++ expect(state.setSearch).toHaveBeenCalledWith(+ { messageId: undefined },+ { history: 'replace' }+ );+ expect(search.messageId).toBe('');+ expect(search.transcriptId).toBe('segment');+ setSearch('seek', 'next');+ expect(+ view.container.querySelector('[data-message-target]')!.textContent+ ).toBe('');+});diff --git a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx b/apps/web/src/features/block-call/component/CallBlockAdapter.tsxindex aac609d098..a8b2356f3a 100644--- a/apps/web/src/features/block-call/component/CallBlockAdapter.tsx+++ b/apps/web/src/features/block-call/component/CallBlockAdapter.tsx@@ -23,7 +23,7 @@ export function CallBlockAdapter(props: CallBlockProps) {const callRecord = useCallRecordQuery(() => callId);const blockHandle = blockHandleSignal.get;const [searchParams] = useSearchParams();- const [routeSearch] = createSearchParams(callDetailSearch);+ const [routeSearch, setRouteSearch] = createSearchParams(callDetailSearch);const initialTranscriptId = ((): string | undefined => {if (routeSearch.transcriptId) return routeSearch.transcriptId;@@ -41,6 +41,46 @@ export function CallBlockAdapter(props: CallBlockProps) {? { transcriptId: initialTranscriptId, gen: 0 }: undefined);+ const initialMessageId = ((): string | undefined => {+ if (routeSearch.messageId) return routeSearch.messageId;+ const fromProps = props[URL_PARAMS.messageId];+ if (fromProps) return fromProps;+ if (globalSplitManager()?.splits().length !== 1) return undefined;+ const fromSearch = searchParams[URL_PARAMS.messageId];+ return typeof fromSearch === 'string' ? fromSearch : undefined;+ })();+ const [messageTarget, setMessageTarget] = createSignal<+ { id: string; requestKey: number } | undefined+ >(initialMessageId ? { id: initialMessageId, requestKey: 0 } : undefined);+ const requestMessageTarget = (id: string | undefined) =>+ setMessageTarget((previous) =>+ id ? { id, requestKey: (previous?.requestKey ?? 0) + 1 } : undefined+ );+ let routeOwnsMessageTarget = Boolean(routeSearch.messageId);+ createEffect(+ on(+ () => [routeSearch.messageId, routeSearch.seek],+ () => {+ if (!routeSearch.messageId) {+ if (routeOwnsMessageTarget) {+ routeOwnsMessageTarget = false;+ setMessageTarget(undefined);+ }+ return;+ }+ routeOwnsMessageTarget = true;+ requestMessageTarget(routeSearch.messageId);+ },+ { defer: true }+ )+ );++ const clearMessageTarget = () => {+ setMessageTarget(undefined);+ if (!routeOwnsMessageTarget) return;+ routeOwnsMessageTarget = false;+ setRouteSearch({ messageId: undefined }, { history: 'replace' });+ };let routeOwnsTarget = Boolean(routeSearch.transcriptId);createEffect(@@ -66,6 +106,9 @@ export function CallBlockAdapter(props: CallBlockProps) {createMethodRegistration(blockHandle, {goToLocationFromParams: async (params: CallBlockProps) => {+ const messageId = params[URL_PARAMS.messageId];+ routeOwnsMessageTarget = false;+ requestMessageTarget(messageId);const next = params[URL_PARAMS.transcriptId];if (!next) return;routeOwnsTarget = false;@@ -93,6 +136,9 @@ export function CallBlockAdapter(props: CallBlockProps) {record={data()}callId={callId}transcriptTarget={transcriptTarget()}+ messageTarget={messageTarget()?.id}+ messageTargetRequestKey={messageTarget()?.requestKey}+ onClearMessageTarget={clearMessageTarget}showOverlayHeaderGap/></div>diff --git a/apps/web/src/features/block-call/component/CallRecording/CallRecordingBody.tsx b/apps/web/src/features/block-call/component/CallRecording/CallRecordingBody.tsxindex 96ac0bffd6..c7fd04e5ec 100644--- a/apps/web/src/features/block-call/component/CallRecording/CallRecordingBody.tsx+++ b/apps/web/src/features/block-call/component/CallRecording/CallRecordingBody.tsx@@ -1,4 +1,5 @@import { AskMacroButton } from '@app/features/chat/ChatWithAgentButton';+import { CallChatHistory } from '@channel/Call/chat/CallChatHistory';import { SidePanel } from '@components/app/side-panel';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { isMobile } from '@core/mobile/isMobile';@@ -34,6 +35,9 @@ export function CallRecordingBody(props: {callId: string;transcriptTarget?: CallTranscriptTarget;showOverlayHeaderGap?: boolean;+ messageTarget?: string;+ messageTargetRequestKey?: string | number;+ onClearMessageTarget?: () => void;}) {const record = () => props.record;const hasTranscripts = createMemo(() => record().transcript.length > 0);@@ -161,6 +165,7 @@ export function CallRecordingBody(props: {</div></SidePanel.Section><div+ data-channel-scrollclass="h-full min-h-0 overflow-y-auto scrollbar-hidden"ref={setScrollRef}>@@ -239,6 +244,12 @@ export function CallRecordingBody(props: {</div></section></Show>+ <CallChatHistory+ callId={props.callId}+ targetId={props.messageTarget}+ targetRequestKey={props.messageTargetRequestKey}+ onClearTarget={props.onClearMessageTarget}+ /></div></div></div>diff --git a/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx b/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsxindex b155b43db7..b7c0420f17 100644--- a/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx+++ b/apps/web/src/features/block-call/component/sidepanel/CallSidePanelSections.tsx@@ -186,13 +186,13 @@ function SharingSectionContent(props: { record: 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.";+ return "Lets everyone on the creator's team view this call's chat, 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 "Lets everyone on your team view this call's chat, transcript, and AI summary.";}return isShared()- ? "Everyone on the creator's team can view and search this call's transcript and AI summary."+ ? "Everyone on the creator's team can view this call's chat, transcript, and AI summary.": "Only the call's creator can share it with their team.";};diff --git a/apps/web/src/features/block-call/constants.ts b/apps/web/src/features/block-call/constants.tsindex 9a33b5cb1d..88fb31c662 100644--- a/apps/web/src/features/block-call/constants.ts+++ b/apps/web/src/features/block-call/constants.ts@@ -1,8 +1,10 @@export const URL_PARAMS = {transcriptId: 'call_transcript_id',+ messageId: 'call_message_id',};export type CallBlockProps = {+ [URL_PARAMS.messageId]?: string;[URL_PARAMS.transcriptId]?: string;};diff --git a/apps/web/src/features/block-call/route.tsx b/apps/web/src/features/block-call/route.tsxindex 3d33a34cea..3f31e791a0 100644--- a/apps/web/src/features/block-call/route.tsx+++ b/apps/web/src/features/block-call/route.tsx@@ -29,6 +29,7 @@ const CallDetailRouteView = withAuth(() => {<StandaloneCallDetailcallId={params.callId}transcriptId={search.transcriptId}+ messageId={search.messageId}seek={search.seek}/>);@@ -39,7 +40,7 @@ export const callDetailRoute = defineRoute({path: 'call/:callId',params: z.object({ callId: z.string().min(1) }),search: [callDetailSearch.namespace],- externalSearch: [URL_PARAMS.transcriptId],+ externalSearch: [URL_PARAMS.transcriptId, URL_PARAMS.messageId],component: CallDetailRouteView,remountKey: ({ callId }) => callId,claim: ({ callId }) => ({ namespace: 'block', id: `call:${callId}` }),diff --git a/apps/web/src/features/block-call/views/CallDetailView.test.tsx b/apps/web/src/features/block-call/views/CallDetailView.test.tsxnew file mode 100644index 0000000000..4d2a7ac0bc--- /dev/null+++ b/apps/web/src/features/block-call/views/CallDetailView.test.tsx@@ -0,0 +1,124 @@+import type { CallRecord } from '@service-storage/generated/schemas/callRecord';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import type { JSX } from 'solid-js';+import { createStore } from 'solid-js/store';+import { afterEach, expect, it, vi } from 'vitest';+import { CallDetailContent, useCallDetail } from './CallDetailView';++const mocks = vi.hoisted(() => ({+ setSearch: vi.fn(),+ query: {+ status: 'success',+ data: {+ callId: 'call-id',+ createdBy: 'user-id',+ guests: [],+ isActive: false,+ participants: [],+ roomName: 'room',+ shareWithTeam: false,+ startedAt: '2026-10-02T00:00:00Z',+ transcript: [],+ } satisfies CallRecord,+ },+}));++vi.mock('@app/lib/split-router', () => ({+ createSearchParams: () => [{}, mocks.setSearch],+}));+vi.mock('../call-route', () => ({+ callDetailSearch: { namespace: 'call-detail' },+}));+vi.mock('@app/components/view-shell', () => ({ ViewShell: {} }));+vi.mock('@app/features/chat/ChatWithAgentButton', () => ({+ ChatWithAgentButton: () => null,+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({}),+}));+vi.mock('@components/app/split-panel', () => ({ SplitPanel: {} }));+vi.mock('@core/component/SharePermissions', () => ({+ getPermissions: () => ({}),+}));+vi.mock('@core/component/TopBar/ShareButton', () => ({+ ShareTrigger: () => null,+}));+vi.mock('@core/component/TopBar/shareModal', () => ({+ useShareModal: () => () => {},+}));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@ui', () => ({ Button: () => null }));+vi.mock('../component/use-call-again', () => ({ useCallAgain: () => ({}) }));+vi.mock('@queries/call/call', () => ({+ useCallRecordQuery: () => mocks.query,+}));+vi.mock('@queries/soup/cache', () => ({+ hasSoupEntity: () => true,+ optimisticUpdateSoupItemViewedAt: vi.fn(),+ refetchSoupEntity: vi.fn(),+}));+vi.mock('@components/app/side-panel', () => ({+ SidePanel: { Layout: (props: { children: JSX.Element }) => props.children },+}));+vi.mock('../component/sidepanel/CallSidePanelSections', () => ({+ CallSidePanelSections: () => null,+}));+vi.mock('../component/CallRecording/CallRecordingBody', () => ({+ CallRecordingBody: (props: {+ messageTarget?: string;+ messageTargetRequestKey?: string | number;+ onClearMessageTarget?: () => void;+ }) => (+ <button+ data-request-key={props.messageTargetRequestKey}+ onClick={props.onClearMessageTarget}+ >+ Target: {props.messageTarget || 'none'}+ </button>+ ),+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it('clears the route message target through the shared recording content', () => {+ const [search, setSearch] = createStore({+ messageId: 'reply-id',+ transcriptId: 'transcript-id',+ seek: 'seek-token',+ });+ mocks.setSearch.mockImplementation((patch) => {+ setSearch({ ...patch, messageId: patch.messageId ?? '' });+ });+ render(() => {+ const detail = useCallDetail(() => 'call-id');+ return (+ <CallDetailContent+ callId="call-id"+ query={detail.query}+ data={{ record: mocks.query.data, name: 'Call' }}+ messageId={search.messageId}+ transcriptId={search.transcriptId}+ seek={search.seek}+ />+ );+ });++ const target = screen.getByRole('button', { name: 'Target: reply-id' });+ expect(target.getAttribute('data-request-key')).toBe('seek-token');+ setSearch('seek', 'repeat-seek');+ expect(screen.getByRole('button', { name: 'Target: reply-id' })).toBe(target);+ expect(target.getAttribute('data-request-key')).toBe('repeat-seek');++ fireEvent.click(screen.getByRole('button', { name: 'Target: reply-id' }));++ expect(mocks.setSearch).toHaveBeenCalledWith(+ { messageId: undefined },+ { history: 'replace' }+ );+ expect(screen.getByRole('button', { name: 'Target: none' })).toBeTruthy();+ expect(search.transcriptId).toBe('transcript-id');+ expect(search.seek).toBe('repeat-seek');+});diff --git a/apps/web/src/features/block-call/views/CallDetailView.tsx b/apps/web/src/features/block-call/views/CallDetailView.tsxindex ca71b5fef0..eaf393d852 100644--- a/apps/web/src/features/block-call/views/CallDetailView.tsx+++ b/apps/web/src/features/block-call/views/CallDetailView.tsx@@ -1,5 +1,6 @@import { ViewShell } from '@app/components/view-shell';import { ChatWithAgentButton } from '@app/features/chat/ChatWithAgentButton';+import { createSearchParams } from '@app/lib/split-router';import { SidePanel } from '@components/app/side-panel';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { SplitPanel } from '@components/app/split-panel';@@ -27,6 +28,7 @@ import {Suspense,Switch,} from 'solid-js';+import { callDetailSearch } from '../call-route';import { CallRecordingBody } from '../component/CallRecording/CallRecordingBody';import { CallSidePanelSections } from '../component/sidepanel/CallSidePanelSections';import { useCallAgain } from '../component/use-call-again';@@ -110,7 +112,10 @@ function LoadedCallContent(props: {callId: string;record: CallRecord;transcriptTarget?: CallTranscriptTarget;+ messageId?: string;+ seek?: string;}) {+ const [, setSearch] = createSearchParams(callDetailSearch);onMount(() => {optimisticUpdateSoupItemViewedAt(props.callId);if (!hasSoupEntity(props.callId)) {@@ -125,6 +130,11 @@ function LoadedCallContent(props: {record={props.record}callId={props.callId}transcriptTarget={props.transcriptTarget}+ messageTarget={props.messageId}+ messageTargetRequestKey={props.seek}+ onClearMessageTarget={() =>+ setSearch({ messageId: undefined }, { history: 'replace' })+ }/></div></SidePanel.Layout>@@ -137,6 +147,7 @@ export function CallDetailContent(props: {query: ReturnType<typeof useCallRecordQuery>;data?: CallDetailData;transcriptId?: string;+ messageId?: string;seek?: string;}) {// Include the route's seek token so selecting the same segment re-runs the seek.@@ -191,6 +202,8 @@ export function CallDetailContent(props: {callId={props.callId}record={data().record}transcriptTarget={transcriptTarget()}+ messageId={props.messageId}+ seek={props.seek}/></Suspense>)}@@ -202,6 +215,7 @@ export function CallDetailContent(props: {export function StandaloneCallDetail(props: {callId: string;transcriptId?: string;+ messageId?: string;seek?: string;}) {const detail = useCallDetail(() => props.callId);@@ -229,6 +243,7 @@ export function StandaloneCallDetail(props: {query={detail.query}data={detail.data()}transcriptId={props.transcriptId}+ messageId={props.messageId}seek={props.seek}/></div>diff --git a/apps/web/src/features/channel/Call/CallControls/CallControlBar.tsx b/apps/web/src/features/channel/Call/CallControls/CallControlBar.tsxindex c944bca028..c983739677 100644--- a/apps/web/src/features/channel/Call/CallControls/CallControlBar.tsx+++ b/apps/web/src/features/channel/Call/CallControls/CallControlBar.tsx@@ -33,7 +33,7 @@ export function CallControlButton(props: {aria-pressed={props.pressed}disabled={props.disabled}onClick={props.onClick}- class="size-12"+ class="size-10 @sm:size-12">{props.children}</Button>@@ -174,7 +174,7 @@ export function CallControlBar(props: {?.focus();}}}- class="h-12 w-6 @sm:w-8"+ class="h-10 w-5 @sm:h-12 @sm:w-8"><CaretUpclass="size-4 transition-transform duration-200 ease-out motion-reduce:transition-none"diff --git a/apps/web/src/features/channel/Call/CallOverlay.tsx b/apps/web/src/features/channel/Call/CallOverlay.tsxindex 9fbdcdc4e1..c97ea56211 100644--- a/apps/web/src/features/channel/Call/CallOverlay.tsx+++ b/apps/web/src/features/channel/Call/CallOverlay.tsx@@ -2,9 +2,19 @@ import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { UserIcon } from '@core/component/UserIcon';import { useAuthor, useUserId } from '@core/context/user';import { getDisplayName, tryMacroId } from '@core/user';+import ChatIcon from '@phosphor/chat-circle.svg';import { cn, InlineCheckbox, Tooltip } from '@ui';import type { RemoteParticipant, Track } from 'livekit-client';-import { For, type JSXElement, Show } from 'solid-js';+import {+ createSignal,+ createUniqueId,+ For,+ type JSXElement,+ lazy,+ Show,+ Suspense,+} from 'solid-js';+import { useCallContext } from './CallContext';import { CallControls } from './CallControls/CallControls';import {@@ -16,6 +26,8 @@ import { MutedMicrophoneBadge } from './MutedMicrophoneBadge';import { TrackView } from './TrackView';import { useActiveCallTeamShare } from './use-toggle-share-with-team';+const CallChat = lazy(() => import('./chat/CallChat'));+function VideoTag(props: {children: JSXElement;class?: string;@@ -212,6 +224,8 @@ export function CallOverlay(props: {showTeamSharing?: boolean;sharedWithTeam?: boolean;localName?: string;+ /** Shared messages require an authenticated Macro participant. */+ showChat?: boolean;}) {const callCtx = useCallContext();const currentUserId = useUserId();@@ -220,6 +234,20 @@ export function CallOverlay(props: {const teamShare = useActiveCallTeamShare();const sharedWithTeam = () =>props.sharedWithTeam ?? callCtx.isSharedWithTeam();+ const [chatOpen, setChatOpen] = createSignal(false);+ const [chatMounted, setChatMounted] = createSignal(false);+ const chatId = createUniqueId();+ let chatButton: HTMLButtonElement | undefined;+ const closeChat = () => {+ setChatOpen(false);+ chatButton?.focus();+ };+ const toggleChat = () => {+ if (chatOpen()) return closeChat();+ setChatMounted(true);+ setChatOpen(true);+ };+ const canChat = () => props.showChat !== false && !!callCtx.activeCallId();const teamShareLocked = () =>isConnecting() || !teamShare.canToggle() || teamShare.isPending();@@ -278,80 +306,101 @@ export function CallOverlay(props: {};return (- <div class="flex flex-col h-full touch:pb-(--mobile-content-inset-bottom)">- {/* Screen share area */}- <Show when={hasAnyScreenShare()}>- <div class="flex-1 min-h-0 pt-2">- <div class="h-full rounded-lg overflow-hidden bg-surface-2 flex items-center justify-center">- <Show when={callCtx.isScreenSharing()}>- <div class="relative size-full">- <TrackView track={localScreenTrack()} fit="contain" />-- <VideoTag>Your screen</VideoTag>+ <div class="flex flex-col h-full min-h-0 @container/call touch:pb-(--mobile-content-inset-bottom)">+ <div class="relative flex min-h-0 flex-1 overflow-hidden">+ <div class="flex min-w-0 flex-1 flex-col">+ {/* Screen share area */}+ <Show when={hasAnyScreenShare()}>+ <div class="flex-1 min-h-0 pt-2">+ <div class="h-full rounded-lg overflow-hidden bg-surface-2 flex items-center justify-center">+ <Show when={callCtx.isScreenSharing()}>+ <div class="relative size-full">+ <TrackView track={localScreenTrack()} fit="contain" />++ <VideoTag>Your screen</VideoTag>+ </div>+ </Show>+ <For each={remoteScreenShares()}>+ {(participant) => (+ <ScreenShareTile participant={participant} />+ )}+ </For></div>- </Show>- <For each={remoteScreenShares()}>- {(participant) => <ScreenShareTile participant={participant} />}- </For>- </div>- </div>- </Show>+ </div>+ </Show>- {/* Participants area */}- <div- class={`${hasAnyScreenShare() ? 'h-45 shrink-0' : 'flex-1 min-h-0'} relative pt-2`}- >- <Show- when={participants().length > 0}- fallback={- <LocalParticipantTile- class="size-full"- isSpeaking={isLocalSpeaking()}- isConnecting={isConnecting()}- isAudioMuted={callCtx.isAudioMuted()}- isVideoMuted={callCtx.isVideoMuted()}- track={localVideoTrack()}- userId={localUserId()}- fallbackName={- props.localName ||- callCtx.room()?.localParticipant.name ||- currentUserName()- }- />- }- >- {/* Remote participants grid */}+ {/* Participants area */}<div- class={`size-full grid ${gridCols()} gap-2 auto-rows-fr overflow-hidden`}+ class={`${hasAnyScreenShare() ? 'h-45 shrink-0' : 'flex-1 min-h-0'} relative pt-2`}>- <For each={participants()}>- {(participant) => <ParticipantTile participant={participant} />}- </For>- </div>-- {/* Local participant PIP (Google Meet style: small, bottom-right) */}- <div class="absolute bottom-4 right-4 w-40 aspect-video shadow-lg z-10 sm:w-48">- <LocalParticipantTile- class="size-full min-h-0"- isSpeaking={isLocalSpeaking()}- isConnecting={isConnecting()}- isAudioMuted={callCtx.isAudioMuted()}- isVideoMuted={callCtx.isVideoMuted()}- track={localVideoTrack()}- userId={localUserId()}- fallbackName={- props.localName ||- callCtx.room()?.localParticipant.name ||- currentUserName()+ <Show+ when={participants().length > 0}+ fallback={+ <LocalParticipantTile+ class="size-full"+ isSpeaking={isLocalSpeaking()}+ isConnecting={isConnecting()}+ isAudioMuted={callCtx.isAudioMuted()}+ isVideoMuted={callCtx.isVideoMuted()}+ track={localVideoTrack()}+ userId={localUserId()}+ fallbackName={+ props.localName ||+ callCtx.room()?.localParticipant.name ||+ currentUserName()+ }+ />}- avatarSize="sm"- />+ >+ {/* Remote participants grid */}+ <div+ class={`size-full grid ${gridCols()} gap-2 auto-rows-fr overflow-hidden`}+ >+ <For each={participants()}>+ {(participant) => (+ <ParticipantTile participant={participant} />+ )}+ </For>+ </div>++ {/* Local participant PIP (Google Meet style: small, bottom-right) */}+ <div class="absolute bottom-4 right-4 w-40 aspect-video shadow-lg z-10 sm:w-48">+ <LocalParticipantTile+ class="size-full min-h-0"+ isSpeaking={isLocalSpeaking()}+ isConnecting={isConnecting()}+ isAudioMuted={callCtx.isAudioMuted()}+ isVideoMuted={callCtx.isVideoMuted()}+ track={localVideoTrack()}+ userId={localUserId()}+ fallbackName={+ props.localName ||+ callCtx.room()?.localParticipant.name ||+ currentUserName()+ }+ avatarSize="sm"+ />+ </div>+ </Show></div>+ </div>+ <Show when={canChat() && chatMounted()}>+ <Show when={callCtx.activeCallId()} keyed>+ {(callId) => (+ <Suspense>+ <CallChat+ callId={callId}+ id={chatId}+ open={chatOpen()}+ onClose={closeChat}+ />+ </Suspense>+ )}+ </Show></Show></div>-{/* Settings expand over the tiles; sharing stays clear of the controls. */}- <div class="flex flex-col items-center gap-2 py-3 relative">+ <div class="relative flex shrink-0 flex-col items-center gap-2 py-3"><Showwhen={callCtx.activeChannelId() !== null &&@@ -363,8 +412,8 @@ export function CallOverlay(props: {placement="top"label={sharedWithTeam()- ? "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"+ ? "The creator's team can view the chat, transcript, and AI summary once the call ends"+ : "Let the creator's team view the chat, transcript, and AI summary once the call ends"}><button@@ -388,7 +437,34 @@ export function CallOverlay(props: {</button></Tooltip></Show>- <CallControls onLeave={props.onLeave} />+ <div class="grid w-full grid-cols-[minmax(0,1fr)_auto] items-center gap-2 px-2 @min-[500px]/call:gap-3 @min-[500px]/call:px-3 @min-[800px]/call:grid-cols-[minmax(0,1fr)_minmax(0,36rem)_minmax(0,1fr)]">+ <div+ class="flex min-w-0 justify-center @min-[800px]/call:col-start-2"+ classList={{+ 'col-span-2 @min-[800px]/call:col-span-1': !canChat(),+ }}+ >+ <CallControls onLeave={props.onLeave} />+ </div>+ <Show when={canChat()}>+ <div class="justify-self-end rounded-xl border border-edge-muted bg-panel p-1.5 shadow-sm">+ <Tooltip label={chatOpen() ? 'Close chat' : 'Open chat'}>+ <button+ ref={chatButton}+ type="button"+ aria-label={chatOpen() ? 'Close chat' : 'Open chat'}+ aria-expanded={chatOpen()}+ aria-controls={chatId}+ onClick={toggleChat}+ class="flex size-10 items-center justify-center rounded-lg hover:bg-hover focus-visible:outline-2 focus-visible:outline-accent @min-[500px]/call:size-12"+ classList={{ 'bg-hover text-accent': chatOpen() }}+ >+ <ChatIcon class="size-5" />+ </button>+ </Tooltip>+ </div>+ </Show>+ </div></div></div>);diff --git a/apps/web/src/features/channel/Call/chat/CallChat.test.tsx b/apps/web/src/features/channel/Call/chat/CallChat.test.tsxnew file mode 100644index 0000000000..5b40038803--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/CallChat.test.tsx@@ -0,0 +1,162 @@+/** @vitest-environment jsdom */+import type { ChannelInputProps } from '@channel/Input/ChannelInput';+import type { InputHandle, InputSnapshot } from '@channel/Input/types';+import { MessageReferenceNavigation } from '@core/messages/message-reference-navigation';+import type { MessageActionHandler } from '@core/messages/types';+import type { MessageListItem, MessageThread } from '@service-storage/messages';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { type JSX, useContext } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import CallChat from './CallChat';++const mocks = vi.hoisted(() => ({+ source: undefined as unknown,+ composer: undefined as ChannelInputProps | undefined,+ restore: vi.fn(),+ snapshot: vi.fn(),+ send: vi.fn().mockResolvedValue(undefined),+ refresh: vi.fn(),+}));+vi.mock('./queries/use-call-chat', () => ({ useCallChat: () => mocks.source }));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user-id' }));+vi.mock('@queries/messages/mutations', () => ({+ useSendMessageMutation: () => ({ mutateAsync: mocks.send }),+ newMessageId: () => 'new-message',+}));+vi.mock('@channel/Input', () => ({+ ChannelInput: (props: ChannelInputProps) => {+ mocks.composer = props;+ const handle: InputHandle = {+ snapshot: mocks.snapshot,+ clear: vi.fn(),+ focus: vi.fn(),+ send: vi.fn(),+ attachFiles: vi.fn(),+ restoreSnapshot: mocks.restore,+ };+ props.onReady?.(handle);+ return <div data-testid="call-composer" />;+ },+}));+vi.mock('./components/CallChatPanel', () => ({+ CallChatPanel: (props: { children: JSX.Element; composer: JSX.Element }) => (+ <>+ {props.children}+ {props.composer}+ </>+ ),+}));+vi.mock(+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',+ () => ({+ StaticMarkdownContext: (props: { children: JSX.Element }) => props.children,+ })+);+vi.mock('@core/messages/MessageThread', () => ({+ threadListItem: (thread: MessageThread) => thread.root,+ MessageThread: (props: {+ data: MessageListItem;+ onReply?: MessageActionHandler;+ targetId?: string;+ targetRequestKey?: string | number;+ }) => {+ const navigate = useContext(MessageReferenceNavigation);+ return (+ <>+ <button onClick={() => props.onReply?.({ message: props.data })}>+ Reply+ </button>+ <button+ onClick={() =>+ navigate?.({+ parent: props.data.parent,+ targetMessageId: props.data.id,+ targetThreadId: 'call-id',+ displayText: props.data.content,+ senderId: props.data.sender_id,+ })+ }+ >+ Quoted message+ </button>+ <span data-testid="target" data-request-key={props.targetRequestKey}>+ {props.targetId}+ </span>+ </>+ );+ },+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it.each(['user-id', 'another-user'])(+ 'quotes a message from %s into the existing draft and sends in the call thread',+ async (senderId) => {+ const root: MessageThread['root'] = {+ id: 'call-id',+ parent: { type: 'call', id: 'call-id' },+ sender_id: senderId,+ content: 'Original message',+ created_at: '2026-09-28T00:00:00Z',+ updated_at: '2026-09-28T00:00:00Z',+ attachments: [],+ mentions: [],+ reactions: [],+ };+ mocks.source = {+ thread: () => ({ root, replies: [] }),+ parent: () => root.parent,+ empty: () => false,+ loading: () => false,+ failed: () => false,+ refresh: mocks.refresh,+ };+ render(() => (+ <CallChat callId="call-id" id="chat" open onClose={() => {}} />+ ));+ const draft: InputSnapshot = {+ value: 'Existing draft',+ mentions: [{ itemType: 'user', itemId: 'bot|owned-agent' }],+ attachments: [{ id: 'file-id', name: 'Notes', kind: 'document' }],+ };+ // A draft restored from persistence has not emitted onChange yet.+ mocks.snapshot.mockReturnValue(draft);+ fireEvent.click(screen.getByRole('button', { name: 'Reply' }));+ expect(screen.getAllByTestId('call-composer')).toHaveLength(1);+ fireEvent.click(screen.getByRole('button', { name: 'Quoted message' }));+ expect(screen.getByTestId('target').textContent).toBe('call-id');+ const target = screen.getByTestId('target');+ const composer = screen.getByTestId('call-composer');+ const firstRequest = target.getAttribute('data-request-key');+ fireEvent.click(screen.getByRole('button', { name: 'Quoted message' }));+ expect(target.getAttribute('data-request-key')).not.toBe(firstRequest);+ expect(screen.getByTestId('target')).toBe(target);+ expect(screen.getByTestId('call-composer')).toBe(composer);+ expect(mocks.restore).toHaveBeenCalledOnce();+ expect(mocks.restore).toHaveBeenCalledWith(+ {+ ...draft,+ value: expect.stringContaining('"targetThreadId":"call-id"'),+ },+ { cursor: 'trailing-paragraph' }+ );+ const quoted: InputSnapshot = mocks.restore.mock.calls[0][0];+ expect(quoted.value).toContain('"parent":{"type":"call","id":"call-id"}');+ expect(quoted.value).toMatch(/\n\nExisting draft$/);+ await mocks.composer?.onSend?.(quoted);+ expect(mocks.send).toHaveBeenCalledWith(+ expect.objectContaining({+ parent: root.parent,+ message: expect.objectContaining({+ thread_id: 'call-id',+ content: quoted.value,+ mentions: [{ entity_type: 'bot', entity_id: 'bot|owned-agent' }],+ attachments: [expect.objectContaining({ entity_id: 'file-id' })],+ }),+ })+ );+ }+);diff --git a/apps/web/src/features/channel/Call/chat/CallChat.tsx b/apps/web/src/features/channel/Call/chat/CallChat.tsxnew file mode 100644index 0000000000..9e089dc337--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/CallChat.tsx@@ -0,0 +1,196 @@+import {+ ChannelInput,+ type InputHandle,+ type InputSnapshot,+} from '@channel/Input';+import { buildPostMessageSendPayload } from '@channel/Input/message-payload';+import { buildReplyTargetValue } from '@channel/Thread/utils/message-actions';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { useUserId } from '@core/context/user';+import { MessageThread, threadListItem } from '@core/messages/MessageThread';+import { MessageReferenceNavigation } from '@core/messages/message-reference-navigation';+import {+ newMessageId,+ useSendMessageMutation,+} from '@queries/messages/mutations';+import {+ createEffect,+ createMemo,+ createSignal,+ on,+ Show,+ Suspense,+} from 'solid-js';+import { buildCallMessageLink } from './build-call-message-link';+import { CallChatPanel } from './components/CallChatPanel';+import { useCallChat } from './queries/use-call-chat';++export default function CallChat(props: {+ callId: string;+ id: string;+ open: boolean;+ onClose: () => void;+}) {+ // Queries and all shared Markdown descendants stay within the chat boundary.+ return (+ <Suspense+ fallback={+ <CallChatPanel {...props} composer={null}>+ <p role="status" class="text-sm text-ink-muted">+ Loading chat…+ </p>+ </CallChatPanel>+ }+ >+ <CallChatContent {...props} />+ </Suspense>+ );+}++function CallChatContent(props: {+ callId: string;+ id: string;+ open: boolean;+ onClose: () => void;+}) {+ const chat = useCallChat(() => props.callId);+ const send = useSendMessageMutation();+ const userId = useUserId();+ const [sendFailed, setSendFailed] = createSignal(false);+ const [input, setInput] = createSignal<InputHandle>();+ const [messageTarget, setMessageTarget] = createSignal<{+ id: string;+ requestKey: number;+ }>();+ const canSend = createMemo(() => !!chat.thread() || chat.empty());++ createEffect(+ on([() => props.open, canSend, input], ([open, ready, handle]) => {+ if (open && ready) handle?.focus();+ })+ );++ async function sendMessage(snapshot: InputSnapshot) {+ const senderId = userId();+ if (!senderId || (!chat.thread() && !chat.empty())) {+ throw new Error('Call chat is not ready');+ }+ setSendFailed(false);+ try {+ await send.mutateAsync({+ parent: chat.parent(),+ senderId,+ optimisticId: newMessageId(),+ ...buildPostMessageSendPayload({+ snapshot,+ threadId: chat.thread() ? props.callId : undefined,+ }),+ });+ } catch (error) {+ setSendFailed(true);+ throw error;+ }+ await chat.refresh();+ }++ return (+ <MessageReferenceNavigation.Provider+ value={(target) => {+ if (target.parent.type !== 'call' || target.parent.id !== props.callId)+ return false;+ setMessageTarget((previous) => ({+ id: target.targetMessageId,+ requestKey: (previous?.requestKey ?? 0) + 1,+ }));+ return true;+ }}+ >+ <StaticMarkdownContext>+ <CallChatPanel+ id={props.id}+ open={props.open}+ onClose={props.onClose}+ composer={+ <div inert={!canSend()} classList={{ 'opacity-50': !canSend() }}>+ <Show when={sendFailed()}>+ <p role="alert" class="mb-2 text-xs text-failure">+ Message could not be sent. Try again.+ </p>+ </Show>+ <ChannelInput+ parent={chat.parent()}+ input={{ mode: 'channel', placeholder: 'Message this call…' }}+ persistenceKey={`call-chat-${userId()}-${props.callId}-persist-v1`}+ autofocus={false}+ onReady={setInput}+ onSend={sendMessage}+ onSendError={() => setSendFailed(true)}+ onEscape={props.onClose}+ />+ </div>+ }+ >+ <Show when={chat.loading()}>+ <p role="status" class="text-sm text-ink-muted">+ Loading chat…+ </p>+ </Show>+ <Show when={chat.empty()}>+ <p class="px-1 text-sm text-ink-muted">+ Start the conversation. Messages stay with this call.+ </p>+ </Show>+ <Show when={chat.failed()}>+ <p role="alert" class="text-sm text-ink-muted">+ Could not load chat.+ </p>+ <button+ type="button"+ class="mt-2 text-sm text-accent"+ onClick={() => void chat.refresh()}+ >+ Retry+ </button>+ </Show>+ <Show when={chat.thread()}>+ {(thread) => (+ <MessageThread+ data={threadListItem(thread())}+ canWrite+ expanded+ hideReplyInput+ monorail+ hideRail+ targetId={messageTarget()?.id}+ targetRequestKey={messageTarget()?.requestKey}+ onClearTarget={() => setMessageTarget(undefined)}+ onReply={({ message, selectedText, renderedText }) => {+ const handle = input();+ if (!handle) return;+ const current = handle.snapshot();+ handle.restoreSnapshot(+ {+ value: buildReplyTargetValue({+ parent: chat.parent(),+ message,+ selectedText,+ renderedText,+ existingValue: current.value,+ }),+ mentions: current.mentions,+ attachments: current.attachments,+ },+ { cursor: 'trailing-paragraph' }+ );+ }}+ buildLink={(message) =>+ buildCallMessageLink(props.callId, message.id)+ }+ />+ )}+ </Show>+ </CallChatPanel>+ </StaticMarkdownContext>+ </MessageReferenceNavigation.Provider>+ );+}diff --git a/apps/web/src/features/channel/Call/chat/CallChatHistory.test.tsx b/apps/web/src/features/channel/Call/chat/CallChatHistory.test.tsxnew file mode 100644index 0000000000..dfd706b053--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/CallChatHistory.test.tsx@@ -0,0 +1,107 @@+/** @vitest-environment jsdom */+import type { MessageListItem, MessageThread } from '@service-storage/messages';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { type Accessor, createSignal, type JSX } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { CallChatHistory } from './CallChatHistory';++const mocks = vi.hoisted(() => ({+ source: undefined as unknown,+ refresh: vi.fn(),+}));+vi.mock('./queries/use-call-chat', () => ({ useCallChat: () => mocks.source }));+vi.mock(+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',+ () => ({+ StaticMarkdownContext: (props: { children: JSX.Element }) => props.children,+ })+);+vi.mock('@core/messages/MessageThread', () => ({+ threadListItem: (thread: MessageThread) => thread.root,+ MessageThread: (props: {+ data: MessageListItem;+ canWrite: boolean;+ targetId?: string;+ onClearTarget?: () => void;+ buildLink: (message: MessageListItem) => string;+ }) => (+ <>+ <p>+ {props.canWrite ? 'Writable' : 'Read only'}: {props.data.content}+ </p>+ <a href={props.buildLink(props.data)}>Message link</a>+ <button onClick={props.onClearTarget}>+ Target: {props.targetId ?? 'none'}+ </button>+ </>+ ),+}));++function source(thread: Accessor<MessageThread | undefined>, status = 'ready') {+ mocks.source = {+ thread,+ empty: () => status === 'empty',+ failed: () => status === 'error',+ loading: () => status === 'loading',+ refresh: mocks.refresh,+ };+}++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it('shows the saved thread read-only and clears a linked message highlight', () => {+ const [target, setTarget] = createSignal<string | undefined>('reply-id');+ const root: MessageThread['root'] = {+ id: 'call-id',+ content: 'Saved chat',+ parent: { type: 'call', id: 'call-id' },+ sender_id: 'user-id',+ created_at: '2026-09-26T00:00:00Z',+ updated_at: '2026-09-26T00:00:00Z',+ attachments: [],+ mentions: [],+ reactions: [],+ };+ source(() => ({+ root,+ state: {+ root_id: 'call-id',+ user_id: 'user-id',+ resolved: false,+ created_at: root.created_at,+ updated_at: root.updated_at,+ },+ replies: [],+ }));+ render(() => (+ <CallChatHistory+ callId="call-id"+ targetId={target()}+ onClearTarget={() => setTarget(undefined)}+ />+ ));+ expect(screen.getByText('Read only: Saved chat')).toBeTruthy();+ const link = new URL(screen.getByRole('link').getAttribute('href')!);+ expect(link.pathname).toBe('/app/call/call-id');+ expect(link.searchParams.get('call_message_id')).toBe('call-id');+ fireEvent.click(screen.getByRole('button', { name: 'Target: reply-id' }));+ expect(screen.getByRole('button', { name: 'Target: none' })).toBeTruthy();+});++it('distinguishes an empty chat from a failed request with retry', () => {+ source(() => undefined, 'empty');+ const empty = render(() => <CallChatHistory callId="empty-call" />);+ expect(+ screen.getByText('No messages were sent during this call.')+ ).toBeTruthy();+ expect(screen.queryByRole('alert')).toBeNull();+ empty.unmount();+ source(() => undefined, 'error');+ render(() => <CallChatHistory callId="failed-call" />);+ expect(screen.getByRole('alert').textContent).toBe('Could not load chat.');+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(mocks.refresh).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/channel/Call/chat/CallChatHistory.tsx b/apps/web/src/features/channel/Call/chat/CallChatHistory.tsxnew file mode 100644index 0000000000..d8f136bd0f--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/CallChatHistory.tsx@@ -0,0 +1,76 @@+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { MessageThread, threadListItem } from '@core/messages/MessageThread';+import { Show, Suspense } from 'solid-js';+import { buildCallMessageLink } from './build-call-message-link';+import { useCallChat } from './queries/use-call-chat';++type CallChatHistoryProps = {+ callId: string;+ targetId?: string;+ targetRequestKey?: string | number;+ onClearTarget?: () => void;+};++/** Saved call chat shares the live thread cache and read-only message controls. */+export function CallChatHistory(props: CallChatHistoryProps) {+ return (+ <section class="flex min-w-0 flex-col gap-3" aria-label="Call chat">+ <h3 class="text-sm font-semibold text-ink">Call chat</h3>+ <Suspense fallback={<p class="text-sm text-ink-muted">Loading chat…</p>}>+ <CallChatHistoryContent {...props} />+ </Suspense>+ </section>+ );+}++function CallChatHistoryContent(props: CallChatHistoryProps) {+ const chat = useCallChat(() => props.callId);+ return (+ <StaticMarkdownContext>+ <Show when={chat.loading()}>+ <p role="status" class="text-sm text-ink-muted">+ Loading chat…+ </p>+ </Show>+ <Show when={chat.empty()}>+ <p class="text-sm text-ink-muted">+ No messages were sent during this call.+ </p>+ </Show>+ <Show when={chat.failed()}>+ <div>+ <p role="alert" class="text-sm text-ink-muted">+ Could not load chat.+ </p>+ <button+ type="button"+ class="mt-2 text-sm text-accent"+ onClick={() => void chat.refresh()}+ >+ Retry+ </button>+ </div>+ </Show>+ <Show when={chat.thread()}>+ {(thread) => (+ <div class="min-w-0 rounded border border-edge-muted/50 py-2">+ <MessageThread+ data={threadListItem(thread())}+ canWrite={false}+ expanded+ hideReplyInput+ monorail+ hideRail+ targetId={props.targetId}+ targetRequestKey={props.targetRequestKey}+ onClearTarget={props.onClearTarget}+ buildLink={(message) =>+ buildCallMessageLink(props.callId, message.id)+ }+ />+ </div>+ )}+ </Show>+ </StaticMarkdownContext>+ );+}diff --git a/apps/web/src/features/channel/Call/chat/build-call-message-link.ts b/apps/web/src/features/channel/Call/chat/build-call-message-link.tsnew file mode 100644index 0000000000..bb9cdc79e4--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/build-call-message-link.ts@@ -0,0 +1,12 @@+import { URL_PARAMS } from '@block-call/constants';+import { buildSimpleEntityUrl } from '@core/util/url';++export function buildCallMessageLink(+ callId: string,+ messageId: string+): string {+ return buildSimpleEntityUrl(+ { type: 'call', id: callId },+ { [URL_PARAMS.messageId]: messageId }+ );+}diff --git a/apps/web/src/features/channel/Call/chat/components/CallChatPanel.test.tsx b/apps/web/src/features/channel/Call/chat/components/CallChatPanel.test.tsxnew file mode 100644index 0000000000..5318fe1fef--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/components/CallChatPanel.test.tsx@@ -0,0 +1,79 @@+/** @vitest-environment jsdom */+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { CallChatPanel } from './CallChatPanel';++let resize: () => void;+const disconnect = vi.fn();+beforeEach(() => {+ disconnect.mockClear();+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor(callback: () => void) {+ resize = callback;+ }+ observe() {}+ disconnect = disconnect;+ }+ );+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++it('preserves the draft and content nodes when closing and reopening', () => {+ const [open, setOpen] = createSignal(true);+ render(() => (+ <CallChatPanel+ id="chat"+ open={open()}+ onClose={() => setOpen(false)}+ composer={<input aria-label="Message" />}+ >+ <p>Earlier message</p>+ </CallChatPanel>+ ));+ const input = screen.getByRole('textbox') as HTMLInputElement;+ fireEvent.input(input, { target: { value: 'Unsent draft' } });+ const panel = screen.getByRole('complementary', { name: 'Call chat' });+ setOpen(false);+ expect(panel.hidden).toBe(true);+ expect(screen.queryByRole('textbox')).toBeNull();+ setOpen(true);+ expect(screen.getByRole('textbox')).toBe(input);+ expect(input.value).toBe('Unsent draft');+ fireEvent.keyDown(input, { key: 'Escape' });+ expect(panel.hidden).toBe(true);+});++it('follows new messages at the bottom without jumping while reading history', () => {+ const result = render(() => (+ <CallChatPanel id="chat" open onClose={() => {}} composer={null}>+ <p>Messages</p>+ </CallChatPanel>+ ));+ const content = screen.getByText('Messages').parentElement!;+ const viewport = content.parentElement!;+ let height = 1000;+ Object.defineProperties(viewport, {+ scrollHeight: { get: () => height },+ clientHeight: { value: 200 },+ });+ resize();+ expect(viewport.scrollTop).toBe(1000);+ viewport.scrollTop = 300;+ fireEvent.scroll(viewport);+ height = 1200;+ resize();+ expect(viewport.scrollTop).toBe(300);+ viewport.scrollTop = 1000;+ fireEvent.scroll(viewport);+ height = 1400;+ resize();+ expect(viewport.scrollTop).toBe(1400);+ result.unmount();+ expect(disconnect).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsx b/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsxnew file mode 100644index 0000000000..30c0248feb--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/components/CallChatPanel.tsx@@ -0,0 +1,54 @@+import { type JSX, onCleanup, onMount } from 'solid-js';++/** A persistent sidebar: closing it preserves the composer and scroll position. */+export function CallChatPanel(props: {+ id: string;+ open: boolean;+ onClose: () => void;+ children: JSX.Element;+ composer: JSX.Element;+}) {+ let viewport!: HTMLDivElement;+ let content!: HTMLDivElement;+ let pinned = true;++ onMount(() => {+ const observer = new ResizeObserver(() => {+ if (props.open && pinned) viewport.scrollTop = viewport.scrollHeight;+ });+ observer.observe(viewport);+ observer.observe(content);+ onCleanup(() => observer.disconnect());+ });++ return (+ <aside+ id={props.id}+ aria-label="Call chat"+ hidden={!props.open}+ class="absolute inset-y-0 right-0 z-20 w-full max-w-90 min-h-0 flex-col bg-surface @min-[800px]/call:static @min-[800px]/call:w-90 @min-[800px]/call:shrink-0"+ classList={{ flex: props.open }}+ onKeyDown={(event) => {+ if (event.key !== 'Escape' || event.defaultPrevented) return;+ event.preventDefault();+ event.stopPropagation();+ props.onClose();+ }}+ >+ <div+ ref={viewport}+ data-channel-scroll+ class="min-h-0 flex-1 overflow-y-auto overscroll-contain px-3 py-4"+ onScroll={() => {+ if (!props.open) return;+ pinned =+ viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <+ 48;+ }}+ >+ <div ref={content}>{props.children}</div>+ </div>+ <div class="shrink-0 p-3">{props.composer}</div>+ </aside>+ );+}diff --git a/apps/web/src/features/channel/Call/chat/queries/keys.ts b/apps/web/src/features/channel/Call/chat/queries/keys.tsnew file mode 100644index 0000000000..045a08fb9f--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/queries/keys.ts@@ -0,0 +1,2 @@+// Call chat shares the canonical message thread cache with every messaging surface.+export { messageKeys as callChatKeys } from '@queries/messages/keys';diff --git a/apps/web/src/features/channel/Call/chat/queries/use-call-chat.test.tsx b/apps/web/src/features/channel/Call/chat/queries/use-call-chat.test.tsxnew file mode 100644index 0000000000..551d815203--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/queries/use-call-chat.test.tsx@@ -0,0 +1,131 @@+/** @vitest-environment jsdom */+import { ThrownResultError } from '@core/util/result';+import type { MessageThread } from '@service-storage/messages';+import { cleanup, render, waitFor } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { useCallChat } from './use-call-chat';++let client: QueryClient;+const mocks = vi.hoisted(() => ({ thread: vi.fn() }));+vi.mock('@service-storage/messages', () => ({ entityMessagesClient: mocks }));+vi.mock('@queries/messages/subscription', () => ({+ useMessageSubscription: () => {},+}));+vi.mock('@queries/client', () => ({+ get queryClient() {+ return client;+ },+}));++beforeEach(() => {+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ mocks.thread.mockReset();+});+afterEach(() => {+ cleanup();+ client.clear();+});++function mount() {+ let source!: ReturnType<typeof useCallChat>;+ render(() => (+ <QueryClientProvider client={client}>+ {(() => {+ source = useCallChat(() => 'call-id');+ return null;+ })()}+ </QueryClientProvider>+ ));+ return source;+}++function failure(code: string) {+ return new ThrownResultError([{ code, message: code }]);+}++const thread: MessageThread = {+ root: {+ id: 'call-id',+ parent: { type: 'call', id: 'call-id' },+ sender_id: 'user',+ content: 'First message',+ mentions: [],+ attachments: [],+ reactions: [],+ created_at: '2026-09-26T00:00:00Z',+ updated_at: '2026-09-26T00:00:00Z',+ },+ state: {+ root_id: 'call-id',+ user_id: 'user',+ resolved: false,+ created_at: '2026-09-26T00:00:00Z',+ updated_at: '2026-09-26T00:00:00Z',+ },+ replies: [],+};++it('treats only a missing root as an empty conversation and can refresh after the first send', async () => {+ mocks.thread.mockRejectedValueOnce(failure('NOT_FOUND'));+ const source = mount();+ expect(source.loading()).toBe(true);+ expect(source.thread()).toBeUndefined();+ await waitFor(() => expect(source.empty()).toBe(true));+ expect(source.failed()).toBe(false);+ expect(mocks.thread).toHaveBeenCalledOnce();+ expect(mocks.thread).toHaveBeenCalledWith(+ { type: 'call', id: 'call-id' },+ 'call-id'+ );+ mocks.thread.mockResolvedValue(thread);+ await source.refresh();+ await waitFor(() =>+ expect(source.thread()?.root.content).toBe('First message')+ );+ expect(source.empty()).toBe(false);+});++it.each(['FORBIDDEN', 'UNAUTHORIZED', 'INTERNAL_SERVER_ERROR'])(+ 'keeps %s failures distinct from an empty chat',+ async (code) => {+ mocks.thread.mockRejectedValue(failure(code));+ const source = mount();+ await waitFor(() => expect(source.failed()).toBe(true));+ expect(source.empty()).toBe(false);+ expect(source.thread()).toBeUndefined();+ }+);++it('retains readable messages through a failed background refresh', async () => {+ mocks.thread.mockResolvedValueOnce(thread);+ const source = mount();+ await waitFor(() => expect(source.thread()).toBeDefined());+ mocks.thread.mockRejectedValue(failure('INTERNAL_SERVER_ERROR'));+ await source.refresh();+ await waitFor(() => expect(source.failed()).toBe(true));+ expect(source.thread()?.root.content).toBe('First message');+});++it.each(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHORIZED'])(+ 'hides cached messages after a %s refresh and restores them on recovery',+ async (code) => {+ mocks.thread.mockResolvedValueOnce(thread);+ const source = mount();+ await waitFor(() => expect(source.thread()).toBeDefined());+ mocks.thread.mockRejectedValue(failure(code));++ await source.refresh();++ await waitFor(() => expect(source.failed()).toBe(true));+ expect(source.empty()).toBe(false);+ expect(source.loading()).toBe(false);+ expect(source.thread()).toBeUndefined();++ mocks.thread.mockResolvedValue(thread);+ await source.refresh();+ await waitFor(() => expect(source.failed()).toBe(false));+ expect(source.empty()).toBe(false);+ expect(source.thread()?.root.content).toBe('First message');+ }+);diff --git a/apps/web/src/features/channel/Call/chat/queries/use-call-chat.ts b/apps/web/src/features/channel/Call/chat/queries/use-call-chat.tsnew file mode 100644index 0000000000..0b029c4221--- /dev/null+++ b/apps/web/src/features/channel/Call/chat/queries/use-call-chat.ts@@ -0,0 +1,36 @@+import { thrownResultErrorHasCode } from '@core/util/result';+import { useMessageSubscription } from '@queries/messages/subscription';+import { threadRepliesQueryOptions } from '@queries/messages/thread-replies';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { callChatKeys } from './keys';++/** A missing canonical root means nobody has sent the first message yet. */+export function useCallChat(callId: Accessor<string>) {+ const parent = () => ({ type: 'call' as const, id: callId() });+ useMessageSubscription(parent);+ const query = useQuery(() => ({+ ...threadRepliesQueryOptions(parent(), callId()),+ queryKey: callChatKeys.threadReplies(parent(), callId()).queryKey,+ retry: false,+ refetchOnMount: 'always' as const,+ }));+ const empty = () =>+ query.isLoadingError && thrownResultErrorHasCode(query.error, 'NOT_FOUND');+ const unavailable = () =>+ query.isError &&+ ['NOT_FOUND', 'FORBIDDEN', 'UNAUTHORIZED'].some((code) =>+ thrownResultErrorHasCode(query.error, code)+ );+ return {+ parent,+ thread: () =>+ query.isSuccess || (query.isRefetchError && !unavailable())+ ? query.data+ : undefined,+ empty,+ loading: () => query.isPending,+ failed: () => query.isError && !empty(),+ refresh: () => query.refetch(),+ };+}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.tsxindex 22c2fc7752..d1b751c2e1 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@@ -2,7 +2,7 @@* @vitest-environment jsdom*/-import { render, screen } from '@solidjs/testing-library';+import { fireEvent, render, screen } from '@solidjs/testing-library';import type { RemoteParticipant, Track } from 'livekit-client';import { createSignal, type Setter } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -52,6 +52,16 @@ vi.mock('../CallControls/CallControls', () => ({CallControls: () => null,}));+vi.mock('../chat/CallChat', () => ({+ default: (props: { callId: string; open: boolean; onClose: () => void }) => (+ <aside hidden={!props.open} aria-label="Call chat">+ <p>{props.callId}</p>+ <input aria-label="Message this call" />+ <button onClick={props.onClose}>Close sidebar</button>+ </aside>+ ),+}));+vi.mock('../TrackView', () => ({TrackView: (props: { track?: { sid?: string } }) => (<div data-testid={`track-${props.track?.sid ?? 'none'}`} />@@ -118,6 +128,7 @@ function setUpCallState(mocks.callContext = {activeChannelId: channelId,+ activeCallId: () => 'call-id',connectionState: () => 'connected',isAudioMuted: audioMuted,isConnecting: () => false,@@ -174,6 +185,54 @@ describe('CallOverlay muted microphone badges', () => {expect(screen.queryByRole('checkbox')).toBeNull();});+ it('opens chat for a standalone meeting without a channel', async () => {+ const controls = setUpCallState();+ controls.setChannelId(null);+ render(() => (+ <CallOverlay onLeave={() => undefined} showTeamSharing={false} />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Open chat' }));+ expect(+ await screen.findByRole('textbox', { name: 'Message this call' })+ ).toBeTruthy();+ expect(screen.getByText('call-id')).toBeTruthy();+ expect(screen.queryByRole('checkbox')).toBeNull();+ });++ it('does not mount authenticated message queries for a guest', () => {+ const controls = setUpCallState();+ controls.setChannelId(null);+ render(() => <CallOverlay onLeave={() => undefined} showChat={false} />);+ expect(screen.queryByRole('button', { name: 'Open chat' })).toBeNull();+ expect(+ screen.queryByRole('complementary', { name: 'Call chat' })+ ).toBeNull();+ });++ it('opens the call thread without remounting video and restores focus when closed', async () => {+ setUpCallState();+ render(() => <CallOverlay onLeave={() => undefined} />);+ const video = screen.getByTestId('track-local-camera');+ const toggle = screen.getByRole('button', { name: 'Open chat' });+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ fireEvent.click(toggle);+ const composer = await screen.findByRole('textbox', {+ name: 'Message this call',+ });+ fireEvent.input(composer, { target: { value: 'Draft' } });+ expect(screen.getByText('call-id')).toBeTruthy();+ expect(screen.getByTestId('track-local-camera')).toBe(video);+ fireEvent.click(screen.getByRole('button', { name: 'Close sidebar' }));+ expect(document.activeElement).toBe(toggle);+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ fireEvent.click(toggle);+ expect(screen.getByRole('textbox', { name: 'Message this call' })).toBe(+ composer+ );+ expect((composer as HTMLInputElement).value).toBe('Draft');+ expect(screen.getByTestId('track-local-camera')).toBe(video);+ });+it('shows local mute state on both the full tile and local PIP', () => {const controls = setUpCallState();diff --git a/apps/web/src/features/channel/Channel/create-channel-message-actions.ts b/apps/web/src/features/channel/Channel/create-channel-message-actions.tsindex 7981183df8..91cb237b71 100644--- a/apps/web/src/features/channel/Channel/create-channel-message-actions.ts+++ b/apps/web/src/features/channel/Channel/create-channel-message-actions.ts@@ -111,13 +111,13 @@ export function createChannelMessageActions(const currentUserId = options.userId();const writable = options.canWrite?.(message) ?? true;const canEdit = writable && canEditMessage(message, currentUserId);+ const canModerate = options.canModerate?.() ?? false;const canDelete =writable &&- canDeleteMessage(- message,- currentUserId,- options.canModerate?.() ?? false- );+ canDeleteMessage(message, currentUserId, canModerate) &&+ (canModerate ||+ (message.parent ?? options.parent()).type === 'channel' ||+ message.sender_id === currentUserId);const canReply = writable && canReplyToMessage(message);const isDeleted = !!message.deleted_at;diff --git a/apps/web/src/features/channel/Channel/tests/create-channel-message-actions.test.ts b/apps/web/src/features/channel/Channel/tests/create-channel-message-actions.test.tsindex 8bc75610f3..c4247b758a 100644--- a/apps/web/src/features/channel/Channel/tests/create-channel-message-actions.test.ts+++ b/apps/web/src/features/channel/Channel/tests/create-channel-message-actions.test.ts@@ -1,3 +1,4 @@+import type { MessageParent } from '@service-storage/messages';import { describe, expect, it, vi } from 'vitest';import type { MessageData } from '../../Message';import { createChannelMessageActions } from '../create-channel-message-actions';@@ -30,6 +31,8 @@ function buildMessage(overrides?: Partial<ActionMessage>): ActionMessage {function buildHarness(input?: {userId?: string | undefined;channelId?: string;+ parentType?: MessageParent['type'];+ canModerate?: boolean;onReply?: Parameters<typeof createChannelMessageActions>[0]['onReply'];onEdit?: Parameters<typeof createChannelMessageActions>[0]['onEdit'];effects?: Parameters<typeof createChannelMessageActions>[0]['effects'];@@ -40,10 +43,11 @@ function buildHarness(input?: {const getMessageActions = createChannelMessageActions({parent: () => ({- type: 'channel',+ type: input?.parentType ?? 'channel',id: (() => input?.channelId ?? 'channel-1')(),}),userId: () => input?.userId,+ canModerate: () => input?.canModerate ?? false,deleteMessage,addReaction,removeReaction,@@ -61,6 +65,27 @@ function buildHarness(input?: {}describe('createChannelMessageActions', () => {+ it.each([+ ['channel', false, true],+ ['call', false, false],+ ['document', false, false],+ ['document', true, true],+ ] as const)(+ 'matches bot deletion permissions for %s (moderator: %s)',+ (parentType, canModerate, canDelete) => {+ const harness = buildHarness({+ userId: 'user-1',+ parentType,+ canModerate,+ });+ const actions = harness.getMessageActions(+ buildMessage({ sender_id: 'bot|agent-1' })+ );++ expect(!!actions.onDelete).toBe(canDelete);+ }+ );+it('uses the live message from the reaction context when toggling', () => {const harness = buildHarness({ userId: 'user-1' });const staleMessage = buildMessage({ reactions: [] });diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsxindex 1328d0b99c..b724faca62 100644--- a/apps/web/src/features/channel/Input/ChannelInput.tsx+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx@@ -83,6 +83,10 @@ export type ChannelInputProps = InputCallbacks & {participants?: Accessor<IUser[]>;/** Channel bots surfaced in the `@`-mention typeahead alongside users. */bots?: Accessor<IUser[]>;+ /** Handles a failed send while preserving the composer's draft. */+ onSendError?: (error: unknown) => void;+ /** Dismiss the host after Escape has closed inline menus or dictation. */+ onEscape?: () => void;onReady?: (handle: InputHandle) => void;children?: JSX.Element;/** Whether to auto-focus the input on mount. Defaults to `!isTouchDevice()`. */@@ -176,6 +180,7 @@ export function ChannelInput(props: ChannelInputProps) {attachmentTracker: props.attachmentTracker,persistenceKey: props.persistenceKey,callbacks: props,+ onSendError: props.onSendError,clearEditor: () => clearComposer(),trackTyping: () => acceptTyping,attachFiles: async (files) => {@@ -262,7 +267,7 @@ export function ChannelInput(props: ChannelInputProps) {? useMessageParticipants(() => props.parent!): () => [];// Connection-prompt behavior for the built-in agents lives in- // useAgentMentionUsers; participants and channel/document bots feed it here.+ // useAgentMentionUsers; participants and parent agents feed it here.const mentionUsers = useAgentMentionUsers(() => [...(props.participants?.() ?? parentParticipants()),...(props.bots?.() ?? parentBots()),@@ -392,6 +397,7 @@ export function ChannelInput(props: ChannelInputProps) {};props.onReady?.({+ snapshot: inputState.snapshot,clear: () => markdownEditor.controls.clear(),focus: () => {// A collapsed pill hides the editor; programmatic focus implies intent@@ -426,7 +432,10 @@ export function ChannelInput(props: ChannelInputProps) {return true;}// Block upstream escape handlers when ESC should close inline menus.- return markdownEditor.controls.isInlineMenuOpen();+ if (markdownEditor.controls.isInlineMenuOpen()) return true;+ if (!props.onEscape) return false;+ props.onEscape();+ return true;},});diff --git a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx b/apps/web/src/features/channel/Input/tests/input-slots.test.tsxindex d9966a05cc..b2c96fb9a2 100644--- a/apps/web/src/features/channel/Input/tests/input-slots.test.tsx+++ b/apps/web/src/features/channel/Input/tests/input-slots.test.tsx@@ -19,6 +19,8 @@ const editorMocks = vi.hoisted(() => ({mentionUsers: undefined as (() => IUser[]) | undefined,emitChange: undefined as ((markdown: string) => void) | undefined,onEnter: undefined as (() => boolean) | undefined,+ inlineMenuOpen: false,+ onEscape: undefined as ((event?: KeyboardEvent) => boolean) | undefined,}));vi.mock(@@ -26,6 +28,19 @@ vi.mock(() => ({ StaticMarkdown: () => null }));+vi.mock('@core/hotkey/hotkeys', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@core/hotkey/hotkeys')>();+ return {+ ...actual,+ registerHotkey: (options: Parameters<typeof actual.registerHotkey>[0]) => {+ if (options.description === 'block escape from moving up scope') {+ editorMocks.onEscape = options.keyDownHandler;+ }+ return actual.registerHotkey(options);+ },+ };+});+// These slots render the microphone, so they run with dictation rolled out.// Other flags keep their real values.vi.mock('@core/constant/featureFlags', async (original) => {@@ -176,6 +191,18 @@ vi.mock('@core/component/EntityIcon', () => ({EntityIcon: () => <span data-testid="entity-icon" />,}));+// Input slots do not exercise rich message rendering. Keep collapsed drafts+// outside StaticMarkdown's application/decorator import graph.+vi.mock(+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',+ () => ({+ StaticMarkdown: (props: { markdown: string }) => (+ <span>{props.markdown}</span>+ ),+ StaticMarkdownContext: (props: { children: JSX.Element }) => props.children,+ })+);+vi.mock('@core/component/ImagePreview', () => ({ImagePreview: (props: { image: { id: string } }) => (<div data-testid={`image-preview-${props.image.id}`} />@@ -221,6 +248,7 @@ vi.mock(const controls = {clear: editorMocks.clear,focus: editorMocks.focus,+ isInlineMenuOpen: () => editorMocks.inlineMenuOpen,setMarkdown: (markdown: string) => {editorMocks.emitChange?.(markdown);},@@ -373,6 +401,8 @@ describe('Input slots', () => {editorMocks.focus.mockClear();editorMocks.emitChange = undefined;editorMocks.onEnter = undefined;+ editorMocks.inlineMenuOpen = false;+ editorMocks.onEscape = undefined;editorMocks.mentionUsers = undefined;vi.mocked(isMobile).mockReturnValue(false);});@@ -408,6 +438,30 @@ describe('Input slots', () => {expect(onSend.mock.calls[0]?.[0]?.value).toBe('existing draft');});+ it('handles dictation and inline menus before dismissing the composer host on Escape', async () => {+ const user = userEvent.setup();+ const closeHost = vi.fn();+ render(() => <ChannelInput input={baseInput} onEscape={closeHost} />);++ await user.click(screen.getByRole('button', { name: 'Start dictation' }));+ expect(editorMocks.onEscape?.()).toBe(true);+ expect(screen.queryByRole('group', { name: 'Dictation' })).toBeNull();+ expect(closeHost).not.toHaveBeenCalled();++ editorMocks.inlineMenuOpen = true;+ expect(editorMocks.onEscape?.()).toBe(true);+ expect(closeHost).not.toHaveBeenCalled();++ editorMocks.inlineMenuOpen = false;+ expect(editorMocks.onEscape?.()).toBe(true);+ expect(closeHost).toHaveBeenCalledOnce();+ });++ it('lets Escape continue when there is no menu, dictation, or host handler', () => {+ render(() => <ChannelInput input={baseInput} />);+ expect(editorMocks.onEscape?.()).toBe(false);+ });+it('starts dictation from the collapsed channel composer', async () => {vi.mocked(isMobile).mockReturnValue(true);const user = userEvent.setup();@@ -435,6 +489,30 @@ describe('Input slots', () => {);});+ it.each([false, true])(+ 'offers one Macro entry in call chat with agents rollout %s',+ (enabled) => {+ editorMocks.agentsEnabled = enabled;+ render(() => (+ <ChannelInput+ input={baseInput}+ parent={{ type: 'call', id: 'call-1' }}+ bots={() => [+ { id: 'bot|owned', name: 'Owned agent', email: 'Owned agent' },+ { id: 'bot|team', name: 'Team agent', email: 'Team agent' },+ ]}+ />+ ));+ const users = editorMocks.mentionUsers?.() ?? [];+ expect(+ users.filter((user) => user.name === 'Macro').map((user) => user.id)+ ).toEqual([enabled ? MACRO_NEW_PRINCIPAL_ID : MACRO_AGENT_PRINCIPAL_ID]);+ expect(users.map((user) => user.id)).toEqual(+ expect.arrayContaining(['bot|owned', 'bot|team'])+ );+ }+ );+it('offers a single Macro mention, aimed by the agents rollout', () => {render(() => <ChannelInput input={baseInput} />);expect(diff --git a/apps/web/src/features/channel/Input/types.ts b/apps/web/src/features/channel/Input/types.tsindex 48f4257e1d..4a0a55c358 100644--- a/apps/web/src/features/channel/Input/types.ts+++ b/apps/web/src/features/channel/Input/types.ts@@ -101,6 +101,8 @@ export type RestoreSnapshotOptions = {};export type InputHandle = {+ /** Read the current draft, including restored persisted content. */+ snapshot: () => InputSnapshot;clear: () => void;focus: () => void;send: () => Promise<boolean>;diff --git a/apps/web/src/features/channel/Thread/ChannelThread.tsx b/apps/web/src/features/channel/Thread/ChannelThread.tsxindex 65f38459e8..d202fee24d 100644--- a/apps/web/src/features/channel/Thread/ChannelThread.tsx+++ b/apps/web/src/features/channel/Thread/ChannelThread.tsx@@ -188,6 +188,8 @@ export function ChannelThread(props: ThreadProps) {props.isReplying() || unifiedReplyBinding() !== undefined;const hasInlineReplyInput = () =>props.isReplying() && props.inputMode !== 'unified';+ const rootRailVisible = () =>+ !props.hideRail && (hasReplies() || hasInlineReplyInput());const shouldShowCollapsedIndicator = () =>!isReplyingToThread() && !props.isExpanded() && collapsedRepliesCount() > 0;const replyAction = () => props.getMessageActions?.(props.data())?.onReply;@@ -209,7 +211,11 @@ export function ChannelThread(props: ThreadProps) {createEffect(on(- [() => props.targetNavigation?.targetMessageId(), threadRowElement],+ [+ () => props.targetNavigation?.targetMessageId(),+ threadRowElement,+ () => props.targetNavigation?.requestKey?.(),+ ],([targetMessageId]) => {if (!targetMessageId || targetMessageId !== props.data().id) {targetMessageScroller.cancel();@@ -254,8 +260,9 @@ export function ChannelThread(props: ThreadProps) {replyListHandle,canScrollToTargetReply,props.isExpanded,+ () => props.targetNavigation?.requestKey?.(),],- ([targetReplyId, handle, canScroll, isExpanded]) => {+ ([targetReplyId, handle, canScroll, isExpanded, requestKey]) => {// Untracked: channel-message reconciles must not re-fire scroll.const replies =targetReplyId && canScroll && handle@@ -264,6 +271,7 @@ export function ChannelThread(props: ThreadProps) {: untrack(displayReplies): [];targetReplyNavigation.update({+ requestKey,targetReplyId,handle,canScroll,@@ -299,7 +307,7 @@ export function ChannelThread(props: ThreadProps) {messages carry no rail. */}<div class="relative"><Thread.RootRail- visible={hasReplies() || hasInlineReplyInput()}+ visible={rootRailVisible()}grouped={props.listMeta?.isGroupedWithPrevious}/><MarkMessageNotifications@@ -327,12 +335,15 @@ export function ChannelThread(props: ThreadProps) {</div><Show when={hasReplies() || hasInlineReplyInput()}><div class="relative w-full">- <Thread.RepliesBridgeRail />+ <Show when={!props.hideRail}>+ <Thread.RepliesBridgeRail />+ </Show>{/* Terminal branch: the spine's final curve into the footerbutton's left edge. Its vertical part starts exactly at thelast reply row's bottom (button h-8 + mb-2 + container pb). */}<Showwhen={+ !props.hideRail &&!props.monorail &&(shouldShowCollapsedIndicator() || shouldShowReplyButton())}@@ -360,6 +371,7 @@ export function ChannelThread(props: ThreadProps) {isThreadFocused={isThreadFocused}onSelectReply={selectReply}monorail={props.monorail}+ hideRail={props.hideRail}railContinues={hasInlineReplyInput() ||shouldShowCollapsedIndicator() ||@@ -380,7 +392,7 @@ export function ChannelThread(props: ThreadProps) {composer, so this branch turns at the avatar'scenter. Once replies exist, it instead joins thecomposer at its vertical center. */}- <Show when={!props.monorail}>+ <Show when={!props.hideRail && !props.monorail}><divclass="pointer-events-none absolute top-0 -z-1 channel-rail-left channel-rail-bottom border-thread-rail rounded-bl-[14px]"style={{diff --git a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx b/apps/web/src/features/channel/Thread/ThreadReplyList.tsxindex 680ed8fb32..cef40ae43d 100644--- a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx+++ b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx@@ -50,6 +50,7 @@ export function ThreadReplyList(props: {onSelectReply?: (replyId: string) => void;/** Keep replies on the root's rail instead of branching each one off it. */monorail?: boolean;+ hideRail?: boolean;/** An inline composer or footer continues the rail after the replies. */railContinues?: boolean;}) {@@ -98,23 +99,27 @@ export function ThreadReplyList(props: {}}class="relative">- <Show- when={props.monorail}- fallback={- <ThreadReplyRail- grouped={listMetaByReplyId()[id].isGroupedWithPrevious}- terminal={- !props.railContinues &&- listMetaByReplyId()[id].index >= lastAvatarIndex()- }- />- }- >- <Show when={listMetaByReplyId()[id].index <= lastAvatarIndex()}>- <ThreadReplyMonorail- grouped={listMetaByReplyId()[id].isGroupedWithPrevious}- terminal={listMetaByReplyId()[id].index === lastAvatarIndex()}- />+ <Show when={!props.hideRail}>+ <Show+ when={props.monorail}+ fallback={+ <ThreadReplyRail+ grouped={listMetaByReplyId()[id].isGroupedWithPrevious}+ terminal={+ !props.railContinues &&+ listMetaByReplyId()[id].index >= lastAvatarIndex()+ }+ />+ }+ >+ <Show when={listMetaByReplyId()[id].index <= lastAvatarIndex()}>+ <ThreadReplyMonorail+ grouped={listMetaByReplyId()[id].isGroupedWithPrevious}+ terminal={+ listMetaByReplyId()[id].index === lastAvatarIndex()+ }+ />+ </Show></Show></Show><MarkMessageNotifications messageId={id} parent={props.parent}>diff --git a/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.ts b/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.tsindex 94728b2a9d..eebb9d5920 100644--- a/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.ts+++ b/apps/web/src/features/channel/Thread/create-target-reply-navigation-controller.ts@@ -3,6 +3,7 @@ import type { ThreadReplyListHandle } from './ThreadReplyList';type Reply = { id: string };type TargetReplyNavigation = {+ requestKey?: string | number;targetReplyId?: string;handle?: ThreadReplyListHandle;canScroll: boolean;@@ -13,6 +14,8 @@ type TargetReplyNavigation = {/** Coordinates one-shot reply navigation across async target changes. */export function createTargetReplyNavigationController() {+ let currentRequestKey: string | number | undefined;+ let requestGeneration = 0;let lastScrolledReplyId: string | undefined;let inFlightReplyId: string | undefined;let inFlightHandle: ThreadReplyListHandle | undefined;@@ -28,6 +31,7 @@ export function createTargetReplyNavigationController() {};const update = ({+ requestKey,targetReplyId,handle,canScroll,@@ -35,6 +39,12 @@ export function createTargetReplyNavigationController() {getCurrentTargetReplyId,onScrolled,}: TargetReplyNavigation) => {+ if (currentRequestKey !== requestKey) {+ cancelInFlight();+ lastScrolledReplyId = undefined;+ currentRequestKey = requestKey;+ requestGeneration += 1;+ }if (inFlightReplyId && inFlightReplyId !== targetReplyId) {cancelInFlight();}@@ -54,7 +64,9 @@ export function createTargetReplyNavigationController() {if (inFlightHandle && inFlightHandle !== handle) cancelInFlight();inFlightReplyId = targetReplyId;inFlightHandle = handle;+ const generation = requestGeneration;const started = handle.scrollToIndex(index, () => {+ if (generation !== requestGeneration) return;if (inFlightReplyId === targetReplyId && inFlightHandle === handle) {clearInFlight();}diff --git a/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.ts b/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.tsindex 31a5c420b4..7f4341b7d0 100644--- a/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.ts+++ b/apps/web/src/features/channel/Thread/tests/create-target-reply-navigation-controller.test.ts@@ -15,6 +15,76 @@ function createHandle() {}describe('createTargetReplyNavigationController', () => {+ it('revisits a settled reply only for a new navigation request', () => {+ const controller = createTargetReplyNavigationController();+ const { handle, settle } = createHandle();+ const options = {+ targetReplyId: 'reply',+ handle,+ canScroll: true,+ replies: [{ id: 'reply' }],+ getCurrentTargetReplyId: () => 'reply',+ };++ controller.update({ ...options, requestKey: 'first' });+ settle();+ controller.update({ ...options, requestKey: 'first' });+ expect(handle.scrollToIndex).toHaveBeenCalledTimes(1);+ controller.update({ ...options, requestKey: 'again' });+ expect(handle.scrollToIndex).toHaveBeenCalledTimes(2);+ });++ it('ignores a cancelled request settling after the same reply is requested again', () => {+ const controller = createTargetReplyNavigationController();+ const { handle, settle } = createHandle();+ const onScrolled = vi.fn();+ const options = {+ targetReplyId: 'reply',+ handle,+ canScroll: true,+ replies: [{ id: 'reply' }],+ getCurrentTargetReplyId: () => 'reply',+ onScrolled,+ };+ controller.update({ ...options, requestKey: 1 });+ const staleSettlement = vi.mocked(handle.scrollToIndex).mock.calls[0][1];+ controller.update({ ...options, requestKey: 2 });+ expect(handle.cancelScroll).toHaveBeenCalledOnce();++ staleSettlement();+ expect(onScrolled).not.toHaveBeenCalled();+ settle();+ expect(onScrolled).toHaveBeenCalledExactlyOnceWith('reply');+ });++ it('invalidates an earlier request even when its key is reused after clearing', () => {+ const controller = createTargetReplyNavigationController();+ const { handle, settle } = createHandle();+ const onScrolled = vi.fn();+ const options = {+ targetReplyId: 'reply',+ requestKey: 1,+ handle,+ canScroll: true,+ replies: [{ id: 'reply' }],+ getCurrentTargetReplyId: () => 'reply',+ onScrolled,+ };+ controller.update(options);+ const staleSettlement = vi.mocked(handle.scrollToIndex).mock.calls[0][1];+ controller.update({+ ...options,+ targetReplyId: undefined,+ requestKey: undefined,+ });+ controller.update(options);++ staleSettlement();+ expect(onScrolled).not.toHaveBeenCalled();+ settle();+ expect(onScrolled).toHaveBeenCalledExactlyOnceWith('reply');+ });+it('cancels target A before returning while target B is unavailable', () => {const controller = createTargetReplyNavigationController();const first = createHandle();diff --git a/apps/web/src/features/channel/Thread/tests/message-actions.test.ts b/apps/web/src/features/channel/Thread/tests/message-actions.test.tsindex f97c686e1d..f5d2a627fc 100644--- a/apps/web/src/features/channel/Thread/tests/message-actions.test.ts+++ b/apps/web/src/features/channel/Thread/tests/message-actions.test.ts@@ -103,6 +103,38 @@ describe('message-actions helpers', () => {);});+ it.each([undefined, 'call-1'])(+ 'quotes a call message with thread_id %s in its canonical thread',+ (threadId) => {+ const value = buildReplyTargetValue({+ parent: { type: 'call', id: 'call-1' },+ message: {+ ...threadReply,+ id: threadId ? 'reply-1' : 'call-1',+ thread_id: threadId,+ },+ existingValue: 'draft',+ });+ expect(value).toContain('"parent":{"type":"call","id":"call-1"}');+ expect(value).toContain('"targetThreadId":"call-1"');+ expect(value).toContain(+ '"targetMessageId":"' + (threadId ? 'reply-1' : 'call-1') + '"'+ );+ expect(value).toMatch(/\n\ndraft$/);+ expect(+ buildReplyTargetValue({+ parent: { type: 'call', id: 'call-1' },+ message: {+ ...threadReply,+ id: threadId ? 'reply-1' : 'call-1',+ thread_id: threadId,+ },+ existingValue: value,+ })+ ).toBe(value);+ }+ );+it('uses browser-selected text for the reply preview', () => {expect(buildReplyTargetValue({diff --git a/apps/web/src/features/channel/Thread/types.ts b/apps/web/src/features/channel/Thread/types.tsindex c5596e5ed4..416317aeb2 100644--- a/apps/web/src/features/channel/Thread/types.ts+++ b/apps/web/src/features/channel/Thread/types.ts@@ -37,6 +37,8 @@ export type MessageEditState = {/** Reactive contract for positioning and releasing a channel navigation target. */export type ThreadTargetNavigation = {+ /** A new request can revisit the same message without remounting the thread. */+ requestKey?: Accessor<string | number | undefined>;targetThreadId: Accessor<string | undefined>;targetMessageId: Accessor<string | undefined>;targetReplyId: Accessor<string | undefined>;@@ -75,4 +77,6 @@ export type ThreadProps = {* the root on one straight rail instead of indenting and branching them.*/monorail?: boolean;+ /** Flat chat surfaces do not draw thread connector rails. */+ hideRail?: boolean;} & ThreadState;diff --git a/apps/web/src/features/channel/Thread/utils/message-actions.ts b/apps/web/src/features/channel/Thread/utils/message-actions.tsindex 42adcfee53..2d7b358902 100644--- a/apps/web/src/features/channel/Thread/utils/message-actions.ts+++ b/apps/web/src/features/channel/Thread/utils/message-actions.ts@@ -4,6 +4,7 @@ import {buildReplyTargetMarkdown,isReplyTargetData,markdownToPlainText,+ type ReplyTargetParent,stripLeadingReplyTargetMarkdown,} from '@macro-inc/lexical-core';import type { MessageData } from '../../Message';@@ -69,14 +70,24 @@ function stripMagicChipMarkdown(markdown: string): string {return markdown.replace(/<m-magic-chip>.*?<\/m-magic-chip>/gs, '');}-export function buildReplyTargetValue(input: {- channelId: string;- message: Pick<MessageData, 'id' | 'content' | 'sender_id' | 'thread_id'>;- selectedText?: string;- renderedText?: string;- existingValue?: string;-}): string {- if (!input.message.thread_id) return input.existingValue ?? '';+export function buildReplyTargetValue(+ input: {+ message: Pick<MessageData, 'id' | 'content' | 'sender_id' | 'thread_id'>;+ selectedText?: string;+ renderedText?: string;+ existingValue?: string;+ } & (+ | { channelId: string; parent?: never }+ | { parent: ReplyTargetParent; channelId?: never }+ )+): string {+ const parent: ReplyTargetParent = input.parent ?? {+ type: 'channel',+ id: input.channelId,+ };+ if (parent.type === 'channel' && !input.message.thread_id) {+ return input.existingValue ?? '';+ }for (const match of (input.existingValue ?? '').matchAll(/<m-reply-target>(.*?)<\/m-reply-target>/gs@@ -103,9 +114,9 @@ export function buildReplyTargetValue(input: {input.selectedText || input.renderedText || messageText);const replyTarget = buildReplyTargetMarkdown({- parent: { type: 'channel', id: input.channelId },+ parent,targetMessageId: input.message.id,- targetThreadId: input.message.thread_id,+ targetThreadId: input.message.thread_id ?? input.message.id,displayText,senderId: input.message.sender_id,});diff --git a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts b/apps/web/src/features/channel/use-channel-bot-mention-users.test.tsindex f3711314e1..e25076176f 100644--- a/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts+++ b/apps/web/src/features/channel/use-channel-bot-mention-users.test.ts@@ -211,4 +211,14 @@ describe('availableBotMentionUsers', () => {).toEqual(['bot|doc-only']);});++ it('offers owned and team agents in calls regardless of channel scope', () => {+ const owned = agent('owned-agent', 'Owned agent', 'selected');+ const team = agent('team-agent', 'Team agent', 'all');+ expect(+ availableBotMentionUsers([], [owned, team], true, 'call').map(+ (user) => user.id+ )+ ).toEqual(['bot|owned-agent', 'bot|team-agent']);+ });});diff --git a/apps/web/src/features/channel/use-message-participants.test.ts b/apps/web/src/features/channel/use-message-participants.test.tsindex 9437df8928..4a403043b8 100644--- a/apps/web/src/features/channel/use-message-participants.test.ts+++ b/apps/web/src/features/channel/use-message-participants.test.ts@@ -53,6 +53,9 @@ it('offers the owning team on CRM records and contacts on documents', () => {setParent({ type: 'document', id: 'document' });expect(ids()).toEqual(['macro|[email protected]']);+ setParent({ type: 'call', id: 'call' });+ expect(ids()).toEqual(['macro|[email protected]']);+setParent({ type: 'channel', id: 'channel' });expect(ids()).toEqual(['macro|[email protected]']);dispose();diff --git a/apps/web/src/features/channel/use-message-participants.ts b/apps/web/src/features/channel/use-message-participants.tsindex a4a47b1ea2..1bd16bf368 100644--- a/apps/web/src/features/channel/use-message-participants.ts+++ b/apps/web/src/features/channel/use-message-participants.ts@@ -10,7 +10,7 @@ import { useChannelParticipants } from './use-channel-participants';/*** The people a composer on `parent` offers in the `@`-mention typeahead: a- * channel's participants; on a document or project, the workspace contacts the+ * channel's participants; on a document, project, or call, the workspace contacts the* legacy comment input suggested; on a CRM record, the team that owns it, the only* people who can read its discussion. Mirrors `useMessageBotMentionUsers` so* that every composer on a parent — root, reply, and edit — suggests the same@@ -39,7 +39,7 @@ export function useMessageParticipants(return createMemo(() =>match(parent().type).with('channel', () => channelParticipants.users())- .with(P.union('document', 'initiative'), () => contacts())+ .with(P.union('document', 'initiative', 'call'), () => contacts()).with(P.union('crm_company', 'crm_contact'), () => teamMembers()).exhaustive());diff --git a/apps/web/src/features/drive-view/route.tsx b/apps/web/src/features/drive-view/route.tsxindex d88219cdfb..aad91eb56e 100644--- a/apps/web/src/features/drive-view/route.tsx+++ b/apps/web/src/features/drive-view/route.tsx@@ -54,6 +54,7 @@ function DriveCallRouteView() {<DriveCallDetailcallId={params.callId}transcriptId={search.transcriptId}+ messageId={search.messageId}seek={search.seek}/>);@@ -176,7 +177,7 @@ export const driveSplitRoute = defineRoute({typeof routeParams<{ callId?: string }>(entry.location.route).callId ==='string')- return [CALL_URL_PARAMS.transcriptId];+ return [CALL_URL_PARAMS.transcriptId, CALL_URL_PARAMS.messageId];return [];},children: [diff --git a/apps/web/src/features/drive-view/views/DriveCallDetail.tsx b/apps/web/src/features/drive-view/views/DriveCallDetail.tsxindex e0087eba93..fcaae87bf7 100644--- a/apps/web/src/features/drive-view/views/DriveCallDetail.tsx+++ b/apps/web/src/features/drive-view/views/DriveCallDetail.tsx@@ -48,6 +48,7 @@ function DriveCallBreadcrumb(props: { callId: string; name: string }) {export function DriveCallDetail(props: {callId: string;transcriptId?: string;+ messageId?: string;seek?: string;}) {const detail = useCallDetail(() => props.callId);@@ -84,6 +85,7 @@ export function DriveCallDetail(props: {query={detail.query}data={detail.data()}transcriptId={props.transcriptId}+ messageId={props.messageId}seek={props.seek}/></div>diff --git a/apps/web/src/features/meetings/meeting-route.tsx b/apps/web/src/features/meetings/meeting-route.tsxindex 88d39a4264..5f855b27cc 100644--- a/apps/web/src/features/meetings/meeting-route.tsx+++ b/apps/web/src/features/meetings/meeting-route.tsx@@ -132,6 +132,7 @@ export function MeetingRouteContent(props: {<CallOverlayonLeave={onLeave}localName={name()}+ showChat={authenticated() === true}showTeamSharing={canShareWithTeam()}sharedWithTeam={record.isSuccess ? record.data.shareWithTeam : undefineddiff --git a/apps/web/src/features/next-soup/search-navigation.ts b/apps/web/src/features/next-soup/search-navigation.tsindex 432659f1a6..2b7a732778 100644--- a/apps/web/src/features/next-soup/search-navigation.ts+++ b/apps/web/src/features/next-soup/search-navigation.ts@@ -99,9 +99,10 @@ export function searchLocationTarget(namespace: callDetailSearch.namespace,params: callDetailSearchCodec.serialize({transcriptId: target.transcriptId,+ messageId: '',seek,})!,- fields: ['transcriptId', 'seek'],+ fields: ['transcriptId', 'messageId', 'seek'],})).exhaustive();}diff --git a/apps/web/src/lib/core/comments/discussion/DiscussionInput.tsx b/apps/web/src/lib/core/comments/discussion/DiscussionInput.tsxindex 1e59fa7752..13e79a0770 100644--- a/apps/web/src/lib/core/comments/discussion/DiscussionInput.tsx+++ b/apps/web/src/lib/core/comments/discussion/DiscussionInput.tsx@@ -221,6 +221,7 @@ export function DiscussionInput(props: DiscussionInputProps) {};props.onReady?.({+ snapshot: createSnapshot,clear: () => {// On iOS, blur before clearing so dictation finalizes and discards its bufferconst root = markdownEditor.lexical.getRootElement();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.test.tsxnew file mode 100644index 0000000000..6643d6f62e--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.test.tsx@@ -0,0 +1,177 @@+import { MessageReferenceNavigation } from '@core/messages/message-reference-navigation';+import type {+ ReplyTargetDecoratorProps,+ ReplyTargetParent,+} from '@macro-inc/lexical-core';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, expect, it, vi } from 'vitest';+import { ReplyTarget } from './ReplyTarget';++const mocks = vi.hoisted(() => ({ open: vi.fn(), openWithSplit: vi.fn() }));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: mocks.openWithSplit }),+}));+vi.mock('@core/block', () => ({+ useMaybeBlockId: () => undefined,+ useMaybeBlockName: () => undefined,+}));+vi.mock('@core/user', () => ({+ getDisplayName: () => 'Eric',+ tryMacroId: (id: string) => id,+}));+vi.mock('@core/util/openInNewSplit', () => ({+ openInNewSplitForMention: () => true,+}));+vi.mock('@queries/bots/bots', () => ({+ useBotsQuery: () => ({ isSuccess: true, data: [] }),+}));+vi.mock('@queries/channel/channel-bots', () => ({+ useChannelBotsQuery: () => ({ isSuccess: true, data: [] }),+}));+vi.mock('@queries/messages/message-sender', () => ({+ getBotDisplayName: () => undefined,+}));+vi.mock('@queries/storage/document-metadata', () => ({+ useDocumentMetadataQuery: () => ({+ isSuccess: true,+ data: { fileType: 'md' },+ }),+}));+vi.mock('../core/BlockLink', () => ({ openDocument: mocks.open }));+vi.mock('./QuoteReplyPreview', () => ({+ QuoteReplyPreview: (props: {+ onClick: (event: MouseEvent) => void;+ disabled?: boolean;+ }) => (+ <button disabled={props.disabled} onClick={props.onClick}>+ Quoted message+ </button>+ ),+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it.each<{+ parentType: ReplyTargetParent['type'];+ type: string;+ id: string;+ params: Record<string, string>;+}>([+ {+ parentType: 'crm_company',+ type: 'crm_company',+ id: 'parent-id',+ params: { comment_id: 'message-id' },+ },+ {+ parentType: 'crm_contact',+ type: 'crm_contact',+ id: 'parent-id',+ params: { comment_id: 'message-id' },+ },+ {+ parentType: 'initiative',+ type: 'component',+ id: 'initiative-view~parent-id~overview~message-id',+ params: {},+ },+ {+ parentType: 'document',+ type: 'md',+ id: 'parent-id',+ params: { comment_id: 'message-id' },+ },+ {+ parentType: 'channel',+ type: 'channel',+ id: 'parent-id',+ params: { channel_message_id: 'message-id', channel_thread_id: 'root-id' },+ },+])(+ 'opens a quoted $parentType message at its durable target',+ ({ parentType, type, id, params }) => {+ const props: ReplyTargetDecoratorProps = {+ parent: { type: parentType, id: 'parent-id' },+ targetMessageId: 'message-id',+ targetThreadId: 'root-id',+ displayText: 'Quoted text',+ senderId: 'macro|[email protected]',+ key: 'node-key',+ theme: {},+ };+ render(() => <ReplyTarget {...props} />);+ const quote = screen.getByRole('button', { name: 'Quoted message' });+ expect(quote.hasAttribute('disabled')).toBe(false);+ fireEvent.click(quote);+ expect(mocks.open).toHaveBeenCalledWith(type, id, params, true);+ }+);++it('reissues call quote navigation with a fresh route request each time', () => {+ render(() => (+ <ReplyTarget+ parent={{ type: 'call', id: 'call-id' }}+ targetMessageId="message-id"+ targetThreadId="call-id"+ senderId="user-id"+ displayText="Quoted text"+ key="node-key"+ theme={{}}+ />+ ));+ const button = screen.getByRole('button', { name: 'Quoted message' });+ fireEvent.click(button);+ fireEvent.click(button);++ expect(mocks.openWithSplit).toHaveBeenCalledTimes(2);+ const first = mocks.openWithSplit.mock.calls[0];+ const second = mocks.openWithSplit.mock.calls[1];+ expect(first).toEqual([+ { type: 'call', id: 'call-id' },+ {+ preferNewSplit: true,+ search: {+ 'call-detail': {+ messageId: ['message-id'],+ seek: [expect.any(String)],+ },+ },+ },+ ]);+ expect(second[1].search['call-detail'].seek).not.toEqual(+ first[1].search['call-detail'].seek+ );+ expect(mocks.open).not.toHaveBeenCalled();+});++it('lets the active chat handle a quote locally, preserving Shift for opening a split', () => {+ const navigate = vi.fn(() => true);+ render(() => (+ <MessageReferenceNavigation.Provider value={navigate}>+ <ReplyTarget+ parent={{ type: 'call', id: 'call-id' }}+ targetMessageId="message-id"+ targetThreadId="call-id"+ senderId="user-id"+ displayText="Quoted text"+ key="node-key"+ theme={{}}+ />+ </MessageReferenceNavigation.Provider>+ ));+ const button = screen.getByRole('button', { name: 'Quoted message' });+ fireEvent.click(button);+ expect(navigate).toHaveBeenCalledWith(+ expect.objectContaining({ targetMessageId: 'message-id' })+ );+ expect(mocks.open).not.toHaveBeenCalled();+ expect(mocks.openWithSplit).not.toHaveBeenCalled();+ fireEvent.click(button, { shiftKey: true });+ expect(mocks.openWithSplit).toHaveBeenCalledWith(+ { type: 'call', id: 'call-id' },+ expect.objectContaining({ preferNewSplit: true })+ );+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsxindex d26e0a63b3..e24c4e0f6f 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsx@@ -1,5 +1,13 @@+import { projectRouteId } from '@app/features/projects/core/route';+import {+ callDetailSearch,+ callDetailSearchCodec,+} from '@block-call/call-route';+import { URL_PARAMS as CALL_PARAMS } from '@block-call/constants';import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';+import { useSplitLayout } from '@components/app/split-layout/layout';import { useMaybeBlockId, useMaybeBlockName } from '@core/block';+import { MessageReferenceNavigation } from '@core/messages/message-reference-navigation';import { getDisplayName, tryMacroId } from '@core/user';import { openInNewSplitForMention } from '@core/util/openInNewSplit';import type { ReplyTargetDecoratorProps } from '@macro-inc/lexical-core';@@ -8,11 +16,14 @@ import { useChannelBotsQuery } from '@queries/channel/channel-bots';import { getBotDisplayName } from '@queries/messages/message-sender';import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';import { createCallback } from '@solid-primitives/rootless';+import { useContext } from 'solid-js';+import { match } from 'ts-pattern';import { openDocument } from '../core/BlockLink';import { QuoteReplyPreview } from './QuoteReplyPreview';-/** Single-line channel reply reference rendered by a ReplyTargetNode. */+/** Single-line message reply reference rendered by a ReplyTargetNode. */export function ReplyTarget(props: ReplyTargetDecoratorProps) {+ const navigateReference = useContext(MessageReferenceNavigation);const currentBlockId = useMaybeBlockId();const currentBlockName = useMaybeBlockName();const channelBots = useChannelBotsQuery(() =>@@ -37,33 +48,84 @@ export function ReplyTarget(props: ReplyTargetDecoratorProps) {getDisplayName(tryMacroId(props.senderId), {}) ||props.senderId;- const targetReady = () =>- props.parent.type === 'channel' ||- (document.isSuccess && !!document.data.fileType);+ const target = ():+ | {+ type: string;+ id: string;+ params: Record<string, string>;+ }+ | undefined =>+ match(props.parent.type)+ .with('channel', () => ({+ type: 'channel',+ id: props.parent.id,+ params: {+ [CHANNEL_PARAMS.message]: props.targetMessageId,+ [CHANNEL_PARAMS.thread]: props.targetThreadId,+ },+ }))+ .with('call', () => ({+ type: 'call',+ id: props.parent.id,+ params: { [CALL_PARAMS.messageId]: props.targetMessageId },+ }))+ .with('initiative', () => ({+ type: 'component',+ id: projectRouteId({+ id: props.parent.id,+ section: 'overview',+ discussionId: props.targetMessageId,+ }),+ params: {},+ }))+ .with('crm_company', 'crm_contact', (type) => ({+ type,+ id: props.parent.id,+ params: { comment_id: props.targetMessageId },+ }))+ .with('document', () =>+ document.isSuccess && document.data.fileType+ ? {+ type: document.data.fileType,+ id: props.parent.id,+ params: { comment_id: props.targetMessageId },+ }+ : undefined+ )+ .exhaustive();const openTarget = createCallback((event: MouseEvent) => {event.preventDefault();event.stopPropagation();- const channel = props.parent.type === 'channel';- const fileType = channel- ? 'channel'- : document.isSuccess- ? document.data.fileType- : undefined;- if (!fileType) return;+ if (!event.shiftKey && navigateReference?.(props)) return;+ const destination = target();+ if (!destination) return;+ const preferNewSplit = openInNewSplitForMention(+ event.shiftKey,+ currentBlockName !== destination.type || currentBlockId !== destination.id+ );+ if (props.parent.type === 'call') {+ // Route search delivers a fresh request even when this call is already open.+ useSplitLayout().openWithSplit(+ { type: 'call', id: destination.id },+ {+ preferNewSplit,+ search: {+ [callDetailSearch.namespace]: callDetailSearchCodec.serialize({+ ...callDetailSearch.defaults,+ messageId: props.targetMessageId,+ seek: crypto.randomUUID(),+ }),+ },+ }+ );+ return;+ }openDocument(- fileType,- props.parent.id,- channel- ? {- [CHANNEL_PARAMS.message]: props.targetMessageId,- [CHANNEL_PARAMS.thread]: props.targetThreadId,- }- : { comment_id: props.targetMessageId },- openInNewSplitForMention(- event.shiftKey,- currentBlockName !== fileType || currentBlockId !== props.parent.id- )+ destination.type,+ destination.id,+ destination.params,+ preferNewSplit);});@@ -72,7 +134,7 @@ export function ReplyTarget(props: ReplyTargetDecoratorProps) {label={senderName()}text={props.displayText}ariaLabel={`Replying to ${senderName()}: ${props.displayText}`}- disabled={!targetReady()}+ disabled={!target()}onClick={openTarget}buttonAttrs={{'data-reply-target-target-message-id': props.targetMessageId,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.tsindex a5bfc8becb..e083a621a8 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts@@ -25,5 +25,6 @@* Version 4.3 - Sep 2026. ReplyTargetNode references a message parent (channel or document) instead of a channel id.* Version 4.4 - Sep 2026. Expanded agent session mentions are block decorators with node selection.* Version 5.0 - Sep 2026. Added CursorSystemNotificationNode (Cursor `<system_notification>` event cards).+ * Version 5.1 - Oct 2026. ReplyTargetNode accepts call, initiative, and CRM message parents.*/-export const MARKDOWN_VERSION_COUNTER = 5.0;+export const MARKDOWN_VERSION_COUNTER = 5.1;diff --git a/apps/web/src/lib/core/messages/MessageThread.test.tsx b/apps/web/src/lib/core/messages/MessageThread.test.tsxindex e5e8e1d34f..a7f9de6367 100644--- a/apps/web/src/lib/core/messages/MessageThread.test.tsx+++ b/apps/web/src/lib/core/messages/MessageThread.test.tsx@@ -221,6 +221,47 @@ describe('document discussion controls', () => {});});+it('offers a durable copy link without write actions for saved call chat', () => {+ const callMessage: MessageListItem = {+ ...message,+ parent: { type: 'call', id: 'call-id' },+ };+ const link = 'https://macro.test/app/call/call-id?call_message_id=root';+ const view = render(() => (+ <MessageThread data={callMessage} canWrite={false} buildLink={() => link} />+ ));+ fireEvent.click(view.getByRole('button', { name: 'Long press message' }));+ expect(view.queryByRole('button', { name: 'Reply' })).toBeNull();+ expect(view.queryByRole('button', { name: 'Edit' })).toBeNull();+ expect(view.queryByRole('button', { name: 'Delete' })).toBeNull();+ fireEvent.click(view.getByRole('button', { name: 'Copy link' }));+ expect(mocks.clipboard).toHaveBeenCalledWith(link);+});++it.each(['user', 'another-participant'])(+ 'offers external call reply actions for messages from %s without opening an inline composer',+ (senderId) => {+ const onReply = vi.fn();+ const callMessage = {+ ...message,+ parent: { type: 'call' as const, id: 'call-id' },+ sender_id: senderId,+ };+ const view = render(() => (+ <MessageThread+ data={callMessage}+ canWrite+ hideReplyInput+ onReply={onReply}+ />+ ));+ openActions(view);+ fireEvent.click(view.getByRole('button', { name: 'Reply' }));+ expect(onReply).toHaveBeenCalledWith({ message: callMessage });+ expect(view.queryByRole('textbox', { name: 'Reply composer' })).toBeNull();+ }+);+describe('linked message highlight', () => {it('releases the highlight when the linked message is clicked, keeping the thread expanded', () => {const [targetId, setTargetId] = createSignal<string | null>('root');@@ -292,3 +333,19 @@ it('closes an active project reply composer and editor when comment access is loexpect(view.queryByRole('textbox', { name: 'Reply composer' })).toBeNull();expect(view.queryByText('Editor enabled')).toBeNull();});++it('does not offer deletion of another sender’s bot message outside a channel', () => {+ const view = render(() => (+ <MessageThread+ data={{+ ...message,+ parent: { type: 'call', id: 'call-id' },+ sender_id: 'bot|macro',+ }}+ canWrite+ />+ ));+ openActions(view);+ expect(view.queryByRole('button', { name: 'Delete' })).toBeNull();+ expect(view.getByRole('button', { name: 'Reply' })).toBeTruthy();+});diff --git a/apps/web/src/lib/core/messages/MessageThread.tsx b/apps/web/src/lib/core/messages/MessageThread.tsxindex 7a918e057a..3994ab0a72 100644--- a/apps/web/src/lib/core/messages/MessageThread.tsx+++ b/apps/web/src/lib/core/messages/MessageThread.tsx@@ -23,7 +23,7 @@ import type {MessageThread as ThreadData,} from '@service-storage/messages';import { createSignal, Show } from 'solid-js';-import type { MessageData } from './types';+import type { MessageActionHandler, MessageData } from './types';export function threadListItem(thread: ThreadData): MessageListItem {return {@@ -44,10 +44,15 @@ type ThreadOptions = {canModerate?: boolean;buildLink?: (message: MessageData) => string;targetId?: string | null;+ /** Change this key to navigate to the same target again. */+ targetRequestKey?: string | number;/** Releases the highlight on `targetId`; called when the linked message is clicked. */onClearTarget?: () => void;expanded?: boolean;hideReplyInput?: boolean;+ /** Reply through a composer owned by the enclosing surface. */+ onReply?: MessageActionHandler;+ hideRail?: boolean;onEditingChange?: (id: string, editing: boolean) => void;monorail?: boolean;};@@ -89,7 +94,8 @@ export function MessageThread(editor.start(message);props.onEditingChange?.(message.id, true);},- onReply: () => {+ onReply: (context) => {+ if (props.onReply) return props.onReply(context);setExpanded(true);setReplying(true);focus.request();@@ -108,14 +114,16 @@ export function MessageThread(parent={() => props.data.parent}getMessageActions={(message) => {const value = actions(message);- return props.hideReplyInput+ return props.hideReplyInput && !props.onReply? { ...value, onReply: undefined }: value;}}messageEditor={props.canWrite ? editor : undefined}isExpanded={() => expanded() || !!props.targetId}setIsExpanded={setExpanded}- isReplying={() => props.canWrite && replying()}+ isReplying={() =>+ props.canWrite && !props.hideReplyInput && replying()+ }setIsReplying={setReplying}replyInputState={draft}setReplyInputState={setDraft}@@ -124,9 +132,11 @@ export function MessageThread(replyInputFocusRequest={focus}isFindBarOpen={() => false}monorail={props.monorail}+ hideRail={props.hideRail}messageListScopeId={scopeId}selectedMessageId={() => (props.targetId ? props.data.id : undefined)}targetNavigation={{+ requestKey: () => props.targetRequestKey,targetThreadId: () => (props.targetId ? props.data.id : undefined),targetMessageId: () => props.targetId ?? undefined,targetReplyId: () =>diff --git a/apps/web/src/lib/core/messages/message-reference-navigation.ts b/apps/web/src/lib/core/messages/message-reference-navigation.tsnew file mode 100644index 0000000000..625622e2f7--- /dev/null+++ b/apps/web/src/lib/core/messages/message-reference-navigation.ts@@ -0,0 +1,6 @@+import type { ReplyTargetData } from '@macro-inc/lexical-core';+import { createContext } from 'solid-js';++/** A message surface can handle a reference locally before durable route navigation. */+export const MessageReferenceNavigation =+ createContext<(target: ReplyTargetData) => boolean>();diff --git a/apps/web/src/lib/queries/messages/mutations.ts b/apps/web/src/lib/queries/messages/mutations.tsindex e8b43f7baa..dc320abc56 100644--- a/apps/web/src/lib/queries/messages/mutations.ts+++ b/apps/web/src/lib/queries/messages/mutations.ts@@ -256,14 +256,19 @@ export function optimisticDeleteMessage(target,};- if (target.kind === 'top_level' && vars.parent.type !== 'channel') {+ if (+ target.kind === 'top_level' &&+ vars.parent.type !== 'channel' &&+ vars.parent.type !== 'call'+ ) {context.threadState = getCachedThreadState(vars.parent, target.messageId);}if (target.kind === 'top_level' &&- vars.parent.type === 'channel' &&- topLevelMessageHasReplies(vars.parent, target.messageId)+ (vars.parent.type === 'call' ||+ (vars.parent.type === 'channel' &&+ topLevelMessageHasReplies(vars.parent, target.messageId)))) {context.previousDeletedAt =getTopLevelMessageDeletedAt(vars.parent, target.messageId) ?? null;@@ -458,12 +463,18 @@ export function useSendMessageMutation(return { insert, updatedAt };},onSuccess(data, variables, context) {- const threadId = variables.message.thread_id ?? undefined;+ const threadId = data.thread_id ?? undefined;// A server predating client-minted ids ignores `id` and mints its// own. Rebuild the optimistic row under the server id so it keeps// its thread state (including the anchor) and never holds a dead id;// `applyMessage` below then settles it on the server's fields.- if (data.id !== variables.optimisticId && context?.insert) {+ // A concurrent first call message may become a reply to the root+ // another participant just created, while retaining its client id.+ if (+ (data.id !== variables.optimisticId ||+ threadId !== (variables.message.thread_id ?? undefined)) &&+ context?.insert+ ) {rollbackInsertChannelMessage(variables.parent, context.insert);optimisticInsertMessage({parent: variables.parent,@@ -471,6 +482,7 @@ export function useSendMessageMutation(senderId: variables.senderId,optimisticAttachments: variables.optimisticAttachments,...variables.message,+ thread_id: threadId,});}@@ -494,7 +506,7 @@ export function useSendMessageMutation(attachmentsLength: variables.message.attachments?.length ?? 0,isThreadReply: threadId !== undefined,});- applyMessage(data, 'edited');+ applyMessage(data, 'posted');},onError(error, vars, context) {console.error('failed to send message', error);@@ -504,13 +516,15 @@ export function useSendMessageMutation(}context?.updatedAt?.rollback();},- onSettled: (_data, _error, variables) => {+ onSettled: (data, _error, variables) => {softInvalidateTargetCaches(variables.parent,resolveMessageTarget({parent: variables.parent,- messageId: variables.optimisticId,- threadId: variables.message.thread_id ?? undefined,+ messageId: data?.id ?? variables.optimisticId,+ threadId:+ (data ? data.thread_id : variables.message.thread_id) ??+ undefined,}));},diff --git a/apps/web/src/lib/queries/messages/sync.ts b/apps/web/src/lib/queries/messages/sync.tsindex 7539d5092f..34112b38a9 100644--- a/apps/web/src/lib/queries/messages/sync.ts+++ b/apps/web/src/lib/queries/messages/sync.ts@@ -99,6 +99,30 @@ export function applyMessage(patchTargetMessage(parent, target, normalized);}softInvalidateTargetCaches(parent, target);+ // Calls have one thread and no mounted timeline to seed its first fetch.+ // A view may still be showing the empty response when the first post arrives.+ if (+ parent.type === 'call' &&+ change === 'posted' &&+ !queryClient.getQueryData(getThreadRepliesQueryKey(parent, parent.id))+ ) {+ void refreshUnloadedCallThread(parent);+ }+}++async function refreshUnloadedCallThread(parent: MessageParent) {+ const queryKey = getThreadRepliesQueryKey(parent, parent.id);+ const inFlight = queryClient+ .getQueryCache()+ .find({ queryKey, exact: true })?.promise;+ if (inFlight) {+ try {+ await inFlight;+ } catch {+ // An empty call may return 404; retry after the committed first message.+ }+ }+ await queryClient.invalidateQueries({ queryKey, exact: true });}/**@@ -114,7 +138,8 @@ export function applyRootDeletion(cached?: MessageThread['state']) {const parent = message.parent;- if (parent.type === 'channel' || message.thread_id) return;+ if (parent.type === 'channel' || parent.type === 'call' || message.thread_id)+ return;const state = cached ?? getCachedThreadState(parent, message.id);if (!state) {void queryClient.invalidateQueries({@@ -185,11 +210,23 @@ function refetchTimelineAwaitingFirstPage(parent: MessageParent): boolean {const refetch = () =>queryClient.invalidateQueries({ queryKey, exact: true });const inFlight = query.promise;- if (inFlight) void inFlight.catch(() => {}).finally(refetch);+ if (inFlight) void refetchAfterPendingPage(inFlight, refetch);else void refetch();return true;}+async function refetchAfterPendingPage(+ pending: Promise<unknown>,+ refetch: () => Promise<void>+) {+ try {+ await pending;+ } catch {+ // The new message still needs a fetch if the initial page request failed.+ }+ await refetch();+}+/*** Live discussion roots need authoritative thread state. Preserve derived senders* when replacing cached roots so agent comments keep their names after live updates.diff --git a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx b/apps/web/src/lib/queries/messages/tests/mutations.test.tsxindex 9f3993f91c..ee7a76eab6 100644--- a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx+++ b/apps/web/src/lib/queries/messages/tests/mutations.test.tsx@@ -156,88 +156,93 @@ it('reopens a resolved project discussion through the real mutation and shared t).toBe(false);});-describe.each(['channel', 'document'] as const)('%s reply deletion', (type) => {- it.each(['before response', 'after response'] as const)(- 'applies deletion once when the live echo arrives %s',- async (echoTiming) => {- const parent: MessageParent = { type, id: 'parent' };- const replies = [- message(parent, 'first', 'root'),- message(parent, 'second', 'root'),- ];- const state = {- root_id: 'root',- user_id: 'macro|[email protected]',- resolved: false,- created_at: time,- updated_at: time,- anchor: null,- };- const root: MessageListItem = {- ...message(parent, 'root'),- state,- thread: { reply_count: 2, preview: replies, latest_reply_at: time },- };- const timelineKey = getMessageTimelineQueryKey(parent);- const selectedKey = messageKeys.messagesByIds(parent, ['root']).queryKey;- const threadKey = getThreadRepliesQueryKey(parent, 'root');- testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {- pageParams: [null],- pages: [{ items: [root], next_cursor: null, previous_cursor: null }],- });- testQueryClient.setQueryData(selectedKey, [root]);- testQueryClient.setQueryData<MessageThread>(threadKey, {- state,- root,- replies,- });- const deleted = { ...replies[0], content: '', deleted_at: time };- let echo: () => void = () => {};- mocks.delete.mockImplementation(async (_parent, _id, nonce) => {- echo = () =>- handleMessageEvent({- parent,- actor: root.sender_id,- nonce,- change: { type: 'message_deleted', message: deleted },- });- if (echoTiming === 'before response') echo();- return deleted;- });- let mutation!: ReturnType<typeof useDeleteMessageMutation>;- function Harness() {- mutation = useDeleteMessageMutation();- return null;+describe.each(['channel', 'document', 'call'] as const)(+ '%s reply deletion',+ (type) => {+ it.each(['before response', 'after response'] as const)(+ 'applies deletion once when the live echo arrives %s',+ async (echoTiming) => {+ const parent: MessageParent = { type, id: 'parent' };+ const replies = [+ message(parent, 'first', 'root'),+ message(parent, 'second', 'root'),+ ];+ const state = {+ root_id: 'root',+ user_id: 'macro|[email protected]',+ resolved: false,+ created_at: time,+ updated_at: time,+ anchor: null,+ };+ const root: MessageListItem = {+ ...message(parent, 'root'),+ state,+ thread: { reply_count: 2, preview: replies, latest_reply_at: time },+ };+ const timelineKey = getMessageTimelineQueryKey(parent);+ const selectedKey = messageKeys.messagesByIds(parent, [+ 'root',+ ]).queryKey;+ const threadKey = getThreadRepliesQueryKey(parent, 'root');+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {+ pageParams: [null],+ pages: [{ items: [root], next_cursor: null, previous_cursor: null }],+ });+ testQueryClient.setQueryData(selectedKey, [root]);+ testQueryClient.setQueryData<MessageThread>(threadKey, {+ state,+ root,+ replies,+ });+ const deleted = { ...replies[0], content: '', deleted_at: time };+ let echo: () => void = () => {};+ mocks.delete.mockImplementation(async (_parent, _id, nonce) => {+ echo = () =>+ handleMessageEvent({+ parent,+ actor: root.sender_id,+ nonce,+ change: { type: 'message_deleted', message: deleted },+ });+ if (echoTiming === 'before response') echo();+ return deleted;+ });+ let mutation!: ReturnType<typeof useDeleteMessageMutation>;+ function Harness() {+ mutation = useDeleteMessageMutation();+ return null;+ }+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <Harness />+ </QueryClientProvider>+ ));++ await mutation.mutateAsync({+ parent,+ messageID: 'first',+ threadID: 'root',+ });+ if (echoTiming === 'after response') echo();++ expect(+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey)!+ .pages[0].items[0].thread.reply_count+ ).toBe(1);+ expect(+ testQueryClient.getQueryData<MessageListItem[]>(selectedKey)![0]+ .thread.reply_count+ ).toBe(1);+ expect(+ testQueryClient+ .getQueryData<MessageThread>(threadKey)!+ .replies.map((reply) => reply.id)+ ).toEqual(['second']);}- render(() => (- <QueryClientProvider client={testQueryClient}>- <Harness />- </QueryClientProvider>- ));-- await mutation.mutateAsync({- parent,- messageID: 'first',- threadID: 'root',- });- if (echoTiming === 'after response') echo();-- expect(- testQueryClient.getQueryData<MessageTimelineData>(timelineKey)!.pages[0]- .items[0].thread.reply_count- ).toBe(1);- expect(- testQueryClient.getQueryData<MessageListItem[]>(selectedKey)![0].thread- .reply_count- ).toBe(1);- expect(- testQueryClient- .getQueryData<MessageThread>(threadKey)!- .replies.map((reply) => reply.id)- ).toEqual(['second']);- }- );-});+ );+ }+);describe('root deletion', () => {const threadState = (rootId: string) => ({@@ -294,52 +299,58 @@ describe('root deletion', () => {.getQueryData<MessageTimelineData>(getMessageTimelineQueryKey(parent))!.pages.flatMap((page) => page.items);- it("takes the whole discussion, including another author's replies", async () => {- const parent: MessageParent = { type: 'document', id: 'doc' };- seed(parent);- mocks.delete.mockResolvedValue({- ...message(parent, 'root'),- content: '',- deleted_at: time,- });- const deletedThreads: string[] = [];- const stop = onThreadStateUpdated((_parent, state) => {- if (state.deleted_at) deletedThreads.push(state.root_id);- });-- await mount().mutateAsync({ parent, messageID: 'root' });+ it.each(['document', 'initiative', 'crm_company', 'crm_contact'] as const)(+ "takes the whole %s discussion, including another author's replies",+ async (type) => {+ const parent: MessageParent = { type, id: 'parent' };+ seed(parent);+ mocks.delete.mockResolvedValue({+ ...message(parent, 'root'),+ content: '',+ deleted_at: time,+ });+ const deletedThreads: string[] = [];+ const stop = onThreadStateUpdated((_parent, state) => {+ if (state.deleted_at) deletedThreads.push(state.root_id);+ });- expect(roots(parent)).toEqual([]);- const thread = testQueryClient.getQueryData<MessageThread>(- getThreadRepliesQueryKey(parent, 'root')- )!;- expect(thread.state.deleted_at).toBe(time);- expect(thread.replies).toEqual([]);- // The margin and the document mark clear off this notification.- expect(deletedThreads).toEqual(['root']);- stop();- });+ await mount().mutateAsync({ parent, messageID: 'root' });++ expect(roots(parent)).toEqual([]);+ const thread = testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root')+ )!;+ expect(thread.state.deleted_at).toBe(time);+ expect(thread.replies).toEqual([]);+ // The margin and the document mark clear off this notification.+ expect(deletedThreads).toEqual(['root']);+ stop();+ }+ );- it('tears down a root whose replies were never opened', async () => {- // The only copy of this thread's state is the timeline item the optimistic- // delete removes, so the teardown has to read it before that happens.- const parent: MessageParent = { type: 'document', id: 'doc' };- seed(parent, false);- mocks.delete.mockResolvedValue({- ...message(parent, 'root'),- content: '',- deleted_at: time,- });- const deletedThreads: string[] = [];- const stop = onThreadStateUpdated((_parent, state) => {- if (state.deleted_at) deletedThreads.push(state.root_id);- });+ it.each(['document', 'initiative', 'crm_company', 'crm_contact'] as const)(+ 'tears down a %s root whose replies were never opened',+ async (type) => {+ // The only copy of this thread's state is the timeline item the optimistic+ // delete removes, so the teardown has to read it before that happens.+ const parent: MessageParent = { type, id: 'parent' };+ seed(parent, false);+ mocks.delete.mockResolvedValue({+ ...message(parent, 'root'),+ content: '',+ deleted_at: time,+ });+ const deletedThreads: string[] = [];+ const stop = onThreadStateUpdated((_parent, state) => {+ if (state.deleted_at) deletedThreads.push(state.root_id);+ });- await mount().mutateAsync({ parent, messageID: 'root' });+ await mount().mutateAsync({ parent, messageID: 'root' });- expect(deletedThreads).toEqual(['root']);- stop();- });+ expect(deletedThreads).toEqual(['root']);+ stop();+ }+ );it('restores the discussion when the delete fails', async () => {const parent: MessageParent = { type: 'document', id: 'doc' };@@ -376,6 +387,57 @@ describe('root deletion', () => {expect(thread.state.deleted_at).toBeUndefined();expect(thread.replies).toHaveLength(1);});++ it.each([false, true])(+ 'preserves the canonical call root when deleted (has replies: %s)',+ async (withReplies) => {+ const parent: MessageParent = { type: 'call', id: 'root' };+ const { root, state, replies } = seed(parent);+ if (!withReplies) {+ testQueryClient.setQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root'),+ { root, state, replies: [] }+ );+ testQueryClient.setQueryData<MessageTimelineData>(+ getMessageTimelineQueryKey(parent),+ {+ pageParams: [null],+ pages: [+ {+ items: [+ {+ ...root,+ thread: {+ reply_count: 0,+ preview: [],+ latest_reply_at: null,+ },+ },+ ],+ next_cursor: null,+ previous_cursor: null,+ },+ ],+ }+ );+ }+ mocks.delete.mockResolvedValue({+ ...root,+ content: '',+ deleted_at: time,+ });++ await mount().mutateAsync({ parent, messageID: 'root' });++ expect(roots(parent)).toHaveLength(1);+ const thread = testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'root')+ )!;+ expect(thread.root.deleted_at).toBeTruthy();+ expect(thread.state.deleted_at).toBeUndefined();+ expect(thread.replies).toEqual(withReplies ? replies : []);+ }+ );});describe('thread resolution', () => {@@ -463,6 +525,107 @@ describe('thread resolution', () => {});describe('sending', () => {+ function mountSend() {+ let mutation!: ReturnType<typeof useSendMessageMutation>;+ function Harness() {+ mutation = useSendMessageMutation();+ return null;+ }+ render(() => (+ <QueryClientProvider client={testQueryClient}>+ <Harness />+ </QueryClientProvider>+ ));+ return mutation;+ }++ it.each([undefined, 'call-id'])(+ 'adopts the canonical call root from a first send (requested thread: %s)',+ async (threadId) => {+ const parent: MessageParent = { type: 'call', id: 'call-id' };+ const timelineKey = getMessageTimelineQueryKey(parent);+ const threadKey = getThreadRepliesQueryKey(parent, parent.id);+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {+ pageParams: [null],+ pages: [{ items: [], next_cursor: null, previous_cursor: null }],+ });+ testQueryClient.setQueryData(threadKey, null);+ mocks.post.mockResolvedValue(message(parent, parent.id));++ await mountSend().mutateAsync({+ parent,+ message: { content: 'Hello', thread_id: threadId },+ senderId: 'macro|[email protected]',+ optimisticId: newMessageId(),+ });++ const roots =+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey)!.pages[0]+ .items;+ expect(roots.map((root) => [root.id, root.thread_id])).toEqual([+ ['call-id', undefined],+ ]);+ expect(testQueryClient.getQueryState(threadKey)?.isInvalidated).toBe(+ true+ );+ }+ );++ it('moves a racing initial call message into the canonical thread without duplicating its root', async () => {+ const parent: MessageParent = { type: 'call', id: 'call-id' };+ const timelineKey = getMessageTimelineQueryKey(parent);+ const threadKey = getThreadRepliesQueryKey(parent, parent.id);+ const root = message(parent, parent.id);+ const state = {+ root_id: root.id,+ user_id: root.sender_id,+ resolved: false,+ created_at: time,+ updated_at: time,+ };+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {+ pageParams: [null],+ pages: [+ {+ items: [+ {+ ...root,+ state,+ thread: { reply_count: 0, preview: [], latest_reply_at: null },+ },+ ],+ next_cursor: null,+ previous_cursor: null,+ },+ ],+ });+ testQueryClient.setQueryData<MessageThread>(threadKey, {+ root,+ state,+ replies: [],+ });+ const replyId = newMessageId();+ mocks.post.mockResolvedValue(message(parent, replyId, parent.id));++ await mountSend().mutateAsync({+ parent,+ message: { content: 'Hello from another participant' },+ senderId: 'macro|[email protected]',+ optimisticId: replyId,+ });++ const roots =+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey)!.pages[0]+ .items;+ expect(roots.map((item) => item.id)).toEqual([root.id]);+ expect(roots[0].thread.reply_count).toBe(1);+ const thread = testQueryClient.getQueryData<MessageThread>(threadKey)!;+ expect(thread.root.id).toBe(root.id);+ expect(thread.replies.map((reply) => [reply.id, reply.thread_id])).toEqual([+ [replyId, root.id],+ ]);+ });+it.each([undefined,{diff --git a/apps/web/src/lib/queries/messages/tests/subscription.test.ts b/apps/web/src/lib/queries/messages/tests/subscription.test.tsindex 8e4d73548d..5c663fa459 100644--- a/apps/web/src/lib/queries/messages/tests/subscription.test.ts+++ b/apps/web/src/lib/queries/messages/tests/subscription.test.ts@@ -109,6 +109,32 @@ it('subscribes and heartbeats a linked document drawer without a document block'expect(mocks.updates.size).toBe(0);});+it('tracks and refreshes a call thread independently from its channel', () => {+ const call: MessageParent = { type: 'call', id: 'call-id' };+ const channel: MessageParent = { type: 'channel', id: 'channel-id' };+ mount(() => {+ useReopenTrackedEntitiesOnReconnect();+ useMessageThreadQuery(+ () => call,+ () => call.id+ );+ useMessageThreadQuery(+ () => channel,+ () => 'root'+ );+ });+ expect(sent('open', call.id)[0][0].entity_type).toBe('call');+ expect(sent('open', channel.id)[0][0].entity_type).toBe('channel');+ mocks.invalidate.mockClear();+ for (const reconnect of mocks.reconnects) reconnect();+ expect(mocks.invalidate).toHaveBeenCalledWith({+ queryKey: ['messages', 'threadReplies', call],+ });+ expect(mocks.invalidate).toHaveBeenCalledWith({+ queryKey: ['messages', 'threadReplies', channel],+ });+});+it.each(['drawer', 'block'] as const)('keeps the source subscription alive when the %s closes first',(first) => {diff --git a/apps/web/src/lib/queries/messages/tests/sync.test.ts b/apps/web/src/lib/queries/messages/tests/sync.test.tsindex e3a8a69e27..6305977ef1 100644--- a/apps/web/src/lib/queries/messages/tests/sync.test.ts+++ b/apps/web/src/lib/queries/messages/tests/sync.test.ts@@ -76,577 +76,630 @@ afterEach(() => {testQueryClient.clear();clearTypingIndicators();});-describe.each(['channel', 'document', 'initiative', 'crm_company'] as const)(- '%s uses the shared live cache',- (type) => {- const parent: MessageParent = { type, id: 'source' };- const other: MessageParent = {- type: type === 'channel' ? 'document' : 'channel',- id: 'source',- };- const timelineKey = () => getMessageTimelineQueryKey(parent);- const threadKey = () => getThreadRepliesQueryKey(parent, 'root');- function seed() {- testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {- pageParams: [null],- pages: [- { items: [item(parent)], next_cursor: null, previous_cursor: null },- ],- });- testQueryClient.setQueryData<MessageListItem[]>(- messageKeys.messagesByIds(parent, ['root']).queryKey,- [item(parent)]- );- testQueryClient.setQueryData<MessageThread>(threadKey(), {- state,- root: message(parent, 'root'),- replies: [],- });- testQueryClient.setQueryData<MessageThread>(- getThreadRepliesQueryKey(other, 'root'),- { state, root: message(other, 'root'), replies: [] }- );- }- it('reconciles replies, attachments, mentions, reactions, and edits across timeline and linked drawer', () => {- seed();- const reply = {- ...message(parent, 'reply', 'root'),- attachments: [- {- id: 'attachment',- entity_id: 'doc',- entity_type: 'document',- created_at: time,- },- ],- };- applyMessage(reply, 'posted');- const edit = {- ...reply,- content: 'edited',- mentions: [{ entity_type: 'document', entity_id: 'doc' }],- reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],- };- applyMessage(edit, 'edited');- const root = testQueryClient.getQueryData<MessageTimelineData>(- timelineKey()- )!.pages[0].items[0];- expect(root.thread.reply_count).toBe(1);- expect(root.thread.preview).toEqual([expect.objectContaining(edit)]);- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.replies- ).toEqual([expect.objectContaining(edit)]);- expect(- testQueryClient.getQueryData<MessageListItem[]>(- messageKeys.messagesByIds(parent, ['root']).queryKey- )![0].thread.preview- ).toEqual([expect.objectContaining(edit)]);- expect(- testQueryClient.getQueryData<MessageThread>(- getThreadRepliesQueryKey(other, 'root')- )!.replies- ).toEqual([]);++it('refetches an empty call after a first message races the initial thread fetch', async () => {+ const parent: MessageParent = { type: 'call', id: 'call-id' };+ const key = getThreadRepliesQueryKey(parent, parent.id);+ const root = message(parent, parent.id);+ const thread: MessageThread = {+ root,+ state: { ...state, root_id: root.id },+ replies: [],+ };+ let finishEmptyFetch!: (value: null) => void;+ const fetchThread = vi+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise<null>((resolve) => {+ finishEmptyFetch = resolve;+ })+ )+ .mockResolvedValue(thread);+ const observer = new QueryObserver<MessageThread | null>(testQueryClient, {+ queryKey: key,+ queryFn: fetchThread,+ });+ const stop = observer.subscribe(() => {});++ handleMessageEvent({+ parent,+ actor: root.sender_id,+ change: {+ type: 'posted',+ message: root,+ mentions: [],+ notification_policy: 'Default',+ },+ });+ expect(fetchThread).toHaveBeenCalledTimes(1);+ finishEmptyFetch(null);++ await vi.waitFor(() => {+ expect(fetchThread).toHaveBeenCalledTimes(2);+ expect(testQueryClient.getQueryData(key)).toEqual(thread);+ });+ stop();+});++describe.each([+ 'channel',+ 'document',+ 'initiative',+ 'crm_company',+ 'call',+] as const)('%s uses the shared live cache', (type) => {+ const parent: MessageParent = { type, id: 'source' };+ const other: MessageParent = {+ type: type === 'channel' ? 'document' : 'channel',+ id: 'source',+ };+ const timelineKey = () => getMessageTimelineQueryKey(parent);+ const threadKey = () => getThreadRepliesQueryKey(parent, 'root');+ function seed() {+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {+ pageParams: [null],+ pages: [+ { items: [item(parent)], next_cursor: null, previous_cursor: null },+ ],});- it('preserves imported reply order when an older reply is edited', () => {- seed();- const first = {- ...message(parent, 'first', 'root'),- created_at: '2026-01-03T00:00:00Z',- };- const second = {- ...message(parent, 'second', 'root'),- created_at: '2026-01-01T00:00:00Z',- };- testQueryClient.setQueryData<MessageThread>(threadKey(), {- state,- root: message(parent, 'root'),- replies: [first, second],- });- applyMessage({ ...first, content: 'edited historical reply' }, 'edited');- expect(- testQueryClient- .getQueryData<MessageThread>(threadKey())!- .replies.map((reply) => reply.id)- ).toEqual(['first', 'second']);+ testQueryClient.setQueryData<MessageListItem[]>(+ messageKeys.messagesByIds(parent, ['root']).queryKey,+ [item(parent)]+ );+ testQueryClient.setQueryData<MessageThread>(threadKey(), {+ state,+ root: message(parent, 'root'),+ replies: [],});- it('does not count a reaction to an unseen preview reply as a new post', () => {- seed();- testQueryClient.removeQueries({ queryKey: threadKey() });- const root = {- ...item(parent),- thread: {- reply_count: 4,- latest_reply_at: time,- preview: ['first', 'second', 'third'].map((id) =>- message(parent, id, 'root')- ),- },- };- testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {- pageParams: [null],- pages: [{ items: [root], next_cursor: null, previous_cursor: null }],- });- testQueryClient.setQueryData<MessageListItem[]>(- messageKeys.messagesByIds(parent, ['root']).queryKey,- [root]- );-- handleMessageEvent({- parent,- actor: 'macro|[email protected]',- change: {- type: 'reaction_changed',- emoji: '👍',- added: true,- message: {- ...message(parent, 'fourth', 'root'),- reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],- },+ testQueryClient.setQueryData<MessageThread>(+ getThreadRepliesQueryKey(other, 'root'),+ { state, root: message(other, 'root'), replies: [] }+ );+ }+ it('reconciles replies, attachments, mentions, reactions, and edits across timeline and linked drawer', () => {+ seed();+ const reply = {+ ...message(parent, 'reply', 'root'),+ attachments: [+ {+ id: 'attachment',+ entity_id: 'doc',+ entity_type: 'document',+ created_at: time,},- });-- expect(- testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items[0].thread- ).toEqual(root.thread);- expect(- testQueryClient.getQueryData<MessageListItem[]>(- messageKeys.messagesByIds(parent, ['root']).queryKey- )![0].thread- ).toEqual(root.thread);- expect(testQueryClient.getQueryData(threadKey())).toBeUndefined();+ ],+ };+ applyMessage(reply, 'posted');+ const edit = {+ ...reply,+ content: 'edited',+ mentions: [{ entity_type: 'document', entity_id: 'doc' }],+ reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],+ };+ applyMessage(edit, 'edited');+ const root = testQueryClient.getQueryData<MessageTimelineData>(+ timelineKey()+ )!.pages[0].items[0];+ expect(root.thread.reply_count).toBe(1);+ expect(root.thread.preview).toEqual([expect.objectContaining(edit)]);+ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.replies+ ).toEqual([expect.objectContaining(edit)]);+ expect(+ testQueryClient.getQueryData<MessageListItem[]>(+ messageKeys.messagesByIds(parent, ['root']).queryKey+ )![0].thread.preview+ ).toEqual([expect.objectContaining(edit)]);+ expect(+ testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(other, 'root')+ )!.replies+ ).toEqual([]);+ });+ it('preserves imported reply order when an older reply is edited', () => {+ seed();+ const first = {+ ...message(parent, 'first', 'root'),+ created_at: '2026-01-03T00:00:00Z',+ };+ const second = {+ ...message(parent, 'second', 'root'),+ created_at: '2026-01-01T00:00:00Z',+ };+ testQueryClient.setQueryData<MessageThread>(threadKey(), {+ state,+ root: message(parent, 'root'),+ replies: [first, second],});- it('does not insert an unseen edit or let a reaction snapshot overwrite content', () => {- seed();- applyMessage(message(parent, 'unseen', 'root'), 'edited');- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.replies- ).toEqual([]);+ applyMessage({ ...first, content: 'edited historical reply' }, 'edited');+ expect(+ testQueryClient+ .getQueryData<MessageThread>(threadKey())!+ .replies.map((reply) => reply.id)+ ).toEqual(['first', 'second']);+ });+ it('does not count a reaction to an unseen preview reply as a new post', () => {+ seed();+ testQueryClient.removeQueries({ queryKey: threadKey() });+ const root = {+ ...item(parent),+ thread: {+ reply_count: 4,+ latest_reply_at: time,+ preview: ['first', 'second', 'third'].map((id) =>+ message(parent, id, 'root')+ ),+ },+ };+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {+ pageParams: [null],+ pages: [{ items: [root], next_cursor: null, previous_cursor: null }],+ });+ testQueryClient.setQueryData<MessageListItem[]>(+ messageKeys.messagesByIds(parent, ['root']).queryKey,+ [root]+ );- const reply = message(parent, 'reply', 'root');- applyMessage(reply, 'posted');- applyMessage({ ...reply, content: 'new content' }, 'edited');- applyMessage(- {- ...reply,+ handleMessageEvent({+ parent,+ actor: 'macro|[email protected]',+ change: {+ type: 'reaction_changed',+ emoji: '👍',+ added: true,+ message: {+ ...message(parent, 'fourth', 'root'),reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],},- 'reaction_changed'- );+ },+ });- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.replies- ).toEqual([- expect.objectContaining({- content: 'new content',- reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],- }),- ]);- expect(- testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items[0].thread.reply_count- ).toBe(1);+ expect(+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!.pages[0]+ .items[0].thread+ ).toEqual(root.thread);+ expect(+ testQueryClient.getQueryData<MessageListItem[]>(+ messageKeys.messagesByIds(parent, ['root']).queryKey+ )![0].thread+ ).toEqual(root.thread);+ expect(testQueryClient.getQueryData(threadKey())).toBeUndefined();+ });+ it('does not insert an unseen edit or let a reaction snapshot overwrite content', () => {+ seed();+ applyMessage(message(parent, 'unseen', 'root'), 'edited');+ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.replies+ ).toEqual([]);++ const reply = message(parent, 'reply', 'root');+ applyMessage(reply, 'posted');+ applyMessage({ ...reply, content: 'new content' }, 'edited');+ applyMessage(+ {+ ...reply,+ reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],+ },+ 'reaction_changed'+ );++ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.replies+ ).toEqual([+ expect.objectContaining({+ content: 'new content',+ reactions: [{ emoji: '👍', users: ['macro|[email protected]'] }],+ }),+ ]);+ expect(+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!.pages[0]+ .items[0].thread.reply_count+ ).toBe(1);+ });+ it('updates the canonical root when only a linked thread is cached', () => {+ testQueryClient.setQueryData<MessageThread>(threadKey(), {+ state,+ root: message(parent, 'root'),+ replies: [message(parent, 'reply', 'root')],});- it('updates the canonical root when only a linked thread is cached', () => {- testQueryClient.setQueryData<MessageThread>(threadKey(), {- state,- root: message(parent, 'root'),- replies: [message(parent, 'reply', 'root')],- });- applyMessage(- { ...message(parent, 'root'), content: 'edited root' },- 'edited'- );- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.root.content- ).toBe('edited root');- applyMessage(- { ...message(parent, 'root'), content: '', deleted_at: time },- 'message_deleted'- );- const thread = testQueryClient.getQueryData<MessageThread>(threadKey())!;- expect(thread.root.deleted_at).toBe(time);- expect(thread.replies).toHaveLength(1);- expect(testQueryClient.getQueryData(timelineKey())).toBeUndefined();+ applyMessage(+ { ...message(parent, 'root'), content: 'edited root' },+ 'edited'+ );+ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.root.content+ ).toBe('edited root');+ applyMessage(+ { ...message(parent, 'root'), content: '', deleted_at: time },+ 'message_deleted'+ );+ const thread = testQueryClient.getQueryData<MessageThread>(threadKey())!;+ expect(thread.root.deleted_at).toBe(time);+ expect(thread.replies).toHaveLength(1);+ expect(testQueryClient.getQueryData(timelineKey())).toBeUndefined();+ });+ it('keeps root tombstones with replies and propagates resolution and whole-thread deletion', () => {+ seed();+ applyMessage(message(parent, 'reply', 'root'), 'posted');+ applyMessage(+ {+ ...message(parent, 'root'),+ content: '',+ deleted_at: time,+ },+ 'message_deleted'+ );+ expect(+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!.pages[0]+ .items[0].deleted_at+ ).toBe(time);+ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.replies+ ).toHaveLength(1);+ applyThreadState(parent, { ...state, resolved: true });+ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.state.resolved+ ).toBe(true);+ applyThreadState(parent, { ...state, deleted_at: time });+ expect(+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!.pages[0]+ .items+ ).toEqual(+ parent.type === 'document'+ ? [expect.objectContaining({ state: { ...state, deleted_at: time } })]+ : []+ );+ });+ it('inserts an external root post at the bottom of the conversation only', () => {+ seed();+ handleMessageEvent({+ parent,+ actor: 'macro|[email protected]',+ nonce: null,+ change: {+ type: 'posted',+ message: message(parent, 'newer-root'),+ mentions: [],+ notification_policy: 'Default',+ },});- it('keeps root tombstones with replies and propagates resolution and whole-thread deletion', () => {- seed();- applyMessage(message(parent, 'reply', 'root'), 'posted');- applyMessage(+ expect(+ testQueryClient+ .getQueryData<MessageTimelineData>(timelineKey())!+ .pages[0].items.map((root) => root.id)+ ).toEqual(['newer-root', 'root']);++ testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {+ pageParams: [null],+ pages: [{- ...message(parent, 'root'),- content: '',- deleted_at: time,+ items: [item(parent)],+ next_cursor: null,+ previous_cursor: { created_at: time, id: 'root' },},- 'message_deleted'- );- expect(- testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items[0].deleted_at- ).toBe(time);- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.replies- ).toHaveLength(1);- applyThreadState(parent, { ...state, resolved: true });- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.state.resolved- ).toBe(true);- applyThreadState(parent, { ...state, deleted_at: time });- expect(- testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items- ).toEqual(- parent.type === 'document'- ? [expect.objectContaining({ state: { ...state, deleted_at: time } })]- : []- );+ ],});- it('inserts an external root post at the bottom of the conversation only', () => {+ applyMessage(message(parent, 'mid-conversation'), 'posted');+ expect(+ testQueryClient+ .getQueryData<MessageTimelineData>(timelineKey())!+ .pages[0].items.map((root) => root.id)+ ).toEqual(['root']);+ });+ it(+ type !== 'channel'+ ? "loads a live root's thread state instead of refetching the timeline"+ : 'applies a live root without a metadata refetch',+ async () => {seed();+ mocks.thread.mockReset();+ const rootState = {+ ...state,+ root_id: 'newer-root',+ anchor:+ type === 'document'+ ? ({ type: 'markdown', mark_id: 'mark' } as const)+ : null,+ };+ // An agent's comment: the thread endpoint returns the same+ // bot_profile the timeline does, never a pre-derived sender.+ const agentRoot: Message = {+ ...message(parent, 'newer-root'),+ sender_id: 'bot|00000000-0000-0000-0000-000000000001',+ bot_profile: { name: 'Bingus', avatar_url: null },+ triggered_by: 'macro|[email protected]',+ };+ mocks.thread.mockResolvedValue({+ root: agentRoot,+ state: rootState,+ replies: [],+ });+ const invalidate = vi.spyOn(testQueryClient, 'invalidateQueries');handleMessageEvent({parent,- actor: 'macro|[email protected]',+ actor: agentRoot.sender_id,nonce: null,change: {type: 'posted',- message: message(parent, 'newer-root'),+ message: agentRoot,mentions: [],notification_policy: 'Default',},});- expect(- testQueryClient- .getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items.map((root) => root.id)- ).toEqual(['newer-root', 'root']);-- testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {- pageParams: [null],- pages: [- {- items: [item(parent)],- next_cursor: null,- previous_cursor: { created_at: time, id: 'root' },- },- ],+ const newestRoot = () =>+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!+ .pages[0].items[0];+ const agentSender = expect.objectContaining({+ type: 'bot',+ name: 'Bingus',+ triggered_by: 'macro|[email protected]',});- applyMessage(message(parent, 'mid-conversation'), 'posted');- expect(- testQueryClient- .getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items.map((root) => root.id)- ).toEqual(['root']);- });- it(- type !== 'channel'- ? "loads a live root's thread state instead of refetching the timeline"- : 'applies a live root without a metadata refetch',- async () => {- seed();- mocks.thread.mockReset();- const rootState = {- ...state,- root_id: 'newer-root',- anchor:- type === 'document'- ? ({ type: 'markdown', mark_id: 'mark' } as const)- : null,- };- // An agent's comment: the thread endpoint returns the same- // bot_profile the timeline does, never a pre-derived sender.- const agentRoot: Message = {- ...message(parent, 'newer-root'),- sender_id: 'bot|00000000-0000-0000-0000-000000000001',- bot_profile: { name: 'Bingus', avatar_url: null },- triggered_by: 'macro|[email protected]',- };- mocks.thread.mockResolvedValue({- root: agentRoot,- state: rootState,- replies: [],- });- const invalidate = vi.spyOn(testQueryClient, 'invalidateQueries');- handleMessageEvent({- parent,- actor: agentRoot.sender_id,- nonce: null,- change: {- type: 'posted',- message: agentRoot,- mentions: [],- notification_policy: 'Default',- },- });- const newestRoot = () =>- testQueryClient.getQueryData<MessageTimelineData>(timelineKey())!- .pages[0].items[0];- const agentSender = expect.objectContaining({- type: 'bot',- name: 'Bingus',- triggered_by: 'macro|[email protected]',- });- expect(newestRoot().sender).toEqual(agentSender);- if (type !== 'channel') {- expect(mocks.thread).toHaveBeenCalledWith(parent, 'newer-root');- await vi.waitFor(() =>- expect(- testQueryClient.getQueryData<MessageThread>(- getThreadRepliesQueryKey(parent, 'newer-root')- )?.state- ).toEqual(rootState)- );- expect(newestRoot().state.anchor).toEqual(rootState.anchor);- const thread = testQueryClient.getQueryData<MessageThread>(- getThreadRepliesQueryKey(parent, 'newer-root')+ expect(newestRoot().sender).toEqual(agentSender);+ if (type !== 'channel') {+ expect(mocks.thread).toHaveBeenCalledWith(parent, 'newer-root');+ await vi.waitFor(() =>+ expect(+ testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'newer-root')+ )?.state+ ).toEqual(rootState)+ );+ expect(newestRoot().state.anchor).toEqual(rootState.anchor);+ const thread = testQueryClient.getQueryData<MessageThread>(+ getThreadRepliesQueryKey(parent, 'newer-root')+ );+ expect(thread?.state).toEqual(rootState);+ // The margin renders this cached root, so the agent must keep its+ // name here too rather than falling back to a generic "Bot".+ expect(thread?.root.sender).toEqual(agentSender);+ } else {+ expect(mocks.thread).not.toHaveBeenCalled();+ expect(newestRoot().id).toBe('newer-root');+ expect(newestRoot().state.anchor).toBeNull();+ }+ // Only the soft invalidation that leaves mounted timelines alone may run.+ for (const [filters] of invalidate.mock.calls) {+ if (type === 'call' && filters?.exact) {+ expect(filters.queryKey).toEqual(+ getThreadRepliesQueryKey(parent, parent.id));- expect(thread?.state).toEqual(rootState);- // The margin renders this cached root, so the agent must keep its- // name here too rather than falling back to a generic "Bot".- expect(thread?.root.sender).toEqual(agentSender);} else {- expect(mocks.thread).not.toHaveBeenCalled();- expect(newestRoot().id).toBe('newer-root');- expect(newestRoot().state.anchor).toBeNull();- }- // Only the soft invalidation that leaves mounted timelines alone may run.- for (const [filters] of invalidate.mock.calls) {expect(filters?.refetchType).toBe('inactive');}}- );- it('refetches a bottom page that is still loading when a root arrives', async () => {- mocks.thread.mockReset();- let resolveFetch: (data: MessageTimelineData) => void = () => {};- const fetching = testQueryClient.fetchQuery({+ }+ );+ it('refetches a bottom page that is still loading when a root arrives', async () => {+ mocks.thread.mockReset();+ let resolveFetch: (data: MessageTimelineData) => void = () => {};+ const fetching = testQueryClient.fetchQuery({+ queryKey: timelineKey(),+ queryFn: () =>+ new Promise<MessageTimelineData>((resolve) => {+ resolveFetch = resolve;+ }),+ });+ const invalidate = vi.spyOn(testQueryClient, 'invalidateQueries');+ handleMessageEvent({+ parent,+ actor: 'macro|[email protected]',+ nonce: null,+ change: {+ type: 'posted',+ message: message(parent, 'racing-root'),+ mentions: [],+ notification_policy: 'Default',+ },+ });+ // The refetch waits for the in-flight page to settle rather than+ // deduping into it, so nothing is invalidated yet.+ expect(invalidate).not.toHaveBeenCalled();+ expect(mocks.thread).not.toHaveBeenCalled();+ resolveFetch({+ pageParams: [null],+ pages: [+ { items: [item(parent)], next_cursor: null, previous_cursor: null },+ ],+ });+ await fetching.catch(() => undefined);+ await vi.waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({queryKey: timelineKey(),- queryFn: () =>- new Promise<MessageTimelineData>((resolve) => {- resolveFetch = resolve;- }),- });- const invalidate = vi.spyOn(testQueryClient, 'invalidateQueries');- handleMessageEvent({- parent,- actor: 'macro|[email protected]',- nonce: null,- change: {- type: 'posted',- message: message(parent, 'racing-root'),- mentions: [],- notification_policy: 'Default',- },- });- // The refetch waits for the in-flight page to settle rather than- // deduping into it, so nothing is invalidated yet.- expect(invalidate).not.toHaveBeenCalled();- expect(mocks.thread).not.toHaveBeenCalled();- resolveFetch({- pageParams: [null],- pages: [- { items: [item(parent)], next_cursor: null, previous_cursor: null },- ],- });- await fetching.catch(() => undefined);- await vi.waitFor(() =>- expect(invalidate).toHaveBeenCalledWith({- queryKey: timelineKey(),- exact: true,- })- );+ exact: true,+ })+ );+ });+ it("recovers the sender's own root posted before the bottom page loads", async () => {+ let resolveFetch: (data: MessageTimelineData) => void = () => {};+ const fetching = testQueryClient.fetchQuery({+ queryKey: timelineKey(),+ queryFn: () =>+ new Promise<MessageTimelineData>((resolve) => {+ resolveFetch = resolve;+ }),+ });+ registerNonce(MessageNonceKeys.MESSAGE, 'own-send');+ const invalidate = vi.spyOn(testQueryClient, 'invalidateQueries');+ handleMessageEvent({+ parent,+ actor: 'macro|[email protected]',+ nonce: 'own-send',+ change: {+ type: 'posted',+ message: message(parent, 'own-root'),+ mentions: [],+ notification_policy: 'Default',+ },+ });+ // The sender's own optimistic insert no-oped while the page was loading,+ // and the echo alone would be consumed by the nonce; the recovery fetch+ // still runs once the page settles.+ resolveFetch({+ pageParams: [null],+ pages: [{ items: [], next_cursor: null, previous_cursor: null }],});- it("recovers the sender's own root posted before the bottom page loads", async () => {- let resolveFetch: (data: MessageTimelineData) => void = () => {};- const fetching = testQueryClient.fetchQuery({+ await fetching.catch(() => undefined);+ await vi.waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({queryKey: timelineKey(),- queryFn: () =>- new Promise<MessageTimelineData>((resolve) => {- resolveFetch = resolve;- }),- });- registerNonce(MessageNonceKeys.MESSAGE, 'own-send');- const invalidate = vi.spyOn(testQueryClient, 'invalidateQueries');- handleMessageEvent({- parent,- actor: 'macro|[email protected]',- nonce: 'own-send',- change: {- type: 'posted',- message: message(parent, 'own-root'),- mentions: [],- notification_policy: 'Default',- },- });- // The sender's own optimistic insert no-oped while the page was loading,- // and the echo alone would be consumed by the nonce; the recovery fetch- // still runs once the page settles.- resolveFetch({- pageParams: [null],- pages: [{ items: [], next_cursor: null, previous_cursor: null }],- });- await fetching.catch(() => undefined);- await vi.waitFor(() =>- expect(invalidate).toHaveBeenCalledWith({- queryKey: timelineKey(),- exact: true,- })- );+ exact: true,+ })+ );+ });+ // An expanded thread whose first replies fetch is still in flight: the root+ // is in the timeline, but the thread's own query has not resolved yet.+ async function expandThreadWithPendingFetch() {+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {+ pageParams: [null],+ pages: [+ { items: [item(parent)], next_cursor: null, previous_cursor: null },+ ],});- // An expanded thread whose first replies fetch is still in flight: the root- // is in the timeline, but the thread's own query has not resolved yet.- async function expandThreadWithPendingFetch() {- testQueryClient.setQueryData<MessageTimelineData>(timelineKey(), {- pageParams: [null],- pages: [- { items: [item(parent)], next_cursor: null, previous_cursor: null },- ],- });- mocks.thread.mockReset();- let resolveFirst: (thread: MessageThread) => void = () => {};- mocks.thread.mockImplementationOnce(- () =>- new Promise<MessageThread>((resolve) => {- resolveFirst = resolve;- })- );- const observer = new QueryObserver(- testQueryClient,- threadRepliesQueryOptions(parent, 'root')- );- const unsubscribe = observer.subscribe(() => {});- await vi.waitFor(() => expect(mocks.thread).toHaveBeenCalledTimes(1));- const threadReplies = () =>- testQueryClient.getQueryData<MessageThread>(threadKey())?.replies;- // The fetch settles predating whatever arrived while it was in flight.- const settleEmpty = async () => {- resolveFirst({ state, root: message(parent, 'root'), replies: [] });- await vi.waitFor(() => expect(threadReplies()).toBeDefined());- await Promise.resolve();- };- return { settleEmpty, threadReplies, unsubscribe };- }+ mocks.thread.mockReset();+ let resolveFirst: (thread: MessageThread) => void = () => {};+ mocks.thread.mockImplementationOnce(+ () =>+ new Promise<MessageThread>((resolve) => {+ resolveFirst = resolve;+ })+ );+ const observer = new QueryObserver(+ testQueryClient,+ threadRepliesQueryOptions(parent, 'root')+ );+ const unsubscribe = observer.subscribe(() => {});+ await vi.waitFor(() => expect(mocks.thread).toHaveBeenCalledTimes(1));+ const threadReplies = () =>+ testQueryClient.getQueryData<MessageThread>(threadKey())?.replies;+ // The fetch settles predating whatever arrived while it was in flight.+ const settleEmpty = async () => {+ resolveFirst({ state, root: message(parent, 'root'), replies: [] });+ await vi.waitFor(() => expect(threadReplies()).toBeDefined());+ await Promise.resolve();+ };+ return { settleEmpty, threadReplies, unsubscribe };+ }- it('keeps a live reply that arrives while its first replies fetch is in flight', async () => {- const { settleEmpty, threadReplies, unsubscribe } =- await expandThreadWithPendingFetch();+ it('keeps a live reply that arrives while its first replies fetch is in flight', async () => {+ const { settleEmpty, threadReplies, unsubscribe } =+ await expandThreadWithPendingFetch();- // The preview-only insert drops the reply from the not-yet-cached thread;- // it must be re-applied once the fetch settles rather than lost.- applyMessage(message(parent, 'reply', 'root'), 'posted');- await settleEmpty();+ // The preview-only insert drops the reply from the not-yet-cached thread;+ // it must be re-applied once the fetch settles rather than lost.+ applyMessage(message(parent, 'reply', 'root'), 'posted');+ await settleEmpty();- expect(threadReplies()).toEqual([- expect.objectContaining({ id: 'reply' }),- ]);- // Convergence needs no extra network round trip.- expect(mocks.thread).toHaveBeenCalledTimes(1);+ expect(threadReplies()).toEqual([expect.objectContaining({ id: 'reply' })]);+ // Convergence needs no extra network round trip.+ expect(mocks.thread).toHaveBeenCalledTimes(1);- // The timeline preview mirrors the reply while the thread settles.- const root = testQueryClient.getQueryData<MessageTimelineData>(- timelineKey()- )!.pages[0].items[0];- expect(root.thread.reply_count).toBe(1);- expect(root.thread.preview).toEqual([- expect.objectContaining({ id: 'reply' }),- ]);- unsubscribe();- });+ // The timeline preview mirrors the reply while the thread settles.+ const root = testQueryClient.getQueryData<MessageTimelineData>(+ timelineKey()+ )!.pages[0].items[0];+ expect(root.thread.reply_count).toBe(1);+ expect(root.thread.preview).toEqual([+ expect.objectContaining({ id: 'reply' }),+ ]);+ unsubscribe();+ });- it('applies the latest edit of a reply that arrives while the fetch is in flight', async () => {- const { settleEmpty, threadReplies, unsubscribe } =- await expandThreadWithPendingFetch();- const reply = message(parent, 'reply', 'root');+ it('applies the latest edit of a reply that arrives while the fetch is in flight', async () => {+ const { settleEmpty, threadReplies, unsubscribe } =+ await expandThreadWithPendingFetch();+ const reply = message(parent, 'reply', 'root');- applyMessage(reply, 'posted');- applyMessage({ ...reply, content: 'edited' }, 'edited');- await settleEmpty();+ applyMessage(reply, 'posted');+ applyMessage({ ...reply, content: 'edited' }, 'edited');+ await settleEmpty();- // The deferred re-apply reads the current preview state, not the stale- // posted payload, so the edit wins.- expect(threadReplies()).toEqual([- expect.objectContaining({ id: 'reply', content: 'edited' }),- ]);- unsubscribe();- });+ // The deferred re-apply reads the current preview state, not the stale+ // posted payload, so the edit wins.+ expect(threadReplies()).toEqual([+ expect.objectContaining({ id: 'reply', content: 'edited' }),+ ]);+ unsubscribe();+ });- it('does not resurrect a reply deleted while the fetch is in flight', async () => {- const { settleEmpty, threadReplies, unsubscribe } =- await expandThreadWithPendingFetch();- const reply = message(parent, 'reply', 'root');+ it('does not resurrect a reply deleted while the fetch is in flight', async () => {+ const { settleEmpty, threadReplies, unsubscribe } =+ await expandThreadWithPendingFetch();+ const reply = message(parent, 'reply', 'root');- applyMessage(reply, 'posted');- applyMessage(- { ...reply, content: '', deleted_at: time },- 'message_deleted'- );- await settleEmpty();+ applyMessage(reply, 'posted');+ applyMessage(+ { ...reply, content: '', deleted_at: time },+ 'message_deleted'+ );+ await settleEmpty();- // The reply left the preview on delete, so the deferred re-apply skips it.- expect(threadReplies()).toEqual([]);- unsubscribe();- });- it('derives senders for a thread fetched on its own', async () => {- mocks.thread.mockReset();- const agent = 'bot|00000000-0000-0000-0000-000000000001';- mocks.thread.mockResolvedValue({- state,- root: {- ...message(parent, 'root'),+ // The reply left the preview on delete, so the deferred re-apply skips it.+ expect(threadReplies()).toEqual([]);+ unsubscribe();+ });+ it('derives senders for a thread fetched on its own', async () => {+ mocks.thread.mockReset();+ const agent = 'bot|00000000-0000-0000-0000-000000000001';+ mocks.thread.mockResolvedValue({+ state,+ root: {+ ...message(parent, 'root'),+ sender_id: agent,+ bot_profile: { name: 'Bingus', avatar_url: null },+ },+ replies: [+ {+ ...message(parent, 'reply', 'root'),sender_id: agent,bot_profile: { name: 'Bingus', avatar_url: null },- },- replies: [- {- ...message(parent, 'reply', 'root'),- sender_id: agent,- bot_profile: { name: 'Bingus', avatar_url: null },- triggered_by: 'macro|[email protected]',- },- message(parent, 'human-reply', 'root'),- ],- });- const thread = await testQueryClient.fetchQuery(- threadRepliesQueryOptions(parent, 'root')- );- expect(thread.root.sender).toEqual(- expect.objectContaining({ type: 'bot', name: 'Bingus' })- );- expect(thread.replies.map((reply) => reply.sender)).toEqual([- expect.objectContaining({- type: 'bot',- name: 'Bingus',triggered_by: 'macro|[email protected]',- }),- { type: 'user', id: 'macro|[email protected]', triggered_by: undefined },- ]);- });- it('skips the sender nonce and scopes ephemeral typing to the parent and root', () => {- seed();- registerNonce(MessageNonceKeys.MESSAGE, 'own-send');- handleMessageEvent({- parent,- actor: 'macro|[email protected]',- nonce: 'own-send',- change: {- type: 'posted',- message: message(parent, 'reply', 'root'),- mentions: [],- notification_policy: 'Default',},- });- expect(- testQueryClient.getQueryData<MessageThread>(threadKey())!.replies- ).toEqual([]);- handleMessageEvent(- {- parent,- actor: 'macro|[email protected]',- nonce: null,- change: { type: 'typing', active: true, thread_id: null },- },- 'macro|[email protected]'- );- expect([...getTypingUsers(parent)]).toEqual(['macro|[email protected]']);- expect([...getTypingUsers(other)]).toEqual([]);+ message(parent, 'human-reply', 'root'),+ ],});- }-);+ const thread = await testQueryClient.fetchQuery(+ threadRepliesQueryOptions(parent, 'root')+ );+ expect(thread.root.sender).toEqual(+ expect.objectContaining({ type: 'bot', name: 'Bingus' })+ );+ expect(thread.replies.map((reply) => reply.sender)).toEqual([+ expect.objectContaining({+ type: 'bot',+ name: 'Bingus',+ triggered_by: 'macro|[email protected]',+ }),+ { type: 'user', id: 'macro|[email protected]', triggered_by: undefined },+ ]);+ });+ it('skips the sender nonce and scopes ephemeral typing to the parent and root', () => {+ seed();+ registerNonce(MessageNonceKeys.MESSAGE, 'own-send');+ handleMessageEvent({+ parent,+ actor: 'macro|[email protected]',+ nonce: 'own-send',+ change: {+ type: 'posted',+ message: message(parent, 'reply', 'root'),+ mentions: [],+ notification_policy: 'Default',+ },+ });+ expect(+ testQueryClient.getQueryData<MessageThread>(threadKey())!.replies+ ).toEqual([]);+ handleMessageEvent(+ {+ parent,+ actor: 'macro|[email protected]',+ nonce: null,+ change: { type: 'typing', active: true, thread_id: null },+ },+ 'macro|[email protected]'+ );+ expect([...getTypingUsers(parent)]).toEqual(['macro|[email protected]']);+ expect([...getTypingUsers(other)]).toEqual([]);+ });+});diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex 806cdca63d..4c9bc6f1c8 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -160,6 +160,8 @@ export * from './messageParentOneOfFive';export * from './messageParentOneOfFiveType';export * from './messageParentOneOfNine';export * from './messageParentOneOfNineType';+export * from './messageParentOneOfOneone';+export * from './messageParentOneOfOneoneType';export * from './messageParentOneOfSeven';export * from './messageParentOneOfSevenType';export * from './messageParentOneOfThree';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.tsindex 398458bb63..3493ea4cc5 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParent.ts@@ -7,6 +7,7 @@import type { MessageParentOneOf } from './messageParentOneOf';import type { MessageParentOneOfFive } from './messageParentOneOfFive';import type { MessageParentOneOfNine } from './messageParentOneOfNine';+import type { MessageParentOneOfOneone } from './messageParentOneOfOneone';import type { MessageParentOneOfSeven } from './messageParentOneOfSeven';import type { MessageParentOneOfThree } from './messageParentOneOfThree';@@ -18,4 +19,5 @@ export type MessageParent =| MessageParentOneOfThree| MessageParentOneOfFive| MessageParentOneOfSeven- | MessageParentOneOfNine;+ | MessageParentOneOfNine+ | MessageParentOneOfOneone;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfOneone.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfOneone.tsnew file mode 100644index 0000000000..6c79b96c17--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfOneone.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { MessageParentOneOfOneoneType } from './messageParentOneOfOneoneType';++/**+ * A video call and its persistent chat thread.+ */+export type MessageParentOneOfOneone = {+ /** A video call and its persistent chat thread. */+ id: string;+ type: MessageParentOneOfOneoneType;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfOneoneType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfOneoneType.tsnew file mode 100644index 0000000000..ba36369bf3--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/messageParentOneOfOneoneType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type MessageParentOneOfOneoneType =+ (typeof MessageParentOneOfOneoneType)[keyof typeof MessageParentOneOfOneoneType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const MessageParentOneOfOneoneType = {+ call: 'call',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex b23e9212d1..1c2020da63 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -3048,6 +3048,22 @@"enum": ["crm_contact"]}}+ },+ {+ "type": "object",+ "description": "A video call and its persistent chat thread.",+ "required": ["id", "type"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "A video call and its persistent chat thread."+ },+ "type": {+ "type": "string",+ "enum": ["call"]+ }+ }}],"description": "The entity whose permissions and lifecycle govern a message."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.tsindex 862fa0149e..9c09fe72de 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@@ -906,6 +906,8 @@ export * from './messageParentOneOfFive';export * from './messageParentOneOfFiveType';export * from './messageParentOneOfNine';export * from './messageParentOneOfNineType';+export * from './messageParentOneOfOneone';+export * from './messageParentOneOfOneoneType';export * from './messageParentOneOfSeven';export * from './messageParentOneOfSevenType';export * from './messageParentOneOfThree';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParent.tsindex 38b2a64495..f2b33916cf 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParent.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParent.ts@@ -7,6 +7,7 @@import type { MessageParentOneOf } from './messageParentOneOf';import type { MessageParentOneOfFive } from './messageParentOneOfFive';import type { MessageParentOneOfNine } from './messageParentOneOfNine';+import type { MessageParentOneOfOneone } from './messageParentOneOfOneone';import type { MessageParentOneOfSeven } from './messageParentOneOfSeven';import type { MessageParentOneOfThree } from './messageParentOneOfThree';@@ -18,4 +19,5 @@ export type MessageParent =| MessageParentOneOfThree| MessageParentOneOfFive| MessageParentOneOfSeven- | MessageParentOneOfNine;+ | MessageParentOneOfNine+ | MessageParentOneOfOneone;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParentOneOfOneone.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParentOneOfOneone.tsnew file mode 100644index 0000000000..d94c5245d2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParentOneOfOneone.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { MessageParentOneOfOneoneType } from './messageParentOneOfOneoneType';++/**+ * A video call and its persistent chat thread.+ */+export type MessageParentOneOfOneone = {+ /** A video call and its persistent chat thread. */+ id: string;+ type: MessageParentOneOfOneoneType;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParentOneOfOneoneType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParentOneOfOneoneType.tsnew file mode 100644index 0000000000..f178b2d000--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageParentOneOfOneoneType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type MessageParentOneOfOneoneType =+ (typeof MessageParentOneOfOneoneType)[keyof typeof MessageParentOneOfOneoneType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const MessageParentOneOfOneoneType = {+ call: 'call',+} as const;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.tsindex c298aa3bb7..a7f492dfc5 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@@ -29340,6 +29340,14 @@ export const messageTimelineResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'@@ -29637,6 +29645,18 @@ export const messageTimelineResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe(+ 'A video call and its persistent chat thread.'+ ),+ type: zod.enum(['call']),+ })+ .describe(+ 'A video call and its persistent chat thread.'+ ),]).describe('The entity whose permissions and lifecycle govern a message.'@@ -29966,6 +29986,14 @@ export const entityMessageCreateResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'),reactions: zod@@ -30114,6 +30142,14 @@ export const entityMessageGetMessageResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'),reactions: zod@@ -30266,6 +30302,14 @@ export const entityMessageDeleteMessageResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'),reactions: zod@@ -30514,6 +30558,14 @@ export const entityMessageEditResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'),reactions: zod@@ -30670,6 +30722,14 @@ export const entityMessageReactResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'),reactions: zod@@ -30825,6 +30885,14 @@ export const entityMessageLegacyResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'),reactions: zod@@ -30996,6 +31064,14 @@ export const entityMessageGetThreadResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'@@ -31149,6 +31225,14 @@ export const entityMessageGetThreadResponse = zodtype: zod.enum(['crm_contact']),}).describe('A CRM contact.'),+ zod+ .object({+ id: zod+ .uuid()+ .describe('A video call and its persistent chat thread.'),+ type: zod.enum(['call']),+ })+ .describe('A video call and its persistent chat thread.'),]).describe('The entity whose permissions and lifecycle govern a message.'diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 8753baee64..9f85450542 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -24613,6 +24613,22 @@"enum": ["crm_contact"]}}+ },+ {+ "type": "object",+ "description": "A video call and its persistent chat thread.",+ "required": ["id", "type"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "A video call and its persistent chat thread."+ },+ "type": {+ "type": "string",+ "enum": ["call"]+ }+ }}],"description": "The entity whose permissions and lifecycle govern a message."diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rsindex c22e70f0a7..c56986dc00 100644--- a/crates/agent_harness/src/outbound/channel_announcer.rs+++ b/crates/agent_harness/src/outbound/channel_announcer.rs@@ -153,6 +153,7 @@ fn announcement_reply_target(announcement: &SessionAnnouncement) -> AgentAnnouncchannel_id: match &announcement.origin_parent {MessageParent::Channel(channel_id) => Some(channel_id.to_string()),MessageParent::Document(_)+ | MessageParent::Call(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)| MessageParent::CrmContact(_) => None,diff --git a/crates/agent_harness/src/outbound/channel_prompt_context.rs b/crates/agent_harness/src/outbound/channel_prompt_context.rsindex f0ef05e199..6539e68035 100644--- a/crates/agent_harness/src/outbound/channel_prompt_context.rs+++ b/crates/agent_harness/src/outbound/channel_prompt_context.rs@@ -57,6 +57,7 @@ impl<Access: EntityAccessService> ContextAuthorizer for Access {MessageParent::Initiative(_) => EntityType::Initiative,MessageParent::CrmCompany(_) => EntityType::CrmCompany,MessageParent::CrmContact(_) => EntityType::CrmContact,+ MessageParent::Call(_) => EntityType::Call,},).awaitdiff --git a/crates/agent_session/src/domain/events.rs b/crates/agent_session/src/domain/events.rsindex 9ebe6d62b6..bd4eb17c3b 100644--- a/crates/agent_session/src/domain/events.rs+++ b/crates/agent_session/src/domain/events.rs@@ -47,6 +47,7 @@ impl ThreadOrigin {let channel_id = match &parent {MessageParent::Channel(channel_id) => Some(*channel_id),MessageParent::Document(_)+ | MessageParent::Call(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)| MessageParent::CrmContact(_) => None,diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 0da6a76807..e369d26c54 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -634,6 +634,7 @@ impl AgentSessionResponse {Some(messages::domain::models::MessageParent::Channel(channel_id)) => Some(*channel_id),Some(messages::domain::models::MessageParent::Document(_)+ | messages::domain::models::MessageParent::Call(_)| messages::domain::models::MessageParent::Initiative(_)| messages::domain::models::MessageParent::CrmCompany(_)| messages::domain::models::MessageParent::CrmContact(_),diff --git a/crates/agent_session/src/outbound/connection_gateway_realtime.rs b/crates/agent_session/src/outbound/connection_gateway_realtime.rsindex 8feb4c2348..d97847e865 100644--- a/crates/agent_session/src/outbound/connection_gateway_realtime.rs+++ b/crates/agent_session/src/outbound/connection_gateway_realtime.rs@@ -235,6 +235,7 @@ impl crate::domain::audience::SessionSubscriptions for ConnectionGatewaySessionSMessageParent::Initiative(_) => GatewayEntityType::Initiative,MessageParent::CrmCompany(_) => GatewayEntityType::CrmCompany,MessageParent::CrmContact(_) => GatewayEntityType::CrmContact,+ MessageParent::Call(_) => GatewayEntityType::Call,};users.extend(self.0diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex ee497c44e4..58051e8f3f 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -2412,6 +2412,7 @@ async fn a_document_session_preserves_its_origin_and_inherits_live_document_accelet parent = MessageParent::parse("document", &document_id).unwrap();let root = messages.create(CreateMessage {+ canonical_root_id: None,parent: parent.clone(),actor: OWNER.to_owned().try_into().unwrap(),triggered_by: None,diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rsindex b51e3e7542..1d127c971b 100644--- a/crates/agent_trigger/src/domain/broker_events.rs+++ b/crates/agent_trigger/src/domain/broker_events.rs@@ -353,6 +353,7 @@ impl AgentSessionMacroEvent {})?,),MessageParent::Document(_)+ | MessageParent::Call(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)| MessageParent::CrmContact(_) => None,diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rsindex 21700ead01..c30e12ca83 100644--- a/crates/agent_trigger/src/domain/processing.rs+++ b/crates/agent_trigger/src/domain/processing.rs@@ -126,6 +126,7 @@ where}(MessageParent::Document(_)+ | MessageParent::Call(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)| MessageParent::CrmContact(_),diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rsindex cc60969e44..d2fc6713fe 100644--- a/crates/agent_trigger/src/domain/service.rs+++ b/crates/agent_trigger/src/domain/service.rs@@ -250,14 +250,18 @@ whereif !agent.bot.has_agent {return Ok(false);}- // Channel selection restricts channel placement. Discussion invocation- // requires ownership or team membership and is independently bounded- // by the invoking user's parent access at execution time.- if parent.is_discussion() {- return self.owner_allows(caller, agent.bot.owner.as_ref()).await;- }- let MessageParent::Channel(channel_id) = parent else {- unreachable!()+ // Channel selection restricts channel placement. Other conversations,+ // including call chat, require ownership or team membership and are+ // bounded by the invoking user's parent access at execution time.+ let channel_id = match parent {+ MessageParent::Channel(channel_id) => channel_id,+ MessageParent::Document(_)+ | MessageParent::Initiative(_)+ | MessageParent::CrmCompany(_)+ | MessageParent::CrmContact(_)+ | MessageParent::Call(_) => {+ return self.owner_allows(caller, agent.bot.owner.as_ref()).await;+ }};return match agent.channel_scope {AgentChannelScope::All => match agent.bot.owner {@@ -292,9 +296,8 @@ whereMessageParent::Document(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)- | MessageParent::CrmContact(_) => {- self.owner_allows(caller, bot.owner.as_ref()).await- }+ | MessageParent::CrmContact(_)+ | MessageParent::Call(_) => self.owner_allows(caller, bot.owner.as_ref()).await,},}}diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex e0a934e6cb..f3d696994d 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -2,6 +2,7 @@ use super::*;#[cfg(feature = "admission")]mod admission;+mod call;mod task_assignment;use agent_session::domain::error::AgentSessionError;@@ -217,6 +218,7 @@ fn allow_invocation(role: ParticipantRole::Member,},MessageParent::Document(_)+ | MessageParent::Call(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)| MessageParent::CrmContact(_) => EntityPermission::AccessLevel {diff --git a/crates/agent_trigger/src/domain/service/test/call.rs b/crates/agent_trigger/src/domain/service/test/call.rsnew file mode 100644index 0000000000..9698b0ffb4--- /dev/null+++ b/crates/agent_trigger/src/domain/service/test/call.rs@@ -0,0 +1,197 @@+use super::*;++fn call_message(first: bool) -> MessagePostedMetadata {+ let call_id = Uuid::from_u128(901);+ MessagePostedMetadata {+ parent: MessageParent::Call(call_id),+ message_id: if first { call_id } else { Uuid::from_u128(902) },+ thread_id: (!first).then_some(call_id),+ root_id: call_id,+ ..message(vec![mention_of(BotId::TEST_A)])+ }+}++#[tokio::test]+async fn system_mentions_in_first_and_later_call_messages_preserve_the_call_root() {+ for first in [true, false] {+ let posted = call_message(first);+ let mut history = MockThreadHistory::new();+ history+ .expect_authorize_invocation()+ .withf(|actor, parent, root| actor == &user() && parent == &MessageParent::Call(*root))+ .once()+ .returning(allow_invocation);+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .return_once(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot()+ .once()+ .return_once(|id| Box::pin(async move { Ok(Some(system_bot(id))) }));+ let (replies, judge) = no_implicit();+ let service = service_reading(sessions_without_existing(), bots, replies, judge, history);++ let events = service.evaluate(&posted).await.unwrap();+ let [TriggerDecision::Open { bot_id, message }] = events.as_slice() else {+ panic!("expected a new call agent session, got {events:?}");+ };+ assert_eq!(*bot_id, BotId::TEST_A);+ assert_eq!(message, &posted);+ assert_eq!(message.parent, MessageParent::Call(message.root_id()));+ }+}++#[tokio::test]+async fn call_mentions_require_the_private_agents_owner_for_either_channel_scope() {+ for scope in [AgentChannelScope::All, AgentChannelScope::Selected] {+ for is_owner in [true, false] {+ let mut posted = call_message(false);+ if !is_owner {+ posted.sender = ChannelSender::new_from_user(+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ );+ }+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent().once().return_once(move |id| {+ Box::pin(async move {+ let mut agent = private_agent(id);+ agent.channel_scope = scope;+ Ok(Some(agent))+ })+ });++ assert_eq!(mention_yields_event(&posted, bots).await, is_owner);+ }+ }+}++#[tokio::test]+async fn call_mentions_require_membership_of_the_agents_team_for_either_channel_scope() {+ for scope in [AgentChannelScope::All, AgentChannelScope::Selected] {+ for is_member in [true, false] {+ let team_id = Uuid::from_u128(99);+ let mut facts = FactMocks::from(MockAgentBotLookup::new());+ facts.bots.expect_get_agent().once().return_once(move |id| {+ Box::pin(async move { Ok(Some(agent_with(id, BotOwner::Team { team_id }, scope))) })+ });+ facts+ .teams+ .expect_user_has_team()+ .with(+ mockall::predicate::eq(user()),+ mockall::predicate::eq(team_id),+ )+ .once()+ .return_once(move |_, _| Box::pin(async move { Ok(is_member) }));++ assert_eq!(+ mention_yields_event(&call_message(false), facts).await,+ is_member+ );+ }+ }+}++#[tokio::test]+async fn legacy_agent_backed_bots_in_calls_use_owner_authorization() {+ for is_owner in [true, false] {+ let mut posted = call_message(false);+ if !is_owner {+ posted.sender = ChannelSender::new_from_user(+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ );+ }+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .return_once(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot().once().return_once(|id| {+ Box::pin(async move {+ Ok(Some(owned_bot(+ id,+ BotOwner::User {+ user_id: user().to_string(),+ },+ )))+ })+ });+ assert_eq!(mention_yields_event(&posted, bots).await, is_owner);+ }+}++#[tokio::test]+async fn removed_bots_and_bots_without_agents_cannot_be_invoked_in_calls() {+ for present in [true, false] {+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .return_once(|_| Box::pin(async { Ok(None) }));+ bots.expect_get_bot().once().return_once(move |id| {+ Box::pin(async move {+ Ok(present.then(|| {+ let mut bot = system_bot(id);+ bot.has_agent = false;+ bot+ }))+ })+ });+ assert!(!mention_yields_event(&call_message(false), bots).await);+ }+}++#[tokio::test]+async fn call_mentions_route_followups_to_the_session_at_the_call_root() {+ let posted = call_message(false);+ let mut existing = session(AgentSessionId::TEST_A, BotId::TEST_A);+ existing.thread_parent = Some(posted.parent.clone());+ existing.thread_id = Some(posted.root_id());+ let mut sessions = MockAgentSessionRepo::new();+ sessions+ .expect_find_for_thread()+ .with(+ mockall::predicate::eq(Some(posted.root_id())),+ mockall::predicate::eq(Some(BotId::TEST_A)),+ )+ .once()+ .return_once(move |_, _| {+ Box::pin(async move { Ok(ThreadSession::CreatedFromThread(existing)) })+ });+ let mut bots = MockAgentBotLookup::new();+ bots.expect_get_agent()+ .once()+ .return_once(|id| Box::pin(async move { Ok(Some(private_agent(id))) }));+ let (replies, judge) = no_implicit();++ let events = service(sessions, bots, replies, judge)+ .evaluate(&posted)+ .await+ .unwrap();+ let decision = existing_channel_metadata(&events);+ assert_eq!(decision.session_id, AgentSessionId::TEST_A);+ assert_eq!(decision.kind, ThreadMessageKind::MentionThread);+ assert_eq!(decision.message, posted);+}++#[tokio::test]+async fn queued_call_mentions_cannot_invoke_after_write_access_is_revoked() {+ let mut history = MockThreadHistory::new();+ history+ .expect_authorize_invocation()+ .once()+ .return_once(|_, _, _| Box::pin(async { Ok(None) }));+ let (replies, judge) = no_implicit();+ let service = service_reading(+ MockAgentSessionRepo::new(),+ MockAgentBotLookup::new(),+ replies,+ judge,+ history,+ );+ assert!(+ service+ .evaluate(&call_message(false))+ .await+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/agent_trigger/src/outbound/message_thread_history.rs b/crates/agent_trigger/src/outbound/message_thread_history.rsindex cff10181c4..dd17a9cc56 100644--- a/crates/agent_trigger/src/outbound/message_thread_history.rs+++ b/crates/agent_trigger/src/outbound/message_thread_history.rs@@ -43,6 +43,7 @@ impl<Access: EntityAccessService> InvocationAuthorizer for Access {MessageParent::Initiative(_) => EntityType::Initiative,MessageParent::CrmCompany(_) => EntityType::CrmCompany,MessageParent::CrmContact(_) => EntityType::CrmContact,+ MessageParent::Call(_) => EntityType::Call,},).awaitdiff --git a/crates/agent_trigger/src/outbound/message_thread_history/test.rs b/crates/agent_trigger/src/outbound/message_thread_history/test.rsindex a55e990066..a508fc493c 100644--- a/crates/agent_trigger/src/outbound/message_thread_history/test.rs+++ b/crates/agent_trigger/src/outbound/message_thread_history/test.rs@@ -20,7 +20,7 @@ impl InvocationAuthorizer for Authorizer {EntityAccessReceipt::try_new_authenticated_user(user.clone(),Entity {- entity_type: EntityType::Document,+ entity_type: parent.access_entity_type(),entity_id: parent.entity_id(),},EntityPermission::AccessLevel {@@ -115,6 +115,34 @@ async fn revoked_write_permission_yields_no_invocation_or_read() {);}+#[tokio::test]+async fn call_history_uses_the_call_receipt_and_canonical_root() {+ let mut reader = MockMessageReader::new();+ reader+ .expect_get_thread()+ .once()+ .withf(|access, id| {+ access.entity().entity_id == root().to_string()+ && access.entity().entity_type == EntityType::Call+ && access.get_authenticated_user().unwrap() == &user()+ && *id == root()+ })+ .return_once(|_, _| Err(MessageError::NotFound));+ let history = MessageThreadHistory::new(Arc::new(reader), Authorizer { allowed: true });+ let invocation = history+ .authorize_invocation(&user(), &MessageParent::Call(root()), root())+ .await+ .unwrap()+ .unwrap();+ assert!(+ history+ .thread_messages(&invocation)+ .await+ .unwrap()+ .is_empty()+ );+}+#[tokio::test]async fn deleted_thread_uses_the_application_lifecycle_rule() {let mut reader = MockMessageReader::new();diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rsindex a777390f03..0611fab882 100644--- a/crates/call/src/domain/ports.rs+++ b/crates/call/src/domain/ports.rs@@ -201,7 +201,7 @@ pub trait CallRepository: Send + Sync + 'static {user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<CallParticipant, AddParticipantError>> + Send;- /// Commit authenticated link participation and grant view access to this call only.+ /// Commit authenticated link participation and grant comment access to this call only, enabling chat.fn add_meeting_participant<'a>(&self,call_id: &Uuid,diff --git a/crates/call/src/domain/service/meetings.rs b/crates/call/src/domain/service/meetings.rsindex a117f5c30c..7c8ce9ff06 100644--- a/crates/call/src/domain/service/meetings.rs+++ b/crates/call/src/domain/service/meetings.rs@@ -1,4 +1,4 @@-//! Invitation use cases. Guests receive room access; signed-in attendees also receive call-only View access.+//! Invitation use cases. Guests receive room access; signed-in attendees also receive call-only Comment access for chat.use super::*;use crate::domain::meetings::{diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rsindex 03e6959f17..c65cd27d4e 100644--- a/crates/call/src/outbound/pg_call_repo.rs+++ b/crates/call/src/outbound/pg_call_repo.rs@@ -637,7 +637,7 @@ impl CallRepository for PgCallRepo {"INSERT INTO call_participants (call_id, user_id) VALUES ($1, $2) ON CONFLICT (call_id, user_id) DO UPDATE SET left_at = NULL, joined_at = now() RETURNING call_id, user_id, joined_at",call_id, user_id.as_ref(),).fetch_one(tx.as_mut()).await.map_err(classify_add_participant_err)?;- entity_access_db_utils::ensure_call_participant_view_access(+ entity_access_db_utils::ensure_call_participant_comment_access(tx.as_mut(),call_id,user_id.copied(),diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rsindex d53cbc1eac..aa39a5a8a6 100644--- a/crates/call/src/outbound/pg_call_repo/test.rs+++ b/crates/call/src/outbound/pg_call_repo/test.rs@@ -3465,7 +3465,7 @@ async fn authenticated_meeting_attendee_gets_only_call_access_and_owner_keeps_owrepo.add_meeting_participant(&call.id, USER_B.deref().copied()).await?;for (user, expected) in [- (attendee.as_ref(), AccessLevel::View),+ (attendee.as_ref(), AccessLevel::Comment),(USER_B.as_ref(), AccessLevel::Owner),] {let level = sqlx::query_scalar!(diff --git a/crates/channel_bots/src/domain/service.rs b/crates/channel_bots/src/domain/service.rsindex 6f067d6613..bab62cd1b9 100644--- a/crates/channel_bots/src/domain/service.rs+++ b/crates/channel_bots/src/domain/service.rs@@ -386,8 +386,8 @@ where////// The invoking user's current access to the parent gates every read, and/// the live trigger must still sit in the thread the event claims. When- /// the mention is a thread reply or a document discussion, the thread is- /// the primary context and nearby channel messages are demoted to a+ /// the mention is a thread reply or belongs to a non-channel parent, its+ /// thread is the primary context and nearby channel messages are demoted to a/// clearly labeled background block. For a top-level channel mention, the/// chronological channel slice is the primary context. In both cases the/// triggering message is marked inline rather than repeated at the end.@@ -428,12 +428,12 @@ where);let mut prompt = format!("Conversation parent: {}\n", serde_json::to_string(parent)?);- // A document discussion is a thread from its root; a top-level channel- // message is the channel's own timeline.+ // Entity discussions and call chat are threads from their roots;+ // top-level channel messages use the channel's own timeline.let thread_root = event.message.thread_id- .or_else(|| parent.is_discussion().then_some(trigger_id));+ .or_else(|| (!matches!(parent, MessageParent::Channel(_))).then_some(trigger_id));if let Some(root_id) = thread_root {let place = match parent {MessageParent::Channel(_) => "a channel thread",@@ -441,6 +441,7 @@ whereMessageParent::Initiative(_) => "a project discussion",MessageParent::CrmCompany(_) => "a CRM company discussion",MessageParent::CrmContact(_) => "a CRM contact discussion",+ MessageParent::Call(_) => "a call chat",};let (intro, thread_instruction, marker) = match event.trigger {BotTrigger::Mention => (diff --git a/crates/channel_bots/src/domain/service/tests.rs b/crates/channel_bots/src/domain/service/tests.rsindex 778705b775..d09f6b9b06 100644--- a/crates/channel_bots/src/domain/service/tests.rs+++ b/crates/channel_bots/src/domain/service/tests.rs@@ -183,6 +183,66 @@ async fn root_comment_is_valid_agent_context_before_any_replies_exist() {assert!(prompt.contains("<thread>"));}+#[tokio::test]+async fn call_mentions_use_the_same_call_thread_for_context_and_replies() {+ for is_first_message in [true, false] {+ let parent = MessageParent::Call(Uuid::from_u128(1));+ let mut root = message(1, None, "Call agenda");+ root.parent = parent.clone();+ let mut trigger = if is_first_message {+ message(1, None, "@macro help with this call")+ } else {+ message(2, Some(root.id), "@macro help with this call")+ };+ trigger.parent = parent.clone();+ let history = if is_first_message {+ thread(trigger.clone(), vec![])+ } else {+ thread(root, vec![trigger.clone()])+ };+ let mut api = MockMessageServiceApi::new();+ configure_reads(&mut api, &trigger, history);+ let reply_parent = parent.clone();+ api.expect_post().once().returning(move |access, input| {+ assert_eq!(+ access.entity().entity_type,+ reply_parent.access_entity_type()+ );+ assert_eq!(access.entity().entity_id, reply_parent.entity_id());+ assert_eq!(access.acting_user_id(), Some(&user()));+ assert_eq!(input.thread_id, Some(Uuid::from_u128(1)));+ assert_eq!(input.content, THINKING_MESSAGE);+ let mut reply = message(3, input.thread_id, &input.content);+ reply.parent = reply_parent.clone();+ Ok(reply)+ });+ api.expect_patch()+ .once()+ .returning(move |access, id, input| {+ assert_eq!(access.entity().entity_id, parent.entity_id());+ assert_eq!(id, Uuid::from_u128(3));+ assert_eq!(input.content.as_deref(), Some("the call answer"));+ let mut reply = message(3, Some(Uuid::from_u128(1)), "the call answer");+ reply.parent = parent.clone();+ Ok(reply)+ });+ let responder = responder("the call answer");+ handler(api, Arc::new(Access::default()), responder.clone())+ .handle(&invocation(&trigger))+ .await+ .unwrap();+ let prompts = responder.prompts.lock().unwrap();+ assert_eq!(prompts.len(), 1);+ assert!(prompts[0].contains("mentioned you (@macro) in a call chat."));+ assert!(prompts[0].contains("<thread>"));+ assert!(!prompts[0].contains("<channel_context>"));+ assert_eq!(prompts[0].matches("@macro help with this call").count(), 1);+ if !is_first_message {+ assert!(prompts[0].contains("Call agenda"));+ }+ }+}+#[tokio::test]async fn an_anchored_discussion_names_the_text_it_marks() {let trigger = message(1, None, "@macro what is this anchored to?");@@ -329,34 +389,40 @@ async fn a_pdf_pin_discussion_says_it_covers_no_words() {}#[tokio::test]-async fn revoked_document_access_prevents_context_reads_and_agent_work() {- let trigger = message(1, None, "@macro help");- let access = Arc::new(Access::default());- access.revoke();- let responder = responder("reply");- let handler = handler(MockMessageServiceApi::new(), access, responder.clone());- assert!(handler.handle(&invocation(&trigger)).await.is_err());- assert!(responder.prompts.lock().unwrap().is_empty());+async fn revoked_parent_access_prevents_context_reads_and_agent_work() {+ for parent in [parent(), MessageParent::Call(Uuid::from_u128(1))] {+ let mut trigger = message(1, None, "@macro help");+ trigger.parent = parent;+ let access = Arc::new(Access::default());+ access.revoke();+ let responder = responder("reply");+ let handler = handler(MockMessageServiceApi::new(), access, responder.clone());+ assert!(handler.handle(&invocation(&trigger)).await.is_err());+ assert!(responder.prompts.lock().unwrap().is_empty());+ }}#[tokio::test]async fn revocation_while_model_runs_prevents_answer_delivery() {- let trigger = message(1, None, "@macro help");- let mut api = MockMessageServiceApi::new();- configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));- expect_placeholder(&mut api);- let access = Arc::new(Access::default());- let responder = Arc::new(Responder {- prompts: Mutex::new(vec![]),- revoke: Some(access.clone()),- result: "private answer",- });- assert!(- handler(api, access, responder)- .handle(&invocation(&trigger))- .await- .is_err()- );+ for parent in [parent(), MessageParent::Call(Uuid::from_u128(1))] {+ let mut trigger = message(1, None, "@macro help");+ trigger.parent = parent;+ let mut api = MockMessageServiceApi::new();+ configure_reads(&mut api, &trigger, thread(trigger.clone(), vec![]));+ expect_placeholder(&mut api);+ let access = Arc::new(Access::default());+ let responder = Arc::new(Responder {+ prompts: Mutex::new(vec![]),+ revoke: Some(access.clone()),+ result: "private answer",+ });+ assert!(+ handler(api, access, responder)+ .handle(&invocation(&trigger))+ .await+ .is_err()+ );+ }}#[tokio::test]diff --git a/crates/channel_bots/src/domain/test.rs b/crates/channel_bots/src/domain/test.rsindex 782cb74f48..f75fbab754 100644--- a/crates/channel_bots/src/domain/test.rs+++ b/crates/channel_bots/src/domain/test.rs@@ -156,6 +156,7 @@ impl Access {}Ok(match parent {MessageParent::Document(_)+ | MessageParent::Call(_)| MessageParent::Initiative(_)| MessageParent::CrmCompany(_)| MessageParent::CrmContact(_) => (diff --git a/crates/channel_bots/src/outbound/conversation/test.rs b/crates/channel_bots/src/outbound/conversation/test.rsindex 6b637e0989..1b11b824dc 100644--- a/crates/channel_bots/src/outbound/conversation/test.rs+++ b/crates/channel_bots/src/outbound/conversation/test.rs@@ -28,7 +28,7 @@ fn posted(parent: MessageParent, bot: bool) -> MessageEvent {}}#[tokio::test]-async fn user_posts_from_both_parents_dispatch_once_and_bot_responses_never_reenter() {+async fn user_posts_dispatch_once_and_bot_responses_never_reenter() {let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();let delivery = Delivery::default();let publisher = messages::domain::effects::MessageEffects::new(@@ -39,6 +39,7 @@ async fn user_posts_from_both_parents_dispatch_once_and_bot_responses_never_reenfor parent in [MessageParent::Channel(uuid::Uuid::from_u128(900)),MessageParent::parse("document", "doc").unwrap(),+ MessageParent::Call(uuid::Uuid::from_u128(1)),] {publisher.publish(posted(parent.clone(), false))@@ -49,7 +50,7 @@ async fn user_posts_from_both_parents_dispatch_once_and_bot_responses_never_reenpublisher.publish(posted(parent, true)).await.unwrap();assert!(receiver.try_recv().is_err());}- assert_eq!(delivery.0.lock().unwrap().len(), 4);+ assert_eq!(delivery.0.lock().unwrap().len(), 6);}#[tokio::test]async fn closed_agent_receiver_does_not_suppress_realtime_and_notification_delivery() {diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex c4064e3f98..2f88d6d399 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -76,6 +76,7 @@ impl WorkExecutor for Dispatcher {Some(*channel_id)}messages::domain::models::MessageParent::Document(_)+ | messages::domain::models::MessageParent::Call(_)| messages::domain::models::MessageParent::Initiative(_)| messages::domain::models::MessageParent::CrmCompany(_)| messages::domain::models::MessageParent::CrmContact(_) => None,diff --git a/crates/crm/src/outbound/lookup.rs b/crates/crm/src/outbound/lookup.rsindex 4b57cdaf8b..7676a4ccba 100644--- a/crates/crm/src/outbound/lookup.rs+++ b/crates/crm/src/outbound/lookup.rs@@ -91,7 +91,8 @@ impl CrmParentReader for PgCrmParentReader {MessageParent::CrmContact(id) => self.contact(id).await?,MessageParent::Channel(_)| MessageParent::Document(_)- | MessageParent::Initiative(_) => None,+ | MessageParent::Initiative(_)+ | MessageParent::Call(_) => None,};Ok(facts)})diff --git a/crates/crm/src/outbound/lookup/test/message_store.rs b/crates/crm/src/outbound/lookup/test/message_store.rsindex f4c2537a4e..74c9e23e7d 100644--- a/crates/crm/src/outbound/lookup/test/message_store.rs+++ b/crates/crm/src/outbound/lookup/test/message_store.rs@@ -224,6 +224,7 @@ async fn crm_discussion_lifecycle_cascades_on_company_deletion(pool: PgPool) {&& !residual.mentions);let late = CreateMessage {+ canonical_root_id: None,parent: company,actor: USER.to_owned().try_into().unwrap(),triggered_by: None,diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rsindex d3029276ae..c139df2b86 100644--- a/crates/entity_access/src/domain/models.rs+++ b/crates/entity_access/src/domain/models.rs@@ -399,6 +399,30 @@ pub struct Entity {pub entity_type: EntityType,}+/// A live conversation whose current access can be inherited by its agent session.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum AgentSessionParent {+ /// Document discussion, including documents with legacy string identifiers.+ Document(String),+ /// Call chat, identified by the active or archived call.+ Call(Uuid),+}++impl From<AgentSessionParent> for Entity {+ fn from(parent: AgentSessionParent) -> Self {+ match parent {+ AgentSessionParent::Document(entity_id) => Self {+ entity_id,+ entity_type: EntityType::Document,+ },+ AgentSessionParent::Call(call_id) => Self {+ entity_id: call_id.to_string(),+ entity_type: EntityType::Call,+ },+ }+ }+}+/// Authentication context retained for a bot entity-access receipt.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct BotReceiptAuth {diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rsindex c3597c9075..80a6151bb1 100644--- a/crates/entity_access/src/domain/ports.rs+++ b/crates/entity_access/src/domain/ports.rs@@ -4,9 +4,9 @@use super::models::EntityType;use crate::domain::models::{- AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, ChannelRoleResult,- CrmEntityAccess, EntityAccessReceipt, EntityPermission, RequiredPermission, TeamRole,- UserTeamInfo, ViewAccessLevel,+ AccessError, AccessLevel, AgentSessionParent, BotAccessScope, BotId, CallChannelInfo,+ ChannelRoleResult, CrmEntityAccess, EntityAccessReceipt, EntityPermission, RequiredPermission,+ TeamRole, UserTeamInfo, ViewAccessLevel,};#[cfg(feature = "explain_binary")]use crate::domain::models::{AccessExplanation, AccessGrant};@@ -97,12 +97,12 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {user_id: &MacroUserId<Lowercase<'_>>,) -> impl Future<Output = Result<Vec<Uuid>, AccessError>> + Send;- /// Document owning an agent session's still-live originating message thread.+ /// Supported parent owning an agent session's still-live originating message thread./// This is a persisted relationship, not a caller-supplied grant.- fn get_agent_session_document(+ fn get_agent_session_parent(&self,agent_session_id: &str,- ) -> impl Future<Output = Result<Option<String>, AccessError>> + Send;+ ) -> impl Future<Output = Result<Option<AgentSessionParent>, AccessError>> + Send;/// Get the access level a user has for a reminder.///diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rsindex a43f833553..763465692d 100644--- a/crates/entity_access/src/domain/service.rs+++ b/crates/entity_access/src/domain/service.rs@@ -4,9 +4,9 @@ use std::{collections::HashMap, marker::PhantomData, str::FromStr};use crate::domain::{models::{- AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, ChannelRoleResult,- CrmEntityAccess, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,- EntityType, RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,+ AccessError, AccessLevel, AgentSessionParent, BotAccessScope, BotId, CallChannelInfo,+ ChannelRoleResult, CrmEntityAccess, Entity, EntityAccessAuth, EntityAccessReceipt,+ EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,},ports::{AccessRepository, EntityAccessService, ScheduledActionGrants},};@@ -55,17 +55,20 @@ where.repo.get_agent_session_access(entity_id, user_id).await?;- let inherited = if let Some(document) =- self.repo.get_agent_session_document(entity_id).await?- {- self.repo- .get_document_access(&document, user_id)- .await?- .map(session_permission_from_document)- } else {- None+ let parent_access = match self.repo.get_agent_session_parent(entity_id).await? {+ Some(AgentSessionParent::Document(document)) => {+ self.repo.get_document_access(&document, user_id).await?+ }+ // Call history and chat require sign-in, including public+ // call links. Their sessions inherit the same boundary.+ Some(AgentSessionParent::Call(call_id)) if user_id.is_some() => {+ self.repo+ .get_call_access(&call_id.to_string(), user_id)+ .await?+ }+ Some(AgentSessionParent::Call(_)) | None => None,};- Ok(direct.max(inherited))+ Ok(direct.max(parent_access.map(session_permission_from_parent)))}EntityType::Initiative => self.repo.get_initiative_access(entity_id, user_id).await,EntityType::ScheduledAction => {@@ -211,8 +214,9 @@ where}EntityType::AgentSession => {let direct = self.repo.get_team_entity_access(bot_id, team_id, entity_id, entity_type).await?;- let inherited = if let Some(document) = self.repo.get_agent_session_document(entity_id).await? {- self.repo.get_team_entity_access(bot_id, team_id, &document, EntityType::Document).await?.map(session_permission_from_document)+ let inherited = if let Some(parent) = self.repo.get_agent_session_parent(entity_id).await? {+ let parent: Entity = parent.into();+ self.repo.get_team_entity_access(bot_id, team_id, &parent.entity_id, parent.entity_type).await?.map(session_permission_from_parent)} else { None };Ok(EntityPermission::AccessLevel { access_level: direct.max(inherited).ok_or(AccessError::Unauthorized)? })}@@ -713,7 +717,7 @@ mod test;// Commenters can prompt the agent; viewers can inspect the response. Parent// ownership never confers session ownership or permission to delete it.-fn session_permission_from_document(level: AccessLevel) -> AccessLevel {+fn session_permission_from_parent(level: AccessLevel) -> AccessLevel {if level >= AccessLevel::Comment {AccessLevel::Edit} else {diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rsindex 6063fd763b..7a4901d07f 100644--- a/crates/entity_access/src/domain/service/test.rs+++ b/crates/entity_access/src/domain/service/test.rs@@ -2,6 +2,8 @@#[allow(unused_imports)]use super::*;++mod call_session;use crate::domain::models::{AdminParticipantRole, AdminTeamRole, AnyEntityPermission, BotAccessScope, BotId,BotReceiptScope, CallChannelInfo, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,@@ -32,9 +34,11 @@ struct MockRepo {initiative_access: Arc<Mutex<Option<AccessLevel>>>,scheduled_action_access: Arc<Mutex<Option<AccessLevel>>>,accessible_scheduled_action_ids: Arc<Mutex<Vec<Uuid>>>,- agent_session_document: Arc<Mutex<Option<String>>>,+ agent_session_parent: Arc<Mutex<Option<AgentSessionParent>>>,reminder_access: Arc<Mutex<Option<AccessLevel>>>,team_entity_access: Arc<Mutex<Option<AccessLevel>>>,+ team_agent_session_access: Arc<Mutex<Option<AccessLevel>>>,+ team_entity_requests: Arc<Mutex<Vec<(String, EntityType)>>>,team_entity_access_calls: Arc<AtomicUsize>,team_channel_role: Arc<Mutex<ChannelRoleResult>>,team_channel_role_calls: Arc<AtomicUsize>,@@ -73,9 +77,11 @@ impl MockRepo {initiative_access: Arc::new(Mutex::new(None)),scheduled_action_access: Arc::new(Mutex::new(None)),accessible_scheduled_action_ids: Arc::new(Mutex::new(Vec::new())),- agent_session_document: Arc::default(),+ agent_session_parent: Arc::default(),reminder_access: Arc::new(Mutex::new(None)),team_entity_access: Arc::new(Mutex::new(None)),+ team_agent_session_access: Arc::default(),+ team_entity_requests: Arc::default(),team_entity_access_calls: Arc::new(AtomicUsize::new(0)),team_channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),team_channel_role_calls: Arc::new(AtomicUsize::new(0)),@@ -240,8 +246,11 @@ impl MockRepo {}impl AccessRepository for MockRepo {- async fn get_agent_session_document(&self, _: &str) -> Result<Option<String>, AccessError> {- Ok(self.agent_session_document.lock().await.clone())+ async fn get_agent_session_parent(+ &self,+ _: &str,+ ) -> Result<Option<AgentSessionParent>, AccessError> {+ Ok(self.agent_session_parent.lock().await.clone())}async fn get_document_access(@@ -370,10 +379,17 @@ impl AccessRepository for MockRepo {&self,_bot_id: BotId,_team_id: Uuid,- _entity_id: &str,- _entity_type: EntityType,+ entity_id: &str,+ entity_type: EntityType,) -> Result<Option<AccessLevel>, AccessError> {self.team_entity_access_calls.fetch_add(1, Ordering::SeqCst);+ self.team_entity_requests+ .lock()+ .await+ .push((entity_id.into(), entity_type));+ if entity_type == EntityType::AgentSession {+ return Ok(*self.team_agent_session_access.lock().await);+ }Ok(*self.team_entity_access.lock().await)}@@ -2276,7 +2292,7 @@ async fn test_get_users_by_entity_project_with_many_users() {#[tokio::test]async fn document_session_access_tracks_current_document_permission() {let repo = MockRepo::new();- *repo.agent_session_document.lock().await = Some("doc".into());+ *repo.agent_session_parent.lock().await = Some(AgentSessionParent::Document("doc".into()));let service = EntityAccessServiceImpl::new(repo.clone());for (permission, expected) in [(Some(AccessLevel::View), Some(AccessLevel::View)),diff --git a/crates/entity_access/src/domain/service/test/call_session.rs b/crates/entity_access/src/domain/service/test/call_session.rsnew file mode 100644index 0000000000..3a457a643f--- /dev/null+++ b/crates/entity_access/src/domain/service/test/call_session.rs@@ -0,0 +1,179 @@+use super::*;++#[tokio::test]+async fn public_call_permissions_do_not_grant_anonymous_session_access() {+ let repo = MockRepo::new();+ *repo.agent_session_parent.lock().await = Some(AgentSessionParent::Call(Uuid::now_v7()));+ let service = EntityAccessServiceImpl::new(repo.clone());+ for permission in [AccessLevel::View, AccessLevel::Comment, AccessLevel::Edit] {+ *repo.call_access.lock().await = Some(permission);+ assert_eq!(+ service+ .get_access_level(None, "session", EntityType::AgentSession)+ .await+ .unwrap(),+ None+ );+ assert!(matches!(+ service+ .get_entity_permission(None, "session", EntityType::AgentSession, None)+ .await,+ Err(AccessError::Unauthorized)+ ));+ }+}++#[tokio::test]+async fn directly_shared_public_sessions_keep_their_own_access_without_inheriting_call_access() {+ let repo = MockRepo::new().with_call_access(AccessLevel::Comment);+ *repo.agent_session_parent.lock().await = Some(AgentSessionParent::Call(Uuid::now_v7()));+ *repo.agent_session_access.lock().await = Some(AccessLevel::View);+ let service = EntityAccessServiceImpl::new(repo);+ assert_eq!(+ service+ .get_entity_permission(None, "session", EntityType::AgentSession, None)+ .await+ .unwrap(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ }+ );+}++#[tokio::test]+async fn call_session_access_tracks_current_call_permission_and_preserves_owner_grants() {+ let repo = MockRepo::new();+ let call_id = Uuid::now_v7();+ *repo.agent_session_parent.lock().await = Some(AgentSessionParent::Call(call_id));+ let service = EntityAccessServiceImpl::new(repo.clone());+ let user = test_user_id();+ for (permission, expected) in [+ (Some(AccessLevel::View), Some(AccessLevel::View)),+ (Some(AccessLevel::Comment), Some(AccessLevel::Edit)),+ (Some(AccessLevel::Edit), Some(AccessLevel::Edit)),+ (Some(AccessLevel::Owner), Some(AccessLevel::Edit)),+ (None, None),+ ] {+ *repo.call_access.lock().await = permission;+ assert_eq!(+ service+ .get_access_level(Some(&user), "session", EntityType::AgentSession)+ .await+ .unwrap(),+ expected+ );+ assert_eq!(+ service+ .generate_entity_access_receipt::<EditAccessLevel>(+ &user,+ None,+ "session",+ EntityType::AgentSession,+ )+ .await+ .is_ok(),+ expected == Some(AccessLevel::Edit)+ );+ }+ *repo.agent_session_access.lock().await = Some(AccessLevel::Owner);+ assert_eq!(+ service+ .get_access_level(Some(&user), "session", EntityType::AgentSession)+ .await+ .unwrap(),+ Some(AccessLevel::Owner)+ );+}++#[tokio::test]+async fn call_session_team_scope_tracks_current_parent_access() {+ let repo = MockRepo::new();+ let call_id = Uuid::now_v7();+ *repo.agent_session_parent.lock().await = Some(AgentSessionParent::Call(call_id));+ let service = EntityAccessServiceImpl::new(repo.clone());+ for (permission, expected) in [+ (Some(AccessLevel::View), Some(AccessLevel::View)),+ (Some(AccessLevel::Comment), Some(AccessLevel::Edit)),+ (Some(AccessLevel::Edit), Some(AccessLevel::Edit)),+ (Some(AccessLevel::Owner), Some(AccessLevel::Edit)),+ (None, None),+ ] {+ *repo.team_entity_access.lock().await = permission;+ repo.team_entity_requests.lock().await.clear();+ let receipt = service+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(+ test_bot_id(),+ test_bot_scope(),+ "session",+ EntityType::AgentSession,+ )+ .await;+ match expected {+ Some(access_level) => {+ let receipt = receipt.unwrap();+ assert_eq!(+ receipt.entity_permission(),+ &EntityPermission::AccessLevel { access_level }+ );+ assert_eq!(+ receipt.get_authenticated_bot_auth().unwrap().scope(),+ &BotReceiptScope::from(&test_bot_scope())+ );+ }+ None => assert!(matches!(receipt, Err(AccessError::Unauthorized))),+ }+ assert_eq!(+ *repo.team_entity_requests.lock().await,+ vec![+ ("session".into(), EntityType::AgentSession),+ (call_id.to_string(), EntityType::Call),+ ]+ );+ }+ *repo.team_agent_session_access.lock().await = Some(AccessLevel::Owner);+ let owner = service+ .generate_bot_entity_access_receipt::<OwnerAccessLevel>(+ test_bot_id(),+ test_bot_scope(),+ "session",+ EntityType::AgentSession,+ )+ .await+ .unwrap();+ assert_eq!(+ owner.entity_permission(),+ &EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner+ }+ );+}++#[tokio::test]+async fn a_missing_live_parent_never_inherits_unrelated_call_access() {+ let repo = MockRepo::new()+ .with_call_access(AccessLevel::Comment)+ .with_team_entity_access(AccessLevel::Comment);+ let service = EntityAccessServiceImpl::new(repo.clone());+ assert_eq!(+ service+ .get_access_level(Some(&test_user_id()), "session", EntityType::AgentSession)+ .await+ .unwrap(),+ None+ );+ assert!(matches!(+ service+ .generate_bot_entity_access_receipt::<ViewAccessLevel>(+ test_bot_id(),+ test_bot_scope(),+ "session",+ EntityType::AgentSession,+ )+ .await,+ Err(AccessError::Unauthorized)+ ));+ assert_eq!(+ *repo.team_entity_requests.lock().await,+ vec![("session".into(), EntityType::AgentSession)]+ );+}diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rsindex 9fa5a9255a..753264ac67 100644--- a/crates/entity_access/src/outbound/pg_access_repo.rs+++ b/crates/entity_access/src/outbound/pg_access_repo.rs@@ -10,8 +10,8 @@ mod test;use crate::domain::{models::{- AccessError, AccessLevel, BotId, CallChannelInfo, ChannelRoleResult, CrmEntityAccess,- EntityType, UserTeamInfo,+ AccessError, AccessLevel, AgentSessionParent, BotId, CallChannelInfo, ChannelRoleResult,+ CrmEntityAccess, EntityType, UserTeamInfo,},ports::AccessRepository,};@@ -234,22 +234,35 @@ impl AccessRepository for PgAccessRepository {Ok(queries::call_access::get_call_access(&self.pool, &call_uuid, &source_ids).await?)}- async fn get_agent_session_document(+ async fn get_agent_session_parent(&self,agent_session_id: &str,- ) -> Result<Option<String>, AccessError> {+ ) -> Result<Option<AgentSessionParent>, AccessError> {let session = agent_session_id.parse::<Uuid>().map_err(|_| AccessError::BadRequest("Invalid agent session ID format"))?;- Ok(sqlx::query_scalar!(- r#"SELECT m.parent_entity_id FROM agent_session s+ sqlx::query!(+ r#"SELECT m.parent_entity_type, m.parent_entity_id FROM agent_session sJOIN comms_messages m ON m.id = s.thread_idJOIN comms_message_threads t ON t.root_id = m.id- WHERE s.id = $1 AND m.parent_entity_type = 'document' AND t.deleted_at IS NULL"#,+ WHERE s.id = $1 AND m.parent_entity_type IN ('document', 'call')+ AND t.deleted_at IS NULL"#,session,).fetch_optional(&self.pool)- .await?)+ .await?+ .map(|parent| match parent.parent_entity_type.as_str() {+ "document" => Ok(AgentSessionParent::Document(parent.parent_entity_id)),+ "call" => parent+ .parent_entity_id+ .parse()+ .map(AgentSessionParent::Call)+ .map_err(|_| AccessError::internal("Agent session has an invalid call parent")),+ _ => Err(AccessError::internal(+ "Agent session has an unsupported parent",+ )),+ })+ .transpose()}async fn get_agent_session_access(diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rsindex c3729f9cb9..a6c3a3fa66 100644--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs@@ -1,8 +1,8 @@use super::PgAccessRepository;use crate::domain::{models::{- AccessError, AccessLevel, BotId, ChannelRoleResult, CrmEntityAccess, EntityType,- ParticipantRole, TeamRole,+ AccessError, AccessLevel, AgentSessionParent, BotId, ChannelRoleResult, CrmEntityAccess,+ EntityType, ParticipantRole, TeamRole,},ports::AccessRepository,};@@ -19,6 +19,9 @@ const TEAM_OWNER: &str = "macro|[email protected]";const USER_WITHOUT_TEAM: &str = "macro|[email protected]";const TEAM_BETA_OWNER: &str = "macro|[email protected]";+mod agent_session_parent;+mod channel_call_chat;+fn user_id(value: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(value.to_string()).unwrap()}diff --git a/crates/entity_access/src/outbound/pg_access_repo/test/agent_session_parent.rs b/crates/entity_access/src/outbound/pg_access_repo/test/agent_session_parent.rsnew file mode 100644index 0000000000..048de61e4b--- /dev/null+++ b/crates/entity_access/src/outbound/pg_access_repo/test/agent_session_parent.rs@@ -0,0 +1,80 @@+use super::*;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("user_team", "agent_session_sharing")+ )+)]+async fn session_parent_lookup_accepts_live_document_and_call_threads(pool: PgPool) {+ let repo = PgAccessRepository::new(pool.clone());+ let session = uuid::uuid!("60000000-0000-0000-0000-000000000001");+ for kind in ["document", "call", "initiative"] {+ let root = Uuid::now_v7();+ let parent_id = root.to_string();+ sqlx::query!(+ r#"INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)+ VALUES ($1, $2, $3, 'macro|[email protected]', 'Agent invocation')"#,+ root,+ kind,+ parent_id,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ "UPDATE agent_session SET thread_id = $1 WHERE id = $2",+ root,+ session+ )+ .execute(&pool)+ .await+ .unwrap();+ let expected = match kind {+ "document" => Some(AgentSessionParent::Document(parent_id)),+ "call" => Some(AgentSessionParent::Call(root)),+ _ => None,+ };+ assert_eq!(+ repo.get_agent_session_parent(&session.to_string())+ .await+ .unwrap(),+ expected+ );++ // Tombstoning one call message does not delete the call's chat thread.+ sqlx::query!(+ "UPDATE comms_messages SET deleted_at = NOW() WHERE id = $1",+ root+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ repo.get_agent_session_parent(&session.to_string())+ .await+ .unwrap(),+ expected+ );+ sqlx::query!(+ "UPDATE comms_message_threads SET deleted_at = NOW() WHERE root_id = $1",+ root+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ repo.get_agent_session_parent(&session.to_string())+ .await+ .unwrap(),+ None+ );+ }+ assert_eq!(+ repo.get_agent_session_parent(&Uuid::now_v7().to_string())+ .await+ .unwrap(),+ None+ );+}diff --git a/crates/entity_access/src/outbound/pg_access_repo/test/channel_call_chat.rs b/crates/entity_access/src/outbound/pg_access_repo/test/channel_call_chat.rsnew file mode 100644index 0000000000..6dbb81446f--- /dev/null+++ b/crates/entity_access/src/outbound/pg_access_repo/test/channel_call_chat.rs@@ -0,0 +1,101 @@+use super::*;+use crate::domain::{+ models::CommentAccessLevel, ports::EntityAccessService, service::EntityAccessServiceImpl,+};++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../../call/fixtures", scripts("call_repo"))+)]+async fn channel_call_chat_uses_current_channel_grants_without_direct_participant_grants(+ pool: PgPool,+) -> anyhow::Result<()> {+ let repo = PgAccessRepository::new(pool.clone());+ let service = EntityAccessServiceImpl::new(repo);+ let channel_id = uuid::uuid!("00000000-0000-0000-0000-000000000c01");+ let member = user_id("macro|[email protected]");+ let viewer = user_id("macro|[email protected]");++ for call_id in [+ "00000000-0000-0000-0000-0000000ca110",+ "00000000-0000-0000-0000-0000000ca2ed",+ ] {+ for level in [AccessLevel::View, AccessLevel::Comment, AccessLevel::Edit] {+ // Channel calls grant their channel Edit on creation. Also verify+ // an explicit Comment grant and that View remains read-only.+ sqlx::query!(+ r#"UPDATE entity_access SET access_level = $3::text::"AccessLevel"+ WHERE entity_id = $1 AND entity_type = 'call'+ AND source_id = $2 AND source_type = 'channel'"#,+ Uuid::parse_str(call_id)?,+ channel_id.to_string(),+ level.to_string(),+ )+ .execute(&pool)+ .await?;++ assert_eq!(+ service+ .get_access_level(Some(&member), call_id, EntityType::Call)+ .await?,+ Some(level)+ );+ let receipt = service+ .generate_entity_access_receipt::<CommentAccessLevel>(+ &member,+ None,+ call_id,+ EntityType::Call,+ )+ .await;+ if level >= AccessLevel::Comment {+ assert!(receipt.is_ok());+ } else {+ assert!(matches!(receipt, Err(AccessError::Unauthorized)));+ }+ }++ assert!(matches!(+ service+ .generate_entity_access_receipt::<CommentAccessLevel>(+ &viewer,+ None,+ call_id,+ EntityType::Call,+ )+ .await,+ Err(AccessError::Unauthorized)+ ));+ }++ sqlx::query!(+ "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2",+ channel_id,+ member.as_ref(),+ )+ .execute(&pool)+ .await?;+ for call_id in [+ "00000000-0000-0000-0000-0000000ca110",+ "00000000-0000-0000-0000-0000000ca2ed",+ ] {+ assert!(matches!(+ service+ .generate_entity_access_receipt::<CommentAccessLevel>(+ &member,+ None,+ call_id,+ EntityType::Call,+ )+ .await,+ Err(AccessError::Unauthorized)+ ));+ assert_eq!(+ service+ .get_access_level(None, call_id, EntityType::Call)+ .await?,+ None+ );+ }+ Ok(())+}diff --git a/crates/entity_access_db_utils/src/lib.rs b/crates/entity_access_db_utils/src/lib.rsindex 8b72755e47..b2963864ee 100644--- a/crates/entity_access_db_utils/src/lib.rs+++ b/crates/entity_access_db_utils/src/lib.rs@@ -195,12 +195,12 @@ pub async fn delete_entity_access_rows(Ok(())}-/// Grant call-only view access to an active participant of a standalone call.+/// Grant call-only comment access to an active participant of a standalone call.////// The participant must already have been admitted by the call domain. The query/// cannot grant access to other entities, channel calls, or nonparticipants, and/// preserves stronger grants. It does not commit the caller's transaction.-pub async fn ensure_call_participant_view_access<'e, E>(+pub async fn ensure_call_participant_comment_access<'e, E>(executor: E,call_id: ¯o_uuid::Uuid,user_id: MacroUserIdStr<'_>,@@ -210,12 +210,13 @@ where{sqlx::query!(r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)- SELECT c.id, 'call', p.user_id, 'user', 'view'+ SELECT c.id, 'call', p.user_id, 'user', 'comment'FROM calls c JOIN call_participants p ON p.call_id = c.idWHERE c.id = $1 AND c.channel_id IS NULL AND p.user_id = $2 AND p.left_at IS NULLON CONFLICT (entity_id, entity_type, source_id, source_type)WHERE granted_from_project_id IS NULL- DO NOTHING"#,+ DO UPDATE SET access_level = EXCLUDED.access_level, updated_at = now()+ WHERE entity_access.access_level = 'view'"#,call_id,user_id.as_ref(),)diff --git a/crates/entity_access_db_utils/src/test.rs b/crates/entity_access_db_utils/src/test.rsindex c419475995..3bbd0e13f4 100644--- a/crates/entity_access_db_utils/src/test.rs+++ b/crates/entity_access_db_utils/src/test.rs@@ -1089,7 +1089,7 @@ async fn owner_grant_maps_user_bot_and_team_to_their_access_source(pool: Pool<Po}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn ensuring_view_access_is_idempotent_and_preserves_stronger_grants(+async fn ensuring_comment_access_upgrades_view_and_preserves_stronger_grants(pool: Pool<Postgres>,) -> anyhow::Result<()> {let entity = Uuid::now_v7();@@ -1103,7 +1103,9 @@ async fn ensuring_view_access_is_idempotent_and_preserves_stronger_grants(for (email, existing) in [("[email protected]", Some(AccessLevel::Owner)),("[email protected]", Some(AccessLevel::Edit)),- ("[email protected]", None),+ ("[email protected]", Some(AccessLevel::View)),+ ("[email protected]", Some(AccessLevel::Comment)),+ ("[email protected]", None),] {let user = MacroUserIdStr::try_from_email(email)?;if let Some(level) = existing {@@ -1127,13 +1129,20 @@ async fn ensuring_view_access_is_idempotent_and_preserves_stronger_grants(.execute(&pool).await?;for _ in 0..2 {- ensure_call_participant_view_access(&pool, &entity, user.clone()).await?;+ ensure_call_participant_comment_access(&pool, &entity, user.clone()).await?;}let level = sqlx::query_scalar!(r#"SELECT access_level AS "access_level!: AccessLevel" FROM entity_access WHERE entity_id = $1 AND entity_type = 'call' AND source_id = $2 AND source_type = 'user' AND granted_from_project_id IS NULL"#,entity, user.as_ref(),).fetch_one(&pool).await?;- assert_eq!(level, existing.unwrap_or(AccessLevel::View));+ assert_eq!(+ level,+ match existing {+ Some(AccessLevel::Owner) => AccessLevel::Owner,+ Some(AccessLevel::Edit) => AccessLevel::Edit,+ _ => AccessLevel::Comment,+ }+ );}Ok(())}@@ -1147,7 +1156,7 @@ async fn participant_grants_reject_channel_calls_nonparticipants_and_departed_us) -> anyhow::Result<()> {let call_id = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);let participant = MacroUserIdStr::try_from_email("[email protected]")?;- ensure_call_participant_view_access(&pool, &call_id, participant.copied()).await?;+ ensure_call_participant_comment_access(&pool, &call_id, participant.copied()).await?;assert!(!fetch_entity_access_rows(&pool, &call_id, EntityType::Call).await@@ -1159,7 +1168,7 @@ async fn participant_grants_reject_channel_calls_nonparticipants_and_departed_us.execute(&pool).await?;let stranger = MacroUserIdStr::try_from_email("[email protected]")?;- ensure_call_participant_view_access(&pool, &call_id, stranger.copied()).await?;+ ensure_call_participant_comment_access(&pool, &call_id, stranger.copied()).await?;sqlx::query!("UPDATE call_participants SET left_at = now() WHERE call_id = $1 AND user_id = $2",call_id,@@ -1167,7 +1176,7 @@ async fn participant_grants_reject_channel_calls_nonparticipants_and_departed_us).execute(&pool).await?;- ensure_call_participant_view_access(&pool, &call_id, participant.copied()).await?;+ ensure_call_participant_comment_access(&pool, &call_id, participant.copied()).await?;let rows = fetch_entity_access_rows(&pool, &call_id, EntityType::Call).await;assert!(!rowsdiff --git a/crates/macro_db_client/migrations/20260928230225_call_message_threads.sql b/crates/macro_db_client/migrations/20260928230225_call_message_threads.sqlnew file mode 100644index 0000000000..036004c686--- /dev/null+++ b/crates/macro_db_client/migrations/20260928230225_call_message_threads.sql@@ -0,0 +1,49 @@+-- Call chat uses the shared message/thread schema and retains its identity+-- when the ephemeral call is archived into call_records.+-- Defer validation until this DDL transaction releases its stronger locks.+SET LOCAL lock_timeout = '5s';++ALTER TABLE comms_messages+ DROP CONSTRAINT comms_messages_parent_type_check,+ ADD CONSTRAINT comms_messages_parent_type_check+ CHECK (parent_entity_type IN ('channel', 'document', 'initiative', 'crm_company', 'crm_contact', 'call')) NOT VALID,+ DROP CONSTRAINT IF EXISTS comms_messages_call_thread_check,+ ADD CONSTRAINT comms_messages_call_thread_check+ CHECK (parent_entity_type <> 'call' OR+ (thread_id IS NULL AND id::text = parent_entity_id) OR+ (thread_id IS NOT NULL AND thread_id::text = parent_entity_id)) NOT VALID;++-- Polymorphic call parents live in either calls or call_records. Archival+-- inserts the permanent row before deleting the ephemeral one; cleanup only+-- runs once neither form remains. Message foreign keys cascade to replies,+-- thread metadata, attachments, and reactions.+CREATE OR REPLACE FUNCTION cleanup_call_messages() RETURNS trigger+LANGUAGE plpgsql AS $$+BEGIN+ PERFORM pg_advisory_xact_lock(hashtextextended(OLD.id::text, 0));+ IF NOT EXISTS (SELECT 1 FROM calls WHERE id = OLD.id)+ AND NOT EXISTS (SELECT 1 FROM call_records WHERE id = OLD.id) THEN+ -- Mention references are polymorphic and have no message foreign key.+ DELETE FROM comms_entity_mentions+ WHERE source_entity_type = 'message' AND source_entity_id IN (+ SELECT id::text FROM comms_messages+ WHERE parent_entity_type = 'call' AND parent_entity_id = OLD.id::text+ );+ DELETE FROM comms_messages+ WHERE parent_entity_type = 'call' AND parent_entity_id = OLD.id::text;+ END IF;+ RETURN OLD;+END;+$$;++CREATE OR REPLACE TRIGGER trg_cleanup_active_call_messages+AFTER DELETE ON calls+FOR EACH ROW EXECUTE FUNCTION cleanup_call_messages();++CREATE OR REPLACE TRIGGER trg_cleanup_call_record_messages+AFTER DELETE ON call_records+FOR EACH ROW EXECUTE FUNCTION cleanup_call_messages();++-- The first call message takes the call's canonical root id. Keep its+-- original request id so retrying a lost response cannot append it again.+ALTER TABLE comms_messages ADD COLUMN IF NOT EXISTS client_message_id uuid;diff --git a/crates/macro_db_client/migrations/20260928230226_validate_call_message_threads.sql b/crates/macro_db_client/migrations/20260928230226_validate_call_message_threads.sqlnew file mode 100644index 0000000000..2e93d1a4ae--- /dev/null+++ b/crates/macro_db_client/migrations/20260928230226_validate_call_message_threads.sql@@ -0,0 +1,7 @@+-- Validate after the initial DDL transaction releases its stronger locks.+-- These scans allow concurrent message reads and writes.+SET LOCAL lock_timeout = '5s';++ALTER TABLE comms_messages+ VALIDATE CONSTRAINT comms_messages_parent_type_check,+ VALIDATE CONSTRAINT comms_messages_call_thread_check;diff --git a/crates/macro_db_client/migrations/20260928230227_call_client_message_id_index.sql b/crates/macro_db_client/migrations/20260928230227_call_client_message_id_index.sqlnew file mode 100644index 0000000000..3f73218af6--- /dev/null+++ b/crates/macro_db_client/migrations/20260928230227_call_client_message_id_index.sql@@ -0,0 +1,8 @@+-- no-transaction+-- Keep a single statement: a SQLx simple-query batch with multiple statements+-- gets an implicit transaction, which CONCURRENTLY forbids.+-- An interrupted build can leave an invalid index; inspect pg_index.indisvalid,+-- drop the invalid index concurrently, then retry this migration.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS comms_messages_client_message_id_key+ ON comms_messages (client_message_id)+ WHERE client_message_id IS NOT NULL;diff --git a/crates/macro_db_client/src/annotations/create_anchor/test.rs b/crates/macro_db_client/src/annotations/create_anchor/test.rsindex 4a4abb2054..ebff04b33c 100644--- a/crates/macro_db_client/src/annotations/create_anchor/test.rs+++ b/crates/macro_db_client/src/annotations/create_anchor/test.rs@@ -28,6 +28,7 @@ async fn standalone_highlight_remains_unthreaded_until_a_message_attaches_it(poolet repo = messages::outbound::pg_message_repo::PgMessageRepository::new(pool.clone());let root = repo.create(CreateMessage {+ canonical_root_id: None,parent: MessageParent::parse("document", "document-with-comments").unwrap(),actor: "macro|[email protected]".to_owned().try_into().unwrap(),triggered_by: None,diff --git a/crates/messages/src/domain/delivery.rs b/crates/messages/src/domain/delivery.rsindex 49c4ecf1f5..2847f94531 100644--- a/crates/messages/src/domain/delivery.rs+++ b/crates/messages/src/domain/delivery.rs@@ -162,7 +162,7 @@ impl<> MessageEventPublisher for DiscussionDelivery<C, A, R, N, S>{async fn publish(&self, event: MessageEvent) -> Result<(), rootcause::Report> {- if !event.parent.is_discussion() {+ if matches!(event.parent, MessageParent::Channel(_)) {return Err(rootcause::report!("discussion delivery requires an entity parent"));@@ -174,6 +174,10 @@ impl<self.realtime.send(&event, viewers).await}.await;+ // Call chat is delivered in the live sidebar, without document comment notifications.+ if matches!(event.parent, MessageParent::Call(_)) {+ return realtime;+ }let notification = match &event.change {MessageChange::Posted {message,diff --git a/crates/messages/src/domain/delivery/test.rs b/crates/messages/src/domain/delivery/test.rsindex 1ccf9ad30c..ac82ab0f39 100644--- a/crates/messages/src/domain/delivery/test.rs+++ b/crates/messages/src/domain/delivery/test.rs@@ -288,3 +288,22 @@ async fn crm_records_without_an_owner_only_notify_mentions_and_participants() {vec![("viewer".into(), CommentNotificationReason::Mention)]);}++#[tokio::test]+async fn call_chat_only_reaches_authorized_live_subscribers() {+ let log = DeliveryLog::default();+ let mut event = event();+ event.parent = MessageParent::Call(Uuid::from_u128(9));+ if let MessageChange::Posted { message, .. } = &mut event.change {+ message.parent = event.parent.clone();+ }+ DiscussionDelivery::new(Context, Access, log.clone(), log.clone())+ .publish(event)+ .await+ .unwrap();+ assert_eq!(+ *log.live.lock().unwrap(),+ HashSet::from(["viewer".to_owned()])+ );+ assert!(log.notices.lock().unwrap().is_empty());+}diff --git a/crates/messages/src/domain/effects/test.rs b/crates/messages/src/domain/effects/test.rsindex 7f8fdbe5d7..2ebffad169 100644--- a/crates/messages/src/domain/effects/test.rs+++ b/crates/messages/src/domain/effects/test.rs@@ -69,3 +69,30 @@ async fn typing_only_reaches_the_parent_transport() {.unwrap();assert_eq!(*log.lock().unwrap(), vec![2]);}++#[tokio::test]+async fn call_chat_reaches_both_agent_targets_and_the_parent_transport() {+ let log = Arc::new(Mutex::new(Vec::new()));+ let target = |id| Target {+ id,+ fail: false,+ log: log.clone(),+ };+ let mut event = event(MessageChange::ThreadUpdated {+ state: crate::domain::models::ThreadState {+ root_id: uuid::Uuid::from_u128(1),+ user_id: "macro|[email protected]".into(),+ resolved: false,+ anchor: None,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ deleted_at: None,+ },+ });+ event.parent = MessageParent::Call(uuid::Uuid::from_u128(1));+ MessageEffects::new(target(0), target(1), target(2))+ .publish(event)+ .await+ .unwrap();+ assert_eq!(*log.lock().unwrap(), vec![0, 1, 2]);+}diff --git a/crates/messages/src/domain/models.rs b/crates/messages/src/domain/models.rsindex 41daf64436..80629bbbc5 100644--- a/crates/messages/src/domain/models.rs+++ b/crates/messages/src/domain/models.rs@@ -51,6 +51,8 @@ pub enum MessageParent {CrmCompany(Uuid),/// A CRM contact.CrmContact(Uuid),+ /// A video call and its persistent chat thread.+ Call(Uuid),}impl MessageParent {@@ -68,6 +70,7 @@ impl MessageParent {"crm_contact" => Ok(Self::CrmContact(entity_id.parse().map_err(|_| InvalidParent)?,)),+ "call" => Ok(Self::Call(entity_id.parse().map_err(|_| InvalidParent)?)),_ => Err(InvalidParent),}}@@ -80,6 +83,7 @@ impl MessageParent {Self::Initiative(_) => "initiative",Self::CrmCompany(_) => "crm_company",Self::CrmContact(_) => "crm_contact",+ Self::Call(_) => "call",}}@@ -87,6 +91,7 @@ impl MessageParent {pub fn entity_id(&self) -> String {match self {Self::Channel(id)+ | Self::Call(id)| Self::Initiative(id)| Self::CrmCompany(id)| Self::CrmContact(id) => id.to_string(),@@ -96,7 +101,7 @@ impl MessageParent {/// Whether messages are presented as comments on an entity.pub fn is_discussion(&self) -> bool {- !matches!(self, Self::Channel(_))+ !matches!(self, Self::Channel(_) | Self::Call(_))}/// Entity type whose permissions govern messages on this parent.@@ -108,6 +113,7 @@ impl MessageParent {Self::Initiative(_) => entity_access::domain::models::EntityType::Initiative,Self::CrmCompany(_) => entity_access::domain::models::EntityType::CrmCompany,Self::CrmContact(_) => entity_access::domain::models::EntityType::CrmContact,+ Self::Call(_) => entity_access::domain::models::EntityType::Call,}}}diff --git a/crates/messages/src/domain/models/test.rs b/crates/messages/src/domain/models/test.rsindex e8a1605e53..881cef0fb8 100644--- a/crates/messages/src/domain/models/test.rs+++ b/crates/messages/src/domain/models/test.rs@@ -8,6 +8,7 @@ fn parent_identifiers_are_validated_and_round_trip() {("initiative", "0194e3b0-121a-7000-8000-000000000003"),("crm_company", "0194e3b0-121a-7000-8000-000000000004"),("crm_contact", "0194e3b0-121a-7000-8000-000000000005"),+ ("call", "0194e3b0-121a-7000-8000-000000000002"),] {let parent = MessageParent::parse(kind, id).unwrap();assert_eq!(parent.entity_type(), kind);@@ -26,6 +27,7 @@ fn parent_identifiers_are_validated_and_round_trip() {("crm_company", "not-a-uuid"),("crm_contact", "not-a-uuid"),("crm", "0194e3b0-121a-7000-8000-000000000004"),+ ("call", "not-a-uuid"),("email_thread", "not-a-uuid"),("document", ""),("document", " leading-space"),@@ -36,6 +38,17 @@ fn parent_identifiers_are_validated_and_round_trip() {assert!(serde_json::from_str::<MessageParent>(r#"{"type":"document","id":""}"#).is_err());}+#[test]+fn call_chat_does_not_disable_other_entity_discussions() {+ let id = "0194e3b0-121a-7000-8000-000000000002";+ for kind in ["document", "initiative", "crm_company", "crm_contact"] {+ assert!(MessageParent::parse(kind, id).unwrap().is_discussion());+ }+ for kind in ["channel", "call"] {+ assert!(!MessageParent::parse(kind, id).unwrap().is_discussion());+ }+}+#[test]fn email_threads_are_not_message_parents() {let id = "0194e3b0-121a-7000-8000-000000000002";diff --git a/crates/messages/src/domain/ports.rs b/crates/messages/src/domain/ports.rsindex 200c483081..5d70e40992 100644--- a/crates/messages/src/domain/ports.rs+++ b/crates/messages/src/domain/ports.rs@@ -90,6 +90,9 @@ pub struct MessagePage {/// Authenticated create command; attribution fields are never client controlled.#[derive(Debug, Clone)]pub struct CreateMessage {+ /// Append to this canonical thread, creating its first message atomically when absent.+ /// Its root identity is server-owned and overrides the first message's client id.+ pub canonical_root_id: Option<Uuid>,/// Parent with verified actor access.pub parent: MessageParent,/// Verified actor.@@ -249,6 +252,14 @@ pub trait MessageRepository: Send + Sync + 'static {parent: &MessageParent,id: Uuid,) -> impl Future<Output = Result<Option<Message>, MessageError>> + Send;+ /// Recover a call submission within its authorized parent and original sender.+ /// Includes tombstones so retries never recreate deleted content.+ fn get_by_client_message_id(+ &self,+ parent: &MessageParent,+ actor: &ChannelSender<'_>,+ client_message_id: Uuid,+ ) -> impl Future<Output = Result<Option<Message>, MessageError>> + Send;/// Read thread state; returns deleted state so callers can reject writes.fn thread(&self,diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rsindex 7796dcfffb..f0e9a8f8c5 100644--- a/crates/messages/src/domain/service.rs+++ b/crates/messages/src/domain/service.rs@@ -187,7 +187,32 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {if let Some(id) = input.id {validate_client_id(id, chrono::Utc::now())?;}- self.post_validated(access, input).await+ let parent = parent_from_receipt(&access)?;+ if !matches!(parent, MessageParent::Call(_)) {+ return self.post_validated(access, input).await;+ }+ let Some(client_message_id) = input.id else {+ return self.post_validated(access, input).await;+ };+ let actor = actor_from_receipt(&access, &parent)?;+ self.ensure_parent(&parent).await?;+ // The first call message uses the call ID, so its submitted ID must be+ // resolved separately. Replays return persisted content without delivery.+ if let Some(message) = self+ .repo+ .get_by_client_message_id(&parent, &actor, client_message_id)+ .await?+ {+ return Ok(message);+ }+ match self.post_validated(access, input).await {+ Err(MessageError::Conflict) => self+ .repo+ .get_by_client_message_id(&parent, &actor, client_message_id)+ .await?+ .ok_or(MessageError::Conflict),+ result => result,+ }}/// Post a trusted server event once, including after long broker delays.@@ -248,15 +273,29 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {}self.validate_references(&access, &input.mentions, &input.attachments).await?;- if let Some(root) = input.thread_id {- self.active_thread(&parent, root).await?;- }+ let canonical_root_id = match parent {+ MessageParent::Call(call_id) => {+ if input.thread_id.is_some_and(|root| root != call_id) {+ return Err(MessageError::Invalid(+ "call messages belong to the call thread",+ ));+ }+ Some(call_id)+ }+ _ => {+ if let Some(root) = input.thread_id {+ self.active_thread(&parent, root).await?;+ }+ None+ }+ };let notification_policy = input.notification_policy;let nonce = input.nonce.clone();let mentions = self.resolve_mentions(&parent, &input.mentions).await?;let message = self.repo.create(CreateMessage {+ canonical_root_id,parent: parent.clone(),actor: actor.clone(),triggered_by: access@@ -785,6 +824,7 @@ fn parent_from_receipt<P: RequiredPermission>(EntityType::Initiative => "initiative",EntityType::CrmCompany => "crm_company",EntityType::CrmContact => "crm_contact",+ EntityType::Call => "call",_ => return Err(MessageError::Forbidden),};MessageParent::parse(kind, &entity.entity_id)diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rsindex 8bf497e518..d8da60314d 100644--- a/crates/messages/src/domain/service/test.rs+++ b/crates/messages/src/domain/service/test.rs@@ -3,6 +3,7 @@ use chrono::Utc;use entity_access::domain::models::{AccessLevel, EntityAccessAuth};use std::sync::{Arc, Mutex};+mod call_retries;mod event_posts;mod initiative;@@ -18,6 +19,7 @@ struct Repo {reaction_changed: bool,file_type: Option<String>,concurrent_create: bool,+ client_message_id: Option<Uuid>,}impl Repo {@@ -75,6 +77,20 @@ impl MessageRepository for Repo {}Ok(message)}+ async fn get_by_client_message_id(+ &self,+ parent: &MessageParent,+ actor: &ChannelSender<'_>,+ client_message_id: Uuid,+ ) -> Result<Option<Message>, MessageError> {+ if self.client_message_id == Some(client_message_id)+ && self.message.sender_id.as_ref() == actor.as_ref()+ {+ self.get(parent, self.message.id).await+ } else {+ Ok(None)+ }+ }async fn thread(&self,parent: &MessageParent,@@ -115,7 +131,9 @@ impl MessageRepository for Repo {})}async fn create(&self, command: CreateMessage) -> Result<Message, MessageError> {- if command.input.id == Some(self.message.id) {+ if command.input.id == Some(self.message.id)+ || (self.client_message_id.is_some() && command.input.id == self.client_message_id)+ {self.creates.lock().unwrap().push(command);return Err(MessageError::Conflict);}@@ -254,6 +272,7 @@ fn fixture() -> Repo {reaction_changed: true,file_type: Some("md".into()),concurrent_create: false,+ client_message_id: None,}}@@ -970,6 +989,7 @@ async fn human_can_post_canonical_agent_mentions_on_documents_and_channels() {MessageParent::Initiative(Uuid::from_u128(21)),MessageParent::CrmCompany(Uuid::from_u128(22)),MessageParent::CrmContact(Uuid::from_u128(23)),+ MessageParent::Call(Uuid::from_u128(24)),] {let repo = fixture();let events = Events::default();@@ -984,6 +1004,12 @@ async fn human_can_post_canonical_agent_mentions_on_documents_and_channels() {access_level: AccessLevel::Comment,},),+ MessageParent::Call(_) => (+ EntityType::Call,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Comment,+ },+ ),MessageParent::Channel(_) => (EntityType::Channel,EntityPermission::ChannelRole {@@ -1048,72 +1074,89 @@ impl MessageMentionExtractor for RawBotMentions {#[tokio::test]async fn bot_posts_and_edits_extract_mentions_and_preserve_trusted_attribution_and_policy() {- use entity_access::domain::models::BotReceiptScope;- let receipt = || {- EntityAccessReceipt::try_new_bot(- bot_id::MACRO_AI_BOT_ID.into_storage_id(),- BotReceiptScope::User {- acting_user: "macro|[email protected]".to_string().try_into().unwrap(),- },- access("macro|[email protected]", "doc", AccessLevel::Comment)- .entity()- .clone(),- EntityPermission::AccessLevel {- access_level: AccessLevel::Comment,- },- )- .unwrap()- };- let mut repo = fixture();- repo.message.sender_id = ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);- let events = Events::default();- let service =- MessageService::new(repo.clone(), events.clone()).with_mention_extractor(RawBotMentions);- let mut input = post_input();- input.notification_policy = PostMessageNotificationPolicy::Silent;- let posted = service.post(receipt(), input.clone()).await.unwrap();- assert_eq!(- posted.triggered_by.as_deref(),- Some("macro|[email protected]")- );- assert_eq!(posted.mentions.len(), 1);- input.attribution = MessageAttribution::Unprompted;- assert!(+ use entity_access::domain::models::{BotReceiptScope, Entity};+ for parent in [+ MessageParent::parse("document", "doc").unwrap(),+ MessageParent::Call(Uuid::from_u128(1)),+ ] {+ let receipt = || {+ EntityAccessReceipt::try_new_bot(+ bot_id::MACRO_AI_BOT_ID.into_storage_id(),+ BotReceiptScope::User {+ acting_user: "macro|[email protected]".to_string().try_into().unwrap(),+ },+ Entity {+ entity_type: parent.access_entity_type(),+ entity_id: parent.entity_id(),+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Comment,+ },+ )+ .unwrap()+ };+ let mut repo = fixture();+ repo.message.sender_id = ChannelSender::new_from_bot(bot_id::MACRO_AI_BOT_ID);+ repo.message.parent = parent.clone();+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone())+ .with_mention_extractor(RawBotMentions);+ let mut input = post_input();+ input.notification_policy = PostMessageNotificationPolicy::Silent;+ let posted = service.post(receipt(), input.clone()).await.unwrap();+ assert_eq!(+ posted.triggered_by.as_deref(),+ Some("macro|[email protected]")+ );+ assert_eq!(posted.mentions.len(), 1);+ assert_eq!(posted.parent, parent);+ let canonical_root_id = match parent {+ MessageParent::Call(id) => Some(id),+ _ => None,+ };+ assert_eq!(+ repo.creates.lock().unwrap()[0].canonical_root_id,+ canonical_root_id+ );+ input.attribution = MessageAttribution::Unprompted;+ assert!(+ service+ .post(receipt(), input)+ .await+ .unwrap()+ .triggered_by+ .is_none()+ );service- .post(receipt(), input)+ .patch(+ receipt(),+ posted.id,+ MessagePatch {+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,+ content: Some("final @mention".into()),+ ..Default::default()+ },+ ).await- .unwrap()- .triggered_by- .is_none()- );- service- .patch(- receipt(),- posted.id,- MessagePatch {+ .unwrap();+ assert_eq!(repo.edits.lock().unwrap()[0].mentions.len(), 1);+ let events = events.0.lock().unwrap();+ assert!(events.iter().all(|event| event.parent == parent));+ assert!(matches!(+ events[0].change,+ MessageChange::Posted {+ notification_policy: PostMessageNotificationPolicy::Silent,+ ..+ }+ ));+ assert!(matches!(+ events[2].change,+ MessageChange::Edited {notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,- content: Some("final @mention".into()),- ..Default::default()- },- )- .await- .unwrap();- assert_eq!(repo.edits.lock().unwrap()[0].mentions.len(), 1);- let events = events.0.lock().unwrap();- assert!(matches!(- events[0].change,- MessageChange::Posted {- notification_policy: PostMessageNotificationPolicy::Silent,- ..- }- ));- assert!(matches!(- events[2].change,- MessageChange::Edited {- notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,- ..- }- ));+ ..+ }+ ));+ }}#[derive(Clone)]@@ -1148,6 +1191,16 @@ impl MessageRepository for StrictRepo {async fn get(&self, parent: &MessageParent, id: Uuid) -> Result<Option<Message>, MessageError> {self.inner.get(parent, id).await}+ async fn get_by_client_message_id(+ &self,+ parent: &MessageParent,+ actor: &ChannelSender<'_>,+ client_message_id: Uuid,+ ) -> Result<Option<Message>, MessageError> {+ self.inner+ .get_by_client_message_id(parent, actor, client_message_id)+ .await+ }async fn thread(&self,parent: &MessageParent,@@ -1536,3 +1589,133 @@ async fn spreadsheet_anchors_require_a_spreadsheet_root_and_valid_range() {});assert!(validate_post(&MessageParent::parse("document", "doc").unwrap(), &input).is_err());}++fn call_receipt<P: RequiredPermission>(+ user: &str,+ call_id: Uuid,+ level: AccessLevel,+) -> Result<EntityAccessReceipt<P>, entity_access::domain::models::AccessError> {+ EntityAccessReceipt::try_new_authenticated_user(+ user.to_owned().try_into().unwrap(),+ entity_access::domain::models::Entity {+ entity_id: call_id.to_string(),+ entity_type: EntityType::Call,+ },+ EntityPermission::AccessLevel {+ access_level: level,+ },+ )+}++#[tokio::test]+async fn call_posts_use_the_canonical_thread_and_reject_another_root() {+ let call_id = Uuid::from_u128(10);+ let repo = fixture();+ let service = MessageService::new(repo.clone(), Events::default());+ for thread_id in [None, Some(call_id)] {+ let mut input = post_input();+ input.thread_id = thread_id;+ service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await+ .unwrap();+ }+ let creates = repo.creates.lock().unwrap();+ assert_eq!(creates.len(), 2);+ assert!(+ creates+ .iter()+ .all(|command| command.canonical_root_id == Some(call_id))+ );+ drop(creates);+ let mut input = post_input();+ input.thread_id = Some(Uuid::from_u128(11));+ assert!(matches!(+ service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await,+ Err(MessageError::Invalid(_))+ ));+ assert_eq!(repo.creates.lock().unwrap().len(), 2);+}++#[test]+fn call_viewers_can_read_but_cannot_post() {+ let call_id = Uuid::from_u128(10);+ assert!(+ call_receipt::<MessageView>("macro|[email protected]", call_id, AccessLevel::View).is_ok()+ );+ assert!(+ call_receipt::<MessageWrite>("macro|[email protected]", call_id, AccessLevel::View)+ .is_err()+ );+ assert!(+ call_receipt::<MessageWrite>("macro|[email protected]", call_id, AccessLevel::Comment)+ .is_ok()+ );+}++#[tokio::test]+async fn call_root_deletion_preserves_chat_and_cannot_delete_other_authors() {+ let mut repo = fixture();+ let call_id = repo.message.id;+ repo.message.parent = MessageParent::Call(call_id);+ repo.state.anchor = None;+ let service = MessageService::new(repo.clone(), Events::default());+ assert!(matches!(+ service+ .delete(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Edit).unwrap(),+ call_id,+ None,+ )+ .await,+ Err(MessageError::Forbidden)+ ));+ service+ .delete(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ call_id,+ None,+ )+ .await+ .unwrap();+ assert_eq!(*repo.deletes.lock().unwrap(), vec![call_id]);+ assert!(repo.thread_deletes.lock().unwrap().is_empty());+ service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ post_input(),+ )+ .await+ .unwrap();+ assert!(matches!(+ service+ .delete_thread(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Owner).unwrap(),+ call_id,+ None,+ )+ .await,+ Err(MessageError::Invalid(_))+ ));+ assert!(matches!(+ service+ .patch_thread(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Owner).unwrap(),+ call_id,+ ThreadPatch {+ resolved: Some(true),+ ..Default::default()+ },+ )+ .await,+ Err(MessageError::Invalid(_))+ ));+}diff --git a/crates/messages/src/domain/service/test/call_retries.rs b/crates/messages/src/domain/service/test/call_retries.rsnew file mode 100644index 0000000000..c4d95b1aaf--- /dev/null+++ b/crates/messages/src/domain/service/test/call_retries.rs@@ -0,0 +1,137 @@+use super::*;++fn persisted_call_message() -> (Repo, Uuid, PostMessage) {+ let mut repo = fixture();+ let call_id = macro_uuid::generate_uuid_v7();+ repo.message.id = call_id;+ repo.message.parent = MessageParent::Call(call_id);+ repo.state.root_id = call_id;+ repo.client_message_id = Some(macro_uuid::generate_uuid_v7());+ let mut input = post_input();+ input.id = repo.client_message_id;+ (repo, call_id, input)+}++#[tokio::test]+async fn call_root_retry_returns_the_canonical_message_without_delivery() {+ let (mut repo, call_id, input) = persisted_call_message();+ repo.message.content = "Edited since the original send".into();+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ let message = service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await+ .unwrap();+ assert_eq!(message.id, call_id);+ assert_eq!(message.content, "Edited since the original send");+ assert!(repo.creates.lock().unwrap().is_empty());+ assert!(events.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn call_reply_retry_returns_the_existing_reply_without_delivery() {+ let (mut repo, call_id, mut input) = persisted_call_message();+ repo.message.id = input.id.unwrap();+ repo.message.thread_id = Some(call_id);+ input.thread_id = Some(call_id);+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ let message = service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await+ .unwrap();+ assert_eq!(message.id, repo.message.id);+ assert_eq!(message.thread_id, Some(call_id));+ assert!(repo.creates.lock().unwrap().is_empty());+ assert!(events.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn call_retry_recovers_a_concurrent_commit_without_delivery() {+ let (mut repo, call_id, input) = persisted_call_message();+ repo.concurrent_create = true;+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ let message = service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await+ .unwrap();+ assert_eq!(message.id, call_id);+ assert_eq!(repo.creates.lock().unwrap().len(), 1);+ assert!(events.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn call_retry_does_not_restore_a_deleted_message() {+ let (mut repo, call_id, input) = persisted_call_message();+ repo.message.deleted_at = Some(Utc::now());+ repo.message.content.clear();+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ let message = service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await+ .unwrap();+ assert!(message.deleted_at.is_some());+ assert!(message.content.is_empty());+ assert!(repo.creates.lock().unwrap().is_empty());+ assert!(events.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn call_retry_cannot_recover_another_actor_or_parents_message() {+ let (repo, call_id, input) = persisted_call_message();+ let events = Events::default();+ let service = MessageService::new(repo.clone(), events.clone());+ for (actor, parent) in [+ ("macro|[email protected]", call_id),+ ("macro|[email protected]", macro_uuid::generate_uuid_v7()),+ ] {+ assert!(matches!(+ service+ .post(+ call_receipt(actor, parent, AccessLevel::Comment).unwrap(),+ input.clone(),+ )+ .await,+ Err(MessageError::Conflict),+ ));+ }+ assert!(events.0.lock().unwrap().is_empty());+}++#[tokio::test]+async fn call_retry_still_rejects_a_deleted_parent() {+ let (repo, call_id, input) = persisted_call_message();+ let events = Events::default();+ let service = MessageService::new(+ StrictRepo {+ inner: repo.clone(),+ parent_exists: false,+ },+ events.clone(),+ );+ assert!(matches!(+ service+ .post(+ call_receipt("macro|[email protected]", call_id, AccessLevel::Comment).unwrap(),+ input,+ )+ .await,+ Err(MessageError::NotFound),+ ));+ assert!(repo.creates.lock().unwrap().is_empty());+ assert!(events.0.lock().unwrap().is_empty());+}diff --git a/crates/messages/src/inbound/axum_router.rs b/crates/messages/src/inbound/axum_router.rsindex 735a60bd88..88c6234087 100644--- a/crates/messages/src/inbound/axum_router.rs+++ b/crates/messages/src/inbound/axum_router.rs@@ -161,6 +161,7 @@ async fn receipt<P: RequiredPermission, A: EntityAccessService, Auth: MacroAuthoMessageParent::Initiative(_) => EntityType::Initiative,MessageParent::CrmCompany(_) => EntityType::CrmCompany,MessageParent::CrmContact(_) => EntityType::CrmContact,+ MessageParent::Call(_) => EntityType::Call,};entity_access::inbound::axum_extractors::principal_entity_access_receipt::<P>(access,diff --git a/crates/messages/src/outbound/connection_gateway.rs b/crates/messages/src/outbound/connection_gateway.rsindex 9d56792bde..70205a2852 100644--- a/crates/messages/src/outbound/connection_gateway.rs+++ b/crates/messages/src/outbound/connection_gateway.rs@@ -14,6 +14,7 @@ fn entity(parent: &MessageParent) -> Entity<'static> {MessageParent::Initiative(_) => EntityType::Initiative,MessageParent::CrmCompany(_) => EntityType::CrmCompany,MessageParent::CrmContact(_) => EntityType::CrmContact,+ MessageParent::Call(_) => EntityType::Call,};kind.with_entity_string(parent.entity_id())}diff --git a/crates/messages/src/outbound/entity_access_audience.rs b/crates/messages/src/outbound/entity_access_audience.rsindex 9b980e14f2..a84b612842 100644--- a/crates/messages/src/outbound/entity_access_audience.rs+++ b/crates/messages/src/outbound/entity_access_audience.rs@@ -22,6 +22,7 @@ impl<A: EntityAccessService> MessageAudienceAccess for EntityAccessMessageAudienMessageParent::Initiative(_) => EntityType::Initiative,MessageParent::CrmCompany(_) => EntityType::CrmCompany,MessageParent::CrmContact(_) => EntityType::CrmContact,+ MessageParent::Call(_) => EntityType::Call,};let mut viewers = HashSet::new();for candidate in candidates {diff --git a/crates/messages/src/outbound/notification_sender.rs b/crates/messages/src/outbound/notification_sender.rsindex 1aa144dbb7..adf17f786d 100644--- a/crates/messages/src/outbound/notification_sender.rs+++ b/crates/messages/src/outbound/notification_sender.rs@@ -32,7 +32,7 @@ impl<N: NotificationIngress> DiscussionNotifier for MessageNotificationSender<N>MessageParent::Initiative(_) => EntityType::Initiative,MessageParent::CrmCompany(_) => EntityType::CrmCompany,MessageParent::CrmContact(_) => EntityType::CrmContact,- MessageParent::Channel(_) => {+ MessageParent::Channel(_) | MessageParent::Call(_) => {return Err(rootcause::report!("comment notification requires discussion parent"));diff --git a/crates/messages/src/outbound/pg_discussion_context.rs b/crates/messages/src/outbound/pg_discussion_context.rsindex 0657aa6d38..6ce2264431 100644--- a/crates/messages/src/outbound/pg_discussion_context.rs+++ b/crates/messages/src/outbound/pg_discussion_context.rs@@ -187,7 +187,7 @@ impl<MessageParent::CrmCompany(_) | MessageParent::CrmContact(_) => {self.crm_context(parent, root).await}- MessageParent::Channel(_) | MessageParent::Document(_) => {+ MessageParent::Channel(_) | MessageParent::Document(_) | MessageParent::Call(_) => {self.documents.context(parent, root).await}}@@ -227,7 +227,7 @@ impl DiscussionContextReader for PgDiscussionContext {link_share_access: row.link_share_access,}}- MessageParent::Channel(_) => {+ MessageParent::Channel(_) | MessageParent::Call(_) => {return Err(rootcause::report!("channel has no discussion context"));}MessageParent::Initiative(_) => {diff --git a/crates/messages/src/outbound/pg_message_repo.rs b/crates/messages/src/outbound/pg_message_repo.rsindex 0869ea8946..81bff5d981 100644--- a/crates/messages/src/outbound/pg_message_repo.rs+++ b/crates/messages/src/outbound/pg_message_repo.rs@@ -1,4 +1,5 @@use crate::domain::{mentions::MessageReferenceKind, models::*, ports::*};+use channel_sender::ChannelSender;use chrono::{DateTime, Utc};use serde::Deserialize;use sqlx::{PgPool, Postgres, Transaction, types::Json};@@ -38,7 +39,12 @@ fn database_error(error: sqlx::Error) -> MessageError {if let sqlx::Error::Database(ref error) = error {match error.code().as_deref() {Some("23503") => return MessageError::NotFound,- Some("23505") if error.constraint() == Some("comms_messages_pkey") => {+ Some("23505")+ if matches!(+ error.constraint(),+ Some("comms_messages_pkey" | "comms_messages_client_message_id_key")+ ) =>+ {return MessageError::Conflict;}Some("23505") => {@@ -566,6 +572,8 @@ impl MessageRepository for PgMessageRepository {.fetch_one(&self.pool).await,MessageParent::Channel(id) => sqlx::query_scalar!(r#"SELECT EXISTS(SELECT 1 FROM comms_channels WHERE id = $1) AS "exists!""#, id).fetch_one(&self.pool).await,+ MessageParent::Call(id) => sqlx::query_scalar!(r#"SELECT EXISTS(SELECT 1 FROM calls WHERE id = $1 UNION ALL SELECT 1 FROM call_records WHERE id = $1) AS "exists!""#, id)+ .fetch_one(&self.pool).await,};exists.map_err(database_error)}@@ -584,6 +592,27 @@ impl MessageRepository for PgMessageRepository {Ok(self.hydrate(rows).await?.pop())}+ async fn get_by_client_message_id(+ &self,+ parent: &MessageParent,+ actor: &ChannelSender<'_>,+ client_message_id: Uuid,+ ) -> Result<Option<Message>, MessageError> {+ let rows = sqlx::query_scalar!(+ r#"SELECT to_jsonb(m) AS "message!: Json<StoredMessage>" FROM comms_messages m+ WHERE client_message_id = $1 AND parent_entity_type = $2+ AND parent_entity_id = $3 AND sender_id = $4"#,+ client_message_id,+ parent.entity_type(),+ parent.entity_id(),+ actor.as_ref(),+ )+ .fetch_all(&self.pool)+ .await+ .map_err(database_error)?;+ Ok(self.hydrate(rows).await?.pop())+ }+async fn thread(&self,parent: &MessageParent,@@ -639,12 +668,49 @@ impl MessageRepository for PgMessageRepository {self.read_timeline(parent, query).await}- async fn create(&self, command: CreateMessage) -> Result<Message, MessageError> {- let id = command+ async fn create(&self, mut command: CreateMessage) -> Result<Message, MessageError> {+ let mut id = command.input.id.unwrap_or_else(macro_uuid::generate_uuid_v7);let mut tx = self.pool.begin().await.map_err(database_error)?;+ if let Some(root_id) = command.canonical_root_id {+ // Serialize the first writers, and coordinate with parent cleanup. A+ // racing first send becomes a reply rather than failing or losing text.+ sqlx::query_scalar!(+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))::text AS lock",+ root_id.to_string(),+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(database_error)?;+ let parent_exists = sqlx::query_scalar!(+ r#"SELECT EXISTS(SELECT 1 FROM calls WHERE id = $1 UNION ALL SELECT 1 FROM call_records WHERE id = $1) AS "exists!""#,+ root_id,+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(database_error)?;+ if !parent_exists {+ return Err(MessageError::NotFound);+ }+ let thread_exists = sqlx::query_scalar!(+ r#"SELECT EXISTS(SELECT 1 FROM comms_message_threads+ WHERE root_id = $1 AND parent_entity_type = $2 AND parent_entity_id = $3) AS "exists!""#,+ root_id,+ command.parent.entity_type(),+ command.parent.entity_id(),+ )+ .fetch_one(&mut *tx)+ .await+ .map_err(database_error)?;+ if thread_exists {+ command.input.thread_id = Some(root_id);+ } else {+ id = root_id;+ command.input.thread_id = None;+ }+ }if let Some(root_id) = command.input.thread_id {// Replies attach to a live root of the same parent. The composite FK// only checks parent identity at commit and nothing stops a reply from@@ -668,8 +734,8 @@ impl MessageRepository for PgMessageRepository {}sqlx::query!(r#"INSERT INTO comms_messages(id, parent_entity_type, parent_entity_id, thread_id,- sender_id, triggered_by_user_id, content)- VALUES ($1, $2, $3, $4, $5, $6, $7)"#,+ sender_id, triggered_by_user_id, content, client_message_id)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)"#,id,command.parent.entity_type(),command.parent.entity_id(),@@ -677,6 +743,7 @@ impl MessageRepository for PgMessageRepository {command.actor.as_ref(),command.triggered_by,command.input.content,+ command.canonical_root_id.and(command.input.id),).execute(&mut *tx).awaitdiff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rsindex 43d66bf1cb..7d4afce12d 100644--- a/crates/messages/src/outbound/pg_message_repo/test.rs+++ b/crates/messages/src/outbound/pg_message_repo/test.rs@@ -31,6 +31,7 @@ async fn setup(pool: &PgPool) {fn command(document: &str, root: Option<Uuid>, content: &str) -> CreateMessage {CreateMessage {+ canonical_root_id: None,parent: MessageParent::parse("document", document).unwrap(),actor: USER.to_owned().try_into().unwrap(),triggered_by: None,@@ -1356,3 +1357,229 @@ async fn spreadsheet_threads_round_trip_resolve_and_delete(pool: PgPool) {.is_empty());}++async fn setup_call_chat(pool: &PgPool) -> Uuid {+ setup(pool).await;+ let call_id = macro_uuid::generate_uuid_v7();+ let channel_id = macro_uuid::generate_uuid_v7();+ let permission_id = macro_uuid::generate_uuid_v7().to_string();+ sqlx::query!(+ r#"INSERT INTO comms_channels (id, name, channel_type, owner_id)+ VALUES ($1, 'Call chat test', 'public', $2)"#,+ channel_id,+ USER+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO "SharePermission" (id) VALUES ($1)"#,+ permission_id+ )+ .execute(pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id)+ VALUES ($1, $2::uuid, $2::uuid::text, $3, $4)"#,+ call_id,+ channel_id,+ USER,+ permission_id+ )+ .execute(pool)+ .await+ .unwrap();+ call_id+}++fn call_message(call_id: Uuid, content: &str) -> CreateMessage {+ let mut command = command("message-doc-a", None, content);+ command.parent = MessageParent::Call(call_id);+ command.canonical_root_id = Some(call_id);+ command+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn concurrent_first_call_messages_share_one_thread(pool: PgPool) {+ let call_id = setup_call_chat(&pool).await;+ let repo = PgMessageRepository::new(pool);+ let (first, second) = tokio::join!(+ repo.create(call_message(call_id, "First participant")),+ repo.create(call_message(call_id, "Second participant")),+ );+ let first = first.unwrap();+ let second = second.unwrap();+ assert_eq!(first.root_id(), call_id);+ assert_eq!(second.root_id(), call_id);+ assert_ne!(first.id, second.id);+ assert_ne!(first.thread_id.is_none(), second.thread_id.is_none());+ let parent = MessageParent::Call(call_id);+ assert_eq!(+ repo.timeline(&parent, Default::default())+ .await+ .unwrap()+ .items+ .len(),+ 1+ );+ assert_eq!(repo.replies(&parent, call_id).await.unwrap().len(), 1);+ assert!(+ repo.get(&MessageParent::Call(Uuid::from_u128(7)), call_id)+ .await+ .unwrap()+ .is_none()+ );+ repo.delete(&parent, call_id).await.unwrap();+ let after_delete = repo+ .create(call_message(call_id, "After the first message was deleted"))+ .await+ .unwrap();+ assert_eq!(after_delete.thread_id, Some(call_id));+ assert!(+ repo.thread(&parent, call_id)+ .await+ .unwrap()+ .unwrap()+ .deleted_at+ .is_none()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn call_chat_survives_archiving_and_is_removed_with_the_record(pool: PgPool) {+ let call_id = setup_call_chat(&pool).await;+ verify_call_chat_archive(pool, call_id).await;+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn quick_call_chat_survives_archiving(pool: PgPool) {+ let call_id = setup_meeting_chat(&pool, false).await;+ verify_call_chat_archive(pool, call_id).await;+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn scheduled_call_chat_survives_archiving(pool: PgPool) {+ let call_id = setup_meeting_chat(&pool, true).await;+ verify_call_chat_archive(pool, call_id).await;+}++async fn setup_meeting_chat(pool: &PgPool, scheduled: bool) -> Uuid {+ let call_id = setup_call_chat(pool).await;+ let meeting_id = macro_uuid::generate_uuid_v7();+ let start = scheduled.then(chrono::Utc::now);+ let end = start.map(|start| start + chrono::Duration::hours(1));+ sqlx::query!(+ r#"INSERT INTO call_meetings (id, share_token, user_id, title, scheduled_start, scheduled_end, active_call_id)+ VALUES ($1, $1::uuid::text, $2, 'Standalone chat', $3, $4, $5)"#,+ meeting_id, USER, start, end, call_id+ ).execute(pool).await.unwrap();+ sqlx::query!(+ "UPDATE calls SET channel_id = NULL, meeting_id = $2 WHERE id = $1",+ call_id,+ meeting_id+ )+ .execute(pool)+ .await+ .unwrap();+ call_id+}++async fn verify_call_chat_archive(pool: PgPool, call_id: Uuid) {+ let repo = PgMessageRepository::new(pool.clone());+ let mut input = call_message(call_id, "Persistent chat");+ input.input.mentions.push(SimpleMention {+ entity_type: "user".into(),+ entity_id: USER.into(),+ });+ repo.create(input).await.unwrap();+ let parent = MessageParent::Call(call_id);+ let mut tx = pool.begin().await.unwrap();+ sqlx::query!(r#"INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, duration_ms, share_permission_id, meeting_id)+ SELECT id, channel_id, room_name, created_by, created_at, 1000, share_permission_id, meeting_id FROM calls WHERE id = $1"#, call_id)+ .execute(&mut *tx).await.unwrap();+ sqlx::query!("DELETE FROM calls WHERE id = $1", call_id)+ .execute(&mut *tx)+ .await+ .unwrap();+ tx.commit().await.unwrap();+ assert!(repo.parent_exists(&parent).await.unwrap());+ assert_eq!(+ repo.get(&parent, call_id).await.unwrap().unwrap().content,+ "Persistent chat"+ );+ repo.create(call_message(call_id, "Archived reply"))+ .await+ .unwrap();+ sqlx::query!("DELETE FROM call_records WHERE id = $1", call_id)+ .execute(&pool)+ .await+ .unwrap();+ assert!(!repo.parent_exists(&parent).await.unwrap());+ assert!(repo.get(&parent, call_id).await.unwrap().is_none());+ assert!(repo.thread(&parent, call_id).await.unwrap().is_none());+ let mention_count = sqlx::query_scalar!(+ "SELECT count(*) FROM comms_entity_mentions WHERE source_entity_type = 'message' AND source_entity_id = $1",+ call_id.to_string(),+ ).fetch_one(&pool).await.unwrap();+ assert_eq!(mention_count, Some(0));+ assert!(matches!(+ repo.create(call_message(call_id, "Deleted parent")).await,+ Err(MessageError::NotFound)+ ));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn retrying_first_call_message_cannot_append_it_twice(pool: PgPool) {+ let call_id = setup_call_chat(&pool).await;+ let repo = PgMessageRepository::new(pool);+ let mut input = call_message(call_id, "First message");+ input.input.id = Some(macro_uuid::generate_uuid_v7());+ let client_message_id = input.input.id.unwrap();+ let actor = input.actor.clone();+ let parent = input.parent.clone();+ let first = repo.create(input.clone()).await.unwrap();+ assert_eq!(first.id, call_id);+ assert!(matches!(+ repo.create(input).await,+ Err(MessageError::Conflict)+ ));+ assert!(+ repo.replies(&MessageParent::Call(call_id), call_id)+ .await+ .unwrap()+ .is_empty()+ );+ let recovered = repo+ .get_by_client_message_id(&parent, &actor, client_message_id)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(recovered.id, call_id);+ assert_eq!(recovered.content, "First message");+ for (parent, actor) in [+ (+ MessageParent::Call(macro_uuid::generate_uuid_v7()),+ actor.clone(),+ ),+ (+ parent.clone(),+ "macro|[email protected]".to_owned().try_into().unwrap(),+ ),+ ] {+ assert!(+ repo.get_by_client_message_id(&parent, &actor, client_message_id)+ .await+ .unwrap()+ .is_none()+ );+ }+ repo.delete(&parent, call_id).await.unwrap();+ let deleted = repo+ .get_by_client_message_id(&parent, &actor, client_message_id)+ .await+ .unwrap()+ .unwrap();+ assert!(deleted.deleted_at.is_some());+ assert!(deleted.content.is_empty());+}diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 9b18c5d711..dd79a44dd6 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -756,6 +756,49 @@ produce one connection; leaving from either control ends the same call. Navigateaway and return while connected to check that the call and its controls remainusable.+The **Open chat** button in its own island at the far right of the bottom toolbar+opens the chat beside the video. The panel has no header or divider above the+composer. The media controls stay centered. On narrow screens it overlays the+video. The same toolbar button, now **Close chat**, or Escape closes the panel+and returns focus to the chat button; reopening preserves the draft and scroll+position. The call continues while chat is open or closed.++Signed-in participants in channel, quick, and scheduled calls use the same chat+panel. Guest meeting participants do not see chat because shared messages require+a Macro account. Each call session has one persistent message thread, using the+shared message composer, attachments, reactions, and message actions. The `@`+menu offers Macro and available owned and team agents. Mention an agent and send+to invoke it in the call thread; follow-up mentions use the same thread. Reply+on your own or another participant’s message inserts a quote into the bottom+composer while preserving its draft and attachments. Enter sends; subsequent+messages and quoted replies join the same thread. Clicking a quote highlights its+message in the live chat; Shift-click opens its durable saved-call link. Participants see new messages without reopening the panel.+Check simultaneous first sends from two participants, edit/delete/reaction+updates, a retained unsent draft after toggling chat, and a new incoming message+while scrolled into history.++After the call ends, its recording page shows a read-only **Call chat** below+the transcript. A copied chat message link opens+`/app/call/<callId>?call_message_id=<messageId>` and highlights that message in+the recording's chat. Clicking the highlighted message clears the target from+the pane's route while leaving chat expanded; verify this on standalone and+Drive recording pages. A transcript search result clears any earlier chat+target in that pane. In an already-open Home call preview, follow a second+message link and then open the call without a message target: the highlight+must move to the second message and then clear without remounting the preview.+After following a message link, scroll away and follow that same link again:+the view must return to the message. Check repeated links in Home, Drive, and+standalone recordings, and repeated quote clicks in live chat; navigation must+preserve the mounted thread and any unsent draft.+A new call in the same channel starts a separate thread.++An initial missing thread means the call has no messages yet. If a later chat+refresh reports the thread missing or access denied after messages loaded,+show the retry error and hide the stale thread. Verify that it never shows+the empty-conversation prompt alongside cached messages. A transient server+error may retain readable messages; Retry restores the thread when access+and the request recover.+For recovery checks, keep another participant connected and briefly interruptthe first participant's network. Recovery may rejoin that same live call. Itmust not start a replacement call if the original ended, or rejoin after thediff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 140b7698c0..038e7f54fd 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1042,6 +1042,15 @@ flag loads or is off, those controls stay hidden and meeting routes do not mountcall setup. Existing channel calls and the upcoming-events list remain available.For local verification, set `VITE_ENABLE_QUICK_CALLS=true` or `false` explicitly.+During a quick or scheduled call, signed-in participants can open **Call chat**+from its separate button at the far right of the bottom toolbar. Messages persist+with that call session and are visible in its recording page after it ends.+Guests do not see chat. The `@` menu includes Macro and available agents;+mentioning one invokes it in the call thread. Reply on any live message, including+your own, quotes it in the bottom composer. Verify the reply preserves a draft,+an agent reply appears, and messages remain in the saved history; starting a+new session from the same meeting link must start a separate chat thread.+Calendar event creation and editing open in a bottom sheet on touch devices,with scrollable content above the keyboard. Desktop retains the centered dialog.diff --git a/packages/lexical-core/nodes/ReplyTargetNode.ts b/packages/lexical-core/nodes/ReplyTargetNode.tsindex 5d319cd45d..da9f723952 100644--- a/packages/lexical-core/nodes/ReplyTargetNode.ts+++ b/packages/lexical-core/nodes/ReplyTargetNode.ts@@ -18,8 +18,20 @@ const VERSION = 2;export const REPLY_TARGET_NODE_TYPE = 'reply-target';export const REPLY_TARGET_NODE_TAG = 'm-reply-target';+export const REPLY_TARGET_PARENT_TYPES = [+ 'channel',+ 'document',+ 'initiative',+ 'crm_company',+ 'crm_contact',+ 'call',+] as const;+/** The message reference and preview persisted by a reply-target node. */-export type ReplyTargetParent = { type: 'channel' | 'document'; id: string };+export type ReplyTargetParent = {+ type: (typeof REPLY_TARGET_PARENT_TYPES)[number];+ id: string;+};export type ReplyTargetData = {parent: ReplyTargetParent;@@ -33,12 +45,12 @@ export type ReplyTargetData = {export function isReplyTargetData(value: unknown): value is ReplyTargetData {if (!value || typeof value !== 'object') return false;const data = value as Record<string, unknown>;+ if (!data.parent || typeof data.parent !== 'object') return false;+ const parent = data.parent as Record<string, unknown>;return (- !!data.parent &&- typeof data.parent === 'object' &&- ['channel', 'document'].includes((data.parent as ReplyTargetParent).type) &&- typeof (data.parent as ReplyTargetParent).id === 'string' &&- (data.parent as ReplyTargetParent).id.length > 0 &&+ REPLY_TARGET_PARENT_TYPES.some((type) => type === parent.type) &&+ typeof parent.id === 'string' &&+ parent.id.length > 0 &&typeof data.targetMessageId === 'string' &&typeof data.targetThreadId === 'string' &&typeof data.displayText === 'string' &&@@ -86,7 +98,7 @@ export type ReplyTargetDecoratorProps = ReplyTargetData & {theme: EditorThemeClasses;};-/** A block-level reference to another message in a channel thread. */+/** A block-level reference to another message in a conversation. */export class ReplyTargetNode extends DecoratorNode<DecoratorComponent<ReplyTargetDecoratorProps> | undefined> {@@ -207,7 +219,7 @@ export class ReplyTargetNode extends DecoratorNode<}}-/** Create a block-level channel reply-target reference. */+/** Create a block-level message reply-target reference. */export function $createReplyTargetNode(data: ReplyTargetData): ReplyTargetNode {return $applyNodeReplacement(new ReplyTargetNode(diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.tsindex 2f6006ee59..c22331b21b 100644--- a/packages/lexical-core/tests/agent-context.test.ts+++ b/packages/lexical-core/tests/agent-context.test.ts@@ -395,7 +395,8 @@ describe('composeAgentContextPrompt', () => {['initiative', 'a project comment thread'],['crm_company', 'a CRM company comment thread'],['crm_contact', 'a CRM contact comment thread'],- ] as const)('names a %s discussion as the origin', (type, surface) => {+ ['call', 'a call chat thread'],+ ] as const)('names a %s conversation as the origin', (type, surface) => {expect(composedContext({promptMarkdown: 'tell me more',diff --git a/packages/lexical-core/tests/reply-target-node.test.ts b/packages/lexical-core/tests/reply-target-node.test.tsindex ccbc6b88d3..3f0db9f1f4 100644--- a/packages/lexical-core/tests/reply-target-node.test.ts+++ b/packages/lexical-core/tests/reply-target-node.test.ts@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';import { NodeReplacements, SupportedNodeTypes } from '../node-list';import {buildReplyTargetMarkdown,+ readReplyTargetData,stripLeadingReplyTargetMarkdown,} from '../nodes/ReplyTargetNode';import { EXTERNAL_TRANSFORMERS } from '../transformers';@@ -43,10 +44,16 @@ describe('ReplyTargetNode', () => {});});- it('round-trips a document reply target', () => {+ it.each([+ 'document',+ 'initiative',+ 'crm_company',+ 'crm_contact',+ 'call',+ ] as const)('round-trips a %s reply target', (type) => {const target = {...data,- parent: { type: 'document' as const, id: 'document-1' },+ parent: { type, id: 'parent-1' },};const markdown = buildReplyTargetMarkdown(target);const state = markdownToSerializedEditorStateWithIds(markdown);@@ -54,6 +61,15 @@ describe('ReplyTargetNode', () => {expect(serializedEditorStateToMarkdown(state)).toBe(markdown);});+ it.each(['unknown', 'email', 'project'])(+ 'rejects unsupported parent %s',+ (type) => {+ expect(+ readReplyTargetData({ ...data, parent: { type, id: 'parent-1' } })+ ).toBeUndefined();+ }+ );+it('exposes its preview to plain text and embedding conversion', () => {expect(markdownToPlainText(markdown)).toBe(data.displayText);expect(markdownToEmbeddingText(markdown)).toBe(data.displayText);diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.tsindex 2313ca97df..b05415510e 100644--- a/packages/lexical-core/utils/agent-context.ts+++ b/packages/lexical-core/utils/agent-context.ts@@ -45,7 +45,13 @@ export type AgentContextReplyTarget =/** The authorized conversation a prompt was posted in. */export type AgentContextParent = {- type: 'channel' | 'document' | 'initiative' | 'crm_company' | 'crm_contact';+ type:+ | 'channel'+ | 'document'+ | 'initiative'+ | 'crm_company'+ | 'crm_contact'+ | 'call';id: string;};@@ -165,6 +171,7 @@ function describeOrigin(parent: AgentContextParent): string {.with('initiative', () => 'a project comment thread').with('crm_company', () => 'a CRM company comment thread').with('crm_contact', () => 'a CRM contact comment thread')+ .with('call', () => 'a call chat thread').exhaustive();return `This prompt was posted in ${surface}, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.`;}diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex dd823f699b..4b2371d383 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -248,6 +248,12 @@ macro.events.on('message.posted', async ({ metadata, target }) => {app.post('/webhook', (c) => macro.events.webhook()(c.req.raw));```+Call chat events have `event.target.type === 'call'`, with a `CallRecord` in+`event.target.call` and a `CallMessage` in `event.target.message`. Read with+`content()`, or call `reply(body)`, `edit(body)`, and `delete()`. Replies always+join the call's single chat thread, even when responding to another reply.+`macro.calls.byId(callId).message(messageId)` creates the same lazy message handle.+# Upgrading to 0.2Channel messages, document comments, and CRM company and contact comments sharediff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex c1693289a8..32d99df5be 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -1062,6 +1062,12 @@ export type MessageParent = {*/id: string;type: 'crm_contact';+} | {+ /**+ * A video call and its persistent chat thread.+ */+ id: string;+ type: 'call';};/**diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 19e56bf54a..08ca209b14 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -6803,6 +6803,12 @@ export type MessageParent = {*/id: string;type: 'crm_contact';+} | {+ /**+ * A video call and its persistent chat thread.+ */+ id: string;+ type: 'call';};/**diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex b23e9212d1..1c2020da63 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -3048,6 +3048,22 @@"enum": ["crm_contact"]}}+ },+ {+ "type": "object",+ "description": "A video call and its persistent chat thread.",+ "required": ["id", "type"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "A video call and its persistent chat thread."+ },+ "type": {+ "type": "string",+ "enum": ["call"]+ }+ }}],"description": "The entity whose permissions and lifecycle govern a message."diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 8753baee64..9f85450542 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -24613,6 +24613,22 @@"enum": ["crm_contact"]}}+ },+ {+ "type": "object",+ "description": "A video call and its persistent chat thread.",+ "required": ["id", "type"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "A video call and its persistent chat thread."+ },+ "type": {+ "type": "string",+ "enum": ["call"]+ }+ }}],"description": "The entity whose permissions and lifecycle govern a message."diff --git a/packages/sdk/src/entities/calls/call-record.ts b/packages/sdk/src/entities/calls/call-record.tsindex 380d65ab51..e3eb9491a7 100644--- a/packages/sdk/src/entities/calls/call-record.ts+++ b/packages/sdk/src/entities/calls/call-record.ts@@ -5,6 +5,7 @@ import { Channel } from '../channels/channel';import { FavoritableEntity } from '../entity';import { entitySearch } from '../search';import { User } from '../users/user';+import { CallMessage } from './message';type CallRecordDetail = GetCallRecordResponses[200];@@ -24,6 +25,11 @@ export class CallRecord extends FavoritableEntity<CallRecordDetail> {return new CallRecord(client, id);}+ /** A message in this call's persistent chat. Fields load on first access. */+ message(id: string): CallMessage {+ return CallMessage.byId(this.client, this.id, id);+ }+/** The call's display name (user-supplied or AI-generated; unset while active). */readonly name = this.field('customName');diff --git a/packages/sdk/src/entities/calls/message.ts b/packages/sdk/src/entities/calls/message.tsnew file mode 100644index 0000000000..f308e99ea4--- /dev/null+++ b/packages/sdk/src/entities/calls/message.ts@@ -0,0 +1,92 @@+import type { Message as MessageRecord } from '../../../generated/storage/types.gen';+import { type RichMessage, toBody } from '../../mentions';+import { unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import { MacroEntity } from '../entity';+import { User } from '../users/user';+import { CallRecord } from './call-record';++/** A message in a call's single persistent chat thread. */+export class CallMessage extends MacroEntity<MessageRecord> {+ private constructor(+ client: MacroClient,+ readonly callId: string,+ id: string,+ seed?: MessageRecord+ ) {+ super(client, id, seed);+ }++ private get path() {+ return { parent_type: 'call', parent_id: this.callId, id: this.id };+ }++ protected async fetch(): Promise<MessageRecord> {+ return unwrap(+ await this.client.storage.entityMessageGetMessage({ path: this.path })+ );+ }++ /** A handle to a message by id. Fields load on first access. */+ static byId(client: MacroClient, callId: string, id: string): CallMessage {+ return new CallMessage(client, callId, id);+ }++ /** Build a message from its record without another fetch. */+ static from(+ client: MacroClient,+ callId: string,+ record: MessageRecord+ ): CallMessage {+ return new CallMessage(client, callId, record.id, record);+ }++ /** The message body (markdown). */+ readonly content = this.field('content');++ /** When the message was created. */+ readonly createdAt = this.field('created_at');++ /** When the message was last updated. */+ readonly updatedAt = this.field('updated_at');++ /** The call whose chat contains this message. */+ call(): CallRecord {+ return CallRecord.byId(this.client, this.callId);+ }++ /** The user who sent this message. */+ async author(): Promise<User> {+ return User.byId(this.client, (await this.detail.get()).sender_id);+ }++ /** Reply in the call's canonical thread, including when this is a reply. */+ async reply(body: string | RichMessage): Promise<CallMessage> {+ const record = unwrap(+ await this.client.storage.entityMessageCreate({+ path: { parent_type: 'call', parent_id: this.callId },+ body: { ...toBody(body), thread_id: this.callId },+ })+ );+ return CallMessage.from(this.client, this.callId, record);+ }++ /** Replace this message's body. */+ async edit(body: string | RichMessage): Promise<this> {+ const { content, mentions } = toBody(body);+ await this.mutate((client) =>+ client.storage.entityMessageEdit({+ path: this.path,+ body: { content, mentions },+ })+ );+ return this;+ }++ /** Delete this message, preserving the rest of the call's chat. */+ async delete(): Promise<void> {+ await this.mutate((client) =>+ client.storage.entityMessageDeleteMessage({ path: this.path })+ );+ }+}diff --git a/packages/sdk/src/events/hydrate/message.ts b/packages/sdk/src/events/hydrate/message.tsindex 26f4593242..1440628251 100644--- a/packages/sdk/src/events/hydrate/message.ts+++ b/packages/sdk/src/events/hydrate/message.ts@@ -1,5 +1,7 @@import { match } from 'ts-pattern';import type { MessageParent } from '../../../generated/storage/types.gen';+import { CallRecord } from '../../entities/calls/call-record';+import { CallMessage } from '../../entities/calls/message';import { Channel } from '../../entities/channels/channel';import { Message } from '../../entities/channels/message';import { Thread } from '../../entities/channels/thread';@@ -18,10 +20,18 @@ export type MessageEvent = Extract</*** The entity a message event belongs to. Channel messages hydrate a `Channel`,* a `Message`, and the `Thread` for replies; document comments hydrate a- * `Document` and a `Comment`. Both handles share `reply`, `edit`, `delete`,+ * `Document` and a `Comment`. Call chat hydrates a `CallRecord` and a+ * `CallMessage`. The message handles share `reply`, `edit`, `delete`,* `author`, and `content`/`text` reads.*/export type MessageEventTarget =+ | {+ type: 'call';+ call: CallRecord;+ message: CallMessage;+ /** The call id is also its canonical chat thread id. */+ threadId: string;+ }| {type: 'channel';channel: Channel;@@ -45,9 +55,17 @@ function target(thread_id?: string | null;root_id: string;},- mentions: SimpleMention[] = [],+ mentions: SimpleMention[] = []): MessageEventTarget {const parent = metadata.parent;+ if (parent.type === 'call') {+ return {+ type: 'call',+ call: CallRecord.byId(client, parent.id),+ message: CallMessage.byId(client, parent.id, metadata.message_id),+ threadId: parent.id,+ };+ }if (parent.type === 'channel') {return {type: 'channel',diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.tsindex a8424269ad..b43dd5a43f 100644--- a/packages/sdk/src/macro.ts+++ b/packages/sdk/src/macro.ts@@ -23,6 +23,7 @@ import type { MacroEvents } from './events/receiver';import { MacroClient } from './utils/client';export type { MacroOpts } from './config';+export type { CallMessage } from './entities/calls/message';export type { ListenOptions, MacroEvents } from './events/receiver';export {here,diff --git a/packages/sdk/tests/messages.test.ts b/packages/sdk/tests/messages.test.tsindex 56da099a51..58e84d08b2 100644--- a/packages/sdk/tests/messages.test.ts+++ b/packages/sdk/tests/messages.test.ts@@ -5,6 +5,7 @@ import type {MessageListItem,MessageThread,} from '../generated/storage/types.gen';+import { hydrateMessageEvent } from '../src/events/hydrate/message';import { Macro, msg } from '../src/macro';const originalFetch = globalThis.fetch;@@ -13,6 +14,7 @@ const channelId = '0198a4cc-e138-7670-a308-a6b766602700';const documentId = '0198a4cc-e138-7670-a308-a6b766602701';const companyId = '0198a4cc-e138-7670-a308-a6b766602704';const contactId = '0198a4cc-e138-7670-a308-a6b766602705';+const callId = '0198a4cc-e138-7670-a308-a6b766602706';const rootId = '0198a4cc-e138-7670-a308-a6b766602702';const replyId = '0198a4cc-e138-7670-a308-a6b766602703';const timestamp = '2026-09-09T12:00:00Z';@@ -78,6 +80,92 @@ function macro() {}describe('shared message API contracts', () => {+ test.each([callId, replyId])(+ 'call message events hydrate call handles and keep replies in the call thread (%s)',+ async (messageId) => {+ const parent = { type: 'call', id: callId } as const;+ const path = `/messages/call/${callId}`;+ let record = message({+ id: messageId,+ parent,+ thread_id: messageId === callId ? null : callId,+ });+ const requests = serve(async (request) => {+ const url = new URL(request.url);+ if (url.pathname === `${path}/items/${messageId}`) {+ if (request.method === 'PATCH') {+ record = { ...record, ...(await request.json()) };+ }+ if (request.method === 'DELETE') {+ record = { ...record, deleted_at: timestamp, content: '' };+ }+ return Response.json(record);+ }+ if (url.pathname === path && request.method === 'POST') {+ const body = await request.json();+ expect(body.thread_id).toBe(callId);+ return Response.json(+ message({ ...body, parent, id: rootId, thread_id: callId })+ );+ }+ return new Response(null, { status: 404 });+ });+ const client = macro();+ const event = hydrateMessageEvent(client._client, {+ event_type: 'message.posted',+ metadata: {+ parent,+ root_id: callId,+ message_id: messageId,+ thread_id: record.thread_id,+ content: record.content,+ sender: record.sender_id,+ created_at: timestamp,+ attachments: [],+ mentions: [],+ },+ });+ if (event.target.type !== 'call') throw new Error(event.target.type);+ expect(requests).toHaveLength(0);+ expect(event.target.call.id).toBe(callId);+ expect(event.target.threadId).toBe(callId);+ expect(event.target.message.id).toBe(messageId);+ expect(event.target.message.call().id).toBe(callId);+ expect(client.calls.byId(callId).message(messageId).callId).toBe(callId);+ await expect(event.target.message.content()).resolves.toBe(+ record.content+ );+ expect((await event.target.message.author()).id).toBe(record.sender_id);++ await event.target.message.edit('Edited call message');+ await expect(event.target.message.content()).resolves.toBe(+ 'Edited call message'+ );+ const body = msg`Thanks ${client.users.byId('macro|[email protected]')}`;+ const reply = await event.target.message.reply(body);+ expect(reply.callId).toBe(callId);+ await expect(reply.content()).resolves.toBe(body.content);+ await event.target.message.delete();++ expect(+ requests.map((request) => [+ request.method,+ new URL(request.url).pathname,+ ])+ ).toEqual([+ ['GET', `${path}/items/${messageId}`],+ ['PATCH', `${path}/items/${messageId}`],+ ['GET', `${path}/items/${messageId}`],+ ['POST', path],+ ['DELETE', `${path}/items/${messageId}`],+ ]);+ await expect(requests[3]?.json()).resolves.toMatchObject({+ ...body,+ thread_id: callId,+ });+ }+ );+test('channel posts, lazy reads, edits, reactions, and deletes use message routes', async () => {let record = message();const path = `/messages/channel/${channelId}`;@@ -127,8 +215,8 @@ describe('shared message API contracts', () => {]);expect(requests.every(- (r) => r.headers.get('authorization') === 'Bearer user-token',- ),+ (r) => r.headers.get('authorization') === 'Bearer user-token'+ )).toBe(true);await expect(requests[0]?.json()).resolves.toMatchObject(body);await expect(requests[4]?.json()).resolves.toEqual({@@ -294,7 +382,7 @@ describe('shared message API contracts', () => {id: `reply-${index}`,thread_id: rootId,content: `Reply ${index}`,- }),+ }));const full = thread(root, replies);const cursor = { id: root.id, created_at: timestamp };@@ -310,7 +398,7 @@ describe('shared message API contracts', () => {return Response.json(selection.cursor? { items: [listItem(thread(secondRoot))], next_cursor: null }- : { items: [listItem(full)], next_cursor: cursor },+ : { items: [listItem(full)], next_cursor: cursor });}return new Response(null, { status: 404 });@@ -349,7 +437,7 @@ describe('shared message API contracts', () => {if (url.pathname === path && request.method === 'POST') {const body = await request.json();return Response.json(- body.thread_id ? reply : { ...root, content: body.content },+ body.thread_id ? reply : { ...root, content: body.content });}if (url.pathname === `${path}/items/${replyId}`) {@@ -376,7 +464,7 @@ describe('shared message API contracts', () => {const writes = requests.filter((request) => request.method !== 'GET');expect(- writes.map((request) => [request.method, new URL(request.url).pathname]),+ writes.map((request) => [request.method, new URL(request.url).pathname])).toEqual([['POST', path],['POST', path],@@ -394,7 +482,7 @@ describe('shared message API contracts', () => {const parent = { type: 'crm_contact', id: contactId } as const;const path = `/messages/crm_contact/${contactId}`;const requests = serve(() =>- Response.json(message({ parent, content: 'Met at the conference' })),+ Response.json(message({ parent, content: 'Met at the conference' })));const comment = await macro().crm.contactById(contactId)@@ -429,7 +517,7 @@ describe('shared message API contracts', () => {await user.channels.byId(channelId).send('User bot');expect(requests[3]?.headers.get('x-macro-bot-scope')).toBe('user');await expect(- user.channels.byId(channelId).message(rootId).reply('Reply'),+ user.channels.byId(channelId).message(rootId).reply('Reply')).rejects.toThrow('does not support threads');expect(requests).toHaveLength(4);});diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex 63b506130d..812d87d17f 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -17,6 +17,7 @@ files:- apps/web/src/features/channels-view/components/ChannelDetailView*- apps/web/src/features/channel/components/channel-invite*- apps/web/src/features/projects/components/**+ - apps/web/src/features/channel/Call/chat/components/**- apps/web/src/features/block-agent/ui/**- apps/web/src/features/meetings/components/**- apps/web/src/features/block-spreadsheet/components/**diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex ad8f378a6f..f10e58304d 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -18,6 +18,7 @@ files:- apps/web/src/features/crm/core/**- apps/web/src/features/channel/core/channel-invite*- apps/web/src/features/projects/core/**+ - apps/web/src/features/channel/Call/chat/core/**- apps/web/src/features/block-agent/core/**- apps/web/src/features/meetings/core/**- apps/web/src/features/block-spreadsheet/core/**diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex 489580abcc..41eda0a7c1 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -19,6 +19,8 @@ files:- apps/web/src/features/channel/primitives/create-channel-invites*- apps/web/src/features/projects/queries/**- apps/web/src/features/projects/primitives/**+ - apps/web/src/features/channel/Call/chat/queries/**+ - apps/web/src/features/channel/Call/chat/primitives/**- apps/web/src/features/block-agent/queries/**- apps/web/src/features/block-agent/primitives/**- apps/web/src/features/meetings/queries/**diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex 37424f6dba..9c18a3cd20 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -33,6 +33,10 @@ files:- apps/web/src/features/projects/components/**- apps/web/src/features/projects/views/**- apps/web/src/features/projects/context/**+ - apps/web/src/features/channel/Call/chat/queries/**+ - apps/web/src/features/channel/Call/chat/primitives/**+ - apps/web/src/features/channel/Call/chat/components/**+ - apps/web/src/features/channel/Call/chat/views/**- apps/web/src/features/block-agent/queries/**- apps/web/src/features/block-agent/primitives/**- apps/web/src/features/block-agent/ui/**diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex 28c96c20de..ba3b21e4cc 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -17,6 +17,7 @@ files:- apps/web/src/features/channels-view/components/ChannelDetailView*- apps/web/src/features/channel/components/channel-invite*- apps/web/src/features/projects/components/**+ - apps/web/src/features/channel/Call/chat/components/**- apps/web/src/features/block-agent/ui/**- apps/web/src/features/meetings/components/**- apps/web/src/features/block-spreadsheet/components/**diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 13d50c2127..9b94b7f03f 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -18,6 +18,7 @@ files:- apps/web/src/features/crm/core/**- apps/web/src/features/channel/core/channel-invite*- apps/web/src/features/projects/core/**+ - apps/web/src/features/channel/Call/chat/core/**- apps/web/src/features/block-agent/core/**- apps/web/src/features/meetings/core/**- apps/web/src/features/block-spreadsheet/core/**diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex 4e58e2ebc3..e0763cbc45 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -19,6 +19,8 @@ files:- apps/web/src/features/channel/primitives/create-channel-invites*- apps/web/src/features/projects/queries/**- apps/web/src/features/projects/primitives/**+ - apps/web/src/features/channel/Call/chat/queries/**+ - apps/web/src/features/channel/Call/chat/primitives/**- apps/web/src/features/block-agent/queries/**- apps/web/src/features/block-agent/primitives/**- apps/web/src/features/meetings/queries/**diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex 13220a9e8f..77963787cb 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -33,6 +33,10 @@ files:- apps/web/src/features/projects/components/**- apps/web/src/features/projects/views/**- apps/web/src/features/projects/context/**+ - apps/web/src/features/channel/Call/chat/queries/**+ - apps/web/src/features/channel/Call/chat/primitives/**+ - apps/web/src/features/channel/Call/chat/components/**+ - apps/web/src/features/channel/Call/chat/views/**- apps/web/src/features/block-agent/queries/**- apps/web/src/features/block-agent/primitives/**- apps/web/src/features/block-agent/ui/**diff --git a/services/lexical-service/src/endpoints/agent-announcement.test.ts b/services/lexical-service/src/endpoints/agent-announcement.test.tsindex 94ff583683..a7d9c18eb3 100644--- a/services/lexical-service/src/endpoints/agent-announcement.test.ts+++ b/services/lexical-service/src/endpoints/agent-announcement.test.ts@@ -54,8 +54,15 @@ describe('agent announcements', () => {);expect(markdown).not.toContain('m-reply-target');});- it('announces under the parent the reply lives in', async () => {- const parent = { type: 'document' as const, id: 'doc' };+ it.each([+ 'channel',+ 'document',+ 'initiative',+ 'crm_company',+ 'crm_contact',+ 'call',+ ])('announces under the %s parent the reply lives in', async (type) => {+ const parent = { type, id: 'parent-1' };const response = await request({replyTarget: { parent, ...replyTarget },chip,diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.tsindex 4152a54252..a973821dfe 100644--- a/services/lexical-service/src/endpoints/agent-announcement.ts+++ b/services/lexical-service/src/endpoints/agent-announcement.ts@@ -3,7 +3,10 @@ import {MAGIC_CHIP_AUTHORS,MAGIC_CHIP_STATUSES,} from '@macro-inc/lexical-core/nodes/MagicChipNode';-import type { ReplyTargetParent } from '@macro-inc/lexical-core/nodes/ReplyTargetNode';+import {+ REPLY_TARGET_PARENT_TYPES,+ type ReplyTargetParent,+} from '@macro-inc/lexical-core/nodes/ReplyTargetNode';import { composeAgentSessionAnnouncement } from '@macro-inc/lexical-core/utils/agent-announcement';import { composeAgentChatReply } from '@macro-inc/lexical-core/utils/agent-chat-reply';import { composeAgentConnectionPrompt } from '@macro-inc/lexical-core/utils/agent-connection-prompt';@@ -14,7 +17,7 @@ import { handleEndpointError } from '../lib/error-handler';import { standardErrorResponses } from '../lib/schemas';const messageParent = z.object({- type: z.enum(['channel', 'document']),+ type: z.enum(REPLY_TARGET_PARENT_TYPES),id: z.string().min(1),});diff --git a/services/lexical-service/src/endpoints/agent-context.test.ts b/services/lexical-service/src/endpoints/agent-context.test.tsindex 07cc0deca7..20bc7b4957 100644--- a/services/lexical-service/src/endpoints/agent-context.test.ts+++ b/services/lexical-service/src/endpoints/agent-context.test.ts@@ -14,16 +14,20 @@ const request = (body: unknown) =>});describe('agent context', () => {- it.each(['channel', 'document', 'initiative', 'crm_company', 'crm_contact'])(- 'composes a prompt posted on a %s parent',- async (type) => {- const response = await request({- promptMarkdown: 'tell me more',- parent: { type, id: 'parent-1' },- });- expect(response.status).toBe(200);- const { markdown } = await response.json<{ markdown: string }>();- expect(markdown).toContain(`conversation type=\\"${type}\\"`);- }- );+ it.each([+ 'channel',+ 'document',+ 'initiative',+ 'crm_company',+ 'crm_contact',+ 'call',+ ])('composes a prompt posted on a %s parent', async (type) => {+ const response = await request({+ promptMarkdown: 'tell me more',+ parent: { type, id: 'parent-1' },+ });+ expect(response.status).toBe(200);+ const { markdown } = await response.json<{ markdown: string }>();+ expect(markdown).toContain(`conversation type=\\"${type}\\"`);+ });});diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.tsindex 14e5a22f0b..7002b30a46 100644--- a/services/lexical-service/src/endpoints/agent-context.ts+++ b/services/lexical-service/src/endpoints/agent-context.ts@@ -12,6 +12,7 @@ const messageParent = z.object({'initiative','crm_company','crm_contact',+ 'call',]),id: z.string().min(1),});diff --git a/services/lexical-service/src/endpoints/extract-reply.test.ts b/services/lexical-service/src/endpoints/extract-reply.test.tsindex 78c10a88e1..7dc42e0cbf 100644--- a/services/lexical-service/src/endpoints/extract-reply.test.ts+++ b/services/lexical-service/src/endpoints/extract-reply.test.ts@@ -20,8 +20,15 @@ const target = {};describe('extract reply', () => {- it('returns the parent of a leading reply target', async () => {- const parent = { type: 'channel', id: 'channel' };+ it.each([+ 'channel',+ 'document',+ 'initiative',+ 'crm_company',+ 'crm_contact',+ 'call',+ ])('returns the %s parent of a leading reply target', async (type) => {+ const parent = { type, id: 'parent-1' };const response = await request(`<m-reply-target>${JSON.stringify({ parent, ...target })}</m-reply-target>\n\nplease fix`);diff --git a/services/lexical-service/src/endpoints/extract-reply.ts b/services/lexical-service/src/endpoints/extract-reply.tsindex 8ae081d365..c0ddf77d19 100644--- a/services/lexical-service/src/endpoints/extract-reply.ts+++ b/services/lexical-service/src/endpoints/extract-reply.ts@@ -1,3 +1,4 @@+import { REPLY_TARGET_PARENT_TYPES } from '@macro-inc/lexical-core/nodes/ReplyTargetNode';import { extractExplicitReply } from '@macro-inc/lexical-core/utils/explicit-reply';import { OpenAPIRoute } from 'chanfana';import type { Context } from 'hono';@@ -11,7 +12,7 @@ const extractReplyRequest = z.object({const replyTarget = z.object({parent: z.object({- type: z.enum(['channel', 'document']),+ type: z.enum(REPLY_TARGET_PARENT_TYPES),id: z.string(),}),targetMessageId: z.string(),