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
fix(agents): align session sharing with tasks (#6780)
Eric Hayes75a111bf67e5
diff --git a/.sqlx/query-08099d03d67a7546f8b64bd35a9d33a328cd502da43df681d0f875017f4454b3.json b/.sqlx/query-08099d03d67a7546f8b64bd35a9d33a328cd502da43df681d0f875017f4454b3.jsonnew file mode 100644index 0000000000..3fe4afca99--- /dev/null+++ b/.sqlx/query-08099d03d67a7546f8b64bd35a9d33a328cd502da43df681d0f875017f4454b3.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM team_user WHERE user_id = 'macro|[email protected]'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "08099d03d67a7546f8b64bd35a9d33a328cd502da43df681d0f875017f4454b3"+}diff --git a/.sqlx/query-1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5.json b/.sqlx/query-1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5.jsonnew file mode 100644index 0000000000..a0253ea0cf--- /dev/null+++ b/.sqlx/query-1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM agent_session\n WHERE id = $1\n RETURNING share_permission_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "share_permission_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "1edf28fd90647dd3866022069d81e713044bf23dbecfb2bbba03c5f753d261d5"+}diff --git a/.sqlx/query-2feb4077df8f55d8a26d4a05c29db63430a228378a4251a3c304dc56f2f5fd75.json b/.sqlx/query-2feb4077df8f55d8a26d4a05c29db63430a228378a4251a3c304dc56f2f5fd75.jsonnew file mode 100644index 0000000000..caa104b945--- /dev/null+++ b/.sqlx/query-2feb4077df8f55d8a26d4a05c29db63430a228378a4251a3c304dc56f2f5fd75.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT source_id AS channel_id, access_level AS \"access_level: AccessLevel\"\n FROM entity_access\n WHERE entity_id = $1 AND entity_type = 'agent_session' AND source_type = 'channel'\n AND granted_from_project_id IS NULL\n ORDER BY source_id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "channel_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "access_level: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "2feb4077df8f55d8a26d4a05c29db63430a228378a4251a3c304dc56f2f5fd75"+}diff --git a/.sqlx/query-345204da35a24b117169cc4d9634134e937be04811f9131bacac90f33048954c.json b/.sqlx/query-345204da35a24b117169cc4d9634134e937be04811f9131bacac90f33048954c.jsonnew file mode 100644index 0000000000..cf51acc5e3--- /dev/null+++ b/.sqlx/query-345204da35a24b117169cc4d9634134e937be04811f9131bacac90f33048954c.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM \"SharePermission\" WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "345204da35a24b117169cc4d9634134e937be04811f9131bacac90f33048954c"+}diff --git a/.sqlx/query-3be9d6b028e1e403360eb3a5b7efb90db68325a3e4105fc4e3ad32283b96a56c.json b/.sqlx/query-3be9d6b028e1e403360eb3a5b7efb90db68325a3e4105fc4e3ad32283b96a56c.jsonnew file mode 100644index 0000000000..7eeb05f5a0--- /dev/null+++ b/.sqlx/query-3be9d6b028e1e403360eb3a5b7efb90db68325a3e4105fc4e3ad32283b96a56c.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE agent_session SET share_permission_id = 'initialized-session' WHERE id = '20000000-0000-0000-0000-000000000010'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "3be9d6b028e1e403360eb3a5b7efb90db68325a3e4105fc4e3ad32283b96a56c"+}diff --git a/.sqlx/query-43d36c997fba93604673047e1b20134f434a08c57491fe853ace520bbc9fbfcb.json b/.sqlx/query-43d36c997fba93604673047e1b20134f434a08c57491fe853ace520bbc9fbfcb.jsonnew file mode 100644index 0000000000..065f156fe5--- /dev/null+++ b/.sqlx/query-43d36c997fba93604673047e1b20134f434a08c57491fe853ace520bbc9fbfcb.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"SharePermission\" SET \"linkShare\" = NULL, \"linkShareAccessLevel\" = NULL\n WHERE id = 'session-public'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "43d36c997fba93604673047e1b20134f434a08c57491fe853ace520bbc9fbfcb"+}diff --git a/.sqlx/query-508a50a7db2d19d805bc46358de074c88e8fd976dbcae90ebfc18fae8d2f1bc9.json b/.sqlx/query-508a50a7db2d19d805bc46358de074c88e8fd976dbcae90ebfc18fae8d2f1bc9.jsonnew file mode 100644index 0000000000..707c68f48f--- /dev/null+++ b/.sqlx/query-508a50a7db2d19d805bc46358de074c88e8fd976dbcae90ebfc18fae8d2f1bc9.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, $2, $3, 'channel', $4)\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL DO NOTHING",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "508a50a7db2d19d805bc46358de074c88e8fd976dbcae90ebfc18fae8d2f1bc9"+}diff --git a/.sqlx/query-70f39a90ce043a272b3b6a16163da542f73447047593e7ed35b2f9145d012ff7.json b/.sqlx/query-70f39a90ce043a272b3b6a16163da542f73447047593e7ed35b2f9145d012ff7.jsonnew file mode 100644index 0000000000..0994fcc1a0--- /dev/null+++ b/.sqlx/query-70f39a90ce043a272b3b6a16163da542f73447047593e7ed35b2f9145d012ff7.json@@ -0,0 +1,70 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT s.owner_id, s.share_permission_id,\n sp.\"linkShare\" AS \"link_share: LinkShare\",\n sp.\"linkShareAccessLevel\" AS \"link_level: AccessLevel\",\n sp.team_share_access_level AS \"team_level: AccessLevel\"\n FROM agent_session s\n LEFT JOIN \"SharePermission\" sp ON sp.id = s.share_permission_id\n WHERE s.id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "share_permission_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share: LinkShare",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "link_level: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 4,+ "name": "team_level: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "70f39a90ce043a272b3b6a16163da542f73447047593e7ed35b2f9145d012ff7"+}diff --git a/.sqlx/query-7b30d6496b8bf268e37b21a75a8ea8b526efa8ae9e807e6f921b15987ee98755.json b/.sqlx/query-7b30d6496b8bf268e37b21a75a8ea8b526efa8ae9e807e6f921b15987ee98755.jsonnew file mode 100644index 0000000000..858719617f--- /dev/null+++ b/.sqlx/query-7b30d6496b8bf268e37b21a75a8ea8b526efa8ae9e807e6f921b15987ee98755.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"SharePermission\" SET\n \"linkShare\" = CASE WHEN $2 THEN $3 ELSE \"linkShare\" END,\n \"linkShareAccessLevel\" = CASE\n WHEN $2 AND $3 IS NULL THEN NULL\n WHEN $2 THEN COALESCE($5::\"AccessLevel\", 'view')\n WHEN $4 AND \"linkShare\" IS NOT NULL THEN COALESCE($5::\"AccessLevel\", 'view')\n WHEN $4 THEN NULL\n ELSE \"linkShareAccessLevel\"\n END,\n \"updatedAt\" = NOW()\n WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Bool",+ "Text",+ "Bool",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "7b30d6496b8bf268e37b21a75a8ea8b526efa8ae9e807e6f921b15987ee98755"+}diff --git a/.sqlx/query-815b092e4d0ebf123f0a912b16c390d5ad8cdc9fe9f65853e5dfdc06a28ea725.json b/.sqlx/query-815b092e4d0ebf123f0a912b16c390d5ad8cdc9fe9f65853e5dfdc06a28ea725.jsonnew file mode 100644index 0000000000..4cd15d93c8--- /dev/null+++ b/.sqlx/query-815b092e4d0ebf123f0a912b16c390d5ad8cdc9fe9f65853e5dfdc06a28ea725.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT access_level::text\n FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'agent_session'\n AND source_id = ANY($2)\n\n UNION ALL\n\n SELECT sp.\"linkShareAccessLevel\"::text\n FROM agent_session s\n JOIN \"SharePermission\" sp ON sp.id = s.share_permission_id\n WHERE s.id = $1\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1 FROM team_user owner_team\n WHERE owner_team.user_id = s.owner_id\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "815b092e4d0ebf123f0a912b16c390d5ad8cdc9fe9f65853e5dfdc06a28ea725"+}diff --git a/.sqlx/query-a464a5dd3b8f0149e9bf0daf1da30a84a7f01438235e353a9b2fdcd0f90b8ab3.json b/.sqlx/query-a464a5dd3b8f0149e9bf0daf1da30a84a7f01438235e353a9b2fdcd0f90b8ab3.jsonnew file mode 100644index 0000000000..5ee629522a--- /dev/null+++ b/.sqlx/query-a464a5dd3b8f0149e9bf0daf1da30a84a7f01438235e353a9b2fdcd0f90b8ab3.json@@ -0,0 +1,72 @@+{+ "db_name": "PostgreSQL",+ "query": "WITH entity AS (\n SELECT d.owner, dp.\"sharePermissionId\" AS permission_id\n FROM \"Document\" d LEFT JOIN \"DocumentPermission\" dp ON dp.\"documentId\" = d.id\n WHERE $2 = 'document' AND d.id = $1\n UNION ALL\n SELECT p.\"userId\", pp.\"sharePermissionId\"\n FROM \"Project\" p LEFT JOIN \"ProjectPermission\" pp ON pp.\"projectId\" = p.id\n WHERE $2 = 'project' AND p.id = $1\n UNION ALL\n SELECT c.\"userId\", cp.\"sharePermissionId\"\n FROM \"Chat\" c LEFT JOIN \"ChatPermission\" cp ON cp.\"chatId\" = c.id\n WHERE $2 = 'chat' AND c.id = $1\n UNION ALL\n SELECT l.macro_id, tp.\"sharePermissionId\"\n FROM email_threads t JOIN email_links l ON l.id = t.link_id\n LEFT JOIN \"EmailThreadPermission\" tp ON tp.\"threadId\" = t.id::text\n WHERE $2 = 'email_thread' AND t.id = $3\n UNION ALL\n SELECT c.created_by, c.share_permission_id FROM calls c\n WHERE $2 = 'call' AND c.id = $3\n UNION ALL\n SELECT c.created_by, c.share_permission_id FROM call_records c\n WHERE $2 = 'call' AND c.id = $3 AND NOT EXISTS (SELECT 1 FROM calls WHERE id = $3)\n UNION ALL\n SELECT i.owner_user_id, i.share_permission_id FROM initiative i\n WHERE $2 = 'initiative' AND i.id = $3\n UNION ALL\n SELECT s.owner_id, s.share_permission_id FROM agent_session s\n WHERE $2 = 'agent_session' AND s.id = $3\n )\n SELECT e.owner AS \"owner!\", e.permission_id,\n sp.id AS \"stored_permission_id?\",\n sp.team_share_access_level AS \"level: AccessLevel\",\n sp.team_share_team_id AS team_id, sp.team_share_revision AS \"revision?\",\n (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = e.owner\n ORDER BY tu.team_role DESC LIMIT 1) AS owner_team_id\n FROM entity e LEFT JOIN \"SharePermission\" sp ON sp.id = e.permission_id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "permission_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "stored_permission_id?",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "level: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 4,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 5,+ "name": "revision?",+ "type_info": "Int8"+ },+ {+ "ordinal": 6,+ "name": "owner_team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ null,+ null,+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "a464a5dd3b8f0149e9bf0daf1da30a84a7f01438235e353a9b2fdcd0f90b8ab3"+}diff --git a/.sqlx/query-aa2042782493298aa7a1ad09179de7b94288f5c667e1df8d6e21a3a739b19dc8.json b/.sqlx/query-aa2042782493298aa7a1ad09179de7b94288f5c667e1df8d6e21a3a739b19dc8.jsonnew file mode 100644index 0000000000..820a0842c3--- /dev/null+++ b/.sqlx/query-aa2042782493298aa7a1ad09179de7b94288f5c667e1df8d6e21a3a739b19dc8.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\",\n sp.\"linkShare\" = 'PUBLIC' AS \"is_public!\",\n owner_team.team_id AS \"team_id?\"\n FROM agent_session s\n JOIN \"SharePermission\" sp ON sp.id = s.share_permission_id\n LEFT JOIN team_user owner_team ON owner_team.user_id = s.owner_id\n WHERE s.id = $1\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (sp.\"linkShare\" = 'TEAM' AND owner_team.team_id::text = ANY($2))\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level!: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 1,+ "name": "is_public!",+ "type_info": "Bool"+ },+ {+ "ordinal": 2,+ "name": "team_id?",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ true,+ null,+ false+ ]+ },+ "hash": "aa2042782493298aa7a1ad09179de7b94288f5c667e1df8d6e21a3a739b19dc8"+}diff --git a/.sqlx/query-aafcf206e3b09e46234ea9677c5b962ca9f34fbc359f44da5b490499b289d25b.json b/.sqlx/query-aafcf206e3b09e46234ea9677c5b962ca9f34fbc359f44da5b490499b289d25b.jsonnew file mode 100644index 0000000000..d99e0ec10c--- /dev/null+++ b/.sqlx/query-aafcf206e3b09e46234ea9677c5b962ca9f34fbc359f44da5b490499b289d25b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE agent_session SET share_permission_id = $2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "aafcf206e3b09e46234ea9677c5b962ca9f34fbc359f44da5b490499b289d25b"+}diff --git a/.sqlx/query-bae0d700dfb2eab6bb9c94fafaca8b4d9ba83c3de0ff84609c252ac30d19b3ea.json b/.sqlx/query-bae0d700dfb2eab6bb9c94fafaca8b4d9ba83c3de0ff84609c252ac30d19b3ea.jsonnew file mode 100644index 0000000000..4a0c5799b0--- /dev/null+++ b/.sqlx/query-bae0d700dfb2eab6bb9c94fafaca8b4d9ba83c3de0ff84609c252ac30d19b3ea.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"SharePermission\" (id, \"createdAt\", \"updatedAt\") VALUES ($1, NOW(), NOW())",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "bae0d700dfb2eab6bb9c94fafaca8b4d9ba83c3de0ff84609c252ac30d19b3ea"+}diff --git a/.sqlx/query-d1cd1371be8624aaf8a07be1b728dbac1856beea446e4ee099ff6d8262f6befd.json b/.sqlx/query-d1cd1371be8624aaf8a07be1b728dbac1856beea446e4ee099ff6d8262f6befd.jsonnew file mode 100644index 0000000000..c15f70a74e--- /dev/null+++ b/.sqlx/query-d1cd1371be8624aaf8a07be1b728dbac1856beea446e4ee099ff6d8262f6befd.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT EXISTS(SELECT 1 FROM \"SharePermission\" WHERE id = $1) AS \"exists!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "d1cd1371be8624aaf8a07be1b728dbac1856beea446e4ee099ff6d8262f6befd"+}diff --git a/.sqlx/query-d41ddfbac9ee4f0aa4bd6f29c8b06b65eb1447587a1bc0063a4ad6166108f8f9.json b/.sqlx/query-d41ddfbac9ee4f0aa4bd6f29c8b06b65eb1447587a1bc0063a4ad6166108f8f9.jsonnew file mode 100644index 0000000000..63489d49ee--- /dev/null+++ b/.sqlx/query-d41ddfbac9ee4f0aa4bd6f29c8b06b65eb1447587a1bc0063a4ad6166108f8f9.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"SharePermission\" (id) VALUES ('initialized-session')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "d41ddfbac9ee4f0aa4bd6f29c8b06b65eb1447587a1bc0063a4ad6166108f8f9"+}diff --git a/.sqlx/query-dd6f9906f208dc2ef01da6cacae56264e30129ae8e309da34f7a1ad0a6b20e38.json b/.sqlx/query-dd6f9906f208dc2ef01da6cacae56264e30129ae8e309da34f7a1ad0a6b20e38.jsonnew file mode 100644index 0000000000..109040a2f1--- /dev/null+++ b/.sqlx/query-dd6f9906f208dc2ef01da6cacae56264e30129ae8e309da34f7a1ad0a6b20e38.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT access_level AS \"access_level: AccessLevel\" FROM entity_access\n WHERE entity_id = $1 AND entity_type = 'agent_session' AND source_id = $2\n AND source_type = 'channel' AND granted_from_project_id IS NULL",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "dd6f9906f208dc2ef01da6cacae56264e30129ae8e309da34f7a1ad0a6b20e38"+}diff --git a/.sqlx/query-e825b6fb917af9a01cc80f8192d3e1e2ce5ad8fd2deb117b6367928dc1257d83.json b/.sqlx/query-e825b6fb917af9a01cc80f8192d3e1e2ce5ad8fd2deb117b6367928dc1257d83.jsonnew file mode 100644index 0000000000..e0d8842249--- /dev/null+++ b/.sqlx/query-e825b6fb917af9a01cc80f8192d3e1e2ce5ad8fd2deb117b6367928dc1257d83.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT share_permission_id FROM agent_session WHERE id = $1 FOR UPDATE",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "share_permission_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "e825b6fb917af9a01cc80f8192d3e1e2ce5ad8fd2deb117b6367928dc1257d83"+}diff --git a/Cargo.lock b/Cargo.lockindex 5161bd3b27..0489a76335 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -533,6 +533,7 @@ dependencies = ["model-entity","model_owner","model_user",+ "models_permissions","non_empty","opentelemetry","opentelemetry_sdk",@@ -540,6 +541,7 @@ dependencies = ["schemars 1.2.1","serde","serde_json",+ "share_permission_db_utils","sqlx","strum 0.27.2","thiserror 2.0.18",diff --git a/apps/web/src/components/app/ResponsiveBlockToolbar.tsx b/apps/web/src/components/app/ResponsiveBlockToolbar.tsxindex c8e317c927..74380f49f7 100644--- a/apps/web/src/components/app/ResponsiveBlockToolbar.tsx+++ b/apps/web/src/components/app/ResponsiveBlockToolbar.tsx@@ -1,3 +1,4 @@+import type { Permissions } from '@core/component/SharePermissions';import type { HotkeyToken } from '@core/hotkey/tokens';import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { EntityData } from '@entity';@@ -101,6 +102,8 @@ interface BlockToolbarProps {* id/name/blockName alone (e.g. calls need their channelId).*/entity?: EntityData;+ /** Feature-owned access when the session loads outside legacy Block state. */+ permissions?: Permissions;}/**@@ -162,6 +165,7 @@ export function ResponsiveBlockToolbar(props: BlockToolbarProps) {ops={props.ops}tools={fileMenuTools()}entity={props.entity}+ permissions={props.permissions}buttonClass="order-first"/></SplitTitleFileMenu>@@ -192,6 +196,7 @@ export function ResponsiveBlockToolbar(props: BlockToolbarProps) {ops={props.ops}tools={fileMenuTools()}entity={props.entity}+ permissions={props.permissions}buttonClass="order-last"/></SplitTitleFileMenu>diff --git a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsxindex 86e796752d..eeccacabed 100644--- a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx@@ -722,7 +722,7 @@ export function SplitFileMenu(props: SplitFileMenuProps) {export type BlockSplitFileMenuProps = Omit<SplitFileMenuProps,'entityKind' | 'permissions'->;+> & { permissions?: Permissions };/** Supplies legacy Block identity, permissions, and registered hotkeys. */export function BlockSplitFileMenu(props: BlockSplitFileMenuProps) {@@ -733,7 +733,7 @@ export function BlockSplitFileMenu(props: BlockSplitFileMenuProps) {<SplitFileMenu{...props}entityKind={entityKind}- permissions={permissions()}+ permissions={props.permissions ?? permissions()}/>);}diff --git a/apps/web/src/features/agent-changes/agent-changes.tsx b/apps/web/src/features/agent-changes/agent-changes.tsxindex f669bda69d..efa8641532 100644--- a/apps/web/src/features/agent-changes/agent-changes.tsx+++ b/apps/web/src/features/agent-changes/agent-changes.tsx@@ -56,7 +56,9 @@ export function AgentChangesProvider(props: ParentProps) {};const pullRequestChangeCounts = createPullRequestStatsSource(() =>- coding() ? (session.session()?.pullRequestUrl ?? undefined) : undefined,+ coding() && session.userId()+ ? (session.session()?.pullRequestUrl ?? undefined)+ : undefined,() => source.summary()?.changeset?.id);const host: ChangesHost = {diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsxindex 417d2ea9c5..61e0f597e4 100644--- a/apps/web/src/features/block-agent/agent-session-provider.tsx+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx@@ -45,7 +45,9 @@ export function AgentSessionProvider(const live = createAgentSession(sessionId, { userId });const turn = () => live.metadata()?.turn ?? 'idle';const served = createQueueController({- sessionId,+ // Public viewers can read the transcript without signing in, while the+ // live action queue requires an authenticated caller.+ sessionId: () => (userId() ? sessionId() : undefined),messages: live.messages,});// A row the user removes may be one `sendNext` already showed as sent;diff --git a/apps/web/src/features/block-agent/component/AgentComposer.test.tsx b/apps/web/src/features/block-agent/component/AgentComposer.test.tsxnew file mode 100644index 0000000000..675116bfd6--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentComposer.test.tsx@@ -0,0 +1,142 @@+import { cleanup, render } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { AgentInputProps } from '../ui/AgentInput';+import type { AgentModelSelectorProps } from '../ui/AgentModelSelector';+import type { QueuedPromptsProps } from '../ui/QueuedPrompts';+import { AgentComposer } from './AgentComposer';++const mocks = vi.hoisted(() => ({+ session: () => ({ canEdit: false as boolean | undefined }),+ issue: vi.fn(),+ sendNext: vi.fn(),+ editQueued: vi.fn(),+ removeQueued: vi.fn(),+ upload: vi.fn(),+ consumeNotes: vi.fn(),+ input: undefined as AgentInputProps | undefined,+ model: undefined as AgentModelSelectorProps | undefined,+ queued: undefined as QueuedPromptsProps | undefined,+}));++vi.mock('@app/features/agent-changes/context/agent-changes-controller', () => ({+ useOptionalAgentChanges: () => ({ consumeSendableNotes: mocks.consumeNotes }),+}));+vi.mock('@channel/Input', () => ({+ createInputAttachmentTracker: () => ({+ attachments: () => [],+ clearAttachments: vi.fn(),+ removeAttachment: vi.fn(),+ }),+ uploadInputAttachments: mocks.upload,+}));+vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));+vi.mock('@core/util/upload', () => ({ uploadFile: vi.fn() }));+vi.mock('../context/AgentSessionContext', () => ({+ useAgentSession: () => ({+ session: () => mocks.session(),+ displayName: (id: string) => id,+ userId: () => 'viewer',+ interactions: { pending: () => [], canAnswer: () => false },+ issue: mocks.issue,+ loadFailed: () => false,+ messages: () => [],+ metadata: () => undefined,+ pending: () => false,+ queue: {+ entries: () => [+ { actionId: 'queued-1', kind: 'prompt', prompt: 'Queued request' },+ ],+ edit: mocks.editQueued,+ remove: mocks.removeQueued,+ },+ sendNext: mocks.sendNext,+ turn: () => 'idle',+ registerQuoteInsert: vi.fn(),+ }),+}));+vi.mock('../ui', () => ({+ AgentInput: (props: AgentInputProps) => {+ mocks.input = props;+ return <div>{props.modelControl}</div>;+ },+ AgentModelSelector: (props: AgentModelSelectorProps) => {+ mocks.model = props;+ return null;+ },+ QueuedPrompts: (props: QueuedPromptsProps) => {+ mocks.queued = props;+ return null;+ },+ ComposerNotice: () => null,+}));+vi.mock('./PermissionRequest', () => ({ PermissionRequest: () => null }));++beforeEach(() => {+ vi.resetAllMocks();+ mocks.session = () => ({ canEdit: false });+ mocks.issue.mockResolvedValue({ isErr: () => false });+});+afterEach(cleanup);++describe('view-only session controls', () => {+ it('disables and guards prompt, model, stop, queue, and attachment actions', () => {+ render(() => <AgentComposer />);++ expect(mocks.input?.disabled).toBe(true);+ expect(mocks.input?.readOnly).toBe(true);+ expect(mocks.input?.placeholder).toBe(+ 'You have view-only access to this agent session'+ );+ expect(mocks.model?.disabled).toBe(true);+ expect(mocks.queued?.disabled).toBe(true);++ mocks.input?.onSend('A new prompt', []);+ mocks.input?.onStop?.();+ mocks.input?.onSendNext?.();+ mocks.input?.onAttachFiles?.([new File(['text'], 'note.txt')]);+ mocks.model?.onSelect('new-model');+ mocks.queued?.onEdit('queued-1', 'Edited prompt');+ mocks.queued?.onRemove('queued-1');++ expect(mocks.issue).not.toHaveBeenCalled();+ expect(mocks.sendNext).not.toHaveBeenCalled();+ expect(mocks.upload).not.toHaveBeenCalled();+ expect(mocks.consumeNotes).not.toHaveBeenCalled();+ expect(mocks.editQueued).not.toHaveBeenCalled();+ expect(mocks.removeQueued).not.toHaveBeenCalled();+ });++ it('reacts to a permission downgrade without remounting', () => {+ const [canEdit, setCanEdit] = createSignal(true);+ mocks.session = () => ({ canEdit: canEdit() });+ render(() => <AgentComposer />);+ expect(mocks.input?.disabled).toBe(false);+ expect(mocks.model?.disabled).toBe(false);++ setCanEdit(false);++ expect(mocks.input?.readOnly).toBe(true);+ expect(mocks.model?.disabled).toBe(true);+ expect(mocks.queued?.disabled).toBe(true);+ mocks.input?.onSend('Cannot send now', []);+ expect(mocks.issue).not.toHaveBeenCalled();+ });++ it.each([true, undefined])(+ 'preserves editable drafts before a read-only result (%s)',+ (canEdit) => {+ mocks.session = () => ({ canEdit });+ render(() => <AgentComposer />);++ expect(mocks.input?.disabled).toBe(false);+ expect(mocks.input?.readOnly).toBe(false);+ expect(mocks.queued?.disabled).toBe(false);+ mocks.input?.onSend('A permitted prompt', []);+ expect(mocks.issue).toHaveBeenCalledWith({+ type: 'prompt',+ prompt: 'A permitted prompt',+ });+ }+ );+});diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsxindex 3210d8e5da..bc9f7b0d55 100644--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx@@ -50,18 +50,24 @@ export function AgentComposer(props: {metadata,pending,queue,+ session,sendNext,turn,registerQuoteInsert,} = useAgentSession();const changes = useOptionalAgentChanges();+ const readOnly = () => session()?.canEdit === false;// The fold speculates the action the moment it is issued, so success is// observed there; only a refusal needs saying here.- const act = (action: AgentAction, failure: string) => {- void issue(action)?.then((result) => {- if (result.isErr()) toast.failure(failure);- });+ const act = async (action: AgentAction, failure: string) => {+ if (readOnly()) return;+ try {+ const result = await issue(action);+ if (result?.isErr()) toast.failure(failure);+ } catch {+ toast.failure(failure);+ }};// A turn is open in some form: the send button becomes a stop square and@@ -95,17 +101,20 @@ export function AgentComposer(props: {// agent can only reach a file by a URL it can fetch. The chips and the// upload flow are the channel composer's.const attachmentTracker = createInputAttachmentTracker();- const attachFiles = (files: File[]) =>+ const attachFiles = (files: File[]) => {+ if (readOnly()) return;void uploadInputAttachments({files,tracker: attachmentTracker,uploadFile: (file) =>uploadFile(file, 'static', { hideProgressIndicator: true }),});+ };// Attachments ride the prompt action itself, so they take the same path as// the text: issued once, speculated by the fold, and queued server-side// behind a running turn with the files still on them.const send = (markdown: string, attachments: InputAttachmentData[]) => {+ if (readOnly()) return;// Queued review notes ride this send: taking them here marks them sent// before the prompt is issued, so a second Enter cannot post them again// as their own queued prompt (which would then stop-and-flush).@@ -113,7 +122,10 @@ export function AgentComposer(props: {const prompt = [markdown, notes].filter((part) => part.length > 0).join('\n\n');- act(promptActionOf(prompt, attachments), 'The message could not be sent');+ void act(+ promptActionOf(prompt, attachments),+ 'The message could not be sent'+ );attachmentTracker.clearAttachments();};@@ -144,8 +156,13 @@ export function AgentComposer(props: {<div class="pb-1.5"><QueuedPromptsitems={queuedItems()}- onEdit={(actionId, prompt) => void queue.edit(actionId, prompt)}- onRemove={(actionId) => void queue.remove(actionId)}+ disabled={readOnly()}+ onEdit={(actionId, prompt) => {+ if (!readOnly()) void queue.edit(actionId, prompt);+ }}+ onRemove={(actionId) => {+ if (!readOnly()) void queue.remove(actionId);+ }}onNavigateBelow={() => focusInput?.()}registerFocusFromBelow={(focus) => {focusQueueBottom = focus;@@ -173,7 +190,12 @@ export function AgentComposer(props: {)}</For><Input- placeholder="Message the agent, @mention anything"+ placeholder={+ readOnly()+ ? 'You have view-only access to this agent session'+ : 'Message the agent, @mention anything'+ }+ readOnly={readOnly()}autofocus={props.autofocus}busy={busy()}hasQueuedMessages={queuedItems().length > 0}@@ -190,11 +212,15 @@ export function AgentComposer(props: {// Prompts go straight to the service, so sending needs a session to// post to — a block whose create is still on the wire can be typed// into, but not sent from, until the id lands.- disabled={loadFailed() || pending()}+ disabled={loadFailed() || pending() || readOnly()}commands={() => metadata()?.availableCommands ?? []}onSend={send}- onStop={() => act({ type: 'stop' }, 'The agent could not be stopped')}- onSendNext={sendNext}+ onStop={() =>+ void act({ type: 'stop' }, 'The agent could not be stopped')+ }+ onSendNext={() => {+ if (!readOnly()) sendNext();+ }}attachments={attachmentTracker.attachments()}onAttachFiles={attachFiles}onRemoveAttachment={(attachment) =>@@ -216,9 +242,12 @@ export function AgentComposer(props: {model={metadata()?.model ?? null}changingTo={changingModel(messages(), metadata()?.model ?? null)}options={metadata()?.supportedModels ?? []}- disabled={loadFailed()}+ disabled={loadFailed() || readOnly()}onSelect={(model) =>- act({ type: 'setModel', model }, 'The model could not be changed')+ void act(+ { type: 'setModel', model },+ 'The model could not be changed'+ )}/>}diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex 51305544f7..9d5a1b9e57 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -69,9 +69,15 @@ export function AgentSplitHeader(props: {// The session, not `useBlockId()`: a block created from the launcher mounts// against a placeholder and keeps reporting it (see `Block.tsx`), so the// block id is the one thing here that is not a shareable session id.- const { sessionId, metadata } = useAgentSession();+ const { sessionId, metadata, userId } = useAgentSession();const conversation = useDrawerControl(ORIGIN_THREAD_DRAWER_ID);const title = () => agentSessionTitle(props.session, props.title);+ const permissions = () =>+ userId() && props.session?.ownerId === userId()+ ? Permissions.OWNER+ : props.session?.canEdit+ ? Permissions.CAN_EDIT+ : Permissions.CAN_VIEW;const entity = (): AgentSessionEntity | undefined => {const session = props.session;@@ -189,7 +195,7 @@ export function AgentSplitHeader(props: {owner={session().ownerId}itemType="agent_session"blockAlias="agent"- userPermissions={Permissions.OWNER}+ userPermissions={permissions()}isSharePermOpen={shareOpen()}setIsSharePermOpen={setShareOpen}/>@@ -204,6 +210,7 @@ export function AgentSplitHeader(props: {id={sessionId() ?? ''}itemType="agent_session"entity={entity()}+ permissions={permissions()}name={title()}/></ShareDialogContext.Provider>diff --git a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx b/apps/web/src/features/block-agent/ui/AgentInput.test.tsxindex 3b609da0e8..74be54c606 100644--- a/apps/web/src/features/block-agent/ui/AgentInput.test.tsx+++ b/apps/web/src/features/block-agent/ui/AgentInput.test.tsx@@ -58,7 +58,9 @@ vi.mock();vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({- MarkdownShell: () => <div data-testid="agent-input-editor" />,+ MarkdownShell: (props: { disabled?: boolean }) => (+ <div data-testid="agent-input-editor" data-disabled={props.disabled} />+ ),}));// The channel composer's chips and drop zone reach the block registry (and@@ -112,6 +114,38 @@ beforeEach(() => {});describe('queued message advancement', () => {+ it('keeps view-only drafts, stop, and queue advancement inert', () => {+ const onSend = vi.fn();+ const onStop = vi.fn();+ const onSendNext = vi.fn();+ render(() => (+ <AgentInput+ readOnly+ busy+ hasQueuedMessages+ onSend={onSend}+ onStop={onStop}+ onSendNext={onSendNext}+ />+ ));++ expect(+ screen.getByTestId('agent-input-editor').getAttribute('data-disabled')+ ).toBe('true');+ const stop = screen.getByRole('button', {+ name: 'Stop',+ }) as HTMLButtonElement;+ expect(stop.disabled).toBe(true);+ fireEvent.click(stop);+ editor.enter?.();+ editor.change?.('Cannot send this');+ editor.enter?.();++ expect(onSend).not.toHaveBeenCalled();+ expect(onStop).not.toHaveBeenCalled();+ expect(onSendNext).not.toHaveBeenCalled();+ });+it('shows a pressable Enter action that advances the next queued message', () => {const onStop = vi.fn();diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsxindex 3889cad07e..398b39acd4 100644--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx@@ -60,6 +60,8 @@ export interface AgentInputProps {*/onSendNext?: () => void;disabled?: boolean;+ /** View-only sessions cannot edit drafts; pending sessions still can. */+ readOnly?: boolean;autofocus?: boolean;/*** Slash commands the harness advertises (ACP `available_commands_update`);@@ -118,7 +120,8 @@ export function AgentInput(props: AgentInputProps) {useTouchOutsideToDismissKeyboard(() => containerRef);const attachments = () => props.attachments ?? [];- const canAttach = () => props.onAttachFiles !== undefined && !props.disabled;+ const canAttach = () =>+ props.onAttachFiles !== undefined && !props.disabled && !props.readOnly;const hasPendingAttachments = () =>attachments().some((attachment) => attachment.pending);const attachFiles = (files: File[]) => {@@ -132,7 +135,8 @@ export function AgentInput(props: AgentInputProps) {const canSend = () =>(markdown().trim().length > 0 || attachments().length > 0) &&!hasPendingAttachments() &&- !props.disabled;+ !props.disabled &&+ !props.readOnly;// The channel composer's chips, drop zone, and overlay read their state// from `Input.Root`'s context; this is that context, over this composer's@@ -143,7 +147,9 @@ export function AgentInput(props: AgentInputProps) {attachFiles: async (files) => attachFiles(files),toggleFormatRibbon: () => {},close: () => {},- removeAttachment: (attachment) => props.onRemoveAttachment?.(attachment),+ removeAttachment: (attachment) => {+ if (!props.readOnly) props.onRemoveAttachment?.(attachment);+ },};const send = () => {@@ -166,6 +172,7 @@ export function AgentInput(props: AgentInputProps) {props.hasQueuedMessages === true &&!props.sendNextHeld &&!props.disabled &&+ !props.readOnly &&props.onStop !== undefined;const sendNext = () => {@@ -227,6 +234,7 @@ export function AgentInput(props: AgentInputProps) {props.registerFocus?.(() => editor.controls.focus());onCleanup(() => props.registerFocus?.(undefined));props.registerQuoteInsert?.((text) => {+ if (props.readOnly) return;// Discrete so the chip is committed to the DOM before focus moves in.editor.lexical.update(() => $insertReferencedPaste(text), {discrete: true,@@ -250,6 +258,7 @@ export function AgentInput(props: AgentInputProps) {// Taps inside the contenteditable keep their defaults so the caret lands// under the finger.const focusEditor = (event: Event) => {+ if (props.readOnly) return;const target = event.target as HTMLElement | null;if (!target || target.closest('button')) return;if (editor.lexical.getRootElement()?.contains(target)) return;@@ -269,7 +278,12 @@ export function AgentInput(props: AgentInputProps) {commands: inputCommands,}}>- <div ref={containerRef} data-keep-keyboard class="flex flex-col gap-1.5">+ <div+ ref={containerRef}+ data-keep-keyboard+ class="flex flex-col gap-1.5"+ classList={{ 'opacity-50': props.readOnly }}+ >{/* Desktop: the model pill sits above the box, as it always has. */}<Show when={!isTouchDevice() && props.modelControl}><div class="flex items-center px-0.5">{props.modelControl}</div>@@ -324,12 +338,16 @@ export function AgentInput(props: AgentInputProps) {><ComposerEditorconfig={editor}+ disabled={props.readOnly}placeholder={props.placeholder ??'Message the agent, @mention anything'}autofocus={- !isMobile() && !isTouchDevice() && props.autofocus+ !props.readOnly &&+ !isMobile() &&+ !isTouchDevice() &&+ props.autofocus}/></div>@@ -345,7 +363,7 @@ export function AgentInput(props: AgentInputProps) {file, and the static upload stores any type. */}<Input.AttachFilesActionaccept={null}- disabled={props.disabled}+ disabled={props.disabled || props.readOnly}/></Show><div class="ml-auto shrink-0">@@ -367,6 +385,7 @@ export function AgentInput(props: AgentInputProps) {variant={isTouchDevice() ? 'ghost' : 'strong'}size="icon-composer"label="Stop"+ disabled={props.disabled || props.readOnly}onClick={() => props.onStop?.()}class={isTouchDevice()diff --git a/apps/web/src/features/block-agent/ui/QueuedPrompts.test.tsx b/apps/web/src/features/block-agent/ui/QueuedPrompts.test.tsxnew file mode 100644index 0000000000..7ad35d29cd--- /dev/null+++ b/apps/web/src/features/block-agent/ui/QueuedPrompts.test.tsx@@ -0,0 +1,140 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { createSignal, type JSX } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { QueuedPrompts } from './QueuedPrompts';++const editor = vi.hoisted(() => ({+ change: undefined as ((markdown: string) => void) | undefined,+ markdown: 'Queued request',+}));+vi.mock(+ '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder',+ () => ({+ buildConfig: () => {+ const builder = {+ namespace: () => builder,+ withHistory: () => builder,+ onChange: (callback: (markdown: string) => void) => {+ editor.change = callback;+ return builder;+ },+ onFocusLeave: () => builder,+ lexical: { getRootElement: () => null },+ controls: {+ focus: vi.fn(),+ getMarkdown: () => editor.markdown,+ setMarkdown: vi.fn(),+ },+ };+ return builder;+ },+ })+);+vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({+ MarkdownShell: (props: { initialValue?: string; disabled?: boolean }) => (+ <div role="textbox" aria-readonly={props.disabled}>+ {props.initialValue}+ </div>+ ),+}));+vi.mock('@ui', () => ({+ Surface: (props: { children?: JSX.Element }) => props.children,+ Button: (props: {+ label?: string;+ disabled?: boolean;+ onClick?: () => void;+ }) => (+ <button+ aria-label={props.label}+ disabled={props.disabled}+ onClick={props.onClick}+ />+ ),+}));++beforeEach(() => {+ vi.useFakeTimers();+ editor.markdown = 'Queued request';+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+});++describe('queued prompt access', () => {+ it('shows queued text without permitting edits or removal for viewers', () => {+ const onEdit = vi.fn();+ const onRemove = vi.fn();+ render(() => (+ <QueuedPrompts+ disabled+ items={[+ { actionId: 'queued-1', kind: 'prompt', prompt: 'Queued request' },+ ]}+ onEdit={onEdit}+ onRemove={onRemove}+ />+ ));++ const textbox = screen.getByRole('textbox');+ expect(textbox.textContent).toBe('Queued request');+ expect(textbox.getAttribute('aria-readonly')).toBe('true');+ const remove = screen.getByRole('button', {+ name: 'Remove queued message',+ }) as HTMLButtonElement;+ expect(remove.disabled).toBe(true);+ fireEvent.click(remove);+ editor.markdown = 'Attempted edit';+ editor.change?.(editor.markdown);+ fireEvent.focusOut(textbox);+ vi.advanceTimersByTime(400);++ expect(onEdit).not.toHaveBeenCalled();+ expect(onRemove).not.toHaveBeenCalled();+ });++ it('drops a pending autosave after edit access is removed', () => {+ const [disabled, setDisabled] = createSignal(false);+ const onEdit = vi.fn();+ render(() => (+ <QueuedPrompts+ disabled={disabled()}+ items={[+ { actionId: 'queued-1', kind: 'prompt', prompt: 'Queued request' },+ ]}+ onEdit={onEdit}+ onRemove={vi.fn()}+ />+ ));+ editor.markdown = 'An unsaved edit';+ editor.change?.(editor.markdown);++ setDisabled(true);+ vi.advanceTimersByTime(400);++ expect(onEdit).not.toHaveBeenCalled();+ });++ it('retains edit autosave and removal for editors', () => {+ const onEdit = vi.fn();+ const onRemove = vi.fn();+ render(() => (+ <QueuedPrompts+ items={[+ { actionId: 'queued-1', kind: 'prompt', prompt: 'Queued request' },+ ]}+ onEdit={onEdit}+ onRemove={onRemove}+ />+ ));+ editor.markdown = 'An edited request';+ editor.change?.(editor.markdown);+ vi.advanceTimersByTime(400);+ fireEvent.click(+ screen.getByRole('button', { name: 'Remove queued message' })+ );++ expect(onEdit).toHaveBeenCalledWith('queued-1', 'An edited request');+ expect(onRemove).toHaveBeenCalledWith('queued-1');+ });+});diff --git a/apps/web/src/features/block-agent/ui/QueuedPrompts.tsx b/apps/web/src/features/block-agent/ui/QueuedPrompts.tsxindex 22bdfa3065..ac7254b7c4 100644--- a/apps/web/src/features/block-agent/ui/QueuedPrompts.tsx+++ b/apps/web/src/features/block-agent/ui/QueuedPrompts.tsx@@ -41,6 +41,8 @@ export type QueuedPromptItem = {export interface QueuedPromptsProps {/** In dispatch order — oldest (next to send) first, as the server reports. */items: QueuedPromptItem[];+ /** Keep queued text visible without allowing changes. */+ disabled?: boolean;/** Autosave a queued prompt's replacement text. The rows debounce. */onEdit: (actionId: string, prompt: string) => void;/** Remove a queued action before it dispatches. */@@ -99,6 +101,7 @@ export function QueuedPrompts(props: QueuedPromptsProps) {{(item) => (<QueuedRowitem={item()}+ disabled={props.disabled}registerFocus={(focus) => {if (focus) focusFns.set(id, focus);else focusFns.delete(id);@@ -118,6 +121,7 @@ export function QueuedPrompts(props: QueuedPromptsProps) {type QueuedRowProps = {item: QueuedPromptItem;+ disabled?: boolean;/** Ref-style: how navigation focuses this row; `undefined` on unmount. */registerFocus: (focus: (() => void) | undefined) => void;onMoveUp: () => void;@@ -152,6 +156,7 @@ function QueuedRow(props: QueuedRowProps) {variant="ghost"size="icon-sm"label="Remove queued message"+ disabled={props.disabled}onClick={() => props.onRemove()}class="shrink-0">@@ -179,6 +184,7 @@ function PromptBody(props: QueuedRowProps) {clearTimeout(saveTimer);saveTimer = undefined;}+ if (props.disabled) return;const text = editor.controls.getMarkdown();// An emptied row is not an edit to send — the server refuses empty// prompts and "delete the text" has the remove affordance for it.@@ -188,6 +194,7 @@ function PromptBody(props: QueuedRowProps) {};const scheduleSave = (markdown: string) => {+ if (props.disabled) return;if (markdown === synced) return;if (saveTimer !== undefined) clearTimeout(saveTimer);saveTimer = setTimeout(flush, AUTOSAVE_DEBOUNCE_MS);@@ -235,7 +242,11 @@ function PromptBody(props: QueuedRowProps) {return (<div class="text-sm text-ink" onFocusOut={flush}>- <MarkdownShell config={editor} initialValue={props.item.prompt} />+ <MarkdownShell+ config={editor}+ initialValue={props.item.prompt}+ disabled={props.disabled}+ />{/* Attached files ride the prompt as-is: an edit rewrites the text andkeeps them, so they are shown but not editable here. */}<Show when={props.item.attachments?.length}>diff --git a/apps/web/src/lib/core/component/ForwardToChannel.test.tsx b/apps/web/src/lib/core/component/ForwardToChannel.test.tsxnew file mode 100644index 0000000000..d89ea51a5c--- /dev/null+++ b/apps/web/src/lib/core/component/ForwardToChannel.test.tsx@@ -0,0 +1,372 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import type { ComponentProps, JSX } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ForwardToChannel } from './ForwardToChannel';+import { Permissions } from './SharePermissions';++const mocks = vi.hoisted(() => ({+ sendToChannel: vi.fn(),+ sendToUsers: vi.fn(),+ success: vi.fn(),+ failure: vi.fn(),+ recipients: [] as { kind: 'channel' | 'user'; id: string }[],+}));++vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => ({ track: vi.fn() }),+}));+vi.mock('@channel/Input', () => ({+ createConfiguredChannelMarkdownEditor: () => ({+ controls: { focus: vi.fn() },+ }),+}));+vi.mock('@core/auth', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@core/block', () => ({+ useMaybeBlockName: () => 'md',+ useMaybeBlockAliasedName: () => 'md',+ useMaybeBlockId: () => 'enclosing-document',+}));+vi.mock('@core/component/CustomScrollbar', () => ({+ CustomScrollbar: () => null,+}));+vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({+ MarkdownShell: () => null,+}));+vi.mock('@core/component/RecipientSelector', () => ({+ RecipientSelector: (props: {+ setSelectedOptions: (items: unknown[]) => void;+ }) => (+ <button onClick={() => props.setSelectedOptions(mocks.recipients)}>+ Select recipients+ </button>+ ),+}));+vi.mock('@core/component/TopBar/ShareButton', () => ({+ ShareOptions: () => null,+}));+vi.mock('@core/constant/allBlocks', () => ({+ resolveBlockAlias: (name: string) =>+ ['task', 'snippet', 'skill'].includes(name) ? 'md' : name,+}));+vi.mock('@core/hotkey/hotkeys', () => ({+ registerHotkey: vi.fn(),+ useHotkeyDOMScope: () => [vi.fn(), 'share-scope'],+}));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@core/signal/useCombinedRecipient', () => ({+ useCombinedRecipients: () => ({ all: () => [] }),+}));+vi.mock('@core/util/channels', () => ({ useSendMessageToPeople: () => mocks }));+vi.mock('@service-storage/client', () => ({+ blockNameToItemType: () => 'agent_session',+ itemTypeToReferenceEntityType: () => 'agent_session',+}));+vi.mock('./Toast/Toast', () => ({+ toast: { success: mocks.success, failure: mocks.failure },+}));+vi.mock('./VerticalScrollIndicators', () => ({ ScrollIndicators: () => null }));+vi.mock('@ui', () => ({+ Button: (props: {+ children?: JSX.Element;+ disabled?: boolean;+ onClick?: () => void;+ }) => (+ <button disabled={props.disabled} onClick={props.onClick}>+ {props.children}+ </button>+ ),+ Hotkey: () => null,+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+}));++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++function mountForward(+ setChannelPermissions = vi.fn().mockResolvedValue(true),+ blockName: ComponentProps<typeof ForwardToChannel>['blockName'] = 'agent'+) {+ const onSubmit = vi.fn();+ const refetch = vi.fn();+ let controls:+ | Parameters<NonNullable<ComponentProps<typeof ForwardToChannel>['ref']>>[0]+ | undefined;+ render(() => (+ <ForwardToChannel+ name="Agent session"+ blockName={blockName}+ blockId="session-1"+ onSubmit={onSubmit}+ refetch={refetch}+ ref={(value) => {+ controls = value;+ }}+ submitPermissionInfo={{+ userPermissions: Permissions.OWNER,+ setChannelPermissions,+ }}+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Select recipients' }));+ return {+ onSubmit,+ refetch,+ setChannelPermissions,+ setAccessLevel: (level: 'view' | 'edit') =>+ controls?.setSubmitAccessLevel(level),+ submit: () => controls?.handleSubmit(),+ };+}++beforeEach(() => {+ vi.resetAllMocks();+ mocks.recipients = [{ kind: 'channel', id: 'channel-1' }];+});+afterEach(cleanup);++describe('forwarding with selected access', () => {+ it.each(['md', 'task', 'snippet', 'skill'] as const)(+ 'retains the edit default for %s sharing',+ async (blockName) => {+ mocks.sendToChannel.mockResolvedValue({+ channelId: 'channel-1',+ navigateToChannel: vi.fn(),+ });+ const setChannelPermissions = vi.fn().mockResolvedValue(true);+ const { submit } = mountForward(setChannelPermissions, blockName);++ await submit();++ expect(setChannelPermissions).toHaveBeenCalledWith('channel-1', 'edit');+ }+ );++ it.each(['channel', 'user', 'group'] as const)(+ 'finishes sending to a %s before applying the selected access level',+ async (target) => {+ mocks.recipients =+ target === 'channel'+ ? [{ kind: 'channel', id: 'channel-1' }]+ : target === 'user'+ ? [{ kind: 'user', id: 'user-1' }]+ : [+ { kind: 'user', id: 'user-1' },+ { kind: 'user', id: 'user-2' },+ ];+ const send = deferred<{+ channelId: string;+ navigateToChannel: () => void;+ }>();+ const grant = deferred<boolean>();+ const sendMessage =+ target === 'channel' ? mocks.sendToChannel : mocks.sendToUsers;+ sendMessage.mockReturnValue(send.promise);+ const setChannelPermissions = vi.fn().mockReturnValue(grant.promise);+ const { submit, onSubmit } = mountForward(setChannelPermissions);++ const submitted = submit();+ expect(sendMessage).toHaveBeenCalledOnce();+ expect(setChannelPermissions).not.toHaveBeenCalled();+ expect(onSubmit).not.toHaveBeenCalled();++ send.resolve({ channelId: 'channel-1', navigateToChannel: vi.fn() });+ await waitFor(() =>+ expect(setChannelPermissions).toHaveBeenCalledWith('channel-1', 'view')+ );+ expect(onSubmit).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();+ // A second shortcut or button press must not duplicate the message while+ // its access update is still pending.+ await submit();+ expect(sendMessage).toHaveBeenCalledOnce();++ grant.resolve(true);+ await submitted;+ expect(onSubmit).toHaveBeenCalledOnce();+ expect(mocks.success).toHaveBeenCalledWith(+ 'Message sent successfully',+ expect.any(Object)+ );+ }+ );++ it('keeps the dialog open when a permission update reports failure', async () => {+ mocks.sendToChannel.mockResolvedValue({+ channelId: 'channel-1',+ navigateToChannel: vi.fn(),+ });+ const { submit, onSubmit } = mountForward(vi.fn().mockResolvedValue(false));++ await submit();++ expect(onSubmit).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();+ });++ it.each(['channel', 'user', 'group'] as const)(+ 'retries a failed grant for a %s without repeating its delivered message',+ async (target) => {+ mocks.recipients =+ target === 'channel'+ ? [{ kind: 'channel', id: 'channel-1' }]+ : target === 'user'+ ? [{ kind: 'user', id: 'user-1' }]+ : [+ { kind: 'user', id: 'user-1' },+ { kind: 'user', id: 'user-2' },+ ];+ const sendMessage =+ target === 'channel' ? mocks.sendToChannel : mocks.sendToUsers;+ sendMessage.mockResolvedValue({+ channelId: 'channel-1',+ navigateToChannel: vi.fn(),+ });+ const grant = vi+ .fn()+ .mockResolvedValueOnce(false)+ .mockResolvedValue(true);+ const { submit, onSubmit, setAccessLevel } = mountForward(grant);++ await submit();+ expect(onSubmit).not.toHaveBeenCalled();+ setAccessLevel('edit');+ // Reordering a group's recipients still addresses the same group.+ mocks.recipients = [...mocks.recipients].reverse();+ fireEvent.click(+ screen.getByRole('button', { name: 'Select recipients' })+ );+ await submit();++ expect(sendMessage).toHaveBeenCalledOnce();+ expect(grant).toHaveBeenNthCalledWith(1, 'channel-1', 'view');+ expect(grant).toHaveBeenNthCalledWith(2, 'channel-1', 'edit');+ expect(onSubmit).toHaveBeenCalledOnce();+ }+ );++ it('keeps completed recipients while retrying only the failed grant', async () => {+ mocks.recipients = [+ { kind: 'channel', id: 'channel-1' },+ { kind: 'channel', id: 'channel-2' },+ ];+ mocks.sendToChannel.mockImplementation(async ({ channelId }) => ({+ channelId,+ navigateToChannel: vi.fn(),+ }));+ const grant = vi+ .fn()+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(false)+ .mockResolvedValue(true);+ const { submit, onSubmit } = mountForward(grant);++ await submit();+ expect(onSubmit).not.toHaveBeenCalled();+ // A newly added recipient needs delivery; existing recipients do not.+ mocks.recipients = [+ ...mocks.recipients,+ { kind: 'channel', id: 'channel-3' },+ ];+ fireEvent.click(screen.getByRole('button', { name: 'Select recipients' }));+ await submit();++ expect(mocks.sendToChannel).toHaveBeenCalledTimes(3);+ expect(+ mocks.sendToChannel.mock.calls.map(([message]) => message.channelId)+ ).toEqual(['channel-1', 'channel-2', 'channel-3']);+ expect(grant.mock.calls).toEqual([+ ['channel-1', 'view'],+ ['channel-2', 'view'],+ ['channel-2', 'view'],+ ['channel-3', 'view'],+ ]);+ expect(onSubmit).toHaveBeenCalledOnce();+ });++ it('handles rejected permission updates without closing the dialog', async () => {+ const error = new Error('Permission update failed');+ const logError = vi.spyOn(console, 'error').mockImplementation(() => {});+ mocks.sendToChannel.mockResolvedValue({+ channelId: 'channel-1',+ navigateToChannel: vi.fn(),+ });+ const { submit, onSubmit } = mountForward(vi.fn().mockRejectedValue(error));++ await submit();++ expect(onSubmit).not.toHaveBeenCalled();+ expect(mocks.failure).toHaveBeenCalledWith(+ 'Failed to set channel permissions'+ );+ expect(logError).toHaveBeenCalledWith(+ 'Failed to set channel permissions',+ error+ );+ logError.mockRestore();+ });++ it('does not grant access or close when the message fails', async () => {+ mocks.sendToChannel.mockResolvedValue(undefined);+ const { submit, onSubmit, setChannelPermissions } = mountForward();++ await submit();++ expect(setChannelPermissions).not.toHaveBeenCalled();+ expect(onSubmit).not.toHaveBeenCalled();+ expect(mocks.failure).toHaveBeenCalledWith('Message failed to send');+ });++ it('waits for every recipient and reports partial failures', async () => {+ mocks.recipients = [+ { kind: 'channel', id: 'channel-1' },+ { kind: 'channel', id: 'channel-2' },+ ];+ const secondSend = deferred<undefined>();+ mocks.sendToChannel+ .mockResolvedValueOnce({+ channelId: 'channel-1',+ navigateToChannel: vi.fn(),+ })+ .mockReturnValueOnce(secondSend.promise);+ const { submit, onSubmit, setChannelPermissions } = mountForward();++ const submitted = submit();+ await waitFor(() =>+ expect(setChannelPermissions).toHaveBeenCalledWith('channel-1', 'view')+ );+ expect(onSubmit).not.toHaveBeenCalled();+ expect(mocks.success).not.toHaveBeenCalled();+ secondSend.resolve(undefined);+ await submitted;++ expect(setChannelPermissions).toHaveBeenCalledOnce();+ expect(onSubmit).not.toHaveBeenCalled();+ expect(mocks.failure).toHaveBeenCalledWith('Some messages failed to send');++ mocks.sendToChannel.mockResolvedValueOnce({+ channelId: 'channel-2',+ navigateToChannel: vi.fn(),+ });+ await submit();++ expect(+ mocks.sendToChannel.mock.calls.map(([message]) => message.channelId)+ ).toEqual(['channel-1', 'channel-2', 'channel-2']);+ expect(setChannelPermissions.mock.calls).toEqual([+ ['channel-1', 'view'],+ ['channel-2', 'view'],+ ]);+ expect(onSubmit).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/lib/core/component/ForwardToChannel.tsx b/apps/web/src/lib/core/component/ForwardToChannel.tsxindex 2ca8f11b07..68a1a49df5 100644--- a/apps/web/src/lib/core/component/ForwardToChannel.tsx+++ b/apps/web/src/lib/core/component/ForwardToChannel.tsx@@ -12,6 +12,7 @@ import { CustomScrollbar } from '@core/component/CustomScrollbar';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';import { RecipientSelector } from '@core/component/RecipientSelector';import { ShareOptions } from '@core/component/TopBar/ShareButton';+import { resolveBlockAlias } from '@core/constant/allBlocks';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';import { isMobile } from '@core/mobile/isMobile';import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';@@ -44,7 +45,7 @@ type Recipient = WithCustomUserInput<'user' | 'contact' | 'channel'>;interface MobileForwardToChannelLayoutPropsextends Pick<ForwardToChannelProps,- 'submitPermissionInfo' | 'hideAccessLevelSelector'+ 'submitPermissionInfo' | 'hideAccessLevelSelector' | 'editPermissionEnabled'> {isAuthenticated: Accessor<boolean | undefined>;selectedOptions: Accessor<Recipient[]>;@@ -133,6 +134,7 @@ function MobileForwardToChannelLayout(<div class="px-3 py-2 flex items-center"><span class="text-sm text-ink-muted pr-2">Access:</span><ShareOptions+ editPermissionEnabled={props.editPermissionEnabled}setPermissions={(accessLevel) =>props.setSubmitAccessLevel(accessLevel)}@@ -164,11 +166,12 @@ function MobileForwardToChannelLayout(}interface ForwardToChannelProps {+ editPermissionEnabled?: boolean;submitPermissionInfo?: {setChannelPermissions: (channelId: string,accessLevel: AccessLevel- ) => void;+ ) => void | boolean | Promise<void | boolean>;channelSharePermissions?: SharePermissionV2ChannelSharePermissions;userPermissions: Permissions;};@@ -212,6 +215,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {onChange: setMarkdown,});const [triedToSubmit, setTriedToSubmit] = createSignal(false);+ const [isSubmitting, setIsSubmitting] = createSignal(false);const { all: destinationOptions } = useCombinedRecipients();const destination = createMemo(() => {@@ -237,7 +241,10 @@ export function ForwardToChannel(props: ForwardToChannelProps) {});const { sendToUsers, sendToChannel } = useSendMessageToPeople();- const blockBaseName = useMaybeBlockName() ?? props.blockName;+ const contextBlockBaseName = useMaybeBlockName();+ const blockBaseName = props.blockName+ ? resolveBlockAlias(props.blockName)+ : contextBlockBaseName;const [submitAccessLevel, setSubmitAccessLevel] =createSignal<AccessLevel | null>(props.initialAccessLevel ?? (blockBaseName === 'md' ? 'edit' : 'view')@@ -249,18 +256,30 @@ export function ForwardToChannel(props: ForwardToChannelProps) {}});- const submitChannelPermissions = (channelId: string) => {+ const submitChannelPermissions = async (+ channelId: string,+ accessLevel: AccessLevel | null+ ) => {if (!props.submitPermissionInfo) {- return;+ return true;}- const accessLevel = submitAccessLevel();if (!accessLevel) {toast.failure('Failed to set channel permissions');- return;+ return false;}- props.submitPermissionInfo.setChannelPermissions(channelId, accessLevel);+ try {+ const result = await props.submitPermissionInfo.setChannelPermissions(+ channelId,+ accessLevel+ );+ return result !== false;+ } catch (error) {+ console.error('Failed to set channel permissions', error);+ toast.failure('Failed to set channel permissions');+ return false;+ }};const [sendAsGroupMessage, setSendAsGroupMessage] =@@ -309,118 +328,119 @@ export function ForwardToChannel(props: ForwardToChannelProps) {});};- function handleSubmit() {- let options = selectedOptions();- if (!options || options.length === 0) {+ // Keep confirmed deliveries until the whole share succeeds. Retrying a+ // failed grant must not send the same message to that recipient again.+ const deliveries = new Map<+ string,+ {+ result: NonNullable<Awaited<ReturnType<typeof sendToChannel>>>;+ accessLevel?: AccessLevel | null;+ }+ >();++ async function sendForward(+ target: NonNullable<ReturnType<typeof destination>>,+ accessLevel: AccessLevel | null+ ) {+ const message = {+ attachments: [asAttachment()],+ content: markdown(),+ mentions: [],+ };+ const deliveryKey = JSON.stringify([+ message,+ target.type === 'channel'+ ? target+ : { type: target.type, users: [...target.users].sort() },+ ]);+ let delivery = deliveries.get(deliveryKey);+ if (!delivery) {+ let result;+ try {+ result =+ target.type === 'channel'+ ? await sendToChannel({ ...message, channelId: target.id })+ : await sendToUsers({ ...message, users: target.users });+ } catch (error) {+ console.error('Failed to forward message', error);+ }+ if (!result) {+ toast.failure('Message failed to send');+ return;+ }+ delivery = { result };+ deliveries.set(deliveryKey, delivery);+ }++ // Sending an attachment can automatically grant access. Apply the selected+ // level afterward so that auto-grant cannot overwrite the user's choice.+ if (delivery.accessLevel !== accessLevel) {+ if (+ !(await submitChannelPermissions(+ delivery.result.channelId,+ accessLevel+ ))+ ) {+ return;+ }+ if (delivery.accessLevel === undefined) {+ trackForwardShare(target.type === 'channel' ? 'channel' : 'user');+ }+ delivery.accessLevel = accessLevel;+ }+ return delivery.result;+ }++ async function handleSubmit() {+ if (isSubmitting()) return;+ const options = selectedOptions();+ const destination_ = destination();+ if (options.length === 0 || !destination_) {return setTriedToSubmit(true);}- if (canSendAsGroup() && sendAsGroupMessage()) {- const destination_ = destination();- if (destination_ && destination_.type === 'users') {- sendToUsers({- attachments: [asAttachment()],- users: destination_.users,- content: markdown(),- mentions: [],- }).then((res) => {- if (!res) {- return;- }- const { channelId, navigateToChannel } = res;- submitChannelPermissions(channelId);-- props.refetch?.();+ const targets: NonNullable<ReturnType<typeof destination>>[] =+ canSendAsGroup() && sendAsGroupMessage()+ ? [destination_]+ : options.map((option) =>+ option.kind === 'channel'+ ? { type: 'channel', id: option.id }+ : { type: 'users', users: [option.id] }+ );+ const accessLevel = submitAccessLevel();+ setIsSubmitting(true);+ try {+ const results = await Promise.all(+ targets.map((target) => sendForward(target, accessLevel))+ );+ props.refetch?.();+ if (results.some((result) => !result)) {+ if (targets.length > 1) {+ toast.failure('Some messages failed to send');+ }+ return;+ }++ if (targets.length > 1) {+ toast.success('Messages sent successfully');+ } else {+ const result = results[0];+ if (result) {toast.success('Message sent successfully', {actions: [{label: 'View in channel',- onClick: navigateToChannel,+ onClick: result.navigateToChannel,},],});- trackForwardShare('user');- });- } else {- toast.failure('Message failed to send');- }- } else {- const multipleMessages = options.length > 1;- let successfullySentAllMessages = true;- for (const option of options) {- if (option.kind === 'channel') {- Promise.all([- submitChannelPermissions(option.id),- sendToChannel({- attachments: [asAttachment()],- content: markdown(),- channelId: option.id,- mentions: [],- }).then((res) => {- if (!res) {- successfullySentAllMessages = false;- return;- }- props.refetch?.();- if (!multipleMessages) {- const { navigateToChannel } = res;- toast.success('Message sent successfully', {- actions: [- {- label: 'View in channel',- onClick: () => navigateToChannel(),- },- ],- });- }- trackForwardShare('channel');- }),- ]);- } else {- // handles option.kind of user, custom, and contact (gmail)- sendToUsers({- attachments: [asAttachment()],- content: markdown(),- users: [option.id],- mentions: [],- }).then((res) => {- if (!res) {- successfullySentAllMessages = false;- return;- }- const { channelId, navigateToChannel } = res;- submitChannelPermissions(channelId);-- props.refetch?.();- if (!multipleMessages) {- toast.success('Message sent successfully', {- actions: [- {- label: 'View in channel',- onClick: () => navigateToChannel(),- },- ],- });- }- trackForwardShare('user');- });- }- }- if (multipleMessages) {- if (successfullySentAllMessages) {- toast.success('Messages sent successfully');- } else {- toast.failure('Some messages failed to send');}}+ deliveries.clear();+ props.onSubmit?.();+ } finally {+ setIsSubmitting(false);}-- const destination_ = destination();- if (!destination_) {- return;- }-- props.onSubmit?.();}// Not detached: the handler below captures cmd+enter before the scope walk@@ -439,7 +459,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {// Holding the shortcut repeats keydown; swallow the repeats so one press// sends one share, but keep capturing them so none reaches the composer.if (event?.repeat) return true;- handleSubmit();+ void handleSubmit();return true;},});@@ -466,6 +486,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {when={!isMobile()}fallback={<MobileForwardToChannelLayout+ editPermissionEnabled={props.editPermissionEnabled}isAuthenticated={isAuthenticated}selectedOptions={selectedOptions}setSelectedOptions={(v) => setSelectedOptions(v)}@@ -512,6 +533,7 @@ export function ForwardToChannel(props: ForwardToChannelProps) {<span class="text-sm text-ink-extra-muted">can</span></Show><ShareOptions+ editPermissionEnabled={props.editPermissionEnabled}setPermissions={(accessLevel) =>setSubmitAccessLevel(accessLevel)}@@ -611,11 +633,11 @@ export function ForwardToChannel(props: ForwardToChannelProps) {variant={selectedOptions().length > 0 ? 'accent' : 'ghost'}depth={3}class="rounded-lg border-0"- disabled={selectedOptions().length === 0}+ disabled={selectedOptions().length === 0 || isSubmitting()}onClick={() => {const options = selectedOptions();if (options && options.length > 0) {- handleSubmit();+ void handleSubmit();}}}>diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex 46ca81b1f0..f7f17c744c 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -1,15 +1,23 @@import { ForwardToChannel } from '@core/component/ForwardToChannel';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { ok } from 'neverthrow';import { createSignal, For, type JSX } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Permissions } from '../SharePermissions';-import { ShareDialogContext, ShareModal, ShareTrigger } from './ShareButton';+import {+ ShareDialogContext,+ ShareModal,+ ShareOptions,+ ShareTrigger,+} from './ShareButton';const mocks = vi.hoisted(() => ({sendToChannel: vi.fn(),sendToUsers: vi.fn(),mobile: false,hasTeam: false,+ getAgentPermissions: vi.fn(),+ updateAgentPermissions: vi.fn(),getDocumentPermissions: vi.fn(),getChatPermissions: vi.fn(),updateChatPermissions: vi.fn(),@@ -23,6 +31,7 @@ const mocks = vi.hoisted(() => ({editDocument: vi.fn(),copyLink: vi.fn(),blockPermissionsRead: vi.fn(),+ blockEditPermissionEnabled: true,inBlock: true,}));vi.mock('@app/lib/analytics/analytics-context', () => ({@@ -34,6 +43,10 @@ vi.mock('@channel/Input', () => ({}),}));vi.mock('@core/auth', () => ({ useIsAuthenticated: () => () => true }));+vi.mock('@core/constant/allBlocks', () => ({+ resolveBlockAlias: (name: string) =>+ ['task', 'snippet', 'skill'].includes(name) ? 'md' : name,+}));vi.mock('@core/block', () => ({isInBlock: () => mocks.inBlock,useBlockAliasedName: () => 'agent',@@ -83,6 +96,7 @@ vi.mock('@core/signal/useCombinedRecipient', () => ({vi.mock('@core/util/channels', () => ({ useSendMessageToPeople: () => mocks }));vi.mock('@service-storage/client', () => ({storageServiceClient: {+ getBatchChannelPreviews: async () => ok({ previews: [] }),getDocumentPermissions: mocks.getDocumentPermissions,editDocument: mocks.editDocument,projects: {@@ -94,8 +108,14 @@ vi.mock('@service-storage/client', () => ({name === 'agent' ? 'agent_session' : 'document',itemTypeToReferenceEntityType: (type: string) => type,}));+vi.mock('@queries/agent-session/share-permissions', () => ({+ fetchAgentSessionSharePermissions: (...args: unknown[]) =>+ mocks.getAgentPermissions(...args),+ updateAgentSessionSharePermissions: (...args: unknown[]) =>+ mocks.updateAgentPermissions(...args),+}));vi.mock('@core/component/SharePermissions', () => ({- Permissions: { OWNER: 'owner' },+ Permissions: { OWNER: 'owner', CAN_VIEW: 'view' },}));vi.mock('@core/component/Toast/Toast', () => ({toast: { success: vi.fn(), failure: vi.fn() },@@ -108,7 +128,7 @@ vi.mock('@core/context/user', () => ({useReferralCode: () => () => undefined,}));vi.mock('@channel/use-channel-participants', () => ({- useChannelParticipants: () => () => [],+ useChannelParticipants: () => ({ users: () => [], ids: () => [] }),}));vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));@@ -137,7 +157,7 @@ vi.mock('@core/signal/blockElement', () => ({blockHotkeyScopeSignal: { get: () => '' },}));vi.mock('@core/signal/load', () => ({- blockEditPermissionEnabledSignal: () => true,+ blockEditPermissionEnabledSignal: () => mocks.blockEditPermissionEnabled,}));vi.mock('@core/signal/permissions', () => ({useGetPermissions: () => () => 'owner',@@ -215,7 +235,12 @@ vi.mock('@components/app/mobile/MobileDrawer', () => {}),};});-vi.mock('@ui', () => {+vi.mock('@ui', async () => {+ const { createContext, useContext } = await import('solid-js');+ const RadioContext = createContext<{+ label: string;+ onChange?: (value: string) => void;+ }>();const Container = (props: { children?: JSX.Element }) => props.children;return {Button: (props: {@@ -238,8 +263,7 @@ vi.mock('@ui', () => {Trigger: Container,Content: Container,Item: Container,- // Each radio group exposes one button per option, labelled by the group's- // accessible name, so tests can pick a value on a specific group.+ // Use only rendered options, so the mock cannot invent unsupported grants.RadioGroup: (props: {children?: JSX.Element;value?: string;@@ -249,25 +273,40 @@ vi.mock('@ui', () => {const label = props['aria-label'] ?? 'option';return (<div role="group" aria-label={label} data-value={props.value}>- {props.children}- <For each={['NONE', 'view', 'comment', 'edit']}>- {(value) => (- <button- aria-label={`Set ${label} ${value}`}- onClick={() => props.onChange?.(value)}- />- )}- </For>+ <RadioContext.Provider value={{ label, onChange: props.onChange }}>+ {props.children}+ </RadioContext.Provider></div>);},- RadioItem: Container,+ RadioItem: (props: { value: string; children?: JSX.Element }) => {+ const group = useContext(RadioContext);+ return (+ <button+ aria-label={`Set ${group?.label} ${props.value}`}+ onClick={() => group?.onChange?.(props.value)}+ >+ {props.children}+ </button>+ );+ },ItemIndicator: Container,Group: Container,}),ButtonGroup: Object.assign(Container, { Divider: () => null }),- SegmentedControl: (props: { 'aria-label'?: string }) => (- <div role="group" aria-label={props['aria-label']} />+ SegmentedControl: (props: {+ 'aria-label'?: string;+ onChange?: (value: string) => void;+ }) => (+ <div role="group" aria-label={props['aria-label']}>+ <For each={['NONE', 'PUBLIC', 'TEAM']}>+ {(scope) => (+ <button onClick={() => props.onChange?.(scope)}>+ Set link {scope}+ </button>+ )}+ </For>+ </div>),cn: (...values: unknown[]) => values.filter(Boolean).join(' '),Hotkey: () => null,@@ -276,10 +315,19 @@ vi.mock('@ui', () => {beforeEach(() => {vi.clearAllMocks();mocks.inBlock = true;+ mocks.blockEditPermissionEnabled = true;mocks.mobile = false;mocks.hasTeam = false;mocks.callRecordShared = true;mocks.callRecordQuerySuccess = true;+ mocks.getAgentPermissions.mockResolvedValue(+ ok({+ id: 'session-permissions',+ owner: 'owner',+ channelSharePermissions: [],+ })+ );+ mocks.updateAgentPermissions.mockResolvedValue(ok({}));mocks.updateChatPermissions.mockResolvedValue({ isErr: () => false });mocks.updateCallTeamShare.mockResolvedValue({ isErr: () => false });mocks.editProject.mockResolvedValue({ isErr: () => false });@@ -288,7 +336,10 @@ beforeEach(() => {configurable: true,value: { writeText: mocks.copyLink },});- mocks.sendToChannel.mockResolvedValue({ navigateToChannel: vi.fn() });+ mocks.sendToChannel.mockResolvedValue({+ channelId: 'channel-1',+ navigateToChannel: vi.fn(),+ });});afterEach(cleanup);function mountShare(isOwner: boolean) {@@ -314,6 +365,119 @@ const share = () =>fireEvent.click(screen.getByRole('button', { name: 'Share' }));describe('agent session sharing', () => {+ it.each([false, true])(+ 'offers Edit for forwarding, people, and links when the legacy block disables editing (mobile: %s)',+ async (mobile) => {+ mocks.mobile = mobile;+ mocks.blockEditPermissionEnabled = false;+ mocks.getAgentPermissions.mockResolvedValue(+ ok({+ id: 'session-permissions',+ owner: 'owner',+ linkShare: 'PUBLIC',+ linkShareAccessLevel: 'view',+ channelSharePermissions: [+ { channel_id: 'shared-channel', access_level: 'view' },+ ],+ })+ );+ mountShare(true);+ const editOptions = () =>+ screen.getAllByRole('button', { name: 'Set option edit' });+ await vi.waitFor(() =>+ expect(editOptions()).toHaveLength(mobile ? 1 : 3)+ );++ fireEvent.click(editOptions()[0]);+ selectChannel();+ share();+ await vi.waitFor(() =>+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ {+ channelSharePermissions: [+ {+ operation: 'replace',+ accessLevel: 'edit',+ channelId: 'channel-1',+ },+ ],+ }+ )+ );++ if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'People' }));+ fireEvent.click(editOptions()[mobile ? 0 : 1]);+ await vi.waitFor(() =>+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ {+ channelSharePermissions: [+ {+ operation: 'replace',+ accessLevel: 'edit',+ channelId: 'shared-channel',+ },+ ],+ }+ )+ );++ if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Link' }));+ fireEvent.click(editOptions()[mobile ? 0 : 2]);+ await vi.waitFor(() =>+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ { linkShare: 'PUBLIC', linkShareAccessLevel: 'edit' }+ )+ );+ }+ );++ it.each([false, true])(+ 'updates public links and team access through session permissions (mobile: %s)',+ async (mobile) => {+ mocks.mobile = mobile;+ mocks.hasTeam = true;+ mountShare(true);+ if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Link' }));++ fireEvent.click(screen.getByRole('button', { name: 'Set link PUBLIC' }));+ await vi.waitFor(() =>+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ { linkShare: 'PUBLIC', linkShareAccessLevel: 'view' }+ )+ );+ fireEvent.click(screen.getByRole('button', { name: 'Set link NONE' }));+ await vi.waitFor(() =>+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ { linkShare: null, linkShareAccessLevel: null }+ )+ );+ fireEvent.click(+ screen.getByRole('button', { name: 'Set Team access level edit' })+ );+ await vi.waitFor(() =>+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ { teamShareAccessLevel: 'edit' }+ )+ );+ expect(mocks.editDocument).not.toHaveBeenCalled();+ expect(mocks.updateChatPermissions).not.toHaveBeenCalled();+ }+ );++ it('lists the owner in the mobile People tab', () => {+ mocks.mobile = true;+ mountShare(true);+ fireEvent.click(screen.getByRole('tab', { name: 'People' }));+ expect(screen.getByText('Me')).toBeTruthy();+ expect(screen.getByText('Owner')).toBeTruthy();+ });+it.each([false, true])('shows the standard share form for owners (mobile: %s)',(mobile) => {@@ -323,7 +487,17 @@ describe('agent session sharing', () => {screen.getByRole('button', { name: 'Select channel' })).toBeTruthy();expect(screen.getByRole('button', { name: 'Share' })).toBeTruthy();- expect(screen.queryByRole('button', { name: 'Copy Link' })).toBeNull();+ if (mobile) {+ expect(screen.getByRole('tab', { name: 'People' })).toBeTruthy();+ expect(screen.getByRole('tab', { name: 'Link' })).toBeTruthy();+ } else {+ expect(+ screen.getByText('People with access to this agent session')+ ).toBeTruthy();+ expect(+ screen.getByRole('group', { name: 'Link sharing scope' })+ ).toBeTruthy();+ }expect(screen.queryByText('Recipients can view and control this agent session.'@@ -362,14 +536,16 @@ describe('agent session sharing', () => {'https://macro.com/app/agent/current-session');});- it('shares the persisted session instead of its enclosing launcher identity', () => {+ it('shares the persisted session instead of its enclosing launcher identity', async () => {const { onOpenChange } = mountShare(true);- expect(screen.queryByText('Can view')).toBeNull();- expect(screen.queryByText('People with access')).toBeNull();+ expect(+ screen.getByText('People with access to this agent session')+ ).toBeTruthy();expect(mocks.blockPermissionsRead).not.toHaveBeenCalled();expect(mocks.getDocumentPermissions).not.toHaveBeenCalled();expect(mocks.getChatPermissions).not.toHaveBeenCalled();expect(mocks.getProjectPermissions).not.toHaveBeenCalled();+ expect(mocks.getAgentPermissions).toHaveBeenCalledWith('persisted-session');selectChannel();share();expect(mocks.sendToChannel).toHaveBeenCalledWith({@@ -380,7 +556,15 @@ describe('agent session sharing', () => {channelId: 'channel-1',mentions: [],});- expect(onOpenChange).toHaveBeenCalledWith(false);+ await vi.waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ expect(mocks.updateAgentPermissions).toHaveBeenCalledWith(+ 'persisted-session',+ {+ channelSharePermissions: [+ { operation: 'replace', accessLevel: 'view', channelId: 'channel-1' },+ ],+ }+ );});it.each([false, true])('lets participants copy a link without exposing a grant action (mobile: %s)',@@ -391,11 +575,16 @@ describe('agent session sharing', () => {screen.queryByRole('button', { name: 'Select channel' })).toBeNull();expect(screen.queryByRole('button', { name: 'Share' })).toBeNull();+ expect(+ screen.queryByRole('group', { name: 'Link sharing scope' })+ ).toBeNull();+ expect(screen.queryByRole('tab', { name: 'Link' })).toBeNull();fireEvent.click(screen.getByRole('button', { name: 'Copy Link' }));expect(onCopyLink).toHaveBeenCalledWith('https://macro.com/app/agent/persisted-session');expect(mocks.sendToChannel).not.toHaveBeenCalled();+ expect(mocks.updateAgentPermissions).not.toHaveBeenCalled();});it('cancels an owner draft without sharing', () => {@@ -450,6 +639,23 @@ describe('agent session sharing', () => {});});+describe('share edit availability', () => {+ it.each([+ { legacy: false, explicit: undefined, expected: false },+ { legacy: true, explicit: undefined, expected: true },+ { legacy: false, explicit: true, expected: true },+ { legacy: true, explicit: false, expected: false },+ ])('honors capability overrides: %j', ({ legacy, explicit, expected }) => {+ mocks.blockEditPermissionEnabled = legacy;+ render(() => (+ <ShareOptions editPermissionEnabled={explicit} setPermissions={vi.fn()} />+ ));+ expect(+ screen.queryByRole('button', { name: 'Set option edit' }) !== null+ ).toBe(expected);+ });+});+function mountChatShare() {mocks.blockPermissionsRead.mockReturnValue({isErr: () => false,diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex 461785c84a..f57d772a2b 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -48,6 +48,10 @@ import IconShared from '@phosphor/share.svg';import UserCircle from '@phosphor/user-circle.svg';import UsersIcon from '@phosphor/users.svg';import IconX from '@phosphor/x.svg';+import {+ fetchAgentSessionSharePermissions,+ updateAgentSessionSharePermissions,+} from '@queries/agent-session/share-permissions';import {setCallRecordTeamShareCache,sharePermissionFromCallRecord,@@ -120,11 +124,12 @@ import {false && clickOutside;const isLinkSharingDisabledForItem = (itemType: ItemType): boolean =>- itemType === 'email' ||- itemType === 'project' ||- itemType === 'agent_session';+ itemType === 'email' || itemType === 'project';async function fetchSharePermissions(id: string, itemType: ItemType) {+ if (itemType === 'agent_session') {+ return fetchAgentSessionSharePermissions(id);+ }if (itemType === 'chat') {return cognitionApiServiceClient.getChatPermissions({ id });}@@ -296,6 +301,7 @@ function GroupChannelLabel(props: { channelId: string; fallbackName: string }) {}interface LinkSharingControlsProps {+ editPermissionEnabled?: boolean;linkShare: LinkShare | null | undefined;linkShareAccessLevel: AccessLevel | null | undefined;hasExplicitShares: boolean;@@ -408,6 +414,7 @@ function LinkSharingControls(props: LinkSharingControlsProps) {<div class="flex items-center gap-2 text-ink-muted"><span>Access level</span><ShareOptions+ editPermissionEnabled={props.editPermissionEnabled}permissions={props.linkShareAccessLevel ?? 'view'}hideNoAccess={true}setPermissions={props.setLinkShareAccessLevel}@@ -431,6 +438,7 @@ function LinkSharingControls(props: LinkSharingControlsProps) {}interface MobileShareDrawerProps {+ editPermissionEnabled?: boolean;canForward: boolean;isOpen: boolean;setIsOpen: (value: boolean) => void;@@ -453,7 +461,7 @@ interface MobileShareDrawerProps {channelId: string,accessLevel: AccessLevel,hideSuccessToast?: boolean- ) => void;+ ) => Promise<boolean | undefined>;setLinkShareScope: (scope: LinkShareScope) => void;setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;copyLink: () => void;@@ -471,10 +479,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {const mobileTabs = createMemo((): TabItem[] => {const tabs: TabItem[] = [{ value: 'share', label: 'Share' }];- if (- props.itemType !== 'agent_session' &&- ((props.recipients?.length ?? 0) > 0 || props.owner)- )+ if ((props.recipients?.length ?? 0) > 0 || props.owner)tabs.push({ value: 'people', label: 'People' });if (props.userPermissions === Permissions.OWNER &&@@ -556,24 +561,18 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {</Show><Show when={props.canForward}><ForwardToChannel+ editPermissionEnabled={props.editPermissionEnabled}ref={(handle) => setForwardRef(handle)}- submitPermissionInfo={- props.itemType === 'agent_session'- ? undefined- : {- setChannelPermissions: (id, accessLevel) =>- props.setChannelPermissions(id, accessLevel, true),- userPermissions: props.userPermissions,- channelSharePermissions: props.recipients,- }- }+ submitPermissionInfo={{+ setChannelPermissions: (id, accessLevel) =>+ props.setChannelPermissions(id, accessLevel, true),+ userPermissions: props.userPermissions,+ channelSharePermissions: props.recipients,+ }}onSubmit={() => props.setIsOpen(false)}refetch={props.refetch}name={props.name}- hideAccessLevelSelector={- props.itemType === 'email' ||- props.itemType === 'agent_session'- }+ hideAccessLevelSelector={props.itemType === 'email'}initialAccessLevel={props.itemType === 'email' ? 'view' : null}blockId={props.id}blockName={props.blockAlias}@@ -650,6 +649,8 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {</div><div class="flex items-center"><ShareOptions+ editPermissionEnabled={props.editPermissionEnabled}+ disabled={props.userPermissions !== Permissions.OWNER}permissions={recipient.access_level}setPermissions={(accessLevel) => {if (accessLevel === null) {@@ -670,6 +671,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {</Show><Show when={effectiveActiveTab() === 'link'}><LinkSharingControls+ editPermissionEnabled={props.editPermissionEnabled}linkShare={props.linkShare}linkShareAccessLevel={props.linkShareAccessLevel}hasExplicitShares={(props.recipients?.length ?? 0) > 0}@@ -729,6 +731,12 @@ export function ShareModal(props: ShareModalProps) {const canForward = () =>props.itemType !== 'agent_session' ||(Boolean(userId()) && props.owner === userId());+ const userPermissions = () =>+ props.itemType === 'agent_session' && !canForward()+ ? Permissions.CAN_VIEW+ : props.userPermissions;+ const editPermissionEnabled = () =>+ props.itemType === 'agent_session' ? true : undefined;const [recipientScrollRef, setRecipientScrollRef] =createSignal<HTMLElement>();@@ -813,7 +821,20 @@ export function ShareModal(props: ShareModalProps) {});const removeChannelAccess = createCallback(async (channelId: string) => {- if (props.itemType === 'chat') {+ if (userPermissions() !== Permissions.OWNER) return;+ if (props.itemType === 'agent_session') {+ const result = await updateAgentSessionSharePermissions(props.id, {+ channelSharePermissions: [{ operation: 'remove', channelId }],+ });+ if (result.isOk()) {+ refetch();+ toast.success('Removed channel access');+ } else {+ toast.alert('Failed to remove channel access', {+ subtext: 'Please try again',+ });+ }+ } else if (props.itemType === 'chat') {const result = await cognitionApiServiceClient.updateChatPermissions({chat_id: props.id,sharePermission: {@@ -889,13 +910,19 @@ export function ShareModal(props: ShareModalProps) {accessLevel: AccessLevel,hideSuccessToast?: boolean) => {- if (props.userPermissions !== Permissions.OWNER) return;+ if (userPermissions() !== Permissions.OWNER) return;let result:| Result<any, ResultError<any>[]>| Result<void, ResultError<any>[]>| null = null;- if (props.itemType === 'chat') {+ if (props.itemType === 'agent_session') {+ result = await updateAgentSessionSharePermissions(props.id, {+ channelSharePermissions: [+ { operation: 'replace', accessLevel, channelId },+ ],+ });+ } else if (props.itemType === 'chat') {result = await cognitionApiServiceClient.updateChatPermissions({sharePermission: {channelSharePermissions: [@@ -963,11 +990,13 @@ export function ShareModal(props: ShareModalProps) {shareMethod: 'channel',accessLevel,});+ return true;} else {toast.alert('Failed to change channel access', {subtext: 'Please try again',});console.error(result);+ return false;}});@@ -1005,7 +1034,10 @@ export function ShareModal(props: ShareModalProps) {const updateTeamSharePermissions = createCallback(async (sharePermission: TeamSharePayload) => {- if (!isTeamShareSupportedForItem(props.itemType)) {+ if (+ userPermissions() !== Permissions.OWNER ||+ !isTeamShareSupportedForItem(props.itemType)+ ) {return;}const itemNoun = getShareItemNoun(props.itemType);@@ -1013,7 +1045,12 @@ export function ShareModal(props: ShareModalProps) {getTeamShareScope(sharePermission.teamShareAccessLevel) !== 'NONE';let result: Result<unknown, ResultError<any>[]>;- if (props.itemType === 'chat') {+ if (props.itemType === 'agent_session') {+ result = await updateAgentSessionSharePermissions(+ props.id,+ sharePermission+ );+ } else if (props.itemType === 'chat') {result = await cognitionApiServiceClient.updateChatPermissions({sharePermission,chat_id: props.id,@@ -1067,7 +1104,7 @@ export function ShareModal(props: ShareModalProps) {const teamShareControls = (): TeamShareControls | undefined =>isTeamShareSupportedForItem(props.itemType) &&- props.userPermissions === Permissions.OWNER &&+ userPermissions() === Permissions.OWNER &¤tTeamQuery.isSuccess &¤tTeamQuery.data? {@@ -1080,10 +1117,16 @@ export function ShareModal(props: ShareModalProps) {const updateLinkSharePermissions = createCallback(async (sharePermission: LinkSharePayload) => {+ if (userPermissions() !== Permissions.OWNER) return;const scope = getLinkShareScope(sharePermission.linkShare);let result: Result<any, ResultError<any>[]> | undefined;- if (props.itemType === 'chat') {+ if (props.itemType === 'agent_session') {+ result = await updateAgentSessionSharePermissions(+ props.id,+ sharePermission+ );+ } else if (props.itemType === 'chat') {result = await cognitionApiServiceClient.updateChatPermissions({sharePermission,chat_id: props.id,@@ -1100,8 +1143,7 @@ export function ShareModal(props: ShareModalProps) {});}- const entityLabel =- props.itemType === 'project' ? 'folder' : props.itemType;+ const entityLabel = getShareItemNoun(props.itemType);if (!result || result.isErr()) {toast.alert(`Failed to change ${entityLabel} access`, {subtext: 'Please try again',@@ -1172,6 +1214,7 @@ export function ShareModal(props: ShareModalProps) {when={!isMobile()}fallback={<MobileShareDrawer+ editPermissionEnabled={editPermissionEnabled()}canForward={canForward()}isOpen={props.isSharePermOpen}setIsOpen={props.setIsSharePermOpen}@@ -1180,7 +1223,7 @@ export function ShareModal(props: ShareModalProps) {id={props.id}itemType={props.itemType}owner={props.owner}- userPermissions={props.userPermissions}+ userPermissions={userPermissions()}recipients={recipients()}channelNameMap={channelNameMap()}formattedOwner={formattedOwner()}@@ -1229,24 +1272,18 @@ export function ShareModal(props: ShareModalProps) {</Show><Show when={canForward()}><ForwardToChannel- submitPermissionInfo={- props.itemType === 'agent_session'- ? undefined- : {- setChannelPermissions: (id, accessLevel) =>- setChannelPermissions(id, accessLevel, true),- userPermissions: props.userPermissions,- channelSharePermissions: recipients(),- }- }+ editPermissionEnabled={editPermissionEnabled()}+ submitPermissionInfo={{+ setChannelPermissions: (id, accessLevel) =>+ setChannelPermissions(id, accessLevel, true),+ userPermissions: userPermissions(),+ channelSharePermissions: recipients(),+ }}onSubmit={() => props.setIsSharePermOpen(false)}onCancel={() => props.setIsSharePermOpen(false)}refetch={refetch}name={props.name}- hideAccessLevelSelector={- props.itemType === 'email' ||- props.itemType === 'agent_session'- }+ hideAccessLevelSelector={props.itemType === 'email'}initialAccessLevel={props.itemType === 'email' ? 'view' : null}@@ -1266,19 +1303,12 @@ export function ShareModal(props: ShareModalProps) {</Panel>{/* Card 2: Recipients — plain border */}- <Show- when={- props.itemType !== 'agent_session' &&- ((recipients()?.length ?? 0) > 0 || !!props.owner)- }- >+ <Show when={(recipients()?.length ?? 0) > 0 || !!props.owner}><Panel depth={2} class="rounded-xl bg-dialog"><Panel.Header class="px-4"><span class="text-sm font-medium">People with access to this{' '}- {props.itemType === 'email'- ? 'email thread'- : props.itemType}+ {getShareItemNoun(props.itemType)}</span></Panel.Header><Panel.Body class="text-ink">@@ -1372,6 +1402,10 @@ export function ShareModal(props: ShareModalProps) {</div><div class="flex items-center"><ShareOptions+ editPermissionEnabled={editPermissionEnabled()}+ disabled={+ userPermissions() !== Permissions.OWNER+ }permissions={recipient.access_level}setPermissions={(accessLevel) => {if (accessLevel === null) {@@ -1402,13 +1436,14 @@ export function ShareModal(props: ShareModalProps) {{/* Card 3: Link sharing — plain border */}<Showwhen={- props.userPermissions === Permissions.OWNER &&+ userPermissions() === Permissions.OWNER &&!isLinkSharingDisabledForItem(props.itemType)}><Panel depth={2} class="rounded-xl bg-dialog"><Panel.Body><LinkSharingControls+ editPermissionEnabled={editPermissionEnabled()}linkShare={linkShare()}linkShareAccessLevel={linkShareAccessLevel()}hasExplicitShares={(recipients()?.length ?? 0) > 0}@@ -1624,6 +1659,7 @@ const PERMISSION_ICONS = {} as const;export function ShareOptions(props: {+ editPermissionEnabled?: boolean;setPermissions: (accessLevel: AccessLevel | null) => void;permissions?: AccessLevel | null;hideNoAccess?: boolean;@@ -1631,9 +1667,11 @@ export function ShareOptions(props: {disabled?: boolean;noBorder?: boolean;}) {- const editPermissionEnabled = isInBlock()- ? blockEditPermissionEnabledSignal()- : true;+ const blockEditPermissionEnabled = isInBlock()+ ? blockEditPermissionEnabledSignal+ : () => true;+ const editPermissionEnabled = () =>+ props.editPermissionEnabled ?? blockEditPermissionEnabled();const blockName = isInBlock() ? useBlockName() : undefined;const options = createMemo(() => {@@ -1648,7 +1686,7 @@ export function ShareOptions(props: {}// Add edit option if enabled- if (editPermissionEnabled) {+ if (editPermissionEnabled()) {optionsList.push({ value: 'edit', label: accessLevelText('edit') });}diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts b/apps/web/src/lib/core/component/TopBar/linkShare.test.tsindex 8bc54d5268..f7efaa3902 100644--- a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts+++ b/apps/web/src/lib/core/component/TopBar/linkShare.test.ts@@ -15,14 +15,14 @@ import {} from './linkShare';describe('isTeamShareSupportedForItem', () => {- it.each(['document', 'chat', 'call', 'project'] as const)(+ it.each(['document', 'chat', 'call', 'project', 'agent_session'] as const)('supports %s',(itemType) => {expect(isTeamShareSupportedForItem(itemType)).toBe(true);});- it.each(['email', 'agent_session'] as const)(+ it.each(['email'] as const)('does not offer team access for %s',(itemType) => {expect(isTeamShareSupportedForItem(itemType)).toBe(false);diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.tsindex ca5ece194d..a1cfdfb68f 100644--- a/apps/web/src/lib/core/component/TopBar/linkShare.ts+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts@@ -10,6 +10,7 @@ const TEAM_SHAREABLE_ITEM_TYPES: ReadonlySet<ItemType> = new Set<ItemType>(['chat','call','project',+ 'agent_session',]);export function isTeamShareSupportedForItem(itemType: ItemType): boolean {diff --git a/apps/web/src/lib/queries/agent-session/share-permissions.ts b/apps/web/src/lib/queries/agent-session/share-permissions.tsnew file mode 100644index 0000000000..b6a8924366--- /dev/null+++ b/apps/web/src/lib/queries/agent-session/share-permissions.ts@@ -0,0 +1,14 @@+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import type { UpdateSharePermissionRequestV2 } from '@service-agent-harness/generated/schemas';++/** The shared share dialog owns loading and refreshing these permissions. */+export function fetchAgentSessionSharePermissions(sessionId: string) {+ return agentHarnessServiceClient.getPermissions(sessionId);+}++export function updateAgentSessionSharePermissions(+ sessionId: string,+ permissions: UpdateSharePermissionRequestV2+) {+ return agentHarnessServiceClient.updatePermissions(sessionId, permissions);+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.tsindex da63e9576c..b3743ac184 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts@@ -18,6 +18,8 @@ import type {PreviewAgentSessionsResponse,SandboxSize,SandboxSizeBody,+ SharePermissionV2,+ UpdateSharePermissionRequestV2,} from './generated/schemas';export type { SandboxSize, SandboxSizeBody };@@ -106,6 +108,28 @@ export const agentHarnessServiceClient = {);},+ getPermissions(sessionId: string) {+ return fetchWithToken<SharePermissionV2>(+ `${agentHarnessHost}/agent-sessions/${sessionId}/permissions`,+ { method: 'GET' }+ );+ },++ updatePermissions(+ sessionId: string,+ request: UpdateSharePermissionRequestV2+ ) {+ return fetchWithToken<SharePermissionV2>(+ `${agentHarnessHost}/agent-sessions/${sessionId}/permissions`,+ {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ errorResponseHandler: sessionError,+ }+ );+ },+getLog(sessionId: string) {return fetchWithToken<AgentSessionLogResponse>(`${agentHarnessHost}/agent-sessions/${sessionId}/log`,diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.tsindex 80204a6e49..a1d0580990 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts@@ -26,8 +26,10 @@ import type {PreviewAgentSessionsResponse,RenameAgentSessionRequest,SandboxSizeBody,+ SharePermissionV2,StartResponse,StatusResponse,+ UpdateSharePermissionRequestV2,} from './schemas';/**@@ -1064,6 +1066,137 @@ export const renameAgentSession = async (} as renameAgentSessionResponse;};+/**+ * @summary Read sharing settings for a session the caller can view.+ */+export type getAgentSessionPermissionsResponse200 = {+ data: SharePermissionV2;+ status: 200;+};++export type getAgentSessionPermissionsResponse403 = {+ data: string;+ status: 403;+};++export type getAgentSessionPermissionsResponse500 = {+ data: string;+ status: 500;+};++export type getAgentSessionPermissionsResponseSuccess =+ getAgentSessionPermissionsResponse200 & {+ headers: Headers;+ };+export type getAgentSessionPermissionsResponseError = (+ | getAgentSessionPermissionsResponse403+ | getAgentSessionPermissionsResponse500+) & {+ headers: Headers;+};++export type getAgentSessionPermissionsResponse =+ | getAgentSessionPermissionsResponseSuccess+ | getAgentSessionPermissionsResponseError;++export const getGetAgentSessionPermissionsUrl = (sessionId: string) => {+ return `/agent-sessions/${sessionId}/permissions`;+};++export const getAgentSessionPermissions = async (+ sessionId: string,+ options?: RequestInit+): Promise<getAgentSessionPermissionsResponse> => {+ const res = await fetch(getGetAgentSessionPermissionsUrl(sessionId), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getAgentSessionPermissionsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getAgentSessionPermissionsResponse;+};++/**+ * @summary Update link, channel, or team sharing after owner authorization.+ */+export type updateAgentSessionPermissionsResponse200 = {+ data: SharePermissionV2;+ status: 200;+};++export type updateAgentSessionPermissionsResponse400 = {+ data: string;+ status: 400;+};++export type updateAgentSessionPermissionsResponse403 = {+ data: string;+ status: 403;+};++export type updateAgentSessionPermissionsResponse409 = {+ data: string;+ status: 409;+};++export type updateAgentSessionPermissionsResponse500 = {+ data: string;+ status: 500;+};++export type updateAgentSessionPermissionsResponseSuccess =+ updateAgentSessionPermissionsResponse200 & {+ headers: Headers;+ };+export type updateAgentSessionPermissionsResponseError = (+ | updateAgentSessionPermissionsResponse400+ | updateAgentSessionPermissionsResponse403+ | updateAgentSessionPermissionsResponse409+ | updateAgentSessionPermissionsResponse500+) & {+ headers: Headers;+};++export type updateAgentSessionPermissionsResponse =+ | updateAgentSessionPermissionsResponseSuccess+ | updateAgentSessionPermissionsResponseError;++export const getUpdateAgentSessionPermissionsUrl = (sessionId: string) => {+ return `/agent-sessions/${sessionId}/permissions`;+};++export const updateAgentSessionPermissions = async (+ sessionId: string,+ updateSharePermissionRequestV2: UpdateSharePermissionRequestV2,+ options?: RequestInit+): Promise<updateAgentSessionPermissionsResponse> => {+ const res = await fetch(getUpdateAgentSessionPermissionsUrl(sessionId), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(updateSharePermissionRequestV2),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: updateAgentSessionPermissionsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as updateAgentSessionPermissionsResponse;+};+/*** @summary The actions waiting to dispatch in this session, oldest first.*/diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/accessLevel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/accessLevel.tsnew file mode 100644index 0000000000..71641e276d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/accessLevel.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Ordered from least to most access top -> bottom+ */+export type AccessLevel = (typeof AccessLevel)[keyof typeof AccessLevel];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const AccessLevel = {+ view: 'view',+ comment: 'comment',+ edit: 'edit',+ owner: 'owner',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/channelSharePermission.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/channelSharePermission.tsnew file mode 100644index 0000000000..f151157454--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/channelSharePermission.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AccessLevel } from './accessLevel';++/**+ * The channel share permission+ */+export interface ChannelSharePermission {+ /** The access level for the channel */+ access_level: AccessLevel;+ /** The channel id */+ channel_id: string;+}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 fe28a402b6..80ed85579d 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@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/+export * from './accessLevel';export * from './agentAction';export * from './agentActionId';export * from './agentActionOneOf';@@ -78,6 +79,7 @@ export * from './changedFileDtoPreviousPath';export * from './changesetDto';export * from './changesetDtoRepository';export * from './changesetSourceDto';+export * from './channelSharePermission';export * from './completeRequest';export * from './controlRequest';export * from './controlRequestAllOf';@@ -119,6 +121,7 @@ export * from './fileChangeKindDto';export * from './gitRefDto';export * from './gitRefDtoName';export * from './gitRefDtoSha';+export * from './linkShare';export * from './listAgentRepositoryBranchesParams';export * from './loadAgentModelsRequest';export * from './loadAgentModelsRequestHarnessId';@@ -158,6 +161,19 @@ export * from './sessionStatusDtoOneOfFiveKind';export * from './sessionStatusDtoOneOfKind';export * from './sessionStatusDtoOneOfThree';export * from './sessionStatusDtoOneOfThreeKind';+export * from './sharePermissionV2';+export * from './sharePermissionV2ChannelSharePermissions';+export * from './sharePermissionV2LinkShare';+export * from './sharePermissionV2LinkShareAccessLevel';+export * from './sharePermissionV2TeamShareAccessLevel';export * from './startResponse';export * from './statusResponse';+export * from './updateChannelSharePermission';+export * from './updateChannelSharePermissionAccessLevel';+export * from './updateOperation';+export * from './updateSharePermissionRequestV2';+export * from './updateSharePermissionRequestV2ChannelSharePermissions';+export * from './updateSharePermissionRequestV2LinkShare';+export * from './updateSharePermissionRequestV2LinkShareAccessLevel';+export * from './updateSharePermissionRequestV2TeamShareAccessLevel';export * from './withAgentSessionId';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/linkShare.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/linkShare.tsnew file mode 100644index 0000000000..02437a3b69--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/linkShare.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Defines who can access an item through its share link.+ */+export type LinkShare = (typeof LinkShare)[keyof typeof LinkShare];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const LinkShare = {+ PUBLIC: 'PUBLIC',+ TEAM: 'TEAM',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2.tsnew file mode 100644index 0000000000..bdaef26f20--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2.ts@@ -0,0 +1,22 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { SharePermissionV2ChannelSharePermissions } from './sharePermissionV2ChannelSharePermissions';+import type { SharePermissionV2LinkShare } from './sharePermissionV2LinkShare';+import type { SharePermissionV2LinkShareAccessLevel } from './sharePermissionV2LinkShareAccessLevel';+import type { SharePermissionV2TeamShareAccessLevel } from './sharePermissionV2TeamShareAccessLevel';++export interface SharePermissionV2 {+ /** The channel share permissions for the item */+ channelSharePermissions?: SharePermissionV2ChannelSharePermissions;+ /** The share permission id */+ id: string;+ linkShare?: SharePermissionV2LinkShare;+ linkShareAccessLevel?: SharePermissionV2LinkShareAccessLevel;+ /** The owner of the item */+ owner: string;+ teamShareAccessLevel?: SharePermissionV2TeamShareAccessLevel;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2ChannelSharePermissions.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2ChannelSharePermissions.tsnew file mode 100644index 0000000000..b07d7ef7ef--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2ChannelSharePermissions.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelSharePermission } from './channelSharePermission';++/**+ * The channel share permissions for the item+ */+export type SharePermissionV2ChannelSharePermissions =+ | ChannelSharePermission[]+ | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2LinkShare.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2LinkShare.tsnew file mode 100644index 0000000000..2d47b6e567--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2LinkShare.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { LinkShare } from './linkShare';++export type SharePermissionV2LinkShare = null | LinkShare;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2LinkShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2LinkShareAccessLevel.tsnew file mode 100644index 0000000000..2af064a0be--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2LinkShareAccessLevel.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AccessLevel } from './accessLevel';++export type SharePermissionV2LinkShareAccessLevel = null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2TeamShareAccessLevel.tsnew file mode 100644index 0000000000..e4b8bbdd92--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/sharePermissionV2TeamShareAccessLevel.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AccessLevel } from './accessLevel';++export type SharePermissionV2TeamShareAccessLevel = null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateChannelSharePermission.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateChannelSharePermission.tsnew file mode 100644index 0000000000..279bbfb5ca--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateChannelSharePermission.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { UpdateChannelSharePermissionAccessLevel } from './updateChannelSharePermissionAccessLevel';+import type { UpdateOperation } from './updateOperation';++export interface UpdateChannelSharePermission {+ accessLevel?: UpdateChannelSharePermissionAccessLevel;+ /** The channel id */+ channelId: string;+ /** The type of operation to be performed on the chanel share permission+You can add, remove or replace and existing permission */+ operation: UpdateOperation;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateChannelSharePermissionAccessLevel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateChannelSharePermissionAccessLevel.tsnew file mode 100644index 0000000000..6371491be1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateChannelSharePermissionAccessLevel.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AccessLevel } from './accessLevel';++export type UpdateChannelSharePermissionAccessLevel = null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateOperation.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateOperation.tsnew file mode 100644index 0000000000..b36b7d1b0e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateOperation.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++export type UpdateOperation =+ (typeof UpdateOperation)[keyof typeof UpdateOperation];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const UpdateOperation = {+ add: 'add',+ remove: 'remove',+ replace: 'replace',+} as const;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2.tsnew file mode 100644index 0000000000..95fd30ed8b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { UpdateSharePermissionRequestV2ChannelSharePermissions } from './updateSharePermissionRequestV2ChannelSharePermissions';+import type { UpdateSharePermissionRequestV2LinkShare } from './updateSharePermissionRequestV2LinkShare';+import type { UpdateSharePermissionRequestV2LinkShareAccessLevel } from './updateSharePermissionRequestV2LinkShareAccessLevel';+import type { UpdateSharePermissionRequestV2TeamShareAccessLevel } from './updateSharePermissionRequestV2TeamShareAccessLevel';++export interface UpdateSharePermissionRequestV2 {+ /** Any channel share permissions to be created/updated/removed */+ channelSharePermissions?: UpdateSharePermissionRequestV2ChannelSharePermissions;+ linkShare?: UpdateSharePermissionRequestV2LinkShare;+ linkShareAccessLevel?: UpdateSharePermissionRequestV2LinkShareAccessLevel;+ teamShareAccessLevel?: UpdateSharePermissionRequestV2TeamShareAccessLevel;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2ChannelSharePermissions.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2ChannelSharePermissions.tsnew file mode 100644index 0000000000..1532dc36ac--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2ChannelSharePermissions.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { UpdateChannelSharePermission } from './updateChannelSharePermission';++/**+ * Any channel share permissions to be created/updated/removed+ */+export type UpdateSharePermissionRequestV2ChannelSharePermissions =+ | UpdateChannelSharePermission[]+ | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2LinkShare.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2LinkShare.tsnew file mode 100644index 0000000000..b0f573dace--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2LinkShare.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { LinkShare } from './linkShare';++export type UpdateSharePermissionRequestV2LinkShare = null | LinkShare;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.tsnew file mode 100644index 0000000000..0bd4f6e338--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AccessLevel } from './accessLevel';++export type UpdateSharePermissionRequestV2LinkShareAccessLevel =+ null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.tsnew file mode 100644index 0000000000..e9eef08d94--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/updateSharePermissionRequestV2TeamShareAccessLevel.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AccessLevel } from './accessLevel';++export type UpdateSharePermissionRequestV2TeamShareAccessLevel =+ null | AccessLevel;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 47414b47d2..fc949860f6 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@@ -889,6 +889,136 @@}}},+ "/agent-sessions/{session_id}/permissions": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Read sharing settings for a session the caller can view.",+ "operationId": "get_agent_session_permissions",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "description": "ID of the agent session",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SharePermissionV2"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["agent-sessions"],+ "summary": "Update link, channel, or team sharing after owner authorization.",+ "operationId": "update_agent_session_permissions",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "description": "ID of the agent session",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateSharePermissionRequestV2"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SharePermissionV2"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/agent-sessions/{session_id}/queue": {"get": {"tags": ["agent-sessions"],@@ -1321,6 +1451,11 @@},"components": {"schemas": {+ "AccessLevel": {+ "type": "string",+ "description": "Ordered from least to most access top -> bottom",+ "enum": ["view", "comment", "edit", "owner"]+ },"AgentAction": {"oneOf": [{@@ -2076,6 +2211,21 @@"description": "The source of the captured diff, on the wire.","enum": ["github_pull_request"]},+ "ChannelSharePermission": {+ "type": "object",+ "description": "The channel share permission",+ "required": ["channel_id", "access_level"],+ "properties": {+ "access_level": {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The access level for the channel"+ },+ "channel_id": {+ "type": "string",+ "description": "The channel id"+ }+ }+ },"CompleteRequest": {"type": "object","description": "One-time manual code. Deliberately does not implement Debug.",@@ -2382,6 +2532,11 @@}}},+ "LinkShare": {+ "type": "string",+ "description": "Defines who can access an item through its share link.",+ "enum": ["PUBLIC", "TEAM"]+ },"LoadAgentModelsRequest": {"type": "object","description": "HTTP request selecting one provider to probe.",@@ -2692,6 +2847,60 @@],"description": "Transport representation of a session's status, mirroring\n[`SessionStatus`]."},+ "SharePermissionV2": {+ "type": "object",+ "required": ["id", "owner"],+ "properties": {+ "channelSharePermissions": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ChannelSharePermission"+ },+ "description": "The channel share permissions for the item"+ },+ "id": {+ "type": "string",+ "description": "The share permission id"+ },+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link"+ }+ ]+ },+ "linkShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The level of access granted through the share link"+ }+ ]+ },+ "owner": {+ "type": "string",+ "description": "The owner of the item"+ },+ "teamShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The explicit access level granted to the owner's team, or `null` when disabled."+ }+ ]+ }+ }+ },"StartResponse": {"type": "object","description": "Public PKCE challenge and attempt handle; contains no verifier or provider tokens.",@@ -2732,6 +2941,80 @@}}},+ "UpdateChannelSharePermission": {+ "type": "object",+ "required": ["operation", "channelId"],+ "properties": {+ "accessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The access level for the channel\nThis is required if the operation is add or replace"+ }+ ]+ },+ "channelId": {+ "type": "string",+ "description": "The channel id"+ },+ "operation": {+ "$ref": "#/components/schemas/UpdateOperation",+ "description": "The type of operation to be performed on the chanel share permission\nYou can add, remove or replace and existing permission"+ }+ }+ },+ "UpdateOperation": {+ "type": "string",+ "enum": ["add", "remove", "replace"]+ },+ "UpdateSharePermissionRequestV2": {+ "type": "object",+ "properties": {+ "channelSharePermissions": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/UpdateChannelSharePermission"+ },+ "description": "Any channel share permissions to be created/updated/removed"+ },+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link. Omit to leave unchanged or pass `null` to\ndisable link sharing."+ }+ ]+ },+ "linkShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."+ }+ ]+ },+ "teamShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The explicit team access level. Omit to leave unchanged or pass `null` to disable team\nsharing. Only the actual owner may change this setting; `owner` is not an allowed level."+ }+ ]+ }+ }+ },"WithAgentSessionId": {"type": "object","description": "Just a session id, for the preview variants that carry nothing else.\n\nClients deserialize this, so both derives are used.",diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex 2d997878b3..f02a73d8f2 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -28,6 +28,7 @@ outbound = ["dep:entity_registry_db_utils","dep:model-entity","dep:sqlx",+ "dep:share_permission_db_utils","macro_user_id/sqlx",]# OpenAPI schemas for the vocabulary that reaches an HTTP boundary: the@@ -67,6 +68,8 @@ entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utilsgenai_telemetry = { path = "../genai_telemetry" }model-entity = { path = "../model-entity", optional = true }model_owner = { path = "../model_owner" }+models_permissions = { path = "../models_permissions" }+share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }clap = { workspace = true, optional = true }macro_authorization = { path = "../macro_authorization", default-features = false, optional = true }macro_user_id = { path = "../macro_user_id" }diff --git a/crates/agent_session/src/domain/audience.rs b/crates/agent_session/src/domain/audience.rsindex 70dbf2094b..82f319f5b5 100644--- a/crates/agent_session/src/domain/audience.rs+++ b/crates/agent_session/src/domain/audience.rs@@ -94,7 +94,7 @@ impl<Repo: AgentSessionRepo, Access: EntityAccessService, Subscriptions: Session}/// Answers session view access through the entity access service, so a-/// preview sees the same inherited document access a read route does.+/// preview sees the same link and inherited document access a read route does.#[derive(Clone)]pub struct EntityAccessSessionView<Access> {access: Access,diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rsindex 20609a81fc..5fab862bdd 100644--- a/crates/agent_session/src/domain/error.rs+++ b/crates/agent_session/src/domain/error.rs@@ -7,6 +7,15 @@ pub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;#[derive(Error, Debug)]pub enum AgentSessionError {+ /// Invalid link or channel sharing input.+ #[error("{0}")]+ InvalidSharing(&'static str),+ /// Explicit owner-team sharing was rejected by the shared policy.+ #[error(transparent)]+ TeamSharing(models_permissions::share_permission::team_share::TeamSharePolicyError),+ /// Sharing facts changed while an owner update was in flight.+ #[error("sharing changed; reload and try again")]+ SharingChanged,/// A repository or branch cannot be used by this session.#[error("{0}")]InvalidRepositorySelection(&'static str),diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rsindex cfdcedc7b3..5617c48bdc 100644--- a/crates/agent_session/src/domain/mod.rs+++ b/crates/agent_session/src/domain/mod.rs@@ -13,6 +13,8 @@ mod sandbox_size;pub mod search;pub mod service;pub mod session;+/// Session link, channel, and team sharing.+pub mod sharing;pub mod credentials;diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 45fe10a865..1b7fef9f8c 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -1060,8 +1060,8 @@ pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {mod test;/// Current view access to a session, resolved the way a read route resolves-/// it - including access inherited from the document a session was opened-/// from, which no access row materializes.+/// it - including share links and access inherited from the document a session+/// was opened from, which no access row materializes.////// Object-safe so the service holds it erased, like its turn observer.pub trait SessionViewAccess: Send + Sync + 'static {@@ -1074,7 +1074,7 @@ pub trait SessionViewAccess: Send + Sync + 'static {}/// Only materialized grants count: a process with no entity-access service,-/// or a test, never discovers inherited access.+/// or a test, never discovers link or inherited access.#[derive(Debug, Clone, Copy, Default)]pub struct NoInheritedSessionAccess;diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rsindex ab9174da76..211abf94df 100644--- a/crates/agent_session/src/domain/service.rs+++ b/crates/agent_session/src/domain/service.rs@@ -715,14 +715,10 @@ wherepreviews.push(AgentSessionPreview::DoesNotExist(id));continue;};- // A grant row settles it. Without one, a session opened from a- // document discussion may still be visible through the document- // itself, which only the access service knows.- let visible = candidate.has_grant- || (matches!(- candidate.thread_parent,- Some(messages::domain::models::MessageParent::Document(_))- ) && self.view_access.can_view(viewer, id).await?);+ // Links and originating documents can grant access without a+ // materialized row. Resolve those through the same view port as+ // the session's read routes.+ let visible = candidate.has_grant || self.view_access.can_view(viewer, id).await?;previews.push(if visible {AgentSessionPreview::Access(Box::new(candidate.data))} else {diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex db637ad489..e7aafbb978 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -94,7 +94,7 @@ impl crate::domain::ports::SessionViewAccess for GrantingViewAccess {}#[tokio::test]-async fn previews_resolve_inherited_document_access_through_the_view_port() {+async fn previews_resolve_document_and_link_access_through_the_view_port() {let fx = fixture();let mut document_session = test_agent_session(AgentSessionId::new());document_session.thread_parent =@@ -122,7 +122,7 @@ async fn previews_resolve_inherited_document_access_through_the_view_port() {.all(|preview| matches!(preview, AgentSessionPreview::NoAccess(_))));- // With one, the document-born session is asked about and the rest are not.+ // The view port can resolve document inheritance or link sharing.let service = fx.service.clone()@@ -140,14 +140,13 @@ async fn previews_resolve_inherited_document_access_through_the_view_port() {.service.clone().with_view_access(Arc::new(GrantingViewAccess(channel_session.id)));- assert_eq!(+ assert!(matches!(channel_service.preview_sessions(&collaborator, vec![channel_session.id]).await- .unwrap(),- vec![AgentSessionPreview::NoAccess(channel_session.id)],- "channel grants are rows; the view port is never consulted for them"- );+ .unwrap().as_slice(),+ [AgentSessionPreview::Access(data)] if data.id == channel_session.id+ ));}#[tokio::test]diff --git a/crates/agent_session/src/domain/sharing.rs b/crates/agent_session/src/domain/sharing.rsnew file mode 100644index 0000000000..3cc3433b98--- /dev/null+++ b/crates/agent_session/src/domain/sharing.rs@@ -0,0 +1,144 @@+//! Sharing policy for persisted agent sessions.++use entity_access::domain::models::{+ EntityAccessReceipt, EntityType, OwnerAccessLevel, RequiredPermission, ViewAccessLevel,+};+use models_permissions::share_permission::{+ SharePermissionV2, UpdateSharePermissionRequestV2,+ access_level::AccessLevel,+ channel_share_permission::UpdateOperation,+ team_share::{+ AuthorizedTeamShareCommand, TeamShareFacts, TeamShareLevel, TeamShareRequest,+ authorize_team_share,+ },+};++use super::{+ error::{AgentSessionError, Result},+ model::AgentSessionId,+};++#[cfg(test)]+mod test;++/// Persistence capability for session sharing, independent of transport.+pub trait SessionSharingRepo: Send + Sync + 'static {+ /// Read canonical sharing settings and direct channel grants.+ fn permissions(+ &self,+ id: AgentSessionId,+ ) -> impl Future<Output = Result<SharePermissionV2>> + Send;++ /// Load actual ownership, team membership, and explicit sharing facts.+ fn team_share_facts(+ &self,+ id: AgentSessionId,+ ) -> impl Future<Output = Result<TeamShareFacts>> + Send;++ /// Atomically persist sharing settings and grants, rechecking team facts.+ fn update_permissions(+ &self,+ id: AgentSessionId,+ request: UpdateSharePermissionRequestV2,+ team_share: Option<AuthorizedTeamShareCommand>,+ ) -> impl Future<Output = Result<SharePermissionV2>> + Send;+}++/// Authorized use cases exposed to sharing adapters.+pub trait SessionSharing: Send + Sync + 'static {+ /// Read settings for a session the caller can view.+ fn permissions(+ &self,+ access: &EntityAccessReceipt<ViewAccessLevel>,+ ) -> impl Future<Output = Result<SharePermissionV2>> + Send;++ /// Change sharing only after owner access has been established.+ fn update_permissions(+ &self,+ access: &EntityAccessReceipt<OwnerAccessLevel>,+ request: UpdateSharePermissionRequestV2,+ ) -> impl Future<Output = Result<SharePermissionV2>> + Send;+}++/// Session-sharing service; policy lives here and storage remains behind its port.+pub struct SessionSharingService<R> {+ repo: R,+}++impl<R> SessionSharingService<R> {+ /// Construct sharing use cases over a repository.+ pub fn new(repo: R) -> Self {+ Self { repo }+ }+}++fn session_id<T: RequiredPermission>(access: &EntityAccessReceipt<T>) -> Result<AgentSessionId> {+ if access.entity().entity_type != EntityType::AgentSession {+ return Err(AgentSessionError::Forbidden);+ }+ let id = macro_uuid::Uuid::parse_str(&access.entity().entity_id)+ .map_err(|_| AgentSessionError::InvalidSharing("invalid agent session id"))?;+ Ok(AgentSessionId::new_from_uuid(id))+}++fn validate(request: &UpdateSharePermissionRequestV2) -> Result<()> {+ if request.link_share_access_level.flatten() == Some(AccessLevel::Owner) {+ return Err(AgentSessionError::InvalidSharing(+ "links cannot grant owner access",+ ));+ }+ for grant in request.channel_share_permissions.iter().flatten() {+ if macro_uuid::Uuid::parse_str(&grant.channel_id).is_err() {+ return Err(AgentSessionError::InvalidSharing("invalid channel id"));+ }+ if grant.access_level == Some(AccessLevel::Owner) {+ return Err(AgentSessionError::InvalidSharing(+ "channels cannot grant owner access",+ ));+ }+ if grant.operation != UpdateOperation::Remove && grant.access_level.is_none() {+ return Err(AgentSessionError::InvalidSharing(+ "channel access level is required",+ ));+ }+ }+ Ok(())+}++impl<R: SessionSharingRepo> SessionSharing for SessionSharingService<R> {+ async fn permissions(+ &self,+ access: &EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<SharePermissionV2> {+ self.repo.permissions(session_id(access)?).await+ }++ async fn update_permissions(+ &self,+ access: &EntityAccessReceipt<OwnerAccessLevel>,+ request: UpdateSharePermissionRequestV2,+ ) -> Result<SharePermissionV2> {+ let id = session_id(access)?;+ validate(&request)?;+ let permissions = self.repo.permissions(id).await?;+ if access.acting_user_id().map(|user| user.as_ref()) != Some(permissions.owner.as_str()) {+ return Err(AgentSessionError::Forbidden);+ }+ let team_share = if request.team_share_access_level.is_some() {+ let facts = self.repo.team_share_facts(id).await?;+ authorize_team_share(+ access.acting_user_id(),+ &facts,+ TeamShareRequest {+ access_level: request.team_share_access_level,+ legacy_enabled: None,+ },+ TeamShareLevel::View,+ )+ .map_err(AgentSessionError::TeamSharing)?+ } else {+ None+ };+ self.repo.update_permissions(id, request, team_share).await+ }+}diff --git a/crates/agent_session/src/domain/sharing/test.rs b/crates/agent_session/src/domain/sharing/test.rsnew file mode 100644index 0000000000..859ee8776b--- /dev/null+++ b/crates/agent_session/src/domain/sharing/test.rs@@ -0,0 +1,240 @@+use super::*;+use entity_access::domain::models::{Entity, EntityPermission};+use macro_user_id::user_id::MacroUserIdStr;+use models_permissions::share_permission::{+ LinkShare, channel_share_permission::UpdateChannelSharePermission,+};+use std::sync::{Arc, Mutex};++const OWNER: &str = "macro|[email protected]";+type SavedUpdate = (+ UpdateSharePermissionRequestV2,+ Option<AuthorizedTeamShareCommand>,+);++#[derive(Clone)]+struct Repo {+ id: AgentSessionId,+ writes: Arc<Mutex<Vec<SavedUpdate>>>,+}++impl Repo {+ fn new() -> Self {+ Self {+ id: AgentSessionId::new(),+ writes: Default::default(),+ }+ }+}++impl SessionSharingRepo for Repo {+ async fn permissions(&self, _: AgentSessionId) -> Result<SharePermissionV2> {+ Ok(SharePermissionV2 {+ id: self.id.to_string(),+ owner: OWNER.into(),+ link_share: None,+ link_share_access_level: None,+ team_share_access_level: None,+ channel_share_permissions: None,+ })+ }++ async fn team_share_facts(&self, _: AgentSessionId) -> Result<TeamShareFacts> {+ Ok(TeamShareFacts {+ entity: EntityType::AgentSession.with_entity_string(self.id.to_string()),+ owner: user(OWNER),+ owner_team_id: Some(macro_uuid::generate_uuid_v7()),+ current: None,+ revision: 0,+ })+ }++ async fn update_permissions(+ &self,+ id: AgentSessionId,+ request: UpdateSharePermissionRequestV2,+ command: Option<AuthorizedTeamShareCommand>,+ ) -> Result<SharePermissionV2> {+ self.writes.lock().unwrap().push((request, command));+ self.permissions(id).await+ }+}++fn user(value: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(value.to_string()).unwrap()+}++fn entity(id: AgentSessionId, entity_type: EntityType) -> Entity {+ Entity {+ entity_type,+ entity_id: id.to_string(),+ }+}++fn owner_access(id: AgentSessionId, owner: &str) -> EntityAccessReceipt<OwnerAccessLevel> {+ EntityAccessReceipt::try_new_authenticated_user(+ user(owner),+ entity(id, EntityType::AgentSession),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ },+ )+ .unwrap()+}++fn request() -> UpdateSharePermissionRequestV2 {+ UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ team_share_access_level: None,+ channel_share_permissions: None,+ }+}++#[tokio::test]+async fn rejects_owner_grants_before_writing() {+ let repo = Repo::new();+ let service = SessionSharingService::new(repo.clone());+ for change in [+ UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Public)),+ link_share_access_level: Some(Some(AccessLevel::Owner)),+ ..request()+ },+ UpdateSharePermissionRequestV2 {+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {+ channel_id: macro_uuid::generate_uuid_v7().to_string(),+ operation: UpdateOperation::Replace,+ access_level: Some(AccessLevel::Owner),+ }]),+ ..request()+ },+ ] {+ assert!(matches!(+ service+ .update_permissions(&owner_access(repo.id, OWNER), change)+ .await,+ Err(AgentSessionError::InvalidSharing(_))+ ));+ }+ assert!(repo.writes.lock().unwrap().is_empty());+}++#[tokio::test]+async fn validates_channel_identity_and_required_access_level() {+ let repo = Repo::new();+ let service = SessionSharingService::new(repo.clone());+ for (channel_id, access_level) in [+ ("invalid".into(), Some(AccessLevel::View)),+ (macro_uuid::generate_uuid_v7().to_string(), None),+ ] {+ let change = UpdateSharePermissionRequestV2 {+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {+ channel_id,+ operation: UpdateOperation::Add,+ access_level,+ }]),+ ..request()+ };+ assert!(matches!(+ service+ .update_permissions(&owner_access(repo.id, OWNER), change)+ .await,+ Err(AgentSessionError::InvalidSharing(_))+ ));+ }+ assert!(repo.writes.lock().unwrap().is_empty());+}++#[tokio::test]+async fn rejects_a_receipt_for_another_entity() {+ let repo = Repo::new();+ let service = SessionSharingService::new(repo.clone());+ let access = EntityAccessReceipt::dangerously_assert_internal_user(+ &repo.id.to_string(),+ EntityType::Document,+ );+ assert!(matches!(+ service.update_permissions(&access, request()).await,+ Err(AgentSessionError::Forbidden)+ ));+ assert!(repo.writes.lock().unwrap().is_empty());+}++#[tokio::test]+async fn team_sharing_requires_actual_owner_and_preserves_omission() {+ let repo = Repo::new();+ let service = SessionSharingService::new(repo.clone());+ let change = UpdateSharePermissionRequestV2 {+ team_share_access_level: Some(Some(AccessLevel::Edit)),+ ..request()+ };+ assert!(matches!(+ service+ .update_permissions(+ &owner_access(repo.id, "macro|[email protected]"),+ change.clone()+ )+ .await,+ Err(AgentSessionError::Forbidden)+ ));+ assert!(repo.writes.lock().unwrap().is_empty());+ service+ .update_permissions(&owner_access(repo.id, OWNER), change)+ .await+ .unwrap();+ service+ .update_permissions(&owner_access(repo.id, OWNER), request())+ .await+ .unwrap();+ let writes = repo.writes.lock().unwrap();+ assert_eq!(+ writes[0].1.as_ref().unwrap().target().unwrap().level,+ TeamShareLevel::Edit+ );+ assert!(writes[1].1.is_none());+}++#[tokio::test]+async fn forwards_explicit_link_and_channel_downgrades() {+ let repo = Repo::new();+ let service = SessionSharingService::new(repo.clone());+ let change = UpdateSharePermissionRequestV2 {+ link_share: Some(None),+ link_share_access_level: Some(None),+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {+ channel_id: macro_uuid::generate_uuid_v7().to_string(),+ operation: UpdateOperation::Replace,+ access_level: Some(AccessLevel::View),+ }]),+ ..request()+ };+ service+ .update_permissions(&owner_access(repo.id, OWNER), change.clone())+ .await+ .unwrap();+ assert_eq!(repo.writes.lock().unwrap()[0].0, change);+}++#[tokio::test]+async fn effective_owner_access_does_not_substitute_for_the_session_owner() {+ let repo = Repo::new();+ let service = SessionSharingService::new(repo.clone());+ let public = UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Public)),+ ..request()+ };+ for access in [+ owner_access(repo.id, "macro|[email protected]"),+ EntityAccessReceipt::dangerously_assert_internal_user(+ &repo.id.to_string(),+ EntityType::AgentSession,+ ),+ ] {+ assert!(matches!(+ service.update_permissions(&access, public.clone()).await,+ Err(AgentSessionError::Forbidden)+ ));+ }+ assert!(repo.writes.lock().unwrap().is_empty());+}diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 1d8daf86b0..576c49b708 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -6,9 +6,9 @@//! it - sending, and editing or removing what is queued - needs `Edit`, which//! the mention's channel holds, so whoever can prompt the bot through the//! thread can prompt it here too; renaming, resizing, or deleting the session-//! needs `Owner`. Permission comes from the session's own `entity_access`-//! rows - the owner with owner access, the mention's channel as editor - never-//! from any channel the session was once rendered in. Handlers only map+//! needs `Owner`. Permission comes from the session's grants, sharing settings,+//! or originating document. Sharing changes also require actual session ownership.+//! Handlers only map//! transport DTOs to domain types and call the [`AgentSessionService`]; they//! make no authorization or business decisions of their own.//!@@ -60,6 +60,9 @@ use bots::domain::models::BotId;#[cfg(test)]mod test;+/// Link, channel, and team sharing routes.+pub mod sharing;+/// Shared state for the agent session router: the agent session service plus/// the authorization state the request extractors authenticate against.pub struct AgentSessionRouterState<T, Access, Auth> {@@ -295,6 +298,25 @@ impl IntoResponse for AgentSessionApiError {Self::Domain(AgentSessionError::Forbidden) => {(StatusCode::FORBIDDEN, "forbidden").into_response()}+ Self::Domain(AgentSessionError::InvalidSharing(message)) => {+ (StatusCode::BAD_REQUEST, message).into_response()+ }+ Self::Domain(AgentSessionError::SharingChanged) => (+ StatusCode::CONFLICT,+ "sharing changed; reload and try again",+ )+ .into_response(),+ Self::Domain(AgentSessionError::TeamSharing(error)) => {+ use models_permissions::share_permission::team_share::TeamSharePolicyError;+ let status = match error {+ TeamSharePolicyError::MissingActor | TeamSharePolicyError::NotOwner => {+ StatusCode::FORBIDDEN+ }+ TeamSharePolicyError::InvalidRevision => StatusCode::CONFLICT,+ _ => StatusCode::BAD_REQUEST,+ };+ (status, error.to_string()).into_response()+ }// Already dispatched, removed, or never queued: the caller's// entry is not waiting anymore, and there is no un-sending it.Self::Domain(error @ AgentSessionError::QueuedControlNotFound) => {diff --git a/crates/agent_session/src/inbound/axum_router/sharing.rs b/crates/agent_session/src/inbound/axum_router/sharing.rsnew file mode 100644index 0000000000..c4be499090--- /dev/null+++ b/crates/agent_session/src/inbound/axum_router/sharing.rs@@ -0,0 +1,87 @@+//! Thin transport adapters for agent-session sharing use cases.++use super::{AgentSessionApiError, AgentSessionRouterState};+use crate::domain::sharing::SessionSharing;+use axum::{Json, Router, extract::State, routing::get};+use entity_access::{+ domain::{+ models::{OwnerAccessLevel, ViewAccessLevel},+ ports::EntityAccessService,+ },+ inbound::axum_extractors::AgentSessionAccessLevelExtractor,+};+use macro_authorization::MacroAuthorizationService;+use models_permissions::share_permission::{SharePermissionV2, UpdateSharePermissionRequestV2};++/// Sharing routes, mounted below `/agent-sessions`.+pub fn agent_session_sharing_router<T, Access, Auth, S>(+ state: AgentSessionRouterState<T, Access, Auth>,+) -> Router<S>+where+ T: SessionSharing,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+ S: Clone + Send + Sync + 'static,+{+ Router::new()+ .route(+ "/{session_id}/permissions",+ get(get_agent_session_permissions::<T, Access, Auth>)+ .patch(update_agent_session_permissions::<T, Access, Auth>),+ )+ .with_state(state)+}++#[utoipa::path(+ get,+ path = "/agent-sessions/{session_id}/permissions",+ tag = "agent-sessions",+ operation_id = "get_agent_session_permissions",+ params(("session_id" = macro_uuid::Uuid, Path, description = "ID of the agent session")),+ responses((status = 200, body = SharePermissionV2), (status = 403, body = String), (status = 500, body = String))+)]+/// Read sharing settings for a session the caller can view.+#[tracing::instrument(skip_all, err(Debug))]+pub async fn get_agent_session_permissions<+ T: SessionSharing,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,+) -> Result<Json<SharePermissionV2>, AgentSessionApiError> {+ Ok(Json(+ state+ .service+ .permissions(&access.entity_access_receipt)+ .await?,+ ))+}++#[utoipa::path(+ patch,+ path = "/agent-sessions/{session_id}/permissions",+ tag = "agent-sessions",+ operation_id = "update_agent_session_permissions",+ params(("session_id" = macro_uuid::Uuid, Path, description = "ID of the agent session")),+ request_body = UpdateSharePermissionRequestV2,+ responses((status = 200, body = SharePermissionV2), (status = 400, body = String), (status = 403, body = String), (status = 409, body = String), (status = 500, body = String))+)]+/// Update link, channel, or team sharing after owner authorization.+#[tracing::instrument(skip_all, err(Debug))]+pub async fn update_agent_session_permissions<+ T: SessionSharing,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ access: AgentSessionAccessLevelExtractor<OwnerAccessLevel, Access, Auth>,+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,+ Json(request): Json<UpdateSharePermissionRequestV2>,+) -> Result<Json<SharePermissionV2>, AgentSessionApiError> {+ Ok(Json(+ state+ .service+ .update_permissions(&access.entity_access_receipt, request)+ .await?,+ ))+}diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rsindex 7bec2c4fe6..7178f6b5ed 100644--- a/crates/agent_session/src/inbound/axum_router/test/read.rs+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs@@ -50,12 +50,14 @@ async fn view_router() -> Router {))}#[tokio::test]-async fn unauthorized_view_cannot_read_saved_session() {+async fn invalid_credentials_cannot_read_saved_session() {let response = view_router().await.oneshot(Request::builder().uri(format!("/{}", AgentSessionId::TEST_A))+ .header(BOT_TOKEN_HEADER, "invalid-token")+ .header(BOT_SCOPE_HEADER, "user").body(Body::empty()).unwrap(),)diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex b5a8c79f74..c2bc80dc8a 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -10,6 +10,7 @@ use sqlx::types::Json;mod test;mod pull_request;+mod sharing;use crate::domain::error::{AgentSessionError, Result};use crate::domain::model::{@@ -936,17 +937,28 @@ impl AgentSessionRepo for PgAgentSessionRepo {// A session old enough to have owned a dedicated channel leaves it// behind: it holds the history that channel renders, and is not this// operation's to destroy.- sqlx::query!(+ let permission = sqlx::query!(r#"DELETE FROM agent_sessionWHERE id = $1+ RETURNING share_permission_id"#,id.as_uuid(),)- .execute(&mut *transaction)+ .fetch_optional(&mut *transaction).await.context("failed to delete agent session")?;+ if let Some(permission_id) = permission.and_then(|row| row.share_permission_id) {+ sqlx::query!(+ r#"DELETE FROM "SharePermission" WHERE id = $1"#,+ permission_id+ )+ .execute(&mut *transaction)+ .await+ .context("failed to delete agent session sharing settings")?;+ }+transaction.commit().awaitdiff --git a/crates/agent_session/src/outbound/postgres/sharing.rs b/crates/agent_session/src/outbound/postgres/sharing.rsnew file mode 100644index 0000000000..2c4a51adc9--- /dev/null+++ b/crates/agent_session/src/outbound/postgres/sharing.rs@@ -0,0 +1,181 @@+//! Session sharing stored alongside canonical entity-access grants.++use super::PgAgentSessionRepo;+use crate::domain::{+ error::{AgentSessionError, Result},+ model::AgentSessionId,+ sharing::SessionSharingRepo,+};+use anyhow::Context;+use entity_access_db_utils::update_entity_access_channel_share_permissions;+use model_entity::EntityType;+use models_permissions::share_permission::{+ LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,+ access_level::AccessLevel,+ channel_share_permission::ChannelSharePermission,+ team_share::{AuthorizedTeamShareCommand, TeamShareFacts},+};+use share_permission_db_utils::team_share::{self, TeamShareError};++#[cfg(test)]+mod test;++fn team_error(error: rootcause::Report<TeamShareError>) -> AgentSessionError {+ match error.current_context() {+ TeamShareError::ChangedFacts | TeamShareError::UntrackedGrant => {+ AgentSessionError::SharingChanged+ }+ _ => AgentSessionError::Unknown(anyhow::anyhow!("{error:?}")),+ }+}++impl SessionSharingRepo for PgAgentSessionRepo {+ #[tracing::instrument(skip(self), err)]+ async fn permissions(&self, id: AgentSessionId) -> Result<SharePermissionV2> {+ let row = sqlx::query!(+ r#"SELECT s.owner_id, s.share_permission_id,+ sp."linkShare" AS "link_share: LinkShare",+ sp."linkShareAccessLevel" AS "link_level: AccessLevel",+ sp.team_share_access_level AS "team_level: AccessLevel"+ FROM agent_session s+ LEFT JOIN "SharePermission" sp ON sp.id = s.share_permission_id+ WHERE s.id = $1"#,+ id.as_uuid(),+ )+ .fetch_one(&self.pool)+ .await+ .context("read agent session sharing settings")?;+ let channels = sqlx::query!(+ r#"SELECT source_id AS channel_id, access_level AS "access_level: AccessLevel"+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'agent_session' AND source_type = 'channel'+ AND granted_from_project_id IS NULL+ ORDER BY source_id"#,+ id.as_uuid(),+ )+ .fetch_all(&self.pool)+ .await+ .context("read agent session channel access")?;+ Ok(SharePermissionV2 {+ id: row.share_permission_id.unwrap_or_else(|| id.to_string()),+ owner: row.owner_id,+ link_share: row.link_share,+ link_share_access_level: row.link_level,+ team_share_access_level: row.team_level,+ channel_share_permissions: Some(+ channels+ .into_iter()+ .map(|row| ChannelSharePermission {+ channel_id: row.channel_id,+ access_level: row.access_level,+ })+ .collect(),+ ),+ })+ }++ #[tracing::instrument(skip(self), err)]+ async fn team_share_facts(&self, id: AgentSessionId) -> Result<TeamShareFacts> {+ let mut tx = self+ .pool+ .begin()+ .await+ .context("begin session sharing facts read")?;+ let entity = EntityType::AgentSession.with_entity_string(id.to_string());+ let facts = team_share::load_facts(&mut tx, &entity)+ .await+ .map_err(team_error)?;+ tx.commit()+ .await+ .context("complete session sharing facts read")?;+ Ok(facts)+ }++ #[tracing::instrument(skip(self, request, team_share), err)]+ async fn update_permissions(+ &self,+ id: AgentSessionId,+ request: UpdateSharePermissionRequestV2,+ team_share: Option<AuthorizedTeamShareCommand>,+ ) -> Result<SharePermissionV2> {+ let mut tx = self+ .pool+ .begin()+ .await+ .context("begin session sharing update")?;+ team_share::acquire_guard(&mut tx)+ .await+ .context("lock sharing topology")?;+ let row = sqlx::query!(+ "SELECT share_permission_id FROM agent_session WHERE id = $1 FOR UPDATE",+ id.as_uuid(),+ )+ .fetch_one(tx.as_mut())+ .await+ .context("lock agent session sharing settings")?;+ let permission_id = match row.share_permission_id {+ Some(id) => id,+ None => {+ let permission_id = macro_uuid::generate_uuid_v7().to_string();+ sqlx::query!(+ r#"INSERT INTO "SharePermission" (id, "createdAt", "updatedAt") VALUES ($1, NOW(), NOW())"#,+ permission_id,+ )+ .execute(tx.as_mut())+ .await+ .context("create session sharing settings")?;+ sqlx::query!(+ "UPDATE agent_session SET share_permission_id = $2 WHERE id = $1",+ id.as_uuid(),+ permission_id,+ )+ .execute(tx.as_mut())+ .await+ .context("attach session sharing settings")?;+ permission_id+ }+ };+ let update_scope = request.link_share.is_some();+ let scope = request.link_share.flatten().map(|scope| scope.to_string());+ let update_level = request.link_share_access_level.is_some();+ let level = request.link_share_access_level.flatten();+ sqlx::query!(+ r#"UPDATE "SharePermission" SET+ "linkShare" = CASE WHEN $2 THEN $3 ELSE "linkShare" END,+ "linkShareAccessLevel" = CASE+ WHEN $2 AND $3 IS NULL THEN NULL+ WHEN $2 THEN COALESCE($5::"AccessLevel", 'view')+ WHEN $4 AND "linkShare" IS NOT NULL THEN COALESCE($5::"AccessLevel", 'view')+ WHEN $4 THEN NULL+ ELSE "linkShareAccessLevel"+ END,+ "updatedAt" = NOW()+ WHERE id = $1"#,+ permission_id,+ update_scope,+ scope,+ update_level,+ level as Option<AccessLevel>,+ )+ .execute(tx.as_mut())+ .await+ .context("update session link sharing")?;+ if let Some(channels) = request.channel_share_permissions {+ update_entity_access_channel_share_permissions(+ &mut tx,+ &id.as_uuid(),+ EntityType::AgentSession,+ &channels,+ )+ .await+ .context("update session channel access")?;+ }+ if let Some(command) = team_share {+ team_share::apply(&mut tx, &command)+ .await+ .map_err(team_error)?;+ }+ tx.commit().await.context("commit session sharing update")?;+ self.permissions(id).await+ }+}diff --git a/crates/agent_session/src/outbound/postgres/sharing/test.rs b/crates/agent_session/src/outbound/postgres/sharing/test.rsnew file mode 100644index 0000000000..427ba754bd--- /dev/null+++ b/crates/agent_session/src/outbound/postgres/sharing/test.rs@@ -0,0 +1,159 @@+use super::*;+use crate::domain::ports::AgentSessionRepo;+use crate::outbound::postgres::test::{+ create_session, create_test_bot, insert_originating_thread_fixture, new_session,+};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_permissions::share_permission::channel_share_permission::{+ UpdateChannelSharePermission, UpdateOperation,+};+use sqlx::PgPool;++fn request() -> UpdateSharePermissionRequestV2 {+ UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ team_share_access_level: None,+ channel_share_permissions: None,+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn existing_channel_grants_are_visible_before_settings_are_created(pool: PgPool) {+ let repo = PgAgentSessionRepo::new(pool.clone());+ let bot = create_test_bot(&pool).await;+ let (channel, thread, message) = insert_originating_thread_fixture(&pool).await;+ let session = create_session(&repo, new_session(bot, Some(thread), Some(message))).await;+ let settings = repo.permissions(session.id).await.unwrap();+ assert_eq!(settings.link_share, None);+ assert_eq!(+ settings.channel_share_permissions,+ Some(vec![ChannelSharePermission {+ channel_id: channel.to_string(),+ access_level: AccessLevel::Edit+ }])+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn settings_and_channel_grants_round_trip_without_promoting_viewers(pool: PgPool) {+ let repo = PgAgentSessionRepo::new(pool.clone());+ let bot = create_test_bot(&pool).await;+ let session = create_session(&repo, new_session(bot, None, None)).await;+ let channel = macro_uuid::generate_uuid_v7().to_string();+ let initial = repo.permissions(session.id).await.unwrap();+ assert_eq!(initial.link_share, None);+ assert_eq!(initial.channel_share_permissions, Some(vec![]));+ let shared = repo+ .update_permissions(+ session.id,+ UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Public)),+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {+ channel_id: channel.clone(),+ operation: UpdateOperation::Add,+ access_level: Some(AccessLevel::Edit),+ }]),+ ..request()+ },+ None,+ )+ .await+ .unwrap();+ assert_eq!(shared.link_share_access_level, Some(AccessLevel::View));+ let downgraded = repo+ .update_permissions(+ session.id,+ UpdateSharePermissionRequestV2 {+ link_share_access_level: Some(Some(AccessLevel::Comment)),+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {+ channel_id: channel.clone(),+ operation: UpdateOperation::Replace,+ access_level: Some(AccessLevel::View),+ }]),+ ..request()+ },+ None,+ )+ .await+ .unwrap();+ assert_eq!(downgraded.link_share, Some(LinkShare::Public));+ assert_eq!(+ downgraded.link_share_access_level,+ Some(AccessLevel::Comment)+ );+ assert_eq!(+ downgraded.channel_share_permissions.unwrap()[0].access_level,+ AccessLevel::View+ );+ let revoked = repo+ .update_permissions(+ session.id,+ UpdateSharePermissionRequestV2 {+ link_share: Some(None),+ link_share_access_level: Some(Some(AccessLevel::Edit)),+ channel_share_permissions: Some(vec![UpdateChannelSharePermission {+ channel_id: channel,+ operation: UpdateOperation::Remove,+ access_level: None,+ }]),+ ..request()+ },+ None,+ )+ .await+ .unwrap();+ assert_eq!(revoked.link_share, None);+ assert_eq!(revoked.link_share_access_level, None);+ assert_eq!(revoked.channel_share_permissions, Some(vec![]));+ assert_eq!(repo.permissions(session.id).await.unwrap(), revoked);+ AgentSessionRepo::delete(&repo, session.id).await.unwrap();+ assert!(+ !sqlx::query_scalar!(+ r#"SELECT EXISTS(SELECT 1 FROM "SharePermission" WHERE id = $1) AS "exists!""#,+ shared.id+ )+ .fetch_one(&pool)+ .await+ .unwrap()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn link_scopes_levels_and_resets_persist(pool: PgPool) {+ let repo = PgAgentSessionRepo::new(pool.clone());+ let bot = create_test_bot(&pool).await;+ let session = create_session(&repo, new_session(bot, None, None)).await;+ for scope in [LinkShare::Public, LinkShare::Team] {+ for level in [AccessLevel::View, AccessLevel::Edit] {+ let saved = repo+ .update_permissions(+ session.id,+ UpdateSharePermissionRequestV2 {+ link_share: Some(Some(scope)),+ link_share_access_level: Some(Some(level)),+ ..request()+ },+ None,+ )+ .await+ .unwrap();+ assert_eq!(saved.link_share, Some(scope));+ assert_eq!(saved.link_share_access_level, Some(level));+ assert_eq!(repo.permissions(session.id).await.unwrap(), saved);+ }+ }+ let reset = repo+ .update_permissions(+ session.id,+ UpdateSharePermissionRequestV2 {+ link_share_access_level: Some(None),+ ..request()+ },+ None,+ )+ .await+ .unwrap();+ assert_eq!(reset.link_share, Some(LinkShare::Team));+ assert_eq!(reset.link_share_access_level, Some(AccessLevel::View));+}diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 8d715a4658..f3b50fb571 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -52,7 +52,7 @@ async fn insert_user(pool: &PgPool, user_id: &str) {.expect("insert User");}-async fn create_test_bot(pool: &PgPool) -> BotId {+pub(super) async fn create_test_bot(pool: &PgPool) -> BotId {// Every session fixture is owned by the same user, and// `agent_session.owner_id` references `"User"(id)` - so seed the// row here, where every session-creating test already passes through.@@ -78,7 +78,7 @@ async fn create_test_bot(pool: &PgPool) -> BotId {bot.id}-fn new_session(+pub(super) fn new_session(bot_id: BotId,thread_id: Option<Uuid>,originating_message_id: Option<Uuid>,@@ -101,7 +101,7 @@ fn new_session(}}-async fn create_session(+pub(super) async fn create_session(repo: &PgAgentSessionRepo,params: CreateAgentSessionParams,) -> AgentSession {@@ -129,7 +129,7 @@ async fn append_system_event(.expect("append system event log entry");}-async fn insert_originating_thread_fixture(pool: &PgPool) -> (Uuid, Uuid, Uuid) {+pub(super) async fn insert_originating_thread_fixture(pool: &PgPool) -> (Uuid, Uuid, Uuid) {let channel_id = macro_uuid::generate_uuid_v7();let thread_id = macro_uuid::generate_uuid_v7();let originating_message_id = macro_uuid::generate_uuid_v7();diff --git a/crates/channels/src/domain/reference_sharing.rs b/crates/channels/src/domain/reference_sharing.rsindex fac0126377..7c9d47503d 100644--- a/crates/channels/src/domain/reference_sharing.rs+++ b/crates/channels/src/domain/reference_sharing.rs@@ -3,15 +3,15 @@use super::models::ReferencedShareItemType;use entity_access::domain::models::AccessLevel;-/// Agent control may only be shared by its owner; other references retain-/// the established view-sharing behavior. Mentioning never amplifies a viewer.+/// Only owners may share session references, and automatic sharing grants view+/// access. Sending a reference never grants control of an agent session.pub(crate) fn grant_level(item_type: ReferencedShareItemType,access: Option<AccessLevel>,) -> Option<AccessLevel> {match (item_type, access) {(ReferencedShareItemType::AgentSession, Some(AccessLevel::Owner)) => {- Some(AccessLevel::Edit)+ Some(AccessLevel::View)}(ReferencedShareItemType::AgentSession, _) | (_, None) => None,(_, Some(_)) => Some(AccessLevel::View),diff --git a/crates/channels/src/domain/reference_sharing/test.rs b/crates/channels/src/domain/reference_sharing/test.rsindex b253654a66..fdc2887c42 100644--- a/crates/channels/src/domain/reference_sharing/test.rs+++ b/crates/channels/src/domain/reference_sharing/test.rs@@ -1,13 +1,13 @@use super::*;#[test]-fn only_owner_can_share_session_control_with_channel() {+fn only_owner_can_share_session_view_with_channel() {for (access, expected) in [(None, None),(Some(AccessLevel::View), None),(Some(AccessLevel::Comment), None),(Some(AccessLevel::Edit), None),- (Some(AccessLevel::Owner), Some(AccessLevel::Edit)),+ (Some(AccessLevel::Owner), Some(AccessLevel::View)),] {assert_eq!(grant_level(ReferencedShareItemType::AgentSession, access),diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rsindex 4ad3fcca06..cf6479be9d 100644--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs@@ -17,6 +17,9 @@ use sqlx::PgPool;use std::sync::Arc;use uuid::Uuid;+#[cfg(test)]+mod test;+/// Postgres-backed share-permission adapter for channel message references.#[derive(Clone)]pub struct PgChannelReferenceSharePermissions<E> {@@ -79,18 +82,16 @@ async fn ensure_referenced_item_visible_to_channel(.context("failed to insert thread share permissions")?;}- // Sessions use direct entity-access rows, not legacy SharePermission rows.+ // Session channel grants are canonical entity-access rows. A reference must+ // preserve explicit sharing and the originating channel's control grant.if item.entity_type() == ReferencedShareItemType::AgentSession {let mut transaction = db.begin().await?;- entity_access_db_utils::update_entity_access_channel_share_permissions(+ entity_access_db_utils::channel_share::insert_if_absent(&mut transaction,&entity_id,entity_access_db_utils::EntityType::AgentSession,- &[UpdateChannelSharePermission {- channel_id: channel_id.to_string(),- operation: UpdateOperation::Add,- access_level: Some(level),- }],+ &channel_id,+ level,).await?;transaction.commit().await?;diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rsnew file mode 100644index 0000000000..91c12461f8--- /dev/null+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs@@ -0,0 +1,51 @@+use super::*;+use entity_access_db_utils::{EntityAccessSourceType, insert_entity_access_row};+use macro_db_migrator::MACRO_DB_MIGRATIONS;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn session_references_grant_view_and_preserve_existing_channel_access(pool: PgPool) {+ let channel_id = Uuid::now_v7();+ for existing in [+ None,+ Some(AccessLevel::View),+ Some(AccessLevel::Comment),+ Some(AccessLevel::Edit),+ ] {+ let session_id = Uuid::now_v7();+ let item = ReferencedShareItem::new(+ session_id.to_string(),+ ReferencedShareItemType::AgentSession,+ );+ if let Some(level) = existing {+ let mut tx = pool.begin().await.unwrap();+ insert_entity_access_row(+ &mut tx,+ &session_id,+ EntityType::AgentSession,+ &channel_id.to_string(),+ EntityAccessSourceType::Channel,+ level,+ )+ .await+ .unwrap();+ tx.commit().await.unwrap();+ }+ let automatic_level = grant_level(item.entity_type(), Some(AccessLevel::Owner)).unwrap();+ for _ in 0..2 {+ ensure_referenced_item_visible_to_channel(&pool, channel_id, &item, automatic_level)+ .await+ .unwrap();+ }+ let levels = sqlx::query_scalar!(+ r#"SELECT access_level AS "access_level: AccessLevel" FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'agent_session' AND source_id = $2+ AND source_type = 'channel' AND granted_from_project_id IS NULL"#,+ session_id,+ channel_id.to_string(),+ )+ .fetch_all(&pool)+ .await+ .unwrap();+ assert_eq!(levels, vec![existing.unwrap_or(AccessLevel::View)]);+ }+}diff --git a/crates/entity_access/fixtures/agent_session_sharing.sql b/crates/entity_access/fixtures/agent_session_sharing.sqlnew file mode 100644index 0000000000..98dc45646c--- /dev/null+++ b/crates/entity_access/fixtures/agent_session_sharing.sql@@ -0,0 +1,16 @@+INSERT INTO "SharePermission" (id, "linkShare", "linkShareAccessLevel") VALUES+ ('session-private', NULL, NULL),+ ('session-public', 'PUBLIC', 'view'),+ ('session-public-no-level', 'PUBLIC', NULL),+ ('session-team', 'TEAM', 'comment');++INSERT INTO agent_session (id, owner_id, bot_id, model, harness, workspace, share_permission_id) VALUES+ ('60000000-0000-0000-0000-000000000001', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', NULL),+ ('60000000-0000-0000-0000-000000000002', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', 'session-private'),+ ('60000000-0000-0000-0000-000000000003', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', 'session-public'),+ ('60000000-0000-0000-0000-000000000004', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', 'session-public-no-level'),+ ('60000000-0000-0000-0000-000000000005', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', 'session-team');++INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level) VALUES+ ('60000000-0000-0000-0000-000000000003', 'agent_session', 'macro|[email protected]', 'user', 'owner'),+ ('60000000-0000-0000-0000-000000000003', 'agent_session', 'channel', 'channel', 'edit');diff --git a/crates/entity_access/src/inbound/axum_extractors/agent_session.rs b/crates/entity_access/src/inbound/axum_extractors/agent_session.rsindex f3bab7e8d8..75a0eb3c22 100644--- a/crates/entity_access/src/inbound/axum_extractors/agent_session.rs+++ b/crates/entity_access/src/inbound/axum_extractors/agent_session.rs@@ -1,10 +1,8 @@//! Agent session access extractor.//!-//! A session's permissions are entirely its own `entity_access` rows: the-//! owner with owner access, and - when the session was opened by a mention - the-//! channel that mention was posted in as editor. The dedicated channel a-//! session owns is deliberately not consulted; who participates in it says-//! nothing about who may act on the session.+//! Sessions use their canonical grants, link permissions, and inherited document+//! access. Public links allow anonymous viewing; control requests still require+//! authentication. Session channel participation does not itself grant access.use std::marker::PhantomData;use std::sync::Arc;@@ -119,13 +117,9 @@ where});}- let Some(macro_user_id) = macro_user_id else {- return Err(ExtractorError::Unauthorized);- };-let permission = service.get_entity_permission(- Some(¯o_user_id),+ macro_user_id.as_deref(),&session_id,EntityType::AgentSession,None,@@ -133,6 +127,14 @@ where.await.map_err(ExtractorError::from)?;+ let permission = if macro_user_id.is_none() {+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ }+ } else {+ permission+ };+if !permission.satisfies::<T>() {return Err(ExtractorError::Unauthorized);}@@ -143,7 +145,9 @@ whereentity_id: session_id,entity_type: EntityType::AgentSession,},- auth: EntityAccessAuth::Authenticated(macro_user_id),+ auth: macro_user_id+ .map(EntityAccessAuth::Authenticated)+ .unwrap_or(EntityAccessAuth::Unauthenticated),entity_permission: permission,_marker: PhantomData,},diff --git a/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rs b/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rsindex bd2202cb61..4c339a9ccc 100644--- a/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/agent_session/test.rs@@ -1,5 +1,5 @@use super::*;-use crate::domain::models::EditAccessLevel;+use crate::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};use crate::inbound::axum_extractors::test_support::{FakeAuthorizationService, FakeEntityAccessService, TestState, USER_ID,};@@ -11,6 +11,67 @@ use axum::{};use tower::ServiceExt;+async fn anonymous_request<T: RequiredPermission>(state: TestState) -> StatusCode {+ Router::new()+ .route(+ "/sessions/{session_id}",+ post(+ |access: AgentSessionAccessLevelExtractor<+ T,+ FakeEntityAccessService,+ FakeAuthorizationService,+ >| async move {+ assert!(matches!(+ access.entity_access_receipt.auth(),+ EntityAccessAuth::Unauthenticated+ ));+ assert_eq!(+ access.entity_access_receipt.entity_permission(),+ &EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ }+ );+ StatusCode::NO_CONTENT+ },+ ),+ )+ .with_state(state)+ .oneshot(+ Request::post("/sessions/shared-session")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap()+ .status()+}++#[tokio::test]+async fn public_sessions_allow_anonymous_views_only() {+ let public = TestState::new(Some(AccessLevel::View));+ assert_eq!(+ anonymous_request::<ViewAccessLevel>(public.clone()).await,+ StatusCode::NO_CONTENT+ );+ assert_eq!(public.entity_access.calls()[0].user_id, None);+ assert_eq!(+ anonymous_request::<ViewAccessLevel>(TestState::new(Some(AccessLevel::Edit))).await,+ StatusCode::NO_CONTENT+ );+ assert_eq!(+ anonymous_request::<ViewAccessLevel>(TestState::new(None)).await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ anonymous_request::<EditAccessLevel>(TestState::new(Some(AccessLevel::Edit))).await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ anonymous_request::<OwnerAccessLevel>(TestState::new(Some(AccessLevel::Owner))).await,+ StatusCode::UNAUTHORIZED+ );+}+#[tokio::test]async fn permission_approval_access_accepts_editors_and_owners_but_not_viewers() {for (level, expected) in [diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rsindex 948669e0a1..45f9f9af61 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access.rs@@ -44,19 +44,14 @@ pub async fn accessible_session_ids(/// `entity_access`; it arrives here through `source_ids`, so adding someone/// to that channel gives them the session on their next request.///-/// Unlike documents and calls there is no public-sharing arm: a session-/// carries no `SharePermission`, so a caller with no source ids has no way-/// to reach one.+/// Public links also work without source IDs. Team links require membership in+/// the owner's current team, while explicit team shares use canonical grants.#[tracing::instrument(err, skip(pool, source_ids))]pub async fn get_agent_session_access(pool: &PgPool,agent_session_id: &uuid::Uuid,source_ids: &SourceIds,) -> Result<Option<AccessLevel>, sqlx::Error> {- if source_ids.0.is_empty() {- return Ok(None);- }-let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(r#"SELECT access_level::text@@ -64,6 +59,25 @@ pub async fn get_agent_session_access(WHERE entity_id = $1AND entity_type = 'agent_session'AND source_id = ANY($2)++ UNION ALL++ SELECT sp."linkShareAccessLevel"::text+ FROM agent_session s+ JOIN "SharePermission" sp ON sp.id = s.share_permission_id+ WHERE s.id = $1+ AND sp."linkShareAccessLevel" IS NOT NULL+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (+ sp."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1 FROM team_user owner_team+ WHERE owner_team.user_id = s.owner_id+ AND owner_team.team_id::text = ANY($2)+ )+ )+ )"#,agent_session_id,&source_ids.0,@@ -86,5 +100,40 @@ pub async fn explain_agent_session_access(agent_session_id: &uuid::Uuid,source_ids: &SourceIds,) -> Result<Vec<AccessGrant>, sqlx::Error> {- list_entity_access_grants(pool, agent_session_id, EntityType::AgentSession, source_ids).await+ let mut grants =+ list_entity_access_grants(pool, agent_session_id, EntityType::AgentSession, source_ids)+ .await?;+ let links = sqlx::query!(+ r#"+ SELECT sp."linkShareAccessLevel" AS "access_level!: AccessLevel",+ sp."linkShare" = 'PUBLIC' AS "is_public!",+ owner_team.team_id AS "team_id?"+ FROM agent_session s+ JOIN "SharePermission" sp ON sp.id = s.share_permission_id+ LEFT JOIN team_user owner_team ON owner_team.user_id = s.owner_id+ WHERE s.id = $1+ AND sp."linkShareAccessLevel" IS NOT NULL+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (sp."linkShare" = 'TEAM' AND owner_team.team_id::text = ANY($2))+ )+ "#,+ agent_session_id,+ &source_ids.0,+ )+ .fetch_all(pool)+ .await?;+ grants.extend(links.into_iter().filter_map(|row| {+ if row.is_public {+ Some(AccessGrant::PublicLink {+ access_level: row.access_level,+ })+ } else {+ row.team_id.map(|owner_team_id| AccessGrant::TeamLink {+ access_level: row.access_level,+ owner_team_id,+ })+ }+ }));+ Ok(grants)}diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rsindex 91ee0365a4..00de0baa4e 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/agent_session_access/test.rs@@ -1,6 +1,136 @@use super::*;use macro_db_migrator::MACRO_DB_MIGRATIONS;+const OWNER_TEAM: &str = "00000000-0000-0000-0000-0000000ea001";+const OTHER_TEAM: &str = "00000000-0000-0000-0000-0000000ea002";+const PUBLIC_SESSION: uuid::Uuid = uuid::Uuid::from_u128(0x60000000_0000_0000_0000_000000000003);+const TEAM_SESSION: uuid::Uuid = uuid::Uuid::from_u128(0x60000000_0000_0000_0000_000000000005);++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../../fixtures",+ scripts("user_team", "agent_session_sharing")+ )+)]+async fn session_links_require_public_consent_or_owner_team_membership(pool: PgPool) {+ for (session_id, anonymous, same_team, other_team) in [+ (0x60000000_0000_0000_0000_000000000001, None, None, None),+ (0x60000000_0000_0000_0000_000000000002, None, None, None),+ (+ PUBLIC_SESSION.as_u128(),+ Some(AccessLevel::View),+ Some(AccessLevel::View),+ Some(AccessLevel::View),+ ),+ (0x60000000_0000_0000_0000_000000000004, None, None, None),+ (+ TEAM_SESSION.as_u128(),+ None,+ Some(AccessLevel::Comment),+ None,+ ),+ ] {+ for (sources, expected) in [+ (vec![], anonymous),+ (vec![OWNER_TEAM.to_string()], same_team),+ (vec![OTHER_TEAM.to_string()], other_team),+ ] {+ assert_eq!(+ get_agent_session_access(+ &pool,+ &uuid::Uuid::from_u128(session_id),+ &SourceIds(sources)+ )+ .await+ .unwrap(),+ expected,+ "session {session_id}",+ );+ }+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../../fixtures",+ scripts("user_team", "agent_session_sharing")+ )+)]+async fn session_links_preserve_stronger_grants_and_revoke_immediately(pool: PgPool) {+ for (sources, expected) in [+ (vec!["macro|[email protected]".to_string()], AccessLevel::Owner),+ (vec!["channel".to_string()], AccessLevel::Edit),+ ] {+ assert_eq!(+ get_agent_session_access(&pool, &PUBLIC_SESSION, &SourceIds(sources))+ .await+ .unwrap(),+ Some(expected),+ );+ }++ sqlx::query!(+ r#"UPDATE "SharePermission" SET "linkShare" = NULL, "linkShareAccessLevel" = NULL+ WHERE id = 'session-public'"#+ )+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ get_agent_session_access(&pool, &PUBLIC_SESSION, &SourceIds(vec![]))+ .await+ .unwrap(),+ None,+ );++ sqlx::query!("DELETE FROM team_user WHERE user_id = 'macro|[email protected]'")+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(+ get_agent_session_access(+ &pool,+ &TEAM_SESSION,+ &SourceIds(vec![OWNER_TEAM.to_string()])+ )+ .await+ .unwrap(),+ None,+ );+}++#[cfg(feature = "explain_binary")]+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../../fixtures",+ scripts("user_team", "agent_session_sharing")+ )+)]+async fn explanation_includes_public_and_team_links(pool: PgPool) {+ let grants = explain_agent_session_access(&pool, &PUBLIC_SESSION, &SourceIds(vec![]))+ .await+ .unwrap();+ assert!(matches!(+ grants.as_slice(),+ [AccessGrant::PublicLink {+ access_level: AccessLevel::View+ }]+ ));+ let grants = explain_agent_session_access(+ &pool,+ &TEAM_SESSION,+ &SourceIds(vec![OWNER_TEAM.to_string()]),+ )+ .await+ .unwrap();+ assert!(+ matches!(grants.as_slice(), [AccessGrant::TeamLink { access_level: AccessLevel::Comment, owner_team_id }] if *owner_team_id == uuid::Uuid::parse_str(OWNER_TEAM).unwrap())+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn session_allowlist_matches_grants_and_respects_requested_ids(pool: PgPool) {let session = uuid::Uuid::now_v7();diff --git a/crates/entity_access_db_utils/src/channel_share.rs b/crates/entity_access_db_utils/src/channel_share.rsnew file mode 100644index 0000000000..29ca01ba10--- /dev/null+++ b/crates/entity_access_db_utils/src/channel_share.rs@@ -0,0 +1,32 @@+//! Direct channel grants that preserve an existing sharing choice.++use crate::{AccessLevel, EntityType};+use macro_uuid::Uuid;+use sqlx::{Postgres, Transaction};++/// Insert a direct channel grant only when one does not already exist.+///+/// Existing direct grants retain their exact level; project-inherited grants+/// remain separate. The caller owns authorization and commits the transaction.+#[tracing::instrument(skip(transaction), err)]+pub async fn insert_if_absent(+ transaction: &mut Transaction<'_, Postgres>,+ entity_id: &Uuid,+ entity_type: EntityType,+ channel_id: &Uuid,+ access_level: AccessLevel,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)+ VALUES ($1, $2, $3, 'channel', $4)+ ON CONFLICT (entity_id, entity_type, source_id, source_type)+ WHERE granted_from_project_id IS NULL DO NOTHING"#,+ entity_id,+ entity_type.as_ref(),+ channel_id.to_string(),+ access_level as _,+ )+ .execute(transaction.as_mut())+ .await?;+ Ok(())+}diff --git a/crates/entity_access_db_utils/src/lib.rs b/crates/entity_access_db_utils/src/lib.rsindex 2eeaaaa3d4..af77a78efa 100644--- a/crates/entity_access_db_utils/src/lib.rs+++ b/crates/entity_access_db_utils/src/lib.rs@@ -5,6 +5,7 @@#[cfg(test)]mod test;+pub mod channel_share;pub mod team_share;use macro_user_id::user_id::MacroUserIdStr;diff --git a/crates/macro_db_client/migrations/20260922144230_agent_session_sharing.sql b/crates/macro_db_client/migrations/20260922144230_agent_session_sharing.sqlnew file mode 100644index 0000000000..c94d286cdd--- /dev/null+++ b/crates/macro_db_client/migrations/20260922144230_agent_session_sharing.sql@@ -0,0 +1,3 @@+-- Existing sessions retain their private/channel access until the owner changes sharing.+ALTER TABLE agent_session+ ADD COLUMN share_permission_id TEXT UNIQUE REFERENCES "SharePermission"(id);diff --git a/crates/share_permission_db_utils/fixtures/team_share.sql b/crates/share_permission_db_utils/fixtures/team_share.sqlindex f5110cedb2..857b97044a 100644--- a/crates/share_permission_db_utils/fixtures/team_share.sql+++ b/crates/share_permission_db_utils/fixtures/team_share.sql@@ -15,7 +15,10 @@ INSERT INTO "Document" (id, name, owner) VALUES('20000000-0000-0000-0000-000000000008', 'Initiative description', 'macro|[email protected]');INSERT INTO "Chat" (id, name, "userId") VALUES('20000000-0000-0000-0000-000000000003', 'Chat', 'macro|[email protected]');-INSERT INTO "SharePermission" (id) VALUES ('project'), ('document'), ('chat'), ('active-call'), ('archived-call'), ('initiative');+INSERT INTO "SharePermission" (id) VALUES ('project'), ('document'), ('chat'), ('active-call'), ('archived-call'), ('initiative'), ('agent-session');+INSERT INTO agent_session (id, owner_id, bot_id, model, harness, workspace, share_permission_id) VALUES+ ('20000000-0000-0000-0000-000000000009', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', 'agent-session'),+ ('20000000-0000-0000-0000-000000000010', 'macro|[email protected]', '00000000-0000-0000-0000-00000000a9e7', 'model', 'harness', '/workspace', NULL);INSERT INTO initiative (id, name, owner_user_id, share_permission_id, description_document_id) VALUES('20000000-0000-0000-0000-000000000007', 'Initiative', 'macro|[email protected]', 'initiative', '20000000-0000-0000-0000-000000000008');INSERT INTO "ProjectPermission" ("projectId", "sharePermissionId") VALUES ('20000000-0000-0000-0000-000000000001', 'project');diff --git a/crates/share_permission_db_utils/src/team_share.rs b/crates/share_permission_db_utils/src/team_share.rsindex 9ef4fbf8b7..8740f7e7ed 100644--- a/crates/share_permission_db_utils/src/team_share.rs+++ b/crates/share_permission_db_utils/src/team_share.rs@@ -97,6 +97,7 @@ fn entity_uuid(entity: &Entity<'_>) -> TeamShareResult<Uuid> {| EntityType::Chat| EntityType::EmailThread| EntityType::Call+ | EntityType::AgentSession| EntityType::Initiative) {return Err(report!(TeamShareError::InvalidEntity));@@ -105,7 +106,7 @@ fn entity_uuid(entity: &Entity<'_>) -> TeamShareResult<Uuid> {}/// Load actual owner, current membership and canonical state under the shared guard.-/// Threads without permissions read as NULL/revision zero without creating any rows.+/// Threads and sessions without permissions read as NULL/revision zero without creating rows./// Tasks and snippets use Document, and active calls take precedence during archive.pub async fn load_facts(transaction: &mut Transaction<'_, Postgres>,@@ -146,6 +147,9 @@ async fn load_state(connection: &mut PgConnection, entity: &Entity<'_>) -> TeamSUNION ALLSELECT i.owner_user_id, i.share_permission_id FROM initiative iWHERE $2 = 'initiative' AND i.id = $3+ UNION ALL+ SELECT s.owner_id, s.share_permission_id FROM agent_session s+ WHERE $2 = 'agent_session' AND s.id = $3)SELECT e.owner AS "owner!", e.permission_id,sp.id AS "stored_permission_id?",@@ -164,7 +168,11 @@ async fn load_state(connection: &mut PgConnection, entity: &Entity<'_>) -> TeamS.ok_or_else(|| report!(TeamShareError::NotFound))?;if row.stored_permission_id.is_none()- && (row.permission_id.is_some() || entity.entity_type != EntityType::EmailThread)+ && (row.permission_id.is_some()+ || !matches!(+ entity.entity_type,+ EntityType::EmailThread | EntityType::AgentSession+ )){return Err(report!(TeamShareError::InvalidState));}diff --git a/crates/share_permission_db_utils/src/team_share/test.rs b/crates/share_permission_db_utils/src/team_share/test.rsindex eeee35ced2..7f74cd6095 100644--- a/crates/share_permission_db_utils/src/team_share/test.rs+++ b/crates/share_permission_db_utils/src/team_share/test.rs@@ -19,6 +19,10 @@ fn chat() -> Entity<'static> {EntityType::Chat.with_entity_string("20000000-0000-0000-0000-000000000003".to_string())}+fn agent_session() -> Entity<'static> {+ EntityType::AgentSession.with_entity_string("20000000-0000-0000-0000-000000000009".to_string())+}+fn active_call() -> Entity<'static> {EntityType::Call.with_entity_string("20000000-0000-0000-0000-000000000005".to_string())}@@ -150,6 +154,46 @@ async fn apply_inserts_updates_and_deletes_direct_team_entity_access_for_chat(apply_comment_view_and_clear(&mut tx, &chat()).await}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("team_share"))+)]+async fn apply_inserts_updates_and_deletes_direct_team_entity_access_for_agent_sessions(+ pool: PgPool,+) -> rootcause::Result<()> {+ let mut tx = pool.begin().await?;+ apply_comment_view_and_clear(&mut tx, &agent_session()).await+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("team_share"))+)]+async fn legacy_session_facts_stay_valid_after_permission_initialization(+ pool: PgPool,+) -> rootcause::Result<()> {+ let entity = EntityType::AgentSession+ .with_entity_string("20000000-0000-0000-0000-000000000010".to_string());+ let mut tx = pool.begin().await?;+ let facts = load_facts(&mut tx, &entity).await?;+ assert_eq!(facts.current, None);+ assert_eq!(facts.revision, 0);+ let authorized = command(&facts, Some(AccessLevel::View));++ sqlx::query!(r#"INSERT INTO "SharePermission" (id) VALUES ('initialized-session')"#)+ .execute(tx.as_mut())+ .await?;+ sqlx::query!("UPDATE agent_session SET share_permission_id = 'initialized-session' WHERE id = '20000000-0000-0000-0000-000000000010'")+ .execute(tx.as_mut())+ .await?;++ apply(&mut tx, &authorized).await?;+ let current = load_facts(&mut tx, &entity).await?;+ assert_eq!(current.revision, 1);+ assert_eq!(current.current.unwrap().level, TeamShareLevel::View);+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("team_share"))diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex 32266fbbcb..a281836f8d 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -443,16 +443,23 @@ instead of the standalone recent-sessions and tips surface.Saved sessions have **Share** and **Copy Share Link** in the desktop header;on mobile, open the session title menu and choose **Share**. The owner can-select people or channels and send the session with an optional message using-the same Share dialog and mobile drawer as documents. Sessions also support-**Share** from entity list menus and the entity sharing shortcut. People receive it through a direct or-group message. Recipients can view and control the session; there is no access-level selector. The owner sees the standard recipient-and-message form without-an extra session notice or Copy Link footer; **Copy Share Link** remains in-the header. Cancel closes the composer without sending.+select people or channels, choose their access level, and send the session with+an optional message using the same Share dialog and mobile drawer as tasks.+Sessions also support **Share** from entity list menus and the entity sharing+shortcut. **People with access** lists the owner and shared conversations;+the owner can change or remove a conversation's access. **Link sharing** offers+None / Public / Team and an access level. **Team access** shares directly with+the owner's team when one exists. On mobile these controls are in the Share,+People, and Link tabs. View and Comment allow reading; Edit also allows+controlling the session. View-only sessions keep the composer, model selector,+and queued-message controls disabled. **Copy Share Link** remains in the header. Cancel+closes the composer without sending.++Sharing a session reference in a message grants View by default and preserves+an existing grant. Use the access selector to grant Comment or Edit.Other participants can copy a link for people who already have access, but-cannot grant access. Copying a link alone never changes permissions. New,+cannot grant access or change sharing settings. Copying a link alone never changes permissions. New,unsaved session drafts do not offer sharing.Agent sessions in the `@` menu use the shared Quick Access feed, loaded when the app opens. Search matches session titles and agent names. The initial feed covers the 500 most recently updated accessible sessions; it does not load transcripts.diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.tsindex 28ab76373c..5f95ea2bb0 100644--- a/packages/sdk/generated/agent-harness/index.ts+++ b/packages/sdk/generated/agent-harness/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';+export type { AccessLevel, AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WithAgentSessionId } from './types.gen';diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex 8964b807d4..04a5a318da 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses } from './types.gen';+import type { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -240,6 +240,27 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Read sharing settings for a session the caller can view.+ */+ public getAgentSessionPermissions<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionPermissionsData, ThrowOnError>): RequestResult<GetAgentSessionPermissionsResponses, GetAgentSessionPermissionsErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetAgentSessionPermissionsResponses, GetAgentSessionPermissionsErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/permissions', ...options });+ }++ /**+ * Update link, channel, or team sharing after owner authorization.+ */+ public updateAgentSessionPermissions<ThrowOnError extends boolean = false>(options: Options<UpdateAgentSessionPermissionsData, ThrowOnError>): RequestResult<UpdateAgentSessionPermissionsResponses, UpdateAgentSessionPermissionsErrors, ThrowOnError> {+ return (options.client ?? this.client).patch<UpdateAgentSessionPermissionsResponses, UpdateAgentSessionPermissionsErrors, ThrowOnError>({+ url: '/agent-sessions/{session_id}/permissions',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** The actions waiting to dispatch in this session, oldest first.*/diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex de299b81fe..e7d9b20d3b 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -4,6 +4,11 @@ export type ClientOptions = {baseUrl: `${string}://${string}` | (string & {});};+/**+ * Ordered from least to most access top -> bottom+ */+export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';+/*** One thing a caller wants an agent to do.*/@@ -528,6 +533,20 @@ export type ChangesetDto = {*/export type ChangesetSourceDto = 'github_pull_request';+/**+ * The channel share permission+ */+export type ChannelSharePermission = {+ /**+ * The access level for the channel+ */+ access_level: AccessLevel;+ /**+ * The channel id+ */+ channel_id: string;+};+/*** One-time manual code. Deliberately does not implement Debug.*/@@ -789,6 +808,11 @@ export type GitRefDto = {sha?: string | null;};+/**+ * Defines who can access an item through its share link.+ */+export type LinkShare = 'PUBLIC' | 'TEAM';+/*** HTTP request selecting one provider to probe.*/@@ -1041,6 +1065,24 @@ export type SessionStatusDto = {kind: 'disconnected';};+export type SharePermissionV2 = {+ /**+ * The channel share permissions for the item+ */+ channelSharePermissions?: Array<ChannelSharePermission> | null;+ /**+ * The share permission id+ */+ id: string;+ linkShare?: null | LinkShare;+ linkShareAccessLevel?: null | AccessLevel;+ /**+ * The owner of the item+ */+ owner: string;+ teamShareAccessLevel?: null | AccessLevel;+};+/*** Public PKCE challenge and attempt handle; contains no verifier or provider tokens.*/@@ -1077,6 +1119,31 @@ export type StatusResponse = {ephemeral: boolean;};+export type UpdateChannelSharePermission = {+ accessLevel?: null | AccessLevel;+ /**+ * The channel id+ */+ channelId: string;+ /**+ * The type of operation to be performed on the chanel share permission+ * You can add, remove or replace and existing permission+ */+ operation: UpdateOperation;+};++export type UpdateOperation = 'add' | 'remove' | 'replace';++export type UpdateSharePermissionRequestV2 = {+ /**+ * Any channel share permissions to be created/updated/removed+ */+ channelSharePermissions?: Array<UpdateChannelSharePermission> | null;+ linkShare?: null | LinkShare;+ linkShareAccessLevel?: null | AccessLevel;+ teamShareAccessLevel?: null | AccessLevel;+};+/*** Just a session id, for the preview variants that carry nothing else.*@@ -1498,6 +1565,58 @@ export type RenameAgentSessionResponses = {export type RenameAgentSessionResponse = RenameAgentSessionResponses[keyof RenameAgentSessionResponses];+export type GetAgentSessionPermissionsData = {+ body?: never;+ path: {+ /**+ * ID of the agent session+ */+ session_id: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/permissions';+};++export type GetAgentSessionPermissionsErrors = {+ 403: string;+ 500: string;+};++export type GetAgentSessionPermissionsError = GetAgentSessionPermissionsErrors[keyof GetAgentSessionPermissionsErrors];++export type GetAgentSessionPermissionsResponses = {+ 200: SharePermissionV2;+};++export type GetAgentSessionPermissionsResponse = GetAgentSessionPermissionsResponses[keyof GetAgentSessionPermissionsResponses];++export type UpdateAgentSessionPermissionsData = {+ body: UpdateSharePermissionRequestV2;+ path: {+ /**+ * ID of the agent session+ */+ session_id: string;+ };+ query?: never;+ url: '/agent-sessions/{session_id}/permissions';+};++export type UpdateAgentSessionPermissionsErrors = {+ 400: string;+ 403: string;+ 409: string;+ 500: string;+};++export type UpdateAgentSessionPermissionsError = UpdateAgentSessionPermissionsErrors[keyof UpdateAgentSessionPermissionsErrors];++export type UpdateAgentSessionPermissionsResponses = {+ 200: SharePermissionV2;+};++export type UpdateAgentSessionPermissionsResponse = UpdateAgentSessionPermissionsResponses[keyof UpdateAgentSessionPermissionsResponses];+export type GetAgentSessionQueueData = {body?: never;path: {diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 47414b47d2..fc949860f6 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -889,6 +889,136 @@}}},+ "/agent-sessions/{session_id}/permissions": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Read sharing settings for a session the caller can view.",+ "operationId": "get_agent_session_permissions",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "description": "ID of the agent session",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SharePermissionV2"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["agent-sessions"],+ "summary": "Update link, channel, or team sharing after owner authorization.",+ "operationId": "update_agent_session_permissions",+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "description": "ID of the agent session",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateSharePermissionRequestV2"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SharePermissionV2"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/agent-sessions/{session_id}/queue": {"get": {"tags": ["agent-sessions"],@@ -1321,6 +1451,11 @@},"components": {"schemas": {+ "AccessLevel": {+ "type": "string",+ "description": "Ordered from least to most access top -> bottom",+ "enum": ["view", "comment", "edit", "owner"]+ },"AgentAction": {"oneOf": [{@@ -2076,6 +2211,21 @@"description": "The source of the captured diff, on the wire.","enum": ["github_pull_request"]},+ "ChannelSharePermission": {+ "type": "object",+ "description": "The channel share permission",+ "required": ["channel_id", "access_level"],+ "properties": {+ "access_level": {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The access level for the channel"+ },+ "channel_id": {+ "type": "string",+ "description": "The channel id"+ }+ }+ },"CompleteRequest": {"type": "object","description": "One-time manual code. Deliberately does not implement Debug.",@@ -2382,6 +2532,11 @@}}},+ "LinkShare": {+ "type": "string",+ "description": "Defines who can access an item through its share link.",+ "enum": ["PUBLIC", "TEAM"]+ },"LoadAgentModelsRequest": {"type": "object","description": "HTTP request selecting one provider to probe.",@@ -2692,6 +2847,60 @@],"description": "Transport representation of a session's status, mirroring\n[`SessionStatus`]."},+ "SharePermissionV2": {+ "type": "object",+ "required": ["id", "owner"],+ "properties": {+ "channelSharePermissions": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ChannelSharePermission"+ },+ "description": "The channel share permissions for the item"+ },+ "id": {+ "type": "string",+ "description": "The share permission id"+ },+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link"+ }+ ]+ },+ "linkShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The level of access granted through the share link"+ }+ ]+ },+ "owner": {+ "type": "string",+ "description": "The owner of the item"+ },+ "teamShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The explicit access level granted to the owner's team, or `null` when disabled."+ }+ ]+ }+ }+ },"StartResponse": {"type": "object","description": "Public PKCE challenge and attempt handle; contains no verifier or provider tokens.",@@ -2732,6 +2941,80 @@}}},+ "UpdateChannelSharePermission": {+ "type": "object",+ "required": ["operation", "channelId"],+ "properties": {+ "accessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The access level for the channel\nThis is required if the operation is add or replace"+ }+ ]+ },+ "channelId": {+ "type": "string",+ "description": "The channel id"+ },+ "operation": {+ "$ref": "#/components/schemas/UpdateOperation",+ "description": "The type of operation to be performed on the chanel share permission\nYou can add, remove or replace and existing permission"+ }+ }+ },+ "UpdateOperation": {+ "type": "string",+ "enum": ["add", "remove", "replace"]+ },+ "UpdateSharePermissionRequestV2": {+ "type": "object",+ "properties": {+ "channelSharePermissions": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/UpdateChannelSharePermission"+ },+ "description": "Any channel share permissions to be created/updated/removed"+ },+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link. Omit to leave unchanged or pass `null` to\ndisable link sharing."+ }+ ]+ },+ "linkShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."+ }+ ]+ },+ "teamShareAccessLevel": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The explicit team access level. Omit to leave unchanged or pass `null` to disable team\nsharing. Only the actual owner may change this setting; `owner` is not an allowed level."+ }+ ]+ }+ }+ },"WithAgentSessionId": {"type": "object","description": "Just a session id, for the preview variants that carry nothing else.\n\nClients deserialize this, so both derives are used.",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex c55552f100..1f62d7f039 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -33,8 +33,10 @@ export const agentHarnessExcluded = ['previewAgentSessions',] as const satisfies readonly (keyof AgentHarnessSdk)[];-export const agentHarnessBacklog =- [] as const satisfies readonly (keyof AgentHarnessSdk)[];+export const agentHarnessBacklog = [+ 'getAgentSessionPermissions',+ 'updateAgentSessionPermissions',+] as const satisfies readonly (keyof AgentHarnessSdk)[];export const authExcluded = ['appleLogin',diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rsindex e3b7ffc1b1..2ceb1f1a1b 100644--- a/services/agent_harness_service/src/api.rs+++ b/services/agent_harness_service/src/api.rs@@ -69,6 +69,7 @@ pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes> {models: AgentModelsRouterState<Models, Auth>,repositories: AgentRepositoriesRouterState<Auth>,claude_auth: Router,+ sharing: Router,changes: AgentChangesRouterState<Changes, Access, Auth>,}@@ -93,6 +94,7 @@ impl<T, R, Opener, Bots, Access, Auth, Models, Changes>models,repositories,claude_auth: Router::new(),+ sharing: Router::new(),changes,}}@@ -102,6 +104,12 @@ impl<T, R, Opener, Bots, Access, Auth, Models, Changes>self.claude_auth = router;self}++ /// Attach session-sharing routes with their independent domain service.+ pub fn with_sharing(mut self, router: Router) -> Self {+ self.sharing = router;+ self+ }}/// Serve session egress and Macro Internal MCP on the existing egress listener.@@ -190,6 +198,7 @@ wherelet agent_sessions = agent_session_read_router(states.read.clone()).merge(agent_session_control_router(states.control)).merge(agent_session_create_router(states.create))+ .merge(states.sharing).merge(agent_changes_router(states.changes));Router::new().nest("/agent-sessions", agent_sessions)diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rsindex 41a8a59590..cd78cdecd3 100644--- a/services/agent_harness_service/src/api/swagger.rs+++ b/services/agent_harness_service/src/api/swagger.rs@@ -54,6 +54,8 @@ impl Modify for SecurityAddon {axum_router::get_agent_session_handler,axum_router::preview_agent_sessions_handler,axum_router::rename_agent_session_handler,+ axum_router::sharing::get_agent_session_permissions,+ axum_router::sharing::update_agent_session_permissions,axum_router::get_agent_session_log_handler,axum_router::control_agent_session_handler,axum_router::get_agent_session_queue_handler,diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 4401f6ff4b..c2dca0a13a 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -982,7 +982,7 @@ async fn run() -> anyhow::Result<()> {);let control_state = AgentSessionControlState::new(harness.clone(),- entity_access,+ entity_access.clone(),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),);let bots_directory = Arc::new(PgBotDirectory::new(PgBotsRepo::new(pool.clone())));@@ -1013,6 +1013,13 @@ async fn run() -> anyhow::Result<()> {),);let http_port = config.port;+ let sharing = agent_session::inbound::axum_router::sharing::agent_session_sharing_router(+ AgentSessionRouterState::new(+ agent_session::domain::sharing::SessionSharingService::new(session_repo.clone()),+ entity_access,+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),+ ),+ );let http = tokio::spawn(async move {if let Err(error) = api::setup_and_serve(api::ApiStates::new(@@ -1024,7 +1031,8 @@ async fn run() -> anyhow::Result<()> {repositories_state,changes_state,)- .with_claude_auth(claude_auth),+ .with_claude_auth(claude_auth)+ .with_sharing(sharing),http_runtime_commands_readiness,http_port,shutdown_signal(),