Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat: add persistent private agent persona DMs (#7456)

teoa93ee6eb715a
diff --git a/.sqlx/query-011e8bbaeba91d96139da84e1f5a07d876cb20348e9150940c8932399b399e27.json b/.sqlx/query-011e8bbaeba91d96139da84e1f5a07d876cb20348e9150940c8932399b399e27.json
new file mode 100644
index 0000000000..301f01ac72
--- /dev/null
+++ b/.sqlx/query-011e8bbaeba91d96139da84e1f5a07d876cb20348e9150940c8932399b399e27.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH sessions AS (\n SELECT session_id\n FROM agent_conversation_sessions\n WHERE channel_id = $1 AND bot_id = $2\n ),\n shown AS (\n -- Whatever waits or runs, however long ago it was posted.\n SELECT turn.source_message_id\n FROM agent_conversation_turns turn\n JOIN sessions ON sessions.session_id = turn.session_id\n WHERE turn.state IN ('queued', 'running')\n UNION\n -- Each session's first turn, where the transcript shows its\n -- context starting fresh.\n SELECT first.source_message_id\n FROM sessions\n CROSS JOIN LATERAL (\n SELECT source_message_id\n FROM agent_conversation_turns\n WHERE session_id = sessions.session_id\n ORDER BY created_at, source_message_id\n LIMIT 1\n ) first\n UNION\n (\n SELECT source_message_id\n FROM agent_conversation_turns\n WHERE channel_id = $1 AND bot_id = $2\n ORDER BY created_at DESC, source_message_id DESC\n LIMIT $3\n )\n )\n SELECT jsonb_build_object(\n 'source_message_id', source_message_id,\n 'bot_id', bot_id,\n 'session_id', session_id,\n 'action_id', action_id,\n 'reply_message_id', in_flight->'announcement_message_id',\n 'state', state,\n 'retryable', state IN ('failed', 'stopped', 'interrupted')\n AND (reply_finalized OR in_flight->>'announcement_message_id' IS NULL),\n 'created_at', created_at\n ) AS \"value!\"\n FROM agent_conversation_turns\n WHERE channel_id = $1\n AND bot_id = $2\n AND source_message_id IN (SELECT source_message_id FROM shown)\n ORDER BY created_at, source_message_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "011e8bbaeba91d96139da84e1f5a07d876cb20348e9150940c8932399b399e27"
+}
diff --git a/.sqlx/query-09ca8d4cc344e95de45c49ed787d28f81fa820ca18bac401bb1350e1ca40b7c3.json b/.sqlx/query-09ca8d4cc344e95de45c49ed787d28f81fa820ca18bac401bb1350e1ca40b7c3.json
new file mode 100644
index 0000000000..6b7ceaf15c
--- /dev/null
+++ b/.sqlx/query-09ca8d4cc344e95de45c49ed787d28f81fa820ca18bac401bb1350e1ca40b7c3.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 45)) AS \"claimed!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "claimed!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "09ca8d4cc344e95de45c49ed787d28f81fa820ca18bac401bb1350e1ca40b7c3"
+}
diff --git a/.sqlx/query-1382bdb8d243d8784272bfd8e707f7fc43684435c1bed3aa92328abc2a00f74b.json b/.sqlx/query-1382bdb8d243d8784272bfd8e707f7fc43684435c1bed3aa92328abc2a00f74b.json
new file mode 100644
index 0000000000..482117bd71
--- /dev/null
+++ b/.sqlx/query-1382bdb8d243d8784272bfd8e707f7fc43684435c1bed3aa92328abc2a00f74b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM comms_channels WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "1382bdb8d243d8784272bfd8e707f7fc43684435c1bed3aa92328abc2a00f74b"
+}
diff --git a/.sqlx/query-13e54d1aedcbe21c6b51c201f5597e3f67033bf7c46688e160dce262b99083c8.json b/.sqlx/query-13e54d1aedcbe21c6b51c201f5597e3f67033bf7c46688e160dce262b99083c8.json
new file mode 100644
index 0000000000..358b6aec60
--- /dev/null
+++ b/.sqlx/query-13e54d1aedcbe21c6b51c201f5597e3f67033bf7c46688e160dce262b99083c8.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT channel_id, bot_id FROM comms_channel_agents WHERE kind = 'direct' AND user_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "13e54d1aedcbe21c6b51c201f5597e3f67033bf7c46688e160dce262b99083c8"
+}
diff --git a/.sqlx/query-14b42cdfddd60b765545005bd4fd575be48cf67d31e71e76dabb3b9c64325fe6.json b/.sqlx/query-14b42cdfddd60b765545005bd4fd575be48cf67d31e71e76dabb3b9c64325fe6.json
new file mode 100644
index 0000000000..ece8709824
--- /dev/null
+++ b/.sqlx/query-14b42cdfddd60b765545005bd4fd575be48cf67d31e71e76dabb3b9c64325fe6.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns AS candidate SET state = 'running', in_flight = $2, updated_at = now() WHERE action_id = $1 AND state = 'queued' AND NOT EXISTS (SELECT 1 FROM agent_conversation_turns other WHERE other.session_id = candidate.session_id AND (other.state IN ('running', 'interrupted') OR (other.state = 'queued' AND (other.created_at, other.source_message_id) < (candidate.created_at, candidate.source_message_id))))",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "14b42cdfddd60b765545005bd4fd575be48cf67d31e71e76dabb3b9c64325fe6"
+}
diff --git a/.sqlx/query-1e2b5f16fc1eca3b9f8261470249db35499a25f4251d8b62d7ae5a91ad7b7182.json b/.sqlx/query-1e2b5f16fc1eca3b9f8261470249db35499a25f4251d8b62d7ae5a91ad7b7182.json
deleted file mode 100644
index a898f659bb..0000000000
--- a/.sqlx/query-1e2b5f16fc1eca3b9f8261470249db35499a25f4251d8b62d7ae5a91ad7b7182.json
+++ /dev/null
@@ -1,74 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH candidate AS (\n SELECT\n true AS found,\n list_hidden AND thread_id IS NULL AS warm,\n owner_id = $2 AS owner_matches,\n bot_id = $3 AS bot_matches,\n model = $4 AS model_matches,\n instructions IS NOT DISTINCT FROM $5 AS instructions_match,\n COALESCE(status != 'disconnected'\n AND NOT (status = 'event' AND status_event_name = 'disconnected'), false) AS live,\n created_at > NOW() - INTERVAL '10 minutes' AS fresh\n FROM agent_session WHERE id = $1\n ), claimed AS (\n UPDATE agent_session SET list_hidden = false\n WHERE id = $1 AND owner_id = $2 AND bot_id = $3 AND model = $4\n AND instructions IS NOT DISTINCT FROM $5\n AND list_hidden AND thread_id IS NULL\n AND status != 'disconnected'\n AND NOT (status = 'event' AND status_event_name = 'disconnected')\n AND created_at > NOW() - INTERVAL '10 minutes'\n RETURNING id\n )\n SELECT\n EXISTS (SELECT 1 FROM claimed) AS \"claimed!\",\n candidate.found AS \"found?\",\n candidate.warm AS \"warm?\",\n candidate.owner_matches AS \"owner_matches?\",\n candidate.bot_matches AS \"bot_matches?\",\n candidate.model_matches AS \"model_matches?\",\n candidate.instructions_match AS \"instructions_match?\",\n candidate.live AS \"live?\",\n candidate.fresh AS \"fresh?\"\n FROM (SELECT 1) AS one LEFT JOIN candidate ON true\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "claimed!",
- "type_info": "Bool"
- },
- {
- "ordinal": 1,
- "name": "found?",
- "type_info": "Bool"
- },
- {
- "ordinal": 2,
- "name": "warm?",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "owner_matches?",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "bot_matches?",
- "type_info": "Bool"
- },
- {
- "ordinal": 5,
- "name": "model_matches?",
- "type_info": "Bool"
- },
- {
- "ordinal": 6,
- "name": "instructions_match?",
- "type_info": "Bool"
- },
- {
- "ordinal": 7,
- "name": "live?",
- "type_info": "Bool"
- },
- {
- "ordinal": 8,
- "name": "fresh?",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null,
- null
- ]
- },
- "hash": "1e2b5f16fc1eca3b9f8261470249db35499a25f4251d8b62d7ae5a91ad7b7182"
-}
diff --git a/.sqlx/query-1e372ef00447be11a370d30b8bc1511e9a37ca11cbbd414acaed16dc6bd81f22.json b/.sqlx/query-1e372ef00447be11a370d30b8bc1511e9a37ca11cbbd414acaed16dc6bd81f22.json
new file mode 100644
index 0000000000..729f368fd5
--- /dev/null
+++ b/.sqlx/query-1e372ef00447be11a370d30b8bc1511e9a37ca11cbbd414acaed16dc6bd81f22.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET reply_segments = $2 WHERE action_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1e372ef00447be11a370d30b8bc1511e9a37ca11cbbd414acaed16dc6bd81f22"
+}
diff --git a/.sqlx/query-2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298.json b/.sqlx/query-2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298.json
deleted file mode 100644
index c00086e9d7..0000000000
--- a/.sqlx/query-2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE user_id = $1\n AND left_at IS NULL\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "2127340cc22d156ee073bd7a981fe4b29e0a74a606852d82620ef43b3151f298"
-}
diff --git a/.sqlx/query-7f866ed3077d3fcc644b48902cd95584d6d474db9eedafdde38c6479040bf09b.json b/.sqlx/query-21e4f75fca6a182472e3d18674b622731a9861f0852807581f5734da59715d98.json
similarity index 75%
rename from .sqlx/query-7f866ed3077d3fcc644b48902cd95584d6d474db9eedafdde38c6479040bf09b.json
rename to .sqlx/query-21e4f75fca6a182472e3d18674b622731a9861f0852807581f5734da59715d98.json
index 17ec97b116..3a21e1a12d 100644
--- a/.sqlx/query-7f866ed3077d3fcc644b48902cd95584d6d474db9eedafdde38c6479040bf09b.json
+++ b/.sqlx/query-21e4f75fca6a182472e3d18674b622731a9861f0852807581f5734da59715d98.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n a.auto_accept_permissions,\n a.is_coding,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n a.auto_accept_permissions,\n a.is_coding,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = p.channel_id\n AND ca.kind = 'direct'\n )\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.id = $1\n AND b.kind = 'owned'\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -156,5 +156,5 @@
null
]
},
- "hash": "7f866ed3077d3fcc644b48902cd95584d6d474db9eedafdde38c6479040bf09b"
+ "hash": "21e4f75fca6a182472e3d18674b622731a9861f0852807581f5734da59715d98"
}
diff --git a/.sqlx/query-28510e4a4a96978351eb365c19c24cf6ff971511c6e475c6ad0989b1788e8919.json b/.sqlx/query-28510e4a4a96978351eb365c19c24cf6ff971511c6e475c6ad0989b1788e8919.json
new file mode 100644
index 0000000000..ea118dae02
--- /dev/null
+++ b/.sqlx/query-28510e4a4a96978351eb365c19c24cf6ff971511c6e475c6ad0989b1788e8919.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT bot_id, kind, user_id FROM comms_channel_agents WHERE channel_id = $1 ORDER BY bot_id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "28510e4a4a96978351eb365c19c24cf6ff971511c6e475c6ad0989b1788e8919"
+}
diff --git a/.sqlx/query-2a7e42834c154a976cbffa779c60a184a122e3b6b6ccfb2a5c25d4ff45ca197f.json b/.sqlx/query-2a7e42834c154a976cbffa779c60a184a122e3b6b6ccfb2a5c25d4ff45ca197f.json
new file mode 100644
index 0000000000..c84741e6f2
--- /dev/null
+++ b/.sqlx/query-2a7e42834c154a976cbffa779c60a184a122e3b6b6ccfb2a5c25d4ff45ca197f.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_session SET list_hidden = TRUE, for_warming = FALSE WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2a7e42834c154a976cbffa779c60a184a122e3b6b6ccfb2a5c25d4ff45ca197f"
+}
diff --git a/.sqlx/query-310a60b1bb938266bd7c07073b5f83946eac5d89b7b4b395c7c7ef0bea833cca.json b/.sqlx/query-310a60b1bb938266bd7c07073b5f83946eac5d89b7b4b395c7c7ef0bea833cca.json
new file mode 100644
index 0000000000..2a463904d9
--- /dev/null
+++ b/.sqlx/query-310a60b1bb938266bd7c07073b5f83946eac5d89b7b4b395c7c7ef0bea833cca.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT settings FROM agent_conversation_settings WHERE session_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "settings",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "310a60b1bb938266bd7c07073b5f83946eac5d89b7b4b395c7c7ef0bea833cca"
+}
diff --git a/.sqlx/query-32e40da91a44d91eced5fe219721cfa2e32515efca83ae52ef4480311352ee99.json b/.sqlx/query-32e40da91a44d91eced5fe219721cfa2e32515efca83ae52ef4480311352ee99.json
new file mode 100644
index 0000000000..7eff23ef03
--- /dev/null
+++ b/.sqlx/query-32e40da91a44d91eced5fe219721cfa2e32515efca83ae52ef4480311352ee99.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE agent_session SET list_hidden = TRUE, for_warming = FALSE\n WHERE id IN (\n SELECT s.id FROM agent_session s\n JOIN agent_conversation_sessions c ON c.session_id = s.id\n JOIN comms_channel_agents a ON a.channel_id = c.channel_id\n AND a.bot_id = c.bot_id AND a.kind = 'direct'\n WHERE NOT s.list_hidden OR s.for_warming\n ORDER BY s.id LIMIT $1 FOR UPDATE OF s SKIP LOCKED\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "32e40da91a44d91eced5fe219721cfa2e32515efca83ae52ef4480311352ee99"
+}
diff --git a/.sqlx/query-33b3bc517761192f2824524bde4b0b7b9882c5061f32f2320adc64e25ec6daf3.json b/.sqlx/query-33b3bc517761192f2824524bde4b0b7b9882c5061f32f2320adc64e25ec6daf3.json
new file mode 100644
index 0000000000..58d561cf48
--- /dev/null
+++ b/.sqlx/query-33b3bc517761192f2824524bde4b0b7b9882c5061f32f2320adc64e25ec6daf3.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO agent_conversation_sessions (session_id, channel_id, bot_id) VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "33b3bc517761192f2824524bde4b0b7b9882c5061f32f2320adc64e25ec6daf3"
+}
diff --git a/.sqlx/query-34d7836f5b9cb636666859a06c6f88d813af64a3674c6ea8ebd5fa5150a19cf7.json b/.sqlx/query-34d7836f5b9cb636666859a06c6f88d813af64a3674c6ea8ebd5fa5150a19cf7.json
new file mode 100644
index 0000000000..987e22c06b
--- /dev/null
+++ b/.sqlx/query-34d7836f5b9cb636666859a06c6f88d813af64a3674c6ea8ebd5fa5150a19cf7.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_sessions SET is_current = FALSE WHERE channel_id = $1 AND bot_id = $2 AND is_current",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "34d7836f5b9cb636666859a06c6f88d813af64a3674c6ea8ebd5fa5150a19cf7"
+}
diff --git a/.sqlx/query-3b44286e8d29a86ffd3b9c56f1ee781bf9e8f45bb5b4665a96eff6d2b0cf770e.json b/.sqlx/query-3b44286e8d29a86ffd3b9c56f1ee781bf9e8f45bb5b4665a96eff6d2b0cf770e.json
new file mode 100644
index 0000000000..b79056ca07
--- /dev/null
+++ b/.sqlx/query-3b44286e8d29a86ffd3b9c56f1ee781bf9e8f45bb5b4665a96eff6d2b0cf770e.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_session SET for_warming = TRUE WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3b44286e8d29a86ffd3b9c56f1ee781bf9e8f45bb5b4665a96eff6d2b0cf770e"
+}
diff --git a/.sqlx/query-3b5996e8b471476a1e92d24cd8afcebc4a13d19b34b98241a340c53a318fd44f.json b/.sqlx/query-3b5996e8b471476a1e92d24cd8afcebc4a13d19b34b98241a340c53a318fd44f.json
new file mode 100644
index 0000000000..06e216a23b
--- /dev/null
+++ b/.sqlx/query-3b5996e8b471476a1e92d24cd8afcebc4a13d19b34b98241a340c53a318fd44f.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT to_jsonb(j) AS \"value!\" FROM agent_conversation_turns j WHERE source_message_id = $1 AND bot_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3b5996e8b471476a1e92d24cd8afcebc4a13d19b34b98241a340c53a318fd44f"
+}
diff --git a/.sqlx/query-3c3b621f674dbf5e53d78921c03600b2f74e698a41b9081d7a5d601465b398ec.json b/.sqlx/query-3c3b621f674dbf5e53d78921c03600b2f74e698a41b9081d7a5d601465b398ec.json
new file mode 100644
index 0000000000..313e49b981
--- /dev/null
+++ b/.sqlx/query-3c3b621f674dbf5e53d78921c03600b2f74e698a41b9081d7a5d601465b398ec.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO activity_events (id, actor_id, subject_id, action, entity_type, entity_id, occurred_at) VALUES ($1, $2, $2, 'edited', 'agent_session', $3, '2024-06-01 10:22:00+00')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3c3b621f674dbf5e53d78921c03600b2f74e698a41b9081d7a5d601465b398ec"
+}
diff --git a/.sqlx/query-42f4086c14fc46eff788f7c749222c0796a147ff393bf9d87366c7da73851f99.json b/.sqlx/query-42f4086c14fc46eff788f7c749222c0796a147ff393bf9d87366c7da73851f99.json
new file mode 100644
index 0000000000..308f61e906
--- /dev/null
+++ b/.sqlx/query-42f4086c14fc46eff788f7c749222c0796a147ff393bf9d87366c7da73851f99.json
@@ -0,0 +1,27 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO agent_conversation_turns AS turn (source_message_id, bot_id, session_id, channel_id, action_id, command)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (source_message_id, bot_id) DO UPDATE SET source_message_id = turn.source_message_id\n RETURNING to_jsonb(turn) AS \"value!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "42f4086c14fc46eff788f7c749222c0796a147ff393bf9d87366c7da73851f99"
+}
diff --git a/.sqlx/query-486f15bfd292acec985998d529e538b0e4805c9390b6a2c09e89921df3293f97.json b/.sqlx/query-486f15bfd292acec985998d529e538b0e4805c9390b6a2c09e89921df3293f97.json
new file mode 100644
index 0000000000..5dd276aa74
--- /dev/null
+++ b/.sqlx/query-486f15bfd292acec985998d529e538b0e4805c9390b6a2c09e89921df3293f97.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_session SET created_at = NOW() - INTERVAL '11 minutes' WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "486f15bfd292acec985998d529e538b0e4805c9390b6a2c09e89921df3293f97"
+}
diff --git a/.sqlx/query-50cab0828864dbbffc927ef9fac590e5e2135d0f84256790700c53e5846a4147.json b/.sqlx/query-50cab0828864dbbffc927ef9fac590e5e2135d0f84256790700c53e5846a4147.json
new file mode 100644
index 0000000000..069cc6466e
--- /dev/null
+++ b/.sqlx/query-50cab0828864dbbffc927ef9fac590e5e2135d0f84256790700c53e5846a4147.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_advisory_xact_lock(hashtextextended(session_id::text, 43)) FROM agent_conversation_turns WHERE action_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pg_advisory_xact_lock",
+ "type_info": "Void"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "50cab0828864dbbffc927ef9fac590e5e2135d0f84256790700c53e5846a4147"
+}
diff --git a/.sqlx/query-0b8f347e3167ca28d3531dfd593994f5920f68f2140a748b9a8932e83360b942.json b/.sqlx/query-50d78b39341e0518ff25310d079384e18ca9ebc8d39c6c6e601584b7df2772a6.json
similarity index 59%
rename from .sqlx/query-0b8f347e3167ca28d3531dfd593994f5920f68f2140a748b9a8932e83360b942.json
rename to .sqlx/query-50d78b39341e0518ff25310d079384e18ca9ebc8d39c6c6e601584b7df2772a6.json
index 442ca6d9ae..7a8c822fb7 100644
--- a/.sqlx/query-0b8f347e3167ca28d3531dfd593994f5920f68f2140a748b9a8932e83360b942.json
+++ b/.sqlx/query-50d78b39341e0518ff25310d079384e18ca9ebc8d39c6c6e601584b7df2772a6.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n a.auto_accept_permissions,\n a.is_coding,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n OR (\n a.channel_scope = 'selected'\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $1\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = 'bot|' || b.id::text\n AND bot_p.left_at IS NULL\n )\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n a.auto_accept_permissions,\n a.is_coding,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = p.channel_id\n AND ca.kind = 'direct'\n )\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n OR (\n a.channel_scope = 'selected'\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $1\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = 'bot|' || b.id::text\n AND bot_p.left_at IS NULL\n -- A conversation with the persona shares nothing:\n -- only the people it already serves have one.\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = bot_p.channel_id\n AND ca.kind = 'direct'\n )\n )\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
"describe": {
"columns": [
{
@@ -156,5 +156,5 @@
null
]
},
- "hash": "0b8f347e3167ca28d3531dfd593994f5920f68f2140a748b9a8932e83360b942"
+ "hash": "50d78b39341e0518ff25310d079384e18ca9ebc8d39c6c6e601584b7df2772a6"
}
diff --git a/.sqlx/query-5865fd315c9d61123e6532646b776927a1defd5a9a8d36c63329de6fd5c0dabf.json b/.sqlx/query-5865fd315c9d61123e6532646b776927a1defd5a9a8d36c63329de6fd5c0dabf.json
new file mode 100644
index 0000000000..b36da59611
--- /dev/null
+++ b/.sqlx/query-5865fd315c9d61123e6532646b776927a1defd5a9a8d36c63329de6fd5c0dabf.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT user_id, role::text AS \"role!\" FROM comms_channel_participants WHERE channel_id = $1 AND left_at IS NULL",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "role!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "5865fd315c9d61123e6532646b776927a1defd5a9a8d36c63329de6fd5c0dabf"
+}
diff --git a/.sqlx/query-5ac26a87e55b64981f2bf515a6c2e6fbf8c9d39b32f3bb016f6e468e6fabd5f9.json b/.sqlx/query-5ac26a87e55b64981f2bf515a6c2e6fbf8c9d39b32f3bb016f6e468e6fabd5f9.json
new file mode 100644
index 0000000000..e348440e52
--- /dev/null
+++ b/.sqlx/query-5ac26a87e55b64981f2bf515a6c2e6fbf8c9d39b32f3bb016f6e468e6fabd5f9.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5ac26a87e55b64981f2bf515a6c2e6fbf8c9d39b32f3bb016f6e468e6fabd5f9"
+}
diff --git a/.sqlx/query-5c7ca0a7fe9e7ea361eefd9aea0d71bad600396a7a4549f9bf080a5c72321697.json b/.sqlx/query-5c7ca0a7fe9e7ea361eefd9aea0d71bad600396a7a4549f9bf080a5c72321697.json
new file mode 100644
index 0000000000..f94e0a8e66
--- /dev/null
+++ b/.sqlx/query-5c7ca0a7fe9e7ea361eefd9aea0d71bad600396a7a4549f9bf080a5c72321697.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'owner'), ($1, $3, 'member')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5c7ca0a7fe9e7ea361eefd9aea0d71bad600396a7a4549f9bf080a5c72321697"
+}
diff --git a/.sqlx/query-656d4cae4aa26f841ed56193f15b53b41b743cc85e5f2ff9ba48420b20288aee.json b/.sqlx/query-656d4cae4aa26f841ed56193f15b53b41b743cc85e5f2ff9ba48420b20288aee.json
new file mode 100644
index 0000000000..7490f56e4a
--- /dev/null
+++ b/.sqlx/query-656d4cae4aa26f841ed56193f15b53b41b743cc85e5f2ff9ba48420b20288aee.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET state = $2, outcome = $3, reply_finalized = FALSE, updated_at = now() WHERE action_id = $1 AND (state IN ('queued', 'running') OR (state = 'interrupted' AND $2 != 'interrupted'))",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "656d4cae4aa26f841ed56193f15b53b41b743cc85e5f2ff9ba48420b20288aee"
+}
diff --git a/.sqlx/query-67eac3a228ca534d34eaedc160e6afd4d706c8f548bd12ecb5e14e9ab68dc064.json b/.sqlx/query-67eac3a228ca534d34eaedc160e6afd4d706c8f548bd12ecb5e14e9ab68dc064.json
new file mode 100644
index 0000000000..98316beaac
--- /dev/null
+++ b/.sqlx/query-67eac3a228ca534d34eaedc160e6afd4d706c8f548bd12ecb5e14e9ab68dc064.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT channel_id FROM comms_channel_agents WHERE kind = 'direct' AND user_id = $1 AND bot_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "67eac3a228ca534d34eaedc160e6afd4d706c8f548bd12ecb5e14e9ab68dc064"
+}
diff --git a/.sqlx/query-6e5629776d9a9845d2a1bf9a5b2c8b96f456cb8763aca2159773b6d04d2179a1.json b/.sqlx/query-6e5629776d9a9845d2a1bf9a5b2c8b96f456cb8763aca2159773b6d04d2179a1.json
new file mode 100644
index 0000000000..15c613968e
--- /dev/null
+++ b/.sqlx/query-6e5629776d9a9845d2a1bf9a5b2c8b96f456cb8763aca2159773b6d04d2179a1.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT for_warming FROM agent_session WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "for_warming",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6e5629776d9a9845d2a1bf9a5b2c8b96f456cb8763aca2159773b6d04d2179a1"
+}
diff --git a/.sqlx/query-70dc363217dfc780b7854177cc88593e5285c19a8000f172f0275a6e14a5b270.json b/.sqlx/query-70dc363217dfc780b7854177cc88593e5285c19a8000f172f0275a6e14a5b270.json
new file mode 100644
index 0000000000..81342d4ba7
--- /dev/null
+++ b/.sqlx/query-70dc363217dfc780b7854177cc88593e5285c19a8000f172f0275a6e14a5b270.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT to_jsonb(j) AS \"value!\" FROM agent_conversation_turns j WHERE state = 'running' AND updated_at < now() - interval '2 minutes' ORDER BY updated_at LIMIT $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "70dc363217dfc780b7854177cc88593e5285c19a8000f172f0275a6e14a5b270"
+}
diff --git a/.sqlx/query-717deaa8d9a4935a02556b961902331414dfc631437d56688f6443f7dbf71935.json b/.sqlx/query-717deaa8d9a4935a02556b961902331414dfc631437d56688f6443f7dbf71935.json
new file mode 100644
index 0000000000..eb6380bcf7
--- /dev/null
+++ b/.sqlx/query-717deaa8d9a4935a02556b961902331414dfc631437d56688f6443f7dbf71935.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT session_id FROM agent_conversation_sessions WHERE channel_id = $1 AND bot_id = $2 AND is_current",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "session_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "717deaa8d9a4935a02556b961902331414dfc631437d56688f6443f7dbf71935"
+}
diff --git a/.sqlx/query-7228d6ed25f2492d2bd6487e12a4a5812a8489c0ee91970b831a5448b1577dca.json b/.sqlx/query-7228d6ed25f2492d2bd6487e12a4a5812a8489c0ee91970b831a5448b1577dca.json
new file mode 100644
index 0000000000..4ed4517659
--- /dev/null
+++ b/.sqlx/query-7228d6ed25f2492d2bd6487e12a4a5812a8489c0ee91970b831a5448b1577dca.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM team_user WHERE user_id = $1 AND team_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7228d6ed25f2492d2bd6487e12a4a5812a8489c0ee91970b831a5448b1577dca"
+}
diff --git a/.sqlx/query-72fa5e8cf941fac344dbadf80dd6ee8d2fb4b3fe920fecb5d4cd135e34a96adb.json b/.sqlx/query-72fa5e8cf941fac344dbadf80dd6ee8d2fb4b3fe920fecb5d4cd135e34a96adb.json
new file mode 100644
index 0000000000..50badec261
--- /dev/null
+++ b/.sqlx/query-72fa5e8cf941fac344dbadf80dd6ee8d2fb4b3fe920fecb5d4cd135e34a96adb.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channel_agents (channel_id, user_id, bot_id, kind)\n VALUES ($1, $2, $3, 'direct')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "72fa5e8cf941fac344dbadf80dd6ee8d2fb4b3fe920fecb5d4cd135e34a96adb"
+}
diff --git a/.sqlx/query-b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1.json b/.sqlx/query-756d77585ebc481d41ad20bbb8f1d603e5d80c240bdd97db7edcb31e3fc2e344.json
similarity index 69%
rename from .sqlx/query-b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1.json
rename to .sqlx/query-756d77585ebc481d41ad20bbb8f1d603e5d80c240bdd97db7edcb31e3fc2e344.json
index 6090bfe9e2..6e67df90ca 100644
--- a/.sqlx/query-b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1.json
+++ b/.sqlx/query-756d77585ebc481d41ad20bbb8f1d603e5d80c240bdd97db7edcb31e3fc2e344.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n c.id AS channel_id,\n c.name,\n c.channel_type::text AS \"channel_type!\",\n cp.joined_at\n FROM comms_channel_participants cp\n JOIN comms_channels c ON c.id = cp.channel_id\n WHERE cp.user_id = $1\n AND cp.left_at IS NULL\n ORDER BY cp.joined_at ASC, c.id ASC\n ",
+ "query": "\n SELECT\n c.id AS channel_id,\n c.name,\n c.channel_type::text AS \"channel_type!\",\n cp.joined_at\n FROM comms_channel_participants cp\n JOIN comms_channels c ON c.id = cp.channel_id\n WHERE cp.user_id = $1\n AND cp.left_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = cp.channel_id\n AND ca.kind = 'direct'\n )\n ORDER BY cp.joined_at ASC, c.id ASC\n ",
"describe": {
"columns": [
{
@@ -36,5 +36,5 @@
false
]
},
- "hash": "b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1"
+ "hash": "756d77585ebc481d41ad20bbb8f1d603e5d80c240bdd97db7edcb31e3fc2e344"
}
diff --git a/.sqlx/query-7d95b6b6b330fd5a59e0e8d8c883d08d09a79fec0c921fb17579b3921d663a03.json b/.sqlx/query-7d95b6b6b330fd5a59e0e8d8c883d08d09a79fec0c921fb17579b3921d663a03.json
new file mode 100644
index 0000000000..b0f9f3bf17
--- /dev/null
+++ b/.sqlx/query-7d95b6b6b330fd5a59e0e8d8c883d08d09a79fec0c921fb17579b3921d663a03.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE agent_session SET status = 'disconnected'\n WHERE id IN (\n SELECT id FROM agent_session\n WHERE for_warming AND list_hidden AND thread_id IS NULL\n AND NOT EXISTS (SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = agent_session.id)\n AND created_at <= NOW() - INTERVAL '10 minutes'\n ORDER BY created_at LIMIT 64 FOR UPDATE SKIP LOCKED\n ) RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7d95b6b6b330fd5a59e0e8d8c883d08d09a79fec0c921fb17579b3921d663a03"
+}
diff --git a/.sqlx/query-7e268d6fa2b9c43d63f7645133ab0e53abda6614b60d09cf75e0d0230c20d4bf.json b/.sqlx/query-7e268d6fa2b9c43d63f7645133ab0e53abda6614b60d09cf75e0d0230c20d4bf.json
new file mode 100644
index 0000000000..951d6b8d1d
--- /dev/null
+++ b/.sqlx/query-7e268d6fa2b9c43d63f7645133ab0e53abda6614b60d09cf75e0d0230c20d4bf.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET state = 'failed', outcome = $2, reply_finalized = FALSE, updated_at = now() WHERE action_id = $1 AND state = 'queued'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7e268d6fa2b9c43d63f7645133ab0e53abda6614b60d09cf75e0d0230c20d4bf"
+}
diff --git a/.sqlx/query-7eb2d80285937c2ea4634b7fb61a3e029b2ba0bf0fe6205bda2197f9e2228653.json b/.sqlx/query-7eb2d80285937c2ea4634b7fb61a3e029b2ba0bf0fe6205bda2197f9e2228653.json
new file mode 100644
index 0000000000..502c767466
--- /dev/null
+++ b/.sqlx/query-7eb2d80285937c2ea4634b7fb61a3e029b2ba0bf0fe6205bda2197f9e2228653.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id, list_hidden, for_warming FROM agent_session ORDER BY id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "list_hidden",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "for_warming",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "7eb2d80285937c2ea4634b7fb61a3e029b2ba0bf0fe6205bda2197f9e2228653"
+}
diff --git a/.sqlx/query-7eb3bae47ec22657b4a4d418271a8a13b342b839d831b38f5e75deb6d581163a.json b/.sqlx/query-7eb3bae47ec22657b4a4d418271a8a13b342b839d831b38f5e75deb6d581163a.json
new file mode 100644
index 0000000000..e2da13d10c
--- /dev/null
+++ b/.sqlx/query-7eb3bae47ec22657b4a4d418271a8a13b342b839d831b38f5e75deb6d581163a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND left_at IS NULL\n -- Its owner or any member of its team holds a persona's\n -- tokens, not just the person a direct conversation is\n -- with, so the persona posts into one only as their agent.\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = $1\n AND ca.kind = 'direct'\n )\n ) AS \"may_post!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "may_post!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "7eb3bae47ec22657b4a4d418271a8a13b342b839d831b38f5e75deb6d581163a"
+}
diff --git a/.sqlx/query-800e4abb0e3074df79611d0d3f36c0092b1a7174f0bea05b7de4a5f5b65a6033.json b/.sqlx/query-800e4abb0e3074df79611d0d3f36c0092b1a7174f0bea05b7de4a5f5b65a6033.json
new file mode 100644
index 0000000000..9ecbbe3d91
--- /dev/null
+++ b/.sqlx/query-800e4abb0e3074df79611d0d3f36c0092b1a7174f0bea05b7de4a5f5b65a6033.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT to_jsonb(j) AS \"value!\" FROM agent_conversation_turns j WHERE state = 'queued' AND NOT EXISTS (SELECT 1 FROM agent_conversation_turns other WHERE other.session_id = j.session_id AND (other.state IN ('running', 'interrupted') OR (other.state = 'queued' AND (other.created_at, other.source_message_id) < (j.created_at, j.source_message_id)))) ORDER BY created_at, source_message_id LIMIT $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "800e4abb0e3074df79611d0d3f36c0092b1a7174f0bea05b7de4a5f5b65a6033"
+}
diff --git a/.sqlx/query-818e3e09b64d81d10c8dc3dc908762c1a165a00eb2b8f12ae415d71158f146ae.json b/.sqlx/query-818e3e09b64d81d10c8dc3dc908762c1a165a00eb2b8f12ae415d71158f146ae.json
new file mode 100644
index 0000000000..6f8d0c50a8
--- /dev/null
+++ b/.sqlx/query-818e3e09b64d81d10c8dc3dc908762c1a165a00eb2b8f12ae415d71158f146ae.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'owner')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "818e3e09b64d81d10c8dc3dc908762c1a165a00eb2b8f12ae415d71158f146ae"
+}
diff --git a/.sqlx/query-1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c.json b/.sqlx/query-88686892a2d5b3703334eaab66b4c9c584433305dfb4a13b3e3f4cae49be3999.json
similarity index 77%
rename from .sqlx/query-1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c.json
rename to .sqlx/query-88686892a2d5b3703334eaab66b4c9c584433305dfb4a13b3e3f4cae49be3999.json
index 41e01ac1d7..714d958615 100644
--- a/.sqlx/query-1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c.json
+++ b/.sqlx/query-88686892a2d5b3703334eaab66b4c9c584433305dfb4a13b3e3f4cae49be3999.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n cp.role::text AS \"role?\",\n (\n b.id IS NOT NULL\n AND c.channel_type = 'team'\n AND c.team_id = $3\n ) AS \"is_matching_team_channel!\"\n FROM comms_channels c\n LEFT JOIN bots b\n ON b.id = $4\n AND b.team_id = $3\n AND b.deleted_at IS NULL\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id\n AND cp.user_id = $2\n AND cp.left_at IS NULL\n AND b.id IS NOT NULL\n WHERE c.id = $1\n ",
+ "query": "\n SELECT\n cp.role::text AS \"role?\",\n (\n b.id IS NOT NULL\n AND c.channel_type = 'team'\n AND c.team_id = $3\n ) AS \"is_matching_team_channel!\"\n FROM comms_channels c\n LEFT JOIN bots b\n ON b.id = $4\n AND b.team_id = $3\n AND b.deleted_at IS NULL\n LEFT JOIN comms_channel_participants cp\n ON cp.channel_id = c.id\n AND cp.user_id = $2\n AND cp.left_at IS NULL\n AND b.id IS NOT NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = c.id\n AND ca.kind = 'direct'\n )\n WHERE c.id = $1\n ",
"describe": {
"columns": [
{
@@ -27,5 +27,5 @@
null
]
},
- "hash": "1f8d22042058b693766e401728e0fa42dabe7b791cbb2fcf1ee2f52e522f7d3c"
+ "hash": "88686892a2d5b3703334eaab66b4c9c584433305dfb4a13b3e3f4cae49be3999"
}
diff --git a/.sqlx/query-8d9d1ec85c4c682923858f1480716eb1d48b5dd16678203168ba3138eee50b76.json b/.sqlx/query-8d9d1ec85c4c682923858f1480716eb1d48b5dd16678203168ba3138eee50b76.json
new file mode 100644
index 0000000000..14ae5d13c8
--- /dev/null
+++ b/.sqlx/query-8d9d1ec85c4c682923858f1480716eb1d48b5dd16678203168ba3138eee50b76.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO agent_conversation_settings AS original (session_id, settings) VALUES ($1, $2) ON CONFLICT (session_id) DO UPDATE SET session_id = original.session_id RETURNING settings",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "settings",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "8d9d1ec85c4c682923858f1480716eb1d48b5dd16678203168ba3138eee50b76"
+}
diff --git a/.sqlx/query-9189ce583b5228588668f5185dd0f96a726028f5992a82f4b0d48ae8b1388dec.json b/.sqlx/query-9189ce583b5228588668f5185dd0f96a726028f5992a82f4b0d48ae8b1388dec.json
new file mode 100644
index 0000000000..0d9d4e922c
--- /dev/null
+++ b/.sqlx/query-9189ce583b5228588668f5185dd0f96a726028f5992a82f4b0d48ae8b1388dec.json
@@ -0,0 +1,74 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH candidate AS (\n SELECT\n true AS found,\n for_warming AND list_hidden AND thread_id IS NULL AND NOT EXISTS (\n SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = agent_session.id\n ) AS warm,\n owner_id = $2 AS owner_matches,\n bot_id = $3 AS bot_matches,\n model = $4 AS model_matches,\n instructions IS NOT DISTINCT FROM $5 AS instructions_match,\n COALESCE(status != 'disconnected'\n AND NOT (status = 'event' AND status_event_name = 'disconnected'), false) AS live,\n created_at > NOW() - INTERVAL '10 minutes' AS fresh\n FROM agent_session WHERE id = $1\n ), claimed AS (\n UPDATE agent_session SET list_hidden = false, for_warming = false\n WHERE id = $1 AND owner_id = $2 AND bot_id = $3 AND model = $4\n AND instructions IS NOT DISTINCT FROM $5\n AND for_warming AND list_hidden AND thread_id IS NULL\n AND NOT EXISTS (SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = agent_session.id)\n AND status != 'disconnected'\n AND NOT (status = 'event' AND status_event_name = 'disconnected')\n AND created_at > NOW() - INTERVAL '10 minutes'\n RETURNING id\n )\n SELECT\n EXISTS (SELECT 1 FROM claimed) AS \"claimed!\",\n candidate.found AS \"found?\",\n candidate.warm AS \"warm?\",\n candidate.owner_matches AS \"owner_matches?\",\n candidate.bot_matches AS \"bot_matches?\",\n candidate.model_matches AS \"model_matches?\",\n candidate.instructions_match AS \"instructions_match?\",\n candidate.live AS \"live?\",\n candidate.fresh AS \"fresh?\"\n FROM (SELECT 1) AS one LEFT JOIN candidate ON true\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "claimed!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "found?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "warm?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "owner_matches?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "bot_matches?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "model_matches?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "instructions_match?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 7,
+ "name": "live?",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 8,
+ "name": "fresh?",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "9189ce583b5228588668f5185dd0f96a726028f5992a82f4b0d48ae8b1388dec"
+}
diff --git a/.sqlx/query-9997744a3c37a07a9a96151546d9071f93d5954ee0fc03c7382f0a5fa00ea794.json b/.sqlx/query-9997744a3c37a07a9a96151546d9071f93d5954ee0fc03c7382f0a5fa00ea794.json
new file mode 100644
index 0000000000..6e118bc3a1
--- /dev/null
+++ b/.sqlx/query-9997744a3c37a07a9a96151546d9071f93d5954ee0fc03c7382f0a5fa00ea794.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT to_jsonb(j) AS \"value!\" FROM agent_conversation_turns j WHERE outcome IS NOT NULL AND NOT reply_finalized ORDER BY updated_at LIMIT $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "9997744a3c37a07a9a96151546d9071f93d5954ee0fc03c7382f0a5fa00ea794"
+}
diff --git a/.sqlx/query-9a35fc1feb575cd64b80108cfe8e45e93a069cd593d3acf44ca97f79bbc52a87.json b/.sqlx/query-9a35fc1feb575cd64b80108cfe8e45e93a069cd593d3acf44ca97f79bbc52a87.json
new file mode 100644
index 0000000000..b3beed4e93
--- /dev/null
+++ b/.sqlx/query-9a35fc1feb575cd64b80108cfe8e45e93a069cd593d3acf44ca97f79bbc52a87.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE user_id = $1\n AND left_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = comms_channel_participants.channel_id\n AND ca.kind = 'direct'\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9a35fc1feb575cd64b80108cfe8e45e93a069cd593d3acf44ca97f79bbc52a87"
+}
diff --git a/.sqlx/query-9b6abdc583f9a463731a4cbc970af7c9c71aeca7a6b1b2bba9551a7adc9a84ea.json b/.sqlx/query-9b6abdc583f9a463731a4cbc970af7c9c71aeca7a6b1b2bba9551a7adc9a84ea.json
new file mode 100644
index 0000000000..b8539f0e0d
--- /dev/null
+++ b/.sqlx/query-9b6abdc583f9a463731a4cbc970af7c9c71aeca7a6b1b2bba9551a7adc9a84ea.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT kind, user_id FROM comms_channel_agents WHERE channel_id = $1 AND bot_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "9b6abdc583f9a463731a4cbc970af7c9c71aeca7a6b1b2bba9551a7adc9a84ea"
+}
diff --git a/.sqlx/query-9ed3bfdab7de7ee85a791801a65462bbe31c57fbd9a9d69f9d20ac93c5c49b23.json b/.sqlx/query-9ed3bfdab7de7ee85a791801a65462bbe31c57fbd9a9d69f9d20ac93c5c49b23.json
new file mode 100644
index 0000000000..190c8dc938
--- /dev/null
+++ b/.sqlx/query-9ed3bfdab7de7ee85a791801a65462bbe31c57fbd9a9d69f9d20ac93c5c49b23.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET reply_finalized = TRUE, updated_at = now() WHERE action_id = $1 AND outcome = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9ed3bfdab7de7ee85a791801a65462bbe31c57fbd9a9d69f9d20ac93c5c49b23"
+}
diff --git a/.sqlx/query-a40da8424c1ffca84f7209292da450251b6e5b1a3b73bf179f762e036aa72303.json b/.sqlx/query-a40da8424c1ffca84f7209292da450251b6e5b1a3b73bf179f762e036aa72303.json
new file mode 100644
index 0000000000..4cddf413f1
--- /dev/null
+++ b/.sqlx/query-a40da8424c1ffca84f7209292da450251b6e5b1a3b73bf179f762e036aa72303.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT channel_id, bot_id FROM agent_conversation_sessions WHERE session_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "bot_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "a40da8424c1ffca84f7209292da450251b6e5b1a3b73bf179f762e036aa72303"
+}
diff --git a/.sqlx/query-731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e.json b/.sqlx/query-a4826f9cff8bd3ec6c3fb85601e0d541780aa62437862a0c4eda5a0e273b6212.json
similarity index 78%
rename from .sqlx/query-731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e.json
rename to .sqlx/query-a4826f9cff8bd3ec6c3fb85601e0d541780aa62437862a0c4eda5a0e273b6212.json
index 24565c2680..3bfbfd3cce 100644
--- a/.sqlx/query-731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e.json
+++ b/.sqlx/query-a4826f9cff8bd3ec6c3fb85601e0d541780aa62437862a0c4eda5a0e273b6212.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token_hash = $2\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token_hash = $2\n AND b.deleted_at IS NULL\n -- Its owner or any member of its team can mint a persona's\n -- token, not just the person a direct conversation is with, so\n -- no token posts into one.\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = $1\n AND ca.kind = 'direct'\n )\n ",
"describe": {
"columns": [
{
@@ -67,5 +67,5 @@
false
]
},
- "hash": "731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e"
+ "hash": "a4826f9cff8bd3ec6c3fb85601e0d541780aa62437862a0c4eda5a0e273b6212"
}
diff --git a/.sqlx/query-8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70.json b/.sqlx/query-a815ac8c3cf3171722274a5df090315552e5017c8798813a7f3a504372bffc72.json
similarity index 54%
rename from .sqlx/query-8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70.json
rename to .sqlx/query-a815ac8c3cf3171722274a5df090315552e5017c8798813a7f3a504372bffc72.json
index 8a4d64bd44..045ffdd374 100644
--- a/.sqlx/query-8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70.json
+++ b/.sqlx/query-a815ac8c3cf3171722274a5df090315552e5017c8798813a7f3a504372bffc72.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $2\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = $1\n AND bot_p.left_at IS NULL\n ) AS \"shares!\"\n ",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $2\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = $1\n AND bot_p.left_at IS NULL\n -- Only the persona's owner or team has a conversation with\n -- it, so one never makes it available to anyone.\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = bot_p.channel_id\n AND ca.kind = 'direct'\n )\n ) AS \"shares!\"\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
null
]
},
- "hash": "8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70"
+ "hash": "a815ac8c3cf3171722274a5df090315552e5017c8798813a7f3a504372bffc72"
}
diff --git a/.sqlx/query-3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6.json b/.sqlx/query-a9744da3deba792f9a0d50826e9f8d46ac7c7f53a8e91f6f96c64f95184d7a5b.json
similarity index 74%
rename from .sqlx/query-3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6.json
rename to .sqlx/query-a9744da3deba792f9a0d50826e9f8d46ac7c7f53a8e91f6f96c64f95184d7a5b.json
index 66ff410ef9..f41b7497f8 100644
--- a/.sqlx/query-3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6.json
+++ b/.sqlx/query-a9744da3deba792f9a0d50826e9f8d46ac7c7f53a8e91f6f96c64f95184d7a5b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH active_bot AS (\n SELECT id\n FROM bots\n WHERE id = $2\n AND team_id = $3\n AND deleted_at IS NULL\n )\n SELECT $1::text AS \"source_id!\"\n FROM active_bot\n UNION\n SELECT $3::text\n FROM active_bot\n UNION\n SELECT c.id::text\n FROM active_bot\n JOIN comms_channels c\n ON c.channel_type = 'team'\n AND c.team_id = $3\n UNION\n SELECT cp.channel_id::text\n FROM active_bot\n JOIN comms_channel_participants cp\n ON cp.user_id = $1\n AND cp.left_at IS NULL\n ",
+ "query": "\n WITH active_bot AS (\n SELECT id\n FROM bots\n WHERE id = $2\n AND team_id = $3\n AND deleted_at IS NULL\n )\n SELECT $1::text AS \"source_id!\"\n FROM active_bot\n UNION\n SELECT $3::text\n FROM active_bot\n UNION\n SELECT c.id::text\n FROM active_bot\n JOIN comms_channels c\n ON c.channel_type = 'team'\n AND c.team_id = $3\n UNION\n SELECT cp.channel_id::text\n FROM active_bot\n JOIN comms_channel_participants cp\n ON cp.user_id = $1\n AND cp.left_at IS NULL\n WHERE NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = cp.channel_id\n AND ca.kind = 'direct'\n )\n ",
"describe": {
"columns": [
{
@@ -20,5 +20,5 @@
null
]
},
- "hash": "3011831c1dfeb8361383c40c669485d44eef37d61480954deaea0d00252920a6"
+ "hash": "a9744da3deba792f9a0d50826e9f8d46ac7c7f53a8e91f6f96c64f95184d7a5b"
}
diff --git a/.sqlx/query-c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9.json b/.sqlx/query-b45f8d0e8d7f0a8845aac06dd7372e3edbde634d0b3a349b751cfe3c3ade3bc7.json
similarity index 54%
rename from .sqlx/query-c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9.json
rename to .sqlx/query-b45f8d0e8d7f0a8845aac06dd7372e3edbde634d0b3a349b751cfe3c3ade3bc7.json
index 8097b5691b..e980c3c9bb 100644
--- a/.sqlx/query-c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9.json
+++ b/.sqlx/query-b45f8d0e8d7f0a8845aac06dd7372e3edbde634d0b3a349b751cfe3c3ade3bc7.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE channel_id = $1\n AND user_id = $2\n AND left_at IS NULL\n ",
+ "query": "\n UPDATE comms_channel_participants\n SET left_at = now()\n WHERE channel_id = $1\n AND user_id = $2\n AND left_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = $1\n AND ca.kind = 'direct'\n )\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,5 +11,5 @@
},
"nullable": []
},
- "hash": "c59c1f638ad1ff78414fdb6733442120d6333b8c605f6da5b748951d9561c1f9"
+ "hash": "b45f8d0e8d7f0a8845aac06dd7372e3edbde634d0b3a349b751cfe3c3ade3bc7"
}
diff --git a/.sqlx/query-6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8.json b/.sqlx/query-bade632b66600adeca4f65886e7b0cb5e6c035f1c43f5dfc0604f58bf0c3ad10.json
similarity index 77%
rename from .sqlx/query-6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8.json
rename to .sqlx/query-bade632b66600adeca4f65886e7b0cb5e6c035f1c43f5dfc0604f58bf0c3ad10.json
index 2f998c76e8..04fb469b08 100644
--- a/.sqlx/query-6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8.json
+++ b/.sqlx/query-bade632b66600adeca4f65886e7b0cb5e6c035f1c43f5dfc0604f58bf0c3ad10.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch, list_hidden\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)\n RETURNING\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",
+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch, list_hidden, for_warming\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)\n RETURNING\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",
"describe": {
"columns": [
{
@@ -169,6 +169,7 @@
"Text",
"Jsonb",
"Text",
+ "Bool",
"Bool"
]
},
@@ -204,5 +205,5 @@
null
]
},
- "hash": "6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8"
+ "hash": "bade632b66600adeca4f65886e7b0cb5e6c035f1c43f5dfc0604f58bf0c3ad10"
}
diff --git a/.sqlx/query-c0b793d87d408b1c1aec73c08bc9ed0ed8f4dd44b257f3c6453c653529512255.json b/.sqlx/query-c0b793d87d408b1c1aec73c08bc9ed0ed8f4dd44b257f3c6453c653529512255.json
new file mode 100644
index 0000000000..144b183165
--- /dev/null
+++ b/.sqlx/query-c0b793d87d408b1c1aec73c08bc9ed0ed8f4dd44b257f3c6453c653529512255.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', 'macro|[email protected]')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c0b793d87d408b1c1aec73c08bc9ed0ed8f4dd44b257f3c6453c653529512255"
+}
diff --git a/.sqlx/query-c20095da73137cb399bc67743a604447f7fabdd45a77ab42ba4fb5974283683a.json b/.sqlx/query-c20095da73137cb399bc67743a604447f7fabdd45a77ab42ba4fb5974283683a.json
new file mode 100644
index 0000000000..33018af972
--- /dev/null
+++ b/.sqlx/query-c20095da73137cb399bc67743a604447f7fabdd45a77ab42ba4fb5974283683a.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 44)) AS \"claimed!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "claimed!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c20095da73137cb399bc67743a604447f7fabdd45a77ab42ba4fb5974283683a"
+}
diff --git a/.sqlx/query-c27e5909f365e2006330835a166b6191ba444956cbae6214cec99aa774235a29.json b/.sqlx/query-c27e5909f365e2006330835a166b6191ba444956cbae6214cec99aa774235a29.json
new file mode 100644
index 0000000000..2d28e743eb
--- /dev/null
+++ b/.sqlx/query-c27e5909f365e2006330835a166b6191ba444956cbae6214cec99aa774235a29.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT to_jsonb(j) AS \"value!\" FROM agent_conversation_turns j WHERE action_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "value!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c27e5909f365e2006330835a166b6191ba444956cbae6214cec99aa774235a29"
+}
diff --git a/.sqlx/query-c82d37f9704b0c2d6c5efc51441447cfc0471991d3e9284432c49235b68fc5ac.json b/.sqlx/query-c82d37f9704b0c2d6c5efc51441447cfc0471991d3e9284432c49235b68fc5ac.json
new file mode 100644
index 0000000000..dc9666a7ff
--- /dev/null
+++ b/.sqlx/query-c82d37f9704b0c2d6c5efc51441447cfc0471991d3e9284432c49235b68fc5ac.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channel_participants (channel_id, user_id, role)\n VALUES ($1, $2, 'owner'), ($1, $3, 'member')\n ON CONFLICT (channel_id, user_id) DO UPDATE SET left_at = NULL",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c82d37f9704b0c2d6c5efc51441447cfc0471991d3e9284432c49235b68fc5ac"
+}
diff --git a/.sqlx/query-c9e8001e4e31c820031aee2112504838a1072a54f10a924fb86ff126884edbd2.json b/.sqlx/query-c9e8001e4e31c820031aee2112504838a1072a54f10a924fb86ff126884edbd2.json
new file mode 100644
index 0000000000..b2814e8f3f
--- /dev/null
+++ b/.sqlx/query-c9e8001e4e31c820031aee2112504838a1072a54f10a924fb86ff126884edbd2.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_session SET for_warming = TRUE, created_at = NOW() - INTERVAL '11 minutes' WHERE id = ANY($1)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c9e8001e4e31c820031aee2112504838a1072a54f10a924fb86ff126884edbd2"
+}
diff --git a/.sqlx/query-ce76493fd9a427da2fbbbefffd0dc64b0f0ec32cdb5854549fe84564f9d883cf.json b/.sqlx/query-ce76493fd9a427da2fbbbefffd0dc64b0f0ec32cdb5854549fe84564f9d883cf.json
new file mode 100644
index 0000000000..6f2bf37a4e
--- /dev/null
+++ b/.sqlx/query-ce76493fd9a427da2fbbbefffd0dc64b0f0ec32cdb5854549fe84564f9d883cf.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_try_advisory_xact_lock(hashtextextended($1, 43)) AS \"claimed!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "claimed!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "ce76493fd9a427da2fbbbefffd0dc64b0f0ec32cdb5854549fe84564f9d883cf"
+}
diff --git a/.sqlx/query-ce93bf3cf294861cbb88736d17b2cd93b771a56d8a00066bbdd2622c0b2e2dde.json b/.sqlx/query-ce93bf3cf294861cbb88736d17b2cd93b771a56d8a00066bbdd2622c0b2e2dde.json
new file mode 100644
index 0000000000..bd0eb70a82
--- /dev/null
+++ b/.sqlx/query-ce93bf3cf294861cbb88736d17b2cd93b771a56d8a00066bbdd2622c0b2e2dde.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO agent_session (id, list_hidden) VALUES ($1, TRUE)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ce93bf3cf294861cbb88736d17b2cd93b771a56d8a00066bbdd2622c0b2e2dde"
+}
diff --git a/.sqlx/query-cefb6680898e9aa8762d86a8e29f0ba3e976c69c2cdcdddeac79a4afdf9a19b1.json b/.sqlx/query-cefb6680898e9aa8762d86a8e29f0ba3e976c69c2cdcdddeac79a4afdf9a19b1.json
new file mode 100644
index 0000000000..6ecce946a8
--- /dev/null
+++ b/.sqlx/query-cefb6680898e9aa8762d86a8e29f0ba3e976c69c2cdcdddeac79a4afdf9a19b1.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role)\n VALUES ($1, $2, 'owner'), ($1, $3, 'member')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cefb6680898e9aa8762d86a8e29f0ba3e976c69c2cdcdddeac79a4afdf9a19b1"
+}
diff --git a/.sqlx/query-d0637875bf74b4073e8f0bb9ad0b91436fce3a06baeec244e008f6e5a4e254ac.json b/.sqlx/query-d0637875bf74b4073e8f0bb9ad0b91436fce3a06baeec244e008f6e5a4e254ac.json
new file mode 100644
index 0000000000..2c138156d0
--- /dev/null
+++ b/.sqlx/query-d0637875bf74b4073e8f0bb9ad0b91436fce3a06baeec244e008f6e5a4e254ac.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_agents\n WHERE channel_id = $1\n AND kind = 'direct'\n ) AS \"direct!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "direct!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d0637875bf74b4073e8f0bb9ad0b91436fce3a06baeec244e008f6e5a4e254ac"
+}
diff --git a/.sqlx/query-d682c265a2915d4ad19ba86e2b6259577ac7154d3645f62261a22b6a2673c82f.json b/.sqlx/query-d682c265a2915d4ad19ba86e2b6259577ac7154d3645f62261a22b6a2673c82f.json
new file mode 100644
index 0000000000..62f1845eda
--- /dev/null
+++ b/.sqlx/query-d682c265a2915d4ad19ba86e2b6259577ac7154d3645f62261a22b6a2673c82f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (\n SELECT 1\n FROM agent_conversation_sessions session\n JOIN comms_channel_agents agent\n ON agent.channel_id = session.channel_id\n AND agent.bot_id = session.bot_id\n WHERE session.session_id = $1\n AND agent.kind = 'direct'\n ) AS \"private!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "private!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d682c265a2915d4ad19ba86e2b6259577ac7154d3645f62261a22b6a2673c82f"
+}
diff --git a/.sqlx/query-d75444605f983e6b089e15c5faef423037545c37c3b834873a8c6e1fe37194bd.json b/.sqlx/query-d75444605f983e6b089e15c5faef423037545c37c3b834873a8c6e1fe37194bd.json
new file mode 100644
index 0000000000..1264b3873c
--- /dev/null
+++ b/.sqlx/query-d75444605f983e6b089e15c5faef423037545c37c3b834873a8c6e1fe37194bd.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM agent_conversation_sessions\n WHERE session_id = $1\n AND is_current\n ) AS \"current!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "current!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d75444605f983e6b089e15c5faef423037545c37c3b834873a8c6e1fe37194bd"
+}
diff --git a/.sqlx/query-0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf.json b/.sqlx/query-d7b2cfb8b621bcc7ad3701d8497a8a7eba21daeec38b657bc633d95c5aee8419.json
similarity index 61%
rename from .sqlx/query-0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf.json
rename to .sqlx/query-d7b2cfb8b621bcc7ad3701d8497a8a7eba21daeec38b657bc633d95c5aee8419.json
index d391d7fbd9..36a4e844a6 100644
--- a/.sqlx/query-0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf.json
+++ b/.sqlx/query-d7b2cfb8b621bcc7ad3701d8497a8a7eba21daeec38b657bc633d95c5aee8419.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT COUNT(DISTINCT channel_id) = CARDINALITY($2::uuid[]) AS \"has_channels!\"\n FROM comms_channel_participants\n WHERE user_id = $1\n AND channel_id = ANY($2::uuid[])\n AND left_at IS NULL\n ",
+ "query": "\n SELECT COUNT(DISTINCT channel_id) = CARDINALITY($2::uuid[]) AS \"has_channels!\"\n FROM comms_channel_participants\n WHERE user_id = $1\n AND channel_id = ANY($2::uuid[])\n AND left_at IS NULL\n AND NOT EXISTS (\n SELECT 1\n FROM comms_channel_agents ca\n WHERE ca.channel_id = comms_channel_participants.channel_id\n AND ca.kind = 'direct'\n )\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
null
]
},
- "hash": "0aaaba3111fe6ff913eb51c07dcd894a1bd0804cc7060492993e56a4315939bf"
+ "hash": "d7b2cfb8b621bcc7ad3701d8497a8a7eba21daeec38b657bc633d95c5aee8419"
}
diff --git a/.sqlx/query-d863607e97975b7ccf9fe4258efbfd964913639f86f24a632ab457fbf2c6d440.json b/.sqlx/query-d863607e97975b7ccf9fe4258efbfd964913639f86f24a632ab457fbf2c6d440.json
new file mode 100644
index 0000000000..73260c1220
--- /dev/null
+++ b/.sqlx/query-d863607e97975b7ccf9fe4258efbfd964913639f86f24a632ab457fbf2c6d440.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS (SELECT 1 FROM agent_conversation_sessions WHERE session_id = $1) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d863607e97975b7ccf9fe4258efbfd964913639f86f24a632ab457fbf2c6d440"
+}
diff --git a/.sqlx/query-da42fe8424a1a54772f946fd5970c040a23eebe497e4ca345e41155b3aca20cd.json b/.sqlx/query-da42fe8424a1a54772f946fd5970c040a23eebe497e4ca345e41155b3aca20cd.json
new file mode 100644
index 0000000000..3b112191ce
--- /dev/null
+++ b/.sqlx/query-da42fe8424a1a54772f946fd5970c040a23eebe497e4ca345e41155b3aca20cd.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS(SELECT 1 FROM agent_conversation_sessions session JOIN comms_channel_agents agent ON agent.channel_id = session.channel_id AND agent.bot_id = session.bot_id WHERE session.session_id = $1 AND agent.kind = 'direct') AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "da42fe8424a1a54772f946fd5970c040a23eebe497e4ca345e41155b3aca20cd"
+}
diff --git a/.sqlx/query-e68df410e8c754e22adfb0dc34a3dde12e50dbb34ff47ed23c029c728b7f2e34.json b/.sqlx/query-e68df410e8c754e22adfb0dc34a3dde12e50dbb34ff47ed23c029c728b7f2e34.json
new file mode 100644
index 0000000000..fe1a1c7596
--- /dev/null
+++ b/.sqlx/query-e68df410e8c754e22adfb0dc34a3dde12e50dbb34ff47ed23c029c728b7f2e34.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET state = 'stopped', outcome = $2, updated_at = now() WHERE session_id = $1 AND state = 'queued'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e68df410e8c754e22adfb0dc34a3dde12e50dbb34ff47ed23c029c728b7f2e34"
+}
diff --git a/.sqlx/query-e737ee437f8be0aa00bb5a4592697cc624ceb697a25a9f3d35016af86f61f48e.json b/.sqlx/query-e737ee437f8be0aa00bb5a4592697cc624ceb697a25a9f3d35016af86f61f48e.json
new file mode 100644
index 0000000000..6e35414580
--- /dev/null
+++ b/.sqlx/query-e737ee437f8be0aa00bb5a4592697cc624ceb697a25a9f3d35016af86f61f48e.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET action_id = $4, state = 'queued', in_flight = NULL, outcome = NULL, reply_segments = NULL, reply_finalized = FALSE, updated_at = now() WHERE source_message_id = $1 AND bot_id = $2 AND action_id = $3 AND state IN ('failed', 'stopped', 'interrupted') AND (reply_finalized OR in_flight->>'announcement_message_id' IS NULL)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e737ee437f8be0aa00bb5a4592697cc624ceb697a25a9f3d35016af86f61f48e"
+}
diff --git a/.sqlx/query-e7d9a5377b8def1cefefb93a4ae2d9096244a5c73f22e762ed9948bf85fede11.json b/.sqlx/query-e7d9a5377b8def1cefefb93a4ae2d9096244a5c73f22e762ed9948bf85fede11.json
new file mode 100644
index 0000000000..1f3d8e2e2b
--- /dev/null
+++ b/.sqlx/query-e7d9a5377b8def1cefefb93a4ae2d9096244a5c73f22e762ed9948bf85fede11.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET in_flight = $2, updated_at = now() WHERE action_id = $1 AND state IN ('succeeded', 'failed', 'stopped', 'interrupted') AND NOT reply_finalized AND in_flight = $3",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e7d9a5377b8def1cefefb93a4ae2d9096244a5c73f22e762ed9948bf85fede11"
+}
diff --git a/.sqlx/query-f123268007a8acb85f3b814a45e2d2c805d5cff982ad757b20ebfe0bb8de1e81.json b/.sqlx/query-f123268007a8acb85f3b814a45e2d2c805d5cff982ad757b20ebfe0bb8de1e81.json
new file mode 100644
index 0000000000..d38f97f3b7
--- /dev/null
+++ b/.sqlx/query-f123268007a8acb85f3b814a45e2d2c805d5cff982ad757b20ebfe0bb8de1e81.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channel_agents (channel_id, bot_id, kind, user_id) VALUES ($1, $2, 'direct', $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f123268007a8acb85f3b814a45e2d2c805d5cff982ad757b20ebfe0bb8de1e81"
+}
diff --git a/.sqlx/query-f2066d90d503b352bf386963645b94456e1174c5f648ac23293672f02faffd40.json b/.sqlx/query-f2066d90d503b352bf386963645b94456e1174c5f648ac23293672f02faffd40.json
new file mode 100644
index 0000000000..c84fab90cf
--- /dev/null
+++ b/.sqlx/query-f2066d90d503b352bf386963645b94456e1174c5f648ac23293672f02faffd40.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT session_id, created_at, is_current FROM agent_conversation_sessions WHERE channel_id = $1 AND bot_id = $2 ORDER BY created_at, session_id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "is_current",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "f2066d90d503b352bf386963645b94456e1174c5f648ac23293672f02faffd40"
+}
diff --git a/.sqlx/query-f33da26f420babbff3375780082a8bd96742f487982293b97d2871a9bafd52e2.json b/.sqlx/query-f33da26f420babbff3375780082a8bd96742f487982293b97d2871a9bafd52e2.json
new file mode 100644
index 0000000000..2a17fbf682
--- /dev/null
+++ b/.sqlx/query-f33da26f420babbff3375780082a8bd96742f487982293b97d2871a9bafd52e2.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_conversation_turns SET in_flight = $2, updated_at = now() WHERE action_id = $1 AND state = 'running'",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f33da26f420babbff3375780082a8bd96742f487982293b97d2871a9bafd52e2"
+}
diff --git a/.sqlx/query-f416ef3e59ce497f28744d1e8c6dc8b1ccaa6f1109eef524f5c5576434482ce4.json b/.sqlx/query-f416ef3e59ce497f28744d1e8c6dc8b1ccaa6f1109eef524f5c5576434482ce4.json
new file mode 100644
index 0000000000..a75c2995e0
--- /dev/null
+++ b/.sqlx/query-f416ef3e59ce497f28744d1e8c6dc8b1ccaa6f1109eef524f5c5576434482ce4.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM comms_channel_participants WHERE channel_id = $1 AND left_at IS NULL",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "f416ef3e59ce497f28744d1e8c6dc8b1ccaa6f1109eef524f5c5576434482ce4"
+}
diff --git a/.sqlx/query-f72b19d4ac7b804f3a816e55582dbec391bb4e1de853474cf6642ed8319c0276.json b/.sqlx/query-f72b19d4ac7b804f3a816e55582dbec391bb4e1de853474cf6642ed8319c0276.json
deleted file mode 100644
index 298262b74d..0000000000
--- a/.sqlx/query-f72b19d4ac7b804f3a816e55582dbec391bb4e1de853474cf6642ed8319c0276.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE agent_session SET status = 'disconnected'\n WHERE id IN (\n SELECT id FROM agent_session\n WHERE list_hidden AND thread_id IS NULL\n AND created_at <= NOW() - INTERVAL '10 minutes'\n ORDER BY created_at LIMIT 64 FOR UPDATE SKIP LOCKED\n ) RETURNING id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- false
- ]
- },
- "hash": "f72b19d4ac7b804f3a816e55582dbec391bb4e1de853474cf6642ed8319c0276"
-}
diff --git a/.sqlx/query-f92eea9350f4bcdd48c6755491b92ba918c2259503099712747bd7f18d80a66a.json b/.sqlx/query-f92eea9350f4bcdd48c6755491b92ba918c2259503099712747bd7f18d80a66a.json
new file mode 100644
index 0000000000..f735d0fcf6
--- /dev/null
+++ b/.sqlx/query-f92eea9350f4bcdd48c6755491b92ba918c2259503099712747bd7f18d80a66a.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE agent_session SET list_hidden = FALSE WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f92eea9350f4bcdd48c6755491b92ba918c2259503099712747bd7f18d80a66a"
+}
diff --git a/.sqlx/query-f9a5d3c291386c430cf997762a6bca3730901a18d73fe8c5ac86c3d9aff05ae6.json b/.sqlx/query-f9a5d3c291386c430cf997762a6bca3730901a18d73fe8c5ac86c3d9aff05ae6.json
new file mode 100644
index 0000000000..083edc04c2
--- /dev/null
+++ b/.sqlx/query-f9a5d3c291386c430cf997762a6bca3730901a18d73fe8c5ac86c3d9aff05ae6.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM comms_channels WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f9a5d3c291386c430cf997762a6bca3730901a18d73fe8c5ac86c3d9aff05ae6"
+}
diff --git a/.sqlx/query-fbf3f27753d1ef4317be3d51ec9f6a8b49d369d20e8e27b4eaadb6f93ff5bb70.json b/.sqlx/query-fbf3f27753d1ef4317be3d51ec9f6a8b49d369d20e8e27b4eaadb6f93ff5bb70.json
new file mode 100644
index 0000000000..3de27e0ed8
--- /dev/null
+++ b/.sqlx/query-fbf3f27753d1ef4317be3d51ec9f6a8b49d369d20e8e27b4eaadb6f93ff5bb70.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_channels (id, channel_type, owner_id)\n VALUES ($1, 'direct_message', $2)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fbf3f27753d1ef4317be3d51ec9f6a8b49d369d20e8e27b4eaadb6f93ff5bb70"
+}
diff --git a/Cargo.lock b/Cargo.lock
index d398d53408..07414e62ec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -342,6 +342,7 @@ dependencies = [
"axum",
"base64 0.22.1",
"bot_id",
+ "bots",
"channel_sender",
"channels",
"chrono",
@@ -354,12 +355,15 @@ dependencies = [
"documents",
"entity_access",
"entity_access_db_utils",
+ "entity_registry",
+ "entity_registry_db_utils",
"futures",
"github",
"harness_id",
"kafka_util",
"lexical_client",
"macro_authorization",
+ "macro_db_migrator",
"macro_env_var",
"macro_event_broker",
"macro_tower_layers",
@@ -6262,6 +6266,7 @@ dependencies = [
"anyhow",
"async-graphql",
"async-graphql-axum",
+ "async-trait",
"authentication_service_client",
"aws-sdk-dynamodb",
"aws-sdk-s3",
diff --git a/apps/web/src/features/agent-activity/agent-activity.test.tsx b/apps/web/src/features/agent-activity/agent-activity.test.tsx
new file mode 100644
index 0000000000..63393ced9d
--- /dev/null
+++ b/apps/web/src/features/agent-activity/agent-activity.test.tsx
@@ -0,0 +1,180 @@
+import type { AgentActivityRow } from '@macro-inc/lexical-core';
+import type {
+ ActivityRow,
+ FoldedMessage,
+} from '@service-agent-fold/generated/types';
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+
+const live = vi.hoisted(() => ({ acquired: [] as (string | undefined)[] }));
+const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
+vi.mock('./queries/live-session', () => ({
+ createLiveSession: (id: () => string | undefined) => {
+ live.acquired.push(id());
+ return { messages };
+ },
+}));
+vi.mock('@app/features/block-agent/ui', () => ({
+ TextShimmer: (props: { text: string }) => <>{props.text}</>,
+}));
+
+import { AgentActivity } from './agent-activity';
+
+afterEach(() => {
+ cleanup();
+ live.acquired.length = 0;
+ setMessages([]);
+});
+
+const snapshot: AgentActivityRow[] = [
+ { id: 't1', label: 'Running', detail: 'cargo', status: 'running' },
+];
+
+function reply(rows: ActivityRow[]): FoldedMessage {
+ return {
+ agentSessionId: 'session',
+ turn: 2,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts: [],
+ stop: null,
+ pending: false,
+ segments: [
+ { index: 0, kind: 'prose', start: 0, end: 1, sealed: true, rows: [] },
+ { index: 1, kind: 'activity', start: 1, end: 3, sealed: false, rows },
+ ],
+ phase: 'working',
+ };
+}
+
+const steps = (view: ReturnType<typeof render>) =>
+ view
+ .getAllByRole('listitem')
+ .map((item) => [item.textContent, item.dataset.status]);
+
+it('shows a sealed run as the snapshot the message carries, without the session', () => {
+ const view = render(() => (
+ <AgentActivity
+ agentSessionId="session"
+ turn={2}
+ segment={1}
+ rows={[{ id: 't1', label: 'Ran', detail: 'cargo', status: 'completed' }]}
+ sealed
+ />
+ ));
+ expect(steps(view)).toEqual([['Rancargo', 'completed']]);
+ expect(live.acquired).toEqual([]);
+});
+
+it('ticks an open run live from the session, keeping the snapshot until it loads', () => {
+ const view = render(() => (
+ <AgentActivity
+ agentSessionId="session"
+ turn={2}
+ segment={1}
+ rows={snapshot}
+ sealed={false}
+ />
+ ));
+ expect(live.acquired).toEqual(['session']);
+ expect(steps(view)).toEqual([['Runningcargo', 'running']]);
+
+ setMessages([
+ reply([
+ { id: 't1', label: 'Ran', detail: 'cargo', status: 'completed' },
+ { id: 't2', label: 'Reading', detail: 'lib.rs', status: 'running' },
+ ]),
+ ]);
+ expect(steps(view)).toEqual([
+ ['Rancargo', 'completed'],
+ ['Readinglib.rs', 'running'],
+ ]);
+});
+
+it('folds a long run behind a count of its earlier steps', () => {
+ const rows = Array.from({ length: 8 }, (_, index) => ({
+ id: `t${index}`,
+ label: `Step ${index}`,
+ status: 'completed' as const,
+ }));
+ const view = render(() => (
+ <AgentActivity
+ agentSessionId="session"
+ turn={2}
+ segment={1}
+ rows={rows}
+ sealed
+ />
+ ));
+ expect(view.getByRole('button', { name: '2 earlier steps' })).toBeTruthy();
+ expect(view.queryByText('Step 1')).toBeNull();
+ view.getByRole('button', { name: '2 earlier steps' }).click();
+ expect(view.getByText('Step 1')).toBeTruthy();
+});
+
+it('updates a live row in place as the run paints, rather than redrawing it', () => {
+ const view = render(() => (
+ <AgentActivity
+ agentSessionId="session"
+ turn={2}
+ segment={1}
+ rows={snapshot}
+ sealed={false}
+ />
+ ));
+ setMessages([
+ reply([{ id: 't1', label: 'Running', detail: 'cargo', status: 'running' }]),
+ ]);
+ const row = view.getByRole('listitem');
+
+ // Every paint carries the run as new objects.
+ setMessages([
+ reply([{ id: 't1', label: 'Running', detail: 'cargo', status: 'running' }]),
+ ]);
+ expect(view.getByRole('listitem')).toBe(row);
+
+ setMessages([
+ reply([
+ { id: 't1', label: 'Ran', detail: 'cargo', status: 'completed' },
+ { id: 't2', label: 'Reading', detail: 'lib.rs', status: 'running' },
+ ]),
+ ]);
+ expect(view.getAllByRole('listitem')[0]).toBe(row);
+ expect(steps(view)).toEqual([
+ ['Rancargo', 'completed'],
+ ['Readinglib.rs', 'running'],
+ ]);
+});
+
+it('keeps snapshots free of tool details while authorized live rows retain them', () => {
+ const safe = [{ id: 't1', label: 'Ran', status: 'completed' as const }];
+ const snapshotView = render(() => (
+ <AgentActivity
+ agentSessionId="private-session"
+ turn={2}
+ segment={1}
+ rows={safe}
+ sealed
+ />
+ ));
+ expect(snapshotView.getByRole('listitem').textContent).toBe('Ran');
+ expect(live.acquired).toEqual([]);
+ snapshotView.unmount();
+ const liveView = render(() => (
+ <AgentActivity
+ agentSessionId="private-session"
+ turn={2}
+ segment={1}
+ rows={safe}
+ sealed={false}
+ />
+ ));
+ expect(liveView.getByRole('listitem').textContent).toBe('Ran');
+ setMessages([
+ reply([{ ...safe[0], detail: 'TOKEN=private-value run-report' }]),
+ ]);
+ expect(liveView.getByRole('listitem').textContent).toBe(
+ 'RanTOKEN=private-value run-report'
+ );
+});
diff --git a/apps/web/src/features/agent-activity/agent-activity.tsx b/apps/web/src/features/agent-activity/agent-activity.tsx
new file mode 100644
index 0000000000..6a4b3eb884
--- /dev/null
+++ b/apps/web/src/features/agent-activity/agent-activity.tsx
@@ -0,0 +1,33 @@
+import type { AgentActivityData } from '@macro-inc/lexical-core';
+import { Show } from 'solid-js';
+import { ActivityRows } from './components/activity-rows';
+import { replyToTurn, segmentRows } from './core/live-reply';
+import { createLiveSession } from './queries/live-session';
+
+/**
+ * The steps of an agent's reply inside a channel message.
+ *
+ * Live while the run of steps is still open, from the session's own fold, so
+ * a step ticks from running to done where it was posted. Once the run seals,
+ * or for a viewer who cannot read the session, the snapshot the server wrote
+ * into the message keeps the status and label. Raw commands and tool-input
+ * details are available only in the authorized live session view.
+ */
+export function AgentActivity(props: AgentActivityData) {
+ return (
+ <div class="min-w-0 max-w-full" data-agent-activity={props.agentSessionId}>
+ <Show when={!props.sealed} fallback={<ActivityRows rows={props.rows} />}>
+ <LiveActivity {...props} />
+ </Show>
+ </div>
+ );
+}
+
+function LiveActivity(props: AgentActivityData) {
+ const live = createLiveSession(() => props.agentSessionId);
+ const rows = () => {
+ const reply = replyToTurn(live.messages(), props.turn);
+ return (reply && segmentRows(reply, props.segment)) ?? props.rows;
+ };
+ return <ActivityRows rows={rows()} />;
+}
diff --git a/apps/web/src/features/agent-activity/agent-typing.test.tsx b/apps/web/src/features/agent-activity/agent-typing.test.tsx
new file mode 100644
index 0000000000..aaa1b5664c
--- /dev/null
+++ b/apps/web/src/features/agent-activity/agent-typing.test.tsx
@@ -0,0 +1,347 @@
+import type {
+ FoldedMessage,
+ SessionMetadata,
+} from '@service-agent-fold/generated/types';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ waitFor,
+ within,
+} from '@solidjs/testing-library';
+import { ok } from 'neverthrow';
+import { createSignal, For, type JSX, Show } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ issue: vi.fn(),
+ failure: vi.fn(),
+ canEdit: true,
+ profileLoading: false,
+ liveSessions: 0,
+ cards: 0,
+}));
+const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
+const [metadata, setMetadata] = createSignal<SessionMetadata>();
+const [loaded, setLoaded] = createSignal(true);
+vi.mock('./queries/live-session', () => ({
+ createLiveSession: () => {
+ mocks.liveSessions += 1;
+ return {
+ messages,
+ metadata,
+ loaded,
+ failed: () => false,
+ retry: vi.fn(),
+ issue: mocks.issue,
+ };
+ },
+}));
+vi.mock('@queries/agent-session/session', () => ({
+ useAgentSessionQuery: () => ({
+ isPending: false,
+ data: { canEdit: mocks.canEdit },
+ }),
+}));
+vi.mock('@queries/bots/profiles', () => ({
+ useBotProfile: () =>
+ mocks.profileLoading
+ ? { isPending: true, isError: false, data: undefined }
+ : {
+ isPending: false,
+ isError: false,
+ data: { name: 'Researcher', avatarUrl: undefined, deleted: false },
+ },
+}));
+vi.mock('@app/features/agent-dms/components/persona-avatar', () => ({
+ PersonaAvatar: () => null,
+}));
+vi.mock('@app/features/agent-interactions/components/InteractionCard', () => ({
+ InteractionCard: (props: { request: { requestId: string } }) => {
+ mocks.cards += 1;
+ return (
+ <section aria-label="Question">
+ {props.request.requestId}
+ <input aria-label="Answer" />
+ </section>
+ );
+ },
+}));
+vi.mock(
+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
+ () => ({
+ StaticMarkdown: (props: { markdown: string }) => <p>{props.markdown}</p>,
+ })
+);
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.failure },
+}));
+vi.mock('@ui', () => ({
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+
+import {
+ publishSessionTurn,
+ resetSessionTurns,
+} from '@core/agent-session/session-turn';
+import {
+ clearTypingIndicators,
+ getTypingAgents,
+ handleCommsTyping,
+ TYPING_INDICATOR_TIMEOUT_MS,
+} from '@queries/messages/typing';
+import { AgentTyping, AgentTypingProvider } from './agent-typing';
+
+const parent = { type: 'channel', id: 'dm' } as const;
+const BOT = 'bot|0a8f5e1c-2b3d-4e5f-8a9b-0c1d2e3f4a5b';
+
+function typing(phase: 'thinking' | 'working' | 'waiting') {
+ handleCommsTyping(
+ {
+ action: 'start',
+ parent,
+ user_id: BOT,
+ thread_id: null,
+ agent: { session_id: 'session', phase },
+ },
+ );
+}
+
+function writing(text: string): FoldedMessage {
+ return {
+ agentSessionId: 'session',
+ turn: 1,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts: [{ kind: 'text', text }],
+ stop: null,
+ pending: false,
+ segments: [
+ { index: 0, kind: 'prose', start: 0, end: 1, sealed: false, rows: [] },
+ ],
+ phase: 'writing',
+ };
+}
+
+/** The fold's metadata with one question on turn 1, as a new object each time. */
+function asking(requestId: string): SessionMetadata {
+ return {
+ turn: 'blocked',
+ pendingInteractions: [
+ {
+ kind: 'elicitation',
+ turn: 1,
+ requestId,
+ toolCall: null,
+ message: 'Which branch?',
+ request: { kind: 'form', schema: {} },
+ },
+ ],
+ } as unknown as SessionMetadata;
+}
+
+beforeEach(() => {
+ clearTypingIndicators();
+ mocks.canEdit = true;
+ mocks.profileLoading = false;
+ mocks.liveSessions = 0;
+ mocks.cards = 0;
+ mocks.issue.mockResolvedValue(ok({}));
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ resetSessionTurns();
+ setMessages([]);
+ setMetadata(undefined);
+ setLoaded(true);
+});
+
+it('shows an agent typing with what it is doing, and nothing for people', () => {
+ handleCommsTyping(
+ { action: 'start', parent, user_id: 'macro|[email protected]' },
+ );
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ expect(view.queryByRole('status')).toBeNull();
+
+ typing('thinking');
+ expect(view.getByRole('status').textContent).toContain(
+ 'Researcher is thinking'
+ );
+ typing('working');
+ expect(view.getByRole('status').textContent).toContain(
+ 'Researcher is working'
+ );
+});
+
+it('streams the unfinished passage beneath and stops the turn', async () => {
+ typing('thinking');
+ setMessages([writing('Looking at the failing test')]);
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ expect(view.getByText('Looking at the failing test')).toBeTruthy();
+
+ await fireEvent.click(view.getByRole('button', { name: 'Stop' }));
+ await waitFor(() =>
+ expect(mocks.issue).toHaveBeenCalledWith({ type: 'stop' })
+ );
+});
+
+it('allows Stop to be retried after its request rejects', async () => {
+ typing('working');
+ setMessages([writing('Partial')]);
+ mocks.issue.mockRejectedValueOnce(new Error('Disconnected'));
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ const stop = view.getByRole<HTMLButtonElement>('button', { name: 'Stop' });
+
+ await fireEvent.click(stop);
+ await waitFor(() => {
+ expect(mocks.failure).toHaveBeenCalledWith(
+ 'The agent could not be stopped'
+ );
+ expect(stop.disabled).toBe(false);
+ });
+ await fireEvent.click(stop);
+ await waitFor(() => expect(mocks.issue).toHaveBeenCalledTimes(2));
+});
+
+it('puts a question for the running turn under the row', () => {
+ typing('waiting');
+ setMessages([writing('')]);
+ setMetadata({
+ turn: 'running',
+ pendingInteractions: [
+ {
+ kind: 'elicitation',
+ turn: 1,
+ requestId: 'ask-1',
+ toolCall: null,
+ message: 'Which branch?',
+ request: { kind: 'form', schema: {} },
+ },
+ {
+ kind: 'elicitation',
+ turn: 0,
+ requestId: 'stale',
+ toolCall: null,
+ message: 'Old',
+ request: { kind: 'form', schema: {} },
+ },
+ ],
+ } as unknown as SessionMetadata);
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ expect(
+ view.getAllByRole('region', { name: 'Question' }).map((q) => q.textContent)
+ ).toEqual(['ask-1']);
+});
+
+it('offers no Stop to a viewer who cannot drive the session', () => {
+ mocks.canEdit = false;
+ typing('working');
+ setMessages([writing('Partial')]);
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ expect(view.queryByRole('button', { name: 'Stop' })).toBeNull();
+});
+
+it('names nobody until the persona is known, rather than a placeholder', () => {
+ mocks.profileLoading = true;
+ typing('thinking');
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ expect(view.getByRole('status').textContent).toBe('...');
+});
+
+it('keeps a card as it was left through a metadata event that resends it', () => {
+ typing('waiting');
+ setMessages([writing('')]);
+ setMetadata(asking('ask-1'));
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ const answer = view.getByRole<HTMLInputElement>('textbox', {
+ name: 'Answer',
+ });
+ answer.value = 'main';
+ setMetadata(asking('ask-1'));
+ expect(view.getByRole('textbox', { name: 'Answer' })).toBe(answer);
+ expect(answer.value).toBe('main');
+ expect(mocks.cards).toBe(1);
+});
+
+it('moves the live turn with the newest row rather than starting it over', () => {
+ typing('waiting');
+ setMessages([writing('')]);
+ setMetadata(asking('ask-1'));
+ const [newest, setNewest] = createSignal<string>('first');
+ const view = render(() => (
+ <AgentTypingProvider parent={parent} threadId={null}>
+ <For each={['first', 'second']}>
+ {(row) => (
+ <div data-testid={row}>
+ <Show when={newest() === row}>
+ <AgentTyping parent={parent} threadId={null} />
+ </Show>
+ </div>
+ )}
+ </For>
+ {/* Another place makes its own rows; nothing types there. */}
+ <div data-testid="thread">
+ <AgentTyping parent={parent} threadId="thread" />
+ </div>
+ </AgentTypingProvider>
+ ));
+ const answer = within(view.getByTestId('first')).getByRole<HTMLInputElement>(
+ 'textbox',
+ { name: 'Answer' }
+ );
+ answer.value = 'main';
+
+ // A message arrives below, so the next row is the newest.
+ setNewest('second');
+ expect(
+ within(view.getByTestId('second')).getByRole('textbox', { name: 'Answer' })
+ ).toBe(answer);
+ // The reader scrolls away, and the virtualized row unmounts, then back.
+ setNewest('');
+ expect(view.queryByRole('textbox', { name: 'Answer' })).toBeNull();
+ setNewest('second');
+ expect(view.getByRole('textbox', { name: 'Answer' })).toBe(answer);
+
+ expect(answer.value).toBe('main');
+ expect(mocks.cards).toBe(1);
+ expect(mocks.liveSessions).toBe(1);
+ expect(within(view.getByTestId('thread')).queryByRole('status')).toBeNull();
+});
+
+it('keeps the row of a turn waiting on the viewer after its typing lapses', () => {
+ vi.useFakeTimers();
+ typing('waiting');
+ setMessages([writing('')]);
+ setMetadata(asking('ask-1'));
+ publishSessionTurn('session', 'blocked');
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ const answer = view.getByRole('textbox', { name: 'Answer' });
+
+ // No heartbeat for a while, as when a phone sleeps with the app open.
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS);
+ expect(getTypingAgents(parent, null).size).toBe(0);
+ expect(view.getByRole('status').textContent).toContain(
+ 'Researcher is waiting for an answer'
+ );
+ expect(view.getByRole('textbox', { name: 'Answer' })).toBe(answer);
+
+ // The turn ends, and the row goes with it.
+ publishSessionTurn('session', 'idle');
+ expect(view.queryByRole('status')).toBeNull();
+});
+
+it('lets a lapsed typing go when the fold has no turn open', () => {
+ vi.useFakeTimers();
+ typing('thinking');
+ const view = render(() => <AgentTyping parent={parent} threadId={null} />);
+ expect(view.getByRole('status')).toBeTruthy();
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS);
+ expect(view.queryByRole('status')).toBeNull();
+});
diff --git a/apps/web/src/features/agent-activity/agent-typing.tsx b/apps/web/src/features/agent-activity/agent-typing.tsx
new file mode 100644
index 0000000000..a195a3c482
--- /dev/null
+++ b/apps/web/src/features/agent-activity/agent-typing.tsx
@@ -0,0 +1,234 @@
+import { PersonaAvatar } from '@app/features/agent-dms/components/persona-avatar';
+import { InteractionCard } from '@app/features/agent-interactions/components/InteractionCard';
+import type { AgentInteraction } from '@app/features/agent-interactions/context/interaction';
+import { createInteractionController } from '@app/features/agent-interactions/primitives/create-interaction-controller';
+import {
+ isWorkingTurn,
+ sessionTurn,
+ subscribeSessionTurns,
+} from '@core/agent-session/session-turn';
+import { toast } from '@core/component/Toast/Toast';
+import { useAgentSessionQuery } from '@queries/agent-session/session';
+import { firstPartyBotName } from '@queries/bots/first-party-bot-name';
+import { useBotProfile } from '@queries/bots/profiles';
+import { queryReadyGate } from '@queries/gate';
+import { parentKey } from '@queries/messages/keys';
+import { getTypingAgents, type TypingAgent } from '@queries/messages/typing';
+import type { MessagePart } from '@service-agent-fold/generated/types';
+import type { MessageParent } from '@service-storage/messages';
+import { Key } from '@solid-primitives/keyed';
+import {
+ createContext,
+ createMemo,
+ createSignal,
+ For,
+ type JSX,
+ onCleanup,
+ type ParentProps,
+ Show,
+ Suspense,
+ useContext,
+} from 'solid-js';
+import { LiveTail } from './components/live-tail';
+import { TypingRow } from './components/typing-row';
+import { openReply, streamingProse, typingLabel } from './core/live-reply';
+import { createLiveSession } from './queries/live-session';
+
+/** One place of a conversation: the timeline, or one thread. */
+type TypingPlace = { parent: MessageParent; threadId: string | null };
+
+const KeptRowsContext = createContext<{
+ shows: (place: TypingPlace) => boolean;
+ rows: JSX.Element;
+}>();
+
+/**
+ * Agents typing in one place of a conversation - the timeline, or one
+ * thread - each as a typing row. A viewer who can read the session also sees
+ * the turn as it runs beneath it: the passage being written, what it is
+ * waiting on, and Stop.
+ *
+ * Under an {@link AgentTypingProvider} for the same place, these are the
+ * provider's rows, moved here.
+ */
+export function AgentTyping(props: TypingPlace) {
+ const kept = useContext(KeptRowsContext);
+ return (
+ <Show
+ when={kept?.shows(props)}
+ fallback={
+ <AgentTypingRows parent={props.parent} threadId={props.threadId} />
+ }
+ >
+ {kept?.rows}
+ </Show>
+ );
+}
+
+/**
+ * Makes one place's typing rows once, for a list that shows them under
+ * whichever of its rows is newest: a row that changes when a message
+ * arrives, and that a virtualized list unmounts once the reader scrolls
+ * away. Rows made inside it would go with it - the turn's live view would
+ * load again, and every card beneath it would start over, dropping an
+ * answer or a draft the viewer had half written. Made here, the rows outlive
+ * the list's rows and only move between them.
+ */
+export function AgentTypingProvider(props: ParentProps<TypingPlace>) {
+ // A boundary of their own: rows that suspend must not blank the list.
+ const rows = (
+ <Suspense>
+ <AgentTypingRows parent={props.parent} threadId={props.threadId} />
+ </Suspense>
+ );
+ return (
+ <KeptRowsContext.Provider
+ value={{
+ shows: (place) =>
+ place.threadId === props.threadId &&
+ parentKey(place.parent) === parentKey(props.parent),
+ rows,
+ }}
+ >
+ {props.children}
+ </KeptRowsContext.Provider>
+ );
+}
+
+function AgentTypingRows(props: TypingPlace) {
+ const [turns, setTurns] = createSignal(0);
+ onCleanup(subscribeSessionTurns(() => setTurns((count) => count + 1)));
+ // Typing lapses whenever its heartbeat does, as when a phone sleeps with
+ // the app open. An agent whose turn the fold still has open - working, or
+ // waiting on the viewer - keeps its row until the turn ends, and with it
+ // whatever the viewer was answering beneath it.
+ const agents = createMemo<ReadonlyMap<string, TypingAgent>>((shown) => {
+ turns();
+ const next = new Map(getTypingAgents(props.parent, props.threadId));
+ for (const [botUserId, agent] of shown) {
+ const turn = sessionTurn(agent.sessionId);
+ if (!next.has(botUserId) && (isWorkingTurn(turn) || turn === 'blocked'))
+ next.set(botUserId, agent);
+ }
+ return next;
+ }, new Map());
+ return (
+ <For each={[...agents().keys()]}>
+ {(botUserId) => (
+ <Show when={agents().get(botUserId)}>
+ {(info) => (
+ <AgentTypingEntry
+ botUserId={botUserId}
+ sessionId={info().sessionId}
+ phase={info().phase}
+ />
+ )}
+ </Show>
+ )}
+ </For>
+ );
+}
+
+function AgentTypingEntry(props: {
+ botUserId: string;
+ sessionId: string;
+ phase: 'thinking' | 'writing' | 'working' | 'waiting';
+}) {
+ const botId = () => props.botUserId.replace(/^bot\|/, '');
+ const firstParty = () => firstPartyBotName(botId());
+ const profile = useBotProfile(() => (firstParty() ? '' : botId()));
+ // Undefined while the profile loads: the row shows only its dots rather
+ // than a placeholder name that changes a moment later.
+ const name = () => {
+ const known = firstParty();
+ if (known) return known;
+ if (queryReadyGate(profile)) return profile.data?.name ?? 'Agent';
+ return profile.isError ? 'Agent' : undefined;
+ };
+ const avatarUrl = () =>
+ queryReadyGate(profile) ? profile.data?.avatarUrl : undefined;
+ const label = () => {
+ const known = name();
+ return known ? typingLabel(known, props.phase) : '';
+ };
+
+ const live = createLiveSession(() => props.sessionId);
+ const sessionQuery = useAgentSessionQuery(() => props.sessionId);
+ const canEdit = () =>
+ queryReadyGate(sessionQuery) ? sessionQuery.data?.canEdit : undefined;
+ const reply = () => (live.loaded() ? openReply(live.messages()) : undefined);
+ // A held tool call is answered from the session, not here: a turn the
+ // owner prompts, as every DM turn is, is never held for them.
+ const pending = () =>
+ (live.metadata()?.pendingInteractions ?? []).filter(
+ (request): request is AgentInteraction =>
+ request.kind !== 'tool_approval' && request.turn === reply()?.turn
+ );
+ const interactions = createInteractionController({
+ sessionId: () => props.sessionId,
+ pending,
+ canEdit,
+ issue: (action) => live.issue(action),
+ onFailure: (message) => toast.failure(message),
+ });
+ const toolFor = (toolCall: string | null) => {
+ const part = reply()?.parts.find(
+ (candidate): candidate is Extract<MessagePart, { kind: 'tool_use' }> =>
+ candidate.kind === 'tool_use' && candidate.id === toolCall
+ );
+ return part;
+ };
+ const [stopping, setStopping] = createSignal(false);
+ const stop = async () => {
+ setStopping(true);
+ try {
+ const result = await live.issue({ type: 'stop' });
+ if (result?.isErr()) toast.failure('The agent could not be stopped');
+ } catch {
+ toast.failure('The agent could not be stopped');
+ } finally {
+ setStopping(false);
+ }
+ };
+
+ return (
+ <TypingRow
+ avatar={
+ <PersonaAvatar
+ botId={botId()}
+ name={name() ?? ''}
+ avatarUrl={avatarUrl()}
+ size="sm"
+ />
+ }
+ label={label()}
+ >
+ <Show when={reply() || live.failed()}>
+ <LiveTail
+ prose={reply() ? streamingProse(reply()!) : undefined}
+ disconnected={live.failed()}
+ onReconnect={live.retry}
+ onStop={canEdit() && reply() ? () => void stop() : undefined}
+ stopping={stopping()}
+ >
+ {/* Each metadata event carries every request anew. Keyed by what
+ it asks, a card keeps whatever was typed into it. */}
+ <Key
+ each={pending()}
+ by={(request) =>
+ JSON.stringify([request.turn, request.kind, request.requestId])
+ }
+ >
+ {(request) => (
+ <InteractionCard
+ request={request()}
+ controller={interactions}
+ tool={toolFor(request().toolCall)}
+ />
+ )}
+ </Key>
+ </LiveTail>
+ </Show>
+ </TypingRow>
+ );
+}
diff --git a/apps/web/src/features/agent-activity/components/activity-rows.tsx b/apps/web/src/features/agent-activity/components/activity-rows.tsx
new file mode 100644
index 0000000000..e37344203d
--- /dev/null
+++ b/apps/web/src/features/agent-activity/components/activity-rows.tsx
@@ -0,0 +1,94 @@
+import { TextShimmer } from '@app/features/block-agent/ui';
+import CheckIcon from '@phosphor/check.svg';
+import SpinnerIcon from '@phosphor/spinner-gap.svg';
+import WarningIcon from '@phosphor/warning-circle.svg';
+import XIcon from '@phosphor/x.svg';
+import { Key } from '@solid-primitives/keyed';
+import { createSignal, Match, Show, Switch } from 'solid-js';
+
+/** One step of an agent's work, as the session's fold worded it. */
+export type ActivityRowView = {
+ id: string;
+ label: string;
+ detail?: string | null;
+ status: 'running' | 'completed' | 'failed' | 'interrupted';
+};
+
+/** Steps shown before the earlier ones fold behind a count. */
+const VISIBLE_ROWS = 6;
+
+/**
+ * The steps an agent took between two passages of its reply: what it did, to
+ * what, and how that went, one quiet line each. A long run keeps its latest
+ * steps in view and folds the rest behind a count.
+ */
+export function ActivityRows(props: { rows: readonly ActivityRowView[] }) {
+ const [expanded, setExpanded] = createSignal(false);
+ const hidden = () =>
+ expanded() ? 0 : Math.max(0, props.rows.length - VISIBLE_ROWS);
+ return (
+ <ul class="my-1 flex min-w-0 flex-col gap-0.5 text-xs" aria-label="Steps">
+ <Show when={hidden() > 0}>
+ <li>
+ <button
+ type="button"
+ class="text-ink-extra-muted hover:text-ink-muted"
+ onClick={() => setExpanded(true)}
+ >
+ {hidden()} earlier {hidden() === 1 ? 'step' : 'steps'}
+ </button>
+ </li>
+ </Show>
+ {/* A live run's rows arrive as new objects with every paint. Keyed by
+ step, a row updates in place and its spinner and shimmer run on. */}
+ <Key each={props.rows.slice(hidden())} by="id">
+ {(row) => (
+ <li
+ class="flex min-h-5 min-w-0 items-center gap-2"
+ data-status={row().status}
+ >
+ <StatusIcon status={row().status} />
+ <span class="shrink-0 text-ink-muted">
+ <TextShimmer
+ text={row().label}
+ active={row().status === 'running'}
+ />
+ </span>
+ <Show when={row().detail}>
+ {(detail) => (
+ <span class="min-w-0 truncate font-mono text-ink-extra-muted">
+ {detail()}
+ </span>
+ )}
+ </Show>
+ </li>
+ )}
+ </Key>
+ </ul>
+ );
+}
+
+function StatusIcon(props: { status: ActivityRowView['status'] }) {
+ return (
+ <Switch>
+ <Match when={props.status === 'running'}>
+ <SpinnerIcon
+ class="size-3.5 shrink-0 animate-spin text-ink-muted"
+ aria-label="Running"
+ />
+ </Match>
+ <Match when={props.status === 'completed'}>
+ <CheckIcon class="size-3.5 shrink-0 text-success" aria-label="Done" />
+ </Match>
+ <Match when={props.status === 'failed'}>
+ <XIcon class="size-3.5 shrink-0 text-failure" aria-label="Failed" />
+ </Match>
+ <Match when={props.status === 'interrupted'}>
+ <WarningIcon
+ class="size-3.5 shrink-0 text-ink-muted"
+ aria-label="Interrupted: it may or may not have finished"
+ />
+ </Match>
+ </Switch>
+ );
+}
diff --git a/apps/web/src/features/agent-activity/components/live-tail.tsx b/apps/web/src/features/agent-activity/components/live-tail.tsx
new file mode 100644
index 0000000000..49216d5e61
--- /dev/null
+++ b/apps/web/src/features/agent-activity/components/live-tail.tsx
@@ -0,0 +1,61 @@
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { Button } from '@ui';
+import { type ParentProps, Show } from 'solid-js';
+
+/**
+ * The part of a running reply that is not a message yet: the passage the
+ * agent is writing, what it is waiting on (children), and the controls a
+ * person who can steer the session has. Finished passages are posted as their
+ * own messages, so nothing shown here is shown twice.
+ */
+export function LiveTail(
+ props: ParentProps<{
+ /** The unfinished passage, streaming. */
+ prose?: string;
+ /** The live view stopped updating. */
+ disconnected?: boolean;
+ onReconnect?: () => void;
+ /** Present when the viewer may stop the turn. */
+ onStop?: () => void;
+ stopping?: boolean;
+ }>
+) {
+ return (
+ <div class="flex min-w-0 flex-col gap-2">
+ <Show when={props.prose}>
+ {(prose) => (
+ <div class="min-w-0 text-sm text-ink">
+ <StaticMarkdown markdown={prose()} />
+ </div>
+ )}
+ </Show>
+ {props.children}
+ <Show when={props.disconnected || props.onStop}>
+ <div class="flex items-center gap-2 text-xs text-ink-muted">
+ <Show when={props.disconnected}>
+ <span>Live updates disconnected.</span>
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={() => props.onReconnect?.()}
+ >
+ Reconnect
+ </Button>
+ </Show>
+ <Show when={props.onStop}>
+ {(stop) => (
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={props.stopping}
+ onClick={() => stop()()}
+ >
+ Stop
+ </Button>
+ )}
+ </Show>
+ </div>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-activity/components/typing-row.tsx b/apps/web/src/features/agent-activity/components/typing-row.tsx
new file mode 100644
index 0000000000..b7251c9f2a
--- /dev/null
+++ b/apps/web/src/features/agent-activity/components/typing-row.tsx
@@ -0,0 +1,36 @@
+import type { JSX, ParentProps } from 'solid-js';
+
+/**
+ * An agent typing in a conversation: its avatar and what it is doing, the
+ * way a teammate's typing reads. Whatever the agent is writing right now, and
+ * anything it is waiting on, renders beneath as children.
+ */
+export function TypingRow(
+ props: ParentProps<{ avatar: JSX.Element; label: string }>
+) {
+ return (
+ <div
+ class="flex min-w-0 items-start gap-2 py-1 pl-[var(--message-padding-x)] pr-[var(--message-padding-x)]"
+ data-agent-typing
+ >
+ <div class="flex w-[var(--user-icon-width)] shrink-0 justify-center pt-0.5">
+ {props.avatar}
+ </div>
+ <div class="min-w-0 flex-1">
+ <div
+ class="flex min-h-6 items-center text-xs text-ink-extra-muted"
+ role="status"
+ aria-live="polite"
+ >
+ <span>{props.label}</span>
+ <span class="flex" aria-hidden="true">
+ <span class="animate-typing-dot [animation-delay:0ms]">.</span>
+ <span class="animate-typing-dot [animation-delay:200ms]">.</span>
+ <span class="animate-typing-dot [animation-delay:400ms]">.</span>
+ </span>
+ </div>
+ {props.children}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-activity/core/live-reply.test.ts b/apps/web/src/features/agent-activity/core/live-reply.test.ts
new file mode 100644
index 0000000000..7fc970df0a
--- /dev/null
+++ b/apps/web/src/features/agent-activity/core/live-reply.test.ts
@@ -0,0 +1,113 @@
+import type {
+ FoldedMessage,
+ MessagePart,
+ Segment,
+} from '@service-agent-fold/generated/types';
+import { describe, expect, it } from 'vitest';
+import {
+ openReply,
+ replyToTurn,
+ segmentRows,
+ streamingProse,
+ typingLabel,
+} from './live-reply';
+
+function reply(
+ turn: number,
+ parts: MessagePart[],
+ segments: Segment[],
+ closed = false
+): FoldedMessage {
+ return {
+ agentSessionId: 'session',
+ turn,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts,
+ stop: closed ? { kind: 'end_turn' } : null,
+ pending: false,
+ segments,
+ phase: closed ? null : 'writing',
+ };
+}
+
+const prose = (index: number, start: number, sealed: boolean): Segment => ({
+ index,
+ kind: 'prose',
+ start,
+ end: start + 1,
+ sealed,
+ rows: [],
+});
+
+describe('live reply', () => {
+ it('finds the reply still being written, not an earlier finished one', () => {
+ const done = reply(
+ 0,
+ [{ kind: 'text', text: 'Done' }],
+ [prose(0, 0, true)],
+ true
+ );
+ const running = reply(
+ 1,
+ [{ kind: 'text', text: 'Hi' }],
+ [prose(0, 0, false)]
+ );
+ expect(openReply([done, running])?.turn).toBe(1);
+ expect(openReply([done])).toBeUndefined();
+ expect(replyToTurn([done, running], 0)).toBe(done);
+ });
+
+ it('streams only an unfinished passage', () => {
+ const writing = reply(
+ 0,
+ [
+ { kind: 'text', text: 'Posted already.' },
+ {
+ kind: 'tool_use',
+ id: 't1',
+ name: { kind: 'native', name: 'Bash' },
+ status: 'completed',
+ detail: {
+ kind: 'terminal',
+ command: 'ls',
+ output: null,
+ exitCode: 0,
+ },
+ },
+ { kind: 'text', text: 'Still writing' },
+ ],
+ [
+ prose(0, 0, true),
+ {
+ index: 1,
+ kind: 'activity',
+ start: 1,
+ end: 2,
+ sealed: true,
+ rows: [{ id: 't1', label: 'Ran', detail: 'ls', status: 'completed' }],
+ },
+ prose(2, 2, false),
+ ]
+ );
+ expect(streamingProse(writing)).toBe('Still writing');
+ expect(segmentRows(writing, 1)).toEqual([
+ { id: 't1', label: 'Ran', detail: 'ls', status: 'completed' },
+ ]);
+ expect(segmentRows(writing, 0)).toBeUndefined();
+ const finished = reply(
+ 0,
+ [{ kind: 'text', text: 'All done' }],
+ [prose(0, 0, true)]
+ );
+ expect(streamingProse(finished)).toBeUndefined();
+ });
+
+ it('says what the agent is doing in words', () => {
+ expect(typingLabel('Macro', 'writing')).toBe('Macro is typing');
+ expect(typingLabel('Scout', 'working')).toBe('Scout is working');
+ expect(typingLabel('Scout', 'waiting')).toBe(
+ 'Scout is waiting for an answer'
+ );
+ });
+});
diff --git a/apps/web/src/features/agent-activity/core/live-reply.ts b/apps/web/src/features/agent-activity/core/live-reply.ts
new file mode 100644
index 0000000000..35c54dd57a
--- /dev/null
+++ b/apps/web/src/features/agent-activity/core/live-reply.ts
@@ -0,0 +1,62 @@
+import type {
+ ActivityRow,
+ FoldedMessage,
+ TurnPhase,
+} from '@service-agent-fold/generated/types';
+
+/** The reply an agent is still writing; the latest when there are several. */
+export function openReply(
+ messages: readonly FoldedMessage[]
+): FoldedMessage | undefined {
+ return messages.findLast(
+ (message) => message.author.kind === 'agent' && message.stop === null
+ );
+}
+
+/** The agent's reply to `turn`: the reply a posted message's steps belong to. */
+export function replyToTurn(
+ messages: readonly FoldedMessage[],
+ turn: number
+): FoldedMessage | undefined {
+ return messages.find(
+ (message) => message.author.kind === 'agent' && message.turn === turn
+ );
+}
+
+/**
+ * The passage the agent is writing right now: the reply's last segment while
+ * it is unfinished prose. A finished passage is posted as its own message, so
+ * only this one streams live.
+ */
+export function streamingProse(reply: FoldedMessage): string | undefined {
+ const last = reply.segments.at(-1);
+ if (!last || last.kind !== 'prose' || last.sealed) return undefined;
+ const text = reply.parts
+ .slice(last.start, last.end)
+ .flatMap((part) =>
+ part.kind === 'text' && part.text.trim() ? [part.text.trim()] : []
+ )
+ .join('\n\n');
+ return text || undefined;
+}
+
+/** The live rows of one activity segment, by the index the server posted. */
+export function segmentRows(
+ reply: FoldedMessage,
+ segment: number
+): ActivityRow[] | undefined {
+ const found = reply.segments.find((candidate) => candidate.index === segment);
+ return found?.kind === 'activity' ? found.rows : undefined;
+}
+
+const PHASE_VERBS: Record<TurnPhase, string> = {
+ thinking: 'is thinking',
+ writing: 'is typing',
+ working: 'is working',
+ waiting: 'is waiting for an answer',
+};
+
+/** What a typing indicator says an agent is doing. */
+export function typingLabel(name: string, phase: TurnPhase): string {
+ return `${name} ${PHASE_VERBS[phase]}`;
+}
diff --git a/apps/web/src/features/agent-activity/queries/live-session.test.tsx b/apps/web/src/features/agent-activity/queries/live-session.test.tsx
new file mode 100644
index 0000000000..f43cffcf81
--- /dev/null
+++ b/apps/web/src/features/agent-activity/queries/live-session.test.tsx
@@ -0,0 +1,142 @@
+import type {
+ FoldedMessage,
+ FoldedStreamEvent,
+} from '@service-agent-fold/generated/types';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const fake = vi.hoisted(() => ({ acquire: vi.fn() }));
+vi.mock('@core/agent-session/AgentSession', () => ({
+ AgentSession: { acquire: fake.acquire },
+}));
+
+import { createLiveSession, RELEASE_DELAY_MS } from './live-session';
+
+function session() {
+ let listener: ((events: FoldedStreamEvent[]) => void) | undefined;
+ return {
+ load: vi.fn(async () => ({})),
+ snapshot: vi.fn(async () => ({
+ messages: [],
+ metadata: { pendingInteractions: [], turn: 'idle' },
+ })),
+ subscribe: vi.fn((callback) => {
+ listener = callback;
+ return () => {
+ listener = undefined;
+ };
+ }),
+ release: vi.fn(),
+ issue: vi.fn(),
+ emit: (events: FoldedStreamEvent[]) => listener?.(events),
+ };
+}
+
+function message(text: string): FoldedMessage {
+ return {
+ agentSessionId: 'session',
+ turn: 0,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts: [{ kind: 'text', text }],
+ stop: null,
+ pending: false,
+ segments: [],
+ phase: 'writing',
+ };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+describe('live agent session', () => {
+ it('batches token paints and releases its subscription on a context change', async () => {
+ vi.useFakeTimers();
+ const first = session();
+ const second = session();
+ fake.acquire.mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const scope = createRoot((dispose) => {
+ const [id, setId] = createSignal<string | undefined>('first');
+ return { live: createLiveSession(id), setId, dispose };
+ });
+ await vi.runAllTimersAsync();
+ first.emit([{ kind: 'new', message: message('a') }]);
+ first.emit([{ kind: 'update', message: message('answer') }]);
+ expect(scope.live.messages()).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(250);
+ expect(scope.live.messages()).toEqual([message('answer')]);
+ scope.setId('second');
+ expect(scope.live.messages()).toEqual([]);
+ first.emit([{ kind: 'update', message: message('old context') }]);
+ // The fold lingers for a surface about to show it again.
+ expect(first.release).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(RELEASE_DELAY_MS);
+ expect(first.release).toHaveBeenCalledOnce();
+ expect(scope.live.messages()).toEqual([]);
+ scope.dispose();
+ await vi.runAllTimersAsync();
+ expect(second.release).toHaveBeenCalledOnce();
+ });
+
+ it('does not hide a stream failure and lets the user reconnect', async () => {
+ const broken = session();
+ broken.load.mockRejectedValueOnce(new Error('disconnected'));
+ fake.acquire.mockReturnValue(broken);
+ const scope = createRoot((dispose) => ({
+ live: createLiveSession(() => 'session'),
+ dispose,
+ }));
+ await vi.waitFor(() => expect(scope.live.failed()).toBe(true));
+ scope.live.retry();
+ await vi.waitFor(() => expect(broken.load).toHaveBeenCalledTimes(2));
+ expect(scope.live.failed()).toBe(false);
+ scope.dispose();
+ });
+
+ it('treats a session the viewer cannot read as denied, not failed', async () => {
+ const private_ = session();
+ const denied = Object.assign(new Error('no access'), {
+ name: 'AgentSessionAccessDenied',
+ });
+ private_.load.mockRejectedValueOnce(denied);
+ fake.acquire.mockReturnValue(private_);
+ const scope = createRoot((dispose) => ({
+ live: createLiveSession(() => 'session'),
+ dispose,
+ }));
+ await vi.waitFor(() => expect(scope.live.denied()).toBe(true));
+ expect(scope.live.failed()).toBe(false);
+ expect(scope.live.loaded()).toBe(false);
+ scope.dispose();
+ });
+
+ it('keeps one subscription while the same session is read again', async () => {
+ const live = session();
+ fake.acquire.mockReturnValue(live);
+ const scope = createRoot((dispose) => {
+ // A typing heartbeat: new state, same session.
+ const [typing, setTyping] = createSignal({ sessionId: 'session' });
+ return {
+ live: createLiveSession(() => typing().sessionId),
+ heartbeat: () => setTyping({ sessionId: 'session' }),
+ dispose,
+ };
+ });
+ await vi.waitFor(() => expect(scope.live.loaded()).toBe(true));
+ scope.heartbeat();
+ expect(fake.acquire).toHaveBeenCalledOnce();
+ expect(live.release).not.toHaveBeenCalled();
+ expect(scope.live.loaded()).toBe(true);
+ scope.dispose();
+ });
+
+ it('never acquires a runtime for an empty conversation', () => {
+ createRoot((dispose) => {
+ createLiveSession(() => undefined);
+ dispose();
+ });
+ expect(fake.acquire).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/agent-activity/queries/live-session.ts b/apps/web/src/features/agent-activity/queries/live-session.ts
new file mode 100644
index 0000000000..8c14c8d2fa
--- /dev/null
+++ b/apps/web/src/features/agent-activity/queries/live-session.ts
@@ -0,0 +1,115 @@
+import { AgentSession } from '@core/agent-session/AgentSession';
+import type {
+ FoldedMessage,
+ FoldedStreamEvent,
+ SessionMetadata,
+} from '@service-agent-fold/generated/types';
+import type { AgentAction } from '@service-agent-harness/generated/schemas';
+import {
+ type Accessor,
+ batch,
+ createMemo,
+ createSignal,
+ onCleanup,
+} from 'solid-js';
+
+/**
+ * How long a session's shared fold outlives the last surface showing it. The
+ * typing row follows the newest message; moving there re-acquires the fold
+ * instead of loading the whole session again.
+ */
+export const RELEASE_DELAY_MS = 5_000;
+
+/**
+ * One shared subscription to an agent session for a conversation surface: a
+ * typing row's live tail, a reply message's steps. Every surface showing the
+ * same session shares its fold through {@link AgentSession.acquire}; text
+ * paints at most 4 Hz.
+ *
+ * A viewer who cannot read the session is `denied`, which is not a failure:
+ * the conversation still shows the bot typing and the steps it posted.
+ */
+export function createLiveSession(sessionId: Accessor<string | undefined>) {
+ const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
+ const [metadata, setMetadata] = createSignal<SessionMetadata>();
+ const [loaded, setLoaded] = createSignal(false);
+ const [failed, setFailed] = createSignal(false);
+ const [denied, setDenied] = createSignal(false);
+ const [retry, setRetry] = createSignal(0);
+ // Callers derive the id from state that changes for other reasons, such as
+ // a typing heartbeat; only a different session resubscribes.
+ const currentId = createMemo(sessionId);
+ const live = createMemo(() => {
+ retry();
+ const id = currentId();
+ batch(() => {
+ setMessages([]);
+ setMetadata(undefined);
+ setLoaded(false);
+ setFailed(false);
+ setDenied(false);
+ });
+ if (!id) return undefined;
+ const session = AgentSession.acquire(id);
+ const rows = new Map<string, FoldedMessage>();
+ let disposed = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const key = (row: FoldedMessage) => `${row.turn}:${row.author.kind}`;
+ const flush = () => {
+ timer = undefined;
+ if (!disposed) setMessages([...rows.values()]);
+ };
+ const apply = (events: FoldedStreamEvent[]) => {
+ for (const event of events) {
+ if (event.kind === 'metadata') setMetadata(event.metadata);
+ else if (event.kind === 'replace') {
+ rows.clear();
+ for (const row of event.messages) rows.set(key(row), row);
+ } else rows.set(key(event.message), event.message);
+ }
+ timer ??= setTimeout(flush, 250);
+ };
+ const unsubscribe = session.subscribe(apply);
+ const load = async () => {
+ try {
+ await session.load();
+ const snapshot = await session.snapshot();
+ if (disposed) return;
+ apply([
+ { kind: 'replace', messages: snapshot.messages },
+ { kind: 'metadata', metadata: snapshot.metadata },
+ ]);
+ if (timer) clearTimeout(timer);
+ flush();
+ setLoaded(true);
+ } catch (error) {
+ if (disposed) return;
+ // Not readable by this viewer: a channel member watching someone
+ // else's thread reply. Duck-typed so tests can stub the session.
+ if (
+ (error as { name?: string } | undefined)?.name ===
+ 'AgentSessionAccessDenied'
+ )
+ setDenied(true);
+ else setFailed(true);
+ }
+ };
+ void load();
+ onCleanup(() => {
+ disposed = true;
+ if (timer) clearTimeout(timer);
+ unsubscribe();
+ setTimeout(() => session.release(), RELEASE_DELAY_MS);
+ });
+ return session;
+ });
+ return {
+ messages,
+ metadata,
+ loaded,
+ failed,
+ denied,
+ retry: () => setRetry((value) => value + 1),
+ issue: (action: AgentAction) => live()?.issue(action),
+ };
+}
diff --git a/apps/web/src/features/agent-conversations/agent-conversation-controls.test.tsx b/apps/web/src/features/agent-conversations/agent-conversation-controls.test.tsx
new file mode 100644
index 0000000000..5448ad3dce
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/agent-conversation-controls.test.tsx
@@ -0,0 +1,125 @@
+import type {
+ AgentConversation,
+ AgentConversationTurn,
+} from '@service-agent-harness/agent-conversations';
+import { cleanup, fireEvent, render, waitFor } from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { ok } from 'neverthrow';
+import type { JSX } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ retry: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock('@service-agent-harness/client', () => ({
+ agentHarnessServiceClient: { control: vi.fn() },
+}));
+vi.mock('@service-agent-harness/agent-conversations', () => ({
+ retryAgentConversationTurn: mocks.retry,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.failure },
+}));
+vi.mock('@ui', () => ({
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+
+import { AgentConversationControls } from './agent-conversation-controls';
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function turn(
+ sessionId: string,
+ state: AgentConversationTurn['state'],
+ retryable = ['failed', 'stopped', 'interrupted'].includes(state)
+): AgentConversationTurn {
+ return {
+ sessionId,
+ state,
+ retryable,
+ sourceMessageId: `${sessionId}-message`,
+ actionId: `${sessionId}-attempt`,
+ replyMessageId: null,
+ createdAt: '2026-10-01T00:00:00Z',
+ };
+}
+
+function conversation(
+ turns: AgentConversationTurn[],
+ available = true
+): AgentConversation {
+ return {
+ channelId: 'dm',
+ botId: 'bot',
+ name: 'Researcher',
+ avatarUrl: null,
+ available,
+ settingsChanged: false,
+ sessions: [
+ {
+ sessionId: 'current',
+ isCurrent: true,
+ createdAt: '2026-10-01T00:00:00Z',
+ },
+ ],
+ turns,
+ };
+}
+
+function mount(data: AgentConversation) {
+ const changed = vi.fn();
+ const view = render(() => (
+ <QueryClientProvider client={new QueryClient()}>
+ <AgentConversationControls conversation={data} onChanged={changed} />
+ </QueryClientProvider>
+ ));
+ return { ...view, changed };
+}
+
+describe('agent conversation controls', () => {
+ it('counts queued messages while a turn runs and leaves Stop to its typing row', () => {
+ const view = mount(
+ conversation([
+ turn('old', 'failed'),
+ turn('current', 'running'),
+ turn('current', 'queued'),
+ ])
+ );
+ expect(view.getByText('1 queued')).toBeTruthy();
+ expect(view.queryByRole('button', { name: 'Stop' })).toBeNull();
+ expect(view.queryByText(/could not finish/)).toBeNull();
+ });
+
+ it('retries only the chosen current-session attempt with its original identity', async () => {
+ mocks.retry.mockResolvedValue(ok(undefined));
+ const current = turn('current', 'interrupted');
+ const view = mount(conversation([turn('old', 'failed'), current]));
+ expect(view.getByText(/Review any completed actions/)).toBeTruthy();
+ expect(mocks.retry).not.toHaveBeenCalled();
+ await fireEvent.click(view.getByRole('button', { name: 'Retry message' }));
+ await waitFor(() =>
+ expect(mocks.retry).toHaveBeenCalledWith(
+ expect.objectContaining({ channelId: 'dm', botId: 'bot' }),
+ current
+ )
+ );
+ });
+
+ it('offers no Retry while the failed attempt’s reply is still being settled', () => {
+ const view = mount(conversation([turn('current', 'failed', false)]));
+ expect(view.getByText(/could not finish/)).toBeTruthy();
+ expect(view.queryByRole('button', { name: 'Retry message' })).toBeNull();
+ });
+
+ it('keeps unavailable failed conversations readable without offering a new run', () => {
+ const view = mount(conversation([turn('current', 'failed')], false));
+ expect(view.getByText(/could not finish/)).toBeTruthy();
+ expect(view.queryByRole('button', { name: 'Retry message' })).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/agent-conversations/agent-conversation-controls.tsx b/apps/web/src/features/agent-conversations/agent-conversation-controls.tsx
new file mode 100644
index 0000000000..36c6b40081
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/agent-conversation-controls.tsx
@@ -0,0 +1,63 @@
+import { toast } from '@core/component/Toast/Toast';
+import type { AgentConversation } from '@service-agent-harness/agent-conversations';
+import { ConversationActivity } from './components/conversation-activity';
+import { useOptionalAgentConversations } from './context';
+import { useAgentConversationControl } from './queries/controls';
+
+/**
+ * What waits in the conversation's current session and how its last attempt
+ * ended, independent of the agent block. A running turn is stopped from the
+ * agent's typing row, where it shows.
+ */
+export function AgentConversationControls(props: {
+ conversation: AgentConversation;
+ onChanged: () => void;
+}) {
+ const context = useOptionalAgentConversations();
+ const current = () =>
+ props.conversation.sessions?.find((session) => session.isCurrent)
+ ?.sessionId;
+ const turns = () =>
+ (props.conversation.turns ?? []).filter(
+ (turn) => turn.sessionId === current()
+ );
+ const running = () => turns().find((turn) => turn.state === 'running');
+ const queued = () => turns().filter((turn) => turn.state === 'queued').length;
+ const failed = () =>
+ turns().findLast(
+ (turn) =>
+ turn.state === 'failed' ||
+ turn.state === 'stopped' ||
+ turn.state === 'interrupted'
+ );
+ const mutation = useAgentConversationControl({
+ onSuccess: props.onChanged,
+ onError: () =>
+ toast.failure(
+ 'Could not update this conversation. Refresh and try again.'
+ ),
+ });
+ const failure = () => {
+ const state = failed()?.state;
+ return state === 'failed' || state === 'stopped' || state === 'interrupted'
+ ? state
+ : undefined;
+ };
+ return (
+ <ConversationActivity
+ queued={queued()}
+ failed={context || running() ? undefined : failure()}
+ canRetry={props.conversation.available && !!failed()?.retryable}
+ pending={mutation.isPending}
+ onRetry={() => {
+ const turn = failed();
+ if (turn)
+ mutation.mutate({
+ type: 'retry',
+ conversation: props.conversation,
+ turn,
+ });
+ }}
+ />
+ );
+}
diff --git a/apps/web/src/features/agent-conversations/agent-conversation-message.test.tsx b/apps/web/src/features/agent-conversations/agent-conversation-message.test.tsx
new file mode 100644
index 0000000000..70da206f86
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/agent-conversation-message.test.tsx
@@ -0,0 +1,111 @@
+import type { AgentConversation } from '@service-agent-harness/agent-conversations';
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { createSignal, type JSX } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ control: vi.fn() }));
+vi.mock('./queries/controls', () => ({
+ useAgentConversationControl: mocks.control,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({ toast: {} }));
+vi.mock('@ui', () => ({
+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button {...props} />
+ ),
+}));
+
+import {
+ AgentConversationContextBoundary,
+ AgentConversationMessageStatus,
+} from './agent-conversation-message';
+import {
+ AgentConversationsContext,
+ type AgentConversationsContextValue,
+} from './context';
+
+beforeEach(() => {
+ // Each status's own mutation, pending from the click until it settles.
+ mocks.control.mockImplementation(() => {
+ const [pending, setPending] = createSignal(false);
+ return {
+ get isPending() {
+ return pending();
+ },
+ mutate: () => setPending(true),
+ };
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function conversation(): AgentConversation {
+ return {
+ channelId: 'channel',
+ botId: 'bot',
+ name: 'Researcher',
+ avatarUrl: null,
+ available: true,
+ settingsChanged: false,
+ sessions: [
+ { sessionId: 'old', isCurrent: false, createdAt: '2026-10-01T00:00:00Z' },
+ { sessionId: 'new', isCurrent: true, createdAt: '2026-10-01T01:00:00Z' },
+ ],
+ turns: [
+ {
+ sessionId: 'new',
+ sourceMessageId: 'source',
+ replyMessageId: 'reply',
+ actionId: 'attempt',
+ state: 'running',
+ retryable: false,
+ createdAt: '2026-10-01T01:00:00Z',
+ },
+ ],
+ };
+}
+
+function context(
+ data: () => AgentConversation
+): AgentConversationsContextValue {
+ return { conversations: () => [data()], refresh: vi.fn() };
+}
+
+it('places a fresh-context divider only before the session’s first source message', () => {
+ const view = render(() => (
+ <AgentConversationsContext.Provider value={context(conversation)}>
+ <AgentConversationContextBoundary messageId="source" />
+ <AgentConversationContextBoundary messageId="reply" />
+ </AgentConversationsContext.Provider>
+ ));
+ expect(view.getAllByRole('separator')).toHaveLength(1);
+});
+
+it('keeps a failed message’s status, and its Retry in flight, as the conversation polls', async () => {
+ const failed = (): AgentConversation => {
+ const data = conversation();
+ return {
+ ...data,
+ turns: [{ ...data.turns[0]!, state: 'failed', retryable: true }],
+ };
+ };
+ const [data, setData] = createSignal(failed());
+ const view = render(() => (
+ <AgentConversationsContext.Provider value={context(data)}>
+ <AgentConversationMessageStatus messageId="source" />
+ </AgentConversationsContext.Provider>
+ ));
+ const retry = view.getByRole<HTMLButtonElement>('button', {
+ name: 'Retry message',
+ });
+ await fireEvent.click(retry);
+ expect(retry.disabled).toBe(true);
+
+ // The next poll carries the same conversation as new objects.
+ setData(failed());
+ expect(view.getByRole('button', { name: 'Retry message' })).toBe(retry);
+ expect(retry.disabled).toBe(true);
+ expect(mocks.control).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/features/agent-conversations/agent-conversation-message.tsx b/apps/web/src/features/agent-conversations/agent-conversation-message.tsx
new file mode 100644
index 0000000000..f2c9c82999
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/agent-conversation-message.tsx
@@ -0,0 +1,123 @@
+import { toast } from '@core/component/Toast/Toast';
+import type {
+ AgentConversation,
+ AgentConversationTurn,
+} from '@service-agent-harness/agent-conversations';
+import { Key } from '@solid-primitives/keyed';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { useOptionalAgentConversations } from './context';
+import { useAgentConversationControl } from './queries/controls';
+
+/** A context boundary belongs to its first source message, including on reload. */
+export function AgentConversationContextBoundary(props: { messageId: string }) {
+ const context = useOptionalAgentConversations();
+ const startsContext = () =>
+ (context?.conversations() ?? []).some((conversation) =>
+ conversation.sessions
+ .slice(1)
+ .some(
+ (session) =>
+ conversation.turns.find(
+ (turn) => turn.sessionId === session.sessionId
+ )?.sourceMessageId === props.messageId
+ )
+ );
+ return (
+ <Show when={startsContext()}>
+ <div
+ role="separator"
+ class="my-5 flex items-center gap-3 text-xs text-ink-muted"
+ >
+ <span class="h-px flex-1 bg-edge-muted" />
+ Fresh context · earlier messages kept
+ <span class="h-px flex-1 bg-edge-muted" />
+ </div>
+ </Show>
+ );
+}
+
+const FAILED = ['failed', 'stopped', 'interrupted'];
+
+/**
+ * Durable per-message status for each agent answering the message, with an
+ * explicit retry of the exact failed attempt.
+ */
+export function AgentConversationMessageStatus(props: { messageId: string }) {
+ const context = useOptionalAgentConversations();
+ if (!context) return null;
+ const answering = () =>
+ (context.conversations() ?? []).flatMap((conversation) => {
+ const turn = conversation.turns.find(
+ (turn) => turn.sourceMessageId === props.messageId
+ );
+ return turn && (turn.state === 'queued' || FAILED.includes(turn.state))
+ ? [{ conversation, turn }]
+ : [];
+ });
+ // Every poll brings each entry anew. Keyed by the agent answering, a
+ // status stays put, and a Retry it has in flight stays disabled.
+ return (
+ <Key each={answering()} by={(entry) => entry.conversation.botId}>
+ {(entry) => (
+ <TurnStatus
+ conversation={entry().conversation}
+ turn={entry().turn}
+ onChanged={context.refresh}
+ />
+ )}
+ </Key>
+ );
+}
+
+function TurnStatus(props: {
+ conversation: AgentConversation;
+ turn: AgentConversationTurn;
+ onChanged: () => void;
+}) {
+ const retryable = () =>
+ props.turn.retryable &&
+ props.conversation.available &&
+ props.conversation.sessions.some(
+ (session) =>
+ session.isCurrent && session.sessionId === props.turn.sessionId
+ );
+ const failed = () => FAILED.includes(props.turn.state);
+ const mutation = useAgentConversationControl({
+ onSuccess: props.onChanged,
+ onError: () =>
+ toast.failure('Could not retry this message. Refresh and try again.'),
+ });
+ return (
+ <div
+ class="ml-14 flex items-center gap-3 pb-2 text-xs text-ink-muted"
+ role="status"
+ >
+ <span>
+ {props.turn.state === 'queued'
+ ? 'Queued'
+ : props.turn.state === 'interrupted'
+ ? 'Interrupted. Review completed actions before retrying.'
+ : props.turn.state === 'stopped'
+ ? 'Stopped'
+ : 'Could not finish this message.'}
+ </span>
+ <Show when={failed() && retryable()}>
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={mutation.isPending}
+ onClick={() =>
+ mutation.mutate({
+ type: 'retry',
+ conversation: props.conversation,
+ turn: props.turn,
+ })
+ }
+ >
+ Retry message
+ </Button>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-conversations/agent-conversations-provider.test.tsx b/apps/web/src/features/agent-conversations/agent-conversations-provider.test.tsx
new file mode 100644
index 0000000000..cbea86b3af
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/agent-conversations-provider.test.tsx
@@ -0,0 +1,80 @@
+import { cleanup, render } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ query: vi.fn() }));
+vi.mock('./queries/conversations', () => ({
+ useAgentConversations: mocks.query,
+}));
+
+import { AgentConversationsProvider } from './agent-conversations-provider';
+import { useOptionalAgentConversations } from './context';
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function Names() {
+ const context = useOptionalAgentConversations();
+ return (
+ <output>
+ {(context?.conversations() ?? []).map((c) => c.botId).join(',')}
+ </output>
+ );
+}
+
+it('keeps the last conversations through a failed poll', () => {
+ const [state, setState] = createStore({ status: 'success' });
+ mocks.query.mockReturnValue({
+ isPending: false,
+ get isSuccess() {
+ return state.status === 'success';
+ },
+ get isError() {
+ return state.status === 'error';
+ },
+ // A failed refetch keeps the last data it loaded.
+ data: [{ botId: 'persona' }],
+ refetch: vi.fn(),
+ });
+ const view = render(() => (
+ <AgentConversationsProvider channelId="dm" hasAgents>
+ <Names />
+ </AgentConversationsProvider>
+ ));
+ expect(view.getByRole('status').textContent).toBe('persona');
+ setState('status', 'error');
+ expect(view.getByRole('status').textContent).toBe('persona');
+});
+
+it('mounts the channel once when its agent is known only later', () => {
+ const [hasAgents, setHasAgents] = createSignal(false);
+ mocks.query.mockImplementation(
+ (_channelId: () => string, enabled: () => boolean) => ({
+ get isPending() {
+ return !enabled();
+ },
+ get data() {
+ if (!enabled()) throw new Error('Disabled data must not be read');
+ return [{ botId: 'persona' }];
+ },
+ refetch: vi.fn(),
+ })
+ );
+ let mounts = 0;
+ const Channel = () => {
+ mounts += 1;
+ return <Names />;
+ };
+ const view = render(() => (
+ <AgentConversationsProvider channelId="dm" hasAgents={hasAgents()}>
+ <Channel />
+ </AgentConversationsProvider>
+ ));
+ expect(view.getByRole('status').textContent).toBe('');
+ setHasAgents(true);
+ expect(view.getByRole('status').textContent).toBe('persona');
+ expect(mounts).toBe(1);
+});
diff --git a/apps/web/src/features/agent-conversations/agent-conversations-provider.tsx b/apps/web/src/features/agent-conversations/agent-conversations-provider.tsx
new file mode 100644
index 0000000000..eab46af495
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/agent-conversations-provider.tsx
@@ -0,0 +1,31 @@
+import { queryReadyGate } from '@queries/gate';
+import type { ParentProps } from 'solid-js';
+import { AgentConversationsContext } from './context';
+import { useAgentConversations } from './queries/conversations';
+
+/**
+ * Channels without a conversing agent never load conversation state. The
+ * provider is the same either way, so a channel whose metadata names its
+ * agent only after the channel first rendered is not mounted again.
+ */
+export function AgentConversationsProvider(
+ props: ParentProps<{ channelId: string; hasAgents: boolean }>
+) {
+ const query = useAgentConversations(
+ () => props.channelId,
+ () => props.hasAgents
+ );
+ return (
+ <AgentConversationsContext.Provider
+ value={{
+ // A failed poll keeps the last answer: statuses and Retry stay put
+ // until the next poll succeeds.
+ conversations: () =>
+ props.hasAgents && queryReadyGate(query) ? query.data : undefined,
+ refresh: () => void query.refetch(),
+ }}
+ >
+ {props.children}
+ </AgentConversationsContext.Provider>
+ );
+}
diff --git a/apps/web/src/features/agent-conversations/components/conversation-activity.tsx b/apps/web/src/features/agent-conversations/components/conversation-activity.tsx
new file mode 100644
index 0000000000..8d6e2c23bb
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/components/conversation-activity.tsx
@@ -0,0 +1,38 @@
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+/** Messages waiting their turn, and how the last attempt ended. */
+export function ConversationActivity(props: {
+ queued: number;
+ failed?: 'failed' | 'stopped' | 'interrupted';
+ canRetry: boolean;
+ pending: boolean;
+ onRetry: () => void;
+}) {
+ return (
+ <Show when={props.queued > 0 || props.failed}>
+ <div class="flex items-center justify-between gap-3 px-4 py-2 text-sm text-ink-muted">
+ <div role="status" aria-live="polite">
+ <Show when={props.queued > 0}>{props.queued} queued</Show>
+ <Show when={props.queued === 0 && props.failed}>
+ {props.failed === 'interrupted'
+ ? 'Connection interrupted. Review any completed actions before retrying.'
+ : props.failed === 'stopped'
+ ? 'The last attempt was stopped.'
+ : 'The last attempt could not finish.'}
+ </Show>
+ </div>
+ <Show when={props.failed && props.canRetry}>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={props.pending}
+ onClick={props.onRetry}
+ >
+ Retry message
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/agent-conversations/context.ts b/apps/web/src/features/agent-conversations/context.ts
new file mode 100644
index 0000000000..2b2abddc2d
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/context.ts
@@ -0,0 +1,18 @@
+import type { AgentConversation } from '@service-agent-harness/agent-conversations';
+import { type Accessor, createContext, useContext } from 'solid-js';
+
+/**
+ * The durable state of the agent conversations in a channel: each agent's
+ * sessions and the attempt behind each message it answers. The agents'
+ * replies are ordinary channel messages, and what an agent is doing right now
+ * arrives as its typing.
+ */
+export type AgentConversationsContextValue = {
+ conversations: Accessor<AgentConversation[] | undefined>;
+ refresh: () => void;
+};
+
+export const AgentConversationsContext =
+ createContext<AgentConversationsContextValue>();
+export const useOptionalAgentConversations = () =>
+ useContext(AgentConversationsContext);
diff --git a/apps/web/src/features/agent-conversations/queries/controls.ts b/apps/web/src/features/agent-conversations/queries/controls.ts
new file mode 100644
index 0000000000..ceed484adc
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/queries/controls.ts
@@ -0,0 +1,27 @@
+import { throwOnErr } from '@core/util/result';
+import {
+ type AgentConversation,
+ type AgentConversationTurn,
+ retryAgentConversationTurn,
+} from '@service-agent-harness/agent-conversations';
+import { useMutation } from '@tanstack/solid-query';
+
+type ConversationControl = {
+ type: 'retry';
+ conversation: Pick<AgentConversation, 'channelId' | 'botId'>;
+ turn: AgentConversationTurn;
+};
+
+export function useAgentConversationControl(callbacks: {
+ onSuccess: () => void;
+ onError: () => void;
+}) {
+ return useMutation(() => ({
+ mutationFn: async (action: ConversationControl) => {
+ await throwOnErr(() =>
+ retryAgentConversationTurn(action.conversation, action.turn)
+ );
+ },
+ ...callbacks,
+ }));
+}
diff --git a/apps/web/src/features/agent-conversations/queries/conversations.test.ts b/apps/web/src/features/agent-conversations/queries/conversations.test.ts
new file mode 100644
index 0000000000..e051b87147
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/queries/conversations.test.ts
@@ -0,0 +1,133 @@
+import {
+ clearTypingIndicators,
+ handleCommsTyping,
+} from '@queries/messages/typing';
+import {
+ type AgentConversation,
+ type AgentConversationTurn,
+ listAgentConversations,
+} from '@service-agent-harness/agent-conversations';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { ok } from 'neverthrow';
+import { createComponent, createRoot } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useAgentConversations } from './conversations';
+
+vi.mock('@service-agent-harness/agent-conversations', () => ({
+ listAgentConversations: vi.fn(),
+}));
+
+const list = vi.mocked(listAgentConversations);
+const parent = { type: 'channel', id: 'dm' } as const;
+const BOT = 'bot|persona';
+let client: QueryClient;
+let dispose: (() => void) | undefined;
+
+function conversation(
+ state: AgentConversationTurn['state']
+): AgentConversation[] {
+ return [
+ {
+ channelId: 'dm',
+ botId: 'persona',
+ name: 'Researcher',
+ avatarUrl: null,
+ available: true,
+ settingsChanged: false,
+ sessions: [
+ { sessionId: 'session', isCurrent: true, createdAt: '2026-10-01' },
+ ],
+ turns: [
+ {
+ sessionId: 'session',
+ sourceMessageId: 'source',
+ replyMessageId: null,
+ actionId: 'attempt',
+ state,
+ retryable: false,
+ createdAt: '2026-10-01',
+ },
+ ],
+ },
+ ];
+}
+
+function agentTyping(action: 'start' | 'stop') {
+ handleCommsTyping(
+ {
+ action,
+ parent,
+ user_id: BOT,
+ thread_id: null,
+ agent: { session_id: 'session', phase: 'working' },
+ },
+ );
+}
+
+function Harness() {
+ useAgentConversations(() => 'dm');
+ return null;
+}
+
+function mount() {
+ dispose = createRoot((dispose) => {
+ createComponent(QueryClientProvider, {
+ client,
+ get children() {
+ return createComponent(Harness, {});
+ },
+ });
+ return dispose;
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ clearTypingIndicators();
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ list.mockReset();
+});
+
+afterEach(() => {
+ dispose?.();
+ client.clear();
+ clearTypingIndicators();
+ vi.useRealTimers();
+});
+
+it('polls every few seconds while a turn is queued or running', async () => {
+ list.mockResolvedValue(ok(conversation('running')));
+ mount();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(list).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(list).toHaveBeenCalledTimes(2);
+});
+
+it('polls about once a minute while every turn has settled', async () => {
+ list.mockResolvedValue(ok(conversation('succeeded')));
+ mount();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(list).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(list).toHaveBeenCalledTimes(2);
+});
+
+it('polls fast while the agent types, until a poll lands after it stops', async () => {
+ list.mockResolvedValue(ok(conversation('succeeded')));
+ mount();
+ await vi.advanceTimersByTimeAsync(0);
+ // A new turn types before any poll has seen it.
+ agentTyping('start');
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(list).toHaveBeenCalledTimes(2);
+
+ // Its turn ends: one more poll reads how, then polling goes idle.
+ await vi.advanceTimersByTimeAsync(1_000);
+ agentTyping('stop');
+ await vi.advanceTimersByTimeAsync(4_000);
+ expect(list).toHaveBeenCalledTimes(3);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(list).toHaveBeenCalledTimes(3);
+});
diff --git a/apps/web/src/features/agent-conversations/queries/conversations.ts b/apps/web/src/features/agent-conversations/queries/conversations.ts
new file mode 100644
index 0000000000..bed433ad70
--- /dev/null
+++ b/apps/web/src/features/agent-conversations/queries/conversations.ts
@@ -0,0 +1,67 @@
+import { throwOnErr } from '@core/util/result';
+import { getTypingAgents } from '@queries/messages/typing';
+import {
+ type AgentConversation,
+ listAgentConversations,
+} from '@service-agent-harness/agent-conversations';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
+import { type Accessor, createMemo } from 'solid-js';
+
+export const agentConversationsKey = (channelId: string) =>
+ ['agent-conversations', channelId] as const;
+
+/** While a turn moves: whether it is queued, how it ended, and its Retry. */
+const ACTIVE_POLL_MS = 5_000;
+/** Otherwise only what rarely changes: access, settings, a fresh context. */
+const IDLE_POLL_MS = 60_000;
+
+function turnInFlight(conversations: readonly AgentConversation[] | undefined) {
+ return (
+ conversations?.some((conversation) =>
+ conversation.turns.some(
+ (turn) => turn.state === 'queued' || turn.state === 'running'
+ )
+ ) ?? false
+ );
+}
+
+// Cached on the query past unmount; module scope keeps hook state out of it.
+function agentConversationsQueryOptions(
+ channelId: string,
+ enabled: boolean,
+ typingUntil: number
+) {
+ return queryOptions({
+ queryKey: agentConversationsKey(channelId),
+ queryFn: ({ signal }) =>
+ throwOnErr(() => listAgentConversations(channelId, signal)),
+ refetchInterval: (query) =>
+ typingUntil >= query.state.dataUpdatedAt || turnInFlight(query.state.data)
+ ? ACTIVE_POLL_MS
+ : IDLE_POLL_MS,
+ refetchOnWindowFocus: true,
+ enabled,
+ });
+}
+
+/**
+ * Only the open channel polls for context and eligibility changes, and only
+ * while `enabled` says an agent converses there: every few seconds while a
+ * turn is queued or running, about once a minute otherwise.
+ */
+export function useAgentConversations(
+ channelId: Accessor<string>,
+ enabled: Accessor<boolean> = () => true
+) {
+ // An agent typing here has a turn running before a poll has seen it. Its
+ // typing stops as the turn ends; until a poll lands after that, polling
+ // stays fast, so a turn that failed shows its Retry without the idle wait.
+ const typingUntil = createMemo<number>((until) => {
+ if (getTypingAgents({ type: 'channel', id: channelId() }).size > 0)
+ return Number.POSITIVE_INFINITY;
+ return until === Number.POSITIVE_INFINITY ? Date.now() : until;
+ }, 0);
+ return useQuery(() =>
+ agentConversationsQueryOptions(channelId(), enabled(), typingUntil())
+ );
+}
diff --git a/apps/web/src/features/agent-dms/agent-dm-composer.test.tsx b/apps/web/src/features/agent-dms/agent-dm-composer.test.tsx
new file mode 100644
index 0000000000..16c83da4a4
--- /dev/null
+++ b/apps/web/src/features/agent-dms/agent-dm-composer.test.tsx
@@ -0,0 +1,189 @@
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { type Accessor, createSignal, type JSX } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ query: vi.fn() }));
+vi.mock('@app/features/agent-conversations/queries/conversations', () => ({
+ useAgentConversations: mocks.query,
+}));
+vi.mock(
+ '@app/features/agent-conversations/agent-conversation-controls',
+ () => ({
+ AgentConversationControls: () => null,
+ })
+);
+vi.mock('@ui', () => ({
+ Button: (props: { onClick: () => void; children: JSX.Element }) => (
+ <button onClick={props.onClick}>{props.children}</button>
+ ),
+}));
+
+import { AgentDmComposer } from './agent-dm-composer';
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('agent DM composer availability', () => {
+ it('keeps normal channel composers independent of the agent metadata service', () => {
+ mocks.query.mockReturnValue({
+ isPending: true,
+ isError: false,
+ get data() {
+ throw new Error('Disabled data must not be read');
+ },
+ refetch: vi.fn(),
+ });
+ const view = render(() => (
+ <AgentDmComposer channelId="ordinary" botId={undefined}>
+ <textarea aria-label="Message" />
+ </AgentDmComposer>
+ ));
+ expect(view.getByRole('textbox')).toBeTruthy();
+ const [, enabled] = mocks.query.mock.calls[0] as [
+ unknown,
+ Accessor<boolean>,
+ ];
+ expect(enabled()).toBe(false);
+ });
+
+ it('waits for access and preserves readable history when a persona is revoked', () => {
+ const [state, setState] = createStore({
+ status: 'pending',
+ available: true,
+ });
+ mocks.query.mockReturnValue({
+ get isPending() {
+ return state.status === 'pending';
+ },
+ get isSuccess() {
+ return state.status === 'success';
+ },
+ get isError() {
+ return state.status === 'error';
+ },
+ get data() {
+ if (state.status !== 'success')
+ throw new Error('Pending data must not be read');
+ return [{ botId: 'persona', available: state.available }];
+ },
+ refetch: vi.fn(),
+ });
+ const view = render(() => (
+ <>
+ <p>Earlier conversation</p>
+ <AgentDmComposer channelId="dm" botId="persona">
+ <textarea aria-label="Message" />
+ </AgentDmComposer>
+ </>
+ ));
+ expect(view.getByText('Loading conversation…')).toBeTruthy();
+ expect(view.queryByRole('textbox')).toBeNull();
+ setState('status', 'success');
+ expect(view.getByRole('textbox')).toBeTruthy();
+ setState('available', false);
+ expect(view.queryByRole('textbox')).toBeNull();
+ expect(view.getByText(/no longer available/)).toBeTruthy();
+ expect(view.getByText('Earlier conversation')).toBeTruthy();
+ });
+
+ it('offers a retry for metadata failures without treating them as lost access', async () => {
+ const refetch = vi.fn();
+ mocks.query.mockReturnValue({
+ isPending: false,
+ isSuccess: false,
+ isError: true,
+ refetch,
+ });
+ const view = render(() => (
+ <AgentDmComposer channelId="dm" botId="persona">
+ <textarea />
+ </AgentDmComposer>
+ ));
+ await fireEvent.click(view.getByRole('button', { name: 'Try again' }));
+ expect(refetch).toHaveBeenCalledOnce();
+ expect(view.queryByText(/no longer available/)).toBeNull();
+ });
+
+ it('keeps the composer through a failed poll', () => {
+ const [state, setState] = createStore({ status: 'success' });
+ mocks.query.mockReturnValue({
+ isPending: false,
+ get isSuccess() {
+ return state.status === 'success';
+ },
+ get isError() {
+ return state.status === 'error';
+ },
+ // A failed refetch keeps the last data it loaded.
+ data: [{ botId: 'persona', available: true }],
+ refetch: vi.fn(),
+ });
+ let mounts = 0;
+ const Input = () => {
+ mounts += 1;
+ return <textarea aria-label="Message" />;
+ };
+ const view = render(() => (
+ <AgentDmComposer channelId="dm" botId="persona">
+ <Input />
+ </AgentDmComposer>
+ ));
+ expect(view.getByRole('textbox')).toBeTruthy();
+ setState('status', 'error');
+ expect(view.getByRole('textbox')).toBeTruthy();
+ expect(view.queryByText('Could not load this conversation.')).toBeNull();
+ expect(mounts).toBe(1);
+ });
+
+ it('keeps the input it already showed when the channel names its agent late', () => {
+ const [botId, setBotId] = createSignal<string>();
+ const [state, setState] = createStore({
+ status: 'pending',
+ available: true,
+ });
+ mocks.query.mockImplementation(
+ (_channelId: Accessor<string>, enabled: Accessor<boolean>) => ({
+ get isPending() {
+ return !enabled() || state.status === 'pending';
+ },
+ get isError() {
+ return enabled() && state.status === 'error';
+ },
+ get data() {
+ if (!enabled() || state.status !== 'success')
+ throw new Error('Pending data must not be read');
+ return [{ botId: 'persona', available: state.available }];
+ },
+ refetch: vi.fn(),
+ })
+ );
+ let mounts = 0;
+ const Input = () => {
+ mounts += 1;
+ return <textarea aria-label="Message" />;
+ };
+ const view = render(() => (
+ <AgentDmComposer channelId="dm" botId={botId()}>
+ <Input />
+ </AgentDmComposer>
+ ));
+ const input = view.getByRole('textbox');
+ input.focus();
+
+ // The channel's metadata names its agent after the input rendered.
+ setBotId('persona');
+ expect(view.queryByText('Loading conversation…')).toBeNull();
+ setState('status', 'success');
+ expect(view.getByRole('textbox')).toBe(input);
+ expect(document.activeElement).toBe(input);
+ expect(mounts).toBe(1);
+
+ // The input goes only once the conversation says the agent is gone.
+ setState('available', false);
+ expect(view.queryByRole('textbox')).toBeNull();
+ expect(view.getByText(/no longer available/)).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/features/agent-dms/agent-dm-composer.tsx b/apps/web/src/features/agent-dms/agent-dm-composer.tsx
new file mode 100644
index 0000000000..cd2766e28d
--- /dev/null
+++ b/apps/web/src/features/agent-dms/agent-dm-composer.tsx
@@ -0,0 +1,80 @@
+import { AgentConversationControls } from '@app/features/agent-conversations/agent-conversation-controls';
+import { useAgentConversations } from '@app/features/agent-conversations/queries/conversations';
+import { queryReadyGate } from '@queries/gate';
+import { createMemo, type ParentProps, Show } from 'solid-js';
+import { ConversationNotice } from './components/conversation-notice';
+
+/**
+ * App-facing composition; `botId` names the persona when the channel is an
+ * agent DM, and the composer is the channel's own otherwise.
+ *
+ * The input is the same element either way, so a DM whose metadata names its
+ * agent only after the channel first rendered keeps the input the user may
+ * already be typing in.
+ */
+export function AgentDmComposer(
+ props: ParentProps<{ channelId: string; botId: string | undefined }>
+) {
+ const conversations = useAgentConversations(
+ () => props.channelId,
+ () => props.botId !== undefined
+ );
+ // A failed poll keeps the last answer, so the composer stays mounted; only
+ // a conversation that never loaded shows the error.
+ const conversation = () =>
+ props.botId !== undefined && queryReadyGate(conversations)
+ ? conversations.data.find(
+ (conversation) => conversation.botId === props.botId
+ )
+ : undefined;
+ // A DM offers its input once the conversation says the agent is available.
+ // An input already on screen stays until the conversation says it is not.
+ const inputShown = createMemo<boolean>((shown) => {
+ if (props.botId === undefined) return true;
+ if (queryReadyGate(conversations))
+ return conversation()?.available === true;
+ return shown;
+ }, false);
+ const notice = () =>
+ queryReadyGate(conversations)
+ ? 'unavailable'
+ : conversations.isError
+ ? 'error'
+ : 'loading';
+ // In a DM, centered in the message column like the channel input it wraps:
+ // the input sizes itself to that column, and the controls and notices share
+ // its edges. Elsewhere the wrapper makes no box of its own.
+ return (
+ <div
+ class={
+ props.botId === undefined
+ ? 'contents'
+ : 'flex w-full min-w-0 flex-col items-center'
+ }
+ >
+ <Show when={conversation()}>
+ {(data) => (
+ <div class="macro-message-width">
+ <AgentConversationControls
+ conversation={data()}
+ onChanged={() => void conversations.refetch()}
+ />
+ </div>
+ )}
+ </Show>
+ <Show
+ when={inputShown()}
+ fallback={
+ <div class="macro-message-width">
+ <ConversationNotice
+ state={notice()}
+ onRetry={() => void conversations.refetch()}
+ />
+ </div>
+ }
+ >
+ {props.children}
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-dms/agent-dm-recipients.ts b/apps/web/src/features/agent-dms/agent-dm-recipients.ts
new file mode 100644
index 0000000000..30da2e5c41
--- /dev/null
+++ b/apps/web/src/features/agent-dms/agent-dm-recipients.ts
@@ -0,0 +1,31 @@
+import { MACRO_NEW_BOT_ID } from '@core/constant/macroNew';
+import { useUserId } from '@core/context/user';
+import { type CombinedRecipientItem, recipientEntityMapper } from '@core/user';
+import { useAgentsQuery } from '@queries/agents/agents';
+import { useCurrentTeamQuery } from '@queries/team/teams';
+import { createMemo } from 'solid-js';
+import { canDirectMessagePersona } from './core/personas';
+
+/** Production composition for the new-message picker's agent recipients. */
+export function useAgentDmRecipients() {
+ const userId = useUserId();
+ const team = useCurrentTeamQuery();
+ const agents = useAgentsQuery();
+ return createMemo<CombinedRecipientItem<'agent'>[]>(() => {
+ const teamId = team.isSuccess ? team.data?.team.id : undefined;
+ const visibleAgents = agents.isSuccess ? agents.data : [];
+ return [
+ recipientEntityMapper('agent')({
+ id: MACRO_NEW_BOT_ID,
+ name: 'Macro',
+ handle: 'macro',
+ description: 'Your private conversation with Macro',
+ }),
+ ...visibleAgents
+ .filter((agent) =>
+ canDirectMessagePersona(agent.bot.owner, userId(), teamId)
+ )
+ .map((agent) => recipientEntityMapper('agent')(agent.bot)),
+ ];
+ });
+}
diff --git a/apps/web/src/features/agent-dms/components/conversation-notice.tsx b/apps/web/src/features/agent-dms/components/conversation-notice.tsx
new file mode 100644
index 0000000000..7ec4dc719a
--- /dev/null
+++ b/apps/web/src/features/agent-dms/components/conversation-notice.tsx
@@ -0,0 +1,27 @@
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+
+export function ConversationNotice(props: {
+ state: 'loading' | 'error' | 'unavailable';
+ onRetry: () => void;
+}) {
+ return (
+ <div
+ class="flex items-center justify-between gap-3 px-4 py-3 text-sm text-ink-muted"
+ role="status"
+ >
+ <span>
+ {props.state === 'loading'
+ ? 'Loading conversation…'
+ : props.state === 'error'
+ ? 'Could not load this conversation.'
+ : 'This agent is no longer available to you. Your conversation is still here.'}
+ </span>
+ <Show when={props.state === 'error'}>
+ <Button variant="ghost" size="sm" onClick={props.onRetry}>
+ Try again
+ </Button>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-dms/components/persona-avatar.tsx b/apps/web/src/features/agent-dms/components/persona-avatar.tsx
new file mode 100644
index 0000000000..b0ff51d191
--- /dev/null
+++ b/apps/web/src/features/agent-dms/components/persona-avatar.tsx
@@ -0,0 +1,36 @@
+import { BotIcon } from '@channel/Message/BotIcon';
+import { firstPartyBotMark } from '@core/component/firstPartyBotMark';
+import { UserIcon } from '@core/component/UserIcon';
+import type { AvatarSize } from '@ui';
+import { Show } from 'solid-js';
+
+/** Persona avatar without a person's profile card or human DM action. */
+export function PersonaAvatar(props: {
+ botId: string;
+ name: string;
+ avatarUrl?: string | null;
+ class?: string;
+ size?: AvatarSize;
+}) {
+ return (
+ <Show
+ when={firstPartyBotMark(props.botId)}
+ fallback={
+ <BotIcon
+ name={props.name}
+ avatarUrl={props.avatarUrl}
+ size={props.size}
+ class={props.class}
+ />
+ }
+ >
+ <UserIcon
+ id={`bot|${props.botId}`}
+ size={props.size ?? 'md'}
+ class={props.class}
+ suppressClick
+ showTooltip={false}
+ />
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/agent-dms/core/personas.test.ts b/apps/web/src/features/agent-dms/core/personas.test.ts
new file mode 100644
index 0000000000..e82b17cc7b
--- /dev/null
+++ b/apps/web/src/features/agent-dms/core/personas.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import {
+ canDirectMessagePersona,
+ selectConversationRecipients,
+} from './personas';
+
+describe('private agent recipients', () => {
+ it('offers owned and team personas without granting DMs through a shared channel', () => {
+ expect(
+ canDirectMessagePersona({ type: 'user', user_id: 'me' }, 'me', 'team')
+ ).toBe(true);
+ expect(
+ canDirectMessagePersona({ type: 'team', team_id: 'team' }, 'me', 'team')
+ ).toBe(true);
+ expect(
+ canDirectMessagePersona(
+ { type: 'user', user_id: 'teammate' },
+ 'me',
+ 'team'
+ )
+ ).toBe(false);
+ expect(
+ canDirectMessagePersona(
+ { type: 'team', team_id: 'former-team' },
+ 'me',
+ 'team'
+ )
+ ).toBe(false);
+ expect(canDirectMessagePersona(undefined, 'me', 'team')).toBe(false);
+ });
+
+ it('switches between a private agent DM and a human group without mixing them', () => {
+ const alice = { kind: 'user', id: 'alice' };
+ const bob = { kind: 'user', id: 'bob' };
+ const agent = { kind: 'agent', id: 'researcher' };
+ expect(selectConversationRecipients([alice, bob, agent])).toEqual([agent]);
+ expect(selectConversationRecipients([agent, alice])).toEqual([alice]);
+ expect(selectConversationRecipients([alice, bob])).toEqual([alice, bob]);
+ expect(selectConversationRecipients([])).toEqual([]);
+ });
+});
diff --git a/apps/web/src/features/agent-dms/core/personas.ts b/apps/web/src/features/agent-dms/core/personas.ts
new file mode 100644
index 0000000000..23d9c95faf
--- /dev/null
+++ b/apps/web/src/features/agent-dms/core/personas.ts
@@ -0,0 +1,26 @@
+/** Ownership facts used to offer a private conversation with a persona. */
+type PersonaOwner =
+ | { type: 'user'; user_id: string }
+ | { type: 'team'; team_id: string };
+
+/** Sharing a channel with an agent does not make its private DM available. */
+export function canDirectMessagePersona(
+ owner: PersonaOwner | undefined | null,
+ userId: string | undefined,
+ teamId: string | undefined
+): boolean {
+ if (!owner || !userId) return false;
+ return owner.type === 'user'
+ ? owner.user_id === userId
+ : owner.team_id === teamId;
+}
+
+/** A private persona conversation cannot contain additional recipients. */
+export function selectConversationRecipients<T extends { kind: string }>(
+ next: T[]
+): T[] {
+ const newest = next.at(-1);
+ return newest?.kind === 'agent'
+ ? [newest]
+ : next.filter((recipient) => recipient.kind !== 'agent');
+}
diff --git a/apps/web/src/features/agent-dms/open-agent-dm.test.ts b/apps/web/src/features/agent-dms/open-agent-dm.test.ts
new file mode 100644
index 0000000000..2a66caff01
--- /dev/null
+++ b/apps/web/src/features/agent-dms/open-agent-dm.test.ts
@@ -0,0 +1,72 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ mobile: false,
+ createDm: vi.fn(),
+ replaceSplit: vi.fn(),
+ closeSettings: vi.fn(),
+ failure: vi.fn(),
+}));
+vi.mock('@queries/channel/get-or-create-dm', () => ({
+ useGetOrCreateDirectMessageMutation: () => ({
+ mutateAsync: mocks.createDm,
+ isPending: false,
+ }),
+}));
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => ({ replaceSplit: mocks.replaceSplit }),
+}));
+vi.mock('@core/constant/SettingsState', () => ({
+ useSettingsState: () => ({ closeSettings: mocks.closeSettings }),
+}));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => mocks.mobile }));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: mocks.failure },
+}));
+
+import { useOpenAgentDm } from './open-agent-dm';
+
+let dispose: (() => void) | undefined;
+
+function openAgentDm() {
+ return createRoot((root) => {
+ dispose = root;
+ return useOpenAgentDm();
+ });
+}
+
+beforeEach(() => {
+ mocks.mobile = false;
+ mocks.createDm.mockResolvedValue({ channel_id: 'dm' });
+});
+
+afterEach(() => {
+ dispose?.();
+ vi.clearAllMocks();
+});
+
+it('closes the settings sheet over a DM it opened on a phone', async () => {
+ mocks.mobile = true;
+ await openAgentDm().open('persona');
+ expect(mocks.createDm).toHaveBeenCalledWith({ recipient_id: 'bot|persona' });
+ expect(mocks.replaceSplit).toHaveBeenCalledWith({
+ content: { type: 'channel', id: 'dm' },
+ });
+ expect(mocks.closeSettings).toHaveBeenCalledOnce();
+});
+
+it('leaves settings to the split the DM replaced elsewhere', async () => {
+ await openAgentDm().open('persona');
+ expect(mocks.replaceSplit).toHaveBeenCalledOnce();
+ expect(mocks.closeSettings).not.toHaveBeenCalled();
+});
+
+it('keeps settings open when the DM could not be opened', async () => {
+ mocks.mobile = true;
+ mocks.createDm.mockRejectedValue(new Error('offline'));
+ await openAgentDm().open('persona');
+ expect(mocks.replaceSplit).not.toHaveBeenCalled();
+ expect(mocks.closeSettings).not.toHaveBeenCalled();
+ expect(mocks.failure).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/features/agent-dms/open-agent-dm.ts b/apps/web/src/features/agent-dms/open-agent-dm.ts
new file mode 100644
index 0000000000..3b87e21d1a
--- /dev/null
+++ b/apps/web/src/features/agent-dms/open-agent-dm.ts
@@ -0,0 +1,26 @@
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { toast } from '@core/component/Toast/Toast';
+import { useSettingsState } from '@core/constant/SettingsState';
+import { isMobile } from '@core/mobile/isMobile';
+import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
+
+/** App navigation adapter for a persona's Message action. */
+export function useOpenAgentDm() {
+ const mutation = useGetOrCreateDirectMessageMutation();
+ const { replaceSplit } = useSplitLayout();
+ const settings = useSettingsState();
+
+ const open = async (botId: string) => {
+ try {
+ const dm = await mutation.mutateAsync({ recipient_id: `bot|${botId}` });
+ replaceSplit({ content: { type: 'channel', id: dm.channel_id } });
+ // On a phone, settings is a sheet over the conversation just opened;
+ // elsewhere the conversation took the settings split's place.
+ if (isMobile()) settings.closeSettings();
+ } catch {
+ toast.failure('Could not open this conversation. Please try again.');
+ }
+ };
+
+ return { open, pending: () => mutation.isPending };
+}
diff --git a/apps/web/src/features/agent-dms/queries/search-pool.ts b/apps/web/src/features/agent-dms/queries/search-pool.ts
new file mode 100644
index 0000000000..52b85a6f45
--- /dev/null
+++ b/apps/web/src/features/agent-dms/queries/search-pool.ts
@@ -0,0 +1,29 @@
+import type { ChannelEntity } from '@entity/types/entity';
+import { useListChannelsQuery } from '@queries/channel/channels';
+import { createMemo } from 'solid-js';
+
+/** The existing complete channel list finds personas beyond the visible soup page. */
+export function useAgentDmSearchPool() {
+ const channels = useListChannelsQuery();
+ return createMemo<ChannelEntity[]>(() =>
+ channels.isSuccess
+ ? channels.data.flatMap((channel) =>
+ channel.agent_dm
+ ? [
+ {
+ id: channel.id,
+ type: 'channel' as const,
+ name: channel.agent_dm.name,
+ channelType: 'direct_message' as const,
+ ownerId: channel.owner_id,
+ isParticipant: channel.is_participant,
+ participantIds: channel.participants.map(
+ (participant) => participant.user_id
+ ),
+ },
+ ]
+ : []
+ )
+ : []
+ );
+}
diff --git a/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx b/apps/web/src/features/agent-interactions/components/ElicitationForm.test.tsx
similarity index 100%
rename from apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx
rename to apps/web/src/features/agent-interactions/components/ElicitationForm.test.tsx
diff --git a/apps/web/src/features/block-agent/ui/ElicitationForm.tsx b/apps/web/src/features/agent-interactions/components/ElicitationForm.tsx
similarity index 100%
rename from apps/web/src/features/block-agent/ui/ElicitationForm.tsx
rename to apps/web/src/features/agent-interactions/components/ElicitationForm.tsx
diff --git a/apps/web/src/features/agent-interactions/components/InteractionCard.tsx b/apps/web/src/features/agent-interactions/components/InteractionCard.tsx
new file mode 100644
index 0000000000..505899eac8
--- /dev/null
+++ b/apps/web/src/features/agent-interactions/components/InteractionCard.tsx
@@ -0,0 +1,107 @@
+import type { MessagePart } from '@service-agent-fold/generated/types';
+import { Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import type {
+ AgentInteraction,
+ InteractionController,
+} from '../context/interaction';
+import {
+ LiveQuestionCard,
+ parseDraftedTool,
+ type RespondToElicitation,
+ UserToolComposer,
+} from './LiveElicitation';
+import { PermissionCard } from './PermissionCard';
+
+/**
+ * Full live approvals and questions shared by conversation surfaces. Each
+ * card is capped at a fixed height and scrolls inside, so a long form or a
+ * draft under review never pushes the conversation off screen.
+ */
+export function InteractionCard(props: {
+ request: AgentInteraction;
+ controller: InteractionController;
+ tool?: Extract<MessagePart, { kind: 'tool_use' }>;
+}) {
+ const locked = () =>
+ !props.controller.canAnswer() || props.controller.answering(props.request);
+ return match(props.request)
+ .with({ kind: 'permission' }, (request) => (
+ <div class="max-h-80 min-w-0 overflow-y-auto rounded-xl">
+ <PermissionCard
+ options={request.options}
+ canAnswer={props.controller.canAnswer()}
+ disabled={locked()}
+ action={
+ props.tool?.name.kind === 'native'
+ ? props.tool.name.name
+ : props.tool?.name.tool
+ }
+ detail={
+ props.tool?.detail.kind === 'terminal'
+ ? (props.tool.detail.command ?? undefined)
+ : JSON.stringify(props.tool?.detail, null, 2)
+ }
+ onSelect={(optionId) =>
+ void props.controller.respond({
+ ...request,
+ answer: { kind: 'selected', optionId },
+ })
+ }
+ />
+ </div>
+ ))
+ .with({ kind: 'elicitation' }, (request) => {
+ // Keep the answer's typed shape intact; the controller checks liveness.
+ const onRespond: RespondToElicitation = (answer) =>
+ props.controller.respond({ ...request, answer });
+ const content = () => {
+ if (request.request.kind !== 'user_tool')
+ return (
+ <LiveQuestionCard
+ request={request.request}
+ locked={locked()}
+ onRespond={onRespond}
+ />
+ );
+ const fallback = (
+ <LiveQuestionCard
+ request={{ kind: 'form', schema: request.request.schema }}
+ locked={locked()}
+ onRespond={onRespond}
+ />
+ );
+ const toolCall = request.toolCall ?? String(request.requestId);
+ const draft = parseDraftedTool(request.request, toolCall);
+ return (
+ <Show when={draft} fallback={fallback}>
+ {(tool) => (
+ <UserToolComposer
+ tool={tool()}
+ toolCall={toolCall}
+ cancel
+ fallback={fallback}
+ review={{ canAnswer: () => !locked(), respond: onRespond }}
+ />
+ )}
+ </Show>
+ );
+ };
+ return (
+ <section
+ aria-label="Agent question"
+ class="max-h-80 space-y-3 overflow-y-auto rounded-xl border border-edge-muted bg-panel p-4"
+ >
+ <p class="text-sm font-medium">{request.message}</p>
+ <Show when={!props.controller.canAnswer()}>
+ <p class="text-xs text-ink-muted">
+ This agent is no longer available. You can still read the
+ conversation.
+ </p>
+ </Show>
+ {content()}
+ </section>
+ );
+ })
+ .exhaustive();
+}
diff --git a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx b/apps/web/src/features/agent-interactions/components/LiveElicitation.tsx
similarity index 98%
rename from apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
rename to apps/web/src/features/agent-interactions/components/LiveElicitation.tsx
index b30224fc31..a3c389edb1 100644
--- a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx
+++ b/apps/web/src/features/agent-interactions/components/LiveElicitation.tsx
@@ -41,9 +41,9 @@ import {
initialValues,
toContent,
validate,
-} from '../../state/elicitation-form';
-import { createElicitationReviewSink } from '../../state/elicitation-review-sink';
-import { ElicitationForm } from '../../ui';
+} from '../state/elicitation-form';
+import { createElicitationReviewSink } from '../state/elicitation-review-sink';
+import { ElicitationForm } from './ElicitationForm';
export type RespondToElicitation = (
answer: ElicitationAnswer
diff --git a/apps/web/src/features/block-agent/ui/PermissionCard.tsx b/apps/web/src/features/agent-interactions/components/PermissionCard.tsx
similarity index 100%
rename from apps/web/src/features/block-agent/ui/PermissionCard.tsx
rename to apps/web/src/features/agent-interactions/components/PermissionCard.tsx
diff --git a/apps/web/src/features/block-agent/ui/PermissionOptions.tsx b/apps/web/src/features/agent-interactions/components/PermissionOptions.tsx
similarity index 100%
rename from apps/web/src/features/block-agent/ui/PermissionOptions.tsx
rename to apps/web/src/features/agent-interactions/components/PermissionOptions.tsx
diff --git a/apps/web/src/features/block-agent/context/interaction.ts b/apps/web/src/features/agent-interactions/context/interaction.ts
similarity index 100%
rename from apps/web/src/features/block-agent/context/interaction.ts
rename to apps/web/src/features/agent-interactions/context/interaction.ts
diff --git a/apps/web/src/features/block-agent/primitives/create-interaction-controller.test.ts b/apps/web/src/features/agent-interactions/primitives/create-interaction-controller.test.ts
similarity index 100%
rename from apps/web/src/features/block-agent/primitives/create-interaction-controller.test.ts
rename to apps/web/src/features/agent-interactions/primitives/create-interaction-controller.test.ts
diff --git a/apps/web/src/features/block-agent/primitives/create-interaction-controller.ts b/apps/web/src/features/agent-interactions/primitives/create-interaction-controller.ts
similarity index 100%
rename from apps/web/src/features/block-agent/primitives/create-interaction-controller.ts
rename to apps/web/src/features/agent-interactions/primitives/create-interaction-controller.ts
diff --git a/apps/web/src/features/block-agent/state/elicitation-form.test.ts b/apps/web/src/features/agent-interactions/state/elicitation-form.test.ts
similarity index 100%
rename from apps/web/src/features/block-agent/state/elicitation-form.test.ts
rename to apps/web/src/features/agent-interactions/state/elicitation-form.test.ts
diff --git a/apps/web/src/features/block-agent/state/elicitation-form.ts b/apps/web/src/features/agent-interactions/state/elicitation-form.ts
similarity index 100%
rename from apps/web/src/features/block-agent/state/elicitation-form.ts
rename to apps/web/src/features/agent-interactions/state/elicitation-form.ts
diff --git a/apps/web/src/features/block-agent/state/elicitation-review-sink.ts b/apps/web/src/features/agent-interactions/state/elicitation-review-sink.ts
similarity index 100%
rename from apps/web/src/features/block-agent/state/elicitation-review-sink.ts
rename to apps/web/src/features/agent-interactions/state/elicitation-review-sink.ts
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index 5da0e88efb..1bd5e1742b 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -1,5 +1,6 @@
/** App-facing composition for the agent session and its controllers. */
+import { createInteractionController } from '@app/features/agent-interactions/primitives/create-interaction-controller';
import { AgentSession } from '@core/agent-session/AgentSession';
import { toast } from '@core/component/Toast/Toast';
import { isCodexBotId } from '@core/constant/codexAgent';
@@ -29,7 +30,6 @@ import {
import { resolveSessionId } from './context/resolve-session-id';
import { createSendNext } from './context/send-next';
import { createSteer } from './context/steer';
-import { createInteractionController } from './primitives/create-interaction-controller';
import { createToolApprovalController } from './primitives/create-tool-approval-controller';
import type { QuoteInsert } from './ui';
@@ -81,6 +81,8 @@ export function AgentSessionProvider(
parts: [{ kind: 'text', text: prompt }],
stop: null,
pending: true,
+ segments: [],
+ phase: null,
},
];
};
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index d65dbf1651..fda6459e5c 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -162,6 +162,8 @@ const message = (
agentSessionId: 'session',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 0,
author: { kind: 'agent' },
parts,
diff --git a/apps/web/src/features/block-agent/component/PermissionRequest.tsx b/apps/web/src/features/block-agent/component/PermissionRequest.tsx
index 5f5c9d6558..85757942c7 100644
--- a/apps/web/src/features/block-agent/component/PermissionRequest.tsx
+++ b/apps/web/src/features/block-agent/component/PermissionRequest.tsx
@@ -1,6 +1,6 @@
+import { PermissionCard } from '@app/features/agent-interactions/components/PermissionCard';
import type { PendingPermission } from '@service-agent-fold/generated/types';
import { useOptionalAgentSession } from '../context/AgentSessionContext';
-import { PermissionCard } from '../ui/PermissionCard';
import { toolCallDetail, toolLabel } from './parts/shared';
/** Live approval above the composer, with context from the requested tool. */
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
index 57b2880de6..d0025b8569 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
@@ -6,6 +6,7 @@
* URL is never opened without the user pressing Open.
*/
+import type { InteractionResponse } from '@app/features/agent-interactions/context/interaction';
import type {
MessagePart,
PendingElicitation,
@@ -14,7 +15,6 @@ import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas
import { fireEvent, render } from '@solidjs/testing-library';
import type { JSX } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { InteractionResponse } from '../../context/interaction';
const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();
let pending: PendingElicitation | undefined;
@@ -60,6 +60,9 @@ vi.mock('../../ui', () => ({
<div data-testid="body">{props.children}</div>
</div>
),
+}));
+
+vi.mock('@app/features/agent-interactions/components/ElicitationForm', () => ({
ElicitationForm: (props: {
schema: { properties: { name: string; schema: { type: string } }[] };
onChange: (name: string, value: unknown) => void;
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
index 135a833469..b78943b22f 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
@@ -13,6 +13,13 @@
* under review opens the tool's own composer here.
*/
+import {
+ LiveQuestionCard,
+ parseDraftedTool,
+ type RespondToElicitation,
+ UserToolComposer,
+ type UserToolRequest,
+} from '@app/features/agent-interactions/components/LiveElicitation';
import type {
AnsweredField,
AnsweredValue,
@@ -22,13 +29,6 @@ import { createMemo, For, Show } from 'solid-js';
import { match, P } from 'ts-pattern';
import { useAgentSession } from '../../context/AgentSessionContext';
import { ToolCard } from '../../ui';
-import {
- LiveQuestionCard,
- parseDraftedTool,
- type RespondToElicitation,
- UserToolComposer,
- type UserToolRequest,
-} from './LiveElicitation';
import { UserToolCall } from './UserToolCall';
type ElicitationPartData = Extract<MessagePart, { kind: 'elicitation' }>;
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index 33251c8524..8cbd3be2aa 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -1,5 +1,6 @@
/** Feature-owned session state and its provider/consumer boundary. */
+import type { InteractionController } from '@app/features/agent-interactions/context/interaction';
import type { IssueResult } from '@core/agent-session/AgentSession';
import type {
FoldedMessage,
@@ -16,7 +17,6 @@ import type { ToolApprovalController } from '../primitives/create-tool-approval-
import type { EffortSelection } from '../state/session-config';
import type { QuoteInsert } from '../ui';
import type { QueueController } from './create-queue-controller';
-import type { InteractionController } from './interaction';
export type AgentSessionState = {
/** The viewer and display-name lookup supplied by production composition. */
diff --git a/apps/web/src/features/block-agent/context/pending-session.test.tsx b/apps/web/src/features/block-agent/context/pending-session.test.tsx
index f9376fa1e4..5593144b10 100644
--- a/apps/web/src/features/block-agent/context/pending-session.test.tsx
+++ b/apps/web/src/features/block-agent/context/pending-session.test.tsx
@@ -155,6 +155,8 @@ describe('pending navigation ownership', () => {
parts: [{ kind: 'text', text: 'Hello' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
{
@@ -167,6 +169,8 @@ describe('pending navigation ownership', () => {
parts: [{ kind: 'text', text: 'Ready' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
] satisfies FoldedStreamEvent[]);
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 37cfe03c3e..d947b81334 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -4,6 +4,10 @@
* `/component/agent-ui`.
*/
+import {
+ initialValues,
+ validate,
+} from '@app/features/agent-interactions/state/elicitation-form';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { MagicChipView } from '@core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView';
import type { MagicChipPresentation } from '@core/component/LexicalMarkdown/component/decorator/MagicChip/presentation';
@@ -26,7 +30,6 @@ import { createSignal, type JSX, onCleanup } from 'solid-js';
import { createStore } from 'solid-js/store';
import { Message } from '../component/AgentMessage';
import { ReplyToSelection } from '../component/ReplyToSelection';
-import { initialValues, validate } from '../state/elicitation-form';
import {
ActionLine,
AgentInput,
@@ -403,6 +406,8 @@ function ToolReplayDemo() {
agentSessionId: 'tool-replay',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 0,
author: { kind: 'agent' },
stop: inFlight() ? null : { kind: 'end_turn' },
@@ -450,6 +455,8 @@ function DisplayResultsDemo() {
agentSessionId: 'display-results-demo',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 0,
author: { kind: 'agent' },
stop: pending() ? null : { kind: 'end_turn' },
@@ -517,6 +524,8 @@ const FIXTURE_MESSAGE: FoldedMessage = {
agentSessionId: 'demo',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 0,
author: { kind: 'agent' },
stop: { kind: 'end_turn' },
@@ -763,6 +772,8 @@ const FIXTURE_IN_FLIGHT: FoldedMessage = {
agentSessionId: 'demo',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 1,
author: { kind: 'agent' },
stop: null,
@@ -806,6 +817,8 @@ const FIXTURE_UNCLOSED: FoldedMessage = {
agentSessionId: 'demo',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 2,
author: { kind: 'agent' },
stop: null,
@@ -872,6 +885,8 @@ function PromptAuthorDemo() {
agentSessionId: 'demo',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn: 0,
author: { kind: 'user', userId },
stop: null,
diff --git a/apps/web/src/features/block-agent/state/live-turn.test.ts b/apps/web/src/features/block-agent/state/live-turn.test.ts
index 20ce8e4220..632aa057a5 100644
--- a/apps/web/src/features/block-agent/state/live-turn.test.ts
+++ b/apps/web/src/features/block-agent/state/live-turn.test.ts
@@ -5,6 +5,8 @@ import { isLiveTurn, liveTurnMessage } from './live-turn';
const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({
agentSessionId: 'session',
pending: false,
+ segments: [],
+ phase: null,
requestId: null,
turn,
author: { kind: 'agent' },
@@ -14,6 +16,8 @@ const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({
const user = (turn: number): FoldedMessage => ({
agentSessionId: 'session',
pending: false,
+ segments: [],
+ phase: null,
requestId: null,
turn,
author: { kind: 'user', userId: 'u' },
@@ -23,6 +27,8 @@ const user = (turn: number): FoldedMessage => ({
const control = (turn: number): FoldedMessage => ({
agentSessionId: 'session',
pending: false,
+ segments: [],
+ phase: null,
requestId: 'r',
turn,
author: { kind: 'user', userId: 'u' },
diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.ts
index 1e16da09f8..48b74265c1 100644
--- a/apps/web/src/features/block-agent/state/session-summary.test.ts
+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts
@@ -14,6 +14,8 @@ function message(turn: number, parts: MessagePart[]): FoldedMessage {
agentSessionId: 'session',
requestId: null,
pending: false,
+ segments: [],
+ phase: null,
turn,
author: { kind: 'agent' },
parts,
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index b4e74c4789..30163c5170 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -6,6 +6,16 @@
* opencode); see individual file headers.
*/
+export {
+ ElicitationForm,
+ type ElicitationFormProps,
+} from '@app/features/agent-interactions/components/ElicitationForm';
+export {
+ type PermissionOptionItem,
+ type PermissionOptionKind,
+ PermissionOptions,
+ type PermissionOptionsProps,
+} from '@app/features/agent-interactions/components/PermissionOptions';
export { ActionLine, type ActionLineProps } from './ActionLine';
export {
AGENT_INPUT_TEXT_AREA_ID,
@@ -21,10 +31,6 @@ export {
} from './ComposerNotice';
export { type CountItem, CountSummary } from './CountSummary';
export { DiffChanges, type DiffChangesProps } from './DiffChanges';
-export {
- ElicitationForm,
- type ElicitationFormProps,
-} from './ElicitationForm';
export {
FailureNoticeCard,
type FailureNoticeCardProps,
@@ -33,12 +39,6 @@ export { FoldedAnsiText } from './FoldedAnsiText';
export { FoldedOutput } from './FoldedOutput';
export { FoldedPathList } from './FoldedPathList';
export { FoldedTerminal } from './FoldedTerminal';
-export {
- type PermissionOptionItem,
- type PermissionOptionKind,
- PermissionOptions,
- type PermissionOptionsProps,
-} from './PermissionOptions';
export { PierreDiff } from './PierreDiff';
export { QuestionAnswers, type QuestionAnswersProps } from './QuestionAnswers';
export {
diff --git a/apps/web/src/features/block-channel/component/Compose.tsx b/apps/web/src/features/block-channel/component/Compose.tsx
index 4e50f36be6..324ce07f62 100644
--- a/apps/web/src/features/block-channel/component/Compose.tsx
+++ b/apps/web/src/features/block-channel/component/Compose.tsx
@@ -1,3 +1,5 @@
+import { useAgentDmRecipients } from '@app/features/agent-dms/agent-dm-recipients';
+import { selectConversationRecipients } from '@app/features/agent-dms/core/personas';
import {
applyInlineFormat,
applyNodeFormat,
@@ -23,6 +25,7 @@ import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-
import { ComposerEditor } from '@core/component/LexicalMarkdown/component/ComposerEditor';
import { createComposerLayout } from '@core/component/LexicalMarkdown/utils/create-composer-layout';
import { RecipientSelector } from '@core/component/RecipientSelector';
+import { ENABLE_AGENT_DMS } from '@core/constant/featureFlags';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
import {
@@ -41,6 +44,7 @@ import {
} from '@core/util/upload';
import InfoIcon from '@phosphor/info.svg';
import { useCreateChannelMutation } from '@queries/channel/channels';
+import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';
import { ComposerSurface } from '@ui';
import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
@@ -48,11 +52,19 @@ export function ChannelCompose() {
const [layout, setLayout] = createSignal<HTMLDivElement>();
const [channelName, setChannelName] = createSignal<string>('');
- const { users: destinationOptions } = useCombinedRecipients();
+ const { users: humanOptions } = useCombinedRecipients();
+ const agentOptions = ENABLE_AGENT_DMS ? useAgentDmRecipients() : () => [];
+ const destinationOptions = () => [...humanOptions(), ...agentOptions()];
const [selectedRecipients, setSelectedRecipients] = createSignal<
- WithCustomUserInput<'user' | 'contact'>[]
+ WithCustomUserInput<'user' | 'contact' | 'agent'>[]
>([]);
+ const selectRecipients = (
+ next: WithCustomUserInput<'user' | 'contact' | 'agent'>[]
+ ) => {
+ setSelectedRecipients(selectConversationRecipients(next));
+ };
+
const selectedRecipientCount = createMemo(() => selectedRecipients().length);
createEffect(
@@ -73,6 +85,8 @@ export function ChannelCompose() {
});
const dmUserName = createMemo(() => {
+ const recipient = selectedRecipients()[0];
+ if (recipient?.kind === 'agent') return recipient.data.name;
const id = dmUserId();
return id ? getDisplayName(tryMacroId(id)) : undefined;
});
@@ -90,6 +104,7 @@ export function ChannelCompose() {
const names = recipients
.slice(0, 2)
.map((r) => {
+ if (r.kind === 'agent') return r.data.name;
if (r.kind === 'user') {
return getDisplayName(tryMacroId(r.data.id));
}
@@ -109,6 +124,7 @@ export function ChannelCompose() {
const { sendToUsers, sendToChannel } = useSendMessageToPeople();
const createChannelMutation = useCreateChannelMutation();
+ const createDm = useGetOrCreateDirectMessageMutation();
async function handleSend(snapshot: InputSnapshot) {
setError(undefined);
@@ -125,6 +141,26 @@ export function ChannelCompose() {
});
try {
+ const persona = recipients.find(
+ (recipient) => recipient.kind === 'agent'
+ );
+ if (persona) {
+ const dm = await createDm.mutateAsync({
+ recipient_id: `bot|${persona.data.id}`,
+ });
+ const sent = await sendToChannel({
+ channelId: dm.channel_id,
+ content,
+ mentions,
+ attachments,
+ navigate: { navigate: true, mergeHistory: true },
+ });
+ if (!sent)
+ throw new Error(
+ 'Could not send your message. Your draft has been kept.'
+ );
+ return;
+ }
if (
destination.type === 'users' &&
channelName() &&
@@ -249,11 +285,15 @@ export function ChannelCompose() {
}
}}
/>
- <RecipientSelector<'user' | 'contact'>
+ <RecipientSelector<'user' | 'contact' | 'agent'>
options={destinationOptions}
selectedOptions={selectedRecipients()}
- setSelectedOptions={setSelectedRecipients}
- placeholder="To: Macro users or email addresses"
+ setSelectedOptions={selectRecipients}
+ placeholder={
+ ENABLE_AGENT_DMS
+ ? 'To: People, agents, or email addresses'
+ : 'To: Macro users or email addresses'
+ }
triedToSubmit={triedToSubmit}
focusOnMount
hideMenuOnEscape
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
index b3ed8e7a6d..8f3686de59 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.test.tsx
@@ -79,7 +79,10 @@ vi.mock('@channel/channel-picture', () => ({}));
vi.mock('@components/app/split-layout/components/SplitFileMenu', () => ({}));
vi.mock('@components/app/split-layout/components/SplitLabel', () => ({}));
vi.mock('@components/app/split-layout/components/SplitHeader', () => ({}));
-vi.mock('@core/context/channels', () => ({}));
+vi.mock('@core/context/channels', () => ({
+ useChannel: () => () => undefined,
+ useChannelCanCall: () => () => true,
+}));
vi.mock('@core/context/user', () => ({}));
vi.mock('@queries/call/call', () => ({}));
vi.mock('@queries/channel/channel-participants', () => ({}));
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index f3eadb283f..8d435cb612 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -65,6 +65,7 @@ import { useBlockId } from '@core/block';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
import {
useChannel,
+ useChannelCanCall,
useChannelName,
useChannelType,
} from '@core/context/channels';
@@ -281,7 +282,9 @@ function NewTop(props: { channelId: string }) {
)}
</Show>
{/* Hidden once the user has joined — the call surface owns the UI. */}
- <Show when={ENABLE_CALLS && !call.isInThisChannel()}>
+ <Show
+ when={ENABLE_CALLS && !channel()?.agent_dm && !call.isInThisChannel()}
+ >
<SplitHeaderRight>
<HeaderIsland
class={cn(
@@ -319,6 +322,8 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
const canAutofocusSplitContent = useCanAutofocusSplitContent();
const { navigatedFromJK } = useNavigatedFromJK();
const channelId = useBlockId();
+ const conversationChannel = useChannel(channelId);
+ const canCall = useChannelCanCall(channelId);
const blockHandle = blockHandleSignal.get;
const [searchParams, setSearchParams] = useSearchParams();
const [routeSearch] = createSearchParams(channelsSearch);
@@ -397,6 +402,13 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
: undefined,
})
);
+ createComputed(() => {
+ if (
+ conversationChannel()?.agent_dm &&
+ ['call', 'calls', 'participants'].includes(activeTab())
+ )
+ setActiveTabInternal(DEFAULT_CHANNEL_TAB);
+ });
const [pendingJoinCall, setPendingJoinCall] = createSignal(wantsJoinCall);
// Navigation flows into the surface as state; the messages part navigates
@@ -408,7 +420,12 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
let surfaceApi: ChannelSurfaceApi | undefined;
const setActiveTab = (tab: ChannelTabId) => {
- setActiveTabInternal(normalizeChannelTab(tab));
+ setActiveTabInternal(
+ conversationChannel()?.agent_dm &&
+ ['call', 'calls', 'participants'].includes(tab)
+ ? DEFAULT_CHANNEL_TAB
+ : normalizeChannelTab(tab)
+ );
};
createEffect(
@@ -528,6 +545,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
<CallEventSync />
<ChannelTabProvider activeTab={activeTab} setActiveTab={setActiveTab}>
<ChannelCallAutoJoin
+ canCall={canCall}
channelId={channelId}
pendingJoinCall={pendingJoinCall}
onHandled={() => setPendingJoinCall(false)}
diff --git a/apps/web/src/features/channel/Bots/BotDetailPage.tsx b/apps/web/src/features/channel/Bots/BotDetailPage.tsx
index 8a10ea257a..33aaba5e3b 100644
--- a/apps/web/src/features/channel/Bots/BotDetailPage.tsx
+++ b/apps/web/src/features/channel/Bots/BotDetailPage.tsx
@@ -1,5 +1,8 @@
+import { canDirectMessagePersona } from '@app/features/agent-dms/core/personas';
+import { useOpenAgentDm } from '@app/features/agent-dms/open-agent-dm';
import { LoadingSpinner } from '@core/component/LoadingSpinner';
import { toast } from '@core/component/Toast/Toast';
+import { ENABLE_AGENT_DMS } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import CaretLeftIcon from '@phosphor/caret-left.svg';
@@ -35,6 +38,7 @@ import { CreateBotTokenDialog } from './CreateBotTokenDialog';
import { createBotAvatarUpload } from './createBotAvatarUpload';
export function BotDetail(props: { botId: string; onBack: () => void }) {
+ const agentDm = ENABLE_AGENT_DMS ? useOpenAgentDm() : undefined;
const channelsContext = useChannelsContext();
const currentUserId = useUserId();
const currentTeamQuery = useCurrentTeamQuery();
@@ -237,6 +241,28 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {
@{form.handle || bot().handle}
</p>
</div>
+ <Show
+ when={
+ agentDm &&
+ bot().has_agent &&
+ canDirectMessagePersona(
+ bot().owner,
+ currentUserId(),
+ currentTeamQuery.data?.team.id
+ )
+ }
+ >
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ class="ml-auto"
+ disabled={agentDm?.pending()}
+ onClick={() => void agentDm?.open(props.botId)}
+ >
+ Message
+ </Button>
+ </Show>
</header>
<BotFormSection
diff --git a/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx b/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx
index 4a25394480..7c1bf7b7b5 100644
--- a/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx
+++ b/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx
@@ -16,6 +16,8 @@ export function ChannelCallAutoJoin(props: {
channelId: string;
pendingJoinCall: Accessor<boolean>;
onHandled: () => void;
+ /** Wait for metadata; agent DMs cannot host calls. */
+ canCall?: Accessor<boolean | undefined>;
}) {
const { setActiveTab } = useChannelTab();
// Mirror ChannelCallButton's tab-sync behavior so leaving via the
@@ -28,6 +30,13 @@ export function ChannelCallAutoJoin(props: {
createEffect(() => {
if (!props.pendingJoinCall()) return;
+ const canCall = props.canCall ? props.canCall() : true;
+ if (canCall === undefined) return;
+ if (!canCall) {
+ setActiveTab(getCallLeaveTab());
+ props.onHandled();
+ return;
+ }
untrack(() => {
if (!ENABLE_CALLS) {
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsx
index 2cdbfb5cb7..06fb69401c 100644
--- a/apps/web/src/features/channel/Channel/Channel.tsx
+++ b/apps/web/src/features/channel/Channel/Channel.tsx
@@ -1,3 +1,10 @@
+import { AgentTypingProvider } from '@app/features/agent-activity/agent-typing';
+import {
+ AgentConversationContextBoundary,
+ AgentConversationMessageStatus,
+} from '@app/features/agent-conversations/agent-conversation-message';
+import { AgentConversationsProvider } from '@app/features/agent-conversations/agent-conversations-provider';
+import { AgentDmComposer } from '@app/features/agent-dms/agent-dm-composer';
import { openChatWithInput } from '@app/features/chat/ChatWithAgentButton';
import { createActivityTracker } from '@channel/activity-tracker';
import { useStartChannelCall } from '@channel/Call/use-start-channel-call';
@@ -32,6 +39,7 @@ import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component
import { toast } from '@core/component/Toast/Toast';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
import {
+ useChannel,
useChannelActivity,
useChannelName,
useChannelType,
@@ -378,6 +386,7 @@ export function Channel(props: ChannelProps) {
});
const channelName = useChannelName(props.channelId);
+ const channel = useChannel(props.channelId);
const channelType = useChannelType(props.channelId);
const { popoverSplit } = useSplitLayout();
@@ -386,6 +395,7 @@ export function Channel(props: ChannelProps) {
const inputPlaceholderName = () => {
const name = channelName();
if (!name) return undefined;
+ if (channel()?.agent_dm) return name;
if (channelType() !== ChannelTypeEnum.DirectMessage) return `#${name}`;
const parts = name.split(' ');
return parts.length === 2 && !parts[0]?.endsWith(',') ? parts[0] : name;
@@ -393,6 +403,7 @@ export function Channel(props: ChannelProps) {
const inputPlaceholder = () => {
const name = inputPlaceholderName();
+ if (channel()?.agent_dm) return `Message ${name ?? 'agent'}`;
return name ? `Type @ to share with ${name}` : 'Type @ to share';
};
@@ -704,376 +715,426 @@ export function Channel(props: ChannelProps) {
});
return (
- <EntityLoadGate
- result={messagesLoadResult}
- loadErrorTitle="Unable to load this channel"
- onRetry={() => void messagesQuery.refetch()}
+ <AgentConversationsProvider
+ channelId={props.channelId}
+ // Only an agent DM has a conversing agent so far.
+ hasAgents={!!channel()?.agent_dm}
>
- <DebugSuspense name="Channel.root">
- <deleteConfirmation.ConfirmationDialog />
- <StaticMarkdownContext host="channel">
- <SearchHighlightTermsProvider
- value={findBar.getSearchTermsForMessage}
- >
- <MaybeMessageActionDrawerManager>
- <ChannelDropZone dragState={dragState}>
- <div
- class="ph-no-capture relative flex-1 min-h-0 outline-none flex flex-col"
- ref={(element) => {
- attachMessageListRef(element);
- messagesTarget(element);
- }}
- tabIndex={-1}
- data-channel-message-list
- >
- <Show when={findBar.isOpen()}>
- <FindBar
- class="absolute top-2 right-3 z-10 w-80 max-w-[calc(100%-1.5rem)] touch:top-[calc(var(--mobile-content-inset-top,0)+0.5rem)]"
- controller={findBar}
- direction="desc"
- />
- </Show>
- <Show when={messageIndex.entryKeys.length > 0}>
- <div
- class="relative flex-1 min-h-0"
- ref={setThreadListContainerEl}
- >
- <MessageNotificationIndexContext.Provider
- value={unread.unreadByMessage}
+ <EntityLoadGate
+ result={messagesLoadResult}
+ loadErrorTitle="Unable to load this channel"
+ onRetry={() => void messagesQuery.refetch()}
+ >
+ <DebugSuspense name="Channel.root">
+ <deleteConfirmation.ConfirmationDialog />
+ <StaticMarkdownContext host="channel">
+ <SearchHighlightTermsProvider
+ value={findBar.getSearchTermsForMessage}
+ >
+ <MaybeMessageActionDrawerManager>
+ <ChannelDropZone dragState={dragState}>
+ <div
+ class="ph-no-capture relative flex-1 min-h-0 outline-none flex flex-col"
+ ref={(element) => {
+ attachMessageListRef(element);
+ messagesTarget(element);
+ }}
+ tabIndex={-1}
+ data-channel-message-list
+ >
+ <Show when={findBar.isOpen()}>
+ <FindBar
+ class="absolute top-2 right-3 z-10 w-80 max-w-[calc(100%-1.5rem)] touch:top-[calc(var(--mobile-content-inset-top,0)+0.5rem)]"
+ controller={findBar}
+ direction="desc"
+ />
+ </Show>
+ <Show when={messageIndex.entryKeys.length > 0}>
+ <div
+ class="relative flex-1 min-h-0"
+ ref={setThreadListContainerEl}
>
- <SwipableRowProvider
- container={threadListContainerEl}
- triggerBehavior="spring-back"
+ <MessageNotificationIndexContext.Provider
+ value={unread.unreadByMessage}
>
- <ThreadList
- keys={() => messageIndex.entryKeys}
- targetId={
- targetMessageController.hasPendingElementScroll()
- ? targetMessageController.activeTargetMessageId()
- : undefined
- }
- insets={threadListScrollInsets()}
- followOnAppend={!messagesQuery.hasPreviousPage}
- onScrollNearTop={threadPaginator.shiftPaginate}
- onScrollNearBottom={threadPaginator.prependPaginate}
- onReady={onThreadListReady}
- onScroll={onThreadListScroll}
- onUserNavigation={cancelLatestNavigation}
- initialPosition={
- targetMessageController.activeTargetMessageId()
- ? {
- type: 'element',
- id: targetMessageController.activeTargetMessageId()!,
- }
- : props.initialMessagesStateSnapshot?.scroll
- ? {
- type: 'restore',
- snapshot:
- props.initialMessagesStateSnapshot
- .scroll,
- }
- : { type: 'latest' }
- }
+ <SwipableRowProvider
+ container={threadListContainerEl}
+ triggerBehavior="spring-back"
>
- {(item) => {
- const isNewestRow = () =>
- item.id === messageIndex.entryKeys.at(-1);
- const activity = () =>
- messageIndex.activityByKey.get(item.id);
- const message = () => messageById().get(item.id);
+ {/* The newest row shows the agents typing. Their
+ rows are made once, here, so a live turn moves
+ with that row instead of starting over in it. */}
+ <AgentTypingProvider
+ parent={{ type: 'channel', id: props.channelId }}
+ threadId={null}
+ >
+ <ThreadList
+ keys={() => messageIndex.entryKeys}
+ targetId={
+ targetMessageController.hasPendingElementScroll()
+ ? targetMessageController.activeTargetMessageId()
+ : undefined
+ }
+ insets={threadListScrollInsets()}
+ followOnAppend={!messagesQuery.hasPreviousPage}
+ onScrollNearTop={threadPaginator.shiftPaginate}
+ onScrollNearBottom={
+ threadPaginator.prependPaginate
+ }
+ onReady={onThreadListReady}
+ onScroll={onThreadListScroll}
+ onUserNavigation={cancelLatestNavigation}
+ initialPosition={
+ targetMessageController.activeTargetMessageId()
+ ? {
+ type: 'element',
+ id: targetMessageController.activeTargetMessageId()!,
+ }
+ : props.initialMessagesStateSnapshot?.scroll
+ ? {
+ type: 'restore',
+ snapshot:
+ props.initialMessagesStateSnapshot
+ .scroll,
+ }
+ : { type: 'latest' }
+ }
+ >
+ {(item) => {
+ const isNewestRow = () =>
+ item.id === messageIndex.entryKeys.at(-1);
+ const activity = () =>
+ messageIndex.activityByKey.get(item.id);
+ const message = () =>
+ messageById().get(item.id);
- return (
- <Switch>
- <Match when={activity()}>
- {(activity) => (
- <ThreadRow
- channelId={props.channelId}
- message={{
- created_at: activity().occurred_at,
- }}
- listMeta={listMetaByKey()[item.id]}
- >
- <SystemActivity
- event={decodeSystemActivity(
- activity()
- )}
- />
- <Show when={isNewestRow()}>
- <ThreadTypingIndicator
- parent={{
- type: 'channel',
- id: props.channelId,
+ return (
+ <Switch>
+ <Match when={activity()}>
+ {(activity) => (
+ <ThreadRow
+ channelId={props.channelId}
+ message={{
+ created_at:
+ activity().occurred_at,
}}
- threadId={null}
- />
- </Show>
- </ThreadRow>
- )}
- </Match>
- <Match when={message()}>
- {(m) => {
- const state =
- threadManager.getOrCreateThreadState(
- item.id
- );
- return (
- <ChannelThread
- data={m}
- parent={() => ({
- type: 'channel',
- id: (() => props.channelId)(),
- })}
- isNewestThread={isNewestRow()}
- getMessageActions={getMessageActions}
- isFindBarOpen={findBar.isOpen}
- targetNavigation={{
- targetThreadId:
- targetMessageController.activeTargetMessageId,
- targetMessageId: () =>
- !targetMessageController.pendingTargetReplyId()
- ? targetMessageController.pendingScrollTargetId()
- : undefined,
- targetReplyId: () =>
- targetMessageController.pendingScrollTargetId()
- ? undefined
- : targetMessageController.pendingTargetReplyId(),
- activeTargetReplyId:
- targetMessageController.activeTargetMessageReplyId,
- positionTarget: (
- _,
- targetElement
- ) =>
- threadListNavigation()?.scrollToElement(
- targetElement
- ) ?? false,
- onTargetMessageScrolled:
- targetMessageController.completePendingScroll,
- onTargetReplyScrolled: (
- replyId
- ) => {
- targetMessageController.completePendingReplyScroll(
- item.id,
- replyId
- );
- },
- onClearTarget:
- releaseSelectionAndTarget,
- }}
- inputMode={
- isUnifiedInputMode()
- ? 'unified'
- : 'inline'
- }
- unifiedReplyTarget={unifiedInput.replyTarget()}
- onMessageMount={unread.onMessageMount}
- onDisclosureMount={
- unread.onDisclosureMount
- }
- unreadMessageIds={unread
- .unreadByThread()
- .get(item.id)}
- isExpanded={state.isExpanded}
- setIsExpanded={state.setIsExpanded}
- isReplying={state.isReplying}
- setIsReplying={state.setIsReplying}
- replyInputState={
- state.replyInputState
- }
- setReplyInputState={
- state.setReplyInputState
- }
- setReplyInputEl={
- state.setReplyInputEl
- }
- replyInputHandle={
- state.replyInputHandle
- }
- setReplyInputHandle={
- state.setReplyInputHandle
- }
- replyInputFocusRequest={
- state.replyInputFocusRequest
- }
- listMeta={listMetaByKey()[item.id]}
- messageEditor={messageEditor}
- threadActions={{
- onDismissNewMessages:
- activityTracker.dismissNewMessages,
- }}
- isNewMessage={
- activityTracker.isNewMessage
- }
- selectedMessageId={
- selection.selectedId
- }
- onSelectMessage={selectMessage}
- onClearSelection={clearSelection}
- messageListScopeId={
- messageListScopeId
- }
- />
- );
- }}
- </Match>
- </Switch>
- );
- }}
- </ThreadList>
- </SwipableRowProvider>
+ listMeta={listMetaByKey()[item.id]}
+ >
+ <SystemActivity
+ event={decodeSystemActivity(
+ activity()
+ )}
+ />
+ <Show when={isNewestRow()}>
+ <ThreadTypingIndicator
+ parent={{
+ type: 'channel',
+ id: props.channelId,
+ }}
+ threadId={null}
+ />
+ </Show>
+ </ThreadRow>
+ )}
+ </Match>
+ <Match when={message()}>
+ {(m) => {
+ const state =
+ threadManager.getOrCreateThreadState(
+ item.id
+ );
+ return (
+ <ChannelThread
+ beforeMessage={
+ <AgentConversationContextBoundary
+ messageId={item.id}
+ />
+ }
+ afterMessage={
+ <AgentConversationMessageStatus
+ messageId={item.id}
+ />
+ }
+ hideTriggeredBy={
+ !!channel()?.agent_dm
+ }
+ data={m}
+ parent={() => ({
+ type: 'channel',
+ id: (() => props.channelId)(),
+ })}
+ isNewestThread={isNewestRow()}
+ getMessageActions={
+ getMessageActions
+ }
+ isFindBarOpen={findBar.isOpen}
+ targetNavigation={{
+ targetThreadId:
+ targetMessageController.activeTargetMessageId,
+ targetMessageId: () =>
+ !targetMessageController.pendingTargetReplyId()
+ ? targetMessageController.pendingScrollTargetId()
+ : undefined,
+ targetReplyId: () =>
+ targetMessageController.pendingScrollTargetId()
+ ? undefined
+ : targetMessageController.pendingTargetReplyId(),
+ activeTargetReplyId:
+ targetMessageController.activeTargetMessageReplyId,
+ positionTarget: (
+ _,
+ targetElement
+ ) =>
+ threadListNavigation()?.scrollToElement(
+ targetElement
+ ) ?? false,
+ onTargetMessageScrolled:
+ targetMessageController.completePendingScroll,
+ onTargetReplyScrolled: (
+ replyId
+ ) => {
+ targetMessageController.completePendingReplyScroll(
+ item.id,
+ replyId
+ );
+ },
+ onClearTarget:
+ releaseSelectionAndTarget,
+ }}
+ inputMode={
+ isUnifiedInputMode()
+ ? 'unified'
+ : 'inline'
+ }
+ unifiedReplyTarget={unifiedInput.replyTarget()}
+ onMessageMount={
+ unread.onMessageMount
+ }
+ onDisclosureMount={
+ unread.onDisclosureMount
+ }
+ unreadMessageIds={unread
+ .unreadByThread()
+ .get(item.id)}
+ isExpanded={state.isExpanded}
+ setIsExpanded={
+ state.setIsExpanded
+ }
+ isReplying={state.isReplying}
+ setIsReplying={
+ state.setIsReplying
+ }
+ replyInputState={
+ state.replyInputState
+ }
+ setReplyInputState={
+ state.setReplyInputState
+ }
+ setReplyInputEl={
+ state.setReplyInputEl
+ }
+ replyInputHandle={
+ state.replyInputHandle
+ }
+ setReplyInputHandle={
+ state.setReplyInputHandle
+ }
+ replyInputFocusRequest={
+ state.replyInputFocusRequest
+ }
+ listMeta={
+ listMetaByKey()[item.id]
+ }
+ messageEditor={messageEditor}
+ threadActions={{
+ onDismissNewMessages:
+ activityTracker.dismissNewMessages,
+ }}
+ isNewMessage={
+ activityTracker.isNewMessage
+ }
+ selectedMessageId={
+ selection.selectedId
+ }
+ onSelectMessage={selectMessage}
+ onClearSelection={clearSelection}
+ messageListScopeId={
+ messageListScopeId
+ }
+ />
+ );
+ }}
+ </Match>
+ </Switch>
+ );
+ }}
+ </ThreadList>
+ </AgentTypingProvider>
+ </SwipableRowProvider>
- <Show when={!findBar.isOpen()}>
- <Show when={unread.chip()}>
- {(chip) => (
- <UnreadNotificationsOverlay
- direction={chip().direction}
- count={chip().count}
- onClick={() => goToUnread(chip().thread)}
- bottomInset={threadListScrollInsets().end}
+ <Show when={!findBar.isOpen()}>
+ <Show when={unread.chip()}>
+ {(chip) => (
+ <UnreadNotificationsOverlay
+ direction={chip().direction}
+ count={chip().count}
+ onClick={() => goToUnread(chip().thread)}
+ bottomInset={threadListScrollInsets().end}
+ />
+ )}
+ </Show>
+ <Show when={unread.chip()?.direction !== 'above'}>
+ <ScrollToBottomOverlay
+ scrollState={threadListScrollState}
+ onScrollToBottom={goToLatest}
+ class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
/>
- )}
+ </Show>
</Show>
- <Show when={unread.chip()?.direction !== 'above'}>
- <ScrollToBottomOverlay
- scrollState={threadListScrollState}
- onScrollToBottom={goToLatest}
- class="touch:top-[calc(var(--mobile-content-inset-top,0)+1rem)]"
- />
- </Show>
- </Show>
- </MessageNotificationIndexContext.Provider>
- </div>
- </Show>
- <DebugSuspense name="Channel.active-call">
- <ActiveCallMessage channelId={props.channelId} />
- </DebugSuspense>
- </div>
- <DebugSuspense name="Channel.input">
- <FloatRegionOrInline region="accessory">
- <ChannelInputContainer
- ref={(el) => {
- attachInputRef(el);
- composerTarget(el);
- }}
- >
- <Switch>
- <Match
- when={
- isUnifiedInputMode() &&
- messageEditor.state()?.messageId
- }
- keyed
- >
- {(_messageId) => (
- <UnifiedEditInput
- channelId={props.channelId}
- messageEditor={messageEditor}
- onNavigateToMessage={(message) =>
- goToMessage(
- message.thread_id ?? message.id,
- message.thread_id ? message.id : undefined
- )
- }
- />
- )}
- </Match>
- <Match
- when={
- isUnifiedInputMode() &&
- unifiedInput.replyTarget()?.threadId
- }
- keyed
- >
- {(threadId) => (
- <UnifiedReplyInput
- channelId={props.channelId}
- threadId={threadId}
- state={threadManager.getOrCreateThreadState(
- threadId
- )}
- getTargetMessage={() => {
- const target = unifiedInput.replyTarget();
- if (target?.message) return target.message;
- // A restored referenced reply has no resolvable
- // message (messageById only indexes thread
- // roots) — don't misattribute it to the root.
- if (target?.replyId) return undefined;
- return messageById().get(threadId);
- }}
- threadHasReplies={() =>
- (messageById().get(threadId)?.thread
- .reply_count ?? 0) > 0
- }
- onNavigateToTarget={() =>
- goToMessage(
- threadId,
- unifiedInput.replyTarget()?.replyId
- )
- }
- onExit={unifiedInput.closeReply}
- />
- )}
- </Match>
- <Match when={true}>
- <ChannelInput
- autofocus={props.autofocus}
- collapsible
- input={{
- mode: 'channel',
- id: `channel-input-${props.channelId}`,
- placeholder: inputPlaceholder(),
- }}
- participants={participants.users}
- bots={channelBotMentionUsers}
- attachmentTracker={attachmentTracker}
- persistenceKey={makeInputValuePersistenceKey({
- channelId: props.channelId,
- })}
- onReady={(handle) => {
- dragState.setAttachFilesToChannel(
- handle.attachFiles
- );
- dragState.setEntityMentionInputHandlers(handle);
- setChannelInputHandle(handle);
- }}
- onChange={(snapshot) =>
- void setChannelInputSnapshot(snapshot)
- }
- onSend={onSend}
- onStartCall={
- ENABLE_CALLS && !channelCall.isInThisChannel()
- ? () => void channelCall.start()
- : undefined
- }
- callInProgress={channelCall.isCallInProgress()}
- onStartTyping={() =>
- typingMutation.mutate({
- parent: {
- type: 'channel',
- id: props.channelId,
- },
- action: 'start',
- })
+ </MessageNotificationIndexContext.Provider>
+ </div>
+ </Show>
+ <DebugSuspense name="Channel.active-call">
+ <ActiveCallMessage channelId={props.channelId} />
+ </DebugSuspense>
+ </div>
+ <DebugSuspense name="Channel.input">
+ <FloatRegionOrInline region="accessory">
+ <ChannelInputContainer
+ ref={(el) => {
+ attachInputRef(el);
+ composerTarget(el);
+ }}
+ >
+ <Switch>
+ <Match
+ when={
+ isUnifiedInputMode() &&
+ messageEditor.state()?.messageId
}
- onStopTyping={() =>
- typingMutation.mutate({
- parent: {
- type: 'channel',
- id: props.channelId,
- },
- action: 'stop',
- })
+ keyed
+ >
+ {(_messageId) => (
+ <UnifiedEditInput
+ channelId={props.channelId}
+ messageEditor={messageEditor}
+ onNavigateToMessage={(message) =>
+ goToMessage(
+ message.thread_id ?? message.id,
+ message.thread_id ? message.id : undefined
+ )
+ }
+ />
+ )}
+ </Match>
+ <Match
+ when={
+ isUnifiedInputMode() &&
+ unifiedInput.replyTarget()?.threadId
}
- />
- </Match>
- </Switch>
- </ChannelInputContainer>
- </FloatRegionOrInline>
- </DebugSuspense>
- </ChannelDropZone>
- </MaybeMessageActionDrawerManager>
- </SearchHighlightTermsProvider>
- </StaticMarkdownContext>
- </DebugSuspense>
- </EntityLoadGate>
+ keyed
+ >
+ {(threadId) => (
+ <UnifiedReplyInput
+ channelId={props.channelId}
+ threadId={threadId}
+ state={threadManager.getOrCreateThreadState(
+ threadId
+ )}
+ getTargetMessage={() => {
+ const target = unifiedInput.replyTarget();
+ if (target?.message) return target.message;
+ // A restored referenced reply has no resolvable
+ // message (messageById only indexes thread
+ // roots) — don't misattribute it to the root.
+ if (target?.replyId) return undefined;
+ return messageById().get(threadId);
+ }}
+ threadHasReplies={() =>
+ (messageById().get(threadId)?.thread
+ .reply_count ?? 0) > 0
+ }
+ onNavigateToTarget={() =>
+ goToMessage(
+ threadId,
+ unifiedInput.replyTarget()?.replyId
+ )
+ }
+ onExit={unifiedInput.closeReply}
+ />
+ )}
+ </Match>
+ <Match when={true}>
+ {/* An agent DM gates only a new message on its
+ agent: editing and thread replies stay open. */}
+ <AgentDmComposer
+ channelId={props.channelId}
+ botId={channel()?.agent_dm?.bot_id}
+ >
+ <ChannelInput
+ autofocus={props.autofocus}
+ collapsible
+ input={{
+ mode: 'channel',
+ id: `channel-input-${props.channelId}`,
+ placeholder: inputPlaceholder(),
+ }}
+ participants={participants.users}
+ bots={channelBotMentionUsers}
+ attachmentTracker={attachmentTracker}
+ persistenceKey={makeInputValuePersistenceKey({
+ channelId: props.channelId,
+ })}
+ onReady={(handle) => {
+ dragState.setAttachFilesToChannel(
+ handle.attachFiles
+ );
+ dragState.setEntityMentionInputHandlers(
+ handle
+ );
+ setChannelInputHandle(handle);
+ }}
+ onChange={(snapshot) =>
+ void setChannelInputSnapshot(snapshot)
+ }
+ onSend={onSend}
+ onStartCall={
+ ENABLE_CALLS && !channelCall.isInThisChannel()
+ ? () => void channelCall.start()
+ : undefined
+ }
+ callInProgress={channelCall.isCallInProgress()}
+ onStartTyping={() =>
+ typingMutation.mutate({
+ parent: {
+ type: 'channel',
+ id: props.channelId,
+ },
+ action: 'start',
+ })
+ }
+ onStopTyping={() =>
+ typingMutation.mutate({
+ parent: {
+ type: 'channel',
+ id: props.channelId,
+ },
+ action: 'stop',
+ })
+ }
+ />
+ </AgentDmComposer>
+ </Match>
+ </Switch>
+ </ChannelInputContainer>
+ </FloatRegionOrInline>
+ </DebugSuspense>
+ </ChannelDropZone>
+ </MaybeMessageActionDrawerManager>
+ </SearchHighlightTermsProvider>
+ </StaticMarkdownContext>
+ </DebugSuspense>
+ </EntityLoadGate>
+ </AgentConversationsProvider>
);
}
diff --git a/apps/web/src/features/channel/Channel/ChannelDetail.tsx b/apps/web/src/features/channel/Channel/ChannelDetail.tsx
index cf709048f1..7f1d2db45d 100644
--- a/apps/web/src/features/channel/Channel/ChannelDetail.tsx
+++ b/apps/web/src/features/channel/Channel/ChannelDetail.tsx
@@ -27,7 +27,12 @@ import {
import type { PriorityCollapser } from '@components/app/split-layout/utils/createPriorityCollapser';
import { TabsInset } from '@core/component/TabsInset';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
-import { useChannelName, useChannelType } from '@core/context/channels';
+import {
+ useChannel,
+ useChannelCanCall,
+ useChannelName,
+ useChannelType,
+} from '@core/context/channels';
import { createMethodRegistration } from '@core/orchestrator';
import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';
import {
@@ -142,6 +147,7 @@ export function ChannelDetailTabs(props: {
}
export function ChannelDetailActions(props: ChannelDetailHeaderProps) {
+ const channel = useChannel(props.channelId);
const channelName = useChannelName(props.channelId, props.fallbackName);
const channelType = useChannelType(props.channelId);
const call = useCall(() => props.channelId);
@@ -170,7 +176,9 @@ export function ChannelDetailActions(props: ChannelDetailHeaderProps) {
channelType={channelType()}
/>
</DebugSuspense>
- <Show when={ENABLE_CALLS && !call.isInThisChannel()}>
+ <Show
+ when={ENABLE_CALLS && !channel()?.agent_dm && !call.isInThisChannel()}
+ >
<DebugSuspense name="ChannelDetail.call-button">
<ChannelCallButton channelId={props.channelId} />
</DebugSuspense>
@@ -246,6 +254,8 @@ function ChannelDetailContent(props: ChannelDetailProps) {
const panel = useSplitPanelOrThrow();
const orchestrator = useGlobalBlockOrchestrator();
const channelId = props.channelId;
+ const conversationChannel = useChannel(channelId);
+ const canCall = useChannelCanCall(channelId);
const channelName = useChannelName(channelId, props.fallbackName);
useSplitDisplayName(() => channelName() ?? 'New Channel');
@@ -288,8 +298,20 @@ function ChannelDetailContent(props: ChannelDetailProps) {
normalizeChannelTab(hasActiveCallHere ? 'call' : DEFAULT_CHANNEL_TAB)
);
const setActiveTab = (tab: ChannelTabId) => {
- setActiveTabInternal(normalizeChannelTab(tab));
+ setActiveTabInternal(
+ conversationChannel()?.agent_dm &&
+ ['call', 'calls', 'participants'].includes(tab)
+ ? DEFAULT_CHANNEL_TAB
+ : normalizeChannelTab(tab)
+ );
};
+ createComputed(() => {
+ if (
+ conversationChannel()?.agent_dm &&
+ ['call', 'calls', 'participants'].includes(activeTab())
+ )
+ setActiveTabInternal(DEFAULT_CHANNEL_TAB);
+ });
const [pendingJoinCall, setPendingJoinCall] = createSignal(false);
// A new target within the already-mounted channel (a notification jump)
@@ -351,6 +373,7 @@ function ChannelDetailContent(props: ChannelDetailProps) {
<ChannelTabProvider activeTab={activeTab} setActiveTab={setActiveTab}>
<DebugSuspense name="ChannelDetail.auto-join">
<ChannelCallAutoJoin
+ canCall={canCall}
channelId={channelId}
pendingJoinCall={pendingJoinCall}
onHandled={() => setPendingJoinCall(false)}
diff --git a/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx b/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx
index a2fbbca732..6d9a04a4c7 100644
--- a/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx
+++ b/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx
@@ -78,6 +78,8 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
}));
vi.mock('@ui/components/Tabs', () => ({ Tabs: () => null }));
vi.mock('@core/context/channels', () => ({
+ useChannel: () => () => undefined,
+ useChannelCanCall: () => () => true,
useChannelName: () => () => 'channel-name',
useChannelType: () => () => 'private',
}));
diff --git a/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx b/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx
index b69969d806..3aae7ba0c1 100644
--- a/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx
+++ b/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx
@@ -2,7 +2,7 @@ import { useCall } from '@channel/Call/use-call';
import { isNativeIosCallKitEnabled } from '@channel/Call/use-callkit';
import type { TabItem } from '@core/component/Tabs';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
-import { useChannelType } from '@core/context/channels';
+import { useChannel, useChannelType } from '@core/context/channels';
import { useActiveCallQuery } from '@queries/call/call';
import { ChannelType } from '@service-storage/generated/schemas/channelType';
import type { Accessor } from 'solid-js';
@@ -40,6 +40,7 @@ function CallTabLabel() {
export function useChannelTabItems(channelId: string): Accessor<TabItem[]> {
const { activeTab } = useChannelTab();
const channelType = useChannelType(channelId);
+ const channel = useChannel(channelId);
const call = useCall(() => channelId);
const activeCallQuery = useActiveCallQuery(() => channelId);
// Show the Call tab whenever we're actually in the call, mid-join, or
@@ -47,6 +48,7 @@ export function useChannelTabItems(channelId: string): Accessor<TabItem[]> {
// `activeTab` to `call` before the join request resolves).
const showCallTab = () =>
ENABLE_CALLS &&
+ !channel()?.agent_dm &&
canUseInlineCallTab() &&
(call.isInThisChannel() ||
call.isJoining() ||
@@ -56,7 +58,7 @@ export function useChannelTabItems(channelId: string): Accessor<TabItem[]> {
let filtered = [...CHANNEL_TABS];
if (channelType() === ChannelType.direct_message)
filtered = filtered.filter((tab) => tab.value !== 'participants');
- if (!ENABLE_CALLS)
+ if (!ENABLE_CALLS || channel()?.agent_dm)
filtered = filtered.filter((tab) => tab.value !== 'calls');
if (!showCallTab())
filtered = filtered.filter((tab) => tab.value !== 'call');
diff --git a/apps/web/src/features/channel/Message/ChannelMessage.tsx b/apps/web/src/features/channel/Message/ChannelMessage.tsx
index 4f1ffd081a..37f0b9295b 100644
--- a/apps/web/src/features/channel/Message/ChannelMessage.tsx
+++ b/apps/web/src/features/channel/Message/ChannelMessage.tsx
@@ -13,6 +13,7 @@ import { Message } from './Message';
import { MaybeSwipeToReplyRow } from './SwipeToReplyRow';
type ChannelMessageProps = {
+ renderContent?: (content: JSX.Element) => JSX.Element;
parent: MessageParent;
inputMode?: 'inline' | 'unified';
message: MessageData;
@@ -25,6 +26,11 @@ type ChannelMessageProps = {
* navigation, points at this message.
*/
targeted?: boolean;
+ /**
+ * Leave out who triggered a bot's message. In a private conversation with
+ * an agent that is always the viewer, so it says nothing.
+ */
+ hideTriggeredBy?: boolean;
onClick?: JSX.EventHandlerUnion<HTMLDivElement, MouseEvent>;
};
@@ -36,6 +42,7 @@ function isEditingMessage(
}
function MessageContentSlot(props: {
+ renderContent?: (content: JSX.Element) => JSX.Element;
parent: MessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
@@ -44,7 +51,7 @@ function MessageContentSlot(props: {
const message = useMessage();
const isEditing = () => isEditingMessage(props.messageEditor, message().id);
- return (
+ const content = (
<Switch>
<Match
when={
@@ -65,6 +72,7 @@ function MessageContentSlot(props: {
</Match>
</Switch>
);
+ return props.renderContent ? props.renderContent(content) : content;
}
function MessageFooter(props: { messageEditor?: MessageEditor }) {
@@ -110,9 +118,11 @@ function DeletedMessageLayout() {
}
function RegularMessageLayout(props: {
+ renderContent?: (content: JSX.Element) => JSX.Element;
parent: MessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
+ hideTriggeredBy?: boolean;
}) {
return (
<Message.Layout class="pt-(--regular-message-padding-t)">
@@ -130,10 +140,13 @@ function RegularMessageLayout(props: {
<Message.EditedIndicator class="shrink-0" />
<Message.AgentSessionLink class="ml-auto" />
</div>
- <Message.FromPill />
+ <Show when={!props.hideTriggeredBy}>
+ <Message.FromPill />
+ </Show>
</Message.Slot>
<Message.Slot placement="content" class="ph-no-capture">
<MessageContentSlot
+ renderContent={props.renderContent}
parent={props.parent}
inputMode={props.inputMode}
messageEditor={props.messageEditor}
@@ -151,6 +164,7 @@ function RegularMessageLayout(props: {
}
function GroupedMessageLayout(props: {
+ renderContent?: (content: JSX.Element) => JSX.Element;
parent: MessageParent;
inputMode?: 'inline' | 'unified';
messageEditor?: MessageEditor;
@@ -163,6 +177,7 @@ function GroupedMessageLayout(props: {
<Message.Slot placement="content">
<div class="ph-no-capture flex gap-3 min-w-0 items-start">
<MessageContentSlot
+ renderContent={props.renderContent}
parent={props.parent}
inputMode={props.inputMode}
messageEditor={props.messageEditor}
@@ -219,6 +234,7 @@ export function ChannelMessage(props: ChannelMessageProps) {
</Match>
<Match when={isGrouped()}>
<GroupedMessageLayout
+ renderContent={props.renderContent}
parent={props.parent}
inputMode={props.inputMode}
messageEditor={props.messageEditor}
@@ -226,9 +242,11 @@ export function ChannelMessage(props: ChannelMessageProps) {
</Match>
<Match when={true}>
<RegularMessageLayout
+ renderContent={props.renderContent}
parent={props.parent}
inputMode={props.inputMode}
messageEditor={props.messageEditor}
+ hideTriggeredBy={props.hideTriggeredBy}
/>
</Match>
</Switch>
diff --git a/apps/web/src/features/channel/Message/tests/triggered-by.test.tsx b/apps/web/src/features/channel/Message/tests/triggered-by.test.tsx
new file mode 100644
index 0000000000..219133d9cc
--- /dev/null
+++ b/apps/web/src/features/channel/Message/tests/triggered-by.test.tsx
@@ -0,0 +1,80 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { MessageData } from '@core/messages/types';
+import { render } from '@solidjs/testing-library';
+import type { ParentProps } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { MessageProvider, useMessage } from '../context';
+
+vi.mock('@channel/Mobile/message-action-drawer-context', () => ({
+ useMessageActionDrawer: () => undefined,
+}));
+vi.mock('@core/directive/touchHandler', () => ({ touchHandler: () => {} }));
+vi.mock('@core/util/message-send-motion', () => ({
+ messageSendMotion: () => {},
+}));
+vi.mock('../SwipeToReplyRow', () => ({
+ MaybeSwipeToReplyRow: (props: ParentProps) => <>{props.children}</>,
+}));
+vi.mock('../../Channel/InlineMessageEditor', () => ({
+ MessageEditorContent: () => null,
+}));
+vi.mock('../Message', () => {
+ const Pass = (props: ParentProps) => <>{props.children}</>;
+ const Nothing = () => null;
+ return {
+ Message: {
+ Root: (props: ParentProps<{ message: MessageData }>) => (
+ <MessageProvider value={() => props.message}>
+ <div>{props.children}</div>
+ </MessageProvider>
+ ),
+ Layout: Pass,
+ Slot: Pass,
+ Content: Nothing,
+ SenderIcon: Nothing,
+ SenderName: Nothing,
+ AgentBadge: Nothing,
+ Timestamp: Nothing,
+ EditedIndicator: Nothing,
+ AgentSessionLink: Nothing,
+ Attachments: Nothing,
+ Reactions: Nothing,
+ ActionMenu: Nothing,
+ FromPill: () => <span>from {useMessage()().sender?.triggered_by}</span>,
+ },
+ };
+});
+
+import { ChannelMessage } from '../ChannelMessage';
+
+const reply = {
+ id: 'reply',
+ content: 'Here you go.',
+ sender_id: 'bot|ada',
+ sender: { triggered_by: 'macro|[email protected]' },
+ created_at: '2026-10-07T00:00:00.000Z',
+ updated_at: '2026-10-07T00:00:00.000Z',
+ attachments: [],
+ reactions: [],
+} as unknown as MessageData;
+
+const parent = { type: 'channel', id: 'dm' } as const;
+
+describe('who triggered a bot message', () => {
+ it('names them in a channel', () => {
+ const view = render(() => (
+ <ChannelMessage parent={parent} message={reply} />
+ ));
+ expect(view.queryByText(/from macro\|[email protected]/)).not.toBeNull();
+ });
+
+ it('is left out where it is always the viewer', () => {
+ const view = render(() => (
+ <ChannelMessage parent={parent} message={reply} hideTriggeredBy />
+ ));
+ expect(view.queryByText(/^from /)).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/channel/Thread/ChannelThread.tsx b/apps/web/src/features/channel/Thread/ChannelThread.tsx
index ad09193dc2..ad66800696 100644
--- a/apps/web/src/features/channel/Thread/ChannelThread.tsx
+++ b/apps/web/src/features/channel/Thread/ChannelThread.tsx
@@ -306,6 +306,7 @@ export function ChannelThread(props: ThreadProps) {
onDismissNewMessages={props.threadActions?.onDismissNewMessages}
>
<div class="flex flex-col w-full">
+ {props.beforeMessage}
{/* Rail segment along the root message: from the avatar's center
(masked by the avatar's fill until its lower edge) to the
message's bottom, where the reply-branch elbow takes over. A
@@ -333,6 +334,8 @@ export function ChannelThread(props: ThreadProps) {
>
<DebugSuspense name="ChannelThread.message">
<ChannelMessage
+ renderContent={props.renderMessageContent}
+ hideTriggeredBy={props.hideTriggeredBy}
parent={props.parent()}
message={props.data()}
actions={props.getMessageActions?.(props.data())}
@@ -350,6 +353,7 @@ export function ChannelThread(props: ThreadProps) {
</DebugSuspense>
</MarkMessageNotifications>
</div>
+ {props.afterMessage}
<Show when={hasReplies() || hasInlineReplyInput()}>
<div class="relative w-full">
<Show when={!props.hideRail}>
diff --git a/apps/web/src/features/channel/Thread/ThreadTypingIndicator.tsx b/apps/web/src/features/channel/Thread/ThreadTypingIndicator.tsx
index 964b3920b0..6bf793fd5a 100644
--- a/apps/web/src/features/channel/Thread/ThreadTypingIndicator.tsx
+++ b/apps/web/src/features/channel/Thread/ThreadTypingIndicator.tsx
@@ -1,5 +1,6 @@
+import { AgentTyping } from '@app/features/agent-activity/agent-typing';
import { idToDisplayName } from '@core/user';
-import { getTypingUsers } from '@queries/messages/typing';
+import { getTypingAgents, getTypingUsers } from '@queries/messages/typing';
import type { MessageParent } from '@service-storage/messages';
import { createMemo, Show } from 'solid-js';
import { match } from 'ts-pattern';
@@ -10,9 +11,11 @@ type ThreadTypingIndicatorProps = {
};
export function ThreadTypingIndicator(props: ThreadTypingIndicatorProps) {
+ // Agents type as a row of their own, with their turn beneath.
const typingUsers = createMemo(() => {
+ const agents = getTypingAgents(props.parent, props.threadId);
const users = getTypingUsers(props.parent, props.threadId);
- return Array.from(users);
+ return Array.from(users).filter((user) => !agents.has(user));
});
const typingText = createMemo(() => {
@@ -22,11 +25,14 @@ export function ThreadTypingIndicator(props: ThreadTypingIndicatorProps) {
const isActive = () => typingUsers().length > 0;
return (
- <div class="flex flex-row items-stretch justify-start ml-[calc(var(--message-padding-x)+var(--user-icon-width)+--spacing(2))] min-h-7">
- <Show when={isActive()}>
- <ThreadTypingIndicatorContent text={typingText()} />
- </Show>
- </div>
+ <>
+ <AgentTyping parent={props.parent} threadId={props.threadId} />
+ <div class="flex flex-row items-stretch justify-start ml-[calc(var(--message-padding-x)+var(--user-icon-width)+--spacing(2))] min-h-7">
+ <Show when={isActive()}>
+ <ThreadTypingIndicatorContent text={typingText()} />
+ </Show>
+ </div>
+ </>
);
}
diff --git a/apps/web/src/features/channel/Thread/types.ts b/apps/web/src/features/channel/Thread/types.ts
index 7e4812f3c6..7e27f464bf 100644
--- a/apps/web/src/features/channel/Thread/types.ts
+++ b/apps/web/src/features/channel/Thread/types.ts
@@ -2,7 +2,7 @@ import type { MessageEditor } from '@channel/Channel/create-message-editor';
import type { NewMessageCheckable } from '@channel/Channel/util';
import type { InputHandle, InputSnapshot } from '@channel/Input';
import type { MessageListItem, MessageParent } from '@service-storage/messages';
-import type { Accessor, Setter } from 'solid-js';
+import type { Accessor, JSX, Setter } from 'solid-js';
import type {
ChannelMessageListMeta,
MessageActions,
@@ -54,6 +54,12 @@ export type ThreadTargetNavigation = {
};
export type ThreadProps = {
+ /** Optional host-specific timeline decorations and live content. */
+ beforeMessage?: JSX.Element;
+ afterMessage?: JSX.Element;
+ renderMessageContent?: (content: JSX.Element) => JSX.Element;
+ /** See `hideTriggeredBy` on the channel message. */
+ hideTriggeredBy?: boolean;
data: Accessor<MessageListItem>;
parent: Accessor<MessageParent>;
/** The enclosing view owns a floating input only in unified mode. */
diff --git a/apps/web/src/features/channel/components/ChannelTopIcon.tsx b/apps/web/src/features/channel/components/ChannelTopIcon.tsx
index 68a58244ea..90b32e33df 100644
--- a/apps/web/src/features/channel/components/ChannelTopIcon.tsx
+++ b/apps/web/src/features/channel/components/ChannelTopIcon.tsx
@@ -1,5 +1,7 @@
+import { PersonaAvatar } from '@app/features/agent-dms/components/persona-avatar';
import { ChannelAvatar } from '@channel/channel-avatar';
import { UserIcon } from '@core/component/UserIcon';
+import { useChannel } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import type { ChannelParticipant } from '@queries/channel/types';
import { ChannelType } from '@service-storage/generated/schemas/channelType';
@@ -13,6 +15,7 @@ export type ChannelTopIconProps = {
/** Channel avatar, or the other participant's avatar for a direct message. */
export function ChannelTopIcon(props: ChannelTopIconProps) {
+ const channel = useChannel(props.channelId);
const userId = useUserId();
const recipient = () => {
return props.participants.find((p) => p && p.user_id !== userId());
@@ -20,16 +23,30 @@ export function ChannelTopIcon(props: ChannelTopIconProps) {
return (
<Show
- when={props.channelType === ChannelType.direct_message && recipient()}
+ when={channel()?.agent_dm}
fallback={
- <ChannelAvatar
- channelId={props.channelId}
- class="size-4 [&_img]:rounded-full"
- />
+ <Show
+ when={props.channelType === ChannelType.direct_message && recipient()}
+ fallback={
+ <ChannelAvatar
+ channelId={props.channelId}
+ class="size-4 [&_img]:rounded-full"
+ />
+ }
+ >
+ {(recipient) => (
+ <UserIcon id={recipient().user_id} isDeleted={false} size="sm" />
+ )}
+ </Show>
}
>
- {(recipient) => (
- <UserIcon id={recipient().user_id} isDeleted={false} size="sm" />
+ {(persona) => (
+ <PersonaAvatar
+ botId={persona().bot_id}
+ name={persona().name}
+ avatarUrl={persona().avatar_url}
+ size="sm"
+ />
)}
</Show>
);
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsx
index 46728f11c9..c9f37671d9 100644
--- a/apps/web/src/features/channels-view/channels-view.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view.test.tsx
@@ -32,6 +32,9 @@ const mocks = vi.hoisted(() => ({
refresh: vi.fn(async () => {}),
}));
+vi.mock('@app/features/agent-dms/queries/search-pool', () => ({
+ useAgentDmSearchPool: () => () => [],
+}));
vi.mock('@app/features/command/mobile/mobileSearchState', () => ({
SearchState: {
isOpen: () => mocks.searchOpen(),
diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsx
index 5deab72c27..74d1abc269 100644
--- a/apps/web/src/features/channels-view/channels-view.tsx
+++ b/apps/web/src/features/channels-view/channels-view.tsx
@@ -1,4 +1,5 @@
import { ViewShell } from '@app/components/view-shell';
+import { useAgentDmSearchPool } from '@app/features/agent-dms/queries/search-pool';
import { SearchState } from '@app/features/command/mobile/mobileSearchState';
import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';
import { markChannelNotificationsSeenOnOpen } from '@app/features/next-soup/utils';
@@ -50,10 +51,12 @@ export type ChannelsViewProps = {
// Mounted inside the mobile list's Suspense boundary.
function MobileChannelsList(props: { sources: ChannelsSources }) {
+ const agentDms = useAgentDmSearchPool();
const panel = useSplitPanelOrThrow();
const { state, setMobileTab } = useChannelsView();
const mobileSearchText = useMobileSearchText(() => '', panel.handle.isActive);
const mobileSearchSource = createChannelSearchSource({
+ additionalLocalChannels: agentDms,
text: mobileSearchText,
scope: () => state.mobileTab,
source: () => props.sources[state.mobileTab],
@@ -74,8 +77,10 @@ function DesktopChannelsRail(props: {
searchOpen: boolean;
onSearchOpenChange: (open: boolean) => void;
}) {
+ const agentDms = useAgentDmSearchPool();
const [searchQuery, setSearchQuery] = createSignal('');
const searchSource = createChannelSearchSource({
+ additionalLocalChannels: agentDms,
text: searchQuery,
enabled: () => props.searchOpen,
scope: () => 'search',
diff --git a/apps/web/src/features/channels-view/queries/channel-search-source.test.ts b/apps/web/src/features/channels-view/queries/channel-search-source.test.ts
index daa178c662..0d8a0617b6 100644
--- a/apps/web/src/features/channels-view/queries/channel-search-source.test.ts
+++ b/apps/web/src/features/channels-view/queries/channel-search-source.test.ts
@@ -38,6 +38,7 @@ function setup(initialText = '', initialScope: ChannelsSourceScope = 'search') {
const [text, setText] = createSignal(initialText);
const [scope, setScope] = createSignal(initialScope);
const [enabled, setEnabled] = createSignal(true);
+ const [extra, setExtra] = createSignal<ChannelEntity[]>([]);
const [rows, setRows] = createSignal([localChannel, localDm]);
const [remote, setRemote] = createStore<{
data: ChannelEntity[];
@@ -114,9 +115,11 @@ function setup(initialText = '', initialScope: ChannelsSourceScope = 'search') {
scope,
enabled,
source: () => local,
+ additionalLocalChannels: extra,
});
return {
source,
+ setExtra,
local,
request,
queryEnabled,
@@ -144,6 +147,26 @@ describe('shared channel search source', () => {
vi.useRealTimers();
});
+ it('finds an agent persona outside the loaded page and keeps it out of channel-only results', async () => {
+ const s = setup('archivist', 'direct_messages');
+ s.setExtra([channel('agent-dm', 'Archivist', true)]);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(ids(s.source)).toEqual(['agent-dm']);
+ s.setScope('channels');
+ expect(ids(s.source)).toEqual([]);
+ });
+
+ it('deduplicates a persona already in the visible page before local and remote matching', async () => {
+ const s = setup('alpha');
+ s.setExtra([{ ...localDm, name: 'Alpha persona' }]);
+ s.setRemote('data', [localDm]);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(ids(s.source).filter((id) => id === localDm.id)).toHaveLength(1);
+ expect(s.source.items().find((row) => row.id === localDm.id)?.name).toBe(
+ localDm.name
+ );
+ });
+
it('shows the ordinary list for an empty query and restores it on clear', async () => {
const s = setup();
expect(ids(s.source)).toEqual(['channel', 'dm']);
diff --git a/apps/web/src/features/channels-view/queries/channel-search-source.ts b/apps/web/src/features/channels-view/queries/channel-search-source.ts
index 9a3e834d87..24ad5f7d87 100644
--- a/apps/web/src/features/channels-view/queries/channel-search-source.ts
+++ b/apps/web/src/features/channels-view/queries/channel-search-source.ts
@@ -1,6 +1,6 @@
import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';
import { createSearchState } from '@app/features/soup/search/create-search-state';
-import { isChannelEntity } from '@entity';
+import { type ChannelEntity, isChannelEntity } from '@entity';
import { type Accessor, createMemo } from 'solid-js';
import { match } from 'ts-pattern';
import {
@@ -14,17 +14,23 @@ export function createChannelSearchSource(options: {
enabled?: Accessor<boolean>;
scope: Accessor<ChannelsSourceScope>;
source: Accessor<ChannelsDataSource>;
+ additionalLocalChannels?: Accessor<readonly ChannelEntity[]>;
}): ChannelsDataSource {
const enabled = () => options.enabled?.() ?? true;
const searching = () => options.text().trim().length > 0;
+ const localChannels = createMemo(
+ () =>
+ new Map(
+ [
+ ...(options.additionalLocalChannels?.() ?? []),
+ ...options.source().items(),
+ ].map((channel) => [channel.id, channel])
+ )
+ );
const search = createSearchState({
enabled,
text: options.text,
- localPool: () =>
- options
- .source()
- .items()
- .map((data) => ({ data })),
+ localPool: () => [...localChannels().values()].map((data) => ({ data })),
buildRequest: ({ query, matchType }) => ({
params: { page_size: 100 },
body: {
@@ -50,12 +56,7 @@ export function createChannelSearchSource(options: {
if (!searching()) return [...options.source().items()];
// Search records lack loaded conversation metadata, including message previews.
- const loadedById = new Map(
- options
- .source()
- .items()
- .map((channel) => [channel.id, channel])
- );
+ const loadedById = localChannels();
const matches = search
.data()
.filter(isChannelEntity)
diff --git a/apps/web/src/features/entity/extractors/entity-icon.tsx b/apps/web/src/features/entity/extractors/entity-icon.tsx
index efd1ed769e..7e79be81ca 100644
--- a/apps/web/src/features/entity/extractors/entity-icon.tsx
+++ b/apps/web/src/features/entity/extractors/entity-icon.tsx
@@ -1,3 +1,4 @@
+import { PersonaAvatar } from '@app/features/agent-dms/components/persona-avatar';
import { ChannelAvatar } from '@channel/channel-avatar';
import {
EntityIcon as CoreEntityIcon,
@@ -5,6 +6,7 @@ import {
getEntityIconType,
} from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
+import { useChannelsContext } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import type { StreamEvent } from '@service-connection/generated/schemas';
import { Match, Show, Switch } from 'solid-js';
@@ -29,6 +31,8 @@ function DirectMessageIcon(props: {
weight?: CoreEntityIconProps['weight'];
}) {
const userId = useUserId();
+ const channels = useChannelsContext();
+ const agentDm = () => channels.channelsById()[props.entity.id]?.agent_dm;
const participantId = () => {
const participants = props.entity.participantIds ?? [];
return participants.find((id) => id !== userId());
@@ -37,24 +41,51 @@ function DirectMessageIcon(props: {
return (
<div class="size-full flex">
<Show
- when={participantId()}
+ when={agentDm()}
fallback={
- <CoreEntityIcon
- targetType="direct_message"
- size="fill"
- class={props.class}
- weight={props.weight}
- />
+ <Show
+ when={participantId()}
+ fallback={
+ <CoreEntityIcon
+ targetType="direct_message"
+ size="fill"
+ class={props.class}
+ weight={props.weight}
+ />
+ }
+ >
+ {(id) => (
+ <Show
+ when={id().startsWith('bot|')}
+ fallback={
+ <UserIcon
+ id={id()}
+ isDeleted={false}
+ size="fill"
+ class={props.class}
+ suppressClick={props.suppressClick}
+ showTooltip={props.showTooltip}
+ />
+ }
+ >
+ <PersonaAvatar
+ botId={id().slice(4)}
+ name={props.entity.name}
+ size="fill"
+ class={props.class}
+ />
+ </Show>
+ )}
+ </Show>
}
>
- {(id) => (
- <UserIcon
- id={id()}
- isDeleted={false}
+ {(persona) => (
+ <PersonaAvatar
+ botId={persona().bot_id}
+ name={persona().name}
+ avatarUrl={persona().avatar_url}
size="fill"
class={props.class}
- suppressClick={props.suppressClick}
- showTooltip={props.showTooltip}
/>
)}
</Show>
diff --git a/apps/web/src/features/entity/tests/entity-icon.test.tsx b/apps/web/src/features/entity/tests/entity-icon.test.tsx
index 2fcf2cc724..239b4a3fc8 100644
--- a/apps/web/src/features/entity/tests/entity-icon.test.tsx
+++ b/apps/web/src/features/entity/tests/entity-icon.test.tsx
@@ -36,6 +36,16 @@ vi.mock('@core/constant/allBlocks', () => ({
itemToBlockName: vi.fn(),
}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));
+vi.mock('@core/context/channels', () => ({
+ useChannelsContext: () => ({ channelsById: () => ({}) }),
+}));
+vi.mock('@app/features/agent-dms/components/persona-avatar', () => ({
+ PersonaAvatar: (props: { botId: string; name: string }) => (
+ <span data-testid="agent-avatar" data-bot-id={props.botId}>
+ {props.name}
+ </span>
+ ),
+}));
vi.mock('@core/component/UserIcon', () => ({
UserIcon: (props: { id: string }) => (
<span data-testid="user-avatar" data-user-id={props.id} />
@@ -153,6 +163,23 @@ describe('Entity.Icon', () => {
).toBe('other-user');
});
+ it('gives persona DMs an agent avatar without a person tooltip or profile action', () => {
+ const { container } = render(() => (
+ <EntityIcon
+ entity={{
+ ...channel,
+ channelType: 'direct_message',
+ name: 'Researcher',
+ participantIds: ['user', 'bot|researcher'],
+ }}
+ />
+ ));
+ expect(container.querySelector('[data-testid="user-avatar"]')).toBeNull();
+ expect(
+ container.querySelector('[data-testid="agent-avatar"]')?.textContent
+ ).toBe('Researcher');
+ });
+
it.each(['user', 'other-user'])(
'keeps DM message rows on their DM glyph without fetching channel pictures (sender %s)',
(senderId) => {
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index b1768cf54f..474f7bff5f 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -1,3 +1,4 @@
+import { useOpenAgentDm } from '@app/features/agent-dms/open-agent-dm';
import { isCoderHarness } from '@app/features/agents-view/core/agent-kind';
import { AGENTS_TOUR } from '@app/features/agents-view/tour';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
@@ -6,17 +7,19 @@ import { ModelCatalogPicker } from '@core/component/AI/component/input/ModelCata
import { isLargeModelCatalog } from '@core/component/AI/component/input/modelCatalog';
import { MODEL_PRETTYNAME, Model } from '@core/component/AI/constant/model';
import { toast } from '@core/component/Toast/Toast';
-import { claudeCloud } from '@core/constant/featureFlags';
+import { claudeCloud, ENABLE_AGENT_DMS } from '@core/constant/featureFlags';
import {
MACRO_AGENT_BOT_ID,
MACRO_HARNESS_NAME,
} from '@core/constant/macroAgent';
+import { MACRO_NEW_BOT_ID } from '@core/constant/macroNew';
import { useChannelsContext } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import { usePipedreamMcpFlag } from '@core/pipedream/flag';
import MacroLogo from '@icon/macro-logo.svg';
import CursorIcon from '@icon/wide-cursor-ide.svg';
import ArrowLeftIcon from '@phosphor/arrow-left.svg';
+import ChatIcon from '@phosphor/chat-circle.svg';
import PencilIcon from '@phosphor/pencil-simple.svg';
import PlusIcon from '@phosphor/plus.svg';
import AgentIcon from '@phosphor/sparkle.svg';
@@ -128,6 +131,9 @@ export function Agents(props: {
onSetUpRuntime: () => void;
onManageRuntimes: () => void;
}) {
+ const agentDm = ENABLE_AGENT_DMS ? useOpenAgentDm() : undefined;
+ const messageAgent = (id: string) =>
+ agentDm?.open(id === MACRO_AGENT_BOT_ID ? MACRO_NEW_BOT_ID : id);
const agentList = tourTarget(AGENTS_TOUR.agentList);
const claudeCloudFlag = useFeatureFlag(claudeCloud);
const [creating, setCreating] = createSignal(false);
@@ -307,6 +313,10 @@ export function Agents(props: {
{(agent) => (
<AgentRow
agent={agent}
+ onMessage={
+ agentDm ? () => void messageAgent(agent.id) : undefined
+ }
+ messagePending={agentDm?.pending()}
onEdit={
agent.editable && agent.persistedAgent
? () => setEditingAgent(agent.persistedAgent)
@@ -424,6 +434,8 @@ function AgentRow(props: {
agent: AgentSummary;
onEdit?: () => void;
onDelete?: () => void;
+ onMessage?: () => void;
+ messagePending?: boolean;
}) {
return (
<div class="flex items-center gap-4 px-6 py-4 mobile:items-start touch:px-4">
@@ -446,6 +458,21 @@ function AgentRow(props: {
</p>
</div>
<div class="flex shrink-0 items-center gap-1">
+ <Show when={props.onMessage}>
+ {(onMessage) => (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={props.messagePending}
+ aria-label={`Message ${props.agent.name}`}
+ onClick={onMessage()}
+ >
+ <ChatIcon />
+ Message
+ </Button>
+ )}
+ </Show>
<Show when={props.onEdit}>
{(onEdit) => (
<Button
diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
index f060ff39c8..2c9da61c6a 100644
--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts
+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts
@@ -1151,6 +1151,8 @@ describe('AgentSession', () => {
parts: [{ kind: 'text', text: 'Hi' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
{
agentSessionId: SESSION,
@@ -1163,6 +1165,8 @@ describe('AgentSession', () => {
],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
]);
const [span] = renderSpans();
@@ -1288,6 +1292,8 @@ describe('AgentSession', () => {
parts: [{ kind: 'text', text: 'hi' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
{
@@ -1300,6 +1306,8 @@ describe('AgentSession', () => {
parts: [{ kind: 'thought', text: 'thinking' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
] satisfies FoldedStreamEvent[]);
@@ -1351,6 +1359,8 @@ describe('AgentSession', () => {
],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
] satisfies FoldedStreamEvent[]);
diff --git a/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts b/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts
index 2b210bd26e..ca3d6bdf8f 100644
--- a/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts
+++ b/apps/web/src/lib/core/agent-session/prompt-telemetry.test.ts
@@ -97,6 +97,8 @@ function withText(text = 'Hello'): PromptTrace {
parts: [{ kind: 'text', text: 'Question' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
{
@@ -109,6 +111,8 @@ function withText(text = 'Hello'): PromptTrace {
parts: [{ kind: 'text', text }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
]);
@@ -362,6 +366,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'hi' }],
stop: null,
pending: true,
+ segments: [],
+ phase: null,
},
},
];
@@ -377,6 +383,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'hi' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
];
@@ -392,6 +400,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'hello' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
];
@@ -460,6 +470,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'hi' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
{
@@ -472,6 +484,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'thought', text: 'nothing to say' }],
stop: { kind: 'end_turn' },
pending: false,
+ segments: [],
+ phase: null,
},
},
]);
@@ -510,6 +524,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'hi' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
{
@@ -522,6 +538,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'Hello' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
},
},
],
@@ -559,6 +577,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'an earlier turn' }],
stop: { kind: 'end_turn' },
pending: false,
+ segments: [],
+ phase: null,
},
{
agentSessionId: SESSION,
@@ -568,6 +588,8 @@ describe('PromptTrace', () => {
parts: [{ kind: 'text', text: 'hi' }],
stop: { kind: 'cancelled' },
pending: false,
+ segments: [],
+ phase: null,
},
],
},
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index 15af32bbb5..db99c0cf9d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -11,6 +11,7 @@ import type { HeadingNode, QuoteNode } from '@lexical/rich-text';
import type { TableCellNode, TableNode, TableRowNode } from '@lexical/table';
import {
$isClassedBlockNode,
+ type AgentActivityNode,
type AgentContextNode,
type AgentSessionMentionNode,
type AwaitNode,
@@ -83,6 +84,7 @@ import type { SearchMatchNode } from '@macro-inc/lexical-core/nodes/SearchMatchN
import { theme as baseTheme, createTheme } from '../../theme';
import { forceSingleLine, setEditorStateFromMarkdown } from '../../utils';
import { StaticCodeBoxAccessory } from '../accessory/CodeBoxAccessory';
+import { AgentActivity as AgentActivityDecorator } from '../decorator/AgentActivity';
import { AgentContext as AgentContextDecorator } from '../decorator/AgentContext';
import { AgentSessionMention as AgentSessionMentionDecorator } from '../decorator/AgentSessionMention';
import { Await as AwaitDecorator } from '../decorator/Await';
@@ -594,6 +596,18 @@ const AgentContext: TypedRenderableEntity<AgentContextNode> = {
),
};
+const AgentActivity: TypedRenderableEntity<AgentActivityNode> = {
+ guard: (node: LexicalNode): node is AgentActivityNode =>
+ node.__type === 'agent-activity',
+ render: (props) => (
+ <AgentActivityDecorator
+ {...props.node.exportComponentProps()}
+ key={props.node.getKey()}
+ theme={props.theme}
+ />
+ ),
+};
+
const ReplyTarget: TypedRenderableEntity<ReplyTargetNode> = {
guard: (node: LexicalNode): node is ReplyTargetNode =>
node.__type === 'reply-target',
@@ -1016,6 +1030,7 @@ const InlineEntities: RenderableEntity[] = [
eraseRenderableEntity(GroupMention),
eraseRenderableEntity(Await),
eraseRenderableEntity(AgentContext),
+ eraseRenderableEntity(AgentActivity),
eraseRenderableEntity(ReplyTarget),
eraseRenderableEntity(CursorSystemNotification),
eraseRenderableEntity(MagicChip),
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentActivity.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentActivity.tsx
new file mode 100644
index 0000000000..8f95f2d904
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/AgentActivity.tsx
@@ -0,0 +1,16 @@
+import { AgentActivity as AgentActivityView } from '@app/features/agent-activity/agent-activity';
+import type { AgentActivityDecoratorProps } from '@macro-inc/lexical-core';
+import type { Component } from 'solid-js';
+
+/** The steps of an agent's reply, live where the session is readable. */
+export const AgentActivity: Component<AgentActivityDecoratorProps> = (
+ props
+) => (
+ <AgentActivityView
+ agentSessionId={props.agentSessionId}
+ turn={props.turn}
+ segment={props.segment}
+ rows={props.rows}
+ sealed={props.sealed}
+ />
+);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index d96a6c646d..74eb7c0d2d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -109,6 +109,8 @@ const prompt: FoldedMessage = {
parts: [{ kind: 'text', text: 'Say hi' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
};
const response: FoldedMessage = {
@@ -119,6 +121,8 @@ const response: FoldedMessage = {
parts: [{ kind: 'text', text: 'Hi!' }],
stop: { kind: 'end_turn' },
pending: false,
+ segments: [],
+ phase: null,
};
const openResponse: FoldedMessage = {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
index 93d0cdabe6..20c0747cf0 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
@@ -1,3 +1,5 @@
+import type { InteractionController } from '@app/features/agent-interactions/context/interaction';
+import { createInteractionController } from '@app/features/agent-interactions/primitives/create-interaction-controller';
import {
harnessDisplayName,
harnessTitle,
@@ -8,8 +10,6 @@ import {
toolCallDetail,
toolLabel,
} from '@app/features/block-agent/component/parts/shared';
-import type { InteractionController } from '@app/features/block-agent/context/interaction';
-import { createInteractionController } from '@app/features/block-agent/primitives/create-interaction-controller';
import { issueSessionAction } from '@app/features/block-agent/queries/issue-session-action';
import { describeToolCall } from '@app/features/block-agent/state/tool-approval-wording';
import { AgentSession } from '@core/agent-session/AgentSession';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
index 406713bce9..c3e51d9711 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
@@ -14,6 +14,8 @@ const response = (overrides: Partial<FoldedMessage> = {}): FoldedMessage => ({
parts: [{ kind: 'thought', text: 'Inspecting the repository' }],
stop: null,
pending: false,
+ segments: [],
+ phase: null,
...overrides,
});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
index ca5e406171..2468001605 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
@@ -1,5 +1,6 @@
import { lazyNamed } from '@core/util/lazyNamed';
import {
+ AgentActivityNode,
AgentContextNode,
AgentSessionMentionNode,
AwaitNode,
@@ -35,6 +36,7 @@ import {
} from '@macro-inc/lexical-core/decoratorRegistry';
import type { HtmlRenderDecoratorProps } from '@macro-inc/lexical-core/nodes/HtmlRenderNode';
import { createComponent, Suspense } from 'solid-js';
+import { AgentActivity } from './component/decorator/AgentActivity';
import { AgentContext } from './component/decorator/AgentContext';
import { AgentSessionMention } from './component/decorator/AgentSessionMention';
import { Await } from './component/decorator/Await';
@@ -83,6 +85,7 @@ const HtmlRender = (props: HtmlRenderDecoratorProps) =>
export function initializeLexical() {
clearDecorators();
setDecorator(AgentContextNode, AgentContext);
+ setDecorator(AgentActivityNode, AgentActivity);
setDecorator(HorizontalRuleNode, HorizontalRule);
setDecorator(UserMentionNode, UserMention);
setDecorator(GroupMentionNode, GroupMention);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
index 97bfc5ac5b..fcac388bd4 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
@@ -34,5 +34,6 @@
* Version 7.1 - Oct 2026. PullRequestMentionNode: optional GitHub `url`; `id` may be empty
* when an agent mentions a PR by URL, and the decorator resolves the synced PR.
* Version 8.0 - Oct 2026. Added BookingLinkMentionNode for Macro `/app/book/…` URLs.
+ * Version 9.0 - Oct 2026. Added AgentActivityNode: the steps of an agent's reply between two passages, with a snapshot of its rows and live rendering where the session is readable.
*/
-export const MARKDOWN_VERSION_COUNTER = 8.0;
+export const MARKDOWN_VERSION_COUNTER = 9.0;
diff --git a/apps/web/src/lib/core/component/RecipientSelector.tsx b/apps/web/src/lib/core/component/RecipientSelector.tsx
index 28f7b5a6ad..2d916042db 100644
--- a/apps/web/src/lib/core/component/RecipientSelector.tsx
+++ b/apps/web/src/lib/core/component/RecipientSelector.tsx
@@ -29,7 +29,6 @@ import HashIcon from '@phosphor/hash.svg';
import PaperPlaneTiltIcon from '@phosphor/paper-plane-tilt.svg';
import RobotIcon from '@phosphor/robot.svg';
import XIcon from '@phosphor/x.svg';
-import type { Bot } from '@service-storage/generated/schemas/bot';
import { debounce } from '@solid-primitives/scheduled';
import { Avatar, cn, Layer } from '@ui';
import * as EmailValidator from 'email-validator';
@@ -94,7 +93,7 @@ function RecipientChip(props: {
);
}
-function AgentAvatar(props: { agent: Bot }) {
+function AgentAvatar(props: { agent: CombinedRecipientItem<'agent'>['data'] }) {
return (
<Avatar size="sm">
<Show
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index ab759c2df8..bd0eb3b223 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -729,6 +729,13 @@ export const enableChatV3Agents = defineFlag({
default: onInDev,
});
+// Private conversations with agent personas. Explicit environment opt-in;
+// this flag has no remote PostHog source. VITE_ENABLE_AGENT_DMS=true enables it.
+export const ENABLE_AGENT_DMS = defineFlag({
+ env: 'ENABLE_AGENT_DMS',
+ default: false,
+}).enabled;
+
// The built-in @cursor mention, using the mentioning user's own Cursor account.
// Account setup is checked after the mention; this flag controls discovery.
// Override with VITE_ENABLE_CURSOR_AGENTS.
diff --git a/apps/web/src/lib/core/context/channels.test.tsx b/apps/web/src/lib/core/context/channels.test.tsx
new file mode 100644
index 0000000000..a9f6811b67
--- /dev/null
+++ b/apps/web/src/lib/core/context/channels.test.tsx
@@ -0,0 +1,81 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { cleanup, render } from '@solidjs/testing-library';
+import { createStore } from 'solid-js/store';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ channels: vi.fn() }));
+vi.mock('@queries/channel/channels', () => ({
+ useListChannelsQuery: mocks.channels,
+}));
+vi.mock('@queries/channel/activity', () => ({
+ useChannelsActivityQuery: () => ({
+ isPending: false,
+ isLoading: false,
+ data: [],
+ }),
+}));
+vi.mock('./user', () => ({ useUserId: () => () => undefined }));
+
+import { ChannelsContextProvider, useChannelCanCall } from './channels';
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function CanCall(props: { channelId: string }) {
+ const canCall = useChannelCanCall(props.channelId);
+ return <output>{String(canCall())}</output>;
+}
+
+function setup(channelId: string) {
+ const [list, setList] = createStore({
+ loading: true,
+ channels: [] as { id: string; agent_dm?: { bot_id: string } }[],
+ });
+ mocks.channels.mockReturnValue({
+ get isPending() {
+ return list.loading;
+ },
+ get isLoading() {
+ return list.loading;
+ },
+ get data() {
+ if (list.loading) throw new Error('Pending data must not be read');
+ return list.channels;
+ },
+ });
+ const view = render(() => (
+ <ChannelsContextProvider>
+ <CanCall channelId={channelId} />
+ </ChannelsContextProvider>
+ ));
+ return { setList, value: () => view.getByRole('status').textContent };
+}
+
+describe('useChannelCanCall', () => {
+ it('waits for the channel list, then refuses an agent DM', () => {
+ const { setList, value } = setup('dm');
+ expect(value()).toBe('undefined');
+ setList({
+ loading: false,
+ channels: [{ id: 'dm', agent_dm: { bot_id: 'bot' } }],
+ });
+ expect(value()).toBe('false');
+ });
+
+ it('allows a listed channel that is not an agent DM', () => {
+ const { setList, value } = setup('team');
+ setList({ loading: false, channels: [{ id: 'team' }] });
+ expect(value()).toBe('true');
+ });
+
+ it('allows a channel the loaded list does not have', () => {
+ const { setList, value } = setup('public');
+ setList({ loading: false, channels: [{ id: 'other' }] });
+ expect(value()).toBe('true');
+ });
+});
diff --git a/apps/web/src/lib/core/context/channels.ts b/apps/web/src/lib/core/context/channels.ts
index ca00aae515..d76396a533 100644
--- a/apps/web/src/lib/core/context/channels.ts
+++ b/apps/web/src/lib/core/context/channels.ts
@@ -65,6 +65,22 @@ export function useChannel(channelId: string) {
return createMemo(() => ctx.channelsById()[channelId]);
}
+/**
+ * Whether a channel can host a call: unknown while the channel list first
+ * loads, and never in an agent DM. A channel the loaded list lacks is not
+ * one of the user's agent DMs, so it can, as before agent DMs existed.
+ */
+export function useChannelCanCall(
+ channelId: string
+): Accessor<boolean | undefined> {
+ const ctx = useChannelsContext();
+ return createMemo(() => {
+ const channel = ctx.channelsById()[channelId];
+ if (channel) return !channel.agent_dm;
+ return ctx.isLoading() ? undefined : true;
+ });
+}
+
export function useChannelName(channelId: string, fallback?: string) {
const ctx = useChannelsContext();
return createMemo(() => ctx.channelsById()[channelId]?.name ?? fallback);
diff --git a/apps/web/src/lib/core/user/combinedRecipient.ts b/apps/web/src/lib/core/user/combinedRecipient.ts
index 323c598d9f..1c93c1d8dc 100644
--- a/apps/web/src/lib/core/user/combinedRecipient.ts
+++ b/apps/web/src/lib/core/user/combinedRecipient.ts
@@ -18,7 +18,7 @@ type EntityMap = {
channel: ChannelWithParticipants;
contact: ExtractedContactInfo;
custom: CustomUserInput;
- agent: Bot;
+ agent: Pick<Bot, 'id' | 'name' | 'handle' | 'description' | 'avatar_url'>;
};
type Entity<T extends keyof EntityMap> = {
diff --git a/apps/web/src/lib/queries/messages/sync.ts b/apps/web/src/lib/queries/messages/sync.ts
index d0ebfd4c6f..e14fe4cbe1 100644
--- a/apps/web/src/lib/queries/messages/sync.ts
+++ b/apps/web/src/lib/queries/messages/sync.ts
@@ -185,6 +185,7 @@ export function handleMessageEvent(
user_id: event.actor,
thread_id: change.thread_id,
action: change.active ? 'start' : 'stop',
+ agent: change.agent,
},
currentUserId ?? ''
);
diff --git a/apps/web/src/lib/queries/messages/tests/typing.test.ts b/apps/web/src/lib/queries/messages/tests/typing.test.ts
index b492754003..60c75a1659 100644
--- a/apps/web/src/lib/queries/messages/tests/typing.test.ts
+++ b/apps/web/src/lib/queries/messages/tests/typing.test.ts
@@ -8,6 +8,7 @@ vi.mock('@service-storage/client', () => ({
import {
clearTypingIndicators,
+ getTypingAgents,
getTypingUsers,
handleCommsTyping,
TYPING_INDICATOR_TIMEOUT_MS,
@@ -62,3 +63,51 @@ describe('channel typing indicators', () => {
expect(typingUsers()).toEqual([]);
});
});
+
+describe('agent typing indicators', () => {
+ const parent = { type: 'channel', id: 'channel-1' } as const;
+ const agentTyping = (
+ action: 'start' | 'stop',
+ phase: 'thinking' | 'working' = 'thinking',
+ threadId: string | null = null
+ ) =>
+ handleCommsTyping(
+ {
+ action,
+ parent,
+ user_id: 'bot|agent',
+ thread_id: threadId,
+ agent: { session_id: 'session-1', phase },
+ },
+ currentUserId
+ );
+
+ it('keeps what an agent is doing beside its typing, updated in place', () => {
+ agentTyping('start');
+ handleCommsTyping(
+ { action: 'start', parent, user_id: 'user-typing' },
+ currentUserId
+ );
+ expect([...getTypingAgents(parent)]).toEqual([
+ ['bot|agent', { sessionId: 'session-1', phase: 'thinking' }],
+ ]);
+
+ const before = getTypingUsers(parent);
+ agentTyping('start', 'working');
+ expect(getTypingUsers(parent)).toBe(before);
+ expect(getTypingAgents(parent).get('bot|agent')?.phase).toBe('working');
+
+ agentTyping('stop');
+ expect(getTypingAgents(parent).size).toBe(0);
+ expect(typingUsers()).toEqual(['user-typing']);
+ });
+
+ it('scopes an agent to the thread it types in and expires it', () => {
+ agentTyping('start', 'thinking', 'root-1');
+ expect(getTypingAgents(parent).size).toBe(0);
+ expect(getTypingAgents(parent, 'root-1').has('bot|agent')).toBe(true);
+
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS);
+ expect(getTypingAgents(parent, 'root-1').size).toBe(0);
+ });
+});
diff --git a/apps/web/src/lib/queries/messages/typing.ts b/apps/web/src/lib/queries/messages/typing.ts
index ef56c0b0ff..71f8ac754b 100644
--- a/apps/web/src/lib/queries/messages/typing.ts
+++ b/apps/web/src/lib/queries/messages/typing.ts
@@ -1,7 +1,8 @@
+import type { AgentTypingPhase } from '@service-storage/generated/schemas/agentTypingPhase';
import type { MessageParent } from '@service-storage/messages';
import { entityMessagesClient } from '@service-storage/messages';
import { useMutation } from '@tanstack/solid-query';
-import { createSignal } from 'solid-js';
+import { batch, createSignal } from 'solid-js';
import { parentKey } from './keys';
export const TYPING_INDICATOR_TIMEOUT_MS = 8_000;
@@ -21,8 +22,13 @@ type CommsTypingPayload = {
user_id: string;
action: 'start' | 'stop';
thread_id?: string | null;
+ /** Present when a bot types for an agent session. */
+ agent?: { session_id: string; phase: AgentTypingPhase } | null;
};
+/** An agent session typing through its bot: whose turn, and what it is doing. */
+export type TypingAgent = { sessionId: string; phase: AgentTypingPhase };
+
/**
* Ephemeral store for typing indicators.
* Map<parent, Map<threadId | null, Set<userId>>>
@@ -35,12 +41,43 @@ const [typingUsers, setTypingUsers] = createSignal<TypingUsersByChannel>(
const typingTimeouts: TypingTimeoutsByChannel = new Map();
+/** What each typing agent is doing, by {@link agentKey}; humans have none. */
+const [typingAgents, setTypingAgents] = createSignal<Map<string, TypingAgent>>(
+ new Map()
+);
+
+const agentKey = (parent: MessageParent, threadId: ThreadId, userId: string) =>
+ JSON.stringify([parentKey(parent), threadId, userId]);
+
+function setTypingAgent(
+ parent: MessageParent,
+ userId: string,
+ threadId: ThreadId,
+ agent: TypingAgent | undefined
+) {
+ const key = agentKey(parent, threadId, userId);
+ setTypingAgents((prev) => {
+ const current = prev.get(key);
+ if (
+ current?.sessionId === agent?.sessionId &&
+ current?.phase === agent?.phase
+ )
+ return prev;
+ const next = new Map(prev);
+ if (agent) next.set(key, agent);
+ else next.delete(key);
+ return next;
+ });
+}
+
function withAddedTypingUser(
prev: TypingUsersByChannel,
parent: MessageParent,
userId: string,
threadId: ThreadId
): TypingUsersByChannel {
+ // Agents refresh every few seconds; an unchanged set keeps readers still.
+ if (prev.get(parentKey(parent))?.get(threadId)?.has(userId)) return prev;
const next = new Map(prev);
const channelMap = new Map(prev.get(parentKey(parent)));
const threadUsers = new Set(channelMap.get(threadId));
@@ -153,14 +190,21 @@ export function clearTypingIndicators(): void {
typingTimeouts.clear();
setTypingUsers(new Map());
+ setTypingAgents(new Map());
}
function addTypingUser(
parent: MessageParent,
userId: string,
- threadId: ThreadId = null
+ threadId: ThreadId = null,
+ agent?: TypingAgent
) {
- setTypingUsers((prev) => withAddedTypingUser(prev, parent, userId, threadId));
+ batch(() => {
+ setTypingUsers((prev) =>
+ withAddedTypingUser(prev, parent, userId, threadId)
+ );
+ setTypingAgent(parent, userId, threadId, agent);
+ });
setTypingTimeout(parent, userId, threadId);
}
@@ -170,8 +214,11 @@ function removeTypingUser(
threadId: ThreadId = null
) {
removeTypingTimeout(parent, userId, threadId);
- setTypingUsers((prev) => {
- return withoutTypingUser(prev, parent, userId, threadId);
+ batch(() => {
+ setTypingUsers((prev) => {
+ return withoutTypingUser(prev, parent, userId, threadId);
+ });
+ setTypingAgent(parent, userId, threadId, undefined);
});
}
@@ -185,6 +232,23 @@ export function getTypingUsers(
return typingUsers().get(parentKey(parent))?.get(threadId) ?? new Set();
}
+/**
+ * The typing users in a channel/thread that are agent sessions typing
+ * through their bot, with what each is doing.
+ */
+export function getTypingAgents(
+ parent: MessageParent,
+ threadId: ThreadId = null
+): Map<string, TypingAgent> {
+ const agents = typingAgents();
+ const typing = new Map<string, TypingAgent>();
+ for (const userId of getTypingUsers(parent, threadId)) {
+ const agent = agents.get(agentKey(parent, threadId, userId));
+ if (agent) typing.set(userId, agent);
+ }
+ return typing;
+}
+
/**
* Handle typing indicator from websocket.
* Ignores typing events from the current user.
@@ -197,7 +261,14 @@ export function handleCommsTyping(
if (payload.user_id === currentUserId) return;
if (payload.action === 'start') {
- addTypingUser(payload.parent, payload.user_id, payload.thread_id ?? null);
+ addTypingUser(
+ payload.parent,
+ payload.user_id,
+ payload.thread_id ?? null,
+ payload.agent
+ ? { sessionId: payload.agent.session_id, phase: payload.agent.phase }
+ : undefined
+ );
} else {
removeTypingUser(
payload.parent,
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index 56ac9e5920..308c5f4b6c 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -1,4 +1,30 @@
// This file has been generated by Specta. Do not edit this file manually.
+/** One step of work, worded for a person reading a conversation. */
+export type ActivityRow = {
+ /** The tool call's id, stable across updates; `plan` for a plan update. */
+ id: string;
+ /** What happened, as a verb phrase: `Ran`, `Reading`, `Search documents`. */
+ label: string;
+ /**
+ * What it happened to - a command, a file, a query - when that is safe
+ * to show to everyone who can read the conversation.
+ */
+ detail: string | null;
+ /** Where it got to. */
+ status: ActivityStatus;
+};
+
+/** Where one step of work got to. */
+export type ActivityStatus =
+ /** Started and not finished, including a call waiting on permission. */
+ | 'running'
+ /** Finished successfully. */
+ | 'completed'
+ /** Finished unsuccessfully. */
+ | 'failed'
+ /** Still running when its turn ended: nobody knows whether it finished. */
+ | 'interrupted';
+
/**
* The JSON-RPC id of a request the agent made, as the agent wrote it.
*
@@ -494,6 +520,16 @@ export type FoldedMessage = {
* the confirmed frame arrives.
*/
pending: boolean;
+ /**
+ * How an agent's reply reads as a conversation, the same boundaries the
+ * server posts channel messages by. Empty on a user's message.
+ */
+ segments: Segment[];
+ /**
+ * What an agent's unfinished reply is doing now; absent once its turn
+ * has ended and on a user's message.
+ */
+ phase: TurnPhase | null;
};
/**
@@ -886,6 +922,34 @@ export type PlanEntryStatus =
/** Successfully completed. */
| 'completed';
+/** A run of a reply's parts that reads as one unit. */
+export type Segment = {
+ /** Position among the reply's segments, from zero. */
+ index: number;
+ /** What the segment is. */
+ kind: SegmentKind;
+ /** Index of the segment's first part. */
+ start: number;
+ /** Index one past the segment's last part. */
+ end: number;
+ /**
+ * Whether the segment can still change: false only for the last segment
+ * of a reply that is still being written.
+ */
+ sealed: boolean;
+ /** The steps, for an activity segment; empty otherwise. */
+ rows: ActivityRow[];
+};
+
+/** What a segment of a reply is. */
+export type SegmentKind =
+ /** A passage the agent wrote. */
+ | 'prose'
+ /** A run of tool calls and plan updates. */
+ | 'activity'
+ /** A permission or a question the agent put to the user. */
+ | 'interaction';
+
/** The supported ACP session-config shapes. */
export type SessionConfigKind =
/** A single-value selector. */
@@ -1340,6 +1404,17 @@ export type ToolStatus =
/** A tool call within a turn, identified by its ACP `toolCallId`. */
export type ToolUseId = string;
+/** What the agent is doing right now, as a typing indicator says it. */
+export type TurnPhase =
+ /** Nothing to show yet, or between steps. */
+ | 'thinking'
+ /** Writing prose. */
+ | 'writing'
+ /** Running a tool. */
+ | 'working'
+ /** Waiting on the user to answer a permission or a question. */
+ | 'waiting';
+
/** Where the newest turn stands. */
export type TurnState =
/** No turn is open. */
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/agent-conversations.ts b/apps/web/src/lib/service-clients/service-agent-harness/agent-conversations.ts
new file mode 100644
index 0000000000..e61a8ed217
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/agent-conversations.ts
@@ -0,0 +1,36 @@
+import { SERVER_HOSTS } from '@core/constant/servers';
+import { fetchWithToken } from '@core/util/fetchWithToken';
+
+import type {
+ AgentConversationDto,
+ AgentConversationsDto,
+ AgentConversationTurnDto,
+} from './generated/schemas';
+
+export type AgentConversation = AgentConversationDto;
+export type AgentConversationTurn = AgentConversationTurnDto;
+
+/** The agent conversations in a channel that the caller may see. */
+export function listAgentConversations(
+ channelId: string,
+ signal?: AbortSignal
+) {
+ return fetchWithToken<AgentConversationsDto>(
+ `${SERVER_HOSTS['agent-harness']}/agent-conversations/${channelId}`,
+ { method: 'GET', signal }
+ ).then((result) => result.map((data) => data.conversations));
+}
+
+export function retryAgentConversationTurn(
+ conversation: Pick<AgentConversation, 'channelId' | 'botId'>,
+ turn: AgentConversationTurn
+) {
+ return fetchWithToken<Record<string, never>>(
+ `${SERVER_HOSTS['agent-harness']}/agent-conversations/${conversation.channelId}/${conversation.botId}/turns/${turn.sourceMessageId}/retry`,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ actionId: turn.actionId }),
+ }
+ ).then((result) => result.map(() => undefined));
+}
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.ts
index 26082a4b6c..591f0b19d1 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
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type {
+ AgentConversationsDto,
AgentRepositoriesResponse,
AgentRepositoryBranchesResponse,
AgentSessionChangesPatchResponse,
@@ -35,10 +36,12 @@ import type {
PullRequestUrl,
PullRequestUrls,
RenameAgentSessionRequest,
+ RetryAgentConversationTurnRequest,
SandboxSizeBody,
SessionPullRequestsResponse,
SetAgentSessionArchivedRequest,
SharePermissionV2,
+ StartFreshAgentConversationRequest,
StartResponse,
StatusResponse,
UnlinkAgentSessionPullRequestParams,
@@ -248,6 +251,205 @@ export const putAgentCodingPreferences = async (
} as putAgentCodingPreferencesResponse;
};
+/**
+ * @summary The agent conversations in a channel the caller may see. Ordinary channels
+and other people's conversations list none.
+ */
+export type listAgentConversationsResponse200 = {
+ data: AgentConversationsDto;
+ status: 200;
+};
+
+export type listAgentConversationsResponse503 = {
+ data: void;
+ status: 503;
+};
+
+export type listAgentConversationsResponseSuccess =
+ listAgentConversationsResponse200 & {
+ headers: Headers;
+ };
+export type listAgentConversationsResponseError =
+ listAgentConversationsResponse503 & {
+ headers: Headers;
+ };
+
+export type listAgentConversationsResponse =
+ | listAgentConversationsResponseSuccess
+ | listAgentConversationsResponseError;
+
+export const getListAgentConversationsUrl = (channelId: string) => {
+ return `/agent-conversations/${channelId}`;
+};
+
+export const listAgentConversations = async (
+ channelId: string,
+ options?: RequestInit
+): Promise<listAgentConversationsResponse> => {
+ const res = await fetch(getListAgentConversationsUrl(channelId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listAgentConversationsResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listAgentConversationsResponse;
+};
+
+/**
+ * @summary Start a fresh agent context, retaining the channel transcript.
+ */
+export type startFreshAgentConversationResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type startFreshAgentConversationResponse404 = {
+ data: void;
+ status: 404;
+};
+
+export type startFreshAgentConversationResponse409 = {
+ data: void;
+ status: 409;
+};
+
+export type startFreshAgentConversationResponse503 = {
+ data: void;
+ status: 503;
+};
+
+export type startFreshAgentConversationResponseSuccess =
+ startFreshAgentConversationResponse204 & {
+ headers: Headers;
+ };
+export type startFreshAgentConversationResponseError = (
+ | startFreshAgentConversationResponse404
+ | startFreshAgentConversationResponse409
+ | startFreshAgentConversationResponse503
+) & {
+ headers: Headers;
+};
+
+export type startFreshAgentConversationResponse =
+ | startFreshAgentConversationResponseSuccess
+ | startFreshAgentConversationResponseError;
+
+export const getStartFreshAgentConversationUrl = (
+ channelId: string,
+ botId: string
+) => {
+ return `/agent-conversations/${channelId}/${botId}/start-fresh`;
+};
+
+export const startFreshAgentConversation = async (
+ channelId: string,
+ botId: string,
+ startFreshAgentConversationRequest: StartFreshAgentConversationRequest,
+ options?: RequestInit
+): Promise<startFreshAgentConversationResponse> => {
+ const res = await fetch(getStartFreshAgentConversationUrl(channelId, botId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(startFreshAgentConversationRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: startFreshAgentConversationResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as startFreshAgentConversationResponse;
+};
+
+/**
+ * @summary Explicitly retry a failed message in the conversation's current session.
+ */
+export type retryAgentConversationTurnResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type retryAgentConversationTurnResponse404 = {
+ data: void;
+ status: 404;
+};
+
+export type retryAgentConversationTurnResponse409 = {
+ data: void;
+ status: 409;
+};
+
+export type retryAgentConversationTurnResponse503 = {
+ data: void;
+ status: 503;
+};
+
+export type retryAgentConversationTurnResponseSuccess =
+ retryAgentConversationTurnResponse204 & {
+ headers: Headers;
+ };
+export type retryAgentConversationTurnResponseError = (
+ | retryAgentConversationTurnResponse404
+ | retryAgentConversationTurnResponse409
+ | retryAgentConversationTurnResponse503
+) & {
+ headers: Headers;
+};
+
+export type retryAgentConversationTurnResponse =
+ | retryAgentConversationTurnResponseSuccess
+ | retryAgentConversationTurnResponseError;
+
+export const getRetryAgentConversationTurnUrl = (
+ channelId: string,
+ botId: string,
+ source: string
+) => {
+ return `/agent-conversations/${channelId}/${botId}/turns/${source}/retry`;
+};
+
+export const retryAgentConversationTurn = async (
+ channelId: string,
+ botId: string,
+ source: string,
+ retryAgentConversationTurnRequest: RetryAgentConversationTurnRequest,
+ options?: RequestInit
+): Promise<retryAgentConversationTurnResponse> => {
+ const res = await fetch(
+ getRetryAgentConversationTurnUrl(channelId, botId, source),
+ {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(retryAgentConversationTurnRequest),
+ }
+ );
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: retryAgentConversationTurnResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as retryAgentConversationTurnResponse;
+};
+
/**
* @summary Probe one provider's model catalog without creating an agent session.
*/
@@ -1080,6 +1282,11 @@ export type setAgentSessionArchivedResponse403 = {
status: 403;
};
+export type setAgentSessionArchivedResponse409 = {
+ data: string;
+ status: 409;
+};
+
export type setAgentSessionArchivedResponse500 = {
data: string;
status: 500;
@@ -1092,6 +1299,7 @@ export type setAgentSessionArchivedResponseSuccess =
export type setAgentSessionArchivedResponseError = (
| setAgentSessionArchivedResponse401
| setAgentSessionArchivedResponse403
+ | setAgentSessionArchivedResponse409
| setAgentSessionArchivedResponse500
) & {
headers: Headers;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationDto.ts
new file mode 100644
index 0000000000..835babc8f3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationDto.ts
@@ -0,0 +1,31 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentConversationDtoAvatarUrl } from './agentConversationDtoAvatarUrl';
+import type { AgentConversationSessionDto } from './agentConversationSessionDto';
+import type { AgentConversationTurnDto } from './agentConversationTurnDto';
+
+/**
+ * An agent's conversation in a channel, as the person it is with sees it.
+ */
+export interface AgentConversationDto {
+ /** Whether the caller may currently send a new prompt. */
+ available: boolean;
+ /** Optional persona avatar. */
+ avatarUrl?: AgentConversationDtoAvatarUrl;
+ /** Persona id (without the bot principal prefix). */
+ botId: string;
+ /** The channel containing the visible transcript. */
+ channelId: string;
+ /** Persona's historical display name. */
+ name: string;
+ /** The sessions the conversation has run on, oldest first. */
+ sessions: AgentConversationSessionDto[];
+ /** Whether new persona settings are available to adopt explicitly. */
+ settingsChanged: boolean;
+ /** Persistent state of each accepted message and its current attempt. */
+ turns: AgentConversationTurnDto[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationDtoAvatarUrl.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationDtoAvatarUrl.ts
new file mode 100644
index 0000000000..8f56bf9877
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationDtoAvatarUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional persona avatar.
+ */
+export type AgentConversationDtoAvatarUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationSessionDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationSessionDto.ts
new file mode 100644
index 0000000000..244ff93132
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationSessionDto.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * One session a conversation has run on; every channel message stays visible.
+ */
+export interface AgentConversationSessionDto {
+ /** When the session began. */
+ createdAt: string;
+ /** Whether this is the current agent context. */
+ isCurrent: boolean;
+ /** Session whose controls and live events belong to this context. */
+ sessionId: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationTurnDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationTurnDto.ts
new file mode 100644
index 0000000000..9ca94a8796
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationTurnDto.ts
@@ -0,0 +1,29 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentConversationTurnDtoReplyMessageId } from './agentConversationTurnDtoReplyMessageId';
+import type { ConversationTurnState } from './conversationTurnState';
+
+/**
+ * Execution status without exposing the persona prompt or stored credentials.
+ */
+export interface AgentConversationTurnDto {
+ /** Current runtime attempt identity. */
+ actionId: string;
+ /** When the source message was first accepted. */
+ createdAt: string;
+ /** The associated agent reply, if it has been posted. */
+ replyMessageId?: AgentConversationTurnDtoReplyMessageId;
+ /** Whether Retry would be accepted now. A failed attempt is not retryable
+until its reply says how it ended. */
+ retryable: boolean;
+ /** Session carrying this turn. */
+ sessionId: string;
+ /** The user's message in the channel timeline. */
+ sourceMessageId: string;
+ /** Durable execution state. */
+ state: ConversationTurnState;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationTurnDtoReplyMessageId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationTurnDtoReplyMessageId.ts
new file mode 100644
index 0000000000..e0831ee524
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationTurnDtoReplyMessageId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The associated agent reply, if it has been posted.
+ */
+export type AgentConversationTurnDtoReplyMessageId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationsDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationsDto.ts
new file mode 100644
index 0000000000..6347462ae7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentConversationsDto.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentConversationDto } from './agentConversationDto';
+
+/**
+ * The agent conversations in a channel the caller may see.
+ */
+export interface AgentConversationsDto {
+ /** Empty for ordinary channels and other people's conversations. */
+ conversations: AgentConversationDto[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/conversationTurnState.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/conversationTurnState.ts
new file mode 100644
index 0000000000..5c09c2bf27
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/conversationTurnState.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The state of one source message, retained after completion for deduplication.
+ */
+export type ConversationTurnState =
+ (typeof ConversationTurnState)[keyof typeof ConversationTurnState];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ConversationTurnState = {
+ queued: 'queued',
+ running: 'running',
+ succeeded: 'succeeded',
+ failed: 'failed',
+ stopped: 'stopped',
+ interrupted: 'interrupted',
+} as const;
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.ts
index c760df99bc..ab0cadefd8 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
@@ -39,6 +39,12 @@ export * from './agentConfigOptionDtoAllOfDescription';
export * from './agentConfigSelectOptionDto';
export * from './agentConfigSelectOptionDtoDescription';
export * from './agentConfigSelectOptionDtoGroup';
+export * from './agentConversationDto';
+export * from './agentConversationDtoAvatarUrl';
+export * from './agentConversationSessionDto';
+export * from './agentConversationsDto';
+export * from './agentConversationTurnDto';
+export * from './agentConversationTurnDtoReplyMessageId';
export * from './agentModelDto';
export * from './agentModelDtoDescription';
export * from './agentModelDtoGroup';
@@ -111,6 +117,7 @@ export * from './controlRequestAllOfContext';
export * from './controlRequestAllOfContextAnyOf';
export * from './controlResponse';
export * from './controlStatusDto';
+export * from './conversationTurnState';
export * from './createAgentSessionRequest';
export * from './createAgentSessionRequestBotId';
export * from './createAgentSessionRequestId';
@@ -198,6 +205,7 @@ export * from './queuedActionDto';
export * from './queuedActionDtoActorUserId';
export * from './queuedActionDtoPrompt';
export * from './renameAgentSessionRequest';
+export * from './retryAgentConversationTurnRequest';
export * from './sandboxSize';
export * from './sandboxSizeBody';
export * from './sessionBot';
@@ -218,6 +226,7 @@ export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2LinkShare';
export * from './sharePermissionV2LinkShareAccessLevel';
export * from './sharePermissionV2TeamShareAccessLevel';
+export * from './startFreshAgentConversationRequest';
export * from './startResponse';
export * from './statusResponse';
export * from './toolApprovalAnswerDto';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/retryAgentConversationTurnRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/retryAgentConversationTurnRequest.ts
new file mode 100644
index 0000000000..165cc5da03
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/retryAgentConversationTurnRequest.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The attempt the user saw and chose to retry; prevents double-click reruns.
+ */
+export interface RetryAgentConversationTurnRequest {
+ /** Current failed attempt identity. */
+ actionId: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/startFreshAgentConversationRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/startFreshAgentConversationRequest.ts
new file mode 100644
index 0000000000..3caaed0d47
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/startFreshAgentConversationRequest.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The session the user is choosing to leave behind.
+ */
+export interface StartFreshAgentConversationRequest {
+ /** Current session id shown in the conversation metadata. */
+ sessionId: string;
+}
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.json
index 0c9e06eccc..e26c42b56a 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
@@ -148,6 +148,168 @@
}
}
},
+ "/agent-conversations/{channel_id}": {
+ "get": {
+ "tags": ["agent-conversations"],
+ "summary": "The agent conversations in a channel the caller may see. Ordinary channels\nand other people's conversations list none.",
+ "operationId": "list_agent_conversations",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "description": "Conversation channel",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The caller's agent conversations in the channel",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentConversationsDto"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Conversations temporarily unavailable"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
+ "/agent-conversations/{channel_id}/{bot_id}/start-fresh": {
+ "post": {
+ "tags": ["agent-conversations"],
+ "summary": "Start a fresh agent context, retaining the channel transcript.",
+ "operationId": "start_fresh_agent_conversation",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "bot_id",
+ "in": "path",
+ "description": "Persona the conversation is with",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartFreshAgentConversationRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "New context reserved"
+ },
+ "404": {
+ "description": "Conversation not found"
+ },
+ "409": {
+ "description": "Context is busy, stale or unavailable"
+ },
+ "503": {
+ "description": "Temporarily unavailable"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
+ "/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry": {
+ "post": {
+ "tags": ["agent-conversations"],
+ "summary": "Explicitly retry a failed message in the conversation's current session.",
+ "operationId": "retry_agent_conversation_turn",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "bot_id",
+ "in": "path",
+ "description": "Persona the conversation is with",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "source",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RetryAgentConversationTurnRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "Retry queued"
+ },
+ "404": {
+ "description": "Conversation or turn not found"
+ },
+ "409": {
+ "description": "Attempt cannot be retried"
+ },
+ "503": {
+ "description": "Temporarily unavailable"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/agent-models/load": {
"post": {
"tags": ["agent-models"],
@@ -845,6 +1007,16 @@
}
}
},
+ "409": {
+ "description": "The session answers an agent conversation",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -2483,6 +2655,143 @@
}
}
},
+ "AgentConversationDto": {
+ "type": "object",
+ "description": "An agent's conversation in a channel, as the person it is with sees it.",
+ "required": [
+ "channelId",
+ "botId",
+ "name",
+ "available",
+ "settingsChanged",
+ "sessions",
+ "turns"
+ ],
+ "properties": {
+ "available": {
+ "type": "boolean",
+ "description": "Whether the caller may currently send a new prompt."
+ },
+ "avatarUrl": {
+ "type": ["string", "null"],
+ "description": "Optional persona avatar."
+ },
+ "botId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Persona id (without the bot principal prefix)."
+ },
+ "channelId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The channel containing the visible transcript."
+ },
+ "name": {
+ "type": "string",
+ "description": "Persona's historical display name."
+ },
+ "sessions": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentConversationSessionDto"
+ },
+ "description": "The sessions the conversation has run on, oldest first."
+ },
+ "settingsChanged": {
+ "type": "boolean",
+ "description": "Whether new persona settings are available to adopt explicitly."
+ },
+ "turns": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentConversationTurnDto"
+ },
+ "description": "Persistent state of each accepted message and its current attempt."
+ }
+ }
+ },
+ "AgentConversationSessionDto": {
+ "type": "object",
+ "description": "One session a conversation has run on; every channel message stays visible.",
+ "required": ["sessionId", "createdAt", "isCurrent"],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the session began."
+ },
+ "isCurrent": {
+ "type": "boolean",
+ "description": "Whether this is the current agent context."
+ },
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Session whose controls and live events belong to this context."
+ }
+ }
+ },
+ "AgentConversationTurnDto": {
+ "type": "object",
+ "description": "Execution status without exposing the persona prompt or stored credentials.",
+ "required": [
+ "sourceMessageId",
+ "actionId",
+ "sessionId",
+ "state",
+ "retryable",
+ "createdAt"
+ ],
+ "properties": {
+ "actionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Current runtime attempt identity."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the source message was first accepted."
+ },
+ "replyMessageId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The associated agent reply, if it has been posted."
+ },
+ "retryable": {
+ "type": "boolean",
+ "description": "Whether Retry would be accepted now. A failed attempt is not retryable\nuntil its reply says how it ended."
+ },
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Session carrying this turn."
+ },
+ "sourceMessageId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The user's message in the channel timeline."
+ },
+ "state": {
+ "$ref": "#/components/schemas/ConversationTurnState",
+ "description": "Durable execution state."
+ }
+ }
+ },
+ "AgentConversationsDto": {
+ "type": "object",
+ "description": "The agent conversations in a channel the caller may see.",
+ "required": ["conversations"],
+ "properties": {
+ "conversations": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentConversationDto"
+ },
+ "description": "Empty for ordinary channels and other people's conversations."
+ }
+ }
+ },
"AgentModelDto": {
"type": "object",
"description": "One model picker option.",
@@ -3295,6 +3604,18 @@
"description": "What accepting a control operation did with it, on the wire.",
"enum": ["sent", "queued"]
},
+ "ConversationTurnState": {
+ "type": "string",
+ "description": "The state of one source message, retained after completion for deduplication.",
+ "enum": [
+ "queued",
+ "running",
+ "succeeded",
+ "failed",
+ "stopped",
+ "interrupted"
+ ]
+ },
"CreateAgentSessionRequest": {
"type": "object",
"description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose runtime this deployment provisions. A managed\nrequest may select an authorized persisted persona with `botId`; omitting\nit uses the deployment's default coding persona. Fields describing someone\nelse's runtime must still be omitted rather than quietly ignored. Mixing\nthe two shapes is refused rather than guessed at.\n\nClients serialize this, so both derives are used.",
@@ -3998,6 +4319,18 @@
}
}
},
+ "RetryAgentConversationTurnRequest": {
+ "type": "object",
+ "description": "The attempt the user saw and chose to retry; prevents double-click reruns.",
+ "required": ["actionId"],
+ "properties": {
+ "actionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Current failed attempt identity."
+ }
+ }
+ },
"SandboxSize": {
"type": "string",
"description": "Named compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.",
@@ -4186,6 +4519,18 @@
}
}
},
+ "StartFreshAgentConversationRequest": {
+ "type": "object",
+ "description": "The session the user is choosing to leave behind.",
+ "required": ["sessionId"],
+ "properties": {
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Current session id shown in the conversation metadata."
+ }
+ }
+ },
"StartResponse": {
"type": "object",
"description": "Public PKCE challenge and attempt handle; contains no verifier or provider tokens.",
diff --git a/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts b/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts
index be19318f9b..2f075c00fb 100644
--- a/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts
+++ b/apps/web/src/lib/service-clients/service-storage/channel-list-types.ts
@@ -4,6 +4,7 @@
// generated service-storage primitives. (Previously generated as `@service-comms`'s
// `ApiChannelWithLatest`; service-storage's generated `SoupChannel` nests these under
// `.channel` and is therefore not interchangeable.)
+import type { AgentDmProfile } from './generated/schemas/agentDmProfile';
import type { Channel } from './generated/schemas/channel';
import type { ChannelParticipant } from './generated/schemas/channelParticipant';
import type { LatestMessage } from './generated/schemas/latestMessage';
@@ -20,6 +21,7 @@ export type ChannelWithParticipants = Channel & {
/** A channel-list item: channel + participants + latest message + the viewer's read state. */
export type ApiChannelWithLatest = ChannelWithParticipants &
LatestMessage & {
+ agent_dm?: AgentDmProfile;
frecency_score?: number | null;
interacted_at?: string | null;
viewed_at?: string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentDmProfile.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentDmProfile.ts
new file mode 100644
index 0000000000..3197e41157
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentDmProfile.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentDmProfileAvatarUrl } from './agentDmProfileAvatarUrl';
+
+/**
+ * Historical persona identity displayed beside a private conversation.
+ */
+export interface AgentDmProfile {
+ /** Persona avatar, when supplied. */
+ avatar_url?: AgentDmProfileAvatarUrl;
+ /** Persona id without the bot principal prefix. */
+ bot_id: string;
+ /** Persona display name. */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentDmProfileAvatarUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentDmProfileAvatarUrl.ts
new file mode 100644
index 0000000000..1fcc228e36
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentDmProfileAvatarUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Persona avatar, when supplied.
+ */
+export type AgentDmProfileAvatarUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentTyping.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentTyping.ts
new file mode 100644
index 0000000000..85ca78870d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentTyping.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentTypingPhase } from './agentTypingPhase';
+
+/**
+ * An agent session typing through its bot.
+ */
+export interface AgentTyping {
+ /** What the agent is doing. Deliberately coarse: a typing event reaches
+everyone in the conversation, and which tool runs on what is for
+viewers who can read the session itself. */
+ phase: AgentTypingPhase;
+ /** The session whose turn the bot is speaking for. */
+ session_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentTypingPhase.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentTypingPhase.ts
new file mode 100644
index 0000000000..9dc0997892
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentTypingPhase.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * What a typing agent is doing.
+ */
+export type AgentTypingPhase =
+ (typeof AgentTypingPhase)[keyof typeof AgentTypingPhase];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentTypingPhase = {
+ thinking: 'thinking',
+ writing: 'writing',
+ working: 'working',
+ waiting: 'waiting',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatest.ts
index f04b063ea0..e74baa3979 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatest.ts
@@ -7,6 +7,7 @@
import type { ApiChannelListParticipant } from './apiChannelListParticipant';
import type { ApiChannelListType } from './apiChannelListType';
+import type { ApiChannelWithLatestAgentDm } from './apiChannelWithLatestAgentDm';
import type { ApiChannelWithLatestFrecencyScore } from './apiChannelWithLatestFrecencyScore';
import type { ApiChannelWithLatestInteractedAt } from './apiChannelWithLatestInteractedAt';
import type { ApiChannelWithLatestLatestMessage } from './apiChannelWithLatestLatestMessage';
@@ -20,6 +21,7 @@ import type { ApiChannelWithLatestViewedAt } from './apiChannelWithLatestViewedA
* Channel list response item.
*/
export interface ApiChannelWithLatest {
+ agent_dm?: ApiChannelWithLatestAgentDm;
/** Whether team members automatically join the channel. */
auto_join_team: boolean;
/** Channel type. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatestAgentDm.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatestAgentDm.ts
new file mode 100644
index 0000000000..1a9055d343
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelWithLatestAgentDm.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentDmProfile } from './agentDmProfile';
+
+export type ApiChannelWithLatestAgentDm = null | AgentDmProfile;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/getOrCreateDmRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/getOrCreateDmRequest.ts
index b777deb903..fe3f633c7f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/getOrCreateDmRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/getOrCreateDmRequest.ts
@@ -9,6 +9,6 @@
* Request to get or create a direct message channel.
*/
export interface GetOrCreateDmRequest {
- /** Recipient user id. */
+ /** Recipient user id (`macro|...`) or agent persona id (`bot|...`). */
recipient_id: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 76578c033d..01a9b2b5c4 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -22,6 +22,8 @@ export * from './agent';
export * from './agentActionId';
export * from './agentAutoAcceptPermissions';
export * from './agentChannelScope';
+export * from './agentDmProfile';
+export * from './agentDmProfileAvatarUrl';
export * from './agentHarnessId';
export * from './agentMcpServer';
export * from './agentMcpServers';
@@ -54,6 +56,8 @@ export * from './agentSessionLifecycleEventOneOfThree';
export * from './agentSessionLifecycleEventOneOfThreeEventType';
export * from './agentSessionLifecycleEventOneOfTwoone';
export * from './agentSessionLifecycleEventOneOfTwooneEventType';
+export * from './agentTyping';
+export * from './agentTypingPhase';
export * from './anchor';
export * from './anchorId';
export * from './anchorIdOneOf';
@@ -102,6 +106,7 @@ export * from './apiChannelListParticipantLeftAt';
export * from './apiChannelListType';
export * from './apiChannelParticipant';
export * from './apiChannelWithLatest';
+export * from './apiChannelWithLatestAgentDm';
export * from './apiChannelWithLatestFrecencyScore';
export * from './apiChannelWithLatestInteractedAt';
export * from './apiChannelWithLatestLatestMessage';
@@ -1196,6 +1201,7 @@ export * from './messageChangeOneOfFiveType';
export * from './messageChangeOneOfNine';
export * from './messageChangeOneOfNineType';
export * from './messageChangeOneOfOneone';
+export * from './messageChangeOneOfOneoneAgent';
export * from './messageChangeOneOfOneoneThreadId';
export * from './messageChangeOneOfOneoneType';
export * from './messageChangeOneOfSeven';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneone.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneone.ts
index 47cb9de631..f2b7ae8df6 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneone.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneone.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { MessageChangeOneOfOneoneAgent } from './messageChangeOneOfOneoneAgent';
import type { MessageChangeOneOfOneoneThreadId } from './messageChangeOneOfOneoneThreadId';
import type { MessageChangeOneOfOneoneType } from './messageChangeOneOfOneoneType';
@@ -13,6 +14,7 @@ import type { MessageChangeOneOfOneoneType } from './messageChangeOneOfOneoneTyp
export type MessageChangeOneOfOneone = {
/** Whether the user is currently typing. */
active: boolean;
+ agent?: MessageChangeOneOfOneoneAgent;
/** Root being replied to, or no root for the parent composer. */
thread_id?: MessageChangeOneOfOneoneThreadId;
type: MessageChangeOneOfOneoneType;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneoneAgent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneoneAgent.ts
new file mode 100644
index 0000000000..a73cca64b2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/messageChangeOneOfOneoneAgent.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentTyping } from './agentTyping';
+
+export type MessageChangeOneOfOneoneAgent = null | AgentTyping;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 3d38c3a1e9..6f5c5d2823 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -3330,7 +3330,11 @@ export const getAttachmentReferencesResponse = zod
*/
export const getOrCreateDmBody = zod
.object({
- recipient_id: zod.string().describe('Recipient user id.'),
+ recipient_id: zod
+ .string()
+ .describe(
+ 'Recipient user id (`macro|...`) or agent persona id (`bot|...`).'
+ ),
})
.describe('Request to get or create a direct message channel.');
@@ -3938,6 +3942,25 @@ export const getChannelsResponse = zod
.array(
zod
.object({
+ agent_dm: zod
+ .union([
+ zod.null(),
+ zod
+ .object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Persona avatar, when supplied.'),
+ bot_id: zod
+ .string()
+ .describe('Persona id without the bot principal prefix.'),
+ name: zod.string().describe('Persona display name.'),
+ })
+ .describe(
+ 'Historical persona identity displayed beside a private conversation.'
+ ),
+ ])
+ .optional(),
auto_join_team: zod
.boolean()
.describe('Whether team members automatically join the channel.'),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 63b50faa39..36a859f01b 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -18149,6 +18149,25 @@
"description": "Whether an agent is available everywhere or only in selected channels.",
"enum": ["all", "selected"]
},
+ "AgentDmProfile": {
+ "type": "object",
+ "description": "Historical persona identity displayed beside a private conversation.",
+ "required": ["bot_id", "name"],
+ "properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Persona avatar, when supplied."
+ },
+ "bot_id": {
+ "type": "string",
+ "description": "Persona id without the bot principal prefix."
+ },
+ "name": {
+ "type": "string",
+ "description": "Persona display name."
+ }
+ }
+ },
"AgentMcpServer": {
"type": "object",
"description": "One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.",
@@ -18397,6 +18416,27 @@
],
"description": "Events publishable to [`MacroAgentSessionLifecycleTopic`].\n\nThe serde tag and [`AgentSessionLifecycleEventName`] spell the same wire\nnames: subscribers filter on them, so they are API. The\n`event_names_match_the_wire` test holds the two in step. Exhaustive on\npurpose: a consumer's match should break when a variant is added."
},
+ "AgentTyping": {
+ "type": "object",
+ "description": "An agent session typing through its bot.",
+ "required": ["session_id", "phase"],
+ "properties": {
+ "phase": {
+ "$ref": "#/components/schemas/AgentTypingPhase",
+ "description": "What the agent is doing. Deliberately coarse: a typing event reaches\neveryone in the conversation, and which tool runs on what is for\nviewers who can read the session itself."
+ },
+ "session_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The session whose turn the bot is speaking for."
+ }
+ }
+ },
+ "AgentTypingPhase": {
+ "type": "string",
+ "description": "What a typing agent is doing.",
+ "enum": ["thinking", "writing", "working", "waiting"]
+ },
"Anchor": {
"oneOf": [
{
@@ -18958,6 +18998,17 @@
"is_participant"
],
"properties": {
+ "agent_dm": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AgentDmProfile",
+ "description": "Persona identity when this is the viewer's private agent DM."
+ }
+ ]
+ },
"auto_join_team": {
"type": "boolean",
"description": "Whether team members automatically join the channel."
@@ -29193,7 +29244,7 @@
"properties": {
"recipient_id": {
"type": "string",
- "description": "Recipient user id."
+ "description": "Recipient user id (`macro|...`) or agent persona id (`bot|...`)."
}
}
},
@@ -31679,6 +31730,17 @@
"type": "boolean",
"description": "Whether the user is currently typing."
},
+ "agent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AgentTyping",
+ "description": "Present when an agent session is typing through the bot that\nspeaks for it. Names the session, so a viewer who can read it can\nshow the turn live in place of the bare indicator."
+ }
+ ]
+ },
"thread_id": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index 6334db88a9..c1bd6388f9 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -32,6 +32,8 @@ anyhow = { workspace = true }
axum = { workspace = true, features = ["ws"] }
base64 = { workspace = true }
bot_id = { path = "../bot_id" }
+bots = { path = "../bots", default-features = false, features = ["ports"] }
+channels = { path = "../channels", default-features = false, features = ["ports"] }
trigger_context = { path = "../trigger_context" }
harness_id = { path = "../harness_id" }
channel_sender = { path = "../channel_sender" }
@@ -88,7 +90,11 @@ utoipa = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-channels = { path = "../channels", default-features = false }
+entity_registry = { path = "../entity_registry/entity_registry" }
+entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils" }
+macro_db_migrator = { path = "../macro_db_migrator" }
+bots = { path = "../bots", default-features = false, features = ["test-utils"] }
+channels = { path = "../channels", default-features = false, features = ["outbound"] }
messages = { path = "../messages", features = ["test-utils"] }
uuid = { workspace = true }
agent_fold = { path = "../folds/agent_fold", features = ["test-utils"] }
diff --git a/crates/agent_harness/src/domain/claude/test.rs b/crates/agent_harness/src/domain/claude/test.rs
index a874c49e54..4eaafa22fc 100644
--- a/crates/agent_harness/src/domain/claude/test.rs
+++ b/crates/agent_harness/src/domain/claude/test.rs
@@ -150,7 +150,7 @@ async fn seed(
) -> AgentSessionId {
let id = AgentSessionId::new();
repo.create(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
bot_id: bot,
diff --git a/crates/agent_harness/src/domain/conversation_turns.rs b/crates/agent_harness/src/domain/conversation_turns.rs
new file mode 100644
index 0000000000..d24e788226
--- /dev/null
+++ b/crates/agent_harness/src/domain/conversation_turns.rs
@@ -0,0 +1,202 @@
+//! Durable admission and execution records for the channel messages an agent
+//! answers in its conversation.
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use agent_session::domain::{error::Result, model::AgentSessionId};
+use bot_id::BotId;
+use macro_uuid::Uuid;
+
+use super::{
+ model::{AgentRuntimeConfig, OpenSession, PermissionPolicyConfig, ReplyOutcome},
+ queue::InFlightTurn,
+};
+
+/// The state of one source message, retained after completion for deduplication.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum ConversationTurnState {
+ /// Accepted durably; no model request has been dispatched.
+ Queued,
+ /// Claimed for dispatch; it may have performed external actions.
+ Running,
+ /// The turn finished successfully.
+ Succeeded,
+ /// The turn failed; retry requires the user's explicit action.
+ Failed,
+ /// The user stopped the turn.
+ Stopped,
+ /// The managing process disappeared; never automatically repeat its work.
+ Interrupted,
+}
+
+/// Original command and the outcome of its current attempt.
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct ConversationTurn {
+ /// Immutable source identity, even when a broker replays after a context reset.
+ pub source_message_id: Uuid,
+ /// Persona answering the message. Each agent in a channel keeps its own turn.
+ pub bot_id: BotId,
+ /// The session chosen on first admission.
+ pub session_id: AgentSessionId,
+ /// Channel containing this turn.
+ pub channel_id: Uuid,
+ /// Runtime request identity. Explicit retry mints a fresh one.
+ pub action_id: AgentActionId,
+ /// Original persona configuration, prompt, attachments and owner.
+ pub command: OpenSession,
+ /// Durable execution state.
+ pub state: ConversationTurnState,
+ /// Reply placement and runtime turn identity, recorded before delivery.
+ pub in_flight: Option<InFlightTurn>,
+ /// Outcome saved before patching the channel reply.
+ pub outcome: Option<ReplyOutcome>,
+ /// Whether the channel reply has been reconciled with the saved outcome.
+ pub reply_finalized: bool,
+ /// What the reply shows, saved by the replica that watched the turn
+ /// before it showed any of it, and once more, finished, before its
+ /// outcome.
+ #[serde(default)]
+ pub reply_segments: Option<Vec<agent_fold::domain::model::ProjectedSegment>>,
+ /// Stable admission order within the transcript.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// Small transcript projection. Polling must never reload stored prompts or attachments.
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct ConversationTurnStatus {
+ /// Source channel message.
+ pub source_message_id: Uuid,
+ /// Persona answering the message.
+ pub bot_id: BotId,
+ /// Session that accepted this message.
+ pub session_id: AgentSessionId,
+ /// Current attempt identity.
+ pub action_id: AgentActionId,
+ /// Reply in the channel timeline, when one was reserved.
+ pub reply_message_id: Option<Uuid>,
+ /// Current execution state.
+ pub state: ConversationTurnState,
+ /// Whether an explicit retry would be accepted now: the attempt failed,
+ /// stopped or was interrupted, and its reply already says so.
+ pub retryable: bool,
+ /// Stable admission ordering.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+}
+
+/// Persistence mechanics only; authorization and execution decisions stay in the harness.
+/// A held reply reconciliation claim. Dropping it releases the claim, including
+/// on cancellation; no external action is retried by acquiring this lease.
+pub trait ConversationLease: Send {}
+
+/// The persona configuration adopted when a conversation's session first opens.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+pub struct ConversationSettings {
+ /// Instructions, model, runtime and selected tools for this context.
+ pub runtime: AgentRuntimeConfig,
+ /// Persona permission choice at adoption time. The operator may still revoke bypass.
+ pub permissions: PermissionPolicyConfig,
+}
+
+/// Persistence mechanics only; authorization and execution decisions stay in the harness.
+#[async_trait::async_trait]
+pub trait ConversationTurnStore: Send + Sync + 'static {
+ /// Serialize a session's bootstrap, before it has a manager to route to.
+ /// Waits briefly for capacity; `None` means another holder has the session,
+ /// or this replica had no connection to spare.
+ async fn claim_delivery(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Option<Box<dyn ConversationLease>>>;
+ /// Serialize context changes with runtime dispatch across replicas.
+ /// Waits briefly for capacity; `None` means another holder has the session,
+ /// or this replica had no connection to spare.
+ async fn claim_context(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Option<Box<dyn ConversationLease>>>;
+ /// Cancel work that has not dispatched when its owner starts fresh.
+ async fn cancel_queued(&self, session: AgentSessionId) -> Result<()>;
+ /// Read the settings adopted by this session, if it has opened.
+ async fn settings(&self, session: AgentSessionId) -> Result<Option<ConversationSettings>>;
+ /// First writer wins, including a crash before the runtime row was created.
+ async fn pin_settings(
+ &self,
+ session: AgentSessionId,
+ settings: ConversationSettings,
+ ) -> Result<ConversationSettings>;
+ /// Atomically insert or return the first admission of the message for the
+ /// command's persona, never replacing its payload. The first admission
+ /// mints the turn's action id.
+ async fn admit(
+ &self,
+ session: AgentSessionId,
+ channel: Uuid,
+ command: OpenSession,
+ ) -> Result<ConversationTurn>;
+ /// Read a source message's durable admission for one persona.
+ async fn get(&self, source: Uuid, bot: BotId) -> Result<Option<ConversationTurn>>;
+ /// Resolve the current runtime attempt without assuming its id is the source id.
+ async fn by_action(&self, action: AgentActionId) -> Result<Option<ConversationTurn>>;
+ /// Compare-and-swap an explicitly retried failed attempt to a fresh action id.
+ async fn retry(&self, source: Uuid, bot: BotId, expected: AgentActionId) -> Result<bool>;
+ /// At most one replica can move a queued attempt onto a runtime.
+ async fn claim(&self, action: AgentActionId, turn: &InFlightTurn) -> Result<bool>;
+ /// Save the posted reply before the model can begin producing output.
+ async fn record_flight(&self, action: AgentActionId, turn: &InFlightTurn) -> Result<()>;
+ /// Reserve final reply IDs under a reply lease. Returns false if the
+ /// attempt is no longer terminal and unfinalized, or its saved flight
+ /// changed since it was read. No message may be posted on a failed write.
+ async fn record_reply_flight(
+ &self,
+ action: AgentActionId,
+ expected: &InFlightTurn,
+ turn: &InFlightTurn,
+ ) -> Result<bool>;
+ /// Save what a turn's reply shows: as its messages are posted, and
+ /// finished, before its outcome. Whichever replica reconciles the reply
+ /// then posts the same messages, and closes the ones already posted.
+ async fn save_reply(
+ &self,
+ action: AgentActionId,
+ segments: &[agent_fold::domain::model::ProjectedSegment],
+ ) -> Result<()>;
+ /// Save a terminal outcome before resolving the channel message.
+ async fn finish(
+ &self,
+ action: AgentActionId,
+ state: ConversationTurnState,
+ outcome: ReplyOutcome,
+ ) -> Result<()>;
+ /// Fail an attempt that never dispatched. An attempt some replica has
+ /// claimed meanwhile is left to that replica.
+ async fn fail_queued(&self, action: AgentActionId) -> Result<()>;
+ /// Mark the saved outcome as visible in the channel.
+ async fn finalize_reply(&self, action: AgentActionId, outcome: &ReplyOutcome) -> Result<()>;
+ /// Serialize reply reconciliation across replicas, with release on process loss.
+ /// Waits briefly for capacity; `None` means another holder is reconciling
+ /// the reply, or this replica had no connection to spare.
+ async fn claim_reply(
+ &self,
+ action: AgentActionId,
+ ) -> Result<Option<Box<dyn ConversationLease>>>;
+ /// Durable queued work for recovery, in admission order: the oldest
+ /// queued turn of each session that nothing runs or blocks, which is
+ /// exactly what a claim could take.
+ async fn pending(&self, limit: u16) -> Result<Vec<ConversationTurn>>;
+ /// Claims whose session manager must still be alive; used only for recovery checks.
+ async fn running(&self, limit: u16) -> Result<Vec<ConversationTurn>>;
+ /// Read the statuses of the turns one persona's conversation in a channel
+ /// shows, oldest first, after the caller's access to it was checked:
+ /// every turn still queued or running, each session's first turn, and
+ /// the latest `recent` turns.
+ async fn for_conversation(
+ &self,
+ channel: Uuid,
+ bot: BotId,
+ recent: u16,
+ ) -> Result<Vec<ConversationTurnStatus>>;
+ /// Completed outcomes whose reply patch must be retried, without running a model.
+ async fn pending_replies(&self, limit: u16) -> Result<Vec<ConversationTurn>>;
+}
diff --git a/crates/agent_harness/src/domain/conversations.rs b/crates/agent_harness/src/domain/conversations.rs
new file mode 100644
index 0000000000..5202af9b4f
--- /dev/null
+++ b/crates/agent_harness/src/domain/conversations.rs
@@ -0,0 +1,475 @@
+//! An agent's conversation in a channel: the channel holds the transcript,
+//! and the conversation's sessions hold the agent's context.
+
+use agent_session::domain::agent_conversation::{
+ AgentConversation, AgentConversationRepo, ConversationSession,
+};
+use agent_session::domain::{
+ error::{AgentSessionError, Result as SessionResult},
+ model::AgentSessionId,
+};
+use bot_id::BotId;
+use bots::domain::{
+ models::BotProfile,
+ ports::{AgentDmEligibility, BotError, BotRepo},
+};
+use channels::domain::channel_agents::{ChannelAgent, ChannelAgentKind, ChannelAgentRepo};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+/// Runtime policy for agent conversations, rechecked when a queued prompt
+/// dispatches.
+#[async_trait::async_trait]
+pub trait ConversationPolicy: Send + Sync + 'static {
+ /// The current session of an already validated conversation, for new admissions.
+ async fn current_context(&self, session_id: AgentSessionId) -> SessionResult<AgentSessionId>;
+ /// Validate who may prompt the conversation, for durable admission. Current
+ /// persona eligibility is checked at execution, so revoked work can be
+ /// recorded as failed instead of becoming an unacknowledgeable broker event.
+ async fn validate_binding(
+ &self,
+ session_id: AgentSessionId,
+ bot_id: BotId,
+ actor: Option<&MacroUserIdStr<'static>>,
+ ) -> SessionResult<bool>;
+ /// Recheck the prompter and the persona, including team access changes.
+ /// Returns false when this session belongs to no conversation.
+ async fn authorize_prompt(
+ &self,
+ session_id: AgentSessionId,
+ bot_id: BotId,
+ actor: Option<&MacroUserIdStr<'static>>,
+ ) -> SessionResult<bool>;
+ /// Immutable conversation provenance, used to choose notification behavior.
+ async fn is_conversation_session(&self, session_id: AgentSessionId) -> SessionResult<bool>;
+}
+
+#[cfg(test)]
+mod test;
+
+/// How many of its latest turns a conversation reports beside the ones still
+/// waiting or running and the first of each session. The transcript is read
+/// from its end, and a poll that reported every turn would grow with the
+/// conversation's history.
+const RECENT_TURNS: u16 = 100;
+
+/// A conversation as the person it is with sees it.
+pub struct ConversationOverview {
+ /// Channel containing the visible transcript.
+ pub channel_id: Uuid,
+ /// Historical persona identity, retained after deletion.
+ pub persona: BotProfile,
+ /// Whether the caller may still prompt this persona.
+ pub available: bool,
+ /// The persona has edits that a new session would adopt.
+ pub settings_changed: bool,
+ /// The sessions the conversation has run on, oldest first.
+ pub sessions: Vec<ConversationSession>,
+ /// Durable execution status of the messages the persona answered that
+ /// the conversation shows: what still waits or runs, each session's
+ /// first message, and the latest ones.
+ pub turns: Vec<super::conversation_turns::ConversationTurnStatus>,
+}
+
+/// Metadata lookup failures. Someone else's conversation is concealed as not found.
+#[derive(Debug, thiserror::Error)]
+pub enum ConversationError {
+ /// No conversation the caller may see is at this id.
+ #[error("conversation not found")]
+ NotFound,
+ /// This attempt cannot be retried in the current conversation state.
+ #[error("this message cannot be retried now")]
+ NotRetryable,
+ /// A stale reset request or a running turn prevents changing context.
+ #[error("stop the current turn before starting fresh")]
+ ContextBusy,
+ /// An owning domain could not read its durable state.
+ #[error("could not load the conversation")]
+ Unavailable(#[source] anyhow::Error),
+}
+
+/// Queries and controls for the person a conversation is with.
+pub trait AgentConversations: Send + Sync + 'static {
+ /// Adopt current persona settings in a new session while keeping history.
+ /// The expected session makes double submissions and stale tabs safe.
+ fn start_fresh(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ conversation: AgentConversation,
+ expected: AgentSessionId,
+ ) -> impl Future<Output = Result<(), ConversationError>> + Send;
+ /// The conversations in a channel the caller may see, without starting a
+ /// session or requiring current persona eligibility. Ordinary channels and
+ /// other people's conversations have none.
+ fn list(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ConversationOverview>, ConversationError>> + Send;
+ /// Explicitly retry a failed attempt in the current session under current access.
+ fn retry(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ conversation: AgentConversation,
+ source: Uuid,
+ expected: agent_runtime_protocol::domain::action::AgentActionId,
+ ) -> impl Future<Output = Result<(), ConversationError>> + Send;
+}
+
+/// Coordinates the channel, persona, and session domain ports.
+pub struct AgentConversationsService<C, P, B, S> {
+ channels: C,
+ eligibility: P,
+ bots: B,
+ sessions: S,
+ turns: Option<std::sync::Arc<dyn super::conversation_turns::ConversationTurnStore>>,
+}
+
+impl<C, P, B, S> AgentConversationsService<C, P, B, S> {
+ /// Compose owning-domain capabilities; this service owns the read policy.
+ pub fn new(channels: C, eligibility: P, bots: B, sessions: S) -> Self {
+ Self {
+ channels,
+ eligibility,
+ bots,
+ sessions,
+ turns: None,
+ }
+ }
+
+ /// Include durable turn status in the conversation overview.
+ pub fn with_turns(
+ mut self,
+ turns: std::sync::Arc<dyn super::conversation_turns::ConversationTurnStore>,
+ ) -> Self {
+ self.turns = Some(turns);
+ self
+ }
+}
+
+/// Whether `caller` is the person a conversation is with. Only a direct
+/// conversation has one today; a member of a shared channel has no rule yet,
+/// so nobody may prompt it or see its controls.
+fn is_with(agent: &ChannelAgent, caller: &MacroUserIdStr<'static>) -> bool {
+ match &agent.kind {
+ ChannelAgentKind::Direct { user_id } => user_id == caller,
+ ChannelAgentKind::Member => false,
+ }
+}
+
+#[async_trait::async_trait]
+impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversationRepo>
+ ConversationPolicy for AgentConversationsService<C, P, B, S>
+{
+ async fn current_context(&self, session_id: AgentSessionId) -> SessionResult<AgentSessionId> {
+ let conversation = self
+ .sessions
+ .conversation_for_session(session_id)
+ .await?
+ .ok_or(AgentSessionError::Forbidden)?;
+ self.sessions
+ .current(conversation)
+ .await?
+ .ok_or(AgentSessionError::Forbidden)
+ }
+
+ async fn validate_binding(
+ &self,
+ session_id: AgentSessionId,
+ bot_id: BotId,
+ actor: Option<&MacroUserIdStr<'static>>,
+ ) -> SessionResult<bool> {
+ let Some(conversation) = self.sessions.conversation_for_session(session_id).await? else {
+ return Ok(false);
+ };
+ if conversation.bot_id != bot_id {
+ return Err(AgentSessionError::Forbidden);
+ }
+ let agent = self
+ .channels
+ .find(conversation.channel_id, conversation.bot_id)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(AgentSessionError::Forbidden)?;
+ match actor {
+ Some(actor) if is_with(&agent, actor) => Ok(true),
+ _ => Err(AgentSessionError::Forbidden),
+ }
+ }
+
+ async fn authorize_prompt(
+ &self,
+ session_id: AgentSessionId,
+ bot_id: BotId,
+ actor: Option<&MacroUserIdStr<'static>>,
+ ) -> SessionResult<bool> {
+ if !self.validate_binding(session_id, bot_id, actor).await? {
+ return Ok(false);
+ }
+ let conversation = self
+ .sessions
+ .conversation_for_session(session_id)
+ .await?
+ .ok_or(AgentSessionError::Forbidden)?;
+ if self.sessions.current(conversation).await? != Some(session_id) {
+ return Err(AgentSessionError::Forbidden);
+ }
+ match self
+ .eligibility
+ .authorize_agent_dm(actor.cloned().ok_or(AgentSessionError::Forbidden)?, bot_id)
+ .await
+ {
+ Ok(()) => Ok(true),
+ Err(BotError::Unauthorized | BotError::NotFound(_)) => {
+ Err(AgentSessionError::Forbidden)
+ }
+ Err(error) => Err(AgentSessionError::Unknown(error.into())),
+ }
+ }
+
+ async fn is_conversation_session(&self, session_id: AgentSessionId) -> SessionResult<bool> {
+ Ok(self
+ .sessions
+ .conversation_for_session(session_id)
+ .await?
+ .is_some())
+ }
+}
+
+impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversationRepo>
+ AgentConversationsService<C, P, B, S>
+{
+ /// The agent of a conversation the caller is part of. Team ownership of a
+ /// persona never grants access to someone else's conversation.
+ async fn joined(
+ &self,
+ caller: &MacroUserIdStr<'static>,
+ conversation: AgentConversation,
+ ) -> Result<ChannelAgent, ConversationError> {
+ self.channels
+ .find(conversation.channel_id, conversation.bot_id)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ .filter(|agent| is_with(agent, caller))
+ .ok_or(ConversationError::NotFound)
+ }
+
+ async fn overview(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ agent: ChannelAgent,
+ ) -> Result<ConversationOverview, ConversationError> {
+ let conversation = AgentConversation {
+ channel_id: agent.channel_id,
+ bot_id: agent.bot_id,
+ };
+ let available = match self
+ .eligibility
+ .authorize_agent_dm(caller, agent.bot_id)
+ .await
+ {
+ Ok(()) => true,
+ Err(BotError::Unauthorized | BotError::NotFound(_)) => false,
+ Err(error) => return Err(ConversationError::Unavailable(error.into())),
+ };
+ let persona = self
+ .bots
+ .get_bot_profiles(&[agent.bot_id])
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ .remove(&agent.bot_id)
+ .unwrap_or(BotProfile {
+ id: agent.bot_id,
+ name: "Unavailable agent".to_owned(),
+ avatar_url: None,
+ });
+ let sessions = self
+ .sessions
+ .sessions(conversation)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?;
+ let mut settings_changed = false;
+ if available
+ && let Some(current) = sessions.iter().find(|session| session.is_current)
+ && let Some(store) = &self.turns
+ && let Some(settings) = store
+ .settings(current.session_id)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ && let Some(persona_agent) = self
+ .bots
+ .get_agent(agent.bot_id)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ {
+ let runtime = settings.runtime;
+ let permissions_changed = match settings.permissions {
+ super::model::PermissionPolicyConfig::Persona {
+ auto_accept_permissions,
+ ..
+ } => auto_accept_permissions != persona_agent.auto_accept_permissions,
+ _ => false,
+ };
+ settings_changed = runtime.instructions != persona_agent.instructions
+ || runtime.model != persona_agent.default_model
+ || runtime.harness != persona_agent.harness
+ || runtime.mcp_servers != persona_agent.mcp
+ || permissions_changed;
+ }
+ Ok(ConversationOverview {
+ channel_id: agent.channel_id,
+ persona,
+ available,
+ settings_changed,
+ sessions,
+ turns: match &self.turns {
+ Some(turns) => turns
+ .for_conversation(agent.channel_id, agent.bot_id, RECENT_TURNS)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?,
+ None => Vec::new(),
+ },
+ })
+ }
+}
+
+impl<C: ChannelAgentRepo, P: AgentDmEligibility, B: BotRepo, S: AgentConversationRepo>
+ AgentConversations for AgentConversationsService<C, P, B, S>
+{
+ async fn start_fresh(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ conversation: AgentConversation,
+ expected: AgentSessionId,
+ ) -> Result<(), ConversationError> {
+ let agent = self.joined(&caller, conversation).await?;
+ self.eligibility
+ .authorize_agent_dm(caller, agent.bot_id)
+ .await
+ .map_err(|error| match error {
+ BotError::Unauthorized | BotError::NotFound(_) => ConversationError::NotRetryable,
+ error => ConversationError::Unavailable(error.into()),
+ })?;
+ let store = self.turns.as_ref().ok_or(ConversationError::ContextBusy)?;
+ let _lease = store
+ .claim_context(expected)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ .ok_or(ConversationError::ContextBusy)?;
+ if self
+ .sessions
+ .current(conversation)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ != Some(expected)
+ {
+ return Err(ConversationError::ContextBusy);
+ }
+ let turns = store
+ .for_conversation(conversation.channel_id, conversation.bot_id, RECENT_TURNS)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?;
+ if turns.iter().any(|turn| {
+ turn.session_id == expected
+ && turn.state == super::conversation_turns::ConversationTurnState::Running
+ }) {
+ return Err(ConversationError::ContextBusy);
+ }
+ self.sessions
+ .start_fresh(conversation)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?;
+ // Dispatch uses the same lease; no queued action can cross this boundary.
+ // If cancellation fails, dispatch authorization still rejects the old session.
+ store
+ .cancel_queued(expected)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?;
+ tracing::info!(
+ channel_id = %conversation.channel_id,
+ bot_id = %conversation.bot_id,
+ previous_session = %expected,
+ "agent conversation context reset"
+ );
+ Ok(())
+ }
+
+ async fn retry(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ conversation: AgentConversation,
+ source: Uuid,
+ expected: agent_runtime_protocol::domain::action::AgentActionId,
+ ) -> Result<(), ConversationError> {
+ let agent = self.joined(&caller, conversation).await?;
+ match self
+ .eligibility
+ .authorize_agent_dm(caller, agent.bot_id)
+ .await
+ {
+ Ok(()) => {}
+ Err(BotError::Unauthorized | BotError::NotFound(_)) => {
+ return Err(ConversationError::NotRetryable);
+ }
+ Err(error) => return Err(ConversationError::Unavailable(error.into())),
+ }
+ let store = self.turns.as_ref().ok_or(ConversationError::NotRetryable)?;
+ // Read on its own rather than from the overview, which reports only
+ // the turns the conversation shows: an older failure still retries.
+ let record = store
+ .get(source, conversation.bot_id)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ .filter(|record| record.channel_id == conversation.channel_id)
+ .ok_or(ConversationError::NotFound)?;
+ let current = self
+ .sessions
+ .current(conversation)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?;
+ if Some(record.session_id) != current || record.action_id != expected {
+ return Err(ConversationError::NotRetryable);
+ }
+ let _lease = store
+ .claim_context(record.session_id)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ .ok_or(ConversationError::NotRetryable)?;
+ if self
+ .sessions
+ .current(conversation)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ != Some(record.session_id)
+ {
+ return Err(ConversationError::NotRetryable);
+ }
+ if !store
+ .retry(source, conversation.bot_id, expected)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?
+ {
+ return Err(ConversationError::NotRetryable);
+ }
+ Ok(())
+ }
+
+ async fn list(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ ) -> Result<Vec<ConversationOverview>, ConversationError> {
+ let agents = self
+ .channels
+ .agents_in(channel_id)
+ .await
+ .map_err(|error| ConversationError::Unavailable(error.into()))?;
+ let mut overviews = Vec::new();
+ // Check membership before loading profiles, eligibility, or session
+ // identities, so someone else's conversation reveals nothing.
+ for agent in agents.into_iter().filter(|agent| is_with(agent, &caller)) {
+ overviews.push(self.overview(caller.clone(), agent).await?);
+ }
+ Ok(overviews)
+ }
+}
diff --git a/crates/agent_harness/src/domain/conversations/test.rs b/crates/agent_harness/src/domain/conversations/test.rs
new file mode 100644
index 0000000000..956c9b974b
--- /dev/null
+++ b/crates/agent_harness/src/domain/conversations/test.rs
@@ -0,0 +1,245 @@
+use super::*;
+use agent_session::domain::{error::Result as SessionResult, model::AgentSessionId};
+use bot_id::BotId;
+use bots::domain::ports::MockBotRepo;
+use channels::domain::ports::ChannelMutationErr;
+use std::{
+ collections::HashMap,
+ sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+ },
+};
+
+struct Channels(Vec<ChannelAgent>);
+impl ChannelAgentRepo for Channels {
+ async fn agents_in(&self, channel_id: Uuid) -> Result<Vec<ChannelAgent>, ChannelMutationErr> {
+ Ok(self
+ .0
+ .iter()
+ .filter(|agent| agent.channel_id == channel_id)
+ .cloned()
+ .collect())
+ }
+ async fn find(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<Option<ChannelAgent>, ChannelMutationErr> {
+ Ok(self
+ .0
+ .iter()
+ .find(|agent| agent.channel_id == channel_id && agent.bot_id == bot_id)
+ .cloned())
+ }
+}
+
+struct Eligibility {
+ available: bool,
+ calls: Arc<AtomicUsize>,
+}
+impl AgentDmEligibility for Eligibility {
+ async fn authorize_agent_dm(
+ &self,
+ _: MacroUserIdStr<'static>,
+ _: BotId,
+ ) -> Result<(), BotError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ if self.available {
+ Ok(())
+ } else {
+ Err(BotError::Unauthorized)
+ }
+ }
+}
+
+struct Sessions;
+impl AgentConversationRepo for Sessions {
+ async fn current_or_create(&self, _: AgentConversation) -> SessionResult<AgentSessionId> {
+ panic!("read allocates no runtime")
+ }
+ async fn current(&self, _: AgentConversation) -> SessionResult<Option<AgentSessionId>> {
+ Ok(Some(AgentSessionId::TEST_A))
+ }
+ async fn start_fresh(&self, _: AgentConversation) -> SessionResult<AgentSessionId> {
+ panic!("read does not reset")
+ }
+ async fn conversation_for_session(
+ &self,
+ _: AgentSessionId,
+ ) -> SessionResult<Option<AgentConversation>> {
+ Ok(Some(AgentConversation {
+ channel_id: channel(),
+ bot_id: BotId::TEST_A,
+ }))
+ }
+ async fn sessions(&self, _: AgentConversation) -> SessionResult<Vec<ConversationSession>> {
+ Ok(vec![session()])
+ }
+}
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+fn channel() -> Uuid {
+ Uuid::from_u128(1)
+}
+fn direct() -> ChannelAgent {
+ ChannelAgent {
+ channel_id: channel(),
+ bot_id: BotId::TEST_A,
+ kind: ChannelAgentKind::Direct { user_id: owner() },
+ }
+}
+fn session() -> ConversationSession {
+ ConversationSession {
+ session_id: AgentSessionId::TEST_A,
+ created_at: chrono::DateTime::from_timestamp(1, 0).unwrap(),
+ is_current: true,
+ }
+}
+
+#[tokio::test]
+async fn a_teammate_cannot_read_the_personas_conversation_with_its_owner() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let service = AgentConversationsService::new(
+ Channels(vec![direct()]),
+ Eligibility {
+ available: true,
+ calls: calls.clone(),
+ },
+ MockBotRepo::new(),
+ Sessions,
+ );
+ let teammate = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ assert!(
+ service
+ .list(teammate.clone(), channel())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ let conversation = AgentConversation {
+ channel_id: channel(),
+ bot_id: BotId::TEST_A,
+ };
+ assert!(matches!(
+ service
+ .start_fresh(teammate, conversation, AgentSessionId::TEST_A)
+ .await,
+ Err(ConversationError::NotFound)
+ ));
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn revoked_personas_keep_their_history_and_profile_but_cannot_be_prompted() {
+ let mut bots = MockBotRepo::new();
+ bots.expect_get_bot_profiles()
+ .withf(|ids| ids == [BotId::TEST_A])
+ .times(1)
+ .returning(|_| {
+ Box::pin(async {
+ Ok(HashMap::from([(
+ BotId::TEST_A,
+ BotProfile {
+ id: BotId::TEST_A,
+ name: "Researcher".to_owned(),
+ avatar_url: Some("avatar.png".to_owned()),
+ },
+ )]))
+ })
+ });
+ let service = AgentConversationsService::new(
+ Channels(vec![direct()]),
+ Eligibility {
+ available: false,
+ calls: Default::default(),
+ },
+ bots,
+ Sessions,
+ );
+ let [overview] = service
+ .list(owner(), channel())
+ .await
+ .unwrap()
+ .try_into()
+ .unwrap_or_else(|_| panic!("expected the owner's one conversation"));
+ assert!(!overview.available);
+ assert_eq!(overview.persona.name, "Researcher");
+ assert_eq!(overview.sessions, vec![session()]);
+}
+
+#[tokio::test]
+async fn ordinary_channels_have_no_agent_conversation() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let service = AgentConversationsService::new(
+ Channels(Vec::new()),
+ Eligibility {
+ available: true,
+ calls: calls.clone(),
+ },
+ MockBotRepo::new(),
+ Sessions,
+ );
+ assert!(service.list(owner(), channel()).await.unwrap().is_empty());
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn a_shared_channel_member_has_no_controls_and_takes_no_prompts_yet() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let service = AgentConversationsService::new(
+ Channels(vec![ChannelAgent {
+ kind: ChannelAgentKind::Member,
+ ..direct()
+ }]),
+ Eligibility {
+ available: true,
+ calls: calls.clone(),
+ },
+ MockBotRepo::new(),
+ Sessions,
+ );
+ assert!(service.list(owner(), channel()).await.unwrap().is_empty());
+ let prompt = service
+ .authorize_prompt(AgentSessionId::TEST_A, BotId::TEST_A, Some(&owner()))
+ .await;
+ assert!(matches!(prompt, Err(AgentSessionError::Forbidden)));
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn dispatch_rechecks_persona_access_and_the_exact_owner() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let service = AgentConversationsService::new(
+ Channels(vec![direct()]),
+ Eligibility {
+ available: false,
+ calls: calls.clone(),
+ },
+ MockBotRepo::new(),
+ Sessions,
+ );
+ let teammate = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let wrong_actor = service
+ .authorize_prompt(AgentSessionId::TEST_A, BotId::TEST_A, Some(&teammate))
+ .await;
+ assert!(matches!(wrong_actor, Err(AgentSessionError::Forbidden)));
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ let wrong_persona = service
+ .authorize_prompt(AgentSessionId::TEST_A, BotId::TEST_B, Some(&owner()))
+ .await;
+ assert!(matches!(wrong_persona, Err(AgentSessionError::Forbidden)));
+ let revoked = service
+ .authorize_prompt(AgentSessionId::TEST_A, BotId::TEST_A, Some(&owner()))
+ .await;
+ assert!(matches!(revoked, Err(AgentSessionError::Forbidden)));
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert!(
+ service
+ .is_conversation_session(AgentSessionId::TEST_A)
+ .await
+ .unwrap()
+ );
+}
diff --git a/crates/agent_harness/src/domain/error.rs b/crates/agent_harness/src/domain/error.rs
index 0013ca981c..120cf3db45 100644
--- a/crates/agent_harness/src/domain/error.rs
+++ b/crates/agent_harness/src/domain/error.rs
@@ -63,6 +63,11 @@ pub enum HarnessError {
/// Required context for a channel-originated prompt could not be loaded.
#[error("failed to load channel prompt context: {0}")]
PromptContext(rootcause::Report),
+ /// The message a prompt answers is gone, was moved, or is no longer one
+ /// its sender may write beside. Unlike [`Self::PromptContext`], asking
+ /// again cannot succeed.
+ #[error("the message an agent prompt answers is no longer valid: {0}")]
+ InvalidOrigin(rootcause::Report),
/// A prompt could not be composed for the agent runtime.
#[error("failed to compose agent prompt: {0}")]
PromptComposition(rootcause::Report),
diff --git a/crates/agent_harness/src/domain/mod.rs b/crates/agent_harness/src/domain/mod.rs
index 3734e4ffd1..11adf610a8 100644
--- a/crates/agent_harness/src/domain/mod.rs
+++ b/crates/agent_harness/src/domain/mod.rs
@@ -1,5 +1,8 @@
/// Fresh ACP capability discovery without creating an agent session.
pub mod capability_discovery;
+pub mod conversation_turns;
+/// Agent conversations in channels: who may prompt them, and their sessions.
+pub mod conversations;
pub mod error;
pub mod model;
/// Which lifecycle facts become notifications for people, and for whom.
@@ -8,6 +11,8 @@ pub mod notifications;
/// consulted by container managers' idle reapers.
pub mod pending;
pub mod ports;
+/// Which channel messages an agent's reply is shown through.
+pub mod presenter;
/// The per-session queue of turn-occupying actions awaiting their turn.
pub mod queue;
/// Compute resources for a sandbox size.
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 57f681af0f..ee1e79b6ef 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -289,6 +289,7 @@ pub struct ReplyPersona {
}
/// Stored facts used by the domain to choose a session permission policy.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PermissionPolicyConfig {
/// A fixed system bot with no editable persona configuration.
Fixed(AgentKind),
@@ -357,8 +358,115 @@ pub(crate) use agent_egress::domain::model::is_macro_staff;
/// Where a prompt came from, when it came from somewhere the session should
/// answer back into.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ReplyPlacement {
+ /// Answer inside the source discussion, the behavior of existing mentions.
+ #[default]
+ Thread,
+ /// Answer in the channel's main timeline, as an agent conversing there does.
+ Timeline,
+}
+
+impl ReplyPlacement {
+ /// Whether this is the default placement used by existing serialized origins.
+ pub fn is_thread(&self) -> bool {
+ *self == Self::Thread
+ }
+
+ /// Convert a source root to the message API's optional reply target.
+ pub fn thread_id(self, root: Uuid) -> Option<Uuid> {
+ match self {
+ Self::Thread => Some(root),
+ Self::Timeline => None,
+ }
+ }
+
+ /// How a turn answered here is shown.
+ pub fn voice_style(self) -> VoiceStyle {
+ match self {
+ Self::Thread => VoiceStyle::Turn,
+ Self::Timeline => VoiceStyle::Segments,
+ }
+ }
+}
+
+/// How an agent's reply is shown where it was asked.
+///
+/// The same turn reads either way; what differs is how many messages it
+/// takes. A thread carries one reply per mention, so the reply is one message
+/// that grows. A private conversation reads like talking to a teammate, so
+/// each passage the agent writes is its own message as soon as it is
+/// finished, with the steps it took after it attached.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum VoiceStyle {
+ /// One message per turn, posted when the turn starts and updated in place.
+ Turn,
+ /// One message per passage, posted when the passage is finished; nothing
+ /// is posted until the agent has something to say or do.
+ Segments,
+}
+
+/// One message of an agent's reply, as it should read now.
+///
+/// The domain decides which segments a message shows and whether it is
+/// news; the announcer chooses the words around them and composes the
+/// nodes.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ReplyPresentation {
+ /// The session the reply speaks for.
+ pub session_id: AgentSessionId,
+ /// The bot the session speaks as; the message is posted as it.
+ pub bot_id: BotId,
+ /// Who prompted the turn; the bot writes on their current capability.
+ pub triggered_by: MacroUserIdStr<'static>,
+ /// Where the reply is shown.
+ pub parent: messages::domain::models::MessageParent,
+ /// The thread it is shown in; `None` for a timeline.
+ pub thread_id: Option<Uuid>,
+ /// The message's id, allocated before it is first posted so posting it
+ /// again finds the same message.
+ pub message_id: Uuid,
+ /// The turn the segments belong to.
+ pub turn: agent_fold::domain::model::TurnId,
+ /// The segments the message shows, in order.
+ pub segments: Vec<agent_fold::domain::model::ProjectedSegment>,
+ /// Lead with a link to the session.
+ pub link: bool,
+ /// Show that the turn is still running after the segments.
+ pub pending: bool,
+ /// How the turn ended, on the reply's last message once it has.
+ pub outcome: Option<ReplyOutcome>,
+ /// Whether this update is news: the reply's last message, once the turn
+ /// has ended.
+ pub notify: bool,
+}
+
+/// An agent session typing through the bot that speaks for it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AgentTypingUpdate {
+ /// The session whose turn is running.
+ pub session_id: AgentSessionId,
+ /// The bot the session speaks as.
+ pub bot_id: BotId,
+ /// Who prompted the turn; the bot types on their current capability.
+ pub triggered_by: MacroUserIdStr<'static>,
+ /// Where the reply will appear.
+ pub parent: messages::domain::models::MessageParent,
+ /// The thread it will appear in; `None` for a timeline.
+ pub thread_id: Option<Uuid>,
+ /// Whether the agent is typing.
+ pub active: bool,
+ /// What the agent is doing.
+ pub phase: agent_fold::domain::model::TurnPhase,
+}
+
+/// Source message and placement of one agent response.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AnnounceOrigin {
+ /// Ordinary mentions reply in a thread; agent conversations answer in the timeline.
+ #[serde(default, skip_serializing_if = "ReplyPlacement::is_thread")]
+ pub reply_placement: ReplyPlacement,
/// Update the existing agent response instead of posting a reply.
#[serde(default)]
pub reuse_origin_message: bool,
@@ -415,6 +523,8 @@ pub struct DeliverAction {
/// it.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum HarnessCommand {
+ /// Open or continue the durably reserved session of an agent's conversation.
+ ConversationMessage(OpenSession),
/// Open a new session.
Open(OpenSession),
/// Act on a session that already exists.
@@ -538,6 +648,10 @@ pub struct AnnouncePrompt {
/// Facts required to announce one prompt into its originating context.
#[derive(Debug, Clone)]
pub struct SessionAnnouncement {
+ /// Preallocated reply id for a durably journaled conversation turn.
+ pub reply_message_id: Option<Uuid>,
+ /// Whether the answer is a thread reply or a top-level channel message.
+ pub reply_placement: ReplyPlacement,
/// Update the existing agent response instead of posting a reply.
pub reuse_origin_message: bool,
/// Agent session represented by the announcement.
@@ -623,7 +737,7 @@ pub struct AnnouncedMessage {
/// either. So the reply says so ([`Self::NeedsInput`],
/// [`Self::AwaitingApproval`]) and returns to pending once nothing is
/// waiting ([`Self::Resumed`]).
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ReplyOutcome {
/// The agent answered; its last message, whole.
Answered(String),
@@ -715,6 +829,12 @@ pub struct ResolvedReply {
pub triggered_by: MacroUserIdStr<'static>,
/// What the reply should say now.
pub outcome: ReplyOutcome,
+ /// The turn the reply answers.
+ pub turn: agent_fold::domain::model::TurnId,
+ /// The reply's segments, when this replica watched the turn run: the
+ /// passages and steps the reply shows. Empty when it did not, and the
+ /// reply is then told from `outcome` alone.
+ pub segments: Vec<agent_fold::domain::model::ProjectedSegment>,
}
/// Values required to provision a new session container.
diff --git a/crates/agent_harness/src/domain/model/session_origin.rs b/crates/agent_harness/src/domain/model/session_origin.rs
index a77e1b295d..a8d3240f75 100644
--- a/crates/agent_harness/src/domain/model/session_origin.rs
+++ b/crates/agent_harness/src/domain/model/session_origin.rs
@@ -5,7 +5,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use trigger_context::TriggerContext;
-use super::AnnounceOrigin;
+use super::{AnnounceOrigin, ReplyPlacement};
#[cfg(test)]
mod test;
@@ -13,6 +13,9 @@ mod test;
/// Where a mention happened.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct MentionOrigin {
+ /// Whether the reply belongs in a thread or the channel's timeline.
+ #[serde(default, skip_serializing_if = "ReplyPlacement::is_thread")]
+ pub reply_placement: ReplyPlacement,
/// Channel or document the mentioning message was posted in.
pub parent: messages::domain::models::MessageParent,
/// Thread the announcement replies into: the mention's thread root.
@@ -100,12 +103,14 @@ impl SessionOrigin {
pub(crate) fn announcement(&self) -> AnnounceOrigin {
match self {
Self::Mention(origin) => AnnounceOrigin {
+ reply_placement: origin.reply_placement,
reuse_origin_message: false,
parent: origin.parent.clone(),
thread_id: origin.thread_id,
message_id: origin.message_id,
},
Self::TaskAssignment(origin) => AnnounceOrigin {
+ reply_placement: ReplyPlacement::Thread,
reuse_origin_message: true,
parent: origin.parent.clone(),
thread_id: origin.discussion_id,
diff --git a/crates/agent_harness/src/domain/model/session_origin/test.rs b/crates/agent_harness/src/domain/model/session_origin/test.rs
index 5cfbdfca6b..6bbe84f297 100644
--- a/crates/agent_harness/src/domain/model/session_origin/test.rs
+++ b/crates/agent_harness/src/domain/model/session_origin/test.rs
@@ -8,6 +8,7 @@ fn actor() -> MacroUserIdStr<'static> {
#[test]
fn existing_mention_commands_keep_their_wire_shape_and_reply_behavior() {
let mention = MentionOrigin {
+ reply_placement: Default::default(),
parent: MessageParent::Channel(Uuid::from_u128(1)),
thread_id: Uuid::from_u128(2),
message_id: Uuid::from_u128(3),
diff --git a/crates/agent_harness/src/domain/pending.rs b/crates/agent_harness/src/domain/pending.rs
index 4635ab88cc..3a8a258890 100644
--- a/crates/agent_harness/src/domain/pending.rs
+++ b/crates/agent_harness/src/domain/pending.rs
@@ -89,6 +89,21 @@ impl PendingCommands {
pub fn is_pending(&self, session: AgentSessionId) -> bool {
self.0.contains_key(&session)
}
+
+ /// Every turn in flight on this replica, for work that runs per turn on a
+ /// timer - keeping a running turn's typing indicator alive.
+ #[must_use]
+ pub fn running(&self) -> Vec<(AgentSessionId, InFlightTurn)> {
+ self.0
+ .iter()
+ .filter_map(|entry| {
+ entry
+ .value()
+ .as_ref()
+ .map(|turn| (*entry.key(), turn.clone()))
+ })
+ .collect()
+ }
}
#[cfg(test)]
@@ -110,6 +125,9 @@ mod test {
announce: None,
announcement_message_id: None,
dispatched_at: chrono::Utc::now(),
+ bot_id: None,
+ speaks_as_chip: false,
+ presented: Vec::new(),
held_tool_calls: Vec::new(),
}
}
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index b7103a91a5..c7540e2877 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -289,6 +289,20 @@ pub trait SessionAnnouncer: Send + Sync + 'static {
/// session" but "here is what you need first". Same channel, same
/// sender, no session to point at.
fn decline(&self, declined: DeclinedMention) -> impl Future<Output = Result<()>> + Send;
+
+ /// Show one message of a reply as it should read now: post it under its
+ /// allocated id if it is not there yet, or update it if it reads
+ /// differently. Posting the same presentation twice changes nothing.
+ fn present(
+ &self,
+ presentation: crate::domain::model::ReplyPresentation,
+ ) -> impl Future<Output = Result<()>> + Send;
+
+ /// Say that the session is typing through its bot, or that it stopped.
+ fn typing(
+ &self,
+ typing: crate::domain::model::AgentTypingUpdate,
+ ) -> impl Future<Output = Result<()>> + Send;
}
/// Told when a tool call in a session's turn starts or stops waiting for the
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index c9d8e97b1e..85d7a022ba 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -30,7 +30,7 @@ fn owner() -> MacroUserIdStr<'static> {
fn params(id: AgentSessionId) -> CreateAgentSessionParams {
CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: model_owner::Owner::User(owner()),
diff --git a/crates/agent_harness/src/domain/presenter.rs b/crates/agent_harness/src/domain/presenter.rs
new file mode 100644
index 0000000000..3a7d0516cd
--- /dev/null
+++ b/crates/agent_harness/src/domain/presenter.rs
@@ -0,0 +1,119 @@
+//! Which channel messages an agent's reply is shown through, and what each
+//! shows.
+//!
+//! Pure planning over the segments the session's fold reports (see
+//! [`agent_fold::domain::model::segments`]). The harness service applies a
+//! plan as the reply grows; the announcer chooses the words around the
+//! segments and composes their nodes.
+
+use agent_fold::domain::model::{ActivityRow, ActivityStatus, ProjectedSegment, SegmentKind};
+
+#[cfg(test)]
+mod test;
+
+/// One message of a reply shown in
+/// [`VoiceStyle::Segments`](crate::domain::model::VoiceStyle::Segments): a
+/// passage and the steps the agent took after it, or steps alone when the
+/// agent got to work before writing anything.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PlannedMessage {
+ /// The segments the message shows, in order.
+ pub segments: Vec<ProjectedSegment>,
+ /// Whether the message can be posted. One that leads with a passage
+ /// waits until the agent has finished writing it - an unfinished passage
+ /// streams live instead; one that leads with steps is ready at once.
+ pub ready: bool,
+}
+
+/// Split a reply into the messages it is shown through.
+///
+/// A message starts at each passage, so boundaries only ever appear at the
+/// end as a reply grows: a reply's n-th message stays its n-th message,
+/// which is what lets its id be allocated once and reused. Requests for the
+/// user are not part of any message: a pending one is answered live, and an
+/// answered one is history the agent's next passage takes up.
+#[must_use]
+pub fn plan_messages(segments: &[ProjectedSegment]) -> Vec<PlannedMessage> {
+ let mut planned: Vec<PlannedMessage> = Vec::new();
+ for segment in segments {
+ match segment.segment.kind {
+ SegmentKind::Interaction => {}
+ SegmentKind::Prose => planned.push(PlannedMessage {
+ segments: vec![segment.clone()],
+ ready: segment.text.is_some(),
+ }),
+ SegmentKind::Activity => match planned.last_mut() {
+ Some(message) => message.segments.push(segment.clone()),
+ None => planned.push(PlannedMessage {
+ segments: vec![segment.clone()],
+ ready: true,
+ }),
+ },
+ }
+ }
+ planned
+}
+
+/// The segments a single message showing a whole turn carries: finished
+/// passages and every run of steps, in order. An unfinished passage streams
+/// live until it is finished.
+#[must_use]
+pub fn turn_segments(segments: &[ProjectedSegment]) -> Vec<ProjectedSegment> {
+ segments
+ .iter()
+ .filter(|segment| match segment.segment.kind {
+ SegmentKind::Prose => segment.text.is_some(),
+ SegmentKind::Activity => true,
+ SegmentKind::Interaction => false,
+ })
+ .cloned()
+ .collect()
+}
+
+/// What a message showing one segment must be rewritten for.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SegmentShape {
+ index: u32,
+ sealed: bool,
+ /// A sealed segment's steps and passage; nothing while it is open.
+ content: Option<(Vec<ActivityRow>, Option<String>)>,
+}
+
+/// What a message showing `segments` must be rewritten for: a segment
+/// appearing, a segment sealing, or a sealed segment changing. A step
+/// starting or finishing inside an open run of steps is not: viewers who can
+/// read the session see it live, and the message's snapshot of the run is
+/// rewritten once when it seals. A sealed run can still change - a call held
+/// for permission finishes after the request sealed its run, a plan is
+/// updated in place - and its message must not keep the old snapshot.
+#[must_use]
+pub fn shape(segments: &[ProjectedSegment]) -> Vec<SegmentShape> {
+ segments
+ .iter()
+ .map(|segment| SegmentShape {
+ index: segment.segment.index,
+ sealed: segment.segment.sealed,
+ content: segment
+ .segment
+ .sealed
+ .then(|| (segment.segment.rows.clone(), segment.text.clone())),
+ })
+ .collect()
+}
+
+/// A reply as it reads once its turn is over: every segment sealed, and no
+/// step still running. The fold closes a turn that ended this way itself;
+/// one whose session died, or that recovery finishes, never closed, and a
+/// step it left running would spin in its message forever.
+#[must_use]
+pub fn closed(mut segments: Vec<ProjectedSegment>) -> Vec<ProjectedSegment> {
+ for segment in &mut segments {
+ segment.segment.sealed = true;
+ for row in &mut segment.segment.rows {
+ if row.status == ActivityStatus::Running {
+ row.status = ActivityStatus::Interrupted;
+ }
+ }
+ }
+ segments
+}
diff --git a/crates/agent_harness/src/domain/presenter/test.rs b/crates/agent_harness/src/domain/presenter/test.rs
new file mode 100644
index 0000000000..5482e2b9de
--- /dev/null
+++ b/crates/agent_harness/src/domain/presenter/test.rs
@@ -0,0 +1,164 @@
+use agent_fold::domain::model::{ActivityRow, ActivityStatus, Segment};
+
+use super::*;
+
+fn prose(index: u32, text: Option<&str>) -> ProjectedSegment {
+ ProjectedSegment {
+ segment: Segment {
+ index,
+ kind: SegmentKind::Prose,
+ start: index,
+ end: index + 1,
+ sealed: text.is_some(),
+ rows: Vec::new(),
+ },
+ text: text.map(str::to_owned),
+ }
+}
+
+fn activity(index: u32, sealed: bool, rows: usize) -> ProjectedSegment {
+ ProjectedSegment {
+ segment: Segment {
+ index,
+ kind: SegmentKind::Activity,
+ start: index,
+ end: index + 1,
+ sealed,
+ rows: (0..rows)
+ .map(|row| ActivityRow {
+ id: format!("t{row}"),
+ label: "Ran".to_owned(),
+ detail: None,
+ status: ActivityStatus::Completed,
+ })
+ .collect(),
+ },
+ text: None,
+ }
+}
+
+fn interaction(index: u32) -> ProjectedSegment {
+ ProjectedSegment {
+ segment: Segment {
+ index,
+ kind: SegmentKind::Interaction,
+ start: index,
+ end: index + 1,
+ sealed: true,
+ rows: Vec::new(),
+ },
+ text: None,
+ }
+}
+
+fn indices(message: &PlannedMessage) -> Vec<u32> {
+ message.segments.iter().map(|s| s.segment.index).collect()
+}
+
+#[test]
+fn each_passage_opens_a_message_that_carries_the_steps_after_it() {
+ let planned = plan_messages(&[
+ prose(0, Some("Checking first.")),
+ activity(1, true, 2),
+ prose(2, Some("Found it.")),
+ activity(3, false, 1),
+ ]);
+ assert_eq!(planned.len(), 2);
+ assert_eq!(indices(&planned[0]), [0, 1]);
+ assert_eq!(indices(&planned[1]), [2, 3]);
+ assert!(planned.iter().all(|message| message.ready));
+}
+
+#[test]
+fn steps_before_any_passage_are_a_message_of_their_own_ready_at_once() {
+ let planned = plan_messages(&[activity(0, false, 1)]);
+ assert_eq!(planned.len(), 1);
+ assert!(planned[0].ready);
+}
+
+#[test]
+fn a_passage_still_being_written_waits_but_keeps_its_place() {
+ let planned = plan_messages(&[
+ prose(0, Some("Narration.")),
+ activity(1, true, 1),
+ prose(2, None),
+ ]);
+ assert_eq!(planned.len(), 2);
+ assert!(planned[0].ready);
+ assert!(
+ !planned[1].ready,
+ "an unfinished passage streams live instead"
+ );
+}
+
+#[test]
+fn requests_for_the_user_belong_to_no_message() {
+ let planned = plan_messages(&[
+ prose(0, Some("May I?")),
+ interaction(1),
+ activity(2, true, 1),
+ ]);
+ assert_eq!(planned.len(), 1);
+ assert_eq!(indices(&planned[0]), [0, 2]);
+}
+
+#[test]
+fn a_growing_reply_never_renumbers_its_earlier_messages() {
+ let early = plan_messages(&[prose(0, Some("A.")), activity(1, false, 1)]);
+ let later = plan_messages(&[
+ prose(0, Some("A.")),
+ activity(1, true, 3),
+ prose(2, Some("B.")),
+ ]);
+ assert_eq!(indices(&early[0]), indices(&later[0]));
+}
+
+#[test]
+fn a_turn_message_shows_finished_passages_and_every_run_of_steps() {
+ let shown = turn_segments(&[
+ prose(0, Some("A.")),
+ activity(1, false, 1),
+ interaction(2),
+ prose(3, None),
+ ]);
+ assert_eq!(
+ shown.iter().map(|s| s.segment.index).collect::<Vec<_>>(),
+ [0, 1]
+ );
+}
+
+#[test]
+fn a_step_inside_an_open_run_does_not_change_the_shape_but_sealing_does() {
+ let one = [prose(0, Some("A.")), activity(1, false, 1)];
+ let two = [prose(0, Some("A.")), activity(1, false, 2)];
+ let sealed = [prose(0, Some("A.")), activity(1, true, 2)];
+ assert_eq!(shape(&one), shape(&two));
+ assert_ne!(shape(&two), shape(&sealed));
+}
+
+#[test]
+fn a_sealed_run_whose_step_finishes_late_changes_the_shape() {
+ // A call held for permission finishes after the request sealed its run.
+ let mut waiting = activity(0, true, 1);
+ waiting.segment.rows[0].status = ActivityStatus::Running;
+ let mut finished = waiting.clone();
+ finished.segment.rows[0].status = ActivityStatus::Completed;
+ assert_ne!(shape(&[waiting]), shape(&[finished]));
+}
+
+#[test]
+fn a_closed_reply_is_sealed_and_runs_nothing() {
+ let mut open = activity(1, false, 2);
+ open.segment.rows[0].status = ActivityStatus::Running;
+ let reply = closed(vec![prose(0, Some("Checking.")), open]);
+ assert!(reply.iter().all(|segment| segment.segment.sealed));
+ assert_eq!(
+ reply[1]
+ .segment
+ .rows
+ .iter()
+ .map(|row| row.status)
+ .collect::<Vec<_>>(),
+ [ActivityStatus::Interrupted, ActivityStatus::Completed]
+ );
+}
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index daca23ec30..f4e96f6c3a 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -28,6 +28,7 @@ use agent_session::domain::events::{InFlightTurnSummary, TurnSummary};
use agent_session::domain::model::AgentSessionId;
use agent_session::domain::model::StoredQueuedAction;
use agent_session::domain::ports::QueuedControl;
+use bot_id::BotId;
use chrono::{DateTime, Utc};
use dashmap::DashMap;
use macro_user_id::user_id::MacroUserIdStr;
@@ -74,7 +75,7 @@ pub struct QueuedEntry {
/// end is then observed without a record. `turn` is the fold's next turn id
/// at dispatch, which for a compaction (no user message) is the turn the
/// fold would assign to the next prompt.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InFlightTurn {
/// The action that opened the turn.
pub action_id: AgentActionId,
@@ -97,8 +98,23 @@ pub struct InFlightTurn {
/// turn hours old with nothing streaming is the shape of a wedged
/// session, and without this it looks exactly like a long one.
pub dispatched_at: DateTime<Utc>,
+ /// The bot the session speaks as, for the turn's typing and reply
+ /// messages. Absent on a turn recorded before it was kept.
+ #[serde(default)]
+ pub bot_id: Option<BotId>,
+ /// Whether the turn was announced as a session chip (a coding agent or an
+ /// assignment), which renders the turn itself: its message is never
+ /// rewritten into a reply.
+ #[serde(default)]
+ pub speaks_as_chip: bool,
+ /// The messages a reply shown in segments is posted as, in order. Each id
+ /// is allocated, and saved with the turn, before the message is first
+ /// posted, so showing the reply again updates the same messages.
+ #[serde(default)]
+ pub presented: Vec<Uuid>,
/// Tool calls this turn made that wait on the owner's approval, oldest
/// first. The reply names the oldest while any wait.
+ #[serde(default)]
pub held_tool_calls: Vec<HeldToolCall>,
}
@@ -208,6 +224,27 @@ impl SessionQueues {
self.insert(session, entry, VecDeque::push_back)
}
+ /// Recover a conversation's durable admission order even when broker deliveries arrive out of order.
+ pub fn enqueue_chronological(
+ &self,
+ session: AgentSessionId,
+ entry: QueuedEntry,
+ ) -> Result<(), QueueError> {
+ self.insert(session, entry, |queue, entry| {
+ let key = |entry: &QueuedEntry| {
+ (
+ entry.created_at,
+ entry.announce.as_ref().map(|origin| origin.message_id),
+ )
+ };
+ let index = queue
+ .iter()
+ .position(|queued| key(queued) > key(&entry))
+ .unwrap_or(queue.len());
+ queue.insert(index, entry);
+ })
+ }
+
/// Put an entry ahead of everything already waiting, for a channel
/// follow-up that steers the running turn: it runs next, not after work
/// that was queued before it.
diff --git a/crates/agent_harness/src/domain/queue/test.rs b/crates/agent_harness/src/domain/queue/test.rs
index b7be069acd..859f07d82d 100644
--- a/crates/agent_harness/src/domain/queue/test.rs
+++ b/crates/agent_harness/src/domain/queue/test.rs
@@ -258,6 +258,7 @@ fn a_snapshot_round_trips_through_the_durable_shape() {
let session = AgentSessionId::TEST_A;
let mut entry = prompt_entry("keep me");
entry.announce = Some(AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: messages::domain::models::MessageParent::Channel(Uuid::from_u128(0xf0)),
thread_id: Uuid::from_u128(0xf1),
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 65abfcc7af..e8e359cb0e 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -21,6 +21,7 @@ mod deliver;
mod lifecycle;
mod lifecycle_events;
mod open;
+mod present;
mod queue;
mod session_mcp;
mod warm;
@@ -138,6 +139,8 @@ struct AgentHarnessInner<
forwarder: Box<dyn ErasedForwarder>,
permission_policies: Box<dyn ErasedPermissionPolicySource>,
coding_agents: Box<dyn ErasedCodingAgentSource>,
+ conversations: Option<Arc<dyn crate::domain::conversations::ConversationPolicy>>,
+ conversation_turns: Option<Arc<dyn crate::domain::conversation_turns::ConversationTurnStore>>,
defaults: HarnessDefaults,
/// Turn-occupying actions waiting for their session's running turn to
/// end. In-memory working copy; the session store is the durable source.
@@ -165,6 +168,21 @@ struct AgentHarnessInner<
mentions: Mentions,
/// Where the notifications a fact warrants go.
notifier: Notifier,
+ /// How a running turn's reply was last reported, keyed by session: the
+ /// reply's segments as the fold reported them, for the turn's end to
+ /// show. Only ever touched from the session's own command worker.
+ projections: DashMap<
+ AgentSessionId,
+ (
+ agent_fold::domain::model::TurnId,
+ Vec<agent_fold::domain::model::ProjectedSegment>,
+ ),
+ >,
+ /// What each running turn's agent is doing, for its typing indicator.
+ typing_phases: DashMap<AgentSessionId, agent_fold::domain::model::TurnPhase>,
+ /// The shape each reply message was last shown with, so a report that
+ /// changes nothing it shows does not rewrite it.
+ presented_shapes: DashMap<macro_uuid::Uuid, Vec<crate::domain::presenter::SegmentShape>>,
}
/// One handle on the orchestrator's state, shared by the service's clones
@@ -310,6 +328,7 @@ where
/// them into a struct would only move the same list one level down.
#[allow(clippy::too_many_arguments)]
pub fn new(
+ conversations: Option<Arc<dyn crate::domain::conversations::ConversationPolicy>>,
sessions: Sessions,
containers: Containers,
announcer: Announcer,
@@ -339,6 +358,8 @@ where
forwarder: Box::new(forwarder),
permission_policies: Box::new(permission_policies),
coding_agents: Box::new(coding_agents),
+ conversations,
+ conversation_turns: None,
defaults: defaults.into(),
queues: SessionQueues::new(),
hydrated: DashSet::new(),
@@ -346,6 +367,9 @@ where
lifecycle_publisher,
mentions,
notifier,
+ projections: DashMap::new(),
+ typing_phases: DashMap::new(),
+ presented_shapes: DashMap::new(),
}),
workers: Arc::new(DashMap::new()),
repositories: None,
@@ -355,6 +379,149 @@ where
}
}
+ /// Enable durable conversation admission and recovery before sharing this service.
+ pub fn with_conversation_turns(
+ mut self,
+ store: Arc<dyn crate::domain::conversation_turns::ConversationTurnStore>,
+ ) -> Self {
+ Arc::get_mut(&mut self.inner)
+ .expect("configure journal before cloning the harness")
+ .conversation_turns = Some(store);
+ self
+ }
+
+ /// Save a conversation message before acknowledging its broker event. Returns its
+ /// original segment and payload when the source message was already seen.
+ ///
+ /// `None` is a message no attempt can ever admit: its conversation was
+ /// deleted, or its sender may not prompt it. The caller acknowledges it
+ /// instead of having the broker redeliver it forever. A context that
+ /// another replica is changing is waited out; only one that stays busy is
+ /// an error.
+ pub async fn admit_conversation_message(
+ &self,
+ session: AgentSessionId,
+ command: OpenSession,
+ ) -> Result<Option<(AgentSessionId, OpenSession)>> {
+ match self.journal_conversation_message(session, command).await {
+ Err(HarnessError::Session(AgentSessionError::Forbidden)) => Ok(None),
+ admitted => admitted.map(Some),
+ }
+ }
+
+ async fn journal_conversation_message(
+ &self,
+ session: AgentSessionId,
+ command: OpenSession,
+ ) -> Result<(AgentSessionId, OpenSession)> {
+ let origin = command.origin.announcement();
+ if origin.reply_placement != crate::domain::model::ReplyPlacement::Timeline {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ if let Some(policy) = &self.inner.conversations
+ && !policy
+ .validate_binding(session, command.bot_id, Some(command.origin.actor()))
+ .await?
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ let Some(store) = &self.inner.conversation_turns else {
+ return Ok((session, command));
+ };
+ let messages::domain::models::MessageParent::Channel(channel) = origin.parent else {
+ return Err(AgentSessionError::Forbidden.into());
+ };
+ if let Some(record) = store.get(origin.message_id, command.bot_id).await? {
+ if record.channel_id != channel {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ return Ok((record.session_id, record.command));
+ }
+ // An event can have reserved its segment before the user pressed Start
+ // fresh. Serialize first admission with reset and select the current
+ // segment again; replays above always retain their original identity.
+ // The context lease is also taken by every claim and retry of the
+ // session, each a few queries long, so a busy lease is waited out.
+ let mut backoff = std::time::Duration::from_millis(50);
+ for _ in 0..8 {
+ let current = match &self.inner.conversations {
+ Some(policy) => policy.current_context(session).await?,
+ None => session,
+ };
+ let Some(_lease) = store.claim_context(current).await? else {
+ tokio::time::sleep(backoff).await;
+ backoff = (backoff * 2).min(std::time::Duration::from_secs(1));
+ continue;
+ };
+ if let Some(policy) = &self.inner.conversations
+ && policy.current_context(session).await? != current
+ {
+ continue;
+ }
+ let record = store.admit(current, channel, command).await?;
+ return Ok((record.session_id, record.command));
+ }
+ Err(AgentSessionError::RuntimeUnavailable(
+ "conversation context stayed busy; retry admission",
+ )
+ .into())
+ }
+
+ /// Reconcile journaled work after process loss. Only undispatched prompts
+ /// may run automatically; ambiguous attempts are marked interrupted.
+ pub async fn recover_conversations(&self) -> Result<()> {
+ let Some(store) = &self.inner.conversation_turns else {
+ return Ok(());
+ };
+ for record in store.running(100).await? {
+ let management = self.inner.sessions.management(record.session_id).await?;
+ if matches!(management, SessionManagement::Unmanaged)
+ || (matches!(management, SessionManagement::Ours)
+ && !self.inner.busy.is_pending(record.session_id))
+ {
+ store
+ .finish(
+ record.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Interrupted,
+ ReplyOutcome::Failed,
+ )
+ .await?;
+ tracing::warn!(session_id = %record.session_id, action_id = %record.action_id, "conversation turn interrupted; explicit retry required");
+ }
+ }
+ for record in store.pending_replies(100).await? {
+ let Some(outcome) = record.outcome else {
+ continue;
+ };
+ if let Some(turn) = &record.in_flight {
+ self.inner
+ .resolve_reply(record.session_id, Some(turn), outcome)
+ .await;
+ } else {
+ store.finalize_reply(record.action_id, &outcome).await?;
+ }
+ }
+ let pending = store.pending(50).await?;
+ let work: Vec<_> = pending
+ .into_iter()
+ .map(|record| {
+ self.execute(
+ record.session_id,
+ HarnessCommand::ConversationMessage(record.command),
+ )
+ })
+ .collect();
+ for result in futures::future::join_all(work).await {
+ if let Err(error) = result {
+ tracing::warn!(
+ ?error,
+ "durable conversation recovery could not dispatch a queued prompt"
+ );
+ }
+ }
+ Ok(())
+ }
+
/// Configure shared admission before cloning the harness or starting workers.
pub fn with_admission(mut self, admission: Arc<dyn ai_billing::AiAdmissionService>) -> Self {
Arc::get_mut(&mut self.inner)
@@ -436,6 +603,8 @@ where
self.inner
.announcer
.announce(SessionAnnouncement {
+ reply_message_id: None,
+ reply_placement: prompt.origin.reply_placement,
reuse_origin_message: false,
session_id,
bot_id: session.bot_id,
diff --git a/crates/agent_harness/src/domain/service/admission.rs b/crates/agent_harness/src/domain/service/admission.rs
index 1fad4444a8..431a450460 100644
--- a/crates/agent_harness/src/domain/service/admission.rs
+++ b/crates/agent_harness/src/domain/service/admission.rs
@@ -107,14 +107,38 @@ where
// Persist first: never report a terminal rejection while the durable
// queue still says that the command will run after a restart.
for entry in waiting {
- self.resolve_announced_reply(
- session_id,
- entry.announced,
- entry.announce.as_ref(),
- entry.actor.as_ref(),
- ReplyOutcome::Failed,
- )
- .await;
+ let conversation_store = self.conversation_turns.as_ref().filter(|_| {
+ entry.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ })
+ });
+ if let Some(store) = conversation_store {
+ store
+ .finish(
+ entry.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await?;
+ }
+ let resolved = self
+ .resolve_announced_reply(
+ session_id,
+ entry.announced,
+ entry.announce.as_ref(),
+ entry.actor.as_ref(),
+ ReplyOutcome::Failed,
+ // A refused entry never opened a turn: there is nothing
+ // it said or did to show, only that it was refused.
+ agent_fold::domain::model::TurnId(0),
+ Vec::new(),
+ )
+ .await;
+ if resolved && let Some(store) = conversation_store {
+ store
+ .finalize_reply(entry.action_id, &ReplyOutcome::Failed)
+ .await?;
+ }
self.publish_command_rejected(
session_id,
entry.action_id,
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index fb74a0f176..56dc8450fd 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -59,6 +59,14 @@ where
context: _,
} = command;
+ if !matches!(action, AgentAction::Stop)
+ && let Some(policy) = &self.conversations
+ {
+ let session = self.sessions.get_session(session_id).await?;
+ policy
+ .authorize_prompt(session_id, session.bot_id, actor.as_ref())
+ .await?;
+ }
if action.occupies_turn() {
self.admit_session_id(session_id).await?;
self.refresh_mcp_servers(session_id).await;
@@ -80,12 +88,16 @@ where
}
Err(AgentSessionError::Disconnected(_)) => {
let session = self.sessions.get_session(session_id).await?;
- let permission_policy = self.permission_policy_for(session.bot_id).await;
- if AgentKind::for_session(session.bot_id, &session.harness).is_managed() {
+ let permission_policy = self
+ .permission_policy_for_session(session_id, session.bot_id)
+ .await?;
+ let kind = AgentKind::for_session(session.bot_id, &session.harness);
+ if kind.is_managed() {
let container = self.containers.resume(session_id).await?;
let mcp_servers = self
.resumed_mcp_servers(
session_id,
+ kind,
session.owner_user()?,
&session.mcp_servers,
)
@@ -239,13 +251,19 @@ where
// The announcement posts as the session's own bot, which only the
// row remembers.
let session = self.sessions.get_session(session_id).await?;
- let persona = self.reply_persona(&session).await?;
+ let is_coding = if origin.reply_placement == crate::domain::model::ReplyPlacement::Thread {
+ self.reply_persona(&session).await?.is_coding
+ } else {
+ false
+ };
Ok(Some(SessionAnnouncement {
+ reply_message_id: None,
+ reply_placement: origin.reply_placement,
reuse_origin_message: origin.reuse_origin_message,
session_id,
bot_id: session.bot_id,
- is_coding: persona.is_coding,
+ is_coding,
origin_parent: origin.parent,
origin_thread_id: origin.thread_id,
origin_message_id: origin.message_id,
@@ -268,22 +286,104 @@ where
&self,
session_id: AgentSessionId,
turn: Option<&InFlightTurn>,
- outcome: ReplyOutcome,
+ mut outcome: ReplyOutcome,
) {
let Some(turn) = turn else {
return;
};
- self.resolve_announced_reply(
- session_id,
- turn.announcement_message_id,
- turn.announce.as_ref(),
- turn.actor.as_ref(),
+ let terminal = !matches!(
outcome,
- )
- .await;
+ ReplyOutcome::NeedsInput { .. }
+ | ReplyOutcome::AwaitingApproval(_)
+ | ReplyOutcome::Resumed
+ );
+ let in_segments = turn.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement.voice_style() == crate::domain::model::VoiceStyle::Segments
+ });
+ // A reply shown in segments is shown once its turn has ended. While
+ // the turn waits on a question or an approval, it is answered live
+ // and the bot's typing says it is waiting.
+ if in_segments && !terminal {
+ return;
+ }
+ let conversation_store = self.conversation_turns.as_ref().filter(|_| {
+ turn.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ })
+ });
+ let _reply_lease = if terminal && let Some(store) = conversation_store {
+ match store.claim_reply(turn.action_id).await {
+ Ok(Some(lease)) => Some(lease),
+ Ok(None) => return,
+ Err(error) => {
+ tracing::error!(?error, %session_id, "could not claim conversation reply reconciliation");
+ return;
+ }
+ }
+ } else {
+ None
+ };
+ let mut turn = turn.clone();
+ let mut saved_reply = Vec::new();
+ if terminal && let Some(store) = conversation_store {
+ match store.by_action(turn.action_id).await {
+ Ok(Some(record)) if record.reply_finalized => return,
+ Ok(Some(record)) => {
+ // Another replica may have reserved more reply IDs since
+ // the caller read this turn. Always use the durable flight
+ // read under the reply lease, including after a failed post.
+ let Some(saved_flight) = record.in_flight else {
+ return;
+ };
+ turn = saved_flight;
+ if let Some(saved) = record.outcome {
+ outcome = saved;
+ }
+ saved_reply = record.reply_segments.unwrap_or_default();
+ }
+ Err(error) => {
+ tracing::error!(?error, %session_id, "could not read the durable conversation reply state");
+ return;
+ }
+ Ok(None) => return,
+ }
+ }
+ let resolved = if in_segments {
+ self.present_final(session_id, &turn, outcome.clone(), saved_reply)
+ .await
+ } else {
+ let segments = if turn.speaks_as_chip {
+ Vec::new()
+ } else {
+ crate::domain::presenter::turn_segments(
+ &self.reported_segments(session_id, turn.turn),
+ )
+ };
+ self.resolve_announced_reply(
+ session_id,
+ turn.announcement_message_id,
+ turn.announce.as_ref(),
+ turn.actor.as_ref(),
+ outcome.clone(),
+ turn.turn,
+ segments,
+ )
+ .await
+ };
+ if resolved
+ && terminal
+ && let Some(store) = conversation_store
+ && let Err(error) = store.finalize_reply(turn.action_id, &outcome).await
+ {
+ tracing::error!(?error, %session_id, "failed to mark the conversation reply finalized");
+ }
}
/// Resolve an announcement even when its queued command never opened a turn.
+ #[expect(
+ clippy::too_many_arguments,
+ reason = "each argument is a separate fact about the reply; bundling them only moves the list"
+ )]
pub(super) async fn resolve_announced_reply(
&self,
session_id: AgentSessionId,
@@ -291,15 +391,17 @@ where
origin: Option<&AnnounceOrigin>,
actor: Option<&MacroUserIdStr<'static>>,
outcome: ReplyOutcome,
- ) {
+ turn: agent_fold::domain::model::TurnId,
+ segments: Vec<agent_fold::domain::model::ProjectedSegment>,
+ ) -> bool {
let (Some(message_id), Some(origin), Some(triggered_by)) = (message_id, origin, actor)
else {
- return;
+ return true;
};
// An assignment announces a session link, not a discussion reply.
// Later user messages have their own origins and can still be answered.
if origin.reuse_origin_message {
- return;
+ return true;
}
let session = match self.sessions.get_session(session_id).await {
Ok(session) => session,
@@ -310,19 +412,26 @@ where
%message_id,
"leaving a turn's reply unresolved: session row unavailable"
);
- return;
+ return false;
}
};
- let persona = match self.reply_persona(&session).await {
- Ok(persona) => persona,
- Err(error) => {
- tracing::error!(
- error = ?error,
- %session_id,
- %message_id,
- "leaving a turn's reply unresolved: the session's persona is unavailable"
- );
- return;
+ // A timeline reply remains resolvable if its persona was deleted
+ // during the turn. The session preserves its author identity.
+ let is_coding = if origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ {
+ false
+ } else {
+ match self.reply_persona(&session).await {
+ Ok(persona) => persona.is_coding,
+ Err(error) => {
+ tracing::error!(
+ error = ?error,
+ %session_id,
+ %message_id,
+ "leaving a turn's reply unresolved: the session's persona is unavailable"
+ );
+ return false;
+ }
}
};
if let Err(error) = self
@@ -330,11 +439,13 @@ where
.resolve(ResolvedReply {
session_id,
bot_id: session.bot_id,
- is_coding: persona.is_coding,
+ is_coding,
message_id,
origin_parent: origin.parent.clone(),
triggered_by: triggered_by.clone(),
- outcome,
+ outcome: outcome.clone(),
+ turn,
+ segments,
})
.await
{
@@ -344,6 +455,9 @@ where
%message_id,
"failed to resolve a turn's reply in its thread"
);
+ false
+ } else {
+ true
}
}
}
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
index d4839f79be..f2221ba7ef 100644
--- a/crates/agent_harness/src/domain/service/lifecycle.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -354,6 +354,33 @@ where
.unwrap_or(PermissionPolicy::Prompt)
}
+ /// Conversation sessions keep the adopted persona choice across reconnects. Current
+ /// harness operator restrictions can always tighten that choice.
+ pub(super) async fn permission_policy_for_session(
+ &self,
+ session: AgentSessionId,
+ bot: BotId,
+ ) -> agent_session::domain::error::Result<PermissionPolicy> {
+ if let Some(policy) = &self.conversations
+ && policy.is_conversation_session(session).await?
+ && let Some(store) = &self.conversation_turns
+ {
+ let Some(settings) = store.settings(session).await? else {
+ return Ok(PermissionPolicy::Prompt);
+ };
+ let current = self.permission_policies.permission_policy(bot).await;
+ return Ok(match current {
+ Ok(crate::domain::model::PermissionPolicyConfig::Persona {
+ harness_allows_bypass: Some(false),
+ ..
+ })
+ | Err(_) => PermissionPolicy::Prompt,
+ Ok(_) => settings.permissions.resolve(),
+ });
+ }
+ Ok(self.permission_policy_for(bot).await)
+ }
+
/// The MCP servers to advertise when reattaching to an existing container.
///
/// The raw session token exists in exactly one place after spawn - the
@@ -362,22 +389,36 @@ where
/// holds no token (a provider whose sessions carry no egress environment,
/// or a sandbox from before tokens existed) gets no servers, which is
/// also everything it could do with them.
+ ///
+ /// The in-process agent is the exception. Its token lives only in the
+ /// process that spawned it, so a resume after a restart finds none, and
+ /// every turn refreshes its tools with the advertised credential: without
+ /// one it could not take a turn at all. It gets a new token instead, and
+ /// the old one stops working with its hash.
#[tracing::instrument(err, skip(self, owner), fields(%session_id, %owner))]
pub(super) async fn resumed_mcp_servers(
&self,
session_id: AgentSessionId,
+ kind: AgentKind,
owner: &MacroUserIdStr<'static>,
selection: &AgentMcpServers,
) -> Result<Vec<agent_client_protocol::schema::v1::McpServer>> {
- let Some(session_token) = self.containers.session_token(session_id).await? else {
- tracing::debug!("container holds no egress token; restoring no MCP servers");
- return Ok(Vec::new());
- };
- Ok(self
- .egress
- .restore(owner, session_token, selection)
- .await?
- .acp_servers())
+ if let Some(session_token) = self.containers.session_token(session_id).await? {
+ return Ok(self
+ .egress
+ .restore(owner, session_token, selection)
+ .await?
+ .acp_servers());
+ }
+ if kind == AgentKind::InMemory {
+ let egress = self.egress.provision(session_id, owner, selection).await?;
+ self.sessions
+ .set_egress_token_hash(session_id, &egress.session_token_hash)
+ .await?;
+ return Ok(egress.sandbox.acp_servers());
+ }
+ tracing::debug!("container holds no egress token; restoring no MCP servers");
+ Ok(Vec::new())
}
/// Release everything the session holds, then delete it.
@@ -423,9 +464,16 @@ where
if effect == SandboxResizeEffect::Restart {
let container = self.containers.resume(session_id).await?;
let mcp_servers = self
- .resumed_mcp_servers(session_id, owner, &session.mcp_servers)
+ .resumed_mcp_servers(
+ session_id,
+ AgentKind::SandboxedCoder,
+ owner,
+ &session.mcp_servers,
+ )
+ .await?;
+ let permission_policy = self
+ .permission_policy_for_session(session_id, session.bot_id)
.await?;
- let permission_policy = self.permission_policy_for(session.bot_id).await;
self.sessions
.attach_session(
session_id,
diff --git a/crates/agent_harness/src/domain/service/lifecycle_events.rs b/crates/agent_harness/src/domain/service/lifecycle_events.rs
index 21be327503..c06aed9f0c 100644
--- a/crates/agent_harness/src/domain/service/lifecycle_events.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle_events.rs
@@ -65,7 +65,11 @@ where
let session = self.sessions.get_session(session_id).await?;
let (identity, persona) =
tokio::try_join!(self.identity_of(&session), self.reply_persona(&session))?;
- Ok((identity, persona.is_coding))
+ let is_dm = match &self.conversations {
+ Some(policy) => policy.is_conversation_session(session_id).await?,
+ None => false,
+ };
+ Ok((identity, !is_dm && persona.is_coding))
}
/// The persona a session's thread replies speak as: its bot's name, and
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 3286d1413a..97a1ba343f 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -2,7 +2,7 @@
//! external runtime that dials in. Each creates the row, provisions egress
//! where there is a sandbox to give it to, and attaches the runtime.
-use crate::domain::model::{is_coding_agent, with_coding_preferences};
+use crate::domain::model::{ReplyPlacement, is_coding_agent, with_coding_preferences};
use agent_session::domain::model::session_owner_user;
use agent_session::domain::repository_branch::RepositoryBranch;
use model_owner::Owner;
@@ -65,6 +65,7 @@ where
.authorize_origin(
&owner_user,
&AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: thread.reuse_origin_message,
parent: thread.parent.clone(),
thread_id: thread.thread_id,
@@ -103,7 +104,7 @@ where
.inner
.sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id: request.id.unwrap_or_else(AgentSessionId::new),
owner_id: request.owner,
@@ -131,6 +132,8 @@ where
let announce = async {
let persona = self.inner.reply_persona(&session).await?;
let announcement = SessionAnnouncement {
+ reply_message_id: None,
+ reply_placement: Default::default(),
reuse_origin_message: thread.reuse_origin_message,
session_id: session.id,
bot_id: request.bot_id,
@@ -293,6 +296,33 @@ where
.authorize_origin(&actor, &announcement)
.await?;
+ let runtime = if announcement.reply_placement
+ == crate::domain::model::ReplyPlacement::Timeline
+ && let Some(store) = &self.conversation_turns
+ {
+ if let Some(settings) = store.settings(session_id).await? {
+ settings.runtime
+ } else {
+ let permissions = self
+ .permission_policies
+ .permission_policy(bot_id)
+ .await
+ .map_err(AgentSessionError::from)?;
+ store
+ .pin_settings(
+ session_id,
+ crate::domain::conversation_turns::ConversationSettings {
+ runtime,
+ permissions,
+ },
+ )
+ .await?
+ .runtime
+ }
+ } else {
+ runtime
+ };
+
self.admit_open(
bot_id,
runtime.kind.harness_slug().unwrap_or(&runtime.harness),
@@ -311,6 +341,36 @@ where
?blocker,
"declining a session its owner is not set up for"
);
+ if announcement.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ && let Some(store) = &self.conversation_turns
+ && let Some(record) = store.get(announcement.message_id, bot_id).await?
+ {
+ let flight = InFlightTurn {
+ action_id: record.action_id,
+ turn: agent_fold::domain::model::TurnId(0),
+ actor: Some(actor.clone()),
+ announce: None,
+ announcement_message_id: None,
+ dispatched_at: chrono::Utc::now(),
+ bot_id: Some(bot_id),
+ speaks_as_chip: false,
+ presented: Vec::new(),
+ held_tool_calls: Vec::new(),
+ };
+ if !store.claim(record.action_id, &flight).await? {
+ return Ok(());
+ }
+ store
+ .finish(
+ record.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await?;
+ store
+ .finalize_reply(record.action_id, &ReplyOutcome::Failed)
+ .await?;
+ }
self.announcer
.decline(DeclinedMention {
bot_id,
@@ -348,12 +408,18 @@ where
let session = self
.sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: if announcement.reply_placement == ReplyPlacement::Timeline {
+ agent_session::domain::model::SessionPurpose::AgentDm
+ } else {
+ agent_session::domain::model::SessionPurpose::Standalone
+ },
repo_branch: None,
id: session_id,
owner_id: Owner::User(actor.clone()),
bot_id,
- thread_id: Some(announcement.thread_id),
+ thread_id: announcement
+ .reply_placement
+ .thread_id(announcement.thread_id),
originating_message_id: Some(announcement.message_id),
model: runtime.model.clone(),
harness: runtime
@@ -378,55 +444,80 @@ where
.await?;
self.publish_opened(&session).await;
- let mcp_servers = if runtime.kind.takes_egress_mcp_servers() {
- egress.sandbox.acp_servers()
- } else {
- Vec::new()
- };
- let container = match self
- .containers
- .spawn(SpawnContainer {
- session_id,
- kind: runtime.kind,
- size: sandbox_size,
- egress: egress.sandbox,
- })
- .await
- {
- Ok(container) => container,
- Err(error) => {
- let _ = self
- .sessions
- .mark_disconnected(session_id)
- .await
- .inspect_err(|status_error| {
- tracing::error!(
- error = ?status_error,
- %session_id,
- "failed to mark an unprovisioned session disconnected"
- );
- });
- return Err(error);
- }
- };
- let permission_policy = self.permission_policy_for(bot_id).await;
- self.sessions
- .attach_session(
- session_id,
- container
- .mcp_servers(mcp_servers)
- .permission_policy(permission_policy),
- )
- .await?;
+ // External runtimes bind on first delivery. Their operator owns the
+ // process; opening a conversation must never provision a managed sandbox for it.
+ if runtime.kind.is_managed() {
+ let mcp_servers = if runtime.kind.takes_egress_mcp_servers() {
+ egress.sandbox.acp_servers()
+ } else {
+ Vec::new()
+ };
+ let container = match self
+ .containers
+ .spawn(SpawnContainer {
+ session_id,
+ kind: runtime.kind,
+ size: sandbox_size,
+ egress: egress.sandbox,
+ })
+ .await
+ {
+ Ok(container) => container,
+ Err(error) => {
+ let _ = self
+ .sessions
+ .mark_disconnected(session_id)
+ .await
+ .inspect_err(|status_error| {
+ tracing::error!(
+ error = ?status_error,
+ %session_id,
+ "failed to mark an unprovisioned session disconnected"
+ );
+ });
+ return Err(error);
+ }
+ };
+ let permission_policy = self
+ .permission_policy_for_session(session_id, bot_id)
+ .await?;
+ self.sessions
+ .attach_session(
+ session_id,
+ container
+ .mcp_servers(mcp_servers)
+ .permission_policy(permission_policy),
+ )
+ .await?;
+ }
// The first prompt goes through the same door as every later one:
// queued raw, then dispatched - which is where it is composed with
// channel context and announced as the chip the replies render into.
// One door is what holds the one-turn-in-flight invariant from the
// session's very first action.
+ let conversation_action =
+ if announcement.reply_placement == crate::domain::model::ReplyPlacement::Timeline {
+ match &self.conversation_turns {
+ Some(store) => store
+ .get(announcement.message_id, bot_id)
+ .await?
+ .map(|turn| turn.action_id),
+ None => None,
+ }
+ } else {
+ None
+ };
self.enqueue_then_dispatch(
session_id,
DeliverAction {
- id: AgentActionId::mint(),
+ id: if announcement.reply_placement
+ == crate::domain::model::ReplyPlacement::Timeline
+ {
+ conversation_action
+ .unwrap_or_else(|| AgentActionId::from_uuid(announcement.message_id))
+ } else {
+ AgentActionId::mint()
+ },
context: origin.context().cloned(),
action: origin.into_action(),
actor: Some(actor),
diff --git a/crates/agent_harness/src/domain/service/present.rs b/crates/agent_harness/src/domain/service/present.rs
new file mode 100644
index 0000000000..3399e6b802
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/present.rs
@@ -0,0 +1,449 @@
+//! Showing a running turn where it was asked: the agent typing, and its reply
+//! as channel messages that follow the segments the session's fold reports.
+//!
+//! The fold says what the reply is (see [`TurnSignal::Progressed`]); the
+//! presenter plan says which messages show it
+//! ([`crate::domain::presenter`]); this applies the plan as the reply grows
+//! and once more, with how the turn ended, when it is over. Every message's
+//! id is allocated before it is first posted and kept with the turn, so
+//! showing a reply again - a retried report, a recovery - updates the same
+//! messages rather than posting more.
+//!
+//! [`TurnSignal::Progressed`]: agent_fold::domain::model::TurnSignal::Progressed
+
+use agent_fold::domain::model::{ProjectedSegment, TurnId, TurnPhase};
+
+use super::*;
+use crate::domain::model::{AgentTypingUpdate, ReplyPresentation, VoiceStyle};
+use crate::domain::presenter::{closed, plan_messages, shape, turn_segments};
+use crate::domain::queue::InFlightTurn;
+
+/// Where a running turn speaks, when it speaks anywhere: the origin it
+/// answers back into, the person it answers, and the bot it answers as.
+struct Voice {
+ origin: AnnounceOrigin,
+ actor: MacroUserIdStr<'static>,
+ bot_id: BotId,
+}
+
+impl Voice {
+ /// A turn prompted from a discussion it answers into. An assignment's
+ /// chip is its own surface and has no reply to show.
+ fn of(flight: &InFlightTurn) -> Option<Self> {
+ let origin = flight
+ .announce
+ .as_ref()
+ .filter(|origin| !origin.reuse_origin_message)?;
+ Some(Self {
+ origin: origin.clone(),
+ actor: flight.actor.clone()?,
+ bot_id: flight.bot_id?,
+ })
+ }
+
+ fn style(&self) -> VoiceStyle {
+ self.origin.reply_placement.voice_style()
+ }
+
+ fn thread_id(&self) -> Option<macro_uuid::Uuid> {
+ self.origin.reply_placement.thread_id(self.origin.thread_id)
+ }
+
+ /// One message of the reply showing `segments`, not yet news.
+ fn presentation(
+ &self,
+ session_id: AgentSessionId,
+ turn: TurnId,
+ message_id: macro_uuid::Uuid,
+ segments: Vec<ProjectedSegment>,
+ ) -> ReplyPresentation {
+ ReplyPresentation {
+ session_id,
+ bot_id: self.bot_id,
+ triggered_by: self.actor.clone(),
+ parent: self.origin.parent.clone(),
+ thread_id: self.thread_id(),
+ message_id,
+ turn,
+ segments,
+ // A thread reply leads with its session; a private conversation's
+ // messages are the session.
+ link: self.style() == VoiceStyle::Turn,
+ pending: false,
+ outcome: None,
+ notify: false,
+ }
+ }
+}
+
+impl<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ Lifecycle,
+ Mentions,
+ Notifier,
+>
+ AgentHarnessInner<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ Lifecycle,
+ Mentions,
+ Notifier,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: MessagePromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+ Lifecycle: AgentSessionLifecyclePublisher,
+ Mentions: PromptMentions,
+ Notifier: AgentSessionNotifier,
+{
+ /// The running turn a fold report is about, when this replica
+ /// dispatched it. A report for any other turn - one resumed from
+ /// elsewhere, one nobody here prompted - has no voice to show it in.
+ fn reported_flight(
+ &self,
+ session_id: AgentSessionId,
+ turn: TurnId,
+ action_id: Option<AgentActionId>,
+ ) -> Option<InFlightTurn> {
+ let flight = self.busy.turn(session_id)?;
+ (flight.turn == turn || action_id == Some(flight.action_id)).then_some(flight)
+ }
+
+ /// The segments last reported for `turn`, or none when this replica did
+ /// not watch it run.
+ pub(super) fn reported_segments(
+ &self,
+ session_id: AgentSessionId,
+ turn: TurnId,
+ ) -> Vec<ProjectedSegment> {
+ self.projections
+ .get(&session_id)
+ .filter(|reported| reported.0 == turn)
+ .map(|reported| reported.1.clone())
+ .unwrap_or_default()
+ }
+
+ /// Show a running turn's reply as it now stands, and what the agent is
+ /// doing. Only the session's command worker calls this, so reports for
+ /// one turn are applied in the order the fold made them.
+ pub(super) async fn present_progress(
+ &self,
+ session_id: AgentSessionId,
+ turn: TurnId,
+ action_id: Option<AgentActionId>,
+ phase: Option<TurnPhase>,
+ segments: Vec<ProjectedSegment>,
+ ) {
+ let Some(mut flight) = self.reported_flight(session_id, turn, action_id) else {
+ return;
+ };
+ self.projections
+ .insert(session_id, (turn, segments.clone()));
+ let Some(voice) = Voice::of(&flight) else {
+ return;
+ };
+ if let Some(phase) = phase
+ && self.typing_phases.insert(session_id, phase) != Some(phase)
+ {
+ self.publish_typing(session_id, &flight, true).await;
+ }
+ // A closed reply is shown once, with how its turn ended, by the
+ // turn's end - which arrives right behind this report.
+ if phase.is_none() {
+ return;
+ }
+ match voice.style() {
+ VoiceStyle::Turn => {
+ // A chip renders the turn itself; there is no reply to grow.
+ if flight.speaks_as_chip {
+ return;
+ }
+ let Some(message_id) = flight.announcement_message_id else {
+ return;
+ };
+ let shown = turn_segments(&segments);
+ // The pending reply already says the turn is running; until
+ // there is something to add to it, it is left alone.
+ let untouched = !self.presented_shapes.contains_key(&message_id);
+ if (untouched && shown.is_empty()) || !self.shows_differently(message_id, &shown) {
+ return;
+ }
+ let mut presentation = voice.presentation(session_id, turn, message_id, shown);
+ presentation.pending = true;
+ self.present_reply(presentation).await;
+ }
+ VoiceStyle::Segments => {
+ let planned = plan_messages(&segments);
+ if let Err(error) = self
+ .allocate_reply_messages(session_id, &mut flight, planned.len())
+ .await
+ {
+ tracing::error!(?error, %session_id, "could not keep a reply's message ids; not showing it yet");
+ return;
+ }
+ let changed: Vec<_> = planned
+ .into_iter()
+ .zip(flight.presented.clone())
+ .filter(|(message, message_id)| {
+ message.ready && self.shows_differently(*message_id, &message.segments)
+ })
+ .collect();
+ if changed.is_empty() {
+ return;
+ }
+ // Saved with the turn before it shows, so that a replica
+ // recovering the turn after this one is gone can close every
+ // message posted so far rather than leave its steps running.
+ if let Some(store) = &self.conversation_turns
+ && let Err(error) = store.save_reply(flight.action_id, &segments).await
+ {
+ tracing::error!(?error, %session_id, "could not keep a reply's progress for recovery");
+ }
+ for (message, message_id) in changed {
+ let presentation =
+ voice.presentation(session_id, turn, message_id, message.segments);
+ self.present_reply(presentation).await;
+ }
+ }
+ }
+ }
+
+ /// Show a reply in segments once its turn has ended: every message it
+ /// takes, the last one with how the turn ended and as news. `saved` is
+ /// what the replica that watched the turn saved of the reply, for a
+ /// replica that did not watch it, or no longer remembers it.
+ ///
+ /// Returns whether everything was shown, for the durable reply record.
+ pub(super) async fn present_final(
+ &self,
+ session_id: AgentSessionId,
+ flight: &InFlightTurn,
+ outcome: ReplyOutcome,
+ saved: Vec<ProjectedSegment>,
+ ) -> bool {
+ let Some(voice) = Voice::of(flight) else {
+ return true;
+ };
+ let mut segments = self.reported_segments(session_id, flight.turn);
+ if segments.is_empty() {
+ segments = saved;
+ }
+ let planned = plan_messages(&closed(segments));
+ let mut flight = flight.clone();
+ let expected = flight.clone();
+ let count = planned.len().max(1);
+ if flight.presented.len() < count {
+ flight
+ .presented
+ .resize_with(count, macro_uuid::generate_uuid_v7);
+ flight.announcement_message_id = flight.presented.last().copied();
+ if let Some(store) = &self.conversation_turns {
+ match store
+ .record_reply_flight(flight.action_id, &expected, &flight)
+ .await
+ {
+ Ok(true) => {}
+ Ok(false) => return false,
+ Err(error) => {
+ tracing::error!(?error, %session_id, "could not reserve final reply message IDs");
+ return false;
+ }
+ }
+ }
+ }
+ if planned.is_empty() {
+ // Nothing the reply said or did can be shown, so say how the
+ // turn ended. A replica saves a reply's segments before it shows
+ // any of them, and again before its last message, so without
+ // them nothing of the reply was posted: how the turn ended is
+ // posted on its own.
+ let mut presentation =
+ voice.presentation(session_id, flight.turn, flight.presented[0], Vec::new());
+ presentation.outcome = Some(outcome);
+ presentation.notify = true;
+ return self.present_reply(presentation).await;
+ }
+ let last = planned.len() - 1;
+ let mut presented = true;
+ for (index, (message, message_id)) in planned.into_iter().zip(flight.presented).enumerate()
+ {
+ let closing = index == last;
+ if !closing && !self.shows_differently(message_id, &message.segments) {
+ continue;
+ }
+ let mut presentation =
+ voice.presentation(session_id, flight.turn, message_id, message.segments);
+ if closing {
+ presentation.outcome = Some(outcome.clone());
+ presentation.notify = true;
+ }
+ presented &= self.present_reply(presentation).await;
+ }
+ presented
+ }
+
+ /// Give every message a reply needs an id, and keep the ids with the
+ /// turn before any message is posted under one.
+ async fn allocate_reply_messages(
+ &self,
+ session_id: AgentSessionId,
+ flight: &mut InFlightTurn,
+ count: usize,
+ ) -> agent_session::domain::error::Result<()> {
+ if flight.presented.len() >= count {
+ return Ok(());
+ }
+ while flight.presented.len() < count {
+ flight.presented.push(macro_uuid::generate_uuid_v7());
+ }
+ // Downstream events name the reply's latest message.
+ flight.announcement_message_id = flight.presented.last().copied();
+ if let Some(store) = &self.conversation_turns {
+ store.record_flight(flight.action_id, flight).await?;
+ }
+ self.busy.mark_turn(session_id, flight.clone());
+ Ok(())
+ }
+
+ /// Whether `segments` would show differently from what `message_id`
+ /// last showed.
+ fn shows_differently(
+ &self,
+ message_id: macro_uuid::Uuid,
+ segments: &[ProjectedSegment],
+ ) -> bool {
+ self.presented_shapes
+ .get(&message_id)
+ .is_none_or(|shown| *shown != shape(segments))
+ }
+
+ /// Post or update one reply message. Best-effort like every reply: a
+ /// failure leaves the message as it was, and the turn's end shows the
+ /// reply again.
+ async fn present_reply(&self, presentation: ReplyPresentation) -> bool {
+ let message_id = presentation.message_id;
+ let shown = shape(&presentation.segments);
+ match self.announcer.present(presentation).await {
+ Ok(()) => {
+ self.presented_shapes.insert(message_id, shown);
+ true
+ }
+ Err(error) => {
+ tracing::error!(?error, %message_id, "failed to show an agent reply message");
+ false
+ }
+ }
+ }
+
+ /// Say that a running turn's agent is typing, or that it stopped.
+ pub(super) async fn publish_typing(
+ &self,
+ session_id: AgentSessionId,
+ flight: &InFlightTurn,
+ active: bool,
+ ) {
+ let Some(voice) = Voice::of(flight) else {
+ return;
+ };
+ let phase = self
+ .typing_phases
+ .get(&session_id)
+ .map_or(TurnPhase::Thinking, |phase| *phase);
+ let update = AgentTypingUpdate {
+ session_id,
+ bot_id: voice.bot_id,
+ triggered_by: voice.actor.clone(),
+ parent: voice.origin.parent.clone(),
+ thread_id: voice.thread_id(),
+ active,
+ phase,
+ };
+ if let Err(error) = self.announcer.typing(update).await {
+ tracing::debug!(?error, %session_id, "failed to publish an agent typing");
+ }
+ }
+
+ /// Stop a finished turn's typing and forget what its reply showed.
+ pub(super) async fn end_presentation(
+ &self,
+ session_id: AgentSessionId,
+ flight: Option<&InFlightTurn>,
+ ) {
+ if let Some(flight) = flight {
+ self.publish_typing(session_id, flight, false).await;
+ for id in flight
+ .presented
+ .iter()
+ .chain(&flight.announcement_message_id)
+ {
+ self.presented_shapes.remove(id);
+ }
+ }
+ self.typing_phases.remove(&session_id);
+ self.projections.remove(&session_id);
+ }
+}
+
+impl<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ Lifecycle,
+ Mentions,
+ Notifier,
+>
+ AgentHarnessService<
+ Sessions,
+ Containers,
+ Announcer,
+ Runtimes,
+ PromptContext,
+ PromptComposer,
+ Egress,
+ Lifecycle,
+ Mentions,
+ Notifier,
+ >
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+ PromptContext: MessagePromptContext,
+ PromptComposer: AgentPromptComposer,
+ Egress: SandboxEgressProvisioner,
+ Lifecycle: AgentSessionLifecyclePublisher,
+ Mentions: PromptMentions,
+ Notifier: AgentSessionNotifier,
+{
+ /// Refresh the typing indicator of every turn running on this replica.
+ ///
+ /// Viewers drop an indicator nobody refreshes, so this runs on a timer
+ /// shorter than their timeout, and a turn whose replica died stops
+ /// showing as typing on its own.
+ pub async fn refresh_typing(&self) {
+ for (session_id, flight) in self.inner.busy.running() {
+ self.inner.publish_typing(session_id, &flight, true).await;
+ }
+ }
+}
diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rs
index 4bbd6b5702..d408cbd977 100644
--- a/crates/agent_harness/src/domain/service/queue.rs
+++ b/crates/agent_harness/src/domain/service/queue.rs
@@ -9,6 +9,7 @@ use agent_session::domain::events::{
WaitingForInputMetadata,
};
use agent_session::domain::model::{StoredQueuedAction, TurnPrompter};
+use futures::future::BoxFuture;
use super::*;
@@ -236,13 +237,28 @@ where
SessionManagement::Unmanaged => {
span.record("agent.session.management", "unmanaged");
span.record("agent.command.forwarded", false);
- let session = self.sessions.get_session(session_id).await?;
- if AgentKind::for_session(session.bot_id, &session.harness) != AgentKind::External {
+ // A new conversation has a reserved id but no session row yet. External
+ // personas still route to the replica holding their connection;
+ // an existing session uses its pinned harness configuration.
+ let (bot_id, kind) = match self.sessions.get_session(session_id).await {
+ Ok(session) => (
+ session.bot_id,
+ AgentKind::for_session(session.bot_id, &session.harness),
+ ),
+ Err(AgentSessionError::NotFound(_)) => match &command {
+ HarnessCommand::ConversationMessage(open) => {
+ (open.bot_id, open.runtime.kind)
+ }
+ _ => return Err(AgentSessionError::NotFound(session_id).into()),
+ },
+ Err(error) => return Err(error.into()),
+ };
+ if kind != AgentKind::External {
return self.execute(session_id, command).await;
}
let Some(harness) = self
.runtimes
- .bound_harness(session.bot_id)
+ .bound_harness(bot_id)
.await
.map_err(AgentSessionError::Unknown)?
else {
@@ -284,11 +300,98 @@ where
.await
}
- pub(super) async fn execute(
+ /// Run one command; see [`Self::execute_unboxed`].
+ ///
+ /// Boxed, like [`Self::dispatch_next`]: unoptimized builds give every
+ /// awaited future its own slot in the awaiting frame, and the routing and
+ /// worker code await a command in several places, each of which would
+ /// otherwise hold a copy of this large future on the stack.
+ pub(super) fn execute(
+ &self,
+ session_id: AgentSessionId,
+ command: HarnessCommand,
+ ) -> BoxFuture<'_, Result<CommandOutcome>> {
+ Box::pin(self.execute_unboxed(session_id, command))
+ }
+
+ async fn execute_unboxed(
&self,
session_id: AgentSessionId,
command: HarnessCommand,
) -> Result<CommandOutcome> {
+ // A conversation reserves its identity before startup. Commands are serialized
+ // under that identity, so only the first opens; every later post is a
+ // regular queued turn, including after the runtime has disconnected.
+ let mut _delivery_lease = None;
+ let command = match command {
+ HarnessCommand::ConversationMessage(mut open) => {
+ let mut origin = open.origin.announcement();
+ if origin.reply_placement != crate::domain::model::ReplyPlacement::Timeline {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ let mut action_id = AgentActionId::from_uuid(origin.message_id);
+ if let Some(policy) = &self.conversations
+ && !policy
+ .authorize_prompt(session_id, open.bot_id, Some(open.origin.actor()))
+ .await?
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ if let Some(store) = &self.conversation_turns {
+ let messages::domain::models::MessageParent::Channel(channel) = origin.parent
+ else {
+ return Err(AgentSessionError::Forbidden.into());
+ };
+ let record = store.admit(session_id, channel, open.clone()).await?;
+ if record.state
+ != crate::domain::conversation_turns::ConversationTurnState::Queued
+ || record.session_id != session_id
+ {
+ return Ok(CommandOutcome::Completed);
+ }
+ open = record.command;
+ origin = open.origin.announcement();
+ action_id = record.action_id;
+ }
+ // Only a bootstrap takes the delivery lease: until the session
+ // opens it has no manager to route to, while an open session's
+ // turns are already serialized by its queue and its journal
+ // claims. Holding the lease, look again: another replica may
+ // have opened the session meanwhile.
+ let mut session = self.sessions.get_session(session_id).await;
+ if matches!(session, Err(AgentSessionError::NotFound(_)))
+ && let Some(store) = &self.conversation_turns
+ {
+ _delivery_lease = store.claim_delivery(session_id).await?;
+ if _delivery_lease.is_none() {
+ // Already durable; recovery routes it to the manager
+ // after the other replica finishes bootstrapping.
+ return Ok(CommandOutcome::Queued);
+ }
+ session = self.sessions.get_session(session_id).await;
+ }
+ match session {
+ Ok(session) => {
+ if session.bot_id != open.bot_id
+ || !session.owner_id.is_user(open.origin.actor())
+ {
+ return Err(AgentSessionError::Forbidden.into());
+ }
+ let context = open.origin.context().cloned();
+ HarnessCommand::Deliver(DeliverAction {
+ id: action_id,
+ actor: Some(open.origin.actor().clone()),
+ action: open.origin.into_action(),
+ announce: Some(origin),
+ context,
+ })
+ }
+ Err(AgentSessionError::NotFound(_)) => HarnessCommand::Open(open),
+ Err(error) => return Err(error.into()),
+ }
+ }
+ command => command,
+ };
// Persist-as-we-go needs a current working copy before the first
// mutation, or a restart would overwrite the store with an empty
// queue. Open creates the row and has nothing to restore.
@@ -338,6 +441,7 @@ where
}
}
HarnessCommand::Open(_)
+ | HarnessCommand::ConversationMessage(_)
| HarnessCommand::Turn(_)
| HarnessCommand::ToolApproval(_)
| HarnessCommand::SessionStopped { .. }
@@ -350,6 +454,9 @@ where
}
match command {
+ HarnessCommand::ConversationMessage(_) => {
+ unreachable!("conversation messages were normalized before dispatch")
+ }
HarnessCommand::Open(command) => {
self.open(session_id, command).await?;
Ok(CommandOutcome::Completed)
@@ -394,7 +501,77 @@ where
action_id: fold_action_id,
..
}) => {
- let ended = self.busy.take(session_id);
+ let mut ended = self.busy.turn(session_id);
+ if let (Some(turn), Some(action)) = (&ended, fold_action_id)
+ && turn.action_id != action
+ {
+ tracing::warn!(%session_id, %action, "ignoring a stale turn end");
+ return Ok(CommandOutcome::Completed);
+ }
+ // The journal is told before the turn's mark is released, but
+ // a failure to tell it is logged, not returned: the session
+ // must still drain, and recovery marks a turn left running as
+ // interrupted.
+ if let Some(store) = &self.conversation_turns {
+ if ended.is_none()
+ && let Some(action) = fold_action_id
+ {
+ match store.by_action(action).await {
+ Ok(record) => {
+ ended = record
+ .filter(|record| record.session_id == session_id)
+ .and_then(|record| record.in_flight);
+ }
+ Err(error) => tracing::error!(
+ ?error,
+ %session_id,
+ %action,
+ "could not read the conversation turn that ended"
+ ),
+ }
+ }
+ if let Some(turn) = &ended {
+ // Saved before the outcome makes the reply due, so any
+ // replica that reconciles it shows what this one watched.
+ let reply = self.reported_segments(session_id, turn.turn);
+ if !reply.is_empty()
+ && turn.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement
+ == crate::domain::model::ReplyPlacement::Timeline
+ })
+ && let Err(error) = store.save_reply(turn.action_id, &reply).await
+ {
+ tracing::error!(?error, %session_id, "could not save a finished conversation reply");
+ }
+ let state = match &stop {
+ StopReason::Cancelled => {
+ crate::domain::conversation_turns::ConversationTurnState::Stopped
+ }
+ StopReason::Failed { .. } => {
+ crate::domain::conversation_turns::ConversationTurnState::Failed
+ }
+ _ => {
+ crate::domain::conversation_turns::ConversationTurnState::Succeeded
+ }
+ };
+ if let Err(error) = store
+ .finish(
+ turn.action_id,
+ state,
+ ReplyOutcome::of_turn(&stop, last_text.clone()),
+ )
+ .await
+ {
+ tracing::error!(
+ ?error,
+ %session_id,
+ action_id = %turn.action_id,
+ "could not record how a conversation turn ended"
+ );
+ }
+ }
+ }
+ self.busy.take(session_id);
// A turn end with no record: this replica restarted mid-turn
// and the in-memory mark went with it, or the fold closed a
// turn nobody here prompted. The queue still drains; only the
@@ -414,6 +591,8 @@ where
ReplyOutcome::of_turn(&stop, last_text.clone()),
)
.await;
+ // The answer is showing: the bot stops typing.
+ self.end_presentation(session_id, ended.as_ref()).await;
if let (Some(turn), Some(fold_action_id)) = (&ended, fold_action_id)
&& turn.action_id != fold_action_id
{
@@ -467,9 +646,32 @@ where
HarnessCommand::SessionStopped { reason } => {
let in_flight = self.busy.take(session_id);
// No `TurnEnded` follows a death, so this is the turn's last
- // chance to stop its pending reply spinning.
+ // chance to stop its pending reply spinning, and to tell the
+ // journal it failed before recovery takes it for interrupted.
+ if let (Some(store), Some(turn)) = (&self.conversation_turns, &in_flight) {
+ let reply = self.reported_segments(session_id, turn.turn);
+ if !reply.is_empty()
+ && turn.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ })
+ && let Err(error) = store.save_reply(turn.action_id, &reply).await
+ {
+ tracing::error!(?error, %session_id, "could not save a stopped conversation reply");
+ }
+ if let Err(error) = store
+ .finish(
+ turn.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await
+ {
+ tracing::error!(?error, %session_id, "could not record a conversation turn its session stopped under");
+ }
+ }
self.resolve_reply(session_id, in_flight.as_ref(), ReplyOutcome::Failed)
.await;
+ self.end_presentation(session_id, in_flight.as_ref()).await;
self.publish_lifecycle(session_id, |identity| {
AgentSessionLifecycleEvent::Stopped(SessionStoppedMetadata {
identity,
@@ -480,6 +682,16 @@ where
.await;
Ok(CommandOutcome::Completed)
}
+ HarnessCommand::Turn(TurnSignal::Progressed {
+ turn,
+ action_id,
+ phase,
+ segments,
+ }) => {
+ self.present_progress(session_id, turn, action_id, phase, segments)
+ .await;
+ Ok(CommandOutcome::Completed)
+ }
HarnessCommand::Turn(TurnSignal::ElicitationRaised { question, .. }) => {
let Some(turn) = self.busy.turn(session_id) else {
tracing::warn!(%session_id, "elicitation raised with no in-flight record");
@@ -599,6 +811,16 @@ where
self.authorize_action(&command).await?;
let action_id = command.id;
if self.queues.contains(session_id, action_id) {
+ if command.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ }) && !self.busy.is_pending(session_id)
+ {
+ self.busy.admit(session_id);
+ if let Err(error) = self.dispatch_next(session_id).await {
+ self.busy.clear(session_id);
+ return Err(error);
+ }
+ }
return Ok(CommandOutcome::Queued);
}
if self
@@ -632,7 +854,17 @@ where
let actor = command.actor.clone();
let announce = command.announce.clone();
let action = command.action.clone();
- let steers = announce.is_some() && self.busy.turn(session_id).is_some();
+ let steers = announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Thread
+ }) && self.busy.turn(session_id).is_some();
+ let dm_record = if announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ }) && let Some(store) = &self.conversation_turns
+ {
+ store.by_action(action_id).await?
+ } else {
+ None
+ };
let entry = QueuedEntry {
action_id,
action: command.action,
@@ -640,9 +872,13 @@ where
announce: command.announce,
context: command.context,
announced: None,
- created_at: chrono::Utc::now(),
+ created_at: dm_record
+ .as_ref()
+ .map_or_else(chrono::Utc::now, |record| record.created_at),
};
- let enqueued = if steers {
+ let enqueued = if dm_record.is_some() {
+ self.queues.enqueue_chronological(session_id, entry)
+ } else if steers {
self.queues.enqueue_front(session_id, entry)
} else {
self.queues.enqueue(session_id, entry)
@@ -944,6 +1180,20 @@ where
});
}
+ /// Dispatch the next queued entry; see [`Self::dispatch_unboxed`].
+ ///
+ /// Boxed so the dispatch's large future lives on the heap rather than in
+ /// every frame that awaits it. Unoptimized builds give each awaited
+ /// future its own stack slot, and a direct message's first turn nests
+ /// open, dispatch, and delivery inside one command - deep enough to
+ /// overflow a worker thread's stack in a local build.
+ pub(super) fn dispatch_next(
+ &self,
+ session_id: AgentSessionId,
+ ) -> BoxFuture<'_, Result<Dispatch>> {
+ Box::pin(self.dispatch_unboxed(session_id))
+ }
+
/// Deliver the oldest queued action, marking the session busy on success.
///
/// Composition runs first so a lexical failure never posts a chip for a
@@ -957,149 +1207,301 @@ where
/// A failed dispatch puts the entry back at the front: it stays next in
/// line for the next turn end or the next prompt, and stays visible in
/// the queue meanwhile. The error still propagates, so a caller whose
- /// own action triggered this dispatch hears about it.
- #[tracing::instrument(err, skip(self), fields(%session_id))]
- pub(super) async fn dispatch_next(&self, session_id: AgentSessionId) -> Result<Dispatch> {
- if self.sessions.get_session(session_id).await?.is_archived {
+ /// own action triggered this dispatch hears about it. A conversation
+ /// message that can never run is not put back: one its journal no longer
+ /// holds as waiting is dropped, one whose origin is gone fails, and the
+ /// next entry dispatches in its place.
+ #[tracing::instrument(name = "dispatch_next", err, skip(self), fields(%session_id))]
+ async fn dispatch_unboxed(&self, session_id: AgentSessionId) -> Result<Dispatch> {
+ let session = self.sessions.get_session(session_id).await?;
+ if session.is_archived {
self.queues.drop_session(session_id);
self.write_queue(session_id).await?;
self.publish_queue(session_id).await;
return Ok(Dispatch::QueueEmpty);
}
if self.queues.list(session_id).is_empty() {
+ self.busy.clear(session_id);
return Ok(Dispatch::QueueEmpty);
}
self.revalidate_queue(session_id).await?;
- let Some(mut entry) = self.queues.claim_next(session_id) else {
- return Ok(Dispatch::QueueEmpty);
- };
- // Persist the remaining queue before any fallible work: a crash after
- // this leaves the claimed entry as in-flight (lost, like the turn
- // mark) and keeps every still-waiting action.
- if let Err(error) = self.write_queue(session_id).await {
- self.queues.requeue_front(session_id, entry);
- return Err(error);
- }
+ loop {
+ let Some(mut entry) = self.queues.claim_next(session_id) else {
+ self.busy.clear(session_id);
+ return Ok(Dispatch::QueueEmpty);
+ };
+ // Persist the remaining queue before any fallible work: a crash after
+ // this leaves the claimed entry as in-flight (lost, like the turn
+ // mark) and keeps every still-waiting action.
+ if let Err(error) = self.write_queue(session_id).await {
+ self.queues.requeue_front(session_id, entry);
+ return Err(error);
+ }
- // The turn this action opens, read before delivery appends the
- // prompt to the log. Unchanged across a failed attempt, so a retry
- // reports the same turn.
- let prompted_message_id = match self.sessions.next_prompt_message_id(session_id).await {
- Ok(message_id) => message_id,
- Err(error) => {
- self.requeue_claimed(session_id, entry).await?;
- return Err(error.into());
+ let conversation_store = self.conversation_turns.as_ref().filter(|_| {
+ entry.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement == crate::domain::model::ReplyPlacement::Timeline
+ })
+ });
+ // A conversation message's journal says whether it still waits.
+ // One whose turn already ended - failed, stopped when its owner
+ // started fresh, or retried under a new id - is dropped, not run.
+ if let Some(store) = conversation_store {
+ match store.by_action(entry.action_id).await {
+ Ok(Some(record))
+ if record.state
+ == crate::domain::conversation_turns::ConversationTurnState::Queued => {
+ }
+ Ok(_) => continue,
+ Err(error) => {
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error.into());
+ }
+ }
}
- };
- // Compose a copy: the queued entry stays raw so a retry still edits
- // and re-composes the user's text, and the chip (below) still shows
- // what they typed rather than the composed payload.
- let mut composed = entry.action.clone();
- if let Err(error) = self
- .compose_action(
- session_id,
- &mut composed,
- entry.actor.as_ref(),
- entry.announce.as_ref(),
- entry.context.as_ref(),
- prompted_message_id.turn == TurnId(0),
- )
- .await
- {
- self.requeue_claimed(session_id, entry).await?;
- return Err(error);
- }
+ // The turn this action opens, read before delivery appends the
+ // prompt to the log. Unchanged across a failed attempt, so a retry
+ // reports the same turn.
+ let prompted_message_id = match self.sessions.next_prompt_message_id(session_id).await {
+ Ok(message_id) => message_id,
+ Err(error) => {
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error.into());
+ }
+ };
- if let Err(error) = self.admit_session_id(session_id).await {
- self.requeue_claimed(session_id, entry).await?;
- self.reject_waiting_on_denial(session_id, &error).await?;
- return Err(error);
- }
- if entry.announced.is_none() {
- let announcement = match self
- .announcement(
+ // Compose a copy: the queued entry stays raw so a retry still edits
+ // and re-composes the user's text, and the chip (below) still shows
+ // what they typed rather than the composed payload.
+ let mut composed = entry.action.clone();
+ if let Err(error) = self
+ .compose_action(
session_id,
- &entry.action,
+ &mut composed,
entry.actor.as_ref(),
- entry.announce.clone(),
- prompted_message_id,
+ entry.announce.as_ref(),
+ entry.context.as_ref(),
+ prompted_message_id.turn == TurnId(0),
)
.await
{
- Ok(announcement) => announcement,
- Err(error) => {
- self.requeue_claimed(session_id, entry).await?;
- return Err(error);
+ // A conversation message whose origin is gone - deleted,
+ // moved, or no longer its sender's to answer - can never be
+ // composed, and put back it would hold every message behind
+ // it. Its turn fails instead, and the next message dispatches.
+ if let (HarnessError::InvalidOrigin(_), Some(store)) = (&error, conversation_store)
+ {
+ tracing::warn!(
+ ?error,
+ %session_id,
+ action_id = %entry.action_id,
+ "dropping a conversation message whose origin is gone"
+ );
+ store.fail_queued(entry.action_id).await?;
+ store
+ .finalize_reply(entry.action_id, &ReplyOutcome::Failed)
+ .await?;
+ continue;
+ }
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error);
+ }
+
+ if let Err(error) = self.admit_session_id(session_id).await {
+ self.requeue_claimed(session_id, entry).await?;
+ self.reject_waiting_on_denial(session_id, &error).await?;
+ return Err(error);
+ }
+
+ // A reply shown in segments posts nothing until the agent has
+ // something to say or do: the bot types meanwhile.
+ let in_segments = entry.announce.as_ref().is_some_and(|origin| {
+ origin.reply_placement.voice_style() == crate::domain::model::VoiceStyle::Segments
+ });
+ let speaks_as_chip = match &entry.announce {
+ Some(origin) if origin.reuse_origin_message => true,
+ Some(origin)
+ if origin.reply_placement == crate::domain::model::ReplyPlacement::Thread =>
+ {
+ // Unknown is treated as a chip: a chip's message is never
+ // rewritten into a reply, which is the safe mistake.
+ self.reply_persona(&session)
+ .await
+ .map_or(true, |persona| persona.is_coding)
}
+ _ => false,
+ };
+ let mut flight = InFlightTurn {
+ action_id: entry.action_id,
+ turn: prompted_message_id.turn,
+ actor: entry.actor.clone(),
+ announce: entry.announce.clone(),
+ announcement_message_id: entry.announced,
+ dispatched_at: chrono::Utc::now(),
+ bot_id: Some(session.bot_id),
+ speaks_as_chip,
+ presented: Vec::new(),
+ held_tool_calls: Vec::new(),
};
- if let Some(announcement) = announcement {
- match self.announcer.announce(announcement).await {
- Ok(announced) => entry.announced = Some(announced.message_id),
+ if let Some(store) = conversation_store {
+ match store.claim(entry.action_id, &flight).await {
+ Ok(true) => {}
+ Ok(false) => {
+ if store
+ .by_action(entry.action_id)
+ .await?
+ .is_some_and(|record| {
+ record.state == crate::domain::conversation_turns::ConversationTurnState::Queued
+ })
+ {
+ self.requeue_claimed(session_id, entry).await?;
+ self.busy.clear(session_id);
+ return Ok(Dispatch::QueueEmpty);
+ }
+ continue;
+ }
Err(error) => {
self.requeue_claimed(session_id, entry).await?;
- return Err(error);
+ return Err(error.into());
}
}
}
- }
-
- // Recorded before delivery, since the runtime may call a tool the
- // moment the prompt lands: the egress proxy judges every call by who
- // prompted the turn it belongs to, and it may be serving the call on
- // another replica.
- if let Err(error) = self
- .sessions
- .set_turn_prompter(
- session_id,
- &TurnPrompter {
- action_id: entry.action_id,
- user: entry.actor.clone(),
- },
- )
- .await
- {
- self.requeue_claimed(session_id, entry).await?;
- return Err(error.into());
- }
- let command = DeliverAction {
- id: entry.action_id,
- action: composed,
- actor: entry.actor.clone(),
- announce: entry.announce.clone(),
- // Already composed into the action above.
- context: None,
- };
- match self.deliver(session_id, command).await {
- Ok(()) => {
- let turn = InFlightTurn {
- action_id: entry.action_id,
- turn: prompted_message_id.turn,
- actor: entry.actor,
- announce: entry.announce,
- announcement_message_id: entry.announced,
- dispatched_at: chrono::Utc::now(),
- held_tool_calls: Vec::new(),
+ if entry.announced.is_none() && !in_segments {
+ let announcement = match self
+ .announcement(
+ session_id,
+ &entry.action,
+ entry.actor.as_ref(),
+ entry.announce.clone(),
+ prompted_message_id,
+ )
+ .await
+ {
+ Ok(announcement) => announcement,
+ Err(error) => {
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error);
+ }
};
- self.busy.mark_turn(session_id, turn.clone());
- self.publish_lifecycle(session_id, |identity| {
- AgentSessionLifecycleEvent::TurnStarted(TurnStartedMetadata {
- identity,
- turn: turn.turn,
- action_id: turn.action_id,
- actor: turn.actor,
- announcement_message_id: turn.announcement_message_id,
- })
- })
- .await;
- Ok(Dispatch::Dispatched)
+ if let Some(mut announcement) = announcement {
+ announcement.reply_message_id = flight.announcement_message_id;
+ match self.announcer.announce(announcement).await {
+ Ok(announced) => entry.announced = Some(announced.message_id),
+ Err(error) => {
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error);
+ }
+ }
+ }
+ }
+
+ // Recorded before delivery, since the runtime may call a tool the
+ // moment the prompt lands: the egress proxy judges every call by who
+ // prompted the turn it belongs to, and it may be serving the call on
+ // another replica.
+ if let Err(error) = self
+ .sessions
+ .set_turn_prompter(
+ session_id,
+ &TurnPrompter {
+ action_id: entry.action_id,
+ user: entry.actor.clone(),
+ },
+ )
+ .await
+ {
+ // A claimed conversation turn fails as an undelivered one
+ // does, so its journal never shows it running.
+ if let Some(store) = conversation_store {
+ store
+ .finish(
+ entry.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await?;
+ self.resolve_reply(session_id, Some(&flight), ReplyOutcome::Failed)
+ .await;
+ }
+ self.requeue_claimed(session_id, entry).await?;
+ return Err(error.into());
}
- Err(error) => {
+
+ let command = DeliverAction {
+ id: entry.action_id,
+ action: composed,
+ actor: entry.actor.clone(),
+ announce: entry.announce.clone(),
+ // Already composed into the action above.
+ context: None,
+ };
+ flight.announcement_message_id = entry.announced;
+ if let Some(store) = conversation_store
+ && let Err(error) = store.record_flight(entry.action_id, &flight).await
+ {
+ // Claimed but never delivered: it fails like an undelivered turn.
+ if let Err(error) = store
+ .finish(
+ entry.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await
+ {
+ tracing::error!(?error, %session_id, "failed to persist an undelivered conversation turn");
+ }
+ self.resolve_reply(session_id, Some(&flight), ReplyOutcome::Failed)
+ .await;
self.requeue_claimed(session_id, entry).await?;
- self.reject_waiting_on_denial(session_id, &error).await?;
- Err(error)
+ return Err(error.into());
}
+ return match self.deliver(session_id, command).await {
+ Ok(()) => {
+ let turn = InFlightTurn {
+ action_id: entry.action_id,
+ turn: prompted_message_id.turn,
+ actor: entry.actor,
+ announce: entry.announce,
+ announcement_message_id: entry.announced,
+ dispatched_at: chrono::Utc::now(),
+ bot_id: flight.bot_id,
+ speaks_as_chip: flight.speaks_as_chip,
+ presented: flight.presented.clone(),
+ held_tool_calls: Vec::new(),
+ };
+ self.busy.mark_turn(session_id, turn.clone());
+ self.publish_typing(session_id, &turn, true).await;
+ self.publish_lifecycle(session_id, |identity| {
+ AgentSessionLifecycleEvent::TurnStarted(TurnStartedMetadata {
+ identity,
+ turn: turn.turn,
+ action_id: turn.action_id,
+ actor: turn.actor,
+ announcement_message_id: turn.announcement_message_id,
+ })
+ })
+ .await;
+ Ok(Dispatch::Dispatched)
+ }
+ Err(error) => {
+ if let Some(store) = conversation_store {
+ store
+ .finish(
+ entry.action_id,
+ crate::domain::conversation_turns::ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await?;
+ self.resolve_reply(session_id, Some(&flight), ReplyOutcome::Failed)
+ .await;
+ }
+ self.requeue_claimed(session_id, entry).await?;
+ self.reject_waiting_on_denial(session_id, &error).await?;
+ Err(error)
+ }
+ };
}
}
}
@@ -1133,6 +1535,20 @@ pub(super) fn queue_result<T>(
})
}
+/// Whether a conversation message that failed to execute stays queued for
+/// recovery, because the failure means another replica will run it.
+fn leaves_turn_queued(error: &HarnessError) -> bool {
+ matches!(
+ error,
+ HarnessError::Forward(_)
+ | HarnessError::Session(
+ AgentSessionError::Draining(_)
+ | AgentSessionError::ManagedElsewhere(_)
+ | AgentSessionError::FencedOut(_)
+ )
+ )
+}
+
pub(super) async fn run_session_worker<
Sessions,
Containers,
@@ -1178,6 +1594,21 @@ pub(super) async fn run_session_worker<
span,
route,
} = queued;
+ let conversation_action = match (&command, &inner.conversation_turns) {
+ (HarnessCommand::ConversationMessage(open), Some(store)) => {
+ match store
+ .get(open.origin.announcement().message_id, open.bot_id)
+ .await
+ {
+ Ok(record) => record.map(|record| record.action_id),
+ Err(error) => {
+ let _ = completed.send(Err(error.into()));
+ continue;
+ }
+ }
+ }
+ _ => None,
+ };
let result = if route {
inner
.route_then_execute(session_id, command)
@@ -1186,6 +1617,13 @@ pub(super) async fn run_session_worker<
} else {
inner.execute(session_id, command).instrument(span).await
};
+ if let Err(error) = &result
+ && !leaves_turn_queued(error)
+ && let (Some(action), Some(store)) = (conversation_action, &inner.conversation_turns)
+ && let Err(error) = store.fail_queued(action).await
+ {
+ tracing::error!(?error, %session_id, "failed to persist conversation command failure");
+ }
let _ = completed.send(result);
}
}
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 5bd39ca10c..c4ea6bb784 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -104,6 +104,7 @@ fn open_command() -> OpenSession {
mcp_servers: AgentMcpServers::OwnerConnections,
},
origin: SessionOrigin::Mention(MentionOrigin {
+ reply_placement: Default::default(),
parent: MessageParent::Channel(macro_uuid::generate_uuid_v7()),
thread_id,
message_id: thread_id,
@@ -160,6 +161,7 @@ fn forward_message(content: &str) -> DeliverAction {
AgentAction::prompt(content),
Some(staff_sender()),
Some(AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xf0)),
thread_id: macro_uuid::Uuid::from_u128(0xf1),
@@ -173,6 +175,8 @@ fn forward_message(content: &str) -> DeliverAction {
struct PromptContextMock {
unauthorized: Arc<Mutex<Option<String>>>,
authorized: Arc<Mutex<Vec<(MacroUserIdStr<'static>, AnnounceOrigin)>>>,
+ /// Messages deleted since they were posted.
+ deleted: Arc<Mutex<Vec<macro_uuid::Uuid>>>,
}
impl PromptContextMock {
@@ -186,6 +190,11 @@ impl PromptContextMock {
fn authorized(&self) -> Vec<(MacroUserIdStr<'static>, AnnounceOrigin)> {
self.authorized.lock().unwrap().clone()
}
+
+ /// Delete a posted message: an origin naming it is no longer valid.
+ fn delete(&self, message_id: macro_uuid::Uuid) {
+ self.deleted.lock().unwrap().push(message_id);
+ }
}
impl MessagePromptContext for PromptContextMock {
@@ -197,6 +206,11 @@ impl MessagePromptContext for PromptContextMock {
if let Some(message) = self.unauthorized.lock().unwrap().clone() {
return Err(HarnessError::PromptContext(rootcause::report!("{message}")));
}
+ if self.deleted.lock().unwrap().contains(&origin.message_id) {
+ return Err(HarnessError::InvalidOrigin(rootcause::report!(
+ "the message was deleted"
+ )));
+ }
self.authorized
.lock()
.unwrap()
@@ -484,6 +498,52 @@ fn harness_with_ports(
coding_agents: impl crate::domain::ports::CodingAgentSource,
mentions: PromptMentionsMock,
egress: EgressProvisionerMock,
+) -> (TestBench, TurnSignals) {
+ harness_with_ports_and_journal(
+ prompt_context,
+ prompt_composer,
+ permission_policies,
+ coding_agents,
+ mentions,
+ egress,
+ None,
+ )
+}
+
+fn harness_with_ports_and_journal(
+ prompt_context: PromptContextMock,
+ prompt_composer: PromptComposerMock,
+ permission_policies: impl crate::domain::ports::PermissionPolicySource,
+ coding_agents: impl crate::domain::ports::CodingAgentSource,
+ mentions: PromptMentionsMock,
+ egress: EgressProvisionerMock,
+ journal: Option<Arc<dyn crate::domain::conversation_turns::ConversationTurnStore>>,
+) -> (TestBench, TurnSignals) {
+ harness_with_journal_and_policy(
+ prompt_context,
+ prompt_composer,
+ permission_policies,
+ coding_agents,
+ mentions,
+ egress,
+ journal,
+ None,
+ )
+}
+
+#[expect(
+ clippy::too_many_arguments,
+ reason = "the test harness accepts independently replaceable ports"
+)]
+fn harness_with_journal_and_policy(
+ prompt_context: PromptContextMock,
+ prompt_composer: PromptComposerMock,
+ permission_policies: impl crate::domain::ports::PermissionPolicySource,
+ coding_agents: impl crate::domain::ports::CodingAgentSource,
+ mentions: PromptMentionsMock,
+ egress: EgressProvisionerMock,
+ journal: Option<Arc<dyn crate::domain::conversation_turns::ConversationTurnStore>>,
+ policy: Option<Arc<dyn crate::domain::conversations::ConversationPolicy>>,
) -> (TestBench, TurnSignals) {
let repo = InMemoryAgentSessionRepo::new();
let containers = MockContainerManager::new();
@@ -497,6 +557,7 @@ fn harness_with_ports(
let lifecycle = RecordingLifecyclePublisher::new();
let notifier = NotifierMock::new();
let service = AgentHarnessService::new(
+ policy,
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
@@ -535,6 +596,10 @@ fn harness_with_ports(
mentions,
notifier.clone(),
);
+ let service = match journal {
+ Some(journal) => service.with_conversation_turns(journal),
+ None => service,
+ };
let (ended, ended_rx) = mpsc::unbounded_channel();
turn_observer.bind(SignallingTurnObserver {
harness: service.clone(),
@@ -574,6 +639,7 @@ fn harness_sharing_repo(repo: InMemoryAgentSessionRepo) -> TestHarness {
let lifecycle = RecordingLifecyclePublisher::new();
let runtimes = RuntimeRegistry::new();
let service = AgentHarnessService::new(
+ None,
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo),
@@ -680,16 +746,49 @@ async fn disconnected_session_owned_by(
repo: &InMemoryAgentSessionRepo,
containers: &MockContainerManager,
owner: model_owner::Owner,
+) -> AgentSessionId {
+ // The coder bot: resume-on-disconnect only exists for managed sessions.
+ disconnected_session_of(
+ repo,
+ containers,
+ owner,
+ bot_id::MACRO_CODER_BOT_ID,
+ AgentKind::SandboxedCoder,
+ )
+ .await
+}
+
+/// [`disconnected_session`] served by Macro's in-process agent.
+async fn disconnected_in_memory_session(
+ repo: &InMemoryAgentSessionRepo,
+ containers: &MockContainerManager,
+) -> AgentSessionId {
+ let command = open_command();
+ let origin = mention_origin(&command);
+ disconnected_session_of(
+ repo,
+ containers,
+ model_owner::Owner::User(origin.sender.clone()),
+ bot_id::MACRO_NEW_BOT_ID,
+ AgentKind::InMemory,
+ )
+ .await
+}
+
+async fn disconnected_session_of(
+ repo: &InMemoryAgentSessionRepo,
+ containers: &MockContainerManager,
+ owner: model_owner::Owner,
+ bot_id: BotId,
+ kind: AgentKind,
) -> AgentSessionId {
let command = open_command();
let origin = mention_origin(&command);
- // The coder bot: resume-on-disconnect only exists for managed sessions.
- let bot_id = bot_id::MACRO_CODER_BOT_ID;
let id = AgentSessionId::new();
agent_session::domain::ports::AgentSessionRepo::create(
repo,
CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: owner,
@@ -697,7 +796,12 @@ async fn disconnected_session_owned_by(
thread_id: Some(origin.thread_id),
originating_message_id: Some(origin.message_id),
model: "claude".to_owned(),
- harness: "opencode".to_owned(),
+ harness: if kind == AgentKind::InMemory {
+ "in-memory"
+ } else {
+ "opencode"
+ }
+ .to_owned(),
repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
workspace: "/workspace".to_owned(),
sandbox_size: agent_session::domain::model::SandboxSize::Default,
@@ -714,7 +818,7 @@ async fn disconnected_session_owned_by(
containers
.spawn(SpawnContainer {
session_id: id,
- kind: AgentKind::SandboxedCoder,
+ kind,
size: agent_session::domain::model::SandboxSize::Default,
egress: test_egress(),
})
@@ -1070,6 +1174,7 @@ async fn a_mention_its_sender_is_not_set_up_for_is_declined_in_the_thread() {
[DeclinedMention {
bot_id,
origin: AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: origin.parent,
thread_id: origin.thread_id,
@@ -1497,6 +1602,54 @@ async fn forward_to_a_disconnected_session_resumes_acp_and_delivers_the_prompt()
})
.count();
assert_eq!(prompt_logs, 1);
+ assert!(
+ service.inner.egress.provisioned().is_empty(),
+ "a sandbox's own token is restored, not replaced"
+ );
+}
+
+/// The in-process agent keeps its egress token only in the process that
+/// spawned it, and every turn refreshes its tools with the advertised
+/// credential. Resumed after a restart, it gets a new token, or it could not
+/// take a turn at all.
+#[tokio::test]
+async fn resuming_an_in_memory_session_after_a_restart_mints_a_new_token() {
+ let (service, repo, containers, _announcer, _runtimes) = harness();
+ let id = disconnected_in_memory_session(&repo, &containers).await;
+ containers.lose_tokens();
+
+ let forward = service.execute(
+ id,
+ HarnessCommand::Deliver(forward_message("continue after the restart")),
+ );
+ let drive_resume = async {
+ while containers.resumed() == 0 {
+ tokio::task::yield_now().await;
+ }
+ let resumed = containers
+ .container(id)
+ .expect("the resumed container is findable");
+ complete_resume(&resumed).await;
+ resumed
+ };
+ let (forwarded, resumed) = tokio::join!(forward, drive_resume);
+ forwarded.expect("forward should resume and deliver the prompt");
+
+ assert_eq!(service.inner.egress.provisioned().len(), 1);
+ assert_eq!(
+ repo.find_by_egress_token_hash("test-token-hash")
+ .await
+ .unwrap()
+ .expect("the row carries the new token's hash")
+ .id,
+ id
+ );
+ let ClientRequest::ResumeSessionRequest(request) = &resumed.agent().received_requests()[1]
+ else {
+ panic!("the session is resumed over ACP");
+ };
+ assert!(!request.mcp_servers.is_empty());
+ assert_eq!(request.mcp_servers, test_egress().acp_servers());
}
#[tokio::test]
@@ -3240,6 +3393,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
let containers = MockContainerManager::new();
let inmem_bot = BotId::TEST_B;
let service = AgentHarnessService::new(
+ None,
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
@@ -3426,6 +3580,7 @@ async fn an_external_prompt_announce_posts_into_the_observed_origin() {
crate::domain::model::AnnouncePrompt {
bot_id: bot,
origin: AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA)),
thread_id: macro_uuid::Uuid::from_u128(0xAB),
@@ -3467,6 +3622,7 @@ async fn an_announce_whose_bot_does_not_own_the_session_is_dropped() {
crate::domain::model::AnnouncePrompt {
bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
origin: AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: MessageParent::Channel(macro_uuid::Uuid::from_u128(0xAA)),
thread_id: macro_uuid::Uuid::from_u128(0xAB),
@@ -3804,6 +3960,7 @@ async fn commands_for_a_peer_managed_session_forward_through_redis() {
let claim = claim_as_peer(&repo, id).await;
let forwarder = RecordingForwarder::default();
let service = AgentHarnessService::new(
+ None,
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
@@ -3857,6 +4014,7 @@ async fn unmanaged_external_session_forwards_to_its_remote_harness() {
let runtimes = TestConnections::new(MirrorBindings, RuntimeRegistry::new());
let forwarder = RecordingForwarder::default();
let service = AgentHarnessService::new(
+ None,
AgentSessionServiceImpl::new(
repo.clone(),
FoldedMessageService::new(repo.clone()),
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply.rs b/crates/agent_harness/src/domain/service/test/chat_reply.rs
index 0f671f19e9..7656017dcd 100644
--- a/crates/agent_harness/src/domain/service/test/chat_reply.rs
+++ b/crates/agent_harness/src/domain/service/test/chat_reply.rs
@@ -4,6 +4,7 @@
//! is what the domain asked of it and when.
use super::*;
+mod conversations;
use crate::domain::model::{
HeldToolCall, ReplyOutcome, ResolvedReply, TaskAssignmentOrigin, ToolApprovalChange,
};
@@ -148,6 +149,50 @@ fn says(agent: &FakeAgent, text: &str) {
);
}
+/// Wait until `condition` holds; signals reach the harness asynchronously.
+async fn eventually(what: &str, condition: impl Fn() -> bool) {
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ while !condition() {
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .unwrap_or_else(|_| panic!("timed out waiting until {what}"));
+}
+
+fn runs(agent: &FakeAgent, id: &str, status: &str, command: &str) {
+ agent.sends_raw(
+ RawJsonRpcMessage::notification(
+ "session/update".to_owned(),
+ serde_json::json!({
+ "sessionId": "acp-test",
+ "update": {
+ "sessionUpdate": "tool_call",
+ "toolCallId": id,
+ "title": "Bash",
+ "kind": "execute",
+ "status": status,
+ "rawInput": {"command": command}
+ }
+ }),
+ )
+ .expect("notification params are an object"),
+ );
+}
+
+fn finishes(agent: &FakeAgent, id: &str) {
+ agent.sends_raw(
+ RawJsonRpcMessage::notification(
+ "session/update".to_owned(),
+ serde_json::json!({
+ "sessionId": "acp-test",
+ "update": {"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}
+ }),
+ )
+ .expect("notification params are an object"),
+ );
+}
+
fn one_resolved(announcer: &AnnouncerMock) -> ResolvedReply {
match announcer.resolved().as_slice() {
[resolved] => resolved.clone(),
@@ -633,3 +678,69 @@ async fn task_assignment_links_the_session_without_copying_its_answer_to_discuss
ReplyOutcome::Answered("Here is the requested summary.".to_owned())
);
}
+
+#[tokio::test]
+async fn a_thread_reply_grows_in_place_with_its_steps_and_resolves_with_them() {
+ use agent_fold::domain::model::SegmentKind;
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = chat_session_with_a_running_turn(&service, &containers, id).await;
+ let agent = container.agent();
+ let pending = announcer.announced_messages()[0].message_id;
+
+ says(&agent, "Looking into it.");
+ runs(&agent, "t1", "in_progress", "rg TODO");
+ eventually("the pending reply shows the passage and its steps", || {
+ announcer
+ .presented()
+ .iter()
+ .any(|reply| reply.segments.len() == 2)
+ })
+ .await;
+ assert!(
+ announcer
+ .presented()
+ .iter()
+ .all(|reply| !reply.segments.is_empty()),
+ "the pending reply is not rewritten before there is something to add"
+ );
+ let grown = announcer.presented().last().unwrap().clone();
+ assert_eq!(grown.message_id, pending, "the thread reply grows in place");
+ assert!(grown.pending && grown.link && !grown.notify);
+ assert_eq!(
+ grown
+ .segments
+ .iter()
+ .map(|s| s.segment.kind)
+ .collect::<Vec<_>>(),
+ [SegmentKind::Prose, SegmentKind::Activity]
+ );
+ assert!(
+ announcer
+ .typed()
+ .iter()
+ .any(|typing| typing.active && typing.thread_id.is_some()),
+ "the bot types in the thread"
+ );
+
+ finishes(&agent, "t1");
+ says(&agent, "Found three.");
+ agent.completes_prompt().await;
+ turns.lifecycle_published(4).await;
+ let resolved = one_resolved(&announcer);
+ assert_eq!(resolved.message_id, pending);
+ assert_eq!(
+ resolved
+ .segments
+ .iter()
+ .map(|s| (s.segment.kind, s.text.as_deref()))
+ .collect::<Vec<_>>(),
+ [
+ (SegmentKind::Prose, Some("Looking into it.")),
+ (SegmentKind::Activity, None),
+ (SegmentKind::Prose, Some("Found three.")),
+ ]
+ );
+ assert!(matches!(announcer.typed().last(), Some(typing) if !typing.active));
+}
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs b/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs
new file mode 100644
index 0000000000..ed6869484e
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs
@@ -0,0 +1,1177 @@
+mod final_reply;
+
+use super::*;
+use crate::domain::model::ReplyPlacement;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+fn direct_command() -> OpenSession {
+ let mut command = chat_open_command();
+ mention_origin_mut(&mut command).reply_placement = ReplyPlacement::Timeline;
+ command
+}
+
+fn conversation(
+ channel: macro_uuid::Uuid,
+ command: &OpenSession,
+) -> agent_session::domain::agent_conversation::AgentConversation {
+ agent_session::domain::agent_conversation::AgentConversation {
+ channel_id: channel,
+ bot_id: command.bot_id,
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn quota_denial_finishes_queued_conversation_turns_without_stopping_the_running_turn(
+ pool: sqlx::PgPool,
+) {
+ use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+ use agent_session::domain::agent_conversation::AgentConversationRepo;
+ use channels::domain::agent_dm::AgentDmRepo;
+
+ let journal =
+ Arc::new(crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()));
+ let ((service, _, containers, announcer, _), _) = harness_with_ports_and_journal(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal.clone()),
+ );
+ let mut command = direct_command();
+ let channel = channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone())
+ .ensure(mention_origin(&command).sender.clone(), command.bot_id)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool)
+ .current_or_create(conversation(channel, &command))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).parent = MessageParent::Channel(channel);
+ let running_source = mention_origin(&command).message_id;
+ let _container = open_direct(&service, &containers, session, command.clone()).await;
+ let mut queued = Vec::new();
+ for _ in 0..2 {
+ let source = macro_uuid::generate_uuid_v7();
+ mention_origin_mut(&mut command).message_id = source;
+ queued.push(source);
+ assert_eq!(
+ service
+ .execute(
+ session,
+ HarnessCommand::ConversationMessage(command.clone())
+ )
+ .await
+ .unwrap(),
+ CommandOutcome::Queued,
+ );
+ }
+ service
+ .inner
+ .reject_waiting_on_denial(
+ session,
+ &HarnessError::Admission(ai_billing::AiAdmissionError::Denied(
+ ai_billing::DenyReason::AllowanceExhausted,
+ )),
+ )
+ .await
+ .unwrap();
+
+ for source in queued {
+ let record = journal.get(source, command.bot_id).await.unwrap().unwrap();
+ assert_eq!(record.state, ConversationTurnState::Failed);
+ assert!(record.reply_finalized);
+ }
+ assert_eq!(
+ journal
+ .get(running_source, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ ConversationTurnState::Running
+ );
+ assert!(service.inner.busy.turn(session).is_some());
+ assert!(service.inner.queues.snapshot(session).is_empty());
+ assert!(
+ service
+ .inner
+ .sessions
+ .list_queued_actions(session)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ announcer.resolved().is_empty(),
+ "the active reply is still running"
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_message_whose_conversation_was_deleted_is_acknowledged_instead_of_redelivered(
+ pool: sqlx::PgPool,
+) {
+ use agent_session::domain::agent_conversation::AgentConversationRepo;
+ use channels::domain::{agent_dm::AgentDmRepo, ports::ChannelRepo};
+ let journal =
+ Arc::new(crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()));
+ let policy = Arc::new(
+ crate::domain::conversations::AgentConversationsService::new(
+ channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone()),
+ bots::domain::service::BotServiceImpl::new(
+ bots::outbound::pg_bots_repo::PgBotsRepo::new(pool.clone()),
+ macro_event_broker::NoopMacroEventBroker,
+ ),
+ bots::outbound::pg_bots_repo::PgBotsRepo::new(pool.clone()),
+ crate::testing::postgres_sessions(pool.clone()),
+ )
+ .with_turns(journal.clone()),
+ );
+ let ((service, ..), _) = harness_with_journal_and_policy(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal),
+ Some(policy),
+ );
+ let mut command = direct_command();
+ let owner = mention_origin(&command).sender.clone();
+ let channels = channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone());
+ let channel = channels
+ .ensure(owner.clone(), command.bot_id)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool)
+ .current_or_create(conversation(channel, &command))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).parent = MessageParent::Channel(channel);
+ let (admitted, _) = service
+ .admit_conversation_message(session, command.clone())
+ .await
+ .unwrap()
+ .expect("a live conversation admits its owner's message");
+ assert_eq!(admitted, session);
+
+ // Deleted after the trigger published the next message: the session row
+ // went with the channel, and every redelivery would be refused alike.
+ channels
+ .delete_channel(channel, owner.to_string())
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).message_id = macro_uuid::generate_uuid_v7();
+ assert!(
+ service
+ .admit_conversation_message(session, command)
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+async fn open_direct(
+ service: &TestHarness,
+ containers: &MockContainerManager,
+ id: AgentSessionId,
+ command: OpenSession,
+) -> ContainerMock {
+ let open = service.execute(id, HarnessCommand::ConversationMessage(command));
+ let drive = async {
+ while containers.spawned() == 0 {
+ tokio::task::yield_now().await;
+ }
+ let container = containers.container(session_of(containers)).unwrap();
+ complete_session_handshake(&container).await;
+ container.agent().wait_for_requests(3).await;
+ container
+ };
+ let (result, container) = tokio::join!(open, drive);
+ result.expect("the reserved DM session opens");
+ container
+}
+
+#[tokio::test]
+async fn direct_conversations_share_one_session_queue_in_order_and_answer_in_the_timeline() {
+ let ((service, sessions, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let first = direct_command();
+ let container = open_direct(&service, &containers, id, first.clone()).await;
+ let agent = container.agent();
+ let mut next = first.clone();
+ mention_origin_mut(&mut next).message_id = macro_uuid::generate_uuid_v7();
+ mention_origin_mut(&mut next).thread_id = mention_origin(&next).message_id;
+ mention_origin_mut(&mut next).content = "Follow up".to_owned();
+ let outcome = service
+ .execute(id, HarnessCommand::ConversationMessage(next))
+ .await
+ .unwrap();
+ assert_eq!(outcome, CommandOutcome::Queued);
+ assert_eq!(containers.spawned(), 1);
+ assert!(
+ agent.received_notifications().is_empty(),
+ "a DM follow-up must not cancel the current turn"
+ );
+ assert!(
+ announcer.announced().is_empty(),
+ "a private reply posts nothing until the agent has something to show"
+ );
+ assert!(
+ matches!(announcer.typed().as_slice(), [typing] if typing.active && typing.thread_id.is_none()),
+ "the bot types in the timeline while the first turn runs: {:#?}",
+ announcer.typed()
+ );
+ assert!(
+ sessions.get(id).await.unwrap().thread_id.is_none(),
+ "the whole DM owns the conversation, not its first message's thread"
+ );
+ says(&agent, "First answer.");
+ agent.completes_prompt().await;
+ turns.lifecycle_published(4).await;
+ assert_eq!(answers(&announcer), ["First answer."]);
+ says(&agent, "Second answer.");
+ agent.completes_prompt().await;
+ turns.lifecycle_published(6).await;
+ assert_eq!(answers(&announcer), ["First answer.", "Second answer."]);
+ assert!(
+ announcer
+ .presented()
+ .iter()
+ .all(|reply| reply.thread_id.is_none() && !reply.link),
+ "a private reply is top-level and repeats no session link"
+ );
+ assert!(announcer.announced().is_empty());
+}
+
+/// The text of each final reply message shown, in order: the answers.
+fn answers(announcer: &AnnouncerMock) -> Vec<String> {
+ announcer
+ .presented()
+ .iter()
+ .filter(|reply| reply.notify)
+ .filter_map(|reply| {
+ reply
+ .segments
+ .iter()
+ .rev()
+ .find_map(|segment| segment.text.clone())
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn a_private_reply_posts_each_passage_with_its_steps_and_only_the_answer_is_news() {
+ use agent_fold::domain::model::{SegmentKind, TurnPhase};
+ let ((service, _, containers, announcer, _), turns) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let container = open_direct(&service, &containers, id, direct_command()).await;
+ let agent = container.agent();
+
+ says(&agent, "Checking the tests first.");
+ eventually("the agent is seen writing", || {
+ announcer
+ .typed()
+ .iter()
+ .any(|typing| typing.phase == TurnPhase::Writing)
+ })
+ .await;
+ assert!(
+ announcer.presented().is_empty(),
+ "an unfinished passage streams live and is not posted"
+ );
+
+ runs(&agent, "t1", "in_progress", "cargo test");
+ eventually("the narration is posted with its open steps", || {
+ !announcer.presented().is_empty()
+ })
+ .await;
+ let narration = announcer.presented()[0].clone();
+ assert!(!narration.notify, "narration is not news");
+ assert_eq!(
+ narration
+ .segments
+ .iter()
+ .map(|segment| (segment.segment.kind, segment.segment.sealed))
+ .collect::<Vec<_>>(),
+ [(SegmentKind::Prose, true), (SegmentKind::Activity, false)]
+ );
+ assert_eq!(
+ narration.segments[0].text.as_deref(),
+ Some("Checking the tests first.")
+ );
+ assert!(
+ announcer
+ .typed()
+ .iter()
+ .any(|typing| typing.phase == TurnPhase::Working),
+ "the bot says it is working while the step runs"
+ );
+
+ finishes(&agent, "t1");
+ says(&agent, "All green.");
+ agent.completes_prompt().await;
+ turns.lifecycle_published(4).await;
+
+ let presented = announcer.presented();
+ let finals: Vec<_> = presented.iter().filter(|reply| reply.notify).collect();
+ assert_eq!(finals.len(), 1, "{presented:#?}");
+ assert_eq!(
+ finals[0]
+ .segments
+ .last()
+ .and_then(|segment| segment.text.as_deref()),
+ Some("All green.")
+ );
+ assert_ne!(
+ finals[0].message_id, narration.message_id,
+ "the answer is a message of its own"
+ );
+ // The narration's message is rewritten once its steps sealed, never posted twice.
+ let narration_updates: Vec<_> = presented
+ .iter()
+ .filter(|reply| reply.message_id == narration.message_id)
+ .collect();
+ assert!(
+ narration_updates
+ .last()
+ .unwrap()
+ .segments
+ .iter()
+ .all(|segment| segment.segment.sealed)
+ );
+ assert!(
+ matches!(announcer.typed().last(), Some(typing) if !typing.active),
+ "the bot stops typing once the answer is showing"
+ );
+}
+
+#[tokio::test]
+async fn a_different_person_cannot_prompt_the_reserved_direct_session() {
+ let ((service, _, containers, announcer, _), _) =
+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());
+ let id = AgentSessionId::new();
+ let mut command = direct_command();
+ let _container = open_direct(&service, &containers, id, command.clone()).await;
+ mention_origin_mut(&mut command).sender = staff_sender();
+ mention_origin_mut(&mut command).message_id = macro_uuid::generate_uuid_v7();
+ assert!(matches!(
+ service
+ .execute(id, HarnessCommand::ConversationMessage(command))
+ .await,
+ Err(HarnessError::Session(AgentSessionError::Forbidden))
+ ));
+ assert!(announcer.announced().is_empty());
+ assert!(announcer.presented().is_empty());
+}
+
+#[tokio::test]
+async fn an_external_persona_conversation_binds_the_connected_runtime_without_spawning_a_container()
+{
+ let (service, repo, containers, announcer, runtimes) = harness();
+ let id = AgentSessionId::new();
+ let mut command = direct_command();
+ command.bot_id = BotId::new_from_uuid(macro_uuid::generate_uuid_v7());
+ command.runtime.kind = AgentKind::External;
+ command.runtime.harness = "external".to_owned();
+ let runtime = ContainerMock::default();
+ runtimes.attach(harness_for_bot(command.bot_id), runtime.clone());
+ let open = service.execute(id, HarnessCommand::ConversationMessage(command.clone()));
+ let (result, ()) = tokio::join!(open, complete_bound_handshake(&runtime));
+ result.expect("a DM delivers its first prompt to the connected persona");
+ assert_eq!(containers.spawned(), 0);
+ assert_eq!(repo.get(id).await.unwrap().harness, "external");
+ assert_eq!(prompts(&runtime.agent()).len(), 1);
+ assert!(announcer.announced().is_empty());
+ assert!(
+ announcer.typed().iter().any(|typing| typing.active),
+ "an external persona types like any other"
+ );
+
+ mention_origin_mut(&mut command).message_id = macro_uuid::generate_uuid_v7();
+ assert_eq!(
+ service
+ .execute(id, HarnessCommand::ConversationMessage(command))
+ .await
+ .unwrap(),
+ CommandOutcome::Queued
+ );
+ assert!(runtime.agent().received_notifications().is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_completed_conversation_message_never_runs_again_when_the_broker_replays_it(
+ pool: sqlx::PgPool,
+) {
+ use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+ use agent_session::domain::agent_conversation::AgentConversationRepo;
+ use channels::domain::agent_dm::AgentDmRepo;
+ let journal =
+ Arc::new(crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()));
+ let ((service, _, containers, announcer, _), signals) = harness_with_ports_and_journal(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal.clone()),
+ );
+ let mut command = direct_command();
+ let channel = channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone())
+ .ensure(mention_origin(&command).sender.clone(), command.bot_id)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool)
+ .current_or_create(conversation(channel, &command))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).parent = MessageParent::Channel(channel);
+ let source = mention_origin(&command).message_id;
+ let container = open_direct(&service, &containers, session, command.clone()).await;
+ says(&container.agent(), "Recorded answer");
+ container.agent().completes_prompt().await;
+ signals.lifecycle_published(4).await;
+ let completed = journal.get(source, command.bot_id).await.unwrap().unwrap();
+ assert_eq!(completed.state, ConversationTurnState::Succeeded);
+ assert!(completed.reply_finalized);
+ assert_eq!(answers(&announcer), ["Recorded answer"]);
+ assert_eq!(
+ service
+ .execute(session, HarnessCommand::ConversationMessage(command))
+ .await
+ .unwrap(),
+ CommandOutcome::Completed
+ );
+ service.recover_conversations().await.unwrap();
+ assert_eq!(prompts(&container.agent()).len(), 1);
+ assert!(announcer.announced().is_empty());
+ assert_eq!(answers(&announcer), ["Recorded answer"]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn recovered_messages_dispatch_in_durable_order_even_when_delivered_in_reverse(
+ pool: sqlx::PgPool,
+) {
+ use crate::domain::conversation_turns::ConversationTurnStore;
+ use agent_session::domain::agent_conversation::AgentConversationRepo;
+ use channels::domain::agent_dm::AgentDmRepo;
+ let journal =
+ Arc::new(crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()));
+ let ((service, _, containers, announcer, _), signals) = harness_with_ports_and_journal(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal.clone()),
+ );
+ let mut first = direct_command();
+ let channel = channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone())
+ .ensure(mention_origin(&first).sender.clone(), first.bot_id)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool)
+ .current_or_create(conversation(channel, &first))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut first).parent = MessageParent::Channel(channel);
+ mention_origin_mut(&mut first).content = "First admitted message".into();
+ let mut second = first.clone();
+ mention_origin_mut(&mut second).message_id = macro_uuid::generate_uuid_v7();
+ mention_origin_mut(&mut second).content = "Second admitted message".into();
+ journal
+ .admit(session, channel, first.clone())
+ .await
+ .unwrap();
+ journal
+ .admit(session, channel, second.clone())
+ .await
+ .unwrap();
+
+ let open = service.execute(session, HarnessCommand::ConversationMessage(second.clone()));
+ let drive = async {
+ while containers.spawned() == 0 {
+ tokio::task::yield_now().await;
+ }
+ let container = containers.container(session_of(&containers)).unwrap();
+ complete_session_handshake(&container).await;
+ container
+ };
+ let (opened, container) = tokio::join!(open, drive);
+ opened.unwrap();
+ assert!(
+ prompts(&container.agent()).is_empty(),
+ "the later arrival waits for the older durable admission"
+ );
+ service
+ .execute(session, HarnessCommand::ConversationMessage(first.clone()))
+ .await
+ .unwrap();
+ container.agent().wait_for_requests(3).await;
+ assert!(
+ prompt_text(&container.agent(), 0).contains("First admitted message"),
+ "the older admission runs first"
+ );
+ container.agent().completes_prompt().await;
+ signals.lifecycle_published(4).await;
+ container.agent().wait_for_requests(4).await;
+ assert!(prompt_text(&container.agent(), 1).contains("Second admitted message"));
+ assert!(announcer.announced().is_empty());
+ assert_eq!(containers.spawned(), 1);
+}
+
+/// The text of the `index`-th prompt the agent received.
+fn prompt_text(agent: &FakeAgent, index: usize) -> String {
+ serde_json::to_string(&prompts(agent)[index]).unwrap()
+}
+
+/// A direct conversation over `journal`, with its first message delivered
+/// to a running agent.
+async fn journaled_conversation(
+ pool: sqlx::PgPool,
+ journal: Arc<dyn crate::domain::conversation_turns::ConversationTurnStore>,
+) -> (
+ TestHarness,
+ AnnouncerMock,
+ TurnSignals,
+ ContainerMock,
+ OpenSession,
+) {
+ use agent_session::domain::agent_conversation::AgentConversationRepo;
+ use channels::domain::agent_dm::AgentDmRepo;
+ let ((service, _, containers, announcer, _), signals) = harness_with_ports_and_journal(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal),
+ );
+ let mut command = direct_command();
+ let channel = channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone())
+ .ensure(mention_origin(&command).sender.clone(), command.bot_id)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool)
+ .current_or_create(conversation(channel, &command))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).parent = MessageParent::Channel(channel);
+ let container = open_direct(&service, &containers, session, command.clone()).await;
+ (service, announcer, signals, container, command)
+}
+
+fn pg_journal(
+ pool: &sqlx::PgPool,
+) -> Arc<crate::outbound::conversation_turns::PgConversationTurnStore> {
+ Arc::new(crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()))
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_answer_that_could_not_be_posted_is_posted_by_recovery(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::ConversationTurnStore;
+ let journal = pg_journal(&pool);
+ let (service, announcer, signals, container, command) =
+ journaled_conversation(pool, journal.clone()).await;
+ let source = mention_origin(&command).message_id;
+ says(&container.agent(), "The only passage.");
+ announcer.fails("messages unavailable");
+ container.agent().completes_prompt().await;
+ eventually("the original reply attempt has settled", || {
+ signals
+ .lifecycle()
+ .iter()
+ .any(|event| matches!(event, AgentSessionLifecycleEvent::Settled(_)))
+ })
+ .await;
+ let unposted = journal.get(source, command.bot_id).await.unwrap().unwrap();
+ assert!(!unposted.reply_finalized);
+ assert!(answers(&announcer).is_empty());
+
+ // The replica that watched the turn has forgotten its reply by now.
+ announcer.recovers();
+ // Dropping the original reply lease queues its transaction rollback.
+ // Recovery may briefly see that lease held and leave it to the next pass.
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ service.recover_conversations().await.unwrap();
+ if journal
+ .get(source, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .reply_finalized
+ {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("recovery posts and finalizes the answer once the reply lease releases");
+ assert_eq!(answers(&announcer), ["The only passage."]);
+ let reserved = unposted.in_flight.unwrap().presented;
+ assert!(
+ announcer
+ .presented()
+ .iter()
+ .all(|reply| reserved.contains(&reply.message_id)),
+ "the answer is posted under the id its turn reserved"
+ );
+ assert!(
+ journal
+ .get(source, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .reply_finalized
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_answer_whose_turn_ended_unwatched_is_still_posted(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+ let journal = pg_journal(&pool);
+ let (service, announcer, _signals, container, command) =
+ journaled_conversation(pool, journal.clone()).await;
+ let source = mention_origin(&command).message_id;
+ let session = journal
+ .get(source, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .session_id;
+ says(&container.agent(), "Answered after a restart.");
+ eventually("the reply reserves its message", || {
+ service
+ .inner
+ .busy
+ .turn(session)
+ .is_some_and(|turn| !turn.presented.is_empty())
+ })
+ .await;
+ // As after a restart: nothing in memory says which turn runs here.
+ service.inner.busy.take(session);
+ service.inner.projections.clear();
+ container.agent().completes_prompt().await;
+ let finished = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ let record = journal.get(source, command.bot_id).await.unwrap().unwrap();
+ if record.reply_finalized {
+ break record;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("the turn's end reconciles its reply");
+ assert_eq!(finished.state, ConversationTurnState::Succeeded);
+ let presented = announcer.presented();
+ assert!(
+ matches!(
+ presented.as_slice(),
+ [reply] if reply.notify
+ && reply.outcome
+ == Some(ReplyOutcome::Answered("Answered after a restart.".to_owned()))
+ ),
+ "the answer is posted, as news, though nobody saw its passages: {presented:#?}"
+ );
+}
+
+/// A journal whose writes of a turn's end fail while `fail_finish` is set.
+struct FlakyJournal {
+ inner: crate::outbound::conversation_turns::PgConversationTurnStore,
+ fail_finish: std::sync::atomic::AtomicBool,
+ fail_reply_flight: std::sync::atomic::AtomicBool,
+}
+
+#[async_trait::async_trait]
+impl crate::domain::conversation_turns::ConversationTurnStore for FlakyJournal {
+ async fn claim_delivery(
+ &self,
+ session: AgentSessionId,
+ ) -> agent_session::domain::error::Result<
+ Option<Box<dyn crate::domain::conversation_turns::ConversationLease>>,
+ > {
+ self.inner.claim_delivery(session).await
+ }
+ async fn claim_context(
+ &self,
+ session: AgentSessionId,
+ ) -> agent_session::domain::error::Result<
+ Option<Box<dyn crate::domain::conversation_turns::ConversationLease>>,
+ > {
+ self.inner.claim_context(session).await
+ }
+ async fn cancel_queued(
+ &self,
+ session: AgentSessionId,
+ ) -> agent_session::domain::error::Result<()> {
+ self.inner.cancel_queued(session).await
+ }
+ async fn settings(
+ &self,
+ session: AgentSessionId,
+ ) -> agent_session::domain::error::Result<
+ Option<crate::domain::conversation_turns::ConversationSettings>,
+ > {
+ self.inner.settings(session).await
+ }
+ async fn pin_settings(
+ &self,
+ session: AgentSessionId,
+ settings: crate::domain::conversation_turns::ConversationSettings,
+ ) -> agent_session::domain::error::Result<crate::domain::conversation_turns::ConversationSettings>
+ {
+ self.inner.pin_settings(session, settings).await
+ }
+ async fn admit(
+ &self,
+ session: AgentSessionId,
+ channel: macro_uuid::Uuid,
+ command: OpenSession,
+ ) -> agent_session::domain::error::Result<crate::domain::conversation_turns::ConversationTurn>
+ {
+ self.inner.admit(session, channel, command).await
+ }
+ async fn get(
+ &self,
+ source: macro_uuid::Uuid,
+ bot: BotId,
+ ) -> agent_session::domain::error::Result<
+ Option<crate::domain::conversation_turns::ConversationTurn>,
+ > {
+ self.inner.get(source, bot).await
+ }
+ async fn by_action(
+ &self,
+ action: AgentActionId,
+ ) -> agent_session::domain::error::Result<
+ Option<crate::domain::conversation_turns::ConversationTurn>,
+ > {
+ self.inner.by_action(action).await
+ }
+ async fn retry(
+ &self,
+ source: macro_uuid::Uuid,
+ bot: BotId,
+ expected: AgentActionId,
+ ) -> agent_session::domain::error::Result<bool> {
+ self.inner.retry(source, bot, expected).await
+ }
+ async fn claim(
+ &self,
+ action: AgentActionId,
+ turn: &crate::domain::queue::InFlightTurn,
+ ) -> agent_session::domain::error::Result<bool> {
+ self.inner.claim(action, turn).await
+ }
+ async fn record_flight(
+ &self,
+ action: AgentActionId,
+ turn: &crate::domain::queue::InFlightTurn,
+ ) -> agent_session::domain::error::Result<()> {
+ self.inner.record_flight(action, turn).await
+ }
+ async fn record_reply_flight(
+ &self,
+ action: AgentActionId,
+ expected: &crate::domain::queue::InFlightTurn,
+ turn: &crate::domain::queue::InFlightTurn,
+ ) -> agent_session::domain::error::Result<bool> {
+ if self
+ .fail_reply_flight
+ .load(std::sync::atomic::Ordering::SeqCst)
+ {
+ return Err(anyhow::anyhow!("reply ID persistence is unavailable").into());
+ }
+ self.inner.record_reply_flight(action, expected, turn).await
+ }
+ async fn save_reply(
+ &self,
+ action: AgentActionId,
+ segments: &[agent_fold::domain::model::ProjectedSegment],
+ ) -> agent_session::domain::error::Result<()> {
+ self.inner.save_reply(action, segments).await
+ }
+ async fn finish(
+ &self,
+ action: AgentActionId,
+ state: crate::domain::conversation_turns::ConversationTurnState,
+ outcome: ReplyOutcome,
+ ) -> agent_session::domain::error::Result<()> {
+ if self.fail_finish.load(std::sync::atomic::Ordering::SeqCst) {
+ return Err(anyhow::anyhow!("the journal is unreachable").into());
+ }
+ self.inner.finish(action, state, outcome).await
+ }
+ async fn fail_queued(&self, action: AgentActionId) -> agent_session::domain::error::Result<()> {
+ self.inner.fail_queued(action).await
+ }
+ async fn finalize_reply(
+ &self,
+ action: AgentActionId,
+ outcome: &ReplyOutcome,
+ ) -> agent_session::domain::error::Result<()> {
+ self.inner.finalize_reply(action, outcome).await
+ }
+ async fn claim_reply(
+ &self,
+ action: AgentActionId,
+ ) -> agent_session::domain::error::Result<
+ Option<Box<dyn crate::domain::conversation_turns::ConversationLease>>,
+ > {
+ self.inner.claim_reply(action).await
+ }
+ async fn pending(
+ &self,
+ limit: u16,
+ ) -> agent_session::domain::error::Result<
+ Vec<crate::domain::conversation_turns::ConversationTurn>,
+ > {
+ self.inner.pending(limit).await
+ }
+ async fn running(
+ &self,
+ limit: u16,
+ ) -> agent_session::domain::error::Result<
+ Vec<crate::domain::conversation_turns::ConversationTurn>,
+ > {
+ self.inner.running(limit).await
+ }
+ async fn for_conversation(
+ &self,
+ channel: macro_uuid::Uuid,
+ bot: BotId,
+ recent: u16,
+ ) -> agent_session::domain::error::Result<
+ Vec<crate::domain::conversation_turns::ConversationTurnStatus>,
+ > {
+ self.inner.for_conversation(channel, bot, recent).await
+ }
+ async fn pending_replies(
+ &self,
+ limit: u16,
+ ) -> agent_session::domain::error::Result<
+ Vec<crate::domain::conversation_turns::ConversationTurn>,
+ > {
+ self.inner.pending_replies(limit).await
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_turn_end_the_journal_cannot_record_still_frees_the_session(pool: sqlx::PgPool) {
+ let journal = Arc::new(FlakyJournal {
+ inner: crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()),
+ fail_finish: std::sync::atomic::AtomicBool::new(false),
+ fail_reply_flight: std::sync::atomic::AtomicBool::new(false),
+ });
+ let (service, announcer, _signals, container, _) =
+ journaled_conversation(pool, journal.clone()).await;
+ let agent = container.agent();
+ let session = service.inner.busy.running()[0].0;
+ journal
+ .fail_finish
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ says(&agent, "First answer.");
+ agent.completes_prompt().await;
+ eventually("the session is free for its next command", || {
+ service.inner.busy.turn(session).is_none() && !service.inner.busy.is_pending(session)
+ })
+ .await;
+ // The turn's mark is released before its reply is resolved, so the reply
+ // may land a moment after the session is free.
+ eventually("the reply still shows how the turn ended", || {
+ answers(&announcer) == ["First answer."]
+ })
+ .await;
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_turn_whose_runtime_dies_fails_once_and_frees_the_conversation(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+ let journal = pg_journal(&pool);
+ let (service, announcer, _signals, container, command) =
+ journaled_conversation(pool, journal.clone()).await;
+ let source = mention_origin(&command).message_id;
+ says(&container.agent(), "Working on it.");
+ container.disconnects();
+ let failed = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ let record = journal.get(source, command.bot_id).await.unwrap().unwrap();
+ if record.reply_finalized {
+ break record;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("the stopped turn's failure is shown and recorded at once");
+ assert_eq!(failed.state, ConversationTurnState::Failed);
+ service.recover_conversations().await.unwrap();
+ let notices: Vec<_> = announcer
+ .presented()
+ .into_iter()
+ .filter(|reply| reply.notify)
+ .collect();
+ assert!(
+ matches!(notices.as_slice(), [notice] if notice.outcome == Some(ReplyOutcome::Failed)),
+ "the failure is told once, not again by recovery: {notices:#?}"
+ );
+}
+
+/// A direct conversation over `journal` whose first message is running, with
+/// two more messages queued behind it.
+async fn two_queued_behind_a_running_turn(
+ pool: sqlx::PgPool,
+ journal: Arc<crate::outbound::conversation_turns::PgConversationTurnStore>,
+ prompt_context: PromptContextMock,
+ prompt_composer: PromptComposerMock,
+) -> (TestHarness, ContainerMock, OpenSession, OpenSession) {
+ use agent_session::domain::agent_conversation::AgentConversationRepo;
+ use channels::domain::agent_dm::AgentDmRepo;
+ let ((service, _, containers, _, _), _) = harness_with_ports_and_journal(
+ prompt_context,
+ prompt_composer,
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal),
+ );
+ let mut command = direct_command();
+ let channel = channels::outbound::pg_channels_repo::PgChannelsRepo::new(pool.clone())
+ .ensure(mention_origin(&command).sender.clone(), command.bot_id)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool)
+ .current_or_create(conversation(channel, &command))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).parent = MessageParent::Channel(channel);
+ let container = open_direct(&service, &containers, session, command.clone()).await;
+ let queue = |content: &str| {
+ let mut queued = command.clone();
+ let message_id = macro_uuid::generate_uuid_v7();
+ mention_origin_mut(&mut queued).message_id = message_id;
+ mention_origin_mut(&mut queued).thread_id = message_id;
+ mention_origin_mut(&mut queued).content = content.to_owned();
+ queued
+ };
+ let (first, second) = (queue("The second message"), queue("The third message"));
+ for queued in [&first, &second] {
+ assert_eq!(
+ service
+ .execute(session, HarnessCommand::ConversationMessage(queued.clone()))
+ .await
+ .unwrap(),
+ CommandOutcome::Queued
+ );
+ }
+ (service, container, first, second)
+}
+
+/// A message deleted while it waited can never run. It fails instead of
+/// blocking the conversation, and the message behind it runs.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_message_deleted_while_it_waited_fails_and_the_next_one_runs(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+ let journal = pg_journal(&pool);
+ let prompt_context = PromptContextMock::default();
+ let (service, container, deleted, next) = two_queued_behind_a_running_turn(
+ pool,
+ journal.clone(),
+ prompt_context.clone(),
+ PromptComposerMock::default(),
+ )
+ .await;
+ prompt_context.delete(mention_origin(&deleted).message_id);
+
+ container.agent().completes_prompt().await;
+ tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ container.agent().wait_for_requests(4),
+ )
+ .await
+ .expect("the message behind the deleted one is prompted");
+ assert!(prompt_text(&container.agent(), 1).contains("The third message"));
+ let dropped = journal
+ .get(mention_origin(&deleted).message_id, deleted.bot_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(dropped.state, ConversationTurnState::Failed);
+ assert!(dropped.reply_finalized);
+ let running = journal
+ .get(mention_origin(&next).message_id, next.bot_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(running.state, ConversationTurnState::Running);
+ assert!(service.inner.queues.snapshot(running.session_id).is_empty());
+}
+
+/// A waiting message whose turn the journal already ended - failed by an
+/// attempt that could not run it, or stopped when its owner started fresh -
+/// is dropped without being composed, and the message behind it runs.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_waiting_message_whose_turn_already_ended_is_dropped(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::ConversationTurnStore;
+ let journal = pg_journal(&pool);
+ let prompt_composer = PromptComposerMock::default();
+ let (_service, container, ended, _next) = two_queued_behind_a_running_turn(
+ pool,
+ journal.clone(),
+ PromptContextMock::default(),
+ prompt_composer.clone(),
+ )
+ .await;
+ let ended = journal
+ .get(mention_origin(&ended).message_id, ended.bot_id)
+ .await
+ .unwrap()
+ .unwrap();
+ journal.fail_queued(ended.action_id).await.unwrap();
+
+ container.agent().completes_prompt().await;
+ tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ container.agent().wait_for_requests(4),
+ )
+ .await
+ .expect("the message behind the ended one is prompted");
+ assert!(prompt_text(&container.agent(), 1).contains("The third message"));
+ assert!(
+ !prompt_composer
+ .calls()
+ .iter()
+ .any(|(prompt, ..)| prompt.contains("The second message")),
+ "a message whose turn ended is never composed"
+ );
+}
+
+/// The delivery lease serializes bootstraps only. A message to a session that
+/// is already open is answered while another conversation's bootstrap holds
+/// the replica's only lease, instead of waiting for it and then for recovery.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_open_conversation_answers_while_another_one_bootstraps(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::ConversationTurnStore;
+ // The harness service's pool, where each kind of lease has one slot.
+ let small = sqlx::postgres::PgPoolOptions::new()
+ .max_connections(5)
+ .connect_with((*pool.connect_options()).clone())
+ .await
+ .unwrap();
+ let journal =
+ Arc::new(crate::outbound::conversation_turns::PgConversationTurnStore::new(small));
+ let (service, _announcer, signals, container, command) =
+ journaled_conversation(pool, journal.clone()).await;
+ let session = journal
+ .get(mention_origin(&command).message_id, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .session_id;
+ says(&container.agent(), "First answer.");
+ container.agent().completes_prompt().await;
+ signals.lifecycle_published(4).await;
+
+ let _bootstrap = journal
+ .claim_delivery(AgentSessionId::new())
+ .await
+ .unwrap()
+ .expect("an idle replica leases a bootstrap");
+ let mut next = command.clone();
+ let message_id = macro_uuid::generate_uuid_v7();
+ mention_origin_mut(&mut next).message_id = message_id;
+ mention_origin_mut(&mut next).thread_id = message_id;
+ mention_origin_mut(&mut next).content = "Asked during the bootstrap".to_owned();
+ tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ service.execute(session, HarnessCommand::ConversationMessage(next)),
+ )
+ .await
+ .expect("an open session's message does not wait for the bootstrap's lease")
+ .unwrap();
+ tokio::time::timeout(
+ std::time::Duration::from_secs(5),
+ container.agent().wait_for_requests(4),
+ )
+ .await
+ .expect("the message is prompted");
+ assert!(prompt_text(&container.agent(), 1).contains("Asked during the bootstrap"));
+}
+
+/// A replica that dies mid-turn leaves the messages it posted showing their
+/// steps running. Recovery shows each of them closed, the last one with how
+/// the turn ended.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn recovery_closes_the_messages_a_lost_replica_posted(pool: sqlx::PgPool) {
+ use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+ use agent_fold::domain::model::ActivityStatus;
+ let journal = pg_journal(&pool);
+ let (service, announcer, _signals, container, command) =
+ journaled_conversation(pool, journal.clone()).await;
+ let agent = container.agent();
+ says(&agent, "Checking the tests first.");
+ runs(&agent, "t1", "in_progress", "cargo test");
+ eventually("the narration is posted with its step running", || {
+ !announcer.presented().is_empty()
+ })
+ .await;
+ let narration = announcer.presented()[0].message_id;
+ let turn = journal
+ .get(mention_origin(&command).message_id, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap();
+
+ // The replica is gone, and with it what it remembered of the turn;
+ // recovery finds the turn running and interrupts it.
+ service.inner.busy.take(turn.session_id);
+ service.inner.projections.clear();
+ journal
+ .finish(
+ turn.action_id,
+ ConversationTurnState::Interrupted,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ service.recover_conversations().await.unwrap();
+
+ let presented = announcer.presented();
+ let closed = presented.last().unwrap();
+ assert_eq!(closed.message_id, narration, "{presented:#?}");
+ assert_eq!(closed.outcome, Some(ReplyOutcome::Failed));
+ assert!(closed.notify);
+ assert!(closed.segments.iter().all(|segment| segment.segment.sealed));
+ assert!(
+ closed
+ .segments
+ .iter()
+ .flat_map(|segment| &segment.segment.rows)
+ .all(|row| row.status != ActivityStatus::Running),
+ "{closed:#?}"
+ );
+}
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply/conversations/final_reply.rs b/crates/agent_harness/src/domain/service/test/chat_reply/conversations/final_reply.rs
new file mode 100644
index 0000000000..79b0db54f2
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/test/chat_reply/conversations/final_reply.rs
@@ -0,0 +1,240 @@
+use super::*;
+use crate::domain::conversation_turns::{ConversationTurnState, ConversationTurnStore};
+use agent_fold::domain::model::{ProjectedSegment, Segment, SegmentKind};
+
+fn passage(index: u32, text: &str) -> ProjectedSegment {
+ ProjectedSegment {
+ segment: Segment {
+ index,
+ kind: SegmentKind::Prose,
+ start: index,
+ end: index + 1,
+ sealed: true,
+ rows: Vec::new(),
+ },
+ text: Some(text.to_owned()),
+ }
+}
+
+/// A response can be lost after the message commits. A stale replica and
+/// recovery must both reuse every reserved ID, without rerunning the model.
+async fn committed_reply_recovery(pool: sqlx::PgPool, extra_passage: bool) {
+ let journal = pg_journal(&pool);
+ let (service, announcer, _, container, command) =
+ journaled_conversation(pool, journal.clone()).await;
+ let source = mention_origin(&command).message_id;
+ let record = journal.get(source, command.bot_id).await.unwrap().unwrap();
+ let mut stale = record.in_flight.unwrap();
+ if extra_passage {
+ stale.presented.push(macro_uuid::generate_uuid_v7());
+ stale.announcement_message_id = stale.presented.last().copied();
+ journal
+ .record_flight(record.action_id, &stale)
+ .await
+ .unwrap();
+ journal
+ .save_reply(
+ record.action_id,
+ &[passage(0, "First passage."), passage(1, "Final passage.")],
+ )
+ .await
+ .unwrap();
+ }
+ let outcome = ReplyOutcome::Failed;
+ journal
+ .finish(
+ record.action_id,
+ ConversationTurnState::Failed,
+ outcome.clone(),
+ )
+ .await
+ .unwrap();
+ service.inner.busy.take(record.session_id);
+ announcer.fails_after_presenting("committed, but response was lost");
+ service
+ .inner
+ .resolve_reply(record.session_id, Some(&stale), outcome.clone())
+ .await;
+ let reserved = journal.by_action(record.action_id).await.unwrap().unwrap();
+ let ids = reserved.in_flight.unwrap().presented;
+ assert_eq!(ids.len(), if extra_passage { 2 } else { 1 });
+ assert!(!reserved.reply_finalized);
+ assert!(
+ announcer
+ .presented()
+ .iter()
+ .all(|reply| ids.contains(&reply.message_id))
+ );
+ assert_eq!(announcer.presented().len(), ids.len());
+ assert!(
+ !journal
+ .retry(source, command.bot_id, record.action_id)
+ .await
+ .unwrap(),
+ "a reply with a lost response must reconcile before retry"
+ );
+ assert!(
+ !journal
+ .for_conversation(record.channel_id, command.bot_id, 10)
+ .await
+ .unwrap()[0]
+ .retryable
+ );
+ assert!(
+ service.inner.busy.turn(record.session_id).is_none(),
+ "final reservation must not make a finished turn busy again"
+ );
+
+ // Recover with no local projection or successful-shape cache, as on a
+ // second replica. The original caller still carries the shorter flight.
+ announcer.recovers();
+ let ((replica, _, _, replica_announcer, _), _) = harness_with_ports_and_journal(
+ PromptContextMock::default(),
+ PromptComposerMock::default(),
+ KindDefaultPolicies,
+ HarnessDefaultCodingAgents,
+ PromptMentionsMock::new(),
+ EgressProvisionerMock::new(),
+ Some(journal.clone()),
+ );
+ // Both callers deliberately keep their old snapshot. At least one must
+ // reconcile using the IDs reloaded under its lease, rather than needing a
+ // caller that already knows the new IDs.
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ tokio::join!(
+ service
+ .inner
+ .resolve_reply(record.session_id, Some(&stale), outcome.clone()),
+ replica
+ .inner
+ .resolve_reply(record.session_id, Some(&stale), outcome.clone()),
+ );
+ if journal
+ .by_action(record.action_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .reply_finalized
+ {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("stale reconcilers reload the durable IDs after the prior lease releases");
+ service.recover_conversations().await.unwrap();
+ let all_presented = announcer
+ .presented()
+ .into_iter()
+ .chain(replica_announcer.presented())
+ .collect::<Vec<_>>();
+ assert!(
+ all_presented
+ .iter()
+ .all(|reply| ids.contains(&reply.message_id))
+ );
+ assert!(
+ all_presented.len() > ids.len(),
+ "a stale reconciler really reposted the committed reply"
+ );
+ let finalized = journal.by_action(record.action_id).await.unwrap().unwrap();
+ assert_eq!(finalized.in_flight.unwrap().presented, ids);
+ assert!(
+ announcer
+ .presented()
+ .iter()
+ .all(|reply| ids.contains(&reply.message_id))
+ );
+ assert_eq!(prompts(&container.agent()).len(), 1);
+ assert!(
+ journal
+ .retry(source, command.bot_id, record.action_id)
+ .await
+ .unwrap()
+ );
+ // An old terminal snapshot cannot post after retry changed its action ID.
+ let before = announcer.presented().len();
+ service
+ .inner
+ .resolve_reply(record.session_id, Some(&stale), ReplyOutcome::Failed)
+ .await;
+ assert_eq!(announcer.presented().len(), before);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn outcome_only_reply_ids_survive_a_lost_post_response_and_stale_reconciliation(
+ pool: sqlx::PgPool,
+) {
+ committed_reply_recovery(pool, false).await;
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn extra_final_passage_ids_survive_a_lost_post_response_and_stale_reconciliation(
+ pool: sqlx::PgPool,
+) {
+ committed_reply_recovery(pool, true).await;
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn failed_final_id_persistence_posts_nothing_until_recovery_can_reserve_ids(
+ pool: sqlx::PgPool,
+) {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ let journal = Arc::new(FlakyJournal {
+ inner: crate::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()),
+ fail_finish: AtomicBool::new(false),
+ fail_reply_flight: AtomicBool::new(true),
+ });
+ let (service, announcer, _, _, command) = journaled_conversation(pool, journal.clone()).await;
+ let record = journal
+ .get(mention_origin(&command).message_id, command.bot_id)
+ .await
+ .unwrap()
+ .unwrap();
+ journal
+ .finish(
+ record.action_id,
+ ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ service.inner.busy.take(record.session_id);
+ service
+ .inner
+ .resolve_reply(
+ record.session_id,
+ record.in_flight.as_ref(),
+ ReplyOutcome::Failed,
+ )
+ .await;
+ assert!(announcer.presented().is_empty());
+ let unposted = journal.by_action(record.action_id).await.unwrap().unwrap();
+ assert!(!unposted.reply_finalized);
+ assert!(unposted.in_flight.unwrap().presented.is_empty());
+ journal.fail_reply_flight.store(false, Ordering::SeqCst);
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ service.recover_conversations().await.unwrap();
+ if journal
+ .by_action(record.action_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .reply_finalized
+ {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ })
+ .await
+ .expect("IDs are saved before recovery posts");
+ let saved = journal.by_action(record.action_id).await.unwrap().unwrap();
+ assert_eq!(
+ announcer.presented()[0].message_id,
+ saved.in_flight.unwrap().presented[0]
+ );
+}
diff --git a/crates/agent_harness/src/domain/service/test/quota.rs b/crates/agent_harness/src/domain/service/test/quota.rs
index a296d54553..2fc183ea6e 100644
--- a/crates/agent_harness/src/domain/service/test/quota.rs
+++ b/crates/agent_harness/src/domain/service/test/quota.rs
@@ -53,7 +53,7 @@ async fn session(
agent_session::domain::ports::AgentSessionRepo::create(
repo,
CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
id,
owner_id: owner,
bot_id: bot,
@@ -356,6 +356,9 @@ async fn retries_of_queued_and_in_flight_actions_do_not_recheck_quota() {
announce: None,
announcement_message_id: None,
dispatched_at: chrono::Utc::now(),
+ bot_id: None,
+ speaks_as_chip: false,
+ presented: Vec::new(),
held_tool_calls: Vec::new(),
},
);
@@ -618,6 +621,9 @@ async fn denying_a_steering_follow_up_does_not_cancel_the_running_turn() {
announce: None,
announcement_message_id: None,
dispatched_at: chrono::Utc::now(),
+ bot_id: None,
+ speaks_as_chip: false,
+ presented: Vec::new(),
held_tool_calls: Vec::new(),
};
service.inner.busy.mark_turn(id, running.clone());
@@ -747,6 +753,7 @@ async fn rejection_persistence_failure_keeps_work_and_defers_reply_resolution()
})
});
let service = AgentHarnessService::new(
+ None,
sessions,
MockContainerManager::new(),
AnnouncerMock::new(),
diff --git a/crates/agent_harness/src/domain/service/test/reopen.rs b/crates/agent_harness/src/domain/service/test/reopen.rs
index 46c6bac31b..d5eb05ffaf 100644
--- a/crates/agent_harness/src/domain/service/test/reopen.rs
+++ b/crates/agent_harness/src/domain/service/test/reopen.rs
@@ -8,7 +8,7 @@ async fn codex_session(
agent_session::domain::ports::AgentSessionRepo::create(
repo,
CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: model_owner::Owner::User(sender()),
diff --git a/crates/agent_harness/src/domain/service/warm.rs b/crates/agent_harness/src/domain/service/warm.rs
index 40b3483b8e..db56fb0bab 100644
--- a/crates/agent_harness/src/domain/service/warm.rs
+++ b/crates/agent_harness/src/domain/service/warm.rs
@@ -233,7 +233,11 @@ where
.inner
.sessions
.create_session(CreateAgentSessionParams {
- warm,
+ purpose: if warm {
+ agent_session::domain::model::SessionPurpose::Warm
+ } else {
+ agent_session::domain::model::SessionPurpose::Standalone
+ },
repo_branch: selected_repo.as_ref().map(|(_, branch)| branch.clone()),
id: session_id,
owner_id: request.owner,
diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rs
index a093de5600..4e0c31572c 100644
--- a/crates/agent_harness/src/domain/trigger_router.rs
+++ b/crates/agent_harness/src/domain/trigger_router.rs
@@ -62,6 +62,34 @@ pub fn route_agent_trigger(
links: &StaticFileLinks,
) -> Result<RoutedTrigger, Skipped> {
match event {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::ConversationMessage(event)) => {
+ let Some(runtime) = runtime else {
+ return Err(Skipped::ForeignBot);
+ };
+ let sender = event
+ .message
+ .sender
+ .as_user()
+ .cloned()
+ .ok_or(Skipped::NotFromUser)?;
+ Ok(RoutedTrigger::Command(
+ event.session_id,
+ HarnessCommand::ConversationMessage(OpenSession {
+ bot_id: event.bot_id,
+ runtime,
+ origin: SessionOrigin::Mention(MentionOrigin {
+ reply_placement: super::model::ReplyPlacement::Timeline,
+ parent: event.message.parent,
+ thread_id: event.message.thread_id.unwrap_or(event.message.message_id),
+ message_id: event.message.message_id,
+ sender,
+ content: event.message.content,
+ attachments: links.prompt_attachments(&event.message.attachments),
+ context: event.context,
+ }),
+ }),
+ ))
+ }
AgentTriggerTopicEvent::New(NewAgentSessionEvent::AssignedToTask(assigned)) => {
let Some(runtime) = runtime.filter(|runtime| runtime.kind.is_managed()) else {
return Err(Skipped::ForeignBot);
@@ -110,6 +138,7 @@ pub fn route_agent_trigger(
bot_id,
runtime,
origin: SessionOrigin::Mention(MentionOrigin {
+ reply_placement: Default::default(),
parent: message.parent,
// A top-level mention roots its own thread; a mention
// inside a thread answers into that thread.
@@ -135,6 +164,7 @@ pub fn route_agent_trigger(
return Err(Skipped::Unrecognized);
};
let origin = AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: message.parent,
thread_id: message.thread_id.unwrap_or(message.message_id),
diff --git a/crates/agent_harness/src/inbound/conversations.rs b/crates/agent_harness/src/inbound/conversations.rs
new file mode 100644
index 0000000000..cdf3f02773
--- /dev/null
+++ b/crates/agent_harness/src/inbound/conversations.rs
@@ -0,0 +1,307 @@
+//! Thin HTTP projection for agent conversations in channels.
+
+use crate::domain::conversations::{AgentConversations, ConversationError, ConversationOverview};
+use agent_session::domain::agent_conversation::AgentConversation;
+use axum::{
+ Json, Router,
+ extract::{FromRef, Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::{get, post},
+};
+use bot_id::BotId;
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOnly,
+};
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use utoipa::ToSchema;
+
+/// One session a conversation has run on; every channel message stays visible.
+#[derive(Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentConversationSessionDto {
+ /// Session whose controls and live events belong to this context.
+ pub session_id: Uuid,
+ /// When the session began.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ /// Whether this is the current agent context.
+ pub is_current: bool,
+}
+
+/// An agent's conversation in a channel, as the person it is with sees it.
+#[derive(Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentConversationDto {
+ /// The channel containing the visible transcript.
+ pub channel_id: Uuid,
+ /// Persona id (without the bot principal prefix).
+ pub bot_id: Uuid,
+ /// Persona's historical display name.
+ pub name: String,
+ /// Optional persona avatar.
+ pub avatar_url: Option<String>,
+ /// Whether the caller may currently send a new prompt.
+ pub available: bool,
+ /// Whether new persona settings are available to adopt explicitly.
+ pub settings_changed: bool,
+ /// The sessions the conversation has run on, oldest first.
+ pub sessions: Vec<AgentConversationSessionDto>,
+ /// Persistent state of each accepted message and its current attempt.
+ pub turns: Vec<AgentConversationTurnDto>,
+}
+
+/// The agent conversations in a channel the caller may see.
+#[derive(Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentConversationsDto {
+ /// Empty for ordinary channels and other people's conversations.
+ pub conversations: Vec<AgentConversationDto>,
+}
+
+/// Execution status without exposing the persona prompt or stored credentials.
+#[derive(Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentConversationTurnDto {
+ /// The user's message in the channel timeline.
+ pub source_message_id: Uuid,
+ /// Current runtime attempt identity.
+ pub action_id: Uuid,
+ /// Session carrying this turn.
+ pub session_id: Uuid,
+ /// The associated agent reply, if it has been posted.
+ pub reply_message_id: Option<Uuid>,
+ /// Durable execution state.
+ pub state: crate::domain::conversation_turns::ConversationTurnState,
+ /// Whether Retry would be accepted now. A failed attempt is not retryable
+ /// until its reply says how it ended.
+ pub retryable: bool,
+ /// When the source message was first accepted.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+}
+
+impl From<ConversationOverview> for AgentConversationDto {
+ fn from(value: ConversationOverview) -> Self {
+ Self {
+ channel_id: value.channel_id,
+ bot_id: value.persona.id.as_uuid(),
+ name: value.persona.name,
+ avatar_url: value.persona.avatar_url,
+ available: value.available,
+ settings_changed: value.settings_changed,
+ turns: value
+ .turns
+ .into_iter()
+ .map(|turn| AgentConversationTurnDto {
+ source_message_id: turn.source_message_id,
+ action_id: turn.action_id.as_uuid(),
+ session_id: turn.session_id.as_uuid(),
+ reply_message_id: turn.reply_message_id,
+ state: turn.state,
+ retryable: turn.retryable,
+ created_at: turn.created_at,
+ })
+ .collect(),
+ sessions: value
+ .sessions
+ .into_iter()
+ .map(|session| AgentConversationSessionDto {
+ session_id: session.session_id.as_uuid(),
+ created_at: session.created_at,
+ is_current: session.is_current,
+ })
+ .collect(),
+ }
+ }
+}
+
+/// Independently authenticated conversation router state.
+pub struct AgentConversationRouterState<S, A> {
+ service: Arc<S>,
+ authorization: MacroAuthorizationState<A>,
+}
+
+impl<S, A> AgentConversationRouterState<S, A> {
+ /// Compose the domain service and user authentication.
+ pub fn new(service: Arc<S>, authorization: MacroAuthorizationState<A>) -> Self {
+ Self {
+ service,
+ authorization,
+ }
+ }
+}
+
+impl<S, A> Clone for AgentConversationRouterState<S, A> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ authorization: self.authorization.clone(),
+ }
+ }
+}
+
+impl<S, A> FromRef<AgentConversationRouterState<S, A>> for MacroAuthorizationState<A> {
+ fn from_ref(state: &AgentConversationRouterState<S, A>) -> Self {
+ state.authorization.clone()
+ }
+}
+
+/// Read and control a channel's agent conversations, without allocating a runtime.
+pub fn agent_conversation_router<S: AgentConversations, A: MacroAuthorizationService>(
+ state: AgentConversationRouterState<S, A>,
+) -> Router {
+ Router::new()
+ .route(
+ "/agent-conversations/{channel_id}",
+ get(list_agent_conversations::<S, A>),
+ )
+ .route(
+ "/agent-conversations/{channel_id}/{bot_id}/start-fresh",
+ post(start_fresh_agent_conversation::<S, A>),
+ )
+ .route(
+ "/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",
+ post(retry_agent_conversation_turn::<S, A>),
+ )
+ .with_state(state)
+}
+
+/// The session the user is choosing to leave behind.
+#[derive(Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct StartFreshAgentConversationRequest {
+ /// Current session id shown in the conversation metadata.
+ pub session_id: Uuid,
+}
+
+/// Start a fresh agent context, retaining the channel transcript.
+#[utoipa::path(
+ post,
+ path = "/agent-conversations/{channel_id}/{bot_id}/start-fresh",
+ tag = "agent-conversations",
+ security(("bearerAuth" = [])),
+ params(("channel_id" = Uuid, Path), ("bot_id" = Uuid, Path, description = "Persona the conversation is with")),
+ request_body = StartFreshAgentConversationRequest,
+ responses((status = 204, description = "New context reserved"), (status = 404, description = "Conversation not found"), (status = 409, description = "Context is busy, stale or unavailable"), (status = 503, description = "Temporarily unavailable"))
+)]
+pub async fn start_fresh_agent_conversation<S: AgentConversations, A: MacroAuthorizationService>(
+ State(state): State<AgentConversationRouterState<S, A>>,
+ authorization: MacroAuthorizationExtractor<A, UserOnly>,
+ Path((channel_id, bot_id)): Path<(Uuid, Uuid)>,
+ Json(request): Json<StartFreshAgentConversationRequest>,
+) -> Response {
+ match state
+ .service
+ .start_fresh(
+ authorization.authorization.macro_user_id.clone(),
+ AgentConversation {
+ channel_id,
+ bot_id: BotId::new_from_uuid(bot_id),
+ },
+ agent_session::domain::model::AgentSessionId::new_from_uuid(request.session_id),
+ )
+ .await
+ {
+ Ok(()) => StatusCode::NO_CONTENT.into_response(),
+ Err(ConversationError::NotFound) => StatusCode::NOT_FOUND.into_response(),
+ Err(ConversationError::ContextBusy | ConversationError::NotRetryable) => {
+ StatusCode::CONFLICT.into_response()
+ }
+ Err(error) => {
+ tracing::error!(?error, %channel_id, %bot_id, "failed to reset agent conversation context");
+ StatusCode::SERVICE_UNAVAILABLE.into_response()
+ }
+ }
+}
+
+/// The attempt the user saw and chose to retry; prevents double-click reruns.
+#[derive(Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct RetryAgentConversationTurnRequest {
+ /// Current failed attempt identity.
+ pub action_id: Uuid,
+}
+
+/// Explicitly retry a failed message in the conversation's current session.
+#[utoipa::path(
+ post,
+ path = "/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",
+ tag = "agent-conversations",
+ security(("bearerAuth" = [])),
+ params(("channel_id" = Uuid, Path), ("bot_id" = Uuid, Path, description = "Persona the conversation is with"), ("source" = Uuid, Path)),
+ request_body = RetryAgentConversationTurnRequest,
+ responses((status = 204, description = "Retry queued"), (status = 404, description = "Conversation or turn not found"), (status = 409, description = "Attempt cannot be retried"), (status = 503, description = "Temporarily unavailable"))
+)]
+pub async fn retry_agent_conversation_turn<S: AgentConversations, A: MacroAuthorizationService>(
+ State(state): State<AgentConversationRouterState<S, A>>,
+ authorization: MacroAuthorizationExtractor<A, UserOnly>,
+ Path((channel_id, bot_id, source)): Path<(Uuid, Uuid, Uuid)>,
+ Json(request): Json<RetryAgentConversationTurnRequest>,
+) -> Response {
+ match state
+ .service
+ .retry(
+ authorization.authorization.macro_user_id.clone(),
+ AgentConversation {
+ channel_id,
+ bot_id: BotId::new_from_uuid(bot_id),
+ },
+ source,
+ agent_runtime_protocol::domain::action::AgentActionId::from_uuid(request.action_id),
+ )
+ .await
+ {
+ Ok(()) => StatusCode::NO_CONTENT.into_response(),
+ Err(ConversationError::NotFound) => StatusCode::NOT_FOUND.into_response(),
+ Err(ConversationError::NotRetryable) => StatusCode::CONFLICT.into_response(),
+ Err(error) => {
+ tracing::error!(?error, %channel_id, %bot_id, %source, "failed to retry agent conversation turn");
+ StatusCode::SERVICE_UNAVAILABLE.into_response()
+ }
+ }
+}
+
+/// The agent conversations in a channel the caller may see. Ordinary channels
+/// and other people's conversations list none.
+#[utoipa::path(
+ get,
+ path = "/agent-conversations/{channel_id}",
+ tag = "agent-conversations",
+ security(("bearerAuth" = [])),
+ params(("channel_id" = Uuid, Path, description = "Conversation channel")),
+ responses(
+ (status = 200, description = "The caller's agent conversations in the channel", body = AgentConversationsDto),
+ (status = 503, description = "Conversations temporarily unavailable"),
+ )
+)]
+pub async fn list_agent_conversations<S: AgentConversations, A: MacroAuthorizationService>(
+ State(state): State<AgentConversationRouterState<S, A>>,
+ authorization: MacroAuthorizationExtractor<A, UserOnly>,
+ Path(channel_id): Path<Uuid>,
+) -> Response {
+ match state
+ .service
+ .list(
+ authorization.authorization.macro_user_id.clone(),
+ channel_id,
+ )
+ .await
+ {
+ Ok(conversations) => Json(AgentConversationsDto {
+ conversations: conversations
+ .into_iter()
+ .map(AgentConversationDto::from)
+ .collect(),
+ })
+ .into_response(),
+ Err(error) => {
+ tracing::error!(?error, %channel_id, "failed to read agent conversations");
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ "Could not load this conversation",
+ )
+ .into_response()
+ }
+ }
+}
diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rs
index 672cb27b3f..1e28a5c512 100644
--- a/crates/agent_harness/src/inbound/kafka/test.rs
+++ b/crates/agent_harness/src/inbound/kafka/test.rs
@@ -1,9 +1,9 @@
use agent_runtime_protocol::domain::action::AgentAction;
use agent_session::domain::model::{AgentMcpServers, AgentSessionId};
use agent_trigger::domain::broker_events::{
- AgentAssignedToTaskEvent, AgentBotMentionedEvent, AgentMentionedEvent, AgentTriggerTopicEvent,
- ChannelEventMetadata, ExistingAgentSessionEvent, NewAgentSessionEvent, ThreadEventMetadata,
- ThreadMessageKind,
+ AgentAssignedToTaskEvent, AgentBotMentionedEvent, AgentConversationMessageEvent,
+ AgentMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata, ExistingAgentSessionEvent,
+ NewAgentSessionEvent, ThreadEventMetadata, ThreadMessageKind,
};
use bot_id::{BotId, MACRO_CODER_BOT_ID};
use channel_sender::ChannelSender;
@@ -631,3 +631,32 @@ fn a_managed_channel_message_with_files_delivers_them_as_prompt_attachments() {
assert_eq!(prompt.attachments[0].mime_type.as_deref(), Some("image/*"));
assert_eq!(prompt.attachments[1].mime_type.as_deref(), Some("video/*"));
}
+
+#[test]
+fn conversation_messages_route_to_every_configured_runtime() {
+ let session_id = AgentSessionId::TEST_A;
+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::ConversationMessage(
+ AgentConversationMessageEvent {
+ bot_id: BotId::TEST_A,
+ session_id,
+ message: document_message(ChannelSender::new_from_user(user())),
+ context: None,
+ },
+ ));
+ assert_eq!(
+ route_agent_trigger(event.clone(), None, &links()).unwrap_err(),
+ Skipped::ForeignBot,
+ );
+ for kind in [
+ AgentKind::InMemory,
+ AgentKind::SandboxedCoder,
+ AgentKind::External,
+ ] {
+ let routed = route_agent_trigger(event.clone(), runtime(kind), &links()).unwrap();
+ let RoutedTrigger::Command(id, HarnessCommand::ConversationMessage(open)) = routed else {
+ panic!("a conversation message should reach its reserved session");
+ };
+ assert_eq!(id, session_id);
+ assert_eq!(open.runtime.kind, kind);
+ }
+}
diff --git a/crates/agent_harness/src/inbound/mod.rs b/crates/agent_harness/src/inbound/mod.rs
index 728a1211c7..b5bb8849b9 100644
--- a/crates/agent_harness/src/inbound/mod.rs
+++ b/crates/agent_harness/src/inbound/mod.rs
@@ -5,6 +5,8 @@
/// Authenticated ACP capability discovery.
pub mod capability_discovery;
+/// Authenticated agent conversation metadata and controls.
+pub mod conversations;
pub mod kafka;
/// Authenticated model discovery.
pub mod model_load;
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index f3dd5d402e..035f51aa9b 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -18,6 +18,7 @@ mod test;
use std::sync::Arc;
use agent_egress::domain::approval::MACRO_SERVER_SLUG;
+use agent_fold::domain::model::{ActivityStatus, ProjectedSegment, SegmentKind, TurnId, TurnPhase};
use agent_session::domain::model::AgentSessionId;
use bot_id::BotId;
use entity_access::domain::{
@@ -26,8 +27,9 @@ use entity_access::domain::{
};
use lexical_client::LexicalClient;
use lexical_client::parse_markdown::{
- AgentAnnouncementChip, AgentAnnouncementReplyTarget, AgentChatReply, AgentChatReplyBody,
- AgentConnectionChip, AgentConnectionPrompt,
+ AgentActivityRow, AgentActivityStatus, AgentAnnouncementChip, AgentAnnouncementReplyTarget,
+ AgentChatReply, AgentChatReplyBody, AgentConnectionChip, AgentConnectionPrompt,
+ AgentReplySegment,
};
use macro_user_id::user_id::MacroUserIdStr;
use messages::domain::{
@@ -36,14 +38,14 @@ use messages::domain::{
MessageAttribution, MessageParent, PatchMessageNotificationPolicy, PostMessage,
PostMessageNotificationPolicy,
},
- ports::{MessageError, MessagePatch},
+ ports::{AgentTyping, AgentTypingPhase, MessageError, MessagePatch},
service::MessageWrite,
};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
- AnnouncedMessage, DeclinedMention, HeldToolCall, ReplyOutcome, ResolvedReply,
- SessionAnnouncement, SessionBlocker,
+ AgentTypingUpdate, AnnouncedMessage, DeclinedMention, HeldToolCall, ReplyOutcome,
+ ReplyPresentation, ResolvedReply, SessionAnnouncement, SessionBlocker,
};
use crate::domain::ports::SessionAnnouncer;
@@ -73,6 +75,111 @@ fn chat_reply(session_id: AgentSessionId, body: AgentChatReplyBody) -> AgentChat
AgentChatReply {
session_id: session_id.to_string(),
body,
+ link: None,
+ }
+}
+
+/// A reply's segments as the message composer takes them: passages as the
+/// agent wrote them, and runs of steps with their rows. Requests for the
+/// user are answered live and are not part of a message.
+fn reply_segments(turn: TurnId, segments: &[ProjectedSegment]) -> Vec<AgentReplySegment> {
+ segments
+ .iter()
+ .filter_map(|projected| match projected.segment.kind {
+ SegmentKind::Prose => projected
+ .text
+ .clone()
+ .map(|markdown| AgentReplySegment::Prose { markdown }),
+ SegmentKind::Activity => Some(AgentReplySegment::Activity {
+ turn: turn.0,
+ segment: projected.segment.index,
+ rows: projected
+ .segment
+ .rows
+ .iter()
+ .map(|row| AgentActivityRow {
+ id: row.id.clone(),
+ label: row.label.clone(),
+ // Stored messages are readable by the conversation's
+ // audience, which may not have access to the session.
+ // Raw commands and tool inputs stay in authorized live views.
+ detail: None,
+ status: match row.status {
+ ActivityStatus::Running => AgentActivityStatus::Running,
+ ActivityStatus::Completed => AgentActivityStatus::Completed,
+ ActivityStatus::Failed => AgentActivityStatus::Failed,
+ ActivityStatus::Interrupted => AgentActivityStatus::Interrupted,
+ },
+ })
+ .collect(),
+ sealed: projected.segment.sealed,
+ }),
+ SegmentKind::Interaction => None,
+ })
+ .collect()
+}
+
+/// What a message showing a reply's segments says, with how the turn ended
+/// or what it is waiting on. Never blank, like [`reply_body`]: a turn that
+/// said nothing and did nothing is told as such.
+fn segments_body(
+ turn: TurnId,
+ segments: &[ProjectedSegment],
+ outcome: Option<&ReplyOutcome>,
+ pending: bool,
+) -> AgentChatReplyBody {
+ let mut shown = reply_segments(turn, segments);
+ let has_prose = shown
+ .iter()
+ .any(|segment| matches!(segment, AgentReplySegment::Prose { .. }));
+ let mut pending = pending;
+ let footer = match outcome {
+ None => None,
+ // The answer is the reply's last passage; told again only when the
+ // segments do not carry it.
+ Some(ReplyOutcome::Answered(text)) => {
+ if !has_prose {
+ shown.push(AgentReplySegment::Prose {
+ markdown: text.clone(),
+ });
+ }
+ None
+ }
+ Some(ReplyOutcome::Empty) => {
+ (!has_prose && shown.is_empty()).then(|| EMPTY_RESPONSE_FALLBACK.to_owned())
+ }
+ Some(ReplyOutcome::Cancelled) => Some(CANCELLED_FALLBACK.to_owned()),
+ Some(ReplyOutcome::Failed) => Some(ERROR_FALLBACK.to_owned()),
+ Some(ReplyOutcome::NeedsInput { question }) => {
+ shown.push(AgentReplySegment::Prose {
+ markdown: format!("{NEEDS_INPUT_LEAD}\n\n{question}"),
+ });
+ pending = false;
+ None
+ }
+ // The steps so far, then who the turn waits on.
+ Some(ReplyOutcome::AwaitingApproval(call)) => {
+ pending = false;
+ Some(awaiting_approval(call))
+ }
+ Some(ReplyOutcome::Resumed) => {
+ pending = true;
+ None
+ }
+ };
+ AgentChatReplyBody::Segments {
+ segments: shown,
+ pending,
+ footer,
+ }
+}
+
+fn typing_phase(phase: TurnPhase) -> AgentTypingPhase {
+ match phase {
+ TurnPhase::Thinking => AgentTypingPhase::Thinking,
+ TurnPhase::Writing => AgentTypingPhase::Writing,
+ TurnPhase::Working => AgentTypingPhase::Working,
+ TurnPhase::Waiting => AgentTypingPhase::Waiting,
}
}
@@ -296,7 +403,7 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
.post(
access,
PostMessage {
- id: None,
+ id: announcement.reply_message_id,
attribution: MessageAttribution::ActingUser,
// Neither shape is news yet. The chip is a pointer: the
// thread hears about the session when it finishes or
@@ -305,7 +412,9 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
// answer, as the answer.
notification_policy: PostMessageNotificationPolicy::Silent,
content,
- thread_id: Some(announcement.origin_thread_id),
+ thread_id: announcement
+ .reply_placement
+ .thread_id(announcement.origin_thread_id),
anchor: None,
mentions: Vec::new(),
attachments: Vec::new(),
@@ -332,8 +441,20 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
.await?;
let message_id = resolution.message_id;
let notification_policy = patch_policy(&resolution.outcome);
- let body = reply_body(resolution.outcome);
- let carries_answer = matches!(body, AgentChatReplyBody::Markdown { .. });
+ let body = if resolution.segments.is_empty() {
+ reply_body(resolution.outcome)
+ } else {
+ segments_body(
+ resolution.turn,
+ &resolution.segments,
+ Some(&resolution.outcome),
+ false,
+ )
+ };
+ let carries_answer = matches!(
+ body,
+ AgentChatReplyBody::Markdown { .. } | AgentChatReplyBody::Segments { .. }
+ );
let patch = |content| MessagePatch {
notification_policy,
content: Some(content),
@@ -413,7 +534,10 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
anchor: None,
content,
mentions: Vec::new(),
- thread_id: Some(declined.origin.thread_id),
+ thread_id: declined
+ .origin
+ .reply_placement
+ .thread_id(declined.origin.thread_id),
attachments: Vec::new(),
nonce: None,
// Unlike a session chip, this is the whole answer: the
@@ -426,4 +550,104 @@ impl<Access: EntityAccessService> SessionAnnouncer for MessageAnnouncer<Access>
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
Ok(())
}
+
+ async fn present(&self, presentation: ReplyPresentation) -> Result<()> {
+ let access = self
+ .bot_write(
+ presentation.bot_id,
+ presentation.triggered_by.clone(),
+ &presentation.parent,
+ )
+ .await?;
+ let body = match (&presentation.outcome, presentation.segments.is_empty()) {
+ // Nothing to show but how the turn ended.
+ (Some(outcome), true) => reply_body(outcome.clone()),
+ (outcome, _) => segments_body(
+ presentation.turn,
+ &presentation.segments,
+ outcome.as_ref(),
+ presentation.pending,
+ ),
+ };
+ let content = self
+ .lexical
+ .compose_agent_chat_reply(&AgentChatReply {
+ session_id: presentation.session_id.to_string(),
+ body,
+ link: Some(presentation.link),
+ })
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ let message_id = presentation.message_id;
+ // Posted under its allocated id; a message already there under it is
+ // the same reply shown before, and is returned instead.
+ let shown = self
+ .messages
+ .post_from_event(
+ access.clone(),
+ message_id,
+ PostMessage {
+ id: None,
+ attribution: MessageAttribution::ActingUser,
+ // Only the reply's last message is news. Earlier ones are
+ // posted as the agent works, the way a teammate's
+ // messages arrive while you watch.
+ notification_policy: if presentation.notify {
+ PostMessageNotificationPolicy::Default
+ } else {
+ PostMessageNotificationPolicy::Silent
+ },
+ content: content.clone(),
+ thread_id: presentation.thread_id,
+ anchor: None,
+ mentions: Vec::new(),
+ attachments: Vec::new(),
+ nonce: None,
+ },
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
+ // A participant deleted it while the agent ran: they did not want it.
+ if shown.deleted_at.is_some() || shown.content == content {
+ return Ok(());
+ }
+ match self
+ .messages
+ .patch(
+ access,
+ message_id,
+ MessagePatch {
+ content: Some(content),
+ notification_policy: if presentation.notify {
+ PatchMessageNotificationPolicy::NotifyAsPostedMessage
+ } else {
+ PatchMessageNotificationPolicy::Default
+ },
+ ..Default::default()
+ },
+ )
+ .await
+ {
+ Ok(_) | Err(MessageError::NotFound) => Ok(()),
+ Err(error) => Err(HarnessError::Announce(rootcause::report!(error).into())),
+ }
+ }
+
+ async fn typing(&self, typing: AgentTypingUpdate) -> Result<()> {
+ let access = self
+ .bot_write(typing.bot_id, typing.triggered_by, &typing.parent)
+ .await?;
+ self.messages
+ .agent_typing(
+ access,
+ typing.thread_id,
+ typing.active,
+ AgentTyping {
+ session_id: typing.session_id.as_uuid(),
+ phase: typing_phase(typing.phase),
+ },
+ )
+ .await
+ .map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))
+ }
}
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index 4b838b28aa..b586b36df3 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -13,6 +13,8 @@ use messages::domain::models::Message;
fn announcement() -> SessionAnnouncement {
SessionAnnouncement {
+ reply_message_id: None,
+ reply_placement: Default::default(),
reuse_origin_message: false,
bot_id: BotId::TEST_A,
is_coding: true,
@@ -112,6 +114,7 @@ fn markdown(body: AgentChatReplyBody) -> String {
match body {
AgentChatReplyBody::Markdown { markdown } => markdown,
AgentChatReplyBody::Pending => panic!("expected prose, got the spinner"),
+ AgentChatReplyBody::Segments { .. } => panic!("expected prose, got segments"),
}
}
@@ -129,6 +132,7 @@ fn every_reply_names_its_session() {
AgentChatReply {
session_id: "00000000-0000-0000-0000-00000000000a".to_owned(),
body: AgentChatReplyBody::Pending,
+ link: None,
}
);
}
@@ -419,6 +423,8 @@ async fn an_answer_the_thread_may_not_carry_points_at_the_session() {
origin_parent: parent,
triggered_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
outcome: ReplyOutcome::Answered("Your emails: <m-document-mention/>".to_owned()),
+ turn: agent_fold::domain::model::TurnId(0),
+ segments: Vec::new(),
})
.await
.expect("the pointer replaces the spinner");
@@ -428,3 +434,122 @@ async fn an_answer_the_thread_may_not_carry_points_at_the_session() {
["composed answer", "composed pointer"]
);
}
+
+/// Shared threads and DMs both persist message snapshots. Neither audience
+/// grants session access, even when the live view can show tool details.
+#[tokio::test]
+async fn shared_thread_and_dm_snapshots_omit_raw_tool_details() {
+ use agent_fold::domain::model::{ActivityRow, Segment};
+ let segments = vec![ProjectedSegment {
+ segment: Segment {
+ index: 1,
+ kind: SegmentKind::Activity,
+ start: 0,
+ end: 3,
+ sealed: true,
+ rows: vec![
+ ActivityRow {
+ id: "terminal".into(),
+ label: "Ran".into(),
+ detail: Some("TOKEN=private-value run-report".into()),
+ status: ActivityStatus::Completed,
+ },
+ ActivityRow {
+ id: "search".into(),
+ label: "Searched".into(),
+ detail: Some("confidential acquisition".into()),
+ status: ActivityStatus::Completed,
+ },
+ ActivityRow {
+ id: "request".into(),
+ label: "Fetched".into(),
+ detail: Some("https://internal.example/?token=private-value".into()),
+ status: ActivityStatus::Failed,
+ },
+ ],
+ },
+ text: None,
+ }];
+ for thread in [None, Some(Uuid::from_u128(2))] {
+ let lexical = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::path("/agent-announcement"))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"markdown": "safe activity"})),
+ )
+ .expect(1)
+ .mount(&lexical)
+ .await;
+ let parent = MessageParent::Channel(Uuid::from_u128(1));
+ let message_parent = parent.clone();
+ let mut messages = messages::domain::api::MockMessageCommands::new();
+ messages
+ .expect_post_from_event()
+ .times(1)
+ .returning(move |_, id, post| {
+ assert_eq!(post.thread_id, thread);
+ assert_eq!(post.content, "safe activity");
+ Ok(Message {
+ id,
+ parent: message_parent.clone(),
+ thread_id: thread,
+ sender_id: channel_sender::ChannelSender::new_from_user(
+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ ),
+ triggered_by: None,
+ bot_profile: None,
+ mentions: vec![],
+ imported_author: None,
+ content: post.content,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ edited_at: None,
+ deleted_at: None,
+ attachments: vec![],
+ reactions: vec![],
+ })
+ });
+ let announcer = MessageAnnouncer::new(
+ Arc::new(messages),
+ Arc::new(EditingAccess),
+ LexicalClient::new("test-key".to_owned(), lexical.uri()),
+ );
+ announcer
+ .present(ReplyPresentation {
+ session_id: SESSION,
+ bot_id: BotId::TEST_A,
+ triggered_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ parent,
+ thread_id: thread,
+ message_id: Uuid::from_u128(3),
+ turn: TurnId(0),
+ segments: segments.clone(),
+ link: thread.is_some(),
+ pending: false,
+ outcome: None,
+ notify: false,
+ })
+ .await
+ .unwrap();
+ let requests = lexical.received_requests().await.unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
+ let rows = body["chatReply"]["body"]["segments"][0]["rows"]
+ .as_array()
+ .unwrap();
+ assert_eq!(rows.len(), 3);
+ assert!(rows.iter().all(|row| row.get("detail").is_none()));
+ assert_eq!(rows[0]["label"], "Ran");
+ assert_eq!(rows[0]["status"], "completed");
+ assert_eq!(rows[2]["status"], "failed");
+ let serialized = String::from_utf8(requests[0].body.clone()).unwrap();
+ assert!(!serialized.contains("private-value"));
+ assert!(!serialized.contains("confidential acquisition"));
+ assert!(!serialized.contains("internal.example"));
+ }
+ assert_eq!(
+ segments[0].segment.rows[0].detail.as_deref(),
+ Some("TOKEN=private-value run-report"),
+ "snapshot serialization leaves live session details intact"
+ );
+}
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context.rs b/crates/agent_harness/src/outbound/channel_prompt_context.rs
index 127b40a514..9219e87fe4 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context.rs
@@ -10,11 +10,13 @@ use crate::domain::{
ports::MessagePromptContext,
};
use entity_access::domain::{
- models::{EntityAccessReceipt, EntityType},
+ models::{AccessError, EntityAccessReceipt, EntityType},
ports::EntityAccessService,
};
use macro_user_id::user_id::MacroUserIdStr;
-use messages::domain::{api::MessageReader, models::MessageParent, service::MessageWrite};
+use messages::domain::{
+ api::MessageReader, models::MessageParent, ports::MessageError, service::MessageWrite,
+};
use std::sync::Arc;
trait ContextAuthorizer: Send + Sync + 'static {
@@ -45,7 +47,36 @@ impl<Access: EntityAccessService> ContextAuthorizer for Access {
},
)
.await
- .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))
+ .map_err(access_refused)
+ }
+}
+
+/// An access check that answered no is final for the origin; one that could
+/// not answer may succeed later.
+fn access_refused(error: AccessError) -> HarnessError {
+ match error {
+ AccessError::Unauthorized
+ | AccessError::UnauthorizedWithMessage(_)
+ | AccessError::NotFound(_)
+ | AccessError::BadRequest(_) => {
+ HarnessError::InvalidOrigin(rootcause::report!(error).into())
+ }
+ AccessError::Unavailable(_) | AccessError::Internal(_) => {
+ HarnessError::PromptContext(rootcause::report!(error).into())
+ }
+ }
+}
+
+/// A message that is gone or out of the actor's reach is final for the
+/// origin; a read that failed may succeed later.
+fn read_refused(error: MessageError) -> HarnessError {
+ match error {
+ MessageError::NotFound | MessageError::Forbidden | MessageError::Invalid(_) => {
+ HarnessError::InvalidOrigin(rootcause::report!(error).into())
+ }
+ MessageError::Conflict | MessageError::Repository(_) => {
+ HarnessError::PromptContext(rootcause::report!(error).into())
+ }
}
}
@@ -73,17 +104,17 @@ impl<Access: ContextAuthorizer> MessagePromptContext for MessagePromptContextAda
.capability(actor, &origin.parent)
.await?
.try_into_requirement()
- .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ .map_err(|error| HarnessError::InvalidOrigin(rootcause::report!(error).into()))?;
let message = self
.messages
.get(access, origin.message_id)
.await
- .map_err(|error| HarnessError::PromptContext(rootcause::report!(error).into()))?;
+ .map_err(read_refused)?;
if message.root_id() != origin.thread_id
|| message.parent != origin.parent
|| message.deleted_at.is_some()
{
- return Err(HarnessError::PromptContext(rootcause::report!(
+ return Err(HarnessError::InvalidOrigin(rootcause::report!(
"invalid agent message origin"
)));
}
diff --git a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
index 9513ee70b1..9824fc8778 100644
--- a/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
+++ b/crates/agent_harness/src/outbound/channel_prompt_context/test.rs
@@ -37,6 +37,7 @@ fn actor() -> MacroUserIdStr<'static> {
}
fn origin() -> AnnounceOrigin {
AnnounceOrigin {
+ reply_placement: Default::default(),
reuse_origin_message: false,
parent: MessageParent::parse("document", "doc").unwrap(),
thread_id: Uuid::from_u128(1),
@@ -164,6 +165,53 @@ async fn a_claimed_root_or_parent_cannot_link_an_unrelated_session() {
Arc::new(source),
Arc::new(Authorizer { allowed: true }),
);
- assert!(adapter.authorize_origin(&actor(), &origin()).await.is_err());
+ assert!(matches!(
+ adapter.authorize_origin(&actor(), &origin()).await,
+ Err(HarnessError::InvalidOrigin(_))
+ ));
}
}
+
+/// Only a message that is gone or out of reach makes its origin invalid for
+/// good; a read that failed may be asked again.
+#[tokio::test]
+async fn a_failed_read_is_not_mistaken_for_a_gone_message() {
+ for (failure, gone) in [
+ (MessageError::NotFound, true),
+ (MessageError::Forbidden, true),
+ (
+ MessageError::Repository(rootcause::report!("connection reset")),
+ false,
+ ),
+ ] {
+ let mut source = MockMessageReader::new();
+ source
+ .expect_get()
+ .once()
+ .return_once(move |_, _| Err(failure));
+ let adapter = MessagePromptContextAdapter::new(
+ Arc::new(source),
+ Arc::new(Authorizer { allowed: true }),
+ );
+ let result = adapter.authorize_origin(&actor(), &origin()).await;
+ if gone {
+ assert!(matches!(result, Err(HarnessError::InvalidOrigin(_))));
+ } else {
+ assert!(matches!(result, Err(HarnessError::PromptContext(_))));
+ }
+ }
+}
+
+#[test]
+fn an_access_check_that_could_not_answer_is_not_a_refusal() {
+ assert!(matches!(
+ access_refused(AccessError::Unauthorized),
+ HarnessError::InvalidOrigin(_)
+ ));
+ assert!(matches!(
+ access_refused(AccessError::Unavailable(rootcause::report!(
+ "pool timed out"
+ ))),
+ HarnessError::PromptContext(_)
+ ));
+}
diff --git a/crates/agent_harness/src/outbound/conversation_turns.rs b/crates/agent_harness/src/outbound/conversation_turns.rs
new file mode 100644
index 0000000000..bf0dfe477c
--- /dev/null
+++ b/crates/agent_harness/src/outbound/conversation_turns.rs
@@ -0,0 +1,412 @@
+//! PostgreSQL mechanics for the harness-owned conversation turn journal.
+
+use agent_runtime_protocol::domain::action::AgentActionId;
+use agent_session::domain::{error::Result, model::AgentSessionId};
+use bot_id::BotId;
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+
+#[cfg(test)]
+mod test;
+
+use crate::domain::{
+ conversation_turns::{
+ ConversationLease, ConversationSettings, ConversationTurn, ConversationTurnState,
+ ConversationTurnStatus, ConversationTurnStore,
+ },
+ model::{OpenSession, ReplyOutcome},
+ queue::InFlightTurn,
+};
+
+/// A journal independent of the ephemeral runtime and working command queue.
+#[derive(Clone)]
+pub struct PgConversationTurnStore {
+ pool: PgPool,
+ /// Pooled connections a session bootstrap may hold for its whole open.
+ delivery_slots: std::sync::Arc<tokio::sync::Semaphore>,
+ /// Pooled connections held by admission and the context changes it
+ /// serializes with, which last a few queries. A message waiting here
+ /// holds up every broker event behind it, so it never waits on a slow
+ /// bootstrap or on a reply being posted.
+ context_slots: std::sync::Arc<tokio::sync::Semaphore>,
+ /// Pooled connections held by reply reconciliation while it posts a
+ /// turn's reply.
+ reply_slots: std::sync::Arc<tokio::sync::Semaphore>,
+}
+
+/// How long a lease waits for a pooled connection before reporting itself
+/// unavailable. Holders release theirs within a few queries, or once a
+/// bootstrap has opened its session.
+const SLOT_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
+
+/// Wait for one of `slots`, leaving the rest of the pool to everything else.
+async fn take_slot(
+ slots: &std::sync::Arc<tokio::sync::Semaphore>,
+) -> Option<tokio::sync::OwnedSemaphorePermit> {
+ tokio::time::timeout(SLOT_WAIT, slots.clone().acquire_owned())
+ .await
+ .ok()?
+ .ok()
+}
+
+struct PgReplyLease {
+ _transaction: sqlx::Transaction<'static, sqlx::Postgres>,
+ _slot: tokio::sync::OwnedSemaphorePermit,
+}
+impl ConversationLease for PgReplyLease {}
+
+impl PgConversationTurnStore {
+ /// Construct at the composition root from MacroDB.
+ pub fn new(pool: PgPool) -> Self {
+ let slots = (pool.options().get_max_connections() as usize / 4).clamp(1, 16);
+ Self {
+ pool,
+ delivery_slots: std::sync::Arc::new(tokio::sync::Semaphore::new(slots)),
+ context_slots: std::sync::Arc::new(tokio::sync::Semaphore::new(slots)),
+ reply_slots: std::sync::Arc::new(tokio::sync::Semaphore::new(slots)),
+ }
+ }
+}
+
+fn decode(value: serde_json::Value) -> Result<ConversationTurn> {
+ serde_json::from_value(value)
+ .map_err(anyhow::Error::from)
+ .map_err(Into::into)
+}
+
+#[async_trait::async_trait]
+impl ConversationTurnStore for PgConversationTurnStore {
+ async fn claim_delivery(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Option<Box<dyn ConversationLease>>> {
+ let Some(slot) = take_slot(&self.delivery_slots).await else {
+ return Ok(None);
+ };
+ let mut tx = self.pool.begin().await.map_err(anyhow::Error::from)?;
+ let claimed = sqlx::query_scalar!(
+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 45)) AS "claimed!""#,
+ session.to_string()
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(claimed.then(|| {
+ Box::new(PgReplyLease {
+ _transaction: tx,
+ _slot: slot,
+ }) as Box<dyn ConversationLease>
+ }))
+ }
+ async fn claim_context(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Option<Box<dyn ConversationLease>>> {
+ let Some(slot) = take_slot(&self.context_slots).await else {
+ return Ok(None);
+ };
+ let mut tx = self.pool.begin().await.map_err(anyhow::Error::from)?;
+ let claimed = sqlx::query_scalar!(
+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 43)) AS "claimed!""#,
+ session.to_string()
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(claimed.then(|| {
+ Box::new(PgReplyLease {
+ _transaction: tx,
+ _slot: slot,
+ }) as Box<dyn ConversationLease>
+ }))
+ }
+
+ async fn cancel_queued(&self, session: AgentSessionId) -> Result<()> {
+ let outcome = serde_json::to_value(ReplyOutcome::Cancelled).map_err(anyhow::Error::from)?;
+ sqlx::query!("UPDATE agent_conversation_turns SET state = 'stopped', outcome = $2, updated_at = now() WHERE session_id = $1 AND state = 'queued'", session.as_uuid(), outcome)
+ .execute(&self.pool).await.map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn settings(&self, session: AgentSessionId) -> Result<Option<ConversationSettings>> {
+ sqlx::query_scalar!(
+ "SELECT settings FROM agent_conversation_settings WHERE session_id = $1",
+ session.as_uuid()
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?
+ .map(|value| {
+ serde_json::from_value(value)
+ .map_err(anyhow::Error::from)
+ .map_err(Into::into)
+ })
+ .transpose()
+ }
+
+ async fn pin_settings(
+ &self,
+ session: AgentSessionId,
+ settings: ConversationSettings,
+ ) -> Result<ConversationSettings> {
+ let settings = serde_json::to_value(settings).map_err(anyhow::Error::from)?;
+ let value = sqlx::query_scalar!("INSERT INTO agent_conversation_settings AS original (session_id, settings) VALUES ($1, $2) ON CONFLICT (session_id) DO UPDATE SET session_id = original.session_id RETURNING settings", session.as_uuid(), settings)
+ .fetch_one(&self.pool).await.map_err(anyhow::Error::from)?;
+ serde_json::from_value(value)
+ .map_err(anyhow::Error::from)
+ .map_err(Into::into)
+ }
+
+ async fn admit(
+ &self,
+ session: AgentSessionId,
+ channel: Uuid,
+ command: OpenSession,
+ ) -> Result<ConversationTurn> {
+ let source = command.origin.announcement().message_id;
+ let bot = command.bot_id;
+ // A replay keeps the first admission's action id; this one is unused then.
+ let action = AgentActionId::mint();
+ let payload = serde_json::to_value(command).map_err(anyhow::Error::from)?;
+ let value = sqlx::query_scalar!(
+ r#"INSERT INTO agent_conversation_turns AS turn (source_message_id, bot_id, session_id, channel_id, action_id, command)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (source_message_id, bot_id) DO UPDATE SET source_message_id = turn.source_message_id
+ RETURNING to_jsonb(turn) AS "value!""#,
+ source, bot.as_uuid(), session.as_uuid(), channel, action.as_uuid(), payload
+ ).fetch_one(&self.pool).await.map_err(anyhow::Error::from)?;
+ decode(value)
+ }
+
+ async fn get(&self, source: Uuid, bot: BotId) -> Result<Option<ConversationTurn>> {
+ sqlx::query_scalar!(r#"SELECT to_jsonb(j) AS "value!" FROM agent_conversation_turns j WHERE source_message_id = $1 AND bot_id = $2"#, source, bot.as_uuid())
+ .fetch_optional(&self.pool).await.map_err(anyhow::Error::from)?.map(decode).transpose()
+ }
+
+ async fn claim(&self, action: AgentActionId, turn: &InFlightTurn) -> Result<bool> {
+ let flight = serde_json::to_value(turn).map_err(anyhow::Error::from)?;
+ let mut tx = self.pool.begin().await.map_err(anyhow::Error::from)?;
+ // Serialize claims for the conversation's whole session, including two
+ // different source messages received by different replicas at once.
+ sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended(session_id::text, 43)) FROM agent_conversation_turns WHERE action_id = $1", action.as_uuid())
+ .execute(&mut *tx).await.map_err(anyhow::Error::from)?;
+ let claimed = sqlx::query!(
+ "UPDATE agent_conversation_turns AS candidate SET state = 'running', in_flight = $2, updated_at = now() WHERE action_id = $1 AND state = 'queued' AND NOT EXISTS (SELECT 1 FROM agent_conversation_turns other WHERE other.session_id = candidate.session_id AND (other.state IN ('running', 'interrupted') OR (other.state = 'queued' AND (other.created_at, other.source_message_id) < (candidate.created_at, candidate.source_message_id))))",
+ action.as_uuid(), flight
+ ).execute(&mut *tx).await.map_err(anyhow::Error::from)?.rows_affected() == 1;
+ tx.commit().await.map_err(anyhow::Error::from)?;
+ Ok(claimed)
+ }
+
+ // Retryable exactly when `for_conversation` reports the turn retryable.
+ async fn retry(&self, source: Uuid, bot: BotId, expected: AgentActionId) -> Result<bool> {
+ let action = AgentActionId::mint();
+ Ok(sqlx::query!("UPDATE agent_conversation_turns SET action_id = $4, state = 'queued', in_flight = NULL, outcome = NULL, reply_segments = NULL, reply_finalized = FALSE, updated_at = now() WHERE source_message_id = $1 AND bot_id = $2 AND action_id = $3 AND state IN ('failed', 'stopped', 'interrupted') AND (reply_finalized OR in_flight->>'announcement_message_id' IS NULL)", source, bot.as_uuid(), expected.as_uuid(), action.as_uuid())
+ .execute(&self.pool).await.map_err(anyhow::Error::from)?.rows_affected() == 1)
+ }
+
+ async fn by_action(&self, action: AgentActionId) -> Result<Option<ConversationTurn>> {
+ sqlx::query_scalar!(
+ r#"SELECT to_jsonb(j) AS "value!" FROM agent_conversation_turns j WHERE action_id = $1"#,
+ action.as_uuid()
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?
+ .map(decode)
+ .transpose()
+ }
+
+ async fn record_flight(&self, action: AgentActionId, turn: &InFlightTurn) -> Result<()> {
+ let flight = serde_json::to_value(turn).map_err(anyhow::Error::from)?;
+ sqlx::query!("UPDATE agent_conversation_turns SET in_flight = $2, updated_at = now() WHERE action_id = $1 AND state = 'running'", action.as_uuid(), flight)
+ .execute(&self.pool).await.map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn record_reply_flight(
+ &self,
+ action: AgentActionId,
+ expected: &InFlightTurn,
+ turn: &InFlightTurn,
+ ) -> Result<bool> {
+ if expected.action_id != action || turn.action_id != action {
+ return Ok(false);
+ }
+ let expected = serde_json::to_value(expected).map_err(anyhow::Error::from)?;
+ let flight = serde_json::to_value(turn).map_err(anyhow::Error::from)?;
+ let saved = sqlx::query!(
+ "UPDATE agent_conversation_turns SET in_flight = $2, updated_at = now() WHERE action_id = $1 AND state IN ('succeeded', 'failed', 'stopped', 'interrupted') AND NOT reply_finalized AND in_flight = $3",
+ action.as_uuid(), flight, expected
+ ).execute(&self.pool).await.map_err(anyhow::Error::from)?;
+ Ok(saved.rows_affected() == 1)
+ }
+
+ async fn save_reply(
+ &self,
+ action: AgentActionId,
+ segments: &[agent_fold::domain::model::ProjectedSegment],
+ ) -> Result<()> {
+ let segments = serde_json::to_value(segments).map_err(anyhow::Error::from)?;
+ sqlx::query!(
+ "UPDATE agent_conversation_turns SET reply_segments = $2 WHERE action_id = $1",
+ action.as_uuid(),
+ segments
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn finish(
+ &self,
+ action: AgentActionId,
+ state: ConversationTurnState,
+ outcome: ReplyOutcome,
+ ) -> Result<()> {
+ let state = serde_json::to_value(state).map_err(anyhow::Error::from)?;
+ let state = state.as_str().expect("turn states serialize as strings");
+ let outcome = serde_json::to_value(outcome).map_err(anyhow::Error::from)?;
+ sqlx::query!(
+ "UPDATE agent_conversation_turns SET state = $2, outcome = $3, reply_finalized = FALSE, updated_at = now() WHERE action_id = $1 AND (state IN ('queued', 'running') OR (state = 'interrupted' AND $2 != 'interrupted'))",
+ action.as_uuid(), state, outcome
+ ).execute(&self.pool).await.map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn fail_queued(&self, action: AgentActionId) -> Result<()> {
+ let outcome = serde_json::to_value(ReplyOutcome::Failed).map_err(anyhow::Error::from)?;
+ sqlx::query!(
+ "UPDATE agent_conversation_turns SET state = 'failed', outcome = $2, reply_finalized = FALSE, updated_at = now() WHERE action_id = $1 AND state = 'queued'",
+ action.as_uuid(),
+ outcome
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn finalize_reply(&self, action: AgentActionId, outcome: &ReplyOutcome) -> Result<()> {
+ let outcome = serde_json::to_value(outcome).map_err(anyhow::Error::from)?;
+ sqlx::query!("UPDATE agent_conversation_turns SET reply_finalized = TRUE, updated_at = now() WHERE action_id = $1 AND outcome = $2", action.as_uuid(), outcome)
+ .execute(&self.pool).await.map_err(anyhow::Error::from)?;
+ Ok(())
+ }
+
+ async fn claim_reply(
+ &self,
+ action: AgentActionId,
+ ) -> Result<Option<Box<dyn ConversationLease>>> {
+ // Leave pool capacity for the message service while a reply lock is held.
+ let Some(slot) = take_slot(&self.reply_slots).await else {
+ return Ok(None);
+ };
+ let mut tx = self.pool.begin().await.map_err(anyhow::Error::from)?;
+ let claimed = sqlx::query_scalar!(
+ r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 44)) AS "claimed!""#,
+ action.to_string()
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if !claimed {
+ return Ok(None);
+ }
+ Ok(Some(Box::new(PgReplyLease {
+ _transaction: tx,
+ _slot: slot,
+ })))
+ }
+
+ async fn pending(&self, limit: u16) -> Result<Vec<ConversationTurn>> {
+ // The same condition a claim checks, so turns waiting behind a running
+ // one are left to the replica running it.
+ sqlx::query_scalar!(r#"SELECT to_jsonb(j) AS "value!" FROM agent_conversation_turns j WHERE state = 'queued' AND NOT EXISTS (SELECT 1 FROM agent_conversation_turns other WHERE other.session_id = j.session_id AND (other.state IN ('running', 'interrupted') OR (other.state = 'queued' AND (other.created_at, other.source_message_id) < (j.created_at, j.source_message_id)))) ORDER BY created_at, source_message_id LIMIT $1"#, i64::from(limit))
+ .fetch_all(&self.pool).await.map_err(anyhow::Error::from)?.into_iter().map(decode).collect()
+ }
+
+ async fn running(&self, limit: u16) -> Result<Vec<ConversationTurn>> {
+ sqlx::query_scalar!(r#"SELECT to_jsonb(j) AS "value!" FROM agent_conversation_turns j WHERE state = 'running' AND updated_at < now() - interval '2 minutes' ORDER BY updated_at LIMIT $1"#, i64::from(limit))
+ .fetch_all(&self.pool).await.map_err(anyhow::Error::from)?.into_iter().map(decode).collect()
+ }
+
+ async fn for_conversation(
+ &self,
+ channel: Uuid,
+ bot: BotId,
+ recent: u16,
+ ) -> Result<Vec<ConversationTurnStatus>> {
+ sqlx::query_scalar!(
+ r#"
+ WITH sessions AS (
+ SELECT session_id
+ FROM agent_conversation_sessions
+ WHERE channel_id = $1 AND bot_id = $2
+ ),
+ shown AS (
+ -- Whatever waits or runs, however long ago it was posted.
+ SELECT turn.source_message_id
+ FROM agent_conversation_turns turn
+ JOIN sessions ON sessions.session_id = turn.session_id
+ WHERE turn.state IN ('queued', 'running')
+ UNION
+ -- Each session's first turn, where the transcript shows its
+ -- context starting fresh.
+ SELECT first.source_message_id
+ FROM sessions
+ CROSS JOIN LATERAL (
+ SELECT source_message_id
+ FROM agent_conversation_turns
+ WHERE session_id = sessions.session_id
+ ORDER BY created_at, source_message_id
+ LIMIT 1
+ ) first
+ UNION
+ (
+ SELECT source_message_id
+ FROM agent_conversation_turns
+ WHERE channel_id = $1 AND bot_id = $2
+ ORDER BY created_at DESC, source_message_id DESC
+ LIMIT $3
+ )
+ )
+ SELECT jsonb_build_object(
+ 'source_message_id', source_message_id,
+ 'bot_id', bot_id,
+ 'session_id', session_id,
+ 'action_id', action_id,
+ 'reply_message_id', in_flight->'announcement_message_id',
+ 'state', state,
+ 'retryable', state IN ('failed', 'stopped', 'interrupted')
+ AND (reply_finalized OR in_flight->>'announcement_message_id' IS NULL),
+ 'created_at', created_at
+ ) AS "value!"
+ FROM agent_conversation_turns
+ WHERE channel_id = $1
+ AND bot_id = $2
+ AND source_message_id IN (SELECT source_message_id FROM shown)
+ ORDER BY created_at, source_message_id
+ "#,
+ channel,
+ bot.as_uuid(),
+ i64::from(recent),
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?
+ .into_iter()
+ .map(|value| {
+ serde_json::from_value(value)
+ .map_err(anyhow::Error::from)
+ .map_err(Into::into)
+ })
+ .collect()
+ }
+
+ async fn pending_replies(&self, limit: u16) -> Result<Vec<ConversationTurn>> {
+ sqlx::query_scalar!(r#"SELECT to_jsonb(j) AS "value!" FROM agent_conversation_turns j WHERE outcome IS NOT NULL AND NOT reply_finalized ORDER BY updated_at LIMIT $1"#, i64::from(limit))
+ .fetch_all(&self.pool).await.map_err(anyhow::Error::from)?.into_iter().map(decode).collect()
+ }
+}
diff --git a/crates/agent_harness/src/outbound/conversation_turns/test.rs b/crates/agent_harness/src/outbound/conversation_turns/test.rs
new file mode 100644
index 0000000000..b15bfd2837
--- /dev/null
+++ b/crates/agent_harness/src/outbound/conversation_turns/test.rs
@@ -0,0 +1,924 @@
+use super::*;
+use crate::domain::conversations::{
+ AgentConversations, AgentConversationsService, ConversationError,
+};
+use crate::domain::model::{
+ AgentKind, AgentRuntimeConfig, AnnounceOrigin, MentionOrigin, ReplyPlacement,
+};
+use agent_fold::domain::model::TurnId;
+use agent_session::domain::agent_conversation::{AgentConversation, AgentConversationRepo};
+use bots::domain::ports::{AgentDmEligibility, BotError, MockBotRepo};
+use channels::{domain::agent_dm::AgentDmRepo, outbound::pg_channels_repo::PgChannelsRepo};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Arc;
+
+struct Eligibility(bool);
+impl AgentDmEligibility for Eligibility {
+ async fn authorize_agent_dm(
+ &self,
+ _: MacroUserIdStr<'static>,
+ _: bot_id::BotId,
+ ) -> std::result::Result<(), BotError> {
+ if self.0 {
+ Ok(())
+ } else {
+ Err(BotError::Unauthorized)
+ }
+ }
+}
+
+fn conversation(channel: Uuid) -> AgentConversation {
+ AgentConversation {
+ channel_id: channel,
+ bot_id: bot_id::MACRO_NEW_BOT_ID,
+ }
+}
+
+fn conversations(
+ pool: PgPool,
+ store: PgConversationTurnStore,
+ eligible: bool,
+) -> impl AgentConversations {
+ AgentConversationsService::new(
+ PgChannelsRepo::new(pool.clone()),
+ Eligibility(eligible),
+ MockBotRepo::new(),
+ crate::testing::postgres_sessions(pool),
+ )
+ .with_turns(Arc::new(store))
+}
+
+async fn setup(pool: PgPool) -> (PgConversationTurnStore, AgentSessionId, Uuid, OpenSession) {
+ let user = macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let channel = PgChannelsRepo::new(pool.clone())
+ .ensure(user.clone(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .dm
+ .channel_id;
+ let session = crate::testing::postgres_sessions(pool.clone())
+ .current_or_create(conversation(channel))
+ .await
+ .unwrap();
+ let source = macro_uuid::generate_uuid_v7();
+ let command = OpenSession {
+ bot_id: bot_id::MACRO_NEW_BOT_ID,
+ runtime: AgentRuntimeConfig {
+ kind: AgentKind::InMemory,
+ model: "test".to_owned(),
+ harness: "macro-inmem".to_owned(),
+ instructions: "Keep decisions".to_owned(),
+ mcp_servers: agent_session::domain::model::AgentMcpServers::OwnerConnections,
+ },
+ origin: crate::domain::model::SessionOrigin::Mention(MentionOrigin {
+ reply_placement: ReplyPlacement::Timeline,
+ parent: messages::domain::models::MessageParent::Channel(channel),
+ thread_id: source,
+ message_id: source,
+ sender: user,
+ content: "Remember this".to_owned(),
+ attachments: vec![],
+ context: None,
+ }),
+ };
+ (
+ PgConversationTurnStore::new(pool),
+ session,
+ channel,
+ command,
+ )
+}
+
+fn flight(record: &ConversationTurn) -> InFlightTurn {
+ InFlightTurn {
+ action_id: record.action_id,
+ turn: TurnId(0),
+ actor: Some(mention_origin(&record.command).sender.clone()),
+ announce: Some(AnnounceOrigin {
+ reuse_origin_message: false,
+ reply_placement: ReplyPlacement::Timeline,
+ parent: mention_origin(&record.command).parent.clone(),
+ thread_id: record.source_message_id,
+ message_id: record.source_message_id,
+ }),
+ announcement_message_id: Some(macro_uuid::generate_uuid_v7()),
+ dispatched_at: chrono::Utc::now(),
+ bot_id: None,
+ speaks_as_chip: false,
+ presented: Vec::new(),
+ held_tool_calls: Vec::new(),
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn replay_after_reset_retains_the_original_session_payload_and_terminal_deduplication(
+ pool: PgPool,
+) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let original = store
+ .admit(session, channel, command.clone())
+ .await
+ .unwrap();
+ let turn = flight(&original);
+ assert!(store.claim(original.action_id, &turn).await.unwrap());
+ store
+ .finish(
+ original.action_id,
+ ConversationTurnState::Succeeded,
+ ReplyOutcome::Answered("Done".into()),
+ )
+ .await
+ .unwrap();
+ let new_session = crate::testing::postgres_sessions(pool)
+ .start_fresh(conversation(channel))
+ .await
+ .unwrap();
+ let mut edited = command;
+ mention_origin_mut(&mut edited).content = "An edited message must not rerun".to_owned();
+ let duplicate = store.admit(new_session, channel, edited).await.unwrap();
+ assert_eq!(duplicate.session_id, session);
+ assert_eq!(mention_origin(&duplicate.command).content, "Remember this");
+ assert_eq!(duplicate.state, ConversationTurnState::Succeeded);
+ assert!(!store.claim(duplicate.action_id, &turn).await.unwrap());
+ assert_eq!(store.pending_replies(10).await.unwrap().len(), 1);
+ store
+ .finalize_reply(duplicate.action_id, &ReplyOutcome::Answered("Done".into()))
+ .await
+ .unwrap();
+ assert!(store.pending_replies(10).await.unwrap().is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn concurrent_replicas_admit_one_record_and_only_one_claim_can_run(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool).await;
+ let (a, b) = tokio::join!(
+ store.admit(session, channel, command.clone()),
+ store.admit(session, channel, command)
+ );
+ let (a, b) = (a.unwrap(), b.unwrap());
+ assert_eq!(a.action_id, b.action_id);
+ assert_eq!(
+ store
+ .for_conversation(channel, bot_id::MACRO_NEW_BOT_ID, 100)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ let turn = flight(&a);
+ let (a, b) = tokio::join!(
+ store.claim(a.action_id, &turn),
+ store.claim(b.action_id, &turn)
+ );
+ assert_ne!(a.unwrap(), b.unwrap());
+ assert!(store.pending(10).await.unwrap().is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn interrupted_work_holds_its_session_queue_until_an_explicit_decision(pool: PgPool) {
+ let (store, session, channel, mut command) = setup(pool.clone()).await;
+ let interrupted = store
+ .admit(session, channel, command.clone())
+ .await
+ .unwrap();
+ store
+ .claim(interrupted.action_id, &flight(&interrupted))
+ .await
+ .unwrap();
+ store
+ .finish(
+ interrupted.action_id,
+ ConversationTurnState::Interrupted,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).message_id = macro_uuid::generate_uuid_v7();
+ store
+ .admit(session, channel, command.clone())
+ .await
+ .unwrap();
+ assert!(store.pending(10).await.unwrap().is_empty());
+ let fresh = crate::testing::postgres_sessions(pool)
+ .start_fresh(conversation(channel))
+ .await
+ .unwrap();
+ mention_origin_mut(&mut command).message_id = macro_uuid::generate_uuid_v7();
+ store.admit(fresh, channel, command).await.unwrap();
+ let pending = store.pending(10).await.unwrap();
+ assert_eq!(pending.len(), 1);
+ assert_eq!(pending[0].session_id, fresh);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_explicit_retry_waits_for_reply_reconciliation_and_mints_only_one_new_attempt(
+ pool: PgPool,
+) {
+ let (store, session, channel, command) = setup(pool).await;
+ let first = store.admit(session, channel, command).await.unwrap();
+ store.claim(first.action_id, &flight(&first)).await.unwrap();
+ store
+ .finish(
+ first.action_id,
+ ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ assert!(
+ !store
+ .retry(
+ first.source_message_id,
+ bot_id::MACRO_NEW_BOT_ID,
+ first.action_id
+ )
+ .await
+ .unwrap()
+ );
+ assert!(store.pending(10).await.unwrap().is_empty());
+ let retryable = async || {
+ store
+ .for_conversation(channel, bot_id::MACRO_NEW_BOT_ID, 100)
+ .await
+ .unwrap()[0]
+ .retryable
+ };
+ assert!(
+ !retryable().await,
+ "the status says what retry would answer"
+ );
+ store
+ .finalize_reply(first.action_id, &ReplyOutcome::Failed)
+ .await
+ .unwrap();
+ assert!(retryable().await);
+ let (a, b) = tokio::join!(
+ store.retry(
+ first.source_message_id,
+ bot_id::MACRO_NEW_BOT_ID,
+ first.action_id
+ ),
+ store.retry(
+ first.source_message_id,
+ bot_id::MACRO_NEW_BOT_ID,
+ first.action_id
+ )
+ );
+ assert_ne!(a.unwrap(), b.unwrap());
+ let next = store
+ .get(first.source_message_id, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_ne!(next.action_id, first.action_id);
+ assert_eq!(next.state, ConversationTurnState::Queued);
+ assert_eq!(
+ mention_origin(&next.command).content,
+ mention_origin(&first.command).content
+ );
+ assert!(next.in_flight.is_none());
+ assert!(store.by_action(first.action_id).await.unwrap().is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reply_claims_release_on_drop_and_stale_finalizers_cannot_hide_a_late_answer(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let other_replica = PgConversationTurnStore::new(pool);
+ let record = store.admit(session, channel, command).await.unwrap();
+ store
+ .claim(record.action_id, &flight(&record))
+ .await
+ .unwrap();
+ let lease = store.claim_reply(record.action_id).await.unwrap().unwrap();
+ assert!(
+ other_replica
+ .claim_reply(record.action_id)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ drop(lease);
+ let lease = tokio::time::timeout(std::time::Duration::from_secs(2), async {
+ loop {
+ if let Some(lease) = other_replica.claim_reply(record.action_id).await.unwrap() {
+ break lease;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ store
+ .finish(
+ record.action_id,
+ ConversationTurnState::Interrupted,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ store
+ .finish(
+ record.action_id,
+ ConversationTurnState::Succeeded,
+ ReplyOutcome::Answered("Completed before disconnect".into()),
+ )
+ .await
+ .unwrap();
+ store
+ .finalize_reply(record.action_id, &ReplyOutcome::Failed)
+ .await
+ .unwrap();
+ let updated = store
+ .get(record.source_message_id, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(!updated.reply_finalized);
+ assert_eq!(updated.state, ConversationTurnState::Succeeded);
+ drop(lease);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn starting_fresh_requires_owner_and_current_persona_access(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let stranger = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let service = conversations(pool.clone(), store.clone(), true);
+ assert!(matches!(
+ service
+ .start_fresh(stranger, conversation(channel), session)
+ .await,
+ Err(ConversationError::NotFound)
+ ));
+ let service = conversations(pool.clone(), store, false);
+ assert!(matches!(
+ service
+ .start_fresh(
+ mention_origin(&command).sender.clone(),
+ conversation(channel),
+ session
+ )
+ .await,
+ Err(ConversationError::NotRetryable)
+ ));
+ assert_eq!(
+ crate::testing::postgres_sessions(pool)
+ .current(conversation(channel))
+ .await
+ .unwrap(),
+ Some(session)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_running_turn_blocks_reset_and_completed_context_is_retained(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let owner = mention_origin(&command).sender.clone();
+ let record = store.admit(session, channel, command).await.unwrap();
+ let service = conversations(pool.clone(), store.clone(), true);
+ assert!(
+ store
+ .claim(record.action_id, &flight(&record))
+ .await
+ .unwrap()
+ );
+ assert!(matches!(
+ service
+ .start_fresh(owner.clone(), conversation(channel), session)
+ .await,
+ Err(ConversationError::ContextBusy)
+ ));
+ store
+ .finish(
+ record.action_id,
+ ConversationTurnState::Succeeded,
+ ReplyOutcome::Answered("Remembered".into()),
+ )
+ .await
+ .unwrap();
+ service
+ .start_fresh(owner.clone(), conversation(channel), session)
+ .await
+ .unwrap();
+ assert!(matches!(
+ service
+ .start_fresh(owner, conversation(channel), session)
+ .await,
+ Err(ConversationError::ContextBusy)
+ ));
+ let sessions = crate::testing::postgres_sessions(pool)
+ .sessions(conversation(channel))
+ .await
+ .unwrap();
+ assert_eq!(sessions.len(), 2);
+ assert_eq!(sessions[0].session_id, session);
+ assert!(!sessions[0].is_current);
+ assert!(sessions[1].is_current);
+ assert_eq!(
+ store
+ .get(record.source_message_id, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ ConversationTurnState::Succeeded
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reset_cancels_undispatched_work_and_serializes_with_claims(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let owner = mention_origin(&command).sender.clone();
+ let record = store.admit(session, channel, command).await.unwrap();
+ let other = PgConversationTurnStore::new(pool.clone());
+ let lease = store.claim_context(session).await.unwrap().unwrap();
+ assert!(other.claim_context(session).await.unwrap().is_none());
+ let mut claiming = tokio::spawn({
+ let other = other.clone();
+ let turn = flight(&record);
+ async move { other.claim(turn.action_id, &turn).await }
+ });
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(30), &mut claiming)
+ .await
+ .is_err()
+ );
+ // The reset's cancellation is visible before a blocked claimant can run.
+ store.cancel_queued(session).await.unwrap();
+ drop(lease);
+ assert!(!claiming.await.unwrap().unwrap());
+ conversations(pool, other, true)
+ .start_fresh(owner, conversation(channel), session)
+ .await
+ .unwrap();
+ assert_eq!(
+ store
+ .get(record.source_message_id, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ ConversationTurnState::Stopped
+ );
+ assert!(store.pending(10).await.unwrap().is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn settings_remain_pinned_after_reconnect_and_new_sessions_adopt_edits(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let original = ConversationSettings {
+ runtime: command.runtime,
+ permissions: crate::domain::model::PermissionPolicyConfig::Persona {
+ kind: AgentKind::External,
+ harness_allows_bypass: Some(true),
+ auto_accept_permissions: Some(false),
+ },
+ };
+ store.pin_settings(session, original.clone()).await.unwrap();
+ let mut edited = original.clone();
+ edited.runtime.instructions = "New instructions".into();
+ edited.runtime.model = "new-model".into();
+ edited.permissions = crate::domain::model::PermissionPolicyConfig::Fixed(AgentKind::InMemory);
+ let reconnected = PgConversationTurnStore::new(pool.clone());
+ assert_eq!(
+ reconnected
+ .pin_settings(session, edited.clone())
+ .await
+ .unwrap(),
+ original
+ );
+ let fresh = crate::testing::postgres_sessions(pool)
+ .start_fresh(conversation(channel))
+ .await
+ .unwrap();
+ assert_eq!(
+ reconnected
+ .pin_settings(fresh, edited.clone())
+ .await
+ .unwrap(),
+ edited
+ );
+ assert_eq!(reconnected.settings(session).await.unwrap(), Some(original));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn two_personas_keep_separate_turns_for_one_message(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let coder = AgentConversation {
+ channel_id: channel,
+ bot_id: bot_id::MACRO_CODER_BOT_ID,
+ };
+ let coder_session = crate::testing::postgres_sessions(pool)
+ .current_or_create(coder)
+ .await
+ .unwrap();
+ let mut to_coder = command.clone();
+ to_coder.bot_id = coder.bot_id;
+ let first = store.admit(session, channel, command).await.unwrap();
+ let second = store.admit(coder_session, channel, to_coder).await.unwrap();
+ assert_eq!(first.source_message_id, second.source_message_id);
+ assert_ne!(first.action_id, second.action_id);
+ assert_eq!(second.session_id, coder_session);
+ for bot in [bot_id::MACRO_NEW_BOT_ID, coder.bot_id] {
+ let turns = store.for_conversation(channel, bot, 100).await.unwrap();
+ assert_eq!(turns.len(), 1);
+ assert_eq!(turns[0].bot_id, bot);
+ }
+ // Each persona's turn runs in its own session, so neither blocks the other.
+ assert!(store.claim(first.action_id, &flight(&first)).await.unwrap());
+ assert!(
+ store
+ .claim(second.action_id, &flight(&second))
+ .await
+ .unwrap()
+ );
+}
+
+fn mention_origin(command: &OpenSession) -> &MentionOrigin {
+ let crate::domain::model::SessionOrigin::Mention(origin) = &command.origin else {
+ panic!("expected a mention");
+ };
+ origin
+}
+
+fn mention_origin_mut(command: &mut OpenSession) -> &mut MentionOrigin {
+ let crate::domain::model::SessionOrigin::Mention(origin) = &mut command.origin else {
+ panic!("expected a mention");
+ };
+ origin
+}
+
+/// A store over a pool the size of the harness service's, where every kind
+/// of lease has a single connection to spare.
+async fn production_sized(pool: &PgPool) -> PgConversationTurnStore {
+ let small = sqlx::postgres::PgPoolOptions::new()
+ .max_connections(5)
+ .connect_with((*pool.connect_options()).clone())
+ .await
+ .unwrap();
+ PgConversationTurnStore::new(small)
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_bootstrapping_session_does_not_starve_admission_or_replies(pool: PgPool) {
+ let (_, session, channel, command) = setup(pool.clone()).await;
+ let store = production_sized(&pool).await;
+ let record = store.admit(session, channel, command).await.unwrap();
+ store
+ .claim(record.action_id, &flight(&record))
+ .await
+ .unwrap();
+ // Another conversation's open holds its delivery lease for seconds.
+ let _bootstrap = store
+ .claim_delivery(AgentSessionId::new())
+ .await
+ .unwrap()
+ .expect("an idle replica leases a bootstrap");
+ assert!(
+ store.claim_context(session).await.unwrap().is_some(),
+ "admission still gets a context lease"
+ );
+ assert!(
+ store.claim_reply(record.action_id).await.unwrap().is_some(),
+ "the turn's end still gets its reply lease"
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_lease_waits_for_a_busy_slot_instead_of_refusing(pool: PgPool) {
+ let (_, session, channel, command) = setup(pool.clone()).await;
+ let store = production_sized(&pool).await;
+ let record = store.admit(session, channel, command).await.unwrap();
+ let held = store
+ .claim_reply(record.action_id)
+ .await
+ .unwrap()
+ .expect("an idle replica leases a reply");
+ let waiting = tokio::spawn({
+ let store = store.clone();
+ async move { store.claim_reply(AgentActionId::mint()).await }
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert!(
+ !waiting.is_finished(),
+ "the only slot is busy, so the lease waits"
+ );
+ drop(held);
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_secs(2), waiting)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap()
+ .is_some(),
+ "the lease is granted once the slot frees"
+ );
+}
+
+/// Admitting a message holds up every broker event behind it, so it never
+/// waits for the slot a reply being posted holds.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn admission_never_waits_behind_a_reply(pool: PgPool) {
+ let (_, session, channel, command) = setup(pool.clone()).await;
+ let store = production_sized(&pool).await;
+ let record = store.admit(session, channel, command).await.unwrap();
+ let _reply = store
+ .claim_reply(record.action_id)
+ .await
+ .unwrap()
+ .expect("an idle replica leases a reply");
+ assert!(
+ tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ store.claim_context(AgentSessionId::new())
+ )
+ .await
+ .expect("admission does not wait for the reply's slot")
+ .unwrap()
+ .is_some()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn recovery_offers_only_turns_a_claim_could_take(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let running = store
+ .admit(session, channel, command.clone())
+ .await
+ .unwrap();
+ let mut waiting = command.clone();
+ if let crate::domain::model::SessionOrigin::Mention(origin) = &mut waiting.origin {
+ origin.message_id = macro_uuid::generate_uuid_v7();
+ }
+ let waiting = store.admit(session, channel, waiting).await.unwrap();
+ assert_eq!(
+ pending_sources(&store).await,
+ [running.source_message_id],
+ "only the oldest queued turn of a session is due"
+ );
+ assert!(
+ store
+ .claim(running.action_id, &flight(&running))
+ .await
+ .unwrap()
+ );
+ assert!(
+ pending_sources(&store).await.is_empty(),
+ "a turn waiting behind a running one is the running replica's to dispatch"
+ );
+ store
+ .finish(
+ running.action_id,
+ ConversationTurnState::Succeeded,
+ ReplyOutcome::Answered("Done".to_owned()),
+ )
+ .await
+ .unwrap();
+ assert_eq!(pending_sources(&store).await, [waiting.source_message_id]);
+}
+
+async fn pending_sources(store: &PgConversationTurnStore) -> Vec<Uuid> {
+ store
+ .pending(50)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|turn| turn.source_message_id)
+ .collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_failed_delivery_attempt_never_fails_a_turn_another_replica_claimed(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool.clone()).await;
+ let record = store.admit(session, channel, command).await.unwrap();
+ let other_replica = PgConversationTurnStore::new(pool);
+ assert!(
+ other_replica
+ .claim(record.action_id, &flight(&record))
+ .await
+ .unwrap()
+ );
+ store.fail_queued(record.action_id).await.unwrap();
+ let after = store.by_action(record.action_id).await.unwrap().unwrap();
+ assert_eq!(after.state, ConversationTurnState::Running);
+ assert!(after.outcome.is_none());
+}
+
+/// Post another message to `session` and leave its turn `state`.
+async fn turn_in(
+ store: &PgConversationTurnStore,
+ session: AgentSessionId,
+ channel: Uuid,
+ command: &mut OpenSession,
+ state: ConversationTurnState,
+) -> ConversationTurn {
+ mention_origin_mut(command).message_id = macro_uuid::generate_uuid_v7();
+ let record = store
+ .admit(session, channel, command.clone())
+ .await
+ .unwrap();
+ match state {
+ ConversationTurnState::Queued => {}
+ ConversationTurnState::Running => {
+ assert!(
+ store
+ .claim(record.action_id, &flight(&record))
+ .await
+ .unwrap()
+ );
+ }
+ ConversationTurnState::Succeeded => store
+ .finish(
+ record.action_id,
+ state,
+ ReplyOutcome::Answered("Done".into()),
+ )
+ .await
+ .unwrap(),
+ state => store
+ .finish(record.action_id, state, ReplyOutcome::Failed)
+ .await
+ .unwrap(),
+ }
+ record
+}
+
+/// What a conversation reports stays bounded as it grows: what still waits or
+/// runs, where each session's context starts, and its latest turns.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_conversation_reports_what_it_shows_however_long_it_grows(pool: PgPool) {
+ use ConversationTurnState::{Failed, Queued, Running, Succeeded};
+ let (store, session, channel, mut command) = setup(pool.clone()).await;
+ let first = turn_in(&store, session, channel, &mut command, Succeeded).await;
+ let running = turn_in(&store, session, channel, &mut command, Running).await;
+ // Older than the latest two, and neither waiting nor where a context starts.
+ turn_in(&store, session, channel, &mut command, Failed).await;
+ turn_in(&store, session, channel, &mut command, Succeeded).await;
+ let fresh = crate::testing::postgres_sessions(pool)
+ .start_fresh(conversation(channel))
+ .await
+ .unwrap();
+ let fresh_first = turn_in(&store, fresh, channel, &mut command, Succeeded).await;
+ let latest_failure = turn_in(&store, fresh, channel, &mut command, Failed).await;
+ let latest = turn_in(&store, fresh, channel, &mut command, Queued).await;
+
+ let reported: Vec<Uuid> = store
+ .for_conversation(channel, bot_id::MACRO_NEW_BOT_ID, 2)
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|turn| turn.source_message_id)
+ .collect();
+ assert_eq!(
+ reported,
+ [first, running, fresh_first, latest_failure, latest].map(|turn| turn.source_message_id)
+ );
+}
+
+/// The conversation reports only its latest turns, but a failure older than
+/// them can still be retried.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_failure_older_than_the_reported_turns_still_retries(pool: PgPool) {
+ use ConversationTurnState::{Failed, Succeeded};
+ let (store, session, channel, mut command) = setup(pool.clone()).await;
+ let owner = mention_origin(&command).sender.clone();
+ turn_in(&store, session, channel, &mut command, Succeeded).await;
+ let failed = turn_in(&store, session, channel, &mut command, Failed).await;
+ for _ in 0..100 {
+ turn_in(&store, session, channel, &mut command, Succeeded).await;
+ }
+ assert!(
+ !store
+ .for_conversation(channel, bot_id::MACRO_NEW_BOT_ID, 100)
+ .await
+ .unwrap()
+ .iter()
+ .any(|turn| turn.source_message_id == failed.source_message_id)
+ );
+
+ conversations(pool, store.clone(), true)
+ .retry(
+ owner,
+ conversation(channel),
+ failed.source_message_id,
+ failed.action_id,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ store
+ .get(failed.source_message_id, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .unwrap()
+ .state,
+ ConversationTurnState::Queued
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn terminal_reply_ids_require_the_current_unfinalized_attempt_and_saved_flight(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool).await;
+ let record = store.admit(session, channel, command).await.unwrap();
+ let mut original = flight(&record);
+ original.announcement_message_id = None;
+ let mut reserved = original.clone();
+ reserved.presented.push(macro_uuid::generate_uuid_v7());
+ reserved.announcement_message_id = reserved.presented.last().copied();
+ assert!(store.claim(record.action_id, &original).await.unwrap());
+ assert!(
+ !store
+ .record_reply_flight(record.action_id, &original, &reserved)
+ .await
+ .unwrap(),
+ "running attempts use progress persistence"
+ );
+ store
+ .finish(
+ record.action_id,
+ ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ assert!(
+ store
+ .record_reply_flight(record.action_id, &original, &reserved)
+ .await
+ .unwrap()
+ );
+ let mut stale = reserved.clone();
+ stale.presented.push(macro_uuid::generate_uuid_v7());
+ assert!(
+ !store
+ .record_reply_flight(record.action_id, &original, &stale)
+ .await
+ .unwrap(),
+ "a stale flight cannot overwrite already reserved IDs"
+ );
+ assert!(
+ !store
+ .retry(record.source_message_id, record.bot_id, record.action_id)
+ .await
+ .unwrap()
+ );
+ let status = store
+ .for_conversation(channel, record.bot_id, 10)
+ .await
+ .unwrap();
+ assert_eq!(status[0].reply_message_id, reserved.announcement_message_id);
+ assert!(!status[0].retryable);
+ store
+ .finalize_reply(record.action_id, &ReplyOutcome::Failed)
+ .await
+ .unwrap();
+ assert!(
+ !store
+ .record_reply_flight(record.action_id, &reserved, &stale)
+ .await
+ .unwrap(),
+ "finalized replies cannot reserve new IDs"
+ );
+ assert!(
+ store
+ .retry(record.source_message_id, record.bot_id, record.action_id)
+ .await
+ .unwrap()
+ );
+ assert!(
+ !store
+ .record_reply_flight(record.action_id, &original, &reserved)
+ .await
+ .unwrap(),
+ "a retried attempt no longer owns the record"
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn retry_racing_the_first_terminal_reservation_cannot_discard_a_postable_reply(pool: PgPool) {
+ let (store, session, channel, command) = setup(pool).await;
+ let record = store.admit(session, channel, command).await.unwrap();
+ let mut original = flight(&record);
+ original.announcement_message_id = None;
+ assert!(store.claim(record.action_id, &original).await.unwrap());
+ store
+ .finish(
+ record.action_id,
+ ConversationTurnState::Failed,
+ ReplyOutcome::Failed,
+ )
+ .await
+ .unwrap();
+ let mut reserved = original.clone();
+ reserved.presented.push(macro_uuid::generate_uuid_v7());
+ reserved.announcement_message_id = reserved.presented.last().copied();
+ let (retry, saved) = tokio::join!(
+ store.retry(record.source_message_id, record.bot_id, record.action_id),
+ store.record_reply_flight(record.action_id, &original, &reserved),
+ );
+ assert_ne!(
+ retry.unwrap(),
+ saved.unwrap(),
+ "either retry takes ownership or reservation blocks retry, never both"
+ );
+}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index c3cdb03807..cac4a6d370 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -202,6 +202,10 @@ impl AgentSessionRepo for StubSessions {
unimplemented!("archiving sessions is the harness service's job")
}
+ async fn is_current_conversation_session(&self, _id: AgentSessionId) -> SessionResult<bool> {
+ unimplemented!("archiving sessions is the harness service's job")
+ }
+
async fn set_name_if_default(&self, _id: AgentSessionId, _name: &str) -> SessionResult<bool> {
unimplemented!("naming sessions is the session actor's job")
}
diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rs
index 2f608f692b..5f31324fa9 100644
--- a/crates/agent_harness/src/outbound/mod.rs
+++ b/crates/agent_harness/src/outbound/mod.rs
@@ -5,6 +5,8 @@ pub mod agent_prompt_composer;
pub mod channel_announcer;
pub mod channel_prompt_context;
pub mod containers;
+/// Durable agent conversation turn journal.
+pub mod conversation_turns;
pub mod cursor;
pub mod daytona;
pub mod egress;
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index 0c6d69c47e..c1d023d79b 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -254,6 +254,10 @@ impl AgentSessionRepo for FixedBotSessions {
unimplemented!("archiving sessions is the harness service's job")
}
+ async fn is_current_conversation_session(&self, _id: AgentSessionId) -> SessionResult<bool> {
+ unimplemented!("archiving sessions is the harness service's job")
+ }
+
async fn set_name_if_default(&self, _id: AgentSessionId, _name: &str) -> SessionResult<bool> {
unimplemented!("naming sessions is the session actor's job")
}
diff --git a/crates/agent_harness/src/testing/helpers/announcer.rs b/crates/agent_harness/src/testing/helpers/announcer.rs
index ca0d995ed3..8e889794e3 100644
--- a/crates/agent_harness/src/testing/helpers/announcer.rs
+++ b/crates/agent_harness/src/testing/helpers/announcer.rs
@@ -3,7 +3,10 @@
use std::sync::{Arc, Mutex};
use crate::domain::error::{HarnessError, Result};
-use crate::domain::model::{AnnouncedMessage, DeclinedMention, ResolvedReply, SessionAnnouncement};
+use crate::domain::model::{
+ AgentTypingUpdate, AnnouncedMessage, DeclinedMention, ReplyPresentation, ResolvedReply,
+ SessionAnnouncement,
+};
use crate::domain::ports::SessionAnnouncer;
/// A [`SessionAnnouncer`] that records instead of posting. Cloning shares one
@@ -13,6 +16,9 @@ pub struct AnnouncerMock {
announced: Arc<Mutex<Vec<(SessionAnnouncement, AnnouncedMessage)>>>,
declined: Arc<Mutex<Vec<DeclinedMention>>>,
resolved: Arc<Mutex<Vec<ResolvedReply>>>,
+ presented: Arc<Mutex<Vec<ReplyPresentation>>>,
+ typed: Arc<Mutex<Vec<AgentTypingUpdate>>>,
+ present_failure: Arc<Mutex<Option<String>>>,
/// When set, every announce fails with this message.
failure: Arc<Mutex<Option<String>>>,
}
@@ -33,6 +39,26 @@ impl AnnouncerMock {
Some(message.to_owned());
}
+ /// Record a committed presentation, then simulate losing its response.
+ pub fn fails_after_presenting(&self, message: &str) {
+ *self
+ .present_failure
+ .lock()
+ .expect("announcer mock lock should not be poisoned") = Some(message.to_owned());
+ }
+
+ /// Stop failing: the next announce, resolve or presentation succeeds.
+ pub fn recovers(&self) {
+ *self
+ .present_failure
+ .lock()
+ .expect("announcer mock lock should not be poisoned") = None;
+ *self
+ .failure
+ .lock()
+ .expect("announcer mock failure lock should not be poisoned") = None;
+ }
+
/// Every announcement recorded, in order.
#[must_use]
pub fn announced(&self) -> Vec<SessionAnnouncement> {
@@ -63,6 +89,24 @@ impl AnnouncerMock {
.clone()
}
+ /// Every reply message shown, in order, including each update to one.
+ #[must_use]
+ pub fn presented(&self) -> Vec<ReplyPresentation> {
+ self.presented
+ .lock()
+ .expect("announcer mock presented lock should not be poisoned")
+ .clone()
+ }
+
+ /// Every typing update, in order.
+ #[must_use]
+ pub fn typed(&self) -> Vec<AgentTypingUpdate> {
+ self.typed
+ .lock()
+ .expect("announcer mock typed lock should not be poisoned")
+ .clone()
+ }
+
/// The message each recorded announcement became, in order.
#[must_use]
pub fn announced_messages(&self) -> Vec<AnnouncedMessage> {
@@ -131,4 +175,36 @@ impl SessionAnnouncer for AnnouncerMock {
.push(declined);
Ok(())
}
+
+ async fn present(&self, presentation: ReplyPresentation) -> Result<()> {
+ if let Some(message) = self
+ .failure
+ .lock()
+ .expect("announcer mock failure lock should not be poisoned")
+ .clone()
+ {
+ return Err(HarnessError::Announce(rootcause::report!("{message}")));
+ }
+ self.presented
+ .lock()
+ .expect("announcer mock presented lock should not be poisoned")
+ .push(presentation);
+ if let Some(message) = self
+ .present_failure
+ .lock()
+ .expect("announcer mock lock should not be poisoned")
+ .clone()
+ {
+ return Err(HarnessError::Announce(rootcause::report!("{message}")));
+ }
+ Ok(())
+ }
+
+ async fn typing(&self, typing: AgentTypingUpdate) -> Result<()> {
+ self.typed
+ .lock()
+ .expect("announcer mock typed lock should not be poisoned")
+ .push(typing);
+ Ok(())
+ }
}
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index d22db37a2d..5cd1bcc42b 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -205,6 +205,7 @@ pub struct MockContainerManager {
resumes: Arc<AtomicUsize>,
teardowns: Arc<AtomicUsize>,
teardown_error: Arc<AtomicBool>,
+ tokens_lost: Arc<AtomicBool>,
/// Signalled on every spawn, so a test waits for a sandbox instead of
/// spinning on [`Self::spawned`].
spawned_signal: Arc<tokio::sync::Notify>,
@@ -272,6 +273,12 @@ impl MockContainerManager {
self.resumes.load(Ordering::Relaxed)
}
+ /// Hold no session tokens from now on, like an in-process agent's
+ /// manager after a restart.
+ pub fn lose_tokens(&self) {
+ self.tokens_lost.store(true, Ordering::Relaxed);
+ }
+
/// Fail the next teardown before removing its container.
pub fn fail_next_teardown(&self) {
self.teardown_error.store(true, Ordering::Relaxed);
@@ -398,8 +405,12 @@ impl ContainerManager for MockContainerManager {
}
/// The fixed token every mock container "holds", for sessions that were
- /// spawned; `None` otherwise, like a provider that finds no container.
+ /// spawned; `None` otherwise, like a provider that finds no container,
+ /// and after [`Self::lose_tokens`].
async fn session_token(&self, session: AgentSessionId) -> Result<Option<String>, HarnessError> {
+ if self.tokens_lost.load(Ordering::Relaxed) {
+ return Ok(None);
+ }
Ok(self
.lock()
.contains_key(&session)
diff --git a/crates/agent_harness/src/testing/mod.rs b/crates/agent_harness/src/testing/mod.rs
index 1630fabcd1..1262d8b0cb 100644
--- a/crates/agent_harness/src/testing/mod.rs
+++ b/crates/agent_harness/src/testing/mod.rs
@@ -1 +1,6 @@
pub mod helpers;
+
+#[cfg(test)]
+mod postgres;
+#[cfg(test)]
+pub(crate) use postgres::postgres_sessions;
diff --git a/crates/agent_harness/src/testing/postgres.rs b/crates/agent_harness/src/testing/postgres.rs
new file mode 100644
index 0000000000..110cf012fc
--- /dev/null
+++ b/crates/agent_harness/src/testing/postgres.rs
@@ -0,0 +1,11 @@
+/// Compose the real session repository for database-backed harness tests.
+pub(crate) fn postgres_sessions(
+ pool: sqlx::PgPool,
+) -> agent_session::outbound::postgres::PgAgentSessionRepo<bots::outbound::pg_bots_repo::PgBotsRepo>
+{
+ let bots = bots::outbound::pg_bots_repo::PgBotsRepo::new(pool.clone());
+ let registrar = entity_registry_db_utils::OwnedEntityRegistrar::new(
+ entity_registry::OwnerGrantPolicy::new(bots),
+ );
+ agent_session::outbound::postgres::PgAgentSessionRepo::new(pool, registrar)
+}
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index d7439147c0..e82ae56d2d 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -1014,7 +1014,7 @@ async fn run_turn(
)),
));
}
- if let Some(failure) = failure {
+ if let Some(failure) = &failure {
let _ = connection.send_notification(SessionNotification::new(
acp_session_id.clone(),
SessionUpdate::AgentMessageChunk(ContentChunk::new(
@@ -1024,7 +1024,11 @@ async fn run_turn(
}
state.push_turn(request_id, prompt, turn_parts);
- if was_cancelled || cancel.is_cancelled() {
+ // A failure first: the idle timeout cancels the stream itself, and a turn
+ // it stopped failed rather than being stopped by the user.
+ if let Some(failure) = failure {
+ Err(AcpError::internal_error().data(failure))
+ } else if was_cancelled || cancel.is_cancelled() {
Ok(StopReason::Cancelled)
} else {
Ok(StopReason::EndTurn)
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 40da0f56fa..e9f83a43d1 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -2257,7 +2257,8 @@ async fn a_user_tool_review_is_a_tool_scoped_form_elicitation_naming_the_tool()
);
}
-/// The timeout still guards a turn that is silent with nothing asked.
+/// The timeout still guards a turn that is silent with nothing asked, and
+/// the turn it stops failed: nobody pressed Stop.
#[tokio::test(start_paused = true)]
async fn a_silent_turn_with_no_question_out_is_stopped_by_the_idle_timeout() {
let (notifications, _config_options, response) =
@@ -2266,11 +2267,15 @@ async fn a_silent_turn_with_no_question_out_is_stopped_by_the_idle_timeout() {
.send_request(text_prompt(&session, "hang"))
.block_task()
.await
- .expect("the turn should complete")
})
.await;
- assert_eq!(response.stop_reason, StopReason::Cancelled);
+ let error = response.expect_err("a timed-out turn fails");
+ assert!(
+ error.to_string().contains("produced nothing")
+ || format!("{error:?}").contains("produced nothing"),
+ "got {error:?}"
+ );
assert!(
spoken(&notifications).contains("produced nothing"),
"got {:?}",
diff --git a/crates/agent_inmem/src/domain/replay.rs b/crates/agent_inmem/src/domain/replay.rs
index 1550522765..16030d10c5 100644
--- a/crates/agent_inmem/src/domain/replay.rs
+++ b/crates/agent_inmem/src/domain/replay.rs
@@ -40,15 +40,14 @@ mod test;
/// Where a session's durable frames come from when its conversation has to
/// be rebuilt - a cold attach in a process that has never served the session.
///
-/// Failures degrade to an empty history (the model's context starts over,
-/// which was every restart's behavior before replay existed) rather than
-/// failing the attach.
+/// A failed read must fail the attach. An unavailable log is not an empty
+/// conversation: silently forgetting it would misrepresent the agent's memory.
pub trait FrameSource: Send + Sync + 'static {
/// The session's logged frames, oldest first.
fn frames(
&self,
session: agent_session::domain::model::AgentSessionId,
- ) -> BoxFuture<'_, Vec<Message>>;
+ ) -> BoxFuture<'_, agent_session::domain::error::Result<Vec<Message>>>;
}
/// A turn replay has opened and not yet closed.
diff --git a/crates/agent_inmem/src/outbound/log_frames.rs b/crates/agent_inmem/src/outbound/log_frames.rs
index b58ba9fcd6..05dacd8311 100644
--- a/crates/agent_inmem/src/outbound/log_frames.rs
+++ b/crates/agent_inmem/src/outbound/log_frames.rs
@@ -24,24 +24,16 @@ impl<Repo> FrameSource for LogFrameSource<Repo>
where
Repo: AgentSessionLogRepo,
{
- fn frames(&self, session: AgentSessionId) -> BoxFuture<'_, Vec<Message>> {
+ fn frames(
+ &self,
+ session: AgentSessionId,
+ ) -> BoxFuture<'_, agent_session::domain::error::Result<Vec<Message>>> {
Box::pin(async move {
- match self.repo.list_by_session(session).await {
- Ok(entries) => entries
- .into_iter()
- .map(|stored| stored.entry.content)
- .collect(),
- // Degrade to the pre-replay behavior - the model's context
- // starts over - rather than failing the attach.
- Err(error) => {
- tracing::warn!(
- error = ?error,
- %session,
- "failed to load the session log; the in-memory agent starts with no model context"
- );
- Vec::new()
- }
- }
+ let entries = self.repo.list_by_session(session).await?;
+ Ok(entries
+ .into_iter()
+ .map(|stored| stored.entry.content)
+ .collect())
})
}
}
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index 33be2df9c0..da5e4aaf6e 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -138,24 +138,15 @@ impl InMemAgentManager {
/// `session_token` is the egress token minted for this attach; `None`
/// keeps the stored one. A token it replaces is no longer accepted, so
/// the MCP sessions opened with it are released.
- #[must_use]
pub async fn attach(
&self,
facts: SessionFacts,
session_token: Option<String>,
- ) -> ServerChannel {
- // A replaced agent must die before its successor serves the session.
- self.live.remove(&facts.id);
- if let Some(token) = session_token
- && let Some(replaced) = self.tokens.insert(facts.id, token.clone())
- && replaced != token
- {
- self.mcp.release_dyn(&replaced);
- }
+ ) -> agent_session::domain::error::Result<ServerChannel> {
if !self.store.contains_key(&facts.id) {
// Loaded before taking the entry so the read never blocks the
// map; `or_insert_with` still wins any race to create it.
- let frames = self.frames.frames(facts.id).await;
+ let frames = self.frames.frames(facts.id).await?;
let restored_effort = replay_reasoning_effort(&frames);
let reasoning_effort =
if agent::ReasoningEffort::supported(&facts.model).contains(&restored_effort) {
@@ -182,6 +173,16 @@ impl InMemAgentManager {
});
}
+ // Do not replace a runtime or cache a credential until its history is
+ // available. A failed cold restore can safely be retried.
+ self.live.remove(&facts.id);
+ if let Some(token) = session_token
+ && let Some(replaced) = self.tokens.insert(facts.id, token.clone())
+ && replaced != token
+ {
+ self.mcp.release_dyn(&replaced);
+ }
+
let (server_half, runtime_half) = Channel::duplex();
let (runtime, acp) = RuntimeConnection::connect(runtime_half);
let state = Arc::new(AgentState {
@@ -217,7 +218,7 @@ impl InMemAgentManager {
task: task.abort_handle(),
},
);
- server_half
+ Ok(server_half)
}
/// End the session for good: kill its agent task, drop its conversation,
diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rs
index e6df24c2ea..332c69df04 100644
--- a/crates/agent_inmem/src/outbound/manager/test.rs
+++ b/crates/agent_inmem/src/outbound/manager/test.rs
@@ -34,6 +34,53 @@ mod summary;
/// like something a real session would carry.
const INSTRUCTIONS: &str = "Answer in one sentence. Never open a pull request.";
+#[tokio::test]
+async fn a_failed_history_read_never_creates_an_empty_conversation() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+ struct RecoverableFrames(Arc<AtomicBool>);
+ impl FrameSource for RecoverableFrames {
+ fn frames(
+ &self,
+ _: AgentSessionId,
+ ) -> futures::future::BoxFuture<
+ '_,
+ agent_session::domain::error::Result<Vec<agent_session::domain::model::Message>>,
+ > {
+ Box::pin(async move {
+ if self.0.load(Ordering::SeqCst) {
+ Err(agent_session::domain::error::AgentSessionError::Unknown(
+ anyhow::anyhow!("history unavailable"),
+ ))
+ } else {
+ Ok(Vec::new())
+ }
+ })
+ }
+ }
+ let failed = Arc::new(AtomicBool::new(true));
+ let engine = Arc::new(ScriptedEngine::new(Vec::new()));
+ let manager = InMemAgentManager::new(
+ engine.clone(),
+ Arc::new(RecoverableFrames(failed.clone())),
+ Arc::new(crate::domain::mcp::NoMcpServers),
+ Arc::new(crate::testing::TestModelAccess::paid()),
+ );
+ let id = AgentSessionId::new();
+ assert!(
+ manager
+ .attach(facts(id), Some("token".to_owned()))
+ .await
+ .is_err()
+ );
+ assert!(!manager.store.contains_key(&id));
+ assert!(!manager.live.contains_key(&id));
+ assert_eq!(manager.session_token(id), None);
+ assert!(engine.requests().is_empty());
+ failed.store(false, Ordering::SeqCst);
+ assert!(manager.attach(facts(id), None).await.is_ok());
+ assert!(manager.store.contains_key(&id));
+}
+
/// Attach `transport`, waiting out the previous one's disconnect.
///
/// Replacing a session's agent is two independent events: the manager drops
@@ -48,7 +95,10 @@ async fn attach_retrying(
) {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
- let transport = manager.attach(facts.clone(), None).await;
+ let transport = manager
+ .attach(facts.clone(), None)
+ .await
+ .expect("history should restore");
match sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -172,7 +222,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -198,7 +248,10 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
)])),
);
let manager = manager.with_admission(disabled_admission());
- let transport = manager.attach(facts(id), None).await;
+ let transport = manager
+ .attach(facts(id), None)
+ .await
+ .expect("history should restore");
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -255,7 +308,10 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {
// disconnect-then-resume order the harness's deliver path drives.
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
loop {
- let transport = manager.attach(facts(id), None).await;
+ let transport = manager
+ .attach(facts(id), None)
+ .await
+ .expect("history should restore");
match sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -312,7 +368,7 @@ async fn manager_admission_rejects_turns_without_wedging_the_session() {
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -334,7 +390,7 @@ async fn manager_admission_rejects_turns_without_wedging_the_session() {
let denial = AiAdmissionError::Denied(DenyReason::AllowanceExhausted);
let admission = Arc::new(TestAdmission::new(Err(denial)));
let manager = manager(&repo, engine.clone()).with_admission(admission.clone());
- let transport = manager.attach(facts(id), None).await;
+ let transport = manager.attach(facts(id), None).await.unwrap();
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -405,7 +461,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -430,7 +486,10 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
"streamed reply".to_owned(),
)])),
);
- let transport = before.attach(facts(id), None).await;
+ let transport = before
+ .attach(facts(id), None)
+ .await
+ .expect("history should restore");
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -479,7 +538,8 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {
},
None,
)
- .await;
+ .await
+ .expect("history should restore");
match sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -553,7 +613,7 @@ async fn instructions_reach_every_turn_including_after_a_reattach() {
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -629,7 +689,7 @@ async fn a_session_without_instructions_hands_the_engine_none() {
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -652,7 +712,10 @@ async fn a_session_without_instructions_hands_the_engine_none() {
"acknowledged".to_owned(),
)]));
let manager = manager(&repo, Arc::clone(&engine));
- let transport = manager.attach(facts(id), None).await;
+ let transport = manager
+ .attach(facts(id), None)
+ .await
+ .expect("history should restore");
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
@@ -690,7 +753,7 @@ async fn identity_reaches_every_turn_including_after_a_reattach() {
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -763,11 +826,15 @@ async fn the_manager_remembers_the_egress_token_from_spawn_until_teardown() {
let _spawned = manager
.attach(facts(id), Some("session-token".to_owned()))
- .await;
+ .await
+ .expect("history should restore");
assert_eq!(manager.session_token(id).as_deref(), Some("session-token"));
// A resume passes nothing and keeps what spawn stored.
- let _resumed = manager.attach(facts(id), None).await;
+ let _resumed = manager
+ .attach(facts(id), None)
+ .await
+ .expect("history should restore");
assert_eq!(manager.session_token(id).as_deref(), Some("session-token"));
manager.teardown(id);
@@ -791,7 +858,8 @@ async fn teardown_releases_pooled_mcp_sessions_for_the_egress_token() {
let id = AgentSessionId::new();
let _spawned = manager
.attach(facts(id), Some("session-token".to_owned()))
- .await;
+ .await
+ .expect("history should restore");
manager.teardown(id);
@@ -817,11 +885,20 @@ async fn attaching_with_a_new_token_releases_the_replaced_one() {
Arc::new(crate::testing::TestModelAccess::paid()),
);
let id = AgentSessionId::new();
- let _spawned = manager.attach(facts(id), Some("spawned".to_owned())).await;
- let _same = manager.attach(facts(id), Some("spawned".to_owned())).await;
+ let _spawned = manager
+ .attach(facts(id), Some("spawned".to_owned()))
+ .await
+ .expect("history should restore");
+ let _same = manager
+ .attach(facts(id), Some("spawned".to_owned()))
+ .await
+ .expect("history should restore");
assert!(mcp.released.lock().expect("lock").is_empty());
- let _rotated = manager.attach(facts(id), Some("rotated".to_owned())).await;
+ let _rotated = manager
+ .attach(facts(id), Some("rotated".to_owned()))
+ .await
+ .expect("history should restore");
assert_eq!(manager.session_token(id).as_deref(), Some("rotated"));
assert_eq!(mcp.released.lock().expect("lock").as_slice(), ["spawned"]);
diff --git a/crates/agent_inmem/src/outbound/manager/test/summary.rs b/crates/agent_inmem/src/outbound/manager/test/summary.rs
index fe78eb449f..74d42ea842 100644
--- a/crates/agent_inmem/src/outbound/manager/test/summary.rs
+++ b/crates/agent_inmem/src/outbound/manager/test/summary.rs
@@ -111,7 +111,7 @@ async fn a_restarted_manager_reads_a_summary_in_place_of_the_turns_it_covered()
let id = AgentSessionId::new();
sessions
.create_session(CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id,
owner_id: Owner::User(owner()),
@@ -148,7 +148,10 @@ async fn a_restarted_manager_reads_a_summary_in_place_of_the_turns_it_covered()
Arc::new(crate::domain::mcp::NoMcpServers),
Arc::new(crate::testing::TestModelAccess::paid()),
);
- let transport = before.attach(on_model(None), None).await;
+ let transport = before
+ .attach(on_model(None), None)
+ .await
+ .expect("history should restore");
sessions
.attach_session(id, RuntimeAttachment::solo(transport))
.await
diff --git a/crates/agent_inmem/src/outbound/rig_engine/test.rs b/crates/agent_inmem/src/outbound/rig_engine/test.rs
index b891f5a24c..70defa9697 100644
--- a/crates/agent_inmem/src/outbound/rig_engine/test.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine/test.rs
@@ -9,6 +9,40 @@ use schemars::JsonSchema;
use serde::Deserialize;
use std::sync::Mutex;
+#[tokio::test]
+async fn a_runtime_panic_is_reported_as_failure_instead_of_an_empty_success() {
+ let (parts, mut receiver) = mpsc::channel(2);
+ forward_turn_result(async { panic!("provider initialization failed") }, &parts).await;
+ drop(parts);
+ let error = receiver.recv().await.unwrap().unwrap_err();
+ assert!(error.to_string().contains("runtime ended unexpectedly"));
+ assert!(receiver.recv().await.is_none());
+}
+
+#[tokio::test]
+async fn a_failure_after_partial_output_is_still_forwarded_to_the_consumer() {
+ let (parts, mut receiver) = mpsc::channel(2);
+ forward_turn_result(
+ async {
+ parts
+ .send(Ok(StreamPart::Content("Partial answer".into())))
+ .await
+ .unwrap();
+ Err(AgentError::Other(anyhow::anyhow!("provider unavailable")))
+ },
+ &parts,
+ )
+ .await;
+ assert!(matches!(
+ receiver.recv().await.unwrap(),
+ Ok(StreamPart::Content(_))
+ ));
+ assert_eq!(
+ receiver.recv().await.unwrap().unwrap_err().to_string(),
+ "provider unavailable"
+ );
+}
+
/// A stand-in for the toolset prompt, short enough to assert on positionally.
const TOOLS: &str = "TOOLS";
diff --git a/crates/agent_inmem/src/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rs
index 0a064e4b54..74ea17e691 100644
--- a/crates/agent_inmem/src/rig_engine.rs
+++ b/crates/agent_inmem/src/rig_engine.rs
@@ -28,7 +28,7 @@ use ai_tools::user_tool_review::user_tool_finisher;
use ai_tools::{AiHost, DeferredToolSet, ToolServiceContext, tools_for};
use ai_toolset::{AsyncToolCollection, ToolSet as AiToolSet};
use axum::extract::FromRef;
-use futures::StreamExt as _;
+use futures::{FutureExt as _, StreamExt as _};
use macro_user_id::user_id::MacroUserIdStr;
use memory::domain::MemoryService as _;
use memory::domain::service::MemoryServiceImpl;
@@ -243,11 +243,18 @@ impl TurnEngine for RigTurnEngine {
let metering = agent::MeteringContext::current();
tokio::spawn(
agent::MeteringContext::carry(metering, async move {
- if let Err(error) =
- drive_turn(&memory, &native_tools, tool_context, gate, request, &parts).await
- {
- let _ = parts.send(Err(error)).await;
- }
+ // The product toolset makes this future large. Keep its state
+ // on the heap when adding the panic boundary, including in
+ // unoptimized local builds with Tokio's default worker stack.
+ let turn = Box::pin(drive_turn(
+ &memory,
+ &native_tools,
+ tool_context,
+ gate,
+ request,
+ &parts,
+ ));
+ forward_turn_result(turn, &parts).await;
})
.in_current_span(),
);
@@ -255,6 +262,25 @@ impl TurnEngine for RigTurnEngine {
}
}
+// Closing the stream alone means success to the ACP consumer. A panic in
+// provider initialization must therefore become an explicit failed turn.
+async fn forward_turn_result(
+ turn: impl Future<Output = Result<(), AgentError>>,
+ parts: &mpsc::Sender<Result<StreamPart, AgentError>>,
+) {
+ let result = std::panic::AssertUnwindSafe(turn)
+ .catch_unwind()
+ .await
+ .unwrap_or_else(|_| {
+ Err(AgentError::Other(anyhow::anyhow!(
+ "The agent runtime ended unexpectedly. Please retry this message."
+ )))
+ });
+ if let Err(error) = result {
+ let _ = parts.send(Err(error)).await;
+ }
+}
+
async fn drive_turn(
memory: &MemoryServiceImpl<PgMemoryRepo>,
native_tools: &NativeTools,
@@ -427,14 +453,14 @@ async fn drive_turn(
// Bridge the caller's token onto the loop's own; aborted with the turn so
// an uncancelled token does not strand the forwarder.
- let forward = tokio::spawn({
+ let forward = tokio_util::task::AbortOnDropHandle::new(tokio::spawn({
let loop_cancel = loop_cancel.clone();
let cancel = cancel.clone();
async move {
cancel.cancelled().await;
loop_cancel.cancel();
}
- });
+ }));
let rig_messages = agent::to_rig_messages(&messages);
let result = async {
diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rs
index 1d42d850c6..2a6594badd 100644
--- a/crates/agent_session/src/bin/seed_jsonl.rs
+++ b/crates/agent_session/src/bin/seed_jsonl.rs
@@ -245,7 +245,7 @@ async fn seed(args: &Args) -> Result<(), SeedError> {
let session = AgentSessionRepo::create(
&repo,
CreateAgentSessionParams {
- warm: false,
+ purpose: agent_session::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id: session_id,
owner_id: model_owner::Owner::User(owner),
diff --git a/crates/agent_session/src/domain/agent_conversation.rs b/crates/agent_session/src/domain/agent_conversation.rs
new file mode 100644
index 0000000000..7d604ae34c
--- /dev/null
+++ b/crates/agent_session/src/domain/agent_conversation.rs
@@ -0,0 +1,62 @@
+//! An agent's conversation in a channel, and the sessions it runs on.
+
+use bot_id::BotId;
+use macro_uuid::Uuid;
+
+use super::{error::Result, model::AgentSessionId};
+
+/// One agent persona's conversation in one channel.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct AgentConversation {
+ /// Channel the conversation happens in.
+ pub channel_id: Uuid,
+ /// Persona that answers there.
+ pub bot_id: BotId,
+}
+
+/// A session a conversation has run on. Starting fresh begins another; the
+/// channel keeps every earlier message.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ConversationSession {
+ /// Session carrying this context and its controls.
+ pub session_id: AgentSessionId,
+ /// When this context began; older channel messages remain visible.
+ pub created_at: chrono::DateTime<chrono::Utc>,
+ /// Whether new messages go to this session.
+ pub is_current: bool,
+}
+
+/// Session-domain persistence for a conversation's current and earlier sessions.
+pub trait AgentConversationRepo: Send + Sync + 'static {
+ /// Atomically reserve the current session identity, before runtime startup.
+ /// Repeated or concurrent requests return the same id until an explicit reset.
+ fn current_or_create(
+ &self,
+ conversation: AgentConversation,
+ ) -> impl Future<Output = Result<AgentSessionId>> + Send;
+
+ /// Return the current session without starting one.
+ fn current(
+ &self,
+ conversation: AgentConversation,
+ ) -> impl Future<Output = Result<Option<AgentSessionId>>> + Send;
+
+ /// Start a new session while keeping every earlier one and its history.
+ fn start_fresh(
+ &self,
+ conversation: AgentConversation,
+ ) -> impl Future<Output = Result<AgentSessionId>> + Send;
+
+ /// The conversation a session belongs to, including earlier sessions.
+ fn conversation_for_session(
+ &self,
+ session_id: AgentSessionId,
+ ) -> impl Future<Output = Result<Option<AgentConversation>>> + Send;
+
+ /// Every session the conversation has run on, oldest first, without
+ /// starting a runtime.
+ fn sessions(
+ &self,
+ conversation: AgentConversation,
+ ) -> impl Future<Output = Result<Vec<ConversationSession>>> + Send;
+}
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index dfbc4734e8..f7277c4f39 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -10,6 +10,12 @@ pub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;
#[derive(Error, Debug)]
pub enum AgentSessionError {
+ /// Speculative sessions cannot belong to a conversation or a message.
+ #[error("a warm session cannot have conversation or message provenance")]
+ InvalidSessionPurpose,
+ /// No session has been created under this identity yet.
+ #[error("agent session {0} was not found")]
+ NotFound(AgentSessionId),
/// New Macro-funded work was refused before execution.
#[cfg(feature = "admission")]
#[error(transparent)]
@@ -66,6 +72,13 @@ pub enum AgentSessionError {
InvalidName(&'static str),
#[error("agent session {0} is archived")]
Archived(AgentSessionId),
+ /// The session answers an agent conversation's channel, which archiving
+ /// it would leave unanswered. Starting fresh in the conversation retires
+ /// it instead.
+ #[error(
+ "agent session {0} answers an agent conversation; start fresh there instead of archiving it"
+ )]
+ AnswersConversation(AgentSessionId),
#[error("a preview request may name at most {0} sessions")]
TooManyPreviewIds(usize),
#[error("a pull request lookup may name at most {0} pull requests")]
diff --git a/crates/agent_session/src/domain/list_visibility.rs b/crates/agent_session/src/domain/list_visibility.rs
new file mode 100644
index 0000000000..bdaf151189
--- /dev/null
+++ b/crates/agent_session/src/domain/list_visibility.rs
@@ -0,0 +1,29 @@
+//! DM contexts belong in their channel, independently of warm runtime lifecycle.
+
+use super::error::Result;
+
+/// Owning session persistence capability for an existing DM context backfill.
+pub trait SessionListVisibilityRepo: Send + Sync {
+ /// Hide at most `limit` DM contexts, leaving other sessions and channels alone.
+ fn hide_dm_sessions(&self, limit: u16) -> impl Future<Output = Result<u64>> + Send;
+}
+
+/// Default-off until every old hidden/unthreaded warm reaper has been replaced.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SessionListPolicy {
+ /// Enable DM context hiding after the warm-marker rollout is complete.
+ pub hide_agent_dms: bool,
+}
+
+const BACKFILL_BATCH_SIZE: u16 = 256;
+
+impl SessionListPolicy {
+ /// Repair earlier contexts and contexts created by a replica still using the
+ /// disabled policy. Bounded and retryable, so enabling across replicas is safe.
+ pub async fn reconcile(self, repo: &impl SessionListVisibilityRepo) -> Result<()> {
+ if self.hide_agent_dms {
+ repo.hide_dm_sessions(BACKFILL_BATCH_SIZE).await?;
+ }
+ Ok(())
+ }
+}
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 6a108abcee..76741cd573 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -1,3 +1,4 @@
+pub mod agent_conversation;
/// Current authorization for agent session streams.
pub mod audience;
pub mod coding_agents;
@@ -41,3 +42,6 @@ pub mod recovery;
/// Warm session promotion and expiry.
pub mod warm;
+
+/// Visibility policy for standalone session lists.
+pub mod list_visibility;
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index 7f144f8a16..0c6099006b 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -184,11 +184,46 @@ pub enum SessionStatus {
/// editing the agent's selection applies to its next session.
pub use bots::domain::models::{AgentMcpServer, AgentMcpServers};
+/// Why a session is created, independently of whether it appears in broad lists.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionPurpose {
+ /// A regular session opened directly or from a thread mention.
+ Standalone,
+ /// An unprompted speculative runtime, eligible for warm claim and expiry.
+ Warm,
+ /// Context backing an agent DM; accessed through its conversation.
+ AgentDm,
+}
+
+impl SessionPurpose {
+ /// Validate speculative creation against durable conversation provenance.
+ /// A legacy standalone caller naming a reserved context adopts DM policy.
+ pub fn for_creation(
+ self,
+ conversation: bool,
+ has_message: bool,
+ ) -> Result<Self, AgentSessionError> {
+ if self == Self::Warm && (conversation || has_message) {
+ return Err(AgentSessionError::InvalidSessionPurpose);
+ }
+ Ok(if conversation { Self::AgentDm } else { self })
+ }
+
+ /// Whether creation should omit the session from broad Agents/Home lists.
+ pub fn list_hidden(self, bot_id: BotId, thread_id: Option<Uuid>, hide_agent_dms: bool) -> bool {
+ match self {
+ Self::Warm => true,
+ Self::AgentDm => hide_agent_dms,
+ Self::Standalone => bot_id == bot_id::MACRO_NEW_BOT_ID && thread_id.is_some(),
+ }
+ }
+}
+
/// Caller-provided values required to create an agent session.
#[derive(Debug, Clone)]
pub struct CreateAgentSessionParams {
- /// An unclaimed warm session, hidden from lists and history.
- pub warm: bool,
+ /// Creation policy for visibility and speculative runtime lifecycle.
+ pub purpose: SessionPurpose,
/// Caller-minted session id, available before persistence.
pub id: AgentSessionId,
/// Who created and owns the session.
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index e5a08279fb..65f7ce8b27 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -512,6 +512,14 @@ pub trait AgentSessionRepo: Send + Sync + 'static {
is_archived: bool,
) -> impl Future<Output = Result<()>> + Send;
+ /// Whether the session is an agent conversation's current one: the
+ /// session its channel's messages go to now. A session the conversation
+ /// left behind by starting fresh is not.
+ fn is_current_conversation_session(
+ &self,
+ id: AgentSessionId,
+ ) -> impl Future<Output = Result<bool>> + Send;
+
/// Persist an automatically generated name only while the default remains
/// and the session is not archived.
fn set_name_if_default(
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index cc98d04e2a..220bbd0f20 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -748,6 +748,10 @@ where
Namer: AgentSessionNameGenerator + Clone,
{
async fn create_session(&self, params: CreateAgentSessionParams) -> Result<AgentSession> {
+ params.purpose.for_creation(
+ false,
+ params.thread_id.is_some() || params.originating_message_id.is_some(),
+ )?;
AgentSessionRepo::create(&self.repo, params).await
}
@@ -782,6 +786,12 @@ where
is_archived: bool,
) -> Result<()> {
let id = owner_access_session_id(access, "archive")?;
+ // Every message in a conversation's channel goes to its current
+ // session, and an archived session takes none. Starting fresh is how
+ // a conversation retires one; the sessions it left behind archive.
+ if is_archived && self.repo.is_current_conversation_session(id).await? {
+ return Err(AgentSessionError::AnswersConversation(id));
+ }
self.repo.set_archived(id, is_archived).await?;
self.realtime
.publish_updated(id)
@@ -1836,6 +1846,10 @@ where
self.repo.set_archived(id, is_archived).await
}
+ async fn is_current_conversation_session(&self, id: AgentSessionId) -> Result<bool> {
+ self.repo.is_current_conversation_session(id).await
+ }
+
async fn set_name_if_default(&self, id: AgentSessionId, name: &str) -> Result<bool> {
self.repo.set_name_if_default(id, name).await
}
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 1aea18bac0..c609755988 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -422,6 +422,36 @@ async fn archive_is_persisted_published_and_blocks_rename() {
.expect("rename unarchived session");
}
+#[tokio::test]
+async fn a_conversations_current_session_is_not_archived() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = test_session();
+ repo.insert_session(test_agent_session(session));
+ repo.answer_conversation(session);
+ let realtime = RecordingRealtime::default();
+ let service = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ realtime.clone(),
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
+ );
+
+ assert!(matches!(
+ service.set_archived(&owner_access(session), true).await,
+ Err(AgentSessionError::AnswersConversation(id)) if id == session
+ ));
+ assert!(!repo.get(session).await.expect("get session").is_archived);
+ assert!(realtime.updated().is_empty());
+ // Unarchiving is never refused.
+ service
+ .set_archived(&owner_access(session), false)
+ .await
+ .expect("unarchive session");
+}
+
#[tokio::test]
async fn manual_rename_rejects_blank_and_overlong_names() {
let repo = InMemoryAgentSessionRepo::new();
@@ -656,6 +686,10 @@ impl AgentSessionRepo for BlockingPromptLogs {
self.repo.set_archived(id, is_archived).await
}
+ async fn is_current_conversation_session(&self, id: AgentSessionId) -> Result<bool> {
+ self.repo.is_current_conversation_session(id).await
+ }
+
async fn set_name_if_default(&self, id: AgentSessionId, name: &str) -> Result<bool> {
self.repo.set_name_if_default(id, name).await
}
@@ -2354,14 +2388,23 @@ mod fold_signals {
signals.extend(logs.append(frame).await.expect("append succeeds").signals);
}
+ // Progress is reported while the turn runs; its end comes once, last.
+ let (ends, progress): (Vec<_>, Vec<_>) = signals
+ .iter()
+ .partition(|signal| !matches!(signal, TurnSignal::Progressed { .. }));
+ assert!(!progress.is_empty(), "{signals:#?}");
assert!(
matches!(
- signals.as_slice(),
+ ends.as_slice(),
[TurnSignal::TurnEnded { stop: FoldStop::EndTurn, last_text: Some(text), .. }]
if !text.is_empty()
),
"{signals:#?}"
);
+ assert!(
+ matches!(signals.last(), Some(TurnSignal::TurnEnded { .. })),
+ "{signals:#?}"
+ );
}
#[tokio::test]
diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rs
index e92183940a..8dc4638fe2 100644
--- a/crates/agent_session/src/domain/session/actors.rs
+++ b/crates/agent_session/src/domain/session/actors.rs
@@ -654,6 +654,9 @@ where
"agent session elicitation cleared"
);
}
+ // A reply's shape changes several times a turn; the turn's
+ // own span already covers it, so this is not logged.
+ TurnSignal::Progressed { .. } => {}
}
self.turn_observer.signal(self.machine.id(), signal);
}
diff --git a/crates/agent_session/src/domain/sharing.rs b/crates/agent_session/src/domain/sharing.rs
index 2914fdde24..8ae95f9df6 100644
--- a/crates/agent_session/src/domain/sharing.rs
+++ b/crates/agent_session/src/domain/sharing.rs
@@ -45,6 +45,11 @@ pub fn originating_channel_access(bot: SessionBotOwnership) -> AccessLevel {
/// Persistence capability for session sharing, independent of transport.
pub trait SessionSharingRepo: Send + Sync + 'static {
+ /// Whether the session belongs to a private user-persona conversation.
+ fn is_private_conversation(
+ &self,
+ id: AgentSessionId,
+ ) -> impl Future<Output = Result<bool>> + Send;
/// Read canonical sharing settings and direct channel grants.
fn permissions(
&self,
@@ -141,6 +146,11 @@ impl<R: SessionSharingRepo> SessionSharing for SessionSharingService<R> {
request: UpdateSharePermissionRequestV2,
) -> Result<SharePermissionV2> {
let id = session_id(access)?;
+ if self.repo.is_private_conversation(id).await? {
+ return Err(AgentSessionError::InvalidSharing(
+ "an agent DM is private to its owner and cannot be shared",
+ ));
+ }
validate(&request)?;
let permissions = self.repo.permissions(id).await?;
if access.acting_user_id().map(|user| user.as_ref()) != Some(permissions.owner.as_str()) {
diff --git a/crates/agent_session/src/domain/sharing/test.rs b/crates/agent_session/src/domain/sharing/test.rs
index d97f5d9f21..c820913e00 100644
--- a/crates/agent_session/src/domain/sharing/test.rs
+++ b/crates/agent_session/src/domain/sharing/test.rs
@@ -14,6 +14,7 @@ type SavedUpdate = (
#[derive(Clone)]
struct Repo {
+ private_conversation: bool,
id: AgentSessionId,
writes: Arc<Mutex<Vec<SavedUpdate>>>,
}
@@ -21,6 +22,7 @@ struct Repo {
impl Repo {
fn new() -> Self {
Self {
+ private_conversation: false,
id: AgentSessionId::new(),
writes: Default::default(),
}
@@ -28,6 +30,9 @@ impl Repo {
}
impl SessionSharingRepo for Repo {
+ async fn is_private_conversation(&self, _: AgentSessionId) -> Result<bool> {
+ Ok(self.private_conversation)
+ }
async fn permissions(&self, _: AgentSessionId) -> Result<SharePermissionV2> {
Ok(SharePermissionV2 {
id: self.id.to_string(),
@@ -91,6 +96,27 @@ fn request() -> UpdateSharePermissionRequestV2 {
}
}
+#[tokio::test]
+async fn a_dm_owner_cannot_share_the_underlying_session() {
+ let repo = Repo {
+ private_conversation: true,
+ ..Repo::new()
+ };
+ let service = SessionSharingService::new(repo.clone());
+ let result = service
+ .update_permissions(
+ &owner_access(repo.id, OWNER),
+ UpdateSharePermissionRequestV2 {
+ link_share: Some(Some(LinkShare::Public)),
+ link_share_access_level: Some(Some(AccessLevel::View)),
+ ..request()
+ },
+ )
+ .await;
+ assert!(matches!(result, Err(AgentSessionError::InvalidSharing(_))));
+ assert!(repo.writes.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn rejects_owner_grants_before_writing() {
let repo = Repo::new();
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 8ef78c5a89..6b807539fb 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -414,9 +414,10 @@ impl IntoResponse for AgentSessionApiError {
| AgentSessionError::TooManyPullRequests(_)
| AgentSessionError::InvalidPullRequestUrl),
) => (StatusCode::BAD_REQUEST, error.to_string()).into_response(),
- Self::Domain(error @ AgentSessionError::Archived(_)) => {
- (StatusCode::CONFLICT, error.to_string()).into_response()
- }
+ Self::Domain(
+ error
+ @ (AgentSessionError::Archived(_) | AgentSessionError::AnswersConversation(_)),
+ ) => (StatusCode::CONFLICT, error.to_string()).into_response(),
// Somebody else answered first, or the agent moved on: nothing to
// answer anymore, and the transcript already shows how it went.
Self::Domain(error @ AgentSessionError::PermissionRequestNotFound(_)) => {
@@ -948,6 +949,7 @@ pub async fn rename_agent_session_handler<
(status = 204),
(status = 401, body = String),
(status = 403, body = String),
+ (status = 409, body = String, description = "The session answers an agent conversation"),
(status = 500, body = String),
)
)]
diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rs
index 60adea11e9..04d1c8a01a 100644
--- a/crates/agent_session/src/inbound/axum_router/test/read.rs
+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs
@@ -9,7 +9,7 @@ use crate::testing::InMemoryAgentSessionRepo;
async fn view_router() -> Router {
let repo = InMemoryAgentSessionRepo::new();
repo.create(CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id: AgentSessionId::TEST_A,
owner_id: Owner::User(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 04c31c752a..e90a2194d2 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -9,6 +9,7 @@ use sqlx::types::Json;
#[cfg(test)]
mod test;
+mod agent_conversation;
mod pull_request;
mod queue;
mod recovery;
@@ -35,7 +36,6 @@ use crate::outbound::connection_gateway_realtime::SessionAudience;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
use anyhow::Context;
-use bot_id::MACRO_NEW_BOT_ID;
use bots::domain::models::BotId;
use bots::domain::ports::BotRepo;
use bots::outbound::pg_bots_repo::PgBotsRepo;
@@ -59,6 +59,7 @@ use std::num::NonZeroUsize;
pub struct PgAgentSessionRepo<B> {
pool: PgPool,
registrar: OwnedEntityRegistrar<B>,
+ list_policy: crate::domain::list_visibility::SessionListPolicy,
}
impl<B> std::fmt::Debug for PgAgentSessionRepo<B> {
@@ -74,7 +75,20 @@ impl<B: BotFacts> PgAgentSessionRepo<B> {
/// Create a Postgres agent session repository that registers owners
/// through `registrar`.
pub fn new(pool: PgPool, registrar: OwnedEntityRegistrar<B>) -> Self {
- Self { pool, registrar }
+ Self {
+ pool,
+ registrar,
+ list_policy: Default::default(),
+ }
+ }
+
+ /// Configure the session domain's staged DM visibility policy.
+ pub fn with_list_policy(
+ mut self,
+ policy: crate::domain::list_visibility::SessionListPolicy,
+ ) -> Self {
+ self.list_policy = policy;
+ self
}
}
@@ -300,7 +314,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {
impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
async fn create(&self, params: CreateAgentSessionParams) -> Result<AgentSession> {
let CreateAgentSessionParams {
- warm,
+ purpose,
id,
owner_id,
bot_id,
@@ -344,10 +358,19 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
}
let (status, status_event_name) = status_columns(&SessionStatus::NoMessages);
- // An inline @macro mention is a one-shot on the message. It stays out
- // of the agents list and search. Every other session — the agents
- // composer, coding agents — is a list row.
- let list_hidden = warm || (bot_id == MACRO_NEW_BOT_ID && thread_id.is_some());
+ let conversation = sqlx::query_scalar!(
+ "SELECT EXISTS (SELECT 1 FROM agent_conversation_sessions WHERE session_id = $1) AS \"exists!\"",
+ id.as_uuid(),
+ )
+ .fetch_one(&mut *transaction)
+ .await
+ .context("read session creation provenance")?;
+ let purpose = purpose.for_creation(
+ conversation,
+ thread_id.is_some() || originating_message_id.is_some(),
+ )?;
+ let list_hidden = purpose.list_hidden(bot_id, thread_id, self.list_policy.hide_agent_dms);
+ let warm = purpose == crate::domain::model::SessionPurpose::Warm;
let row = sqlx::query_as!(
AgentSessionRow,
r#"
@@ -355,9 +378,9 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
id, owner_id, thread_id, originating_message_id, bot_id, model,
harness, repo_url, workspace, sandbox_size, instructions,
acp_session_id, status, status_event_name, egress_token_hash,
- mcp_scope, mcp_servers, repo_branch, list_hidden
+ mcp_scope, mcp_servers, repo_branch, list_hidden, for_warming
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
RETURNING
id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,
model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,
@@ -390,6 +413,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
mcp_servers_json,
repo_branch.as_ref().map(|branch| branch.as_str()),
list_hidden,
+ warm,
)
.fetch_one(&mut *transaction)
.await
@@ -481,7 +505,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
}
async fn get(&self, id: AgentSessionId) -> Result<AgentSession> {
- Ok(self.find(id).await?.context("agent session not found")?)
+ self.find(id).await?.ok_or(AgentSessionError::NotFound(id))
}
async fn find(&self, id: AgentSessionId) -> Result<Option<AgentSession>> {
@@ -964,6 +988,23 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {
Ok(())
}
+ async fn is_current_conversation_session(&self, id: AgentSessionId) -> Result<bool> {
+ Ok(sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM agent_conversation_sessions
+ WHERE session_id = $1
+ AND is_current
+ ) AS "current!"
+ "#,
+ id.as_uuid(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to read whether the session answers a conversation")?)
+ }
+
async fn set_name_if_default(&self, id: AgentSessionId, name: &str) -> Result<bool> {
let mut transaction = self
.pool
@@ -1858,4 +1899,5 @@ impl<B: BotFacts + 'static> SessionAudience for PgAgentSessionRepo<B> {
}
}
+mod list_visibility;
mod warm;
diff --git a/crates/agent_session/src/outbound/postgres/agent_conversation.rs b/crates/agent_session/src/outbound/postgres/agent_conversation.rs
new file mode 100644
index 0000000000..aa1e0c21d9
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/agent_conversation.rs
@@ -0,0 +1,121 @@
+//! Session reservations keep a conversation stable across concurrent posts
+//! and restarts.
+
+use super::*;
+use crate::domain::agent_conversation::{
+ AgentConversation, AgentConversationRepo, ConversationSession,
+};
+
+#[cfg(test)]
+mod test;
+
+impl<B: BotFacts + 'static> PgAgentSessionRepo<B> {
+ async fn reserve_conversation_session(
+ &self,
+ conversation: AgentConversation,
+ fresh: bool,
+ ) -> Result<AgentSessionId> {
+ let AgentConversation { channel_id, bot_id } = conversation;
+ let mut tx = self.pool.begin().await.map_err(anyhow::Error::from)?;
+ let lock_key = format!("agent-conversation-session:{channel_id}:{bot_id}");
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ lock_key
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if fresh {
+ sqlx::query!(
+ "UPDATE agent_conversation_sessions SET is_current = FALSE WHERE channel_id = $1 AND bot_id = $2 AND is_current",
+ channel_id,
+ bot_id.as_uuid()
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ }
+ let current = sqlx::query_scalar!(
+ "SELECT session_id FROM agent_conversation_sessions WHERE channel_id = $1 AND bot_id = $2 AND is_current",
+ channel_id,
+ bot_id.as_uuid()
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ let session_id = current
+ .map(AgentSessionId::new_from_uuid)
+ .unwrap_or_else(AgentSessionId::new);
+ if current.is_none() {
+ sqlx::query!(
+ "INSERT INTO agent_conversation_sessions (session_id, channel_id, bot_id) VALUES ($1, $2, $3)",
+ session_id.as_uuid(),
+ channel_id,
+ bot_id.as_uuid()
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(anyhow::Error::from)?;
+ }
+ tx.commit().await.map_err(anyhow::Error::from)?;
+ Ok(session_id)
+ }
+}
+
+impl<B: BotFacts + 'static> AgentConversationRepo for PgAgentSessionRepo<B> {
+ async fn sessions(&self, conversation: AgentConversation) -> Result<Vec<ConversationSession>> {
+ let rows = sqlx::query!(
+ "SELECT session_id, created_at, is_current FROM agent_conversation_sessions WHERE channel_id = $1 AND bot_id = $2 ORDER BY created_at, session_id",
+ conversation.channel_id,
+ conversation.bot_id.as_uuid()
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(rows
+ .into_iter()
+ .map(|row| ConversationSession {
+ session_id: AgentSessionId::new_from_uuid(row.session_id),
+ created_at: row.created_at,
+ is_current: row.is_current,
+ })
+ .collect())
+ }
+
+ async fn current_or_create(&self, conversation: AgentConversation) -> Result<AgentSessionId> {
+ self.reserve_conversation_session(conversation, false).await
+ }
+
+ async fn current(&self, conversation: AgentConversation) -> Result<Option<AgentSessionId>> {
+ Ok(sqlx::query_scalar!(
+ "SELECT session_id FROM agent_conversation_sessions WHERE channel_id = $1 AND bot_id = $2 AND is_current",
+ conversation.channel_id,
+ conversation.bot_id.as_uuid()
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?
+ .map(AgentSessionId::new_from_uuid))
+ }
+
+ async fn start_fresh(&self, conversation: AgentConversation) -> Result<AgentSessionId> {
+ self.reserve_conversation_session(conversation, true).await
+ }
+
+ async fn conversation_for_session(
+ &self,
+ session_id: AgentSessionId,
+ ) -> Result<Option<AgentConversation>> {
+ Ok(sqlx::query!(
+ "SELECT channel_id, bot_id FROM agent_conversation_sessions WHERE session_id = $1",
+ session_id.as_uuid()
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?
+ .map(|row| AgentConversation {
+ channel_id: row.channel_id,
+ bot_id: BotId::new_from_uuid(row.bot_id),
+ }))
+ }
+}
diff --git a/crates/agent_session/src/outbound/postgres/agent_conversation/test.rs b/crates/agent_session/src/outbound/postgres/agent_conversation/test.rs
new file mode 100644
index 0000000000..8be9e544a0
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/agent_conversation/test.rs
@@ -0,0 +1,101 @@
+use super::*;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+async fn channel(pool: &PgPool) -> Uuid {
+ let id = macro_uuid::generate_uuid_v7();
+ sqlx::query!("INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', 'macro|[email protected]')", id)
+ .execute(pool).await.unwrap();
+ id
+}
+
+fn with(channel_id: Uuid, bot_id: BotId) -> AgentConversation {
+ AgentConversation { channel_id, bot_id }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn simultaneous_first_posts_reserve_the_same_session_before_it_exists(pool: PgPool) {
+ let conversation = with(channel(&pool).await, bot_id::MACRO_NEW_BOT_ID);
+ let repo = super::super::test::test_repo(&pool);
+ assert_eq!(repo.current(conversation).await.unwrap(), None);
+ let (a, b) = tokio::join!(
+ repo.current_or_create(conversation),
+ repo.current_or_create(conversation)
+ );
+ let id = a.unwrap();
+ assert_eq!(b.unwrap(), id);
+ assert_eq!(repo.current(conversation).await.unwrap(), Some(id));
+ assert_eq!(
+ repo.conversation_for_session(id).await.unwrap(),
+ Some(conversation)
+ );
+ assert!(matches!(
+ AgentSessionRepo::get(&repo, id).await,
+ Err(AgentSessionError::NotFound(_))
+ ));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn start_fresh_preserves_earlier_sessions_and_isolates_other_conversations(pool: PgPool) {
+ let first_conversation = with(channel(&pool).await, bot_id::MACRO_NEW_BOT_ID);
+ let second_conversation = with(channel(&pool).await, bot_id::MACRO_NEW_BOT_ID);
+ let repo = super::super::test::test_repo(&pool);
+ let first = repo.current_or_create(first_conversation).await.unwrap();
+ let second = repo.current_or_create(second_conversation).await.unwrap();
+ let fresh = repo.start_fresh(first_conversation).await.unwrap();
+ assert_ne!(fresh, first);
+ assert_eq!(
+ repo.current_or_create(first_conversation).await.unwrap(),
+ fresh
+ );
+ assert_eq!(
+ repo.current(second_conversation).await.unwrap(),
+ Some(second)
+ );
+ assert_eq!(
+ repo.conversation_for_session(first).await.unwrap(),
+ Some(first_conversation)
+ );
+ assert_eq!(
+ repo.conversation_for_session(fresh).await.unwrap(),
+ Some(first_conversation)
+ );
+ let sessions = repo.sessions(first_conversation).await.unwrap();
+ assert_eq!(
+ sessions
+ .iter()
+ .map(|session| (session.session_id, session.is_current))
+ .collect::<Vec<_>>(),
+ [(first, false), (fresh, true)]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn two_agents_in_one_channel_run_on_separate_sessions(pool: PgPool) {
+ let channel = channel(&pool).await;
+ let first = with(channel, bot_id::MACRO_NEW_BOT_ID);
+ let second = with(channel, bot_id::MACRO_CODER_BOT_ID);
+ let repo = super::super::test::test_repo(&pool);
+ let first_session = repo.current_or_create(first).await.unwrap();
+ let second_session = repo.current_or_create(second).await.unwrap();
+ assert_ne!(first_session, second_session);
+ let fresh = repo.start_fresh(first).await.unwrap();
+ assert_eq!(repo.current(second).await.unwrap(), Some(second_session));
+ assert_eq!(repo.current(first).await.unwrap(), Some(fresh));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn only_the_current_session_answers_its_conversation(pool: PgPool) {
+ let conversation = with(channel(&pool).await, bot_id::MACRO_NEW_BOT_ID);
+ let repo = super::super::test::test_repo(&pool);
+ let first = repo.current_or_create(conversation).await.unwrap();
+ assert!(repo.is_current_conversation_session(first).await.unwrap());
+ let fresh = repo.start_fresh(conversation).await.unwrap();
+ assert!(!repo.is_current_conversation_session(first).await.unwrap());
+ assert!(repo.is_current_conversation_session(fresh).await.unwrap());
+ assert!(
+ !repo
+ .is_current_conversation_session(AgentSessionId::new())
+ .await
+ .unwrap()
+ );
+}
diff --git a/crates/agent_session/src/outbound/postgres/list_visibility.rs b/crates/agent_session/src/outbound/postgres/list_visibility.rs
new file mode 100644
index 0000000000..5637124021
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/list_visibility.rs
@@ -0,0 +1,25 @@
+use super::*;
+use crate::domain::list_visibility::SessionListVisibilityRepo;
+
+impl<B: BotFacts + 'static> SessionListVisibilityRepo for PgAgentSessionRepo<B> {
+ async fn hide_dm_sessions(&self, limit: u16) -> Result<u64> {
+ let result = sqlx::query!(
+ r#"
+ UPDATE agent_session SET list_hidden = TRUE, for_warming = FALSE
+ WHERE id IN (
+ SELECT s.id FROM agent_session s
+ JOIN agent_conversation_sessions c ON c.session_id = s.id
+ JOIN comms_channel_agents a ON a.channel_id = c.channel_id
+ AND a.bot_id = c.bot_id AND a.kind = 'direct'
+ WHERE NOT s.list_hidden OR s.for_warming
+ ORDER BY s.id LIMIT $1 FOR UPDATE OF s SKIP LOCKED
+ )
+ "#,
+ i64::from(limit),
+ )
+ .execute(&self.pool)
+ .await
+ .context("hide existing agent DM contexts")?;
+ Ok(result.rows_affected())
+ }
+}
diff --git a/crates/agent_session/src/outbound/postgres/sharing.rs b/crates/agent_session/src/outbound/postgres/sharing.rs
index e6c49ac11a..699f7d6b15 100644
--- a/crates/agent_session/src/outbound/postgres/sharing.rs
+++ b/crates/agent_session/src/outbound/postgres/sharing.rs
@@ -31,6 +31,12 @@ fn team_error(error: rootcause::Report<TeamShareError>) -> AgentSessionError {
}
impl<B: BotFacts + 'static> SessionSharingRepo for PgAgentSessionRepo<B> {
+ async fn is_private_conversation(&self, id: AgentSessionId) -> Result<bool> {
+ Ok(sqlx::query_scalar!(
+ "SELECT EXISTS(SELECT 1 FROM agent_conversation_sessions session JOIN comms_channel_agents agent ON agent.channel_id = session.channel_id AND agent.bot_id = session.bot_id WHERE session.session_id = $1 AND agent.kind = 'direct') AS \"exists!\"",
+ id.as_uuid()
+ ).fetch_one(&self.pool).await.context("read session conversation provenance")?)
+ }
#[tracing::instrument(skip(self), err)]
async fn permissions(&self, id: AgentSessionId) -> Result<SharePermissionV2> {
let row = sqlx::query!(
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index 47769c68f0..bbf2df7a52 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -22,7 +22,7 @@ fn user_id(value: &str) -> MacroUserIdStr<'static> {
}
/// The fixed owner every [`new_session`] fixture uses.
-const OWNER: &str = "macro|[email protected]";
+pub(super) const OWNER: &str = "macro|[email protected]";
/// Insert a `"User"` row (and its `macro_user` parent) for user-owned sessions
/// and their user history.
@@ -91,7 +91,7 @@ pub(super) fn new_session(
originating_message_id: Option<Uuid>,
) -> CreateAgentSessionParams {
CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
repo_branch: None,
id: AgentSessionId::new(),
owner_id: Owner::User(user_id(OWNER)),
@@ -262,7 +262,7 @@ async fn create_refuses_an_owner_that_is_not_a_user(pool: PgPool) {
let repo = test_repo(&pool);
let bot_id = create_test_bot(&pool).await;
let params = CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
owner_id: Owner::Bot(bot_id),
..new_session(bot_id, None, None)
};
@@ -320,7 +320,7 @@ async fn create_rejects_an_unknown_user_owner(pool: PgPool) {
let repo = test_repo(&pool);
let bot_id = create_test_bot(&pool).await;
let params = CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
owner_id: Owner::User(user_id("macro|[email protected]")),
..new_session(bot_id, None, None)
};
@@ -418,7 +418,7 @@ async fn instructions_round_trip_on_every_read_path(pool: PgPool) {
let (_channel_id, thread_id, originating_message_id) =
insert_originating_thread_fixture(&pool).await;
let params = CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
instructions: Some(INSTRUCTIONS.to_owned()),
egress_token_hash: Some("token-hash".to_owned()),
..new_session(bot_id, Some(thread_id), Some(originating_message_id))
@@ -473,7 +473,7 @@ async fn mcp_server_selection_round_trips_on_every_read_path(pool: PgPool) {
],
};
let params = CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
mcp_servers: selection.clone(),
egress_token_hash: Some("mcp-token-hash".to_owned()),
..new_session(bot_id, Some(thread_id), Some(originating_message_id))
@@ -1072,7 +1072,7 @@ async fn recent_for_owner_returns_the_owners_newest_sessions(pool: PgPool) {
let someone_else = create_session(
&repo,
CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
owner_id: Owner::User(user_id(OTHER_OWNER)),
..new_session(bot_id, None, None)
},
@@ -3070,7 +3070,7 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo
let bot = create_test_bot(&pool).await;
let repo = test_repo(&pool);
let mut params = new_session(bot, None, None);
- params.warm = true;
+ params.purpose = crate::domain::model::SessionPurpose::Warm;
let session = AgentSessionRepo::create(&repo, params)
.await
.expect("warm session");
@@ -3159,6 +3159,16 @@ async fn warm_sessions_are_hidden_and_claimed_only_once_by_the_owner(pool: PgPoo
.len(),
1
);
+ assert!(
+ !sqlx::query_scalar!(
+ "SELECT for_warming FROM agent_session WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ "a successful claim clears the lifecycle marker"
+ );
assert!(repo.expire().await.unwrap().is_empty());
}
@@ -3168,7 +3178,7 @@ async fn expired_warm_sessions_cannot_be_claimed(pool: PgPool) {
let bot = create_test_bot(&pool).await;
let repo = test_repo(&pool);
let mut params = new_session(bot, None, None);
- params.warm = true;
+ params.purpose = crate::domain::model::SessionPurpose::Warm;
let session = AgentSessionRepo::create(&repo, params).await.unwrap();
sqlx::query!(
"UPDATE agent_session SET created_at = NOW() - INTERVAL '11 minutes' WHERE id = $1",
diff --git a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs
index a275609b56..3cd5d5437e 100644
--- a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs
+++ b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs
@@ -20,7 +20,7 @@ async fn cleanup_batches_remove_all_session_rows_without_a_user_cascade(pool: Pg
let other = create_session(
&repo,
CreateAgentSessionParams {
- warm: false,
+ purpose: crate::domain::model::SessionPurpose::Standalone,
owner_id: Owner::User(user_id(OTHER)),
..new_session(bot, None, None)
},
diff --git a/crates/agent_session/src/outbound/postgres/warm.rs b/crates/agent_session/src/outbound/postgres/warm.rs
index 82613d31df..3624bc8e62 100644
--- a/crates/agent_session/src/outbound/postgres/warm.rs
+++ b/crates/agent_session/src/outbound/postgres/warm.rs
@@ -1,5 +1,9 @@
-//! Warm sessions use list_hidden without a thread; hidden mentions always have a thread.
+//! Warm lifecycle is independent of list visibility. Conversation reservations
+//! are excluded defensively, including contexts reserved before runtime startup.
use super::*;
+
+#[cfg(test)]
+mod test;
use crate::domain::warm::{WarmClaim, WarmMissReason, WarmSessionLifecycle};
use std::{future::Future, pin::Pin};
@@ -21,7 +25,9 @@ impl<B: BotFacts + 'static> WarmSessionLifecycle for PgAgentSessionRepo<B> {
WITH candidate AS (
SELECT
true AS found,
- list_hidden AND thread_id IS NULL AS warm,
+ for_warming AND list_hidden AND thread_id IS NULL AND NOT EXISTS (
+ SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = agent_session.id
+ ) AS warm,
owner_id = $2 AS owner_matches,
bot_id = $3 AS bot_matches,
model = $4 AS model_matches,
@@ -31,10 +37,11 @@ impl<B: BotFacts + 'static> WarmSessionLifecycle for PgAgentSessionRepo<B> {
created_at > NOW() - INTERVAL '10 minutes' AS fresh
FROM agent_session WHERE id = $1
), claimed AS (
- UPDATE agent_session SET list_hidden = false
+ UPDATE agent_session SET list_hidden = false, for_warming = false
WHERE id = $1 AND owner_id = $2 AND bot_id = $3 AND model = $4
AND instructions IS NOT DISTINCT FROM $5
- AND list_hidden AND thread_id IS NULL
+ AND for_warming AND list_hidden AND thread_id IS NULL
+ AND NOT EXISTS (SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = agent_session.id)
AND status != 'disconnected'
AND NOT (status = 'event' AND status_event_name = 'disconnected')
AND created_at > NOW() - INTERVAL '10 minutes'
@@ -100,7 +107,8 @@ impl<B: BotFacts + 'static> WarmSessionLifecycle for PgAgentSessionRepo<B> {
UPDATE agent_session SET status = 'disconnected'
WHERE id IN (
SELECT id FROM agent_session
- WHERE list_hidden AND thread_id IS NULL
+ WHERE for_warming AND list_hidden AND thread_id IS NULL
+ AND NOT EXISTS (SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = agent_session.id)
AND created_at <= NOW() - INTERVAL '10 minutes'
ORDER BY created_at LIMIT 64 FOR UPDATE SKIP LOCKED
) RETURNING id
diff --git a/crates/agent_session/src/outbound/postgres/warm/legacy_schema.sql b/crates/agent_session/src/outbound/postgres/warm/legacy_schema.sql
new file mode 100644
index 0000000000..808f8df409
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/warm/legacy_schema.sql
@@ -0,0 +1,16 @@
+DROP SCHEMA public CASCADE;
+CREATE SCHEMA public;
+CREATE TABLE agent_session (id UUID PRIMARY KEY, list_hidden BOOLEAN NOT NULL DEFAULT FALSE, thread_id UUID);
+CREATE TABLE agent_conversation_sessions (session_id UUID PRIMARY KEY, channel_id UUID, bot_id UUID);
+CREATE TABLE comms_channel_agents (channel_id UUID, bot_id UUID, kind TEXT);
+INSERT INTO agent_session (id, list_hidden, thread_id) VALUES
+ ('00000000-0000-0000-0000-000000000001', TRUE, NULL),
+ ('00000000-0000-0000-0000-000000000002', FALSE, NULL),
+ ('00000000-0000-0000-0000-000000000003', FALSE, NULL),
+ ('00000000-0000-0000-0000-000000000004', FALSE, NULL),
+ ('00000000-0000-0000-0000-000000000005', TRUE, '00000000-0000-0000-0000-000000000006');
+INSERT INTO agent_conversation_sessions (session_id, channel_id, bot_id) VALUES
+ ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000008'),
+ ('00000000-0000-0000-0000-000000000003', '00000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000008');
+INSERT INTO comms_channel_agents (channel_id, bot_id, kind) VALUES
+ ('00000000-0000-0000-0000-000000000007', '00000000-0000-0000-0000-000000000008', 'direct');
diff --git a/crates/agent_session/src/outbound/postgres/warm/test.rs b/crates/agent_session/src/outbound/postgres/warm/test.rs
new file mode 100644
index 0000000000..5b9419529d
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/warm/test.rs
@@ -0,0 +1,269 @@
+use crate::domain::agent_conversation::{AgentConversation, AgentConversationRepo};
+use crate::domain::error::AgentSessionError;
+use crate::domain::model::SessionPurpose;
+use crate::domain::model::SessionStatus;
+use crate::domain::ports::AgentSessionRepo;
+use crate::domain::warm::{WarmClaim, WarmMissReason, WarmSessionLifecycle};
+use crate::outbound::postgres::test::{OWNER, create_test_bot, new_session, test_repo};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
+use sqlx::PgPool;
+use std::num::NonZeroUsize;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn dm_contexts_stay_hidden_and_cannot_be_claimed_or_expired(pool: PgPool) {
+ let bot = create_test_bot(&pool).await;
+ let repo =
+ test_repo(&pool).with_list_policy(crate::domain::list_visibility::SessionListPolicy {
+ hide_agent_dms: true,
+ });
+ let channel = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ channel,
+ OWNER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let conversation = AgentConversation {
+ channel_id: channel,
+ bot_id: bot,
+ };
+ let first = repo.current_or_create(conversation).await.unwrap();
+ let fresh = repo.start_fresh(conversation).await.unwrap();
+ let standalone = repo.create(new_session(bot, None, None)).await.unwrap();
+ for (id, purpose) in [
+ (first, SessionPurpose::AgentDm),
+ (fresh, SessionPurpose::Standalone),
+ ] {
+ let mut params = new_session(bot, None, None);
+ params.id = id;
+ params.purpose = purpose;
+ // Legacy standalone callers also adopt durable conversation provenance.
+ let dm = repo.create(params).await.unwrap();
+ assert!(
+ !sqlx::query_scalar!(
+ "SELECT for_warming FROM agent_session WHERE id = $1",
+ id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ );
+ assert_eq!(repo.get(id).await.unwrap().id, id);
+ assert_eq!(
+ repo.claim(id, &dm.owner_id, bot, &dm.model, None)
+ .await
+ .unwrap(),
+ WarmClaim::Missed(WarmMissReason::NotWarm)
+ );
+ }
+ let listed = repo
+ .recent_for_owner(
+ &MacroUserIdStr::parse_from_str(OWNER).unwrap(),
+ NonZeroUsize::new(10).unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ listed.iter().map(|s| s.id).collect::<Vec<_>>(),
+ vec![standalone.id]
+ );
+ // A corrupt/legacy warm marker must not allow cleanup of either context.
+ sqlx::query!("UPDATE agent_session SET for_warming = TRUE, created_at = NOW() - INTERVAL '11 minutes' WHERE id = ANY($1)", &[first.as_uuid(), fresh.as_uuid()])
+ .execute(&pool).await.unwrap();
+ assert!(repo.expire().await.unwrap().is_empty());
+ for id in [first, fresh] {
+ let dm = repo.get(id).await.unwrap();
+ assert_eq!(dm.status, SessionStatus::NoMessages);
+ assert_eq!(
+ repo.claim(id, &dm.owner_id, bot, &dm.model, None)
+ .await
+ .unwrap(),
+ WarmClaim::Missed(WarmMissReason::NotWarm)
+ );
+ }
+ assert_eq!(repo.sessions(conversation).await.unwrap().len(), 2);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn warm_creation_rejects_a_reserved_conversation(pool: PgPool) {
+ let bot = create_test_bot(&pool).await;
+ let repo = test_repo(&pool);
+ let channel = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ channel,
+ OWNER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let id = repo
+ .current_or_create(AgentConversation {
+ channel_id: channel,
+ bot_id: bot,
+ })
+ .await
+ .unwrap();
+ let mut params = new_session(bot, None, None);
+ params.id = id;
+ params.purpose = SessionPurpose::Warm;
+ assert!(matches!(
+ repo.create(params).await,
+ Err(AgentSessionError::InvalidSessionPurpose)
+ ));
+ assert!(matches!(
+ repo.get(id).await,
+ Err(AgentSessionError::NotFound(_))
+ ));
+}
+
+#[test]
+fn warm_policy_rejects_message_provenance() {
+ assert!(matches!(
+ SessionPurpose::Warm.for_creation(false, true),
+ Err(AgentSessionError::InvalidSessionPurpose)
+ ));
+ assert_eq!(
+ SessionPurpose::Warm.for_creation(false, false).unwrap(),
+ SessionPurpose::Warm
+ );
+ assert!(SessionPurpose::AgentDm.list_hidden(bot_id::MACRO_NEW_BOT_ID, None, true));
+ assert!(!SessionPurpose::AgentDm.list_hidden(bot_id::MACRO_NEW_BOT_ID, None, false));
+ assert!(!SessionPurpose::Standalone.list_hidden(bot_id::MACRO_NEW_BOT_ID, None, true));
+}
+
+#[sqlx::test(migrations = false)]
+async fn migration_preserves_old_writers_and_stages_dm_visibility(pool: PgPool) {
+ // SQLx clones template1; this test intentionally reconstructs the old schema.
+ sqlx::raw_sql(include_str!("legacy_schema.sql"))
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql(include_str!("../../../../../macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.up.sql"))
+ .execute(&pool).await.unwrap();
+ let before = sqlx::query!("SELECT id, list_hidden, for_warming FROM agent_session ORDER BY id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert!(
+ before[0].for_warming,
+ "existing speculative session retained"
+ );
+ assert!(
+ !before[1].list_hidden && !before[2].list_hidden,
+ "migration does not expose hidden DMs to old reapers"
+ );
+ assert!(!before[1].for_warming && !before[2].for_warming);
+ assert!(!before[3].list_hidden);
+ assert!(
+ before[4].list_hidden && !before[4].for_warming,
+ "inline mention remains hidden but not warm"
+ );
+ // Emulate an older writer that omits the marker entirely.
+ let id = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ "INSERT INTO agent_session (id, list_hidden) VALUES ($1, TRUE)",
+ id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let warm = sqlx::query_scalar!("SELECT for_warming FROM agent_session WHERE id = $1", id)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(warm);
+ // Emulate an older claimant. New lifecycle must never reclaim/delete it.
+ sqlx::query!(
+ "UPDATE agent_session SET list_hidden = FALSE WHERE id = $1",
+ id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ !sqlx::query_scalar!("SELECT for_warming FROM agent_session WHERE id = $1", id)
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ );
+ // Once the old reapers are gone, the domain policy backfills both contexts.
+ let repo = test_repo(&pool);
+ crate::domain::list_visibility::SessionListPolicy {
+ hide_agent_dms: false,
+ }
+ .reconcile(&repo)
+ .await
+ .unwrap();
+ let disabled =
+ sqlx::query!("SELECT id, list_hidden, for_warming FROM agent_session ORDER BY id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert!(!disabled[1].list_hidden && !disabled[2].list_hidden);
+ crate::domain::list_visibility::SessionListPolicy {
+ hide_agent_dms: true,
+ }
+ .reconcile(&repo)
+ .await
+ .unwrap();
+ let after = sqlx::query!("SELECT id, list_hidden, for_warming FROM agent_session ORDER BY id")
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ assert!(after[1].list_hidden && after[2].list_hidden);
+ assert!(!after[1].for_warming && !after[2].for_warming);
+ assert!(
+ !after[3].list_hidden,
+ "unrelated standalone session stays listed"
+ );
+ assert!(
+ after[0].for_warming,
+ "legitimate warm lifecycle is unchanged"
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_old_claimant_cannot_leave_a_visible_session_eligible_for_cleanup(pool: PgPool) {
+ let bot = create_test_bot(&pool).await;
+ let repo = test_repo(&pool);
+ let mut params = new_session(bot, None, None);
+ params.purpose = SessionPurpose::Warm;
+ let session = repo.create(params).await.unwrap();
+ sqlx::query!(
+ "UPDATE agent_session SET list_hidden = FALSE WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ // Even a stale true marker cannot defeat the visibility invariant.
+ sqlx::query!(
+ "UPDATE agent_session SET for_warming = TRUE WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.claim(session.id, &session.owner_id, bot, &session.model, None)
+ .await
+ .unwrap(),
+ WarmClaim::Missed(WarmMissReason::NotWarm)
+ );
+ sqlx::query!(
+ "UPDATE agent_session SET created_at = NOW() - INTERVAL '11 minutes' WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(repo.expire().await.unwrap().is_empty());
+ assert_eq!(
+ repo.get(session.id).await.unwrap().status,
+ SessionStatus::NoMessages
+ );
+}
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index cf8633c94f..e20941ce88 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -87,6 +87,9 @@ pub struct InMemoryAgentSessionRepo {
queues: Arc<Mutex<HashMap<AgentSessionId, Vec<StoredQueuedAction>>>>,
/// Session -> who prompted its turn, mirroring the `turn_*` columns.
turn_prompters: Arc<Mutex<HashMap<AgentSessionId, TurnPrompter>>>,
+ /// Sessions an agent conversation sends its messages to, mirroring the
+ /// current rows of `agent_conversation_sessions`.
+ conversation_sessions: Arc<Mutex<std::collections::HashSet<AgentSessionId>>>,
}
impl InMemoryAgentSessionRepo {
@@ -105,6 +108,15 @@ impl InMemoryAgentSessionRepo {
.insert(session.id, session);
}
+ /// Make `session` the one an agent conversation's channel sends its
+ /// messages to.
+ pub fn answer_conversation(&self, session: AgentSessionId) {
+ self.conversation_sessions
+ .lock()
+ .expect("in-memory conversation store is not poisoned")
+ .insert(session);
+ }
+
/// The activity projection last committed with this session's log.
#[must_use]
pub fn turn_state(
@@ -262,9 +274,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
}
async fn get(&self, id: AgentSessionId) -> Result<AgentSession> {
- self.find(id).await?.ok_or_else(|| {
- AgentSessionError::Unknown(anyhow::anyhow!("no agent session {}", id.as_uuid()))
- })
+ self.find(id).await?.ok_or(AgentSessionError::NotFound(id))
}
async fn find(&self, id: AgentSessionId) -> Result<Option<AgentSession>> {
@@ -448,6 +458,14 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
Ok(())
}
+ async fn is_current_conversation_session(&self, id: AgentSessionId) -> Result<bool> {
+ Ok(self
+ .conversation_sessions
+ .lock()
+ .expect("in-memory conversation store is not poisoned")
+ .contains(&id))
+ }
+
async fn set_name_if_default(&self, id: AgentSessionId, name: &str) -> Result<bool> {
let mut sessions = self
.sessions
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index 67fee882dc..e587db3fe9 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -11,7 +11,7 @@ admission = ["dep:ai_billing"]
# models_search → models_soup → notification → rdkafka, and the self-hosted
# daemon only needs domain events from this crate. Services that construct
# the adapters enable this; do not add it to coding_agent_worker.
-outbound = ["admission", "dep:agent", "dep:ai_usage", "dep:async-trait", "dep:call", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
+outbound = ["admission", "dep:agent", "dep:ai_usage", "dep:call", "dep:document_storage_service_client", "dep:document_sub_type", "dep:lexical_client", "dep:sqlx", "dep:static_file", "channels/ports"]
[dependencies]
ai_billing = { path = "../ai_billing", optional = true }
@@ -45,7 +45,7 @@ system_properties = { path = "../system_properties" }
rootcause = { workspace = true }
# Domain vocabulary: channel-parent trigger events keep the channel-only post
# shape, and the channel topic's `message_posted` can still feed the trigger.
-channels = { path = "../channels", default-features = false }
+channels = { path = "../channels", default-features = false, features = ["ports"] }
serde = { workspace = true }
sqlx = { workspace = true, optional = true }
strum = { workspace = true }
@@ -54,7 +54,7 @@ sha2 = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
-async-trait = { workspace = true, optional = true }
+async-trait = { workspace = true }
call = { path = "../call", default-features = false, features = ["ports"], optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 73131b8fd7..aaa0295546 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -112,11 +112,30 @@ pub struct AgentSessionRequestedEvent {
pub context: Option<TriggerContext>,
}
+/// A message in a channel where an agent persona converses. The session
+/// identity is reserved durably before publication, so concurrent first
+/// messages agree on it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct AgentConversationMessageEvent {
+ /// Persona the conversation is with.
+ pub bot_id: BotId,
+ /// The conversation's current session, whether its runtime is running yet or not.
+ pub session_id: AgentSessionId,
+ /// Committed user message.
+ pub message: MessagePostedMetadata,
+ /// Why the agent was called, read under the sender's access. Absent when
+ /// the read failed.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub context: Option<TriggerContext>,
+}
+
/// Events that open a new session.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum NewAgentSessionEvent {
+ /// Open or continue the reserved session of an agent's channel conversation.
+ ConversationMessage(AgentConversationMessageEvent),
/// Opened by a bot mention in a top-level channel message.
TopLevelMentioned(AgentBotMentionedEvent),
/// Opened by a bot mention on a message parent other than a channel.
@@ -155,7 +174,7 @@ impl NewAgentSessionEvent {
message: mentioned.message.clone(),
context: mentioned.context.clone(),
}),
- Self::AssignedToTask(_) | Self::Requested(_) => None,
+ Self::AssignedToTask(_) | Self::Requested(_) | Self::ConversationMessage(_) => None,
}
}
@@ -164,7 +183,10 @@ impl NewAgentSessionEvent {
pub fn requested(&self) -> Option<&AgentSessionRequestedEvent> {
match self {
Self::Requested(requested) => Some(requested),
- Self::TopLevelMentioned(_) | Self::Mentioned(_) | Self::AssignedToTask(_) => None,
+ Self::TopLevelMentioned(_)
+ | Self::Mentioned(_)
+ | Self::AssignedToTask(_)
+ | Self::ConversationMessage(_) => None,
}
}
}
@@ -285,6 +307,7 @@ impl AgentTriggerTopicEvent {
#[must_use]
pub fn bot_id(&self) -> Option<BotId> {
match self {
+ Self::New(NewAgentSessionEvent::ConversationMessage(event)) => Some(event.bot_id),
Self::New(NewAgentSessionEvent::AssignedToTask(assigned)) => Some(assigned.bot_id),
Self::New(event) => event
.mention()
@@ -312,6 +335,16 @@ impl TopicEvent for AgentTriggerTopicEvent {
reason = "both variants carry a whole message; boxing would only move the size"
)]
pub enum TriggerDecision {
+ /// Deliver a message to the reserved current session of an agent's
+ /// channel conversation.
+ ConversationMessage {
+ /// Persona the conversation is with.
+ bot_id: BotId,
+ /// Durable current conversation identity.
+ session_id: AgentSessionId,
+ /// The committed user message.
+ message: MessagePostedMetadata,
+ },
/// Open a session for a mentioned bot.
Open {
/// The bot that was mentioned.
@@ -337,7 +370,9 @@ impl TriggerDecision {
#[must_use]
pub fn bot_id(&self) -> BotId {
match self {
- Self::Open { bot_id, .. } | Self::Existing { bot_id, .. } => *bot_id,
+ Self::Open { bot_id, .. }
+ | Self::Existing { bot_id, .. }
+ | Self::ConversationMessage { bot_id, .. } => *bot_id,
}
}
@@ -345,7 +380,9 @@ impl TriggerDecision {
#[must_use]
pub fn message(&self) -> &MessagePostedMetadata {
match self {
- Self::Open { message, .. } | Self::Existing { message, .. } => message,
+ Self::Open { message, .. }
+ | Self::Existing { message, .. }
+ | Self::ConversationMessage { message, .. } => message,
}
}
}
@@ -397,6 +434,18 @@ impl AgentSessionMacroEvent {
| MessageParent::CrmContact(_) => None,
};
Ok(match decision {
+ TriggerDecision::ConversationMessage {
+ bot_id,
+ session_id,
+ message,
+ } => Self::new_session(NewAgentSessionEvent::ConversationMessage(
+ AgentConversationMessageEvent {
+ bot_id,
+ session_id,
+ message,
+ context,
+ },
+ )),
TriggerDecision::Open { bot_id, message } => match channel {
Some((channel_id, channel_type)) => Self::new_session(
NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
@@ -445,6 +494,7 @@ impl AgentSessionMacroEvent {
#[must_use]
pub fn new_session(event: NewAgentSessionEvent) -> Self {
let bot_id = match &event {
+ NewAgentSessionEvent::ConversationMessage(message) => message.bot_id,
NewAgentSessionEvent::TopLevelMentioned(mentioned) => mentioned.bot_id,
NewAgentSessionEvent::Mentioned(mentioned) => mentioned.bot_id,
NewAgentSessionEvent::AssignedToTask(assigned) => assigned.bot_id,
diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rs
index a237518343..d906121ceb 100644
--- a/crates/agent_trigger/src/domain/broker_events/test.rs
+++ b/crates/agent_trigger/src/domain/broker_events/test.rs
@@ -367,3 +367,66 @@ fn channel_kinds_round_trip_in_snake_case() {
assert_eq!(parsed, kind);
}
}
+
+/// A turn of an agent's private conversation travels with why it was called,
+/// and the conversation's own history stands in for the channel around it.
+#[test]
+fn a_conversation_turn_carries_its_trigger_without_the_channel() {
+ let person = trigger_context::ContextPerson {
+ id: "macro|[email protected]".to_owned(),
+ name: "[email protected]".to_owned(),
+ email: None,
+ };
+ let discussion = trigger_context::DiscussionContext {
+ surface: trigger_context::DiscussionSurface::Channel {
+ id: Uuid::from_u128(1),
+ name: None,
+ channel_type: trigger_context::ChannelType::DirectMessage,
+ },
+ prompt_message_id: Uuid::from_u128(2),
+ sender: person.clone(),
+ reply_target: trigger_context::ReplyTarget::None,
+ thread: None,
+ channel: vec![trigger_context::ContextThread {
+ root_id: Uuid::from_u128(3),
+ messages: vec![trigger_context::ContextMessage {
+ id: Uuid::from_u128(3),
+ author: person,
+ content: "an earlier turn".to_owned(),
+ posted_at: Utc::now(),
+ }],
+ messages_omitted: false,
+ }],
+ };
+ let decision = TriggerDecision::ConversationMessage {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ message: posted(MessageParent::Channel(Uuid::from_u128(1)), None),
+ };
+
+ let context = crate::domain::context::discussion_trigger(&decision, discussion.clone());
+ assert_eq!(
+ context,
+ TriggerContext::Conversation(trigger_context::DiscussionContext {
+ channel: Vec::new(),
+ ..discussion
+ })
+ );
+
+ let event = AgentSessionMacroEvent::from_decision(
+ decision,
+ Some(ChannelType::DirectMessage),
+ Some(context.clone()),
+ )
+ .expect("a channel type was supplied");
+ let AgentTriggerTopicEvent::New(NewAgentSessionEvent::ConversationMessage(turn)) =
+ &event.event().event
+ else {
+ panic!("a conversation turn keeps its own shape: {event:?}");
+ };
+ assert_eq!(turn.context, Some(context));
+ let wire = serde_json::to_value(&event.event().event).expect("serialize event");
+ assert_eq!(wire["metadata"]["source"], "conversation_message");
+ assert_eq!(wire["metadata"]["context"]["kind"], "conversation");
+ assert!(wire["metadata"]["context"].get("channel").is_none());
+}
diff --git a/crates/agent_trigger/src/domain/context.rs b/crates/agent_trigger/src/domain/context.rs
index 5cec10caee..7f9167d346 100644
--- a/crates/agent_trigger/src/domain/context.rs
+++ b/crates/agent_trigger/src/domain/context.rs
@@ -31,8 +31,9 @@ pub trait PeopleDirectory: Send + Sync + 'static {
fn people(&self, ids: Vec<String>) -> impl Future<Output = Result<Vec<ContextPerson>>> + Send;
}
-/// Why a decision calls its agent: a mention opens a session, anything else
-/// follows up in one that is running.
+/// Why a decision calls its agent: a mention opens a session, a message in
+/// an agent's conversation is a turn of it, and anything else follows up in
+/// a session that is running.
#[must_use]
pub fn discussion_trigger(
decision: &TriggerDecision,
@@ -40,6 +41,15 @@ pub fn discussion_trigger(
) -> TriggerContext {
match decision {
TriggerDecision::Open { .. } => TriggerContext::Mentioned(discussion),
+ // The session's history already holds the conversation; reading the
+ // channel again would repeat earlier turns and bring back a segment
+ // the person reset.
+ TriggerDecision::ConversationMessage { .. } => {
+ TriggerContext::Conversation(DiscussionContext {
+ channel: Vec::new(),
+ ..discussion
+ })
+ }
TriggerDecision::Existing { kind, .. } => TriggerContext::FollowUp(FollowUpContext {
addressed_by: match kind {
ThreadMessageKind::MentionThread => AddressedBy::Mention,
diff --git a/crates/agent_trigger/src/domain/conversations.rs b/crates/agent_trigger/src/domain/conversations.rs
new file mode 100644
index 0000000000..9ed64c4b76
--- /dev/null
+++ b/crates/agent_trigger/src/domain/conversations.rs
@@ -0,0 +1,121 @@
+//! Routing for a channel where an agent persona converses: messages there are
+//! turns for it, with no mention needed.
+
+use agent_session::domain::{
+ agent_conversation::{AgentConversation, AgentConversationRepo},
+ error::{AgentSessionError, Result},
+};
+use bots::domain::ports::{AgentDmEligibility, BotError};
+use channels::domain::channel_agents::{ChannelAgentKind, ChannelAgentRepo};
+use messages::domain::{events::MessagePostedMetadata, models::MessageParent};
+
+use super::broker_events::TriggerDecision;
+
+#[cfg(test)]
+mod test;
+
+/// Whether a post is a turn in an agent's conversation.
+pub enum ConversationDecision {
+ /// No agent converses in this channel; mention routing evaluates the post.
+ NotConversation,
+ /// An agent converses here, but the sender may not prompt it now.
+ /// Never fall back to mentioning a different agent in the same channel.
+ Unavailable,
+ /// Deliver to the current session of each agent conversing here.
+ Deliver(Vec<TriggerDecision>),
+}
+
+/// Conversation routing exposed to the common committed-message consumer.
+#[async_trait::async_trait]
+pub trait ConversationRouting: Send + Sync + 'static {
+ /// Resolve a channel's agent conversations after the caller's
+ /// message-posting access was checked.
+ async fn evaluate(&self, posted: &MessagePostedMetadata) -> Result<ConversationDecision>;
+}
+
+/// Coordinates channel agents, persona permission, and session reservation.
+pub struct ConversationRouter<Channels, Personas, Sessions> {
+ channels: Channels,
+ personas: Personas,
+ sessions: Sessions,
+}
+
+impl<C, P, S> ConversationRouter<C, P, S> {
+ /// Compose the owning domains' ports.
+ pub fn new(channels: C, personas: P, sessions: S) -> Self {
+ Self {
+ channels,
+ personas,
+ sessions,
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl<C: ChannelAgentRepo, P: AgentDmEligibility, S: AgentConversationRepo> ConversationRouting
+ for ConversationRouter<C, P, S>
+{
+ async fn evaluate(&self, posted: &MessagePostedMetadata) -> Result<ConversationDecision> {
+ let MessageParent::Channel(channel_id) = posted.parent else {
+ return Ok(ConversationDecision::NotConversation);
+ };
+ let agents = self
+ .channels
+ .agents_in(channel_id)
+ .await
+ .map_err(anyhow::Error::new)?;
+ let mut deliveries = Vec::new();
+ for agent in agents {
+ match agent.kind {
+ ChannelAgentKind::Direct { user_id } => {
+ // Only the owner prompts a direct conversation: the agent
+ // acts with their access.
+ if posted.sender.as_user() != Some(&user_id) {
+ return Ok(ConversationDecision::Unavailable);
+ }
+ // The conversation is the channel's timeline. A reply in a
+ // thread is not one of its turns: the answer would land in
+ // the timeline, away from the thread, and the turn's status
+ // and retry would show nowhere. A thread here routes as in
+ // any channel, so mentioning the agent there still works.
+ if posted.thread_id.is_some() {
+ continue;
+ }
+ match self
+ .personas
+ .authorize_agent_dm(user_id, agent.bot_id)
+ .await
+ {
+ Ok(()) => {}
+ Err(BotError::Unauthorized | BotError::NotFound(_)) => {
+ return Ok(ConversationDecision::Unavailable);
+ }
+ Err(error) => {
+ return Err(AgentSessionError::Unknown(anyhow::Error::new(error)));
+ }
+ }
+ }
+ // Which messages a member of a shared channel answers is not
+ // decided yet, so mentions keep routing there.
+ ChannelAgentKind::Member => continue,
+ }
+ let session_id = self
+ .sessions
+ .current_or_create(AgentConversation {
+ channel_id,
+ bot_id: agent.bot_id,
+ })
+ .await?;
+ deliveries.push(TriggerDecision::ConversationMessage {
+ bot_id: agent.bot_id,
+ session_id,
+ message: posted.clone(),
+ });
+ }
+ Ok(if deliveries.is_empty() {
+ ConversationDecision::NotConversation
+ } else {
+ ConversationDecision::Deliver(deliveries)
+ })
+ }
+}
diff --git a/crates/agent_trigger/src/domain/conversations/test.rs b/crates/agent_trigger/src/domain/conversations/test.rs
new file mode 100644
index 0000000000..aab843b22d
--- /dev/null
+++ b/crates/agent_trigger/src/domain/conversations/test.rs
@@ -0,0 +1,199 @@
+use super::*;
+use agent_session::domain::{agent_conversation::ConversationSession, model::AgentSessionId};
+use bot_id::BotId;
+use channels::domain::{channel_agents::ChannelAgent, ports::ChannelMutationErr};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use std::sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+};
+
+struct Channels(Vec<ChannelAgent>);
+impl ChannelAgentRepo for Channels {
+ async fn agents_in(
+ &self,
+ channel_id: Uuid,
+ ) -> std::result::Result<Vec<ChannelAgent>, ChannelMutationErr> {
+ Ok(self
+ .0
+ .iter()
+ .filter(|agent| agent.channel_id == channel_id)
+ .cloned()
+ .collect())
+ }
+ async fn find(
+ &self,
+ _: Uuid,
+ _: BotId,
+ ) -> std::result::Result<Option<ChannelAgent>, ChannelMutationErr> {
+ unreachable!("routing lists the channel's agents")
+ }
+}
+
+struct Personas(bool);
+impl AgentDmEligibility for Personas {
+ async fn authorize_agent_dm(
+ &self,
+ _: MacroUserIdStr<'static>,
+ bot: BotId,
+ ) -> std::result::Result<(), BotError> {
+ assert_eq!(bot, BotId::TEST_A);
+ if self.0 {
+ Ok(())
+ } else {
+ Err(BotError::Unauthorized)
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+struct Sessions(Arc<AtomicUsize>);
+impl AgentConversationRepo for Sessions {
+ async fn sessions(&self, _: AgentConversation) -> Result<Vec<ConversationSession>> {
+ Ok(Vec::new())
+ }
+ async fn current_or_create(&self, conversation: AgentConversation) -> Result<AgentSessionId> {
+ assert_eq!(conversation.bot_id, BotId::TEST_A);
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(AgentSessionId::TEST_A)
+ }
+ async fn current(&self, _: AgentConversation) -> Result<Option<AgentSessionId>> {
+ Ok(Some(AgentSessionId::TEST_A))
+ }
+ async fn start_fresh(&self, _: AgentConversation) -> Result<AgentSessionId> {
+ panic!("a new message never resets context")
+ }
+ async fn conversation_for_session(
+ &self,
+ _: AgentSessionId,
+ ) -> Result<Option<AgentConversation>> {
+ Ok(Some(AgentConversation {
+ channel_id: Uuid::from_u128(1),
+ bot_id: BotId::TEST_A,
+ }))
+ }
+}
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn direct() -> ChannelAgent {
+ ChannelAgent {
+ channel_id: Uuid::from_u128(1),
+ bot_id: BotId::TEST_A,
+ kind: ChannelAgentKind::Direct { user_id: owner() },
+ }
+}
+
+fn message() -> MessagePostedMetadata {
+ MessagePostedMetadata {
+ parent: MessageParent::Channel(Uuid::from_u128(1)),
+ message_id: Uuid::from_u128(2),
+ root_id: Uuid::from_u128(2),
+ thread_id: None,
+ sender: channel_sender::ChannelSender::new_from_user(owner()),
+ triggered_by: None,
+ content: "Continue our conversation".to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: chrono::Utc::now(),
+ }
+}
+
+#[tokio::test]
+async fn unmentioned_messages_always_address_the_direct_persona_and_session() {
+ let router = ConversationRouter::new(
+ Channels(vec![direct()]),
+ Personas(true),
+ Sessions::default(),
+ );
+ let first = message();
+ let mut next = first.clone();
+ next.message_id = Uuid::from_u128(3);
+ next.root_id = next.message_id;
+ for post in [first, next] {
+ let ConversationDecision::Deliver(decisions) = router.evaluate(&post).await.unwrap() else {
+ panic!("expected delivery")
+ };
+ let [
+ TriggerDecision::ConversationMessage {
+ bot_id,
+ session_id,
+ message,
+ },
+ ] = decisions.as_slice()
+ else {
+ panic!("expected one conversation delivery")
+ };
+ assert_eq!(*bot_id, BotId::TEST_A);
+ assert_eq!(*session_id, AgentSessionId::TEST_A);
+ assert_eq!(*message, post);
+ }
+}
+
+#[tokio::test]
+async fn a_bot_or_another_user_cannot_spend_the_direct_owners_credentials() {
+ let sessions = Sessions::default();
+ let router =
+ ConversationRouter::new(Channels(vec![direct()]), Personas(true), sessions.clone());
+ for sender in [
+ channel_sender::ChannelSender::new_from_bot(BotId::TEST_A),
+ channel_sender::ChannelSender::new_from_user(
+ MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ ),
+ ] {
+ let mut post = message();
+ post.sender = sender;
+ assert!(matches!(
+ router.evaluate(&post).await.unwrap(),
+ ConversationDecision::Unavailable
+ ));
+ }
+ assert_eq!(sessions.0.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn revoked_persona_access_never_reserves_a_session_or_falls_back_to_mentions() {
+ let sessions = Sessions::default();
+ let router =
+ ConversationRouter::new(Channels(vec![direct()]), Personas(false), sessions.clone());
+ assert!(matches!(
+ router.evaluate(&message()).await.unwrap(),
+ ConversationDecision::Unavailable
+ ));
+ assert_eq!(sessions.0.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn channels_without_a_conversing_agent_keep_the_existing_trigger_path() {
+ let sessions = Sessions::default();
+ let member = ChannelAgent {
+ kind: ChannelAgentKind::Member,
+ ..direct()
+ };
+ for agents in [Vec::new(), vec![member]] {
+ let router = ConversationRouter::new(Channels(agents), Personas(true), sessions.clone());
+ assert!(matches!(
+ router.evaluate(&message()).await.unwrap(),
+ ConversationDecision::NotConversation
+ ));
+ }
+ assert_eq!(sessions.0.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn a_thread_reply_is_not_a_turn_of_the_direct_conversation() {
+ let sessions = Sessions::default();
+ let router =
+ ConversationRouter::new(Channels(vec![direct()]), Personas(true), sessions.clone());
+ let mut reply = message();
+ reply.message_id = Uuid::from_u128(3);
+ reply.thread_id = Some(Uuid::from_u128(2));
+ assert!(matches!(
+ router.evaluate(&reply).await.unwrap(),
+ ConversationDecision::NotConversation
+ ));
+ assert_eq!(sessions.0.load(Ordering::SeqCst), 0);
+}
diff --git a/crates/agent_trigger/src/domain/mod.rs b/crates/agent_trigger/src/domain/mod.rs
index 1e48fc305a..8b169c17cb 100644
--- a/crates/agent_trigger/src/domain/mod.rs
+++ b/crates/agent_trigger/src/domain/mod.rs
@@ -1,5 +1,6 @@
pub mod broker_events;
pub mod context;
+pub mod conversations;
pub mod processing;
pub mod project_assignment;
pub mod service;
diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rs
index 75dcccf5e0..0ed1794169 100644
--- a/crates/agent_trigger/src/domain/service.rs
+++ b/crates/agent_trigger/src/domain/service.rs
@@ -1,14 +1,14 @@
//! Orchestration for evaluating one posted message.
+use super::conversations::{ConversationDecision, ConversationRouting};
use std::collections::HashSet;
+use std::sync::Arc;
#[cfg(test)]
mod test;
#[cfg(feature = "admission")]
use ai_billing::{AiAdmissionService, AiFeature, DisabledAiAdmissionService};
-#[cfg(feature = "admission")]
-use std::sync::Arc;
use agent_session::domain::error::Result;
use agent_session::domain::model::{AgentSession, AgentSessionId, ThreadSession};
@@ -175,6 +175,7 @@ pub struct AgentTriggerService<Repo, Bots, Teams, Channels, Replies, Judge, Hist
replies: Replies,
judge: Judge,
history: History,
+ conversations: Option<Arc<dyn ConversationRouting>>,
#[cfg(feature = "admission")]
admission: Arc<dyn AiAdmissionService>,
}
@@ -209,11 +210,19 @@ where
replies,
judge,
history,
+ conversations: None,
#[cfg(feature = "admission")]
admission: Arc::new(DisabledAiAdmissionService),
}
}
+ /// Route channels where an agent converses before interpreting mentions
+ /// or thread replies.
+ pub fn with_conversations(mut self, router: Arc<dyn ConversationRouting>) -> Self {
+ self.conversations = Some(router);
+ self
+ }
+
/// Configure admission for implicit classification, including image captions.
/// Explicit mentions and deterministic reply routing are admitted downstream.
#[cfg(feature = "admission")]
@@ -378,6 +387,13 @@ where
else {
return Ok(Vec::new());
};
+ if let Some(router) = &self.conversations {
+ match router.evaluate(posted).await? {
+ ConversationDecision::NotConversation => {}
+ ConversationDecision::Unavailable => return Ok(Vec::new()),
+ ConversationDecision::Deliver(decisions) => return Ok(decisions),
+ }
+ }
let mut mentioned = bot_mention_ids(&posted.mentions);
mentioned.sort_by_key(ToString::to_string);
tracing::Span::current().record(
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index e9927163bb..ec2d0c5232 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -29,6 +29,8 @@ pub trait BotRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Agent, Self::Err>> + Send;
/// Replace an owned agent and its selected channel memberships atomically.
+ /// The direct agent conversations it takes part in are not among them and
+ /// are left as they are.
fn update_agent(
&self,
bot_id: BotId,
@@ -40,13 +42,15 @@ pub trait BotRepo: Send + Sync + 'static {
///
/// Own and team-owned agents are included, plus selected-channel agents
/// installed in a channel the caller belongs to — the same personas they
- /// can `@` mention there.
+ /// can `@` mention there. A direct agent conversation is not such a
+ /// channel.
fn list_manageable_agents(
&self,
caller: MacroUserIdStr<'static>,
) -> impl Future<Output = Result<Vec<Agent>, Self::Err>> + Send;
/// Check whether the caller is an active member of every supplied channel.
+ /// A direct agent conversation never counts: it is not a channel to select.
fn user_has_channels(
&self,
caller: MacroUserIdStr<'static>,
@@ -95,7 +99,8 @@ pub trait BotRepo: Send + Sync + 'static {
bot_ids: &[BotId],
) -> impl Future<Output = Result<HashMap<BotId, BotOwnerProfile>, Self::Err>> + Send;
- /// Get an active persisted agent by bot id.
+ /// Get an active persisted agent by bot id. Its channels are the ones it
+ /// was put in, without the direct agent conversations it takes part in.
fn get_agent(
&self,
bot_id: BotId,
@@ -114,14 +119,28 @@ pub trait BotRepo: Send + Sync + 'static {
harness_id: HarnessId,
) -> impl Future<Output = Result<Option<HarnessFacts>, Self::Err>> + Send;
- /// Check whether a bot is an active channel participant.
+ /// Check whether a bot is an active channel participant. A direct agent
+ /// conversation counts: a mention in one of its threads still reaches
+ /// the persona.
fn bot_active_in_channel(
&self,
channel_id: Uuid,
bot_id: BotId,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Whether the user and bot share at least one active channel.
+ /// Check whether a bot may post in a channel on its own: it is an active
+ /// participant, and the channel is not a direct agent conversation. Its
+ /// owner or any member of its team holds the bot's tokens, not just the
+ /// person a direct conversation is with.
+ fn bot_may_post_in_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Whether the user and bot share at least one active channel, other than a
+ /// direct agent conversation: only the people a persona already serves
+ /// have one, so it never makes the persona available.
fn user_shares_channel_with_bot(
&self,
caller: MacroUserIdStr<'static>,
@@ -159,14 +178,16 @@ pub trait BotRepo: Send + Sync + 'static {
bot_id: BotId,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// Remove bot reach from a channel.
+ /// Remove bot reach from a channel. A direct agent conversation keeps its
+ /// persona, so removing it from one finds nothing to remove.
fn remove_bot_from_channel(
&self,
channel_id: Uuid,
bot_id: BotId,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// List active channels containing a bot.
+ /// List active channels containing a bot, without the direct agent
+ /// conversations it takes part in.
fn list_bot_channels(
&self,
bot_id: BotId,
@@ -206,6 +227,7 @@ pub trait BotRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<BotTokenCandidate>, Self::Err>> + Send;
/// Lookup a channel-scoped token candidate by hashing the presented raw token.
+ /// A direct agent conversation accepts no token.
fn channel_token_candidate(
&self,
channel_id: Uuid,
@@ -217,6 +239,17 @@ pub trait BotRepo: Send + Sync + 'static {
-> impl Future<Output = Result<(), Self::Err>> + Send;
}
+/// Eligibility for private conversations with an agent persona.
+pub trait AgentDmEligibility: Send + Sync + 'static {
+ /// Require a runnable persona owned by the caller or their current team.
+ /// Channel placement does not confer or restrict private DM eligibility.
+ fn authorize_agent_dm(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<(), BotError>> + Send;
+}
+
/// Bot service.
#[cfg_attr(feature = "test-utils", mockall::automock)]
pub trait BotService: Send + Sync + 'static {
@@ -354,7 +387,8 @@ pub trait BotService: Send + Sync + 'static {
token_id: Uuid,
) -> impl Future<Output = Result<(), BotError>> + Send;
- /// Ensure that a bot is an active participant in a channel.
+ /// Ensure that a bot may post in a channel on its own: it is an active
+ /// participant, and the channel is not a direct agent conversation.
fn ensure_bot_in_channel(
&self,
bot_id: BotId,
@@ -363,6 +397,8 @@ pub trait BotService: Send + Sync + 'static {
/// Authorize an autonomous bot's channel messages using its active channel
/// membership alone. The receipt names no acting user and reaches no other entity.
+ /// A direct agent conversation authorizes none, and is refused as a
+ /// channel the bot is not in.
fn channel_message_access(
&self,
bot_id: BotId,
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index aa38723158..f1091a3b12 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -1,5 +1,7 @@
//! Bot service implementation.
+mod agent_dm;
+
use super::{
events::{BotCreatedMetadata, BotDeletedMetadata, BotMacroEvent, BotUpdatedMetadata},
models::{
@@ -928,9 +930,11 @@ where
}
async fn ensure_bot_in_channel(&self, bot_id: BotId, channel_id: Uuid) -> Result<(), BotError> {
+ // A direct agent conversation is answered the same as a channel the
+ // bot is not in, so the answer does not tell which channels are one.
if self
.repo
- .bot_active_in_channel(channel_id, bot_id)
+ .bot_may_post_in_channel(channel_id, bot_id)
.await
.map_err(|err| BotError::Repo(err.into()))?
{
diff --git a/crates/bots/src/domain/service/agent_dm.rs b/crates/bots/src/domain/service/agent_dm.rs
new file mode 100644
index 0000000000..577687e258
--- /dev/null
+++ b/crates/bots/src/domain/service/agent_dm.rs
@@ -0,0 +1,34 @@
+//! Persona eligibility for private user-agent conversations.
+
+use super::*;
+use crate::domain::ports::AgentDmEligibility;
+
+impl<R: BotRepo, B: MacroEventBroker, C: McpAppCatalog> AgentDmEligibility
+ for BotServiceImpl<R, B, C>
+{
+ async fn authorize_agent_dm(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<(), BotError> {
+ if let Some(bot) = bot_id::system_bot(bot_id) {
+ return if bot.has_agent {
+ Ok(())
+ } else {
+ Err(BotError::Unauthorized)
+ };
+ }
+ let bot = self.ensure_manageable(caller, bot_id).await?;
+ if !bot.has_agent
+ || self
+ .repo
+ .get_agent(bot_id)
+ .await
+ .map_err(|error| BotError::Repo(error.into()))?
+ .is_none()
+ {
+ return Err(BotError::Unauthorized);
+ }
+ Ok(())
+ }
+}
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index 435695de35..857bcd672c 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -529,6 +529,8 @@ impl BotRepo for PgBotsRepo {
.context("failed to clear the agent's previous MCP servers")?;
insert_mcp_servers(&mut tx, bot_id, req.mcp.servers()).await?;
+ // A direct conversation the persona is in belongs to the person it
+ // is with, not to the persona's channel selection.
let bot_principal = principal_id(bot_id);
sqlx::query!(
r#"
@@ -536,6 +538,12 @@ impl BotRepo for PgBotsRepo {
SET left_at = now()
WHERE user_id = $1
AND left_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = comms_channel_participants.channel_id
+ AND ca.kind = 'direct'
+ )
"#,
&bot_principal,
)
@@ -613,6 +621,12 @@ impl BotRepo for PgBotsRepo {
FROM comms_channel_participants p
WHERE p.user_id = 'bot|' || b.id::text
AND p.left_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = p.channel_id
+ AND ca.kind = 'direct'
+ )
ORDER BY p.channel_id
) AS "channel_ids!",
a.mcp_scope,
@@ -648,6 +662,14 @@ impl BotRepo for PgBotsRepo {
AND user_p.left_at IS NULL
WHERE bot_p.user_id = 'bot|' || b.id::text
AND bot_p.left_at IS NULL
+ -- A conversation with the persona shares nothing:
+ -- only the people it already serves have one.
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = bot_p.channel_id
+ AND ca.kind = 'direct'
+ )
)
)
)
@@ -674,6 +696,12 @@ impl BotRepo for PgBotsRepo {
WHERE user_id = $1
AND channel_id = ANY($2::uuid[])
AND left_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = comms_channel_participants.channel_id
+ AND ca.kind = 'direct'
+ )
"#,
caller.as_ref(),
channel_ids,
@@ -1036,6 +1064,12 @@ impl BotRepo for PgBotsRepo {
FROM comms_channel_participants p
WHERE p.user_id = 'bot|' || b.id::text
AND p.left_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = p.channel_id
+ AND ca.kind = 'direct'
+ )
ORDER BY p.channel_id
) AS "channel_ids!",
a.mcp_scope,
@@ -1144,6 +1178,40 @@ impl BotRepo for PgBotsRepo {
Ok(is_active)
}
+ async fn bot_may_post_in_channel(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<bool, Self::Err> {
+ let may_post = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ AND user_id = $2
+ AND left_at IS NULL
+ -- Its owner or any member of its team holds a persona's
+ -- tokens, not just the person a direct conversation is
+ -- with, so the persona posts into one only as their agent.
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = $1
+ AND ca.kind = 'direct'
+ )
+ ) AS "may_post!"
+ "#,
+ channel_id,
+ principal_id(bot_id),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check whether a bot may post in a channel")?;
+
+ Ok(may_post)
+ }
+
async fn user_shares_channel_with_bot(
&self,
caller: MacroUserIdStr<'static>,
@@ -1160,6 +1228,14 @@ impl BotRepo for PgBotsRepo {
AND user_p.left_at IS NULL
WHERE bot_p.user_id = $1
AND bot_p.left_at IS NULL
+ -- Only the persona's owner or team has a conversation with
+ -- it, so one never makes it available to anyone.
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = bot_p.channel_id
+ AND ca.kind = 'direct'
+ )
) AS "shares!"
"#,
principal_id(bot_id),
@@ -1330,6 +1406,12 @@ impl BotRepo for PgBotsRepo {
WHERE channel_id = $1
AND user_id = $2
AND left_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = $1
+ AND ca.kind = 'direct'
+ )
"#,
channel_id,
principal_id(bot_id),
@@ -1353,6 +1435,12 @@ impl BotRepo for PgBotsRepo {
JOIN comms_channels c ON c.id = cp.channel_id
WHERE cp.user_id = $1
AND cp.left_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = cp.channel_id
+ AND ca.kind = 'direct'
+ )
ORDER BY cp.joined_at ASC, c.id ASC
"#,
principal_id(bot_id),
@@ -1518,6 +1606,15 @@ impl BotRepo for PgBotsRepo {
AND cp.left_at IS NULL
WHERE bt.token_hash = $2
AND b.deleted_at IS NULL
+ -- Its owner or any member of its team can mint a persona's
+ -- token, not just the person a direct conversation is with, so
+ -- no token posts into one.
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = $1
+ AND ca.kind = 'direct'
+ )
"#,
channel_id,
&token_hash[..],
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index c302cad058..a0257d454e 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -18,6 +18,8 @@ use serde_json::{Value, json};
use sqlx::PgPool;
use std::sync::{Arc, Mutex};
+mod agent_dm;
+
const USER_OWNER: &str = "macro|[email protected]";
const USER_OTHER: &str = "macro|[email protected]";
const TEAM_MEMBER: &str = "macro|[email protected]";
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests/agent_dm.rs b/crates/bots/src/outbound/pg_bots_repo/tests/agent_dm.rs
new file mode 100644
index 0000000000..e62e7eaaa7
--- /dev/null
+++ b/crates/bots/src/outbound/pg_bots_repo/tests/agent_dm.rs
@@ -0,0 +1,383 @@
+use super::*;
+use crate::domain::ports::AgentDmEligibility;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn personal_personas_are_private_and_webhook_bots_are_not_personas(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let agent = service
+ .create_agent(
+ user_id(USER_OWNER),
+ create_agent_req("dm-private", AgentChannelScope::All),
+ )
+ .await?;
+ service
+ .authorize_agent_dm(user_id(USER_OWNER), agent.bot.id)
+ .await?;
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(USER_OTHER), agent.bot.id)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ let webhook = service
+ .create_bot(user_id(USER_OWNER), create_req("dm-webhook"))
+ .await?;
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(USER_OWNER), webhook.id)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ service
+ .delete_bot(user_id(USER_OWNER), agent.bot.id)
+ .await?;
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(USER_OWNER), agent.bot.id)
+ .await,
+ Err(BotError::NotFound(_))
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_members_can_dm_and_revocation_takes_effect_immediately(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = macro_uuid::generate_uuid_v7();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ let service = service(&pool);
+ let mut request = create_agent_req("dm-team", AgentChannelScope::All);
+ request.team_id = Some(team_id);
+ let agent = service.create_agent(user_id(TEAM_ADMIN), request).await?;
+ service
+ .authorize_agent_dm(user_id(TEAM_MEMBER), agent.bot.id)
+ .await?;
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(TEAM_OTHER), agent.bot.id)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ sqlx::query!(
+ "DELETE FROM team_user WHERE user_id = $1 AND team_id = $2",
+ TEAM_MEMBER,
+ team_id
+ )
+ .execute(&pool)
+ .await?;
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(TEAM_MEMBER), agent.bot.id)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn only_runnable_system_personas_are_available(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+ service
+ .authorize_agent_dm(user_id(USER_OWNER), bot_id::MACRO_NEW_BOT_ID)
+ .await?;
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(USER_OWNER), bot_id::MACRO_SYSTEM_BOT_ID)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ assert!(matches!(
+ service
+ .authorize_agent_dm(user_id(USER_OWNER), bot_id::MACRO_AI_BOT_ID)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ Ok(())
+}
+
+/// A direct agent conversation between `owner` and `bot_id`, holding just the
+/// two of them as opening one does.
+pub(super) async fn insert_direct_conversation(
+ pool: &PgPool,
+ channel_id: Uuid,
+ owner: &str,
+ bot_id: BotId,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ channel_id,
+ owner,
+ )
+ .execute(pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO comms_channel_agents (channel_id, bot_id, kind, user_id) VALUES ($1, $2, 'direct', $3)",
+ channel_id,
+ bot_id.as_uuid(),
+ owner,
+ )
+ .execute(pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'owner'), ($1, $3, 'member')",
+ channel_id,
+ owner,
+ principal_id(bot_id),
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// A team persona's tokens are minted by any member of its team, so none of
+/// them may post into the conversation one member has with the persona.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn persona_tokens_cannot_post_into_a_direct_conversation(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = macro_uuid::generate_uuid_v7();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ let service = service(&pool);
+ let mut request = create_agent_req("dm-token", AgentChannelScope::All);
+ request.team_id = Some(team_id);
+ let agent = service.create_agent(user_id(TEAM_ADMIN), request).await?;
+ let shared_channel_id = Uuid::new_v4();
+ insert_channel(&pool, shared_channel_id).await?;
+ service
+ .add_bot_to_channel(
+ channel_member_receipt(TEAM_MEMBER, shared_channel_id),
+ agent.bot.id,
+ )
+ .await?;
+ let conversation_id = Uuid::new_v4();
+ insert_direct_conversation(&pool, conversation_id, TEAM_ADMIN, agent.bot.id).await?;
+ let token = service
+ .create_token(
+ user_id(TEAM_MEMBER),
+ agent.bot.id,
+ CreateBotTokenRequest {
+ label: None,
+ expires_at: None,
+ },
+ )
+ .await?;
+
+ service
+ .authenticate_channel_token(shared_channel_id, &token.bearer_token)
+ .await?;
+ assert!(matches!(
+ service
+ .authenticate_channel_token(conversation_id, &token.bearer_token)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ Ok(())
+}
+
+/// The current webhook header authenticates a persona by a token of its own
+/// and leaves the channel to the persona's membership, which a direct
+/// conversation does not lend it: the webhook refuses the conversation as it
+/// refuses a channel the persona is not in.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn persona_bot_tokens_cannot_post_into_a_direct_conversation(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = macro_uuid::generate_uuid_v7();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ let service = service(&pool);
+ let mut request = create_agent_req("dm-bot-token", AgentChannelScope::All);
+ request.team_id = Some(team_id);
+ let agent = service.create_agent(user_id(TEAM_ADMIN), request).await?;
+ let shared_channel_id = Uuid::new_v4();
+ insert_channel(&pool, shared_channel_id).await?;
+ service
+ .add_bot_to_channel(
+ channel_member_receipt(TEAM_MEMBER, shared_channel_id),
+ agent.bot.id,
+ )
+ .await?;
+ let conversation_id = Uuid::new_v4();
+ insert_direct_conversation(&pool, conversation_id, TEAM_ADMIN, agent.bot.id).await?;
+ let token = service
+ .create_token(
+ user_id(TEAM_MEMBER),
+ agent.bot.id,
+ CreateBotTokenRequest {
+ label: None,
+ expires_at: None,
+ },
+ )
+ .await?;
+ let bot = service.authenticate_token(&token.bearer_token).await?;
+
+ service
+ .channel_message_access(bot.bot_id, shared_channel_id)
+ .await?;
+ assert!(matches!(
+ service
+ .channel_message_access(bot.bot_id, conversation_id)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ // A mention in one of the conversation's threads still finds the persona.
+ assert!(
+ PgBotsRepo::new(pool.clone())
+ .bot_active_in_channel(conversation_id, agent.bot.id)
+ .await?
+ );
+ Ok(())
+}
+
+/// A persona's channels are the ones it was put in. The conversations people
+/// have with it are theirs: editing the persona neither lists them, checks
+/// them against the editor's memberships, nor takes the persona out of them.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn editing_a_team_persona_leaves_its_direct_conversations_alone(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = macro_uuid::generate_uuid_v7();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ let service = service(&pool);
+ let mut request = create_agent_req("dm-edit", AgentChannelScope::All);
+ request.team_id = Some(team_id);
+ let agent = service.create_agent(user_id(TEAM_ADMIN), request).await?;
+ let conversation_id = Uuid::new_v4();
+ insert_direct_conversation(&pool, conversation_id, TEAM_MEMBER, agent.bot.id).await?;
+
+ // A patch that names no channels keeps an everywhere persona valid.
+ let patched = service
+ .patch_agent(
+ user_id(TEAM_ADMIN),
+ agent.bot.id,
+ PatchAgentRequest {
+ instructions: Some("Answer briefly.".to_string()),
+ ..PatchAgentRequest::default()
+ },
+ )
+ .await?;
+ assert!(patched.channel_ids.is_empty());
+
+ // Narrowing it to the editor's channel needs nothing of the teammate's
+ // conversation, and does not end it.
+ let channel_id = Uuid::new_v4();
+ insert_channel_member(&pool, channel_id, TEAM_ADMIN).await?;
+ let mut update = update_agent_req("dm-edit", AgentChannelScope::Selected);
+ update.team_id = Some(team_id);
+ update.channel_ids = vec![channel_id];
+ let updated = service
+ .update_agent(user_id(TEAM_ADMIN), agent.bot.id, update)
+ .await?;
+ assert_eq!(updated.channel_ids, vec![channel_id]);
+ let listed = service.list_agents(user_id(TEAM_ADMIN)).await?;
+ assert_eq!(
+ listed
+ .iter()
+ .find(|listed| listed.bot.id == agent.bot.id)
+ .map(|listed| listed.channel_ids.clone()),
+ Some(vec![channel_id])
+ );
+ assert_eq!(
+ active_channel_participant_count(&pool, conversation_id, agent.bot.id).await?,
+ 1
+ );
+
+ // Nor is the conversation one of its channels, to list a webhook for or
+ // to remove it from.
+ let channels = service
+ .list_bot_channels(
+ BotChannelListCaller::User(user_id(TEAM_ADMIN)),
+ agent.bot.id,
+ )
+ .await?;
+ assert_eq!(
+ channels
+ .iter()
+ .map(|channel| channel.channel_id)
+ .collect::<Vec<_>>(),
+ vec![channel_id]
+ );
+ assert!(matches!(
+ service
+ .remove_bot_from_channel(user_id(TEAM_ADMIN), conversation_id, agent.bot.id)
+ .await,
+ Err(BotError::NotFound(_))
+ ));
+ assert_eq!(
+ active_channel_participant_count(&pool, conversation_id, agent.bot.id).await?,
+ 1
+ );
+
+ // Or one to select, even by the person it is with.
+ let mut select_conversation = update_agent_req("dm-edit", AgentChannelScope::Selected);
+ select_conversation.team_id = Some(team_id);
+ select_conversation.channel_ids = vec![conversation_id];
+ assert!(matches!(
+ service
+ .update_agent(user_id(TEAM_MEMBER), agent.bot.id, select_conversation)
+ .await,
+ Err(BotError::Unauthorized)
+ ));
+ Ok(())
+}
+
+/// A conversation with a persona is not a channel shared with it: only the
+/// people the persona already serves have one, so once someone leaves its
+/// team, their conversation keeps nothing of a selected-channel persona.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_direct_conversation_does_not_share_a_selected_persona(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = macro_uuid::generate_uuid_v7();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ let channel_id = Uuid::new_v4();
+ insert_channel_member(&pool, channel_id, TEAM_ADMIN).await?;
+ let service = service(&pool);
+ let mut request = create_agent_req("dm-selected", AgentChannelScope::Selected);
+ request.team_id = Some(team_id);
+ request.channel_ids = vec![channel_id];
+ let agent = service.create_agent(user_id(TEAM_ADMIN), request).await?;
+ let conversation_id = Uuid::new_v4();
+ insert_direct_conversation(&pool, conversation_id, TEAM_MEMBER, agent.bot.id).await?;
+ sqlx::query!(
+ "DELETE FROM team_user WHERE user_id = $1 AND team_id = $2",
+ TEAM_MEMBER,
+ team_id
+ )
+ .execute(&pool)
+ .await?;
+ let repo = PgBotsRepo::new(pool.clone());
+ let lists_persona =
+ |agents: Vec<Agent>| agents.iter().any(|listed| listed.bot.id == agent.bot.id);
+
+ assert!(
+ !repo
+ .user_shares_channel_with_bot(user_id(TEAM_MEMBER), agent.bot.id)
+ .await?
+ );
+ assert!(!lists_persona(
+ service.list_agents(user_id(TEAM_MEMBER)).await?
+ ));
+
+ // A channel they really share with it still makes it available.
+ sqlx::query!(
+ "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'member')",
+ channel_id,
+ TEAM_MEMBER,
+ )
+ .execute(&pool)
+ .await?;
+ assert!(
+ repo.user_shares_channel_with_bot(user_id(TEAM_MEMBER), agent.bot.id)
+ .await?
+ );
+ assert!(lists_persona(
+ service.list_agents(user_id(TEAM_MEMBER)).await?
+ ));
+ Ok(())
+}
diff --git a/crates/channels/src/domain/agent_dm.rs b/crates/channels/src/domain/agent_dm.rs
new file mode 100644
index 0000000000..855735f26a
--- /dev/null
+++ b/crates/channels/src/domain/agent_dm.rs
@@ -0,0 +1,168 @@
+//! Private, durable conversations between one user and one agent persona:
+//! the direct kind of [`ChannelAgent`](super::channel_agents::ChannelAgent).
+
+use std::sync::Arc;
+
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+use super::{
+ events::ChannelEvent,
+ models::{ChannelType, GetOrCreateAction, GetOrCreateChannelResponse, Sender},
+ ports::{ChannelEventDispatcher, ChannelMutationErr},
+};
+
+#[cfg(test)]
+mod test;
+
+/// The identity of a persona DM. The user alone owns the conversation.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct AgentDm {
+ /// Channel containing the conversation.
+ pub channel_id: Uuid,
+ /// User whose history, credentials, and permissions the conversation uses.
+ pub user_id: MacroUserIdStr<'static>,
+ /// Persona addressed by every user message in the channel.
+ pub bot_id: BotId,
+}
+
+/// Result of atomically ensuring the user's conversation with a persona.
+pub struct EnsuredAgentDm {
+ /// Durable conversation identity.
+ pub dm: AgentDm,
+ /// Whether this request created the channel.
+ pub created: bool,
+}
+
+/// Historical persona identity displayed beside a private conversation.
+#[derive(Debug, Clone, serde::Serialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+pub struct AgentDmProfile {
+ /// Persona id without the bot principal prefix.
+ #[cfg_attr(feature = "inbound", schema(value_type = String))]
+ pub bot_id: BotId,
+ /// Persona display name.
+ pub name: String,
+ /// Persona avatar, when supplied.
+ pub avatar_url: Option<String>,
+}
+
+/// Batch presentation facts supplied by the channel and persona owners.
+#[async_trait::async_trait]
+pub trait AgentDmProfiles: Send + Sync + 'static {
+ /// Resolve profiles only for the caller's DMs among these channels.
+ async fn for_channels(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ channel_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, AgentDmProfile>, rootcause::Report>;
+}
+
+/// Channel-owned persistence for agent DM identities and membership.
+pub trait AgentDmRepo: Send + Sync + 'static {
+ /// List the caller's durable bindings, including retained history.
+ fn for_user(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<AgentDm>, ChannelMutationErr>> + Send;
+ /// Create the channel and both memberships atomically, or restore the
+ /// existing pair. Concurrent requests must return the same channel.
+ fn ensure(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<EnsuredAgentDm, ChannelMutationErr>> + Send;
+}
+
+/// Persona-domain authorization, independent of channel-placement settings.
+pub trait AgentDmAuthorizer: Send + Sync + 'static {
+ /// Require a runnable persona owned by the user or available to their team.
+ /// Existing channel membership alone does not grant permission to start a DM.
+ fn authorize(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send;
+}
+
+/// Agent DM commands exposed to the channel application service.
+#[async_trait::async_trait]
+pub trait AgentDirectMessages: Send + Sync + 'static {
+ /// Open the caller's private conversation with an eligible persona.
+ async fn get_or_create(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr>;
+}
+
+/// Coordinates persona eligibility, atomic channel creation, and channel events.
+pub struct AgentDmService<R, A, E> {
+ repo: R,
+ authorizer: A,
+ events: E,
+}
+
+impl<R, A, E> AgentDmService<R, A, E> {
+ /// Compose channel persistence, persona authorization, and channel events.
+ pub fn new(repo: R, authorizer: A, events: E) -> Self {
+ Self {
+ repo,
+ authorizer,
+ events,
+ }
+ }
+}
+
+#[async_trait::async_trait]
+impl<R: AgentDmRepo, A: AgentDmAuthorizer, E: ChannelEventDispatcher> AgentDirectMessages
+ for AgentDmService<R, A, E>
+{
+ async fn get_or_create(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
+ // Rechecked even for an existing DM: a former teammate may retain
+ // their history without retaining permission to run the persona.
+ self.authorizer.authorize(user_id.clone(), bot_id).await?;
+ let result = self.repo.ensure(user_id.clone(), bot_id).await?;
+ if result.created {
+ self.events.dispatch(ChannelEvent::ChannelCreated {
+ channel_id: result.dm.channel_id,
+ actor: Sender::new_from_user(user_id.clone()),
+ on_behalf_of: None,
+ channel_type: ChannelType::DirectMessage,
+ channel_name: None,
+ // Bots are participants, but never human notification recipients.
+ participant_user_ids: vec![user_id],
+ });
+ }
+ Ok(GetOrCreateChannelResponse {
+ channel_id: result.dm.channel_id.to_string(),
+ action: if result.created {
+ GetOrCreateAction::Create
+ } else {
+ GetOrCreateAction::Get
+ },
+ })
+ }
+}
+
+impl<R: AgentDmRepo> AgentDmRepo for Arc<R> {
+ async fn for_user(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<AgentDm>, ChannelMutationErr> {
+ (**self).for_user(user_id).await
+ }
+ async fn ensure(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<EnsuredAgentDm, ChannelMutationErr> {
+ (**self).ensure(user_id, bot_id).await
+ }
+}
diff --git a/crates/channels/src/domain/agent_dm/test.rs b/crates/channels/src/domain/agent_dm/test.rs
new file mode 100644
index 0000000000..eb9f2ded28
--- /dev/null
+++ b/crates/channels/src/domain/agent_dm/test.rs
@@ -0,0 +1,123 @@
+use super::*;
+use std::sync::{
+ Mutex,
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+};
+
+#[derive(Clone, Default)]
+struct Eligibility(Arc<AtomicBool>);
+
+impl AgentDmAuthorizer for Eligibility {
+ async fn authorize(
+ &self,
+ _: MacroUserIdStr<'static>,
+ _: BotId,
+ ) -> Result<(), ChannelMutationErr> {
+ if self.0.load(Ordering::SeqCst) {
+ Ok(())
+ } else {
+ Err(ChannelMutationErr::Forbidden(
+ "agent unavailable".to_owned(),
+ ))
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+struct Repo(Arc<AtomicUsize>);
+
+impl AgentDmRepo for Repo {
+ async fn for_user(
+ &self,
+ _: MacroUserIdStr<'static>,
+ ) -> Result<Vec<AgentDm>, ChannelMutationErr> {
+ unreachable!("creation does not enumerate conversations")
+ }
+ async fn ensure(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<EnsuredAgentDm, ChannelMutationErr> {
+ Ok(EnsuredAgentDm {
+ dm: AgentDm {
+ channel_id: Uuid::from_u128(42),
+ user_id,
+ bot_id,
+ },
+ created: self.0.fetch_add(1, Ordering::SeqCst) == 0,
+ })
+ }
+}
+
+#[derive(Clone, Default)]
+struct Events(Arc<Mutex<Vec<ChannelEvent>>>);
+
+impl ChannelEventDispatcher for Events {
+ fn dispatch(&self, event: ChannelEvent) {
+ self.0.lock().unwrap().push(event);
+ }
+}
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap()
+}
+
+#[tokio::test]
+async fn reopening_reuses_the_dm_and_only_creation_notifies_the_human() {
+ let eligibility = Eligibility::default();
+ eligibility.0.store(true, Ordering::SeqCst);
+ let events = Events::default();
+ let service = AgentDmService::new(Repo::default(), eligibility, events.clone());
+ let first = service
+ .get_or_create(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap();
+ let second = service
+ .get_or_create(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap();
+ assert_eq!(first.channel_id, second.channel_id);
+ assert_eq!(first.action, GetOrCreateAction::Create);
+ assert_eq!(second.action, GetOrCreateAction::Get);
+ let events = events.0.lock().unwrap();
+ assert!(
+ matches!(events.as_slice(), [ChannelEvent::ChannelCreated { participant_user_ids, channel_type: ChannelType::DirectMessage, .. }] if participant_user_ids == &vec![user()])
+ );
+}
+
+#[tokio::test]
+async fn revoked_persona_access_cannot_restore_or_create_membership() {
+ let eligibility = Eligibility::default();
+ eligibility.0.store(true, Ordering::SeqCst);
+ let repo = Repo::default();
+ let events = Events::default();
+ let service = AgentDmService::new(repo.clone(), eligibility.clone(), events.clone());
+ service
+ .get_or_create(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap();
+ eligibility.0.store(false, Ordering::SeqCst);
+ assert!(matches!(
+ service
+ .get_or_create(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await,
+ Err(ChannelMutationErr::Forbidden(_))
+ ));
+ assert_eq!(repo.0.load(Ordering::SeqCst), 1);
+ assert_eq!(events.0.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn unavailable_persona_does_not_create_a_channel() {
+ let repo = Repo::default();
+ let events = Events::default();
+ let service = AgentDmService::new(repo.clone(), Eligibility::default(), events.clone());
+ assert!(
+ service
+ .get_or_create(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .is_err()
+ );
+ assert_eq!(repo.0.load(Ordering::SeqCst), 0);
+ assert!(events.0.lock().unwrap().is_empty());
+}
diff --git a/crates/channels/src/domain/channel_agents.rs b/crates/channels/src/domain/channel_agents.rs
new file mode 100644
index 0000000000..59599586b8
--- /dev/null
+++ b/crates/channels/src/domain/channel_agents.rs
@@ -0,0 +1,66 @@
+//! Agent personas that converse in a channel, whatever kind of channel it is.
+
+use std::sync::Arc;
+
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use super::ports::ChannelMutationErr;
+
+/// An agent persona that converses in a channel: messages in the channel are
+/// turns for it, with no mention needed.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ChannelAgent {
+ /// Channel the conversation happens in.
+ pub channel_id: Uuid,
+ /// Persona that answers.
+ pub bot_id: BotId,
+ /// Who the persona converses with there.
+ pub kind: ChannelAgentKind,
+}
+
+/// Who an agent converses with in its channel.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ChannelAgentKind {
+ /// A private channel between one user and the persona. Only that user
+ /// prompts it, and it acts with their access.
+ Direct {
+ /// The user who owns the conversation.
+ user_id: MacroUserIdStr<'static>,
+ },
+ /// A member of a shared channel. Nothing adds these yet, and nothing
+ /// routes messages to them until a flow does.
+ Member,
+}
+
+/// Channel-owned facts about the agents conversing in a channel. A lookup is
+/// not authorization.
+pub trait ChannelAgentRepo: Send + Sync + 'static {
+ /// Every agent conversing in a channel.
+ fn agents_in(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ChannelAgent>, ChannelMutationErr>> + Send;
+
+ /// One persona's place in a channel, if it converses there.
+ fn find(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<Option<ChannelAgent>, ChannelMutationErr>> + Send;
+}
+
+impl<R: ChannelAgentRepo> ChannelAgentRepo for Arc<R> {
+ async fn agents_in(&self, channel_id: Uuid) -> Result<Vec<ChannelAgent>, ChannelMutationErr> {
+ (**self).agents_in(channel_id).await
+ }
+
+ async fn find(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<Option<ChannelAgent>, ChannelMutationErr> {
+ (**self).find(channel_id, bot_id).await
+ }
+}
diff --git a/crates/channels/src/domain/list_service.rs b/crates/channels/src/domain/list_service.rs
index 3778bdeb5b..a5bbe04f57 100644
--- a/crates/channels/src/domain/list_service.rs
+++ b/crates/channels/src/domain/list_service.rs
@@ -39,6 +39,7 @@ pub struct ChannelListServiceImpl<Channels, Users, Frec> {
channels: Channels,
users: Users,
frecency: Frec,
+ agent_dms: Option<std::sync::Arc<dyn super::agent_dm::AgentDmProfiles>>,
}
impl<Channels, Users, Frec> ChannelListServiceImpl<Channels, Users, Frec>
@@ -53,8 +54,18 @@ where
channels,
users,
frecency,
+ agent_dms: None,
}
}
+
+ /// Supply batched persona presentation for private agent DMs.
+ pub fn with_agent_dm_profiles(
+ mut self,
+ profiles: std::sync::Arc<dyn super::agent_dm::AgentDmProfiles>,
+ ) -> Self {
+ self.agent_dms = Some(profiles);
+ self
+ }
}
impl<Channels, Users, Frec> ChannelListService for ChannelListServiceImpl<Channels, Users, Frec>
@@ -83,6 +94,14 @@ where
.collect();
let channel_ids: Vec<_> = channels.iter().map(|chan| chan.channel.id).collect();
+ let mut agent_profiles = match &self.agent_dms {
+ Some(profiles) => {
+ profiles
+ .for_channels(user.clone().into_owned(), &channel_ids)
+ .await?
+ }
+ None => HashMap::new(),
+ };
let participant_ids = channels
.iter()
@@ -145,6 +164,7 @@ where
Ok(channels
.into_iter()
.map(|mut channel| {
+ let agent_dm = agent_profiles.remove(&channel.channel.id);
let resolved_name = resolve_channel_name(
channel.channel.channel_type,
channel.channel.name.as_deref(),
@@ -153,12 +173,18 @@ where
&channel.participants,
&name_lookup,
);
- channel.channel.name = Some(resolved_name);
+ channel.channel.name = Some(
+ agent_dm
+ .as_ref()
+ .map(|profile| profile.name.clone())
+ .unwrap_or(resolved_name),
+ );
let activity = activity_lookup.remove(&channel.channel.id);
let viewed_at = activity.as_ref().and_then(|a| a.viewed_at);
let interacted_at = activity.as_ref().and_then(|a| a.interacted_at);
let channel_id = channel.channel.id;
ChannelWithLatest {
+ agent_dm,
channel,
latest_message: latest_messages.remove(&channel_id).unwrap_or_default(),
viewed_at,
diff --git a/crates/channels/src/domain/message_delivery/test.rs b/crates/channels/src/domain/message_delivery/test.rs
index 3c8613ecab..e8a4b7309c 100644
--- a/crates/channels/src/domain/message_delivery/test.rs
+++ b/crates/channels/src/domain/message_delivery/test.rs
@@ -250,6 +250,7 @@ async fn plain_edits_deletions_reactions_and_typing_only_send_the_common_payload
MessageChange::Typing {
thread_id: Some(Uuid::from_u128(9)),
active: false,
+ agent: None,
},
] {
// The plain edit still records sharing, whose failure is reported.
diff --git a/crates/channels/src/domain/mod.rs b/crates/channels/src/domain/mod.rs
index 0026edab16..78e691115c 100644
--- a/crates/channels/src/domain/mod.rs
+++ b/crates/channels/src/domain/mod.rs
@@ -1,7 +1,12 @@
/// Event-to-activity mappings for this domain.
pub mod activity;
+#[cfg(feature = "ports")]
+pub mod agent_dm;
/// Kafka event models for the `macro.channels` topic.
pub mod broker_events;
+/// Agent personas that converse in a channel.
+#[cfg(feature = "ports")]
+pub mod channel_agents;
/// Direct-message identity and batch commands.
pub mod dm;
#[cfg(feature = "entity_mutation")]
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index 9579286790..c96afc7097 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -609,9 +609,9 @@ pub struct CreateChannelResponse {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct GetOrCreateDmRequest {
- /// Recipient user id.
+ /// Recipient user id (`macro|...`) or agent persona id (`bot|...`).
#[cfg_attr(feature = "inbound", schema(value_type = String))]
- pub recipient_id: MacroUserIdStr<'static>,
+ pub recipient_id: Sender,
}
/// Request to get or create a private channel.
@@ -1163,6 +1163,8 @@ pub struct LatestMessage {
#[cfg(feature = "list")]
#[derive(Debug, Clone)]
pub struct ChannelWithLatest {
+ /// Persona identity for the viewer's private agent conversation.
+ pub agent_dm: Option<super::agent_dm::AgentDmProfile>,
/// Channel plus participants.
pub channel: ChannelWithParticipants,
/// Latest message data.
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index 9e9e1a1c95..4f8b5051af 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -218,6 +218,13 @@ pub trait ChannelRepo: Send + Sync + 'static {
channel_id: Uuid,
) -> impl Future<Output = Result<ChannelInfo, Self::Err>> + Send;
+ /// Whether a channel is a direct agent conversation: one user's private
+ /// channel with an agent persona.
+ fn is_direct_agent_conversation(
+ &self,
+ channel_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
/// Atomically assign a channel join code if absent and return the persisted code.
fn get_or_create_channel_join_code(
&self,
diff --git a/crates/channels/src/domain/reference_sharing.rs b/crates/channels/src/domain/reference_sharing.rs
index 82e280a6c0..62e4723e0b 100644
--- a/crates/channels/src/domain/reference_sharing.rs
+++ b/crates/channels/src/domain/reference_sharing.rs
@@ -5,7 +5,9 @@ use entity_access::domain::models::AccessLevel;
use model_file_type::FileType;
/// Only owners may share session references, and automatic sharing grants view
-/// access. Sending a reference never grants control of an agent session.
+/// access. Sending a reference never grants control of an agent session, and a
+/// direct agent conversation's sessions, private to their owner, are never
+/// shared this way: the share adapter skips them before asking.
///
/// A calendar event is shareable only by someone holding it on their own
/// calendar: its owner or a linked account. A member who sees the event only
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index ccbe7cdec0..13540458a6 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -22,6 +22,7 @@ use entity_access::domain::models::{
};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, PaginateOn, Query};
+use std::sync::Arc;
use uuid::Uuid;
mod import;
@@ -41,6 +42,7 @@ pub struct ChannelServiceImpl<
events: E,
reference_share_permissions: P,
picture_files: F,
+ agent_direct_messages: Option<Arc<dyn super::agent_dm::AgentDirectMessages>>,
}
/// Fail-closed picture metadata source for contexts that do not wire uploads.
@@ -96,6 +98,7 @@ where
events: NoopChannelEventDispatcher,
reference_share_permissions: NoopChannelReferenceSharePermissions,
picture_files: UnavailableChannelPictureFiles,
+ agent_direct_messages: None,
}
}
}
@@ -108,11 +111,21 @@ impl<R, E, P> ChannelServiceImpl<R, E, P> {
events,
reference_share_permissions,
picture_files: UnavailableChannelPictureFiles,
+ agent_direct_messages: None,
}
}
}
impl<R, E, P, F> ChannelServiceImpl<R, E, P, F> {
+ /// Enable private conversations with authorized agent personas.
+ pub fn with_agent_direct_messages(
+ mut self,
+ service: Arc<dyn super::agent_dm::AgentDirectMessages>,
+ ) -> Self {
+ self.agent_direct_messages = Some(service);
+ self
+ }
+
/// Wire the static-file metadata source used to authorize channel pictures.
pub fn with_picture_files<F2: ChannelPictureFiles>(
self,
@@ -123,6 +136,7 @@ impl<R, E, P, F> ChannelServiceImpl<R, E, P, F> {
events: self.events,
reference_share_permissions: self.reference_share_permissions,
picture_files,
+ agent_direct_messages: self.agent_direct_messages,
}
}
}
@@ -279,6 +293,15 @@ where
GetOrCreateDmRequest { recipient_id }: GetOrCreateDmRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
let actor = require_user_actor(&actor)?;
+ if let Some(bot) = recipient_id.as_bot() {
+ let service = self.agent_direct_messages.as_ref().ok_or_else(|| {
+ ChannelMutationErr::BadRequest("Agent direct messages are unavailable".to_owned())
+ })?;
+ return service.get_or_create(actor, bot.bot_id()).await;
+ }
+ let recipient_id = recipient_id.into_user().ok_or_else(|| {
+ ChannelMutationErr::BadRequest("Invalid direct message recipient".to_owned())
+ })?;
let pair = DmPair::new(actor.clone(), recipient_id).map_err(|_| {
ChannelMutationErr::BadRequest(
"recipient_id cannot be the same as the user_id".to_string(),
@@ -371,6 +394,19 @@ where
let converting_to_team =
req.convert_to_team_channel == Some(true) && info.channel_type != ChannelType::Team;
+ // An agent DM is its owner's alone. A team channel is open to their
+ // team, and to the team scope of the personas their team owns.
+ if converting_to_team
+ && self
+ .repo
+ .is_direct_agent_conversation(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ {
+ return Err(ChannelMutationErr::BadRequest(
+ "an agent DM cannot become a team channel".to_string(),
+ ));
+ }
let converting_to_private =
req.convert_to_team_channel == Some(false) && info.channel_type == ChannelType::Team;
let team_id = if converting_to_team {
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 8a136f4dd5..95016929fd 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -41,6 +41,7 @@ struct FakeMutationRepoState {
channel_name: Option<String>,
channel_type: ChannelType,
channel_team_id: Option<Uuid>,
+ direct_agent: bool,
user_team_id: Option<Uuid>,
user_team_id_lookups: usize,
join_code: Option<Uuid>,
@@ -65,6 +66,7 @@ impl FakeMutationRepo {
channel_name: Some("Project".to_string()),
channel_type: ChannelType::Private,
channel_team_id: None,
+ direct_agent: false,
user_team_id: None,
user_team_id_lookups: 0,
join_code: None,
@@ -153,6 +155,10 @@ impl ChannelRepo for FakeMutationRepo {
})
}
+ async fn is_direct_agent_conversation(&self, _channel_id: Uuid) -> Result<bool, Self::Err> {
+ Ok(self.state.lock().unwrap().direct_agent)
+ }
+
async fn get_or_create_channel_join_code(&self, _channel_id: Uuid) -> Result<Uuid, Self::Err> {
let mut state = self.state.lock().unwrap();
let join_code = *state.join_code.get_or_insert_with(Uuid::new_v4);
@@ -914,7 +920,9 @@ async fn get_or_create_dm_rejects_self_pair() {
let error = service
.get_or_create_dm(
Sender::new_from_user(user.clone()),
- GetOrCreateDmRequest { recipient_id: user },
+ GetOrCreateDmRequest {
+ recipient_id: Sender::new_from_user(user),
+ },
)
.await
.unwrap_err();
@@ -951,7 +959,7 @@ async fn get_or_create_dm_returns_get_for_existing_pair() {
.get_or_create_dm(
Sender::new_from_user(actor),
GetOrCreateDmRequest {
- recipient_id: recipient,
+ recipient_id: Sender::new_from_user(recipient),
},
)
.await
@@ -1319,6 +1327,40 @@ async fn patch_team_channel_conversion_to_private_clears_team_settings() {
assert_eq!(state.channel_patches[0].0.auto_join_team, Some(false));
}
+#[tokio::test]
+async fn patch_channel_refuses_to_make_an_agent_dm_a_team_channel() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_type = ChannelType::DirectMessage;
+ state.direct_agent = true;
+ state.user_team_id = Some(Uuid::new_v4());
+ }
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let err = svc
+ .patch_channel(
+ patch_receipt("macro|[email protected]", channel_id, AccessRole::Owner),
+ PatchChannelRequest {
+ channel_name: None,
+ convert_to_team_channel: Some(true),
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, ChannelMutationErr::BadRequest(_)));
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.user_team_id_lookups, 0);
+ assert!(state.channel_patches.is_empty());
+}
+
#[tokio::test]
async fn patch_channel_conversion_requires_the_user_to_have_a_team() {
let channel_id = Uuid::new_v4();
diff --git a/crates/channels/src/inbound/list_router.rs b/crates/channels/src/inbound/list_router.rs
index a98df78859..c94452f780 100644
--- a/crates/channels/src/inbound/list_router.rs
+++ b/crates/channels/src/inbound/list_router.rs
@@ -254,6 +254,9 @@ impl ApiChannelListParticipant {
/// Channel list response item.
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct ApiChannelWithLatest {
+ /// Persona identity when this is the viewer's private agent DM.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub agent_dm: Option<crate::domain::agent_dm::AgentDmProfile>,
/// Channel id.
pub id: Uuid,
/// Channel name.
@@ -303,6 +306,7 @@ impl ApiChannelWithLatest {
let ch = ApiChannelListItem::new_from_domain(value.channel.channel);
let latest = ApiLatestMessage::new_from_domain(value.latest_message);
Self {
+ agent_dm: value.agent_dm,
id: ch.id,
name: ch.name,
channel_type: ch.channel_type,
diff --git a/crates/channels/src/inbound/list_router/test.rs b/crates/channels/src/inbound/list_router/test.rs
index b8b44d1330..755a123530 100644
--- a/crates/channels/src/inbound/list_router/test.rs
+++ b/crates/channels/src/inbound/list_router/test.rs
@@ -207,6 +207,7 @@ async fn standard_internal_credentials_pass_acting_user_to_channel_list_service(
fn list_channel(id: Uuid, updated_at_seconds: i64) -> ChannelWithLatest {
let timestamp = Utc.timestamp_opt(updated_at_seconds, 0).unwrap();
ChannelWithLatest {
+ agent_dm: None,
channel: ChannelWithParticipants {
channel: ChannelListItem {
id,
diff --git a/crates/channels/src/inbound/toolset/open_direct_message.rs b/crates/channels/src/inbound/toolset/open_direct_message.rs
index 7f2cc82955..b90a8ca93e 100644
--- a/crates/channels/src/inbound/toolset/open_direct_message.rs
+++ b/crates/channels/src/inbound/toolset/open_direct_message.rs
@@ -1,6 +1,6 @@
use super::{ChannelToolContext, channel_mutation_error, parse_participants};
use crate::domain::{
- models::{GetOrCreateAction, GetOrCreateDmRequest, GetOrCreatePrivateRequest},
+ models::{GetOrCreateAction, GetOrCreateDmRequest, GetOrCreatePrivateRequest, Sender},
ports::ChannelService,
};
use ai_toolset::{
@@ -80,7 +80,7 @@ where
.get_or_create_dm(
actor,
GetOrCreateDmRequest {
- recipient_id: recipient.clone(),
+ recipient_id: Sender::new_from_user(recipient.clone()),
},
)
.await
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index bd93f9ad83..0cff518c52 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -1678,7 +1678,10 @@ async fn open_direct_message_opens_a_one_to_one_dm_as_the_user() {
panic!("expected one dm, got {}", dms.len());
};
assert_eq!(actor.as_user(), Some(&user_id()));
- assert_eq!(request.recipient_id.as_ref(), "macro|[email protected]");
+ assert_eq!(
+ request.recipient_id.as_user().map(|id| id.as_ref()),
+ Some("macro|[email protected]"),
+ );
}
#[tokio::test]
diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
index 8e5eeaf4bf..c66f3c72c7 100644
--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
@@ -81,6 +81,14 @@ async fn share_referenced_item_with_channel(
item: &ReferencedShareItem,
sharer_access: Option<AccessLevel>,
) -> anyhow::Result<ReferenceShareOutcome> {
+ // A direct agent conversation's sessions are private to their owner, and
+ // their sharing settings refuse to share them; posting one's link
+ // elsewhere does not either.
+ if item.entity_type() == ReferencedShareItemType::AgentSession
+ && is_direct_conversation_session(db, item.entity_id()).await?
+ {
+ return Ok(ReferenceShareOutcome::NotPermitted);
+ }
let file_type = match item.entity_type() {
ReferencedShareItemType::Document => get_document_file_type(db, item.entity_id()).await?,
_ => None,
@@ -92,6 +100,25 @@ async fn share_referenced_item_with_channel(
Ok(ReferenceShareOutcome::Shared)
}
+async fn is_direct_conversation_session(db: &PgPool, session_id: &str) -> anyhow::Result<bool> {
+ let session_id = macro_uuid::string_to_uuid(session_id)?;
+ sqlx::query_scalar!(
+ r#"SELECT EXISTS (
+ SELECT 1
+ FROM agent_conversation_sessions session
+ JOIN comms_channel_agents agent
+ ON agent.channel_id = session.channel_id
+ AND agent.bot_id = session.bot_id
+ WHERE session.session_id = $1
+ AND agent.kind = 'direct'
+ ) AS "private!""#,
+ session_id,
+ )
+ .fetch_one(db)
+ .await
+ .context("failed to read whether a session belongs to a direct agent conversation")
+}
+
async fn get_document_file_type(
db: &PgPool,
document_id: &str,
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.rs
index 7c14a6d460..55d0a14a57 100644
--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
@@ -227,3 +227,70 @@ async fn form_references_grant_the_channel_view_and_keep_an_existing_grant(pool:
assert_eq!(levels, vec![existing.unwrap_or(AccessLevel::View)]);
}
}
+
+/// Explicit sharing refuses a direct agent conversation's sessions, which are
+/// private to their owner. Posting one's link in another channel must not
+/// share it either, while a session from anywhere else still is.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn direct_conversation_session_references_grant_nothing(pool: PgPool) {
+ const OWNER: &str = "macro|[email protected]";
+ let conversation_id = Uuid::now_v7();
+ let bot_id = Uuid::now_v7();
+ let private_session_id = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ conversation_id,
+ OWNER,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO comms_channel_agents (channel_id, bot_id, kind, user_id) VALUES ($1, $2, 'direct', $3)",
+ conversation_id,
+ bot_id,
+ OWNER,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO agent_conversation_sessions (session_id, channel_id, bot_id) VALUES ($1, $2, $3)",
+ private_session_id,
+ conversation_id,
+ bot_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let shared_session_id = Uuid::now_v7();
+ let channel_id = Uuid::now_v7();
+
+ for session_id in [private_session_id, shared_session_id] {
+ let item = ReferencedShareItem::new(
+ session_id.to_string(),
+ ReferencedShareItemType::AgentSession,
+ );
+ share_referenced_item_with_channel(&pool, channel_id, &item, Some(AccessLevel::Owner))
+ .await
+ .unwrap();
+ }
+
+ let granted = |session_id: Uuid| {
+ let pool = pool.clone();
+ async move {
+ 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'"#,
+ session_id,
+ channel_id.to_string(),
+ )
+ .fetch_optional(&pool)
+ .await
+ .unwrap()
+ }
+ };
+ assert_eq!(granted(private_session_id).await, None);
+ assert_eq!(granted(shared_session_id).await, Some(AccessLevel::View));
+}
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index 2977240275..9e9cc088b9 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -6,6 +6,9 @@ mod references;
#[cfg(test)]
mod tests;
+mod agent_dm;
+mod channel_agents;
+
#[cfg(feature = "attachment")]
use crate::domain::ports::ChannelAttachmentRepo;
#[cfg(feature = "list")]
@@ -1933,6 +1936,23 @@ impl ChannelRepo for PgChannelsRepo {
})
}
+ async fn is_direct_agent_conversation(&self, channel_id: Uuid) -> Result<bool, Self::Err> {
+ let direct = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents
+ WHERE channel_id = $1
+ AND kind = 'direct'
+ ) AS "direct!"
+ "#,
+ channel_id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(direct)
+ }
+
async fn get_or_create_channel_join_code(&self, channel_id: Uuid) -> Result<Uuid, Self::Err> {
let candidate_join_code = macro_uuid::generate_uuid_v7();
let join_code = sqlx::query_scalar!(
diff --git a/crates/channels/src/outbound/pg_channels_repo/agent_dm.rs b/crates/channels/src/outbound/pg_channels_repo/agent_dm.rs
new file mode 100644
index 0000000000..fda3f1579e
--- /dev/null
+++ b/crates/channels/src/outbound/pg_channels_repo/agent_dm.rs
@@ -0,0 +1,115 @@
+//! Atomic agent-DM identity and membership persistence, as direct
+//! `comms_channel_agents` rows.
+
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::domain::{
+ agent_dm::{AgentDm, AgentDmRepo, EnsuredAgentDm},
+ ports::ChannelMutationErr,
+};
+
+use super::{PgChannelsRepo, create_activity};
+
+#[cfg(test)]
+mod test;
+
+impl PgChannelsRepo {
+ async fn ensure_agent_dm(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> anyhow::Result<EnsuredAgentDm> {
+ let mut tx = self.pool.begin().await?;
+ // Serialize creation of this pair before creating a channel, so a
+ // losing request never leaves an orphan. The unique key is the durable
+ // invariant; the transaction-scoped lock also covers membership repair.
+ let pair_key = format!("agent-dm:{user_id}:{bot_id}");
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ pair_key,
+ )
+ .execute(&mut *tx)
+ .await?;
+ let existing = sqlx::query_scalar!(
+ "SELECT channel_id FROM comms_channel_agents WHERE kind = 'direct' AND user_id = $1 AND bot_id = $2",
+ user_id.as_ref(),
+ bot_id.as_uuid(),
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+ let channel_id = existing.unwrap_or_else(macro_uuid::generate_uuid_v7);
+ if existing.is_none() {
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id)
+ VALUES ($1, 'direct_message', $2)",
+ channel_id,
+ user_id.as_ref(),
+ )
+ .execute(&mut *tx)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO comms_channel_agents (channel_id, user_id, bot_id, kind)
+ VALUES ($1, $2, $3, 'direct')",
+ channel_id,
+ user_id.as_ref(),
+ bot_id.as_uuid(),
+ )
+ .execute(&mut *tx)
+ .await?;
+ create_activity(&mut *tx, channel_id, user_id.as_ref()).await?;
+ }
+ let bot_principal = bot_id.into_storage_id();
+ sqlx::query!(
+ "INSERT INTO comms_channel_participants (channel_id, user_id, role)
+ VALUES ($1, $2, 'owner'), ($1, $3, 'member')
+ ON CONFLICT (channel_id, user_id) DO UPDATE SET left_at = NULL",
+ channel_id,
+ user_id.as_ref(),
+ bot_principal.as_ref(),
+ )
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(EnsuredAgentDm {
+ dm: AgentDm {
+ channel_id,
+ user_id,
+ bot_id,
+ },
+ created: existing.is_none(),
+ })
+ }
+}
+
+impl AgentDmRepo for PgChannelsRepo {
+ async fn for_user(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<AgentDm>, ChannelMutationErr> {
+ let rows = sqlx::query!(
+ "SELECT channel_id, bot_id FROM comms_channel_agents WHERE kind = 'direct' AND user_id = $1",
+ user_id.as_ref()
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ Ok(rows
+ .into_iter()
+ .map(|row| AgentDm {
+ channel_id: row.channel_id,
+ bot_id: BotId::new_from_uuid(row.bot_id),
+ user_id: user_id.clone(),
+ })
+ .collect())
+ }
+ async fn ensure(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<EnsuredAgentDm, ChannelMutationErr> {
+ self.ensure_agent_dm(user_id, bot_id)
+ .await
+ .map_err(ChannelMutationErr::Repo)
+ }
+}
diff --git a/crates/channels/src/outbound/pg_channels_repo/agent_dm/test.rs b/crates/channels/src/outbound/pg_channels_repo/agent_dm/test.rs
new file mode 100644
index 0000000000..d7ee11988f
--- /dev/null
+++ b/crates/channels/src/outbound/pg_channels_repo/agent_dm/test.rs
@@ -0,0 +1,173 @@
+use super::*;
+use crate::domain::channel_agents::{ChannelAgent, ChannelAgentKind, ChannelAgentRepo};
+use crate::domain::ports::ChannelRepo;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn other_people_and_bots_cannot_be_added_to_a_persona_dm(pool: PgPool) {
+ let repo = PgChannelsRepo::new(pool.clone());
+ let dm = repo
+ .ensure(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .dm;
+ for principal in [
+ "macro|[email protected]".to_owned(),
+ bot_id::MACRO_CODER_BOT_ID.into_storage_id().to_string(),
+ ] {
+ let error = sqlx::query!(
+ "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'member')",
+ dm.channel_id, principal
+ ).execute(&pool).await.unwrap_err();
+ assert_eq!(
+ error.as_database_error().unwrap().code().as_deref(),
+ Some("23514")
+ );
+ }
+ assert_eq!(repo.for_user(user()).await.unwrap(), vec![dm]);
+ assert!(
+ repo.for_user(MacroUserIdStr::try_from_email("[email protected]").unwrap())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn concurrent_opens_create_one_channel_and_two_memberships(pool: PgPool) {
+ let repo = PgChannelsRepo::new(pool.clone());
+ let (left, right) = tokio::join!(
+ repo.ensure(user(), bot_id::MACRO_NEW_BOT_ID),
+ repo.ensure(user(), bot_id::MACRO_NEW_BOT_ID),
+ );
+ let left = left.unwrap();
+ let right = right.unwrap();
+ assert_eq!(left.dm, right.dm);
+ assert_ne!(left.created, right.created);
+ let participants = sqlx::query!(
+ "SELECT user_id, role::text AS \"role!\" FROM comms_channel_participants WHERE channel_id = $1 AND left_at IS NULL",
+ left.dm.channel_id,
+ ).fetch_all(&pool).await.unwrap();
+ assert_eq!(participants.len(), 2);
+ assert!(
+ participants
+ .iter()
+ .any(|p| p.user_id == user().as_ref() && p.role == "owner")
+ );
+ assert!(
+ participants
+ .iter()
+ .any(|p| p.user_id == bot_id::MACRO_NEW_BOT_ID.into_storage_id().as_ref())
+ );
+ let count = sqlx::query_scalar!("SELECT COUNT(*) FROM comms_channels")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ count,
+ Some(1),
+ "the losing request must not leave an orphan channel"
+ );
+ assert_eq!(
+ repo.find(left.dm.channel_id, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap(),
+ Some(ChannelAgent {
+ channel_id: left.dm.channel_id,
+ bot_id: bot_id::MACRO_NEW_BOT_ID,
+ kind: ChannelAgentKind::Direct { user_id: user() },
+ })
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn conversations_are_isolated_by_both_user_and_persona(pool: PgPool) {
+ let repo = PgChannelsRepo::new(pool);
+ let first = repo.ensure(user(), bot_id::MACRO_NEW_BOT_ID).await.unwrap();
+ let other_user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ let second = repo
+ .ensure(other_user, bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap();
+ let third = repo
+ .ensure(user(), bot_id::MACRO_CODER_BOT_ID)
+ .await
+ .unwrap();
+ assert_ne!(first.dm.channel_id, second.dm.channel_id);
+ assert_ne!(first.dm.channel_id, third.dm.channel_id);
+ assert_ne!(second.dm.channel_id, third.dm.channel_id);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn reopening_restores_membership_and_deletion_removes_the_pair(pool: PgPool) {
+ let repo = PgChannelsRepo::new(pool.clone());
+ let first = repo.ensure(user(), bot_id::MACRO_NEW_BOT_ID).await.unwrap();
+ sqlx::query!(
+ "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1",
+ first.dm.channel_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let reopened = repo.ensure(user(), bot_id::MACRO_NEW_BOT_ID).await.unwrap();
+ assert_eq!(reopened.dm, first.dm);
+ assert!(!reopened.created);
+ let members = sqlx::query_scalar!(
+ "SELECT COUNT(*) FROM comms_channel_participants WHERE channel_id = $1 AND left_at IS NULL",
+ first.dm.channel_id,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(members, Some(2));
+ // The existing human roster endpoint deliberately excludes bot principals.
+ assert_eq!(
+ repo.get_channel_participants(first.dm.channel_id)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ sqlx::query!(
+ "DELETE FROM comms_channels WHERE id = $1",
+ first.dm.channel_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ repo.agents_in(first.dm.channel_id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ let recreated = repo.ensure(user(), bot_id::MACRO_NEW_BOT_ID).await.unwrap();
+ assert!(recreated.created);
+ assert_ne!(recreated.dm.channel_id, first.dm.channel_id);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn only_a_persona_dm_is_a_direct_agent_conversation(pool: PgPool) {
+ let repo = PgChannelsRepo::new(pool);
+ let dm = repo
+ .ensure(user(), bot_id::MACRO_NEW_BOT_ID)
+ .await
+ .unwrap()
+ .dm;
+ assert!(
+ repo.is_direct_agent_conversation(dm.channel_id)
+ .await
+ .unwrap()
+ );
+ assert!(
+ !repo
+ .is_direct_agent_conversation(macro_uuid::generate_uuid_v7())
+ .await
+ .unwrap()
+ );
+}
diff --git a/crates/channels/src/outbound/pg_channels_repo/channel_agents.rs b/crates/channels/src/outbound/pg_channels_repo/channel_agents.rs
new file mode 100644
index 0000000000..178e2a8534
--- /dev/null
+++ b/crates/channels/src/outbound/pg_channels_repo/channel_agents.rs
@@ -0,0 +1,66 @@
+//! Reads of the agents conversing in a channel.
+
+use bot_id::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+use crate::domain::{
+ channel_agents::{ChannelAgent, ChannelAgentKind, ChannelAgentRepo},
+ ports::ChannelMutationErr,
+};
+
+use super::PgChannelsRepo;
+
+fn kind(kind: &str, user_id: Option<String>) -> anyhow::Result<ChannelAgentKind> {
+ match (kind, user_id) {
+ ("direct", Some(user_id)) => Ok(ChannelAgentKind::Direct {
+ user_id: MacroUserIdStr::try_from(user_id)?,
+ }),
+ ("member", None) => Ok(ChannelAgentKind::Member),
+ (kind, _) => anyhow::bail!("unknown channel agent kind {kind}"),
+ }
+}
+
+impl ChannelAgentRepo for PgChannelsRepo {
+ async fn agents_in(&self, channel_id: Uuid) -> Result<Vec<ChannelAgent>, ChannelMutationErr> {
+ let rows = sqlx::query!(
+ "SELECT bot_id, kind, user_id FROM comms_channel_agents WHERE channel_id = $1 ORDER BY bot_id",
+ channel_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ rows.into_iter()
+ .map(|row| {
+ Ok(ChannelAgent {
+ channel_id,
+ bot_id: BotId::new_from_uuid(row.bot_id),
+ kind: kind(&row.kind, row.user_id)?,
+ })
+ })
+ .collect()
+ }
+
+ async fn find(
+ &self,
+ channel_id: Uuid,
+ bot_id: BotId,
+ ) -> Result<Option<ChannelAgent>, ChannelMutationErr> {
+ let row = sqlx::query!(
+ "SELECT kind, user_id FROM comms_channel_agents WHERE channel_id = $1 AND bot_id = $2",
+ channel_id,
+ bot_id.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(anyhow::Error::from)?;
+ row.map(|row| {
+ Ok(ChannelAgent {
+ channel_id,
+ bot_id,
+ kind: kind(&row.kind, row.user_id)?,
+ })
+ })
+ .transpose()
+ }
+}
diff --git a/crates/channels/src/outbound/pg_channels_repo/historical/test.rs b/crates/channels/src/outbound/pg_channels_repo/historical/test.rs
index 3dfe04dc87..7a173d4403 100644
--- a/crates/channels/src/outbound/pg_channels_repo/historical/test.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/historical/test.rs
@@ -168,7 +168,7 @@ async fn concurrent_live_and_import_dm_creation_share_one_channel(pool: PgPool)
.get_or_create_dm(
Sender::new_from_user(pair().hi().clone()),
GetOrCreateDmRequest {
- recipient_id: pair().lo().clone(),
+ recipient_id: Sender::new_from_user(pair().lo().clone()),
},
)
.await
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries.rs b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
index 367b0d1bf4..204460235f 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
@@ -93,6 +93,9 @@ pub async fn get_user_source_ids(
}
/// Grabs the source ids available to a bot operating in its owning team's scope.
+///
+/// A direct agent conversation is not among them, although the persona takes
+/// part in it: what is shared there belongs to the person it is with.
#[tracing::instrument(skip(pool), err)]
#[cfg_attr(
not(test),
@@ -134,6 +137,12 @@ pub async fn get_team_scope_source_ids(
JOIN comms_channel_participants cp
ON cp.user_id = $1
AND cp.left_at IS NULL
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = cp.channel_id
+ AND ca.kind = 'direct'
+ )
"#,
bot_id.as_ref(),
bot_id.as_uuid(),
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
index 8369563fb6..32acf4fd9b 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/channel_role.rs
@@ -155,8 +155,10 @@ pub async fn explain_channel_access(
/// Get a bot's channel role while operating in its owning team's scope.
///
-/// An active participant row grants its stored role in any channel. Without an
-/// active participant row, only a team channel owned by the supplied team
+/// An active participant row grants its stored role in any channel except a
+/// direct agent conversation: that channel belongs to the person the persona
+/// talks with, and the rest of the persona's team must not reach it. Without
+/// an active participant row, only a team channel owned by the supplied team
/// grants view-only access. The bot must be active and owned by that team.
#[tracing::instrument(err, skip(pool))]
pub async fn get_team_channel_role(
@@ -185,6 +187,12 @@ pub async fn get_team_channel_role(
AND cp.user_id = $2
AND cp.left_at IS NULL
AND b.id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM comms_channel_agents ca
+ WHERE ca.channel_id = c.id
+ AND ca.kind = 'direct'
+ )
WHERE c.id = $1
"#,
channel_id,
diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rs
index a6c3a3fa66..6f7af25f36 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs
@@ -956,6 +956,119 @@ async fn team_channel_role_uses_scoped_channel_rules(pool: PgPool) -> anyhow::Re
Ok(())
}
+/// A direct agent conversation between `owner` and `bot_id`, holding just the
+/// two of them as opening one does.
+async fn insert_pg_direct_agent_conversation(
+ pool: &PgPool,
+ channel_id: Uuid,
+ owner: &str,
+ bot_id: BotId,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ channel_id,
+ owner,
+ )
+ .execute(pool)
+ .await?;
+ sqlx::query!(
+ "INSERT INTO comms_channel_agents (channel_id, bot_id, kind, user_id) VALUES ($1, $2, 'direct', $3)",
+ channel_id,
+ bot_id.as_uuid(),
+ owner,
+ )
+ .execute(pool)
+ .await?;
+ let principal = bot_id.into_storage_id();
+ sqlx::query!(
+ "INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'owner'), ($1, $3, 'member')",
+ channel_id,
+ owner,
+ principal.as_ref(),
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+/// Any member of a persona's team can mint its team-scope token, so the
+/// conversation one teammate has with the persona must stay out of it: its
+/// channel, and everything shared there, including the conversation's
+/// sessions.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_scope_does_not_reach_a_direct_agent_conversation(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let shared_channel_id = Uuid::new_v4();
+ let conversation_id = Uuid::new_v4();
+ insert_pg_bot_team(&pool, team_id).await?;
+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;
+ insert_pg_bot_channel(&pool, shared_channel_id, "private", None).await?;
+ insert_pg_bot_participant(&pool, shared_channel_id, bot_id, "member").await?;
+ insert_pg_direct_agent_conversation(&pool, conversation_id, PG_BOT_OWNER, bot_id).await?;
+ let repo = PgAccessRepository::new(pool);
+
+ assert_eq!(
+ repo.get_team_channel_role(&shared_channel_id, team_id, bot_id)
+ .await?,
+ ChannelRoleResult::Role(ParticipantRole::Member),
+ );
+ assert_eq!(
+ repo.get_team_channel_role(&conversation_id, team_id, bot_id)
+ .await?,
+ ChannelRoleResult::NoAccess,
+ );
+ for (entity_type, stored_type) in [
+ (EntityType::Document, "document"),
+ (EntityType::AgentSession, "agent_session"),
+ ] {
+ let in_shared_channel = Uuid::new_v4();
+ insert_pg_bot_entity_access(
+ &repo.pool,
+ in_shared_channel,
+ stored_type,
+ &shared_channel_id.to_string(),
+ "channel",
+ AccessLevel::Edit,
+ )
+ .await?;
+ assert_eq!(
+ repo.get_team_entity_access(
+ bot_id,
+ team_id,
+ &in_shared_channel.to_string(),
+ entity_type,
+ )
+ .await?,
+ Some(AccessLevel::Edit),
+ "{stored_type} shared in a channel",
+ );
+
+ let in_conversation = Uuid::new_v4();
+ insert_pg_bot_entity_access(
+ &repo.pool,
+ in_conversation,
+ stored_type,
+ &conversation_id.to_string(),
+ "channel",
+ AccessLevel::Edit,
+ )
+ .await?;
+ assert_eq!(
+ repo.get_team_entity_access(
+ bot_id,
+ team_id,
+ &in_conversation.to_string(),
+ entity_type,
+ )
+ .await?,
+ None,
+ "{stored_type} shared in the direct conversation",
+ );
+ }
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn team_foreign_entity_access_uses_only_team_and_bot_pairs(
pool: PgPool,
diff --git a/crates/folds/agent_fold/src/domain/lifecycle.rs b/crates/folds/agent_fold/src/domain/lifecycle.rs
index c11b0f273c..f5dc55b22b 100644
--- a/crates/folds/agent_fold/src/domain/lifecycle.rs
+++ b/crates/folds/agent_fold/src/domain/lifecycle.rs
@@ -17,13 +17,15 @@
//!
//! [`push`]: LifecycleFold::push
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
+
+use agent_runtime_protocol::domain::action::AgentActionId;
use crate::domain::fold::FoldMachineImpl;
use crate::domain::log::AgentSessionLog;
use crate::domain::model::{
Author, ElicitationRequestId, FoldEvent, FoldedMessage, MessagePart, OwnedFoldEvent,
- SessionMetadata, TurnId, TurnSignal,
+ ProjectedSegment, SessionMetadata, TurnId, TurnPhase, TurnSignal, phase, project,
};
use crate::domain::ports::FoldMachine as _;
@@ -47,8 +49,15 @@ pub struct LifecycleFold {
closed: HashSet<TurnId>,
/// The pending elicitation after the last push, to diff against.
pending: Option<(ElicitationRequestId, TurnId)>,
+ /// The shape last reported for each open reply, to diff against. Prose
+ /// still being written is absent from a shape, so a streaming passage
+ /// does not report on every chunk.
+ progress: HashMap<TurnId, ReplyShape>,
}
+/// What [`TurnSignal::Progressed`] last said about a reply.
+type ReplyShape = (Option<TurnPhase>, Vec<ProjectedSegment>);
+
impl LifecycleFold {
/// A fold that has folded nothing.
#[must_use]
@@ -86,30 +95,50 @@ impl LifecycleFold {
}
fn observe_message(&mut self, message: &FoldedMessage, signals: &mut Vec<TurnSignal>) {
- let (Author::Agent, Some(stop)) = (&message.author, &message.stop) else {
- return;
- };
- if !self.closed.insert(message.id) {
+ if !matches!(message.author, Author::Agent) || self.closed.contains(&message.id) {
return;
}
- // The prompt that opened the turn carries the action id; the agent's
- // reply never does.
- let action_id = self
- .inner
- .messages()
- .iter()
- .find(|candidate| {
- candidate.id == message.id && matches!(candidate.author, Author::User { .. })
- })
- .and_then(|prompt| prompt.request_id);
+ let closed = message.stop.is_some();
+ let shape = (
+ phase(&message.parts, closed),
+ project(&message.parts, closed),
+ );
+ let changed = self.progress.get(&message.id) != Some(&shape);
+ if changed {
+ let (phase, segments) = shape.clone();
+ signals.push(TurnSignal::Progressed {
+ turn: message.id,
+ action_id: self.action_id(message),
+ phase,
+ segments,
+ });
+ self.progress.insert(message.id, shape);
+ }
+ let Some(stop) = &message.stop else {
+ return;
+ };
+ self.closed.insert(message.id);
+ self.progress.remove(&message.id);
signals.push(TurnSignal::TurnEnded {
turn: message.id,
- action_id,
+ action_id: self.action_id(message),
stop: stop.clone(),
last_text: last_text(message),
});
}
+ /// The prompt that opened the turn carries the action id; the agent's
+ /// reply never does.
+ fn action_id(&self, reply: &FoldedMessage) -> Option<AgentActionId> {
+ self.inner
+ .messages()
+ .iter()
+ .find(|candidate| {
+ candidate.id == reply.id && matches!(candidate.author, Author::User { .. })
+ })
+ .and_then(|prompt| prompt.request_id)
+ }
+
fn observe_metadata(&mut self, metadata: &SessionMetadata, signals: &mut Vec<TurnSignal>) {
let now = metadata
.pending_elicitation()
@@ -131,6 +160,9 @@ impl LifecycleFold {
}
fn observe_replacement(&mut self, messages: &[FoldedMessage]) {
+ // A replacement is history, not news: the next change to an open
+ // reply reports its whole shape again.
+ self.progress.clear();
self.closed = messages
.iter()
.filter(|message| matches!(message.author, Author::Agent) && message.stop.is_some())
diff --git a/crates/folds/agent_fold/src/domain/model.rs b/crates/folds/agent_fold/src/domain/model.rs
index 519f4fc2ba..f224161cf2 100644
--- a/crates/folds/agent_fold/src/domain/model.rs
+++ b/crates/folds/agent_fold/src/domain/model.rs
@@ -34,6 +34,8 @@ mod permission;
mod plan;
/// Plain text derived from renderable messages for search.
mod search;
+/// How a reply reads as a conversation: prose, activity, interactions.
+mod segment;
/// Turn-level facts derived from the fold.
mod signal;
/// Delegated agents.
@@ -55,6 +57,10 @@ pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata, Turn
pub use part::{Control, ControlOutcome, MessagePart, StopReason};
pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};
pub use plan::{PlanEntry, PlanEntryPriority, PlanEntryStatus};
+pub use segment::{
+ ActivityRow, ActivityStatus, ProjectedSegment, Segment, SegmentKind, TurnPhase, phase, project,
+ prose_text, segments,
+};
pub use signal::TurnSignal;
pub use subagent::{SubagentResult, ToolStats};
pub use tool::{AnsiText, FileDiff, ToolDetail, ToolName, ToolStatus};
diff --git a/crates/folds/agent_fold/src/domain/model/segment.rs b/crates/folds/agent_fold/src/domain/model/segment.rs
new file mode 100644
index 0000000000..f2bfa7c3ed
--- /dev/null
+++ b/crates/folds/agent_fold/src/domain/model/segment.rs
@@ -0,0 +1,516 @@
+//! How an agent's reply reads as a conversation.
+//!
+//! A reply is an ordered list of parts: prose, tool calls, requests for the
+//! user. A conversation surface - a channel message, a typing row, a live
+//! tail under the composer - wants them grouped: a passage the agent wrote,
+//! the work it did between passages, and what it is waiting on. This module is
+//! that grouping, derived from the parts alone.
+//!
+//! The same function runs on the server, which posts a reply's sealed
+//! segments as channel messages, and in the browser through the wasm fold,
+//! which renders the segment still being written. Both read the boundaries
+//! from here, so a message the server posted and the live view of the same
+//! turn never disagree about where one segment ends.
+//!
+//! Activity rows carry their own wording. A row is stored in a channel
+//! message once its segment is posted, so the label a person reads later is
+//! the label the live view showed; wording that differed between the two
+//! would make a finished turn look like it changed.
+
+use agent_runtime_protocol::domain::tool_approval::ToolApprovalStatus;
+use serde::{Deserialize, Serialize};
+use specta::Type;
+
+use super::part::MessagePart;
+use super::plan::PlanEntryStatus;
+use super::tool::{ToolDetail, ToolName, ToolStatus};
+use super::user_tool::UserToolOutcome;
+use super::{ElicitationOutcome, PermissionOutcome};
+
+#[cfg(test)]
+mod test;
+
+/// Longest detail a row keeps, in characters.
+const DETAIL_MAX_CHARS: usize = 80;
+
+/// What a segment of a reply is.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum SegmentKind {
+ /// A passage the agent wrote.
+ Prose,
+ /// A run of tool calls and plan updates.
+ Activity,
+ /// A permission or a question the agent put to the user.
+ Interaction,
+}
+
+/// Where one step of work got to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum ActivityStatus {
+ /// Started and not finished, including a call waiting on permission.
+ Running,
+ /// Finished successfully.
+ Completed,
+ /// Finished unsuccessfully.
+ Failed,
+ /// Still running when its turn ended: nobody knows whether it finished.
+ Interrupted,
+}
+
+/// One step of work, worded for a person reading a conversation.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ActivityRow {
+ /// The tool call's id, stable across updates; `plan` for a plan update.
+ pub id: String,
+ /// What happened, as a verb phrase: `Ran`, `Reading`, `Search documents`.
+ pub label: String,
+ /// What it happened to - a command, a file, a query - when that is safe
+ /// to show to everyone who can read the conversation.
+ pub detail: Option<String>,
+ /// Where it got to.
+ pub status: ActivityStatus,
+}
+
+/// A run of a reply's parts that reads as one unit.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct Segment {
+ /// Position among the reply's segments, from zero.
+ pub index: u32,
+ /// What the segment is.
+ pub kind: SegmentKind,
+ /// Index of the segment's first part.
+ pub start: u32,
+ /// Index one past the segment's last part.
+ pub end: u32,
+ /// Whether the segment can still change: false only for the last segment
+ /// of a reply that is still being written.
+ pub sealed: bool,
+ /// The steps, for an activity segment; empty otherwise.
+ pub rows: Vec<ActivityRow>,
+}
+
+/// What the agent is doing right now, as a typing indicator says it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum TurnPhase {
+ /// Nothing to show yet, or between steps.
+ Thinking,
+ /// Writing prose.
+ Writing,
+ /// Running a tool.
+ Working,
+ /// Waiting on the user to answer a permission or a question.
+ Waiting,
+}
+
+/// A segment with the content a server needs to post it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ProjectedSegment {
+ /// The segment's boundaries and rows.
+ pub segment: Segment,
+ /// The prose, once the segment is sealed. Absent while the agent is
+ /// still writing it - an unfinished passage is not posted - and for
+ /// every other kind.
+ pub text: Option<String>,
+}
+
+/// Group a reply's parts into segments.
+///
+/// `closed` is whether the reply's turn has ended; until it has, the last
+/// segment stays open. Thoughts, attachments and controls belong to no
+/// segment, and whitespace-only prose is not a passage: a newline the agent
+/// emitted between two tool calls must not split their activity in two.
+#[must_use]
+pub fn segments(parts: &[MessagePart], closed: bool) -> Vec<Segment> {
+ let mut out: Vec<Segment> = Vec::new();
+ for (index, part) in parts.iter().enumerate() {
+ let Some(kind) = part_kind(part) else {
+ continue;
+ };
+ let index = u32::try_from(index).unwrap_or(u32::MAX);
+ match out.last_mut() {
+ // Each interaction is its own segment: two requests are two
+ // things to answer, not one.
+ Some(last) if last.kind == kind && kind != SegmentKind::Interaction => {
+ last.end = index.saturating_add(1);
+ }
+ _ => out.push(Segment {
+ index: u32::try_from(out.len()).unwrap_or(u32::MAX),
+ kind,
+ start: index,
+ end: index.saturating_add(1),
+ sealed: true,
+ rows: Vec::new(),
+ }),
+ }
+ }
+ if let Some(last) = out.last_mut() {
+ last.sealed = closed;
+ }
+ for segment in &mut out {
+ if segment.kind == SegmentKind::Activity {
+ segment.rows = activity_rows(slice(parts, segment), closed);
+ }
+ }
+ out
+}
+
+/// The segments, with each sealed passage's prose, for a server to post.
+#[must_use]
+pub fn project(parts: &[MessagePart], closed: bool) -> Vec<ProjectedSegment> {
+ segments(parts, closed)
+ .into_iter()
+ .map(|segment| {
+ let text = (segment.kind == SegmentKind::Prose && segment.sealed)
+ .then(|| prose_text(parts, &segment));
+ ProjectedSegment { segment, text }
+ })
+ .collect()
+}
+
+/// The prose of a segment: its text parts, a blank line apart.
+#[must_use]
+pub fn prose_text(parts: &[MessagePart], segment: &Segment) -> String {
+ slice(parts, segment)
+ .iter()
+ .filter_map(|part| match part {
+ MessagePart::Text { text } if !text.trim().is_empty() => Some(text.trim()),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("\n\n")
+}
+
+/// What an unfinished reply is doing now. `None` once its turn has ended.
+///
+/// A pending question or approval blocks the turn wherever it sits: the tool
+/// that asked can report itself running after its question. Otherwise the
+/// phase is read off the last part rather than the last segment: a thought
+/// belongs to no segment, and an agent thinking after a passage is not still
+/// writing it.
+#[must_use]
+pub fn phase(parts: &[MessagePart], closed: bool) -> Option<TurnPhase> {
+ if closed {
+ return None;
+ }
+ if parts.iter().any(is_pending_request) {
+ return Some(TurnPhase::Waiting);
+ }
+ let phase = match parts.iter().rev().find(|part| !is_blank_text(part)) {
+ Some(MessagePart::Text { .. }) => TurnPhase::Writing,
+ Some(MessagePart::ToolUse {
+ status: ToolStatus::Pending | ToolStatus::Running,
+ ..
+ }) => TurnPhase::Working,
+ _ => TurnPhase::Thinking,
+ };
+ Some(phase)
+}
+
+/// A question or approval the user has not answered yet.
+fn is_pending_request(part: &MessagePart) -> bool {
+ matches!(
+ part,
+ MessagePart::Permission {
+ outcome: PermissionOutcome::Pending,
+ ..
+ } | MessagePart::Elicitation {
+ outcome: ElicitationOutcome::Pending,
+ ..
+ } | MessagePart::ToolApproval {
+ status: ToolApprovalStatus::Pending,
+ ..
+ }
+ )
+}
+
+fn is_blank_text(part: &MessagePart) -> bool {
+ matches!(part, MessagePart::Text { text } if text.trim().is_empty())
+}
+
+fn part_kind(part: &MessagePart) -> Option<SegmentKind> {
+ match part {
+ MessagePart::Text { text } if text.trim().is_empty() => None,
+ MessagePart::Text { .. } => Some(SegmentKind::Prose),
+ MessagePart::ToolUse { .. } | MessagePart::Plan { .. } => Some(SegmentKind::Activity),
+ MessagePart::Permission { .. }
+ | MessagePart::Elicitation { .. }
+ | MessagePart::ToolApproval { .. } => Some(SegmentKind::Interaction),
+ MessagePart::Thought { .. }
+ | MessagePart::Attachment { .. }
+ | MessagePart::Control { .. } => None,
+ }
+}
+
+fn slice<'a>(parts: &'a [MessagePart], segment: &Segment) -> &'a [MessagePart] {
+ let start = (segment.start as usize).min(parts.len());
+ let end = (segment.end as usize).clamp(start, parts.len());
+ &parts[start..end]
+}
+
+fn activity_rows(parts: &[MessagePart], closed: bool) -> Vec<ActivityRow> {
+ parts
+ .iter()
+ .filter_map(|part| match part {
+ MessagePart::ToolUse {
+ id,
+ name,
+ status,
+ detail,
+ } => Some(tool_row(id.0.clone(), name, *status, detail, closed)),
+ MessagePart::Plan { entries } => {
+ let done = entries
+ .iter()
+ .filter(|entry| entry.status == PlanEntryStatus::Completed)
+ .count();
+ Some(ActivityRow {
+ id: "plan".to_owned(),
+ label: "Updated the plan".to_owned(),
+ detail: Some(format!("{done}/{} done", entries.len())),
+ status: ActivityStatus::Completed,
+ })
+ }
+ _ => None,
+ })
+ .collect()
+}
+
+/// Verb forms for a step: while it runs, once it finished, and if it failed.
+struct Verbs {
+ running: &'static str,
+ done: &'static str,
+ failed: &'static str,
+}
+
+const RUN: Verbs = Verbs {
+ running: "Running",
+ done: "Ran",
+ failed: "Command failed",
+};
+const EDIT: Verbs = Verbs {
+ running: "Editing",
+ done: "Edited",
+ failed: "Edit failed",
+};
+const READ: Verbs = Verbs {
+ running: "Reading",
+ done: "Read",
+ failed: "Read failed",
+};
+const DELETE: Verbs = Verbs {
+ running: "Deleting",
+ done: "Deleted",
+ failed: "Delete failed",
+};
+const MOVE: Verbs = Verbs {
+ running: "Moving",
+ done: "Moved",
+ failed: "Move failed",
+};
+const SEARCH: Verbs = Verbs {
+ running: "Searching",
+ done: "Searched",
+ failed: "Search failed",
+};
+const FETCH: Verbs = Verbs {
+ running: "Fetching",
+ done: "Fetched",
+ failed: "Fetch failed",
+};
+const DELEGATE: Verbs = Verbs {
+ running: "Delegating",
+ done: "Delegated",
+ failed: "Delegation failed",
+};
+
+fn tool_row(
+ id: String,
+ name: &ToolName,
+ status: ToolStatus,
+ detail: &ToolDetail,
+ closed: bool,
+) -> ActivityRow {
+ let status = match status {
+ ToolStatus::Pending | ToolStatus::Running if closed => ActivityStatus::Interrupted,
+ ToolStatus::Pending | ToolStatus::Running => ActivityStatus::Running,
+ ToolStatus::Completed => ActivityStatus::Completed,
+ ToolStatus::Failed => ActivityStatus::Failed,
+ };
+ let named = humanize(tool_name(name));
+ let verbed = |verbs: &Verbs, detail: Option<String>| {
+ let label = match status {
+ ActivityStatus::Running => verbs.running,
+ ActivityStatus::Completed | ActivityStatus::Interrupted => verbs.done,
+ ActivityStatus::Failed => verbs.failed,
+ };
+ (label.to_owned(), detail)
+ };
+ let (label, detail) = match detail {
+ ToolDetail::Terminal { command, .. } => {
+ verbed(&RUN, command.as_deref().map(command_detail))
+ }
+ ToolDetail::Edit { diffs } => verbed(
+ &EDIT,
+ paths_detail(diffs.iter().map(|diff| diff.path.as_path())),
+ ),
+ ToolDetail::Read { paths } => {
+ verbed(&READ, paths_detail(paths.iter().map(|p| p.as_path())))
+ }
+ ToolDetail::Delete { paths } => {
+ verbed(&DELETE, paths_detail(paths.iter().map(|p| p.as_path())))
+ }
+ ToolDetail::Move { paths } => {
+ verbed(&MOVE, paths_detail(paths.iter().map(|p| p.as_path())))
+ }
+ ToolDetail::Search { paths, .. } => {
+ verbed(&SEARCH, paths_detail(paths.iter().map(|p| p.as_path())))
+ }
+ ToolDetail::Fetch { .. } => verbed(&FETCH, None),
+ ToolDetail::Think { .. } => ("Thought it through".to_owned(), None),
+ ToolDetail::Other { input, .. } => (
+ named_label(&named, status),
+ input.as_ref().and_then(input_detail),
+ ),
+ ToolDetail::Macro { input, .. } => (named_label(&named, status), input_detail(input)),
+ ToolDetail::UserTool { outcome, .. } => (user_tool_label(&named, outcome), None),
+ ToolDetail::Subagent { title, .. } => verbed(&DELEGATE, Some(truncate(title))),
+ };
+ ActivityRow {
+ id,
+ label,
+ detail,
+ status,
+ }
+}
+
+/// A tool known only by name reads as its name in every state; the status
+/// icon says whether it is running.
+fn named_label(named: &str, status: ActivityStatus) -> String {
+ match status {
+ ActivityStatus::Failed => format!("{named} failed"),
+ ActivityStatus::Running | ActivityStatus::Completed | ActivityStatus::Interrupted => {
+ named.to_owned()
+ }
+ }
+}
+
+fn user_tool_label(named: &str, outcome: &UserToolOutcome) -> String {
+ let state = match outcome {
+ UserToolOutcome::Pending | UserToolOutcome::Edited => "drafted",
+ UserToolOutcome::Sent { .. } => "sent",
+ UserToolOutcome::Draft { .. } => "saved as draft",
+ UserToolOutcome::Completed { .. } => "done",
+ UserToolOutcome::Rejected => "declined",
+ UserToolOutcome::Failed { .. } => "failed",
+ UserToolOutcome::Unrecognized => "finished",
+ };
+ format!("{named} {state}")
+}
+
+fn tool_name(name: &ToolName) -> &str {
+ match name {
+ ToolName::Native { name } => name,
+ ToolName::Mcp { tool, .. } => tool,
+ }
+}
+
+/// `ListEntities`, `list_entities` and `list-entities` all read `List entities`.
+fn humanize(name: &str) -> String {
+ let mut words: Vec<String> = Vec::new();
+ let mut current = String::new();
+ let mut previous: Option<char> = None;
+ for character in name.chars() {
+ if matches!(character, '_' | '-' | ' ' | '.') {
+ if !current.is_empty() {
+ words.push(std::mem::take(&mut current));
+ }
+ } else {
+ let boundary = character.is_uppercase()
+ && previous
+ .is_some_and(|previous| previous.is_lowercase() || previous.is_numeric());
+ if boundary && !current.is_empty() {
+ words.push(std::mem::take(&mut current));
+ }
+ current.push(character);
+ }
+ previous = Some(character);
+ }
+ if !current.is_empty() {
+ words.push(current);
+ }
+ let sentence = words
+ .iter()
+ .map(|word| {
+ // Keep acronyms (`URL`, `PDF`) as written.
+ if word.len() > 1 && word.chars().all(|c| c.is_uppercase() || c.is_numeric()) {
+ word.clone()
+ } else {
+ word.to_lowercase()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" ");
+ let mut characters = sentence.chars();
+ match characters.next() {
+ Some(first) => first.to_uppercase().chain(characters).collect(),
+ None => "Tool".to_owned(),
+ }
+}
+
+fn truncate(text: &str) -> String {
+ let line = text.lines().next().unwrap_or_default().trim();
+ if line.chars().count() <= DETAIL_MAX_CHARS {
+ return line.to_owned();
+ }
+ let kept: String = line.chars().take(DETAIL_MAX_CHARS - 1).collect();
+ format!("{}…", kept.trim_end())
+}
+
+/// A command's first line, cut to length.
+fn command_detail(command: &str) -> String {
+ truncate(command.lines().next().unwrap_or_default())
+}
+
+/// A file's name, or how many files.
+fn paths_detail<'a>(paths: impl Iterator<Item = &'a std::path::Path>) -> Option<String> {
+ let paths: Vec<_> = paths.collect();
+ match paths.as_slice() {
+ [] => None,
+ [path] => Some(truncate(
+ &path
+ .file_name()
+ .map_or_else(|| path.to_string_lossy(), |name| name.to_string_lossy()),
+ )),
+ many => Some(format!("{} files", many.len())),
+ }
+}
+
+/// The argument that says what a tool acted on, for tools known by name: a
+/// query, a title, a name - of a document or file too - a URL. Only short
+/// plain strings qualify.
+fn input_detail(input: &serde_json::Value) -> Option<String> {
+ const KEYS: [&str; 9] = [
+ "query",
+ "q",
+ "title",
+ "name",
+ "documentName",
+ "fileName",
+ "url",
+ "path",
+ "subject",
+ ];
+ let object = input.as_object()?;
+ KEYS.iter().find_map(|key| {
+ object
+ .get(*key)
+ .and_then(serde_json::Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(truncate)
+ })
+}
diff --git a/crates/folds/agent_fold/src/domain/model/segment/test.rs b/crates/folds/agent_fold/src/domain/model/segment/test.rs
new file mode 100644
index 0000000000..a7303ff440
--- /dev/null
+++ b/crates/folds/agent_fold/src/domain/model/segment/test.rs
@@ -0,0 +1,306 @@
+use std::path::PathBuf;
+
+use super::*;
+use crate::domain::model::{AgentRequestId, AnsiText, ToolUseId};
+
+fn text(text: &str) -> MessagePart {
+ MessagePart::Text {
+ text: text.to_owned(),
+ }
+}
+
+fn thought(text: &str) -> MessagePart {
+ MessagePart::Thought {
+ text: text.to_owned(),
+ }
+}
+
+fn run(id: &str, command: &str, status: ToolStatus) -> MessagePart {
+ MessagePart::ToolUse {
+ id: ToolUseId(id.to_owned()),
+ name: ToolName::native("Bash"),
+ status,
+ detail: ToolDetail::Terminal {
+ command: Some(command.to_owned()),
+ output: Some(AnsiText(String::new())),
+ exit_code: None,
+ },
+ }
+}
+
+fn read(id: &str, paths: &[&str], status: ToolStatus) -> MessagePart {
+ MessagePart::ToolUse {
+ id: ToolUseId(id.to_owned()),
+ name: ToolName::native("Read"),
+ status,
+ detail: ToolDetail::Read {
+ paths: paths.iter().map(PathBuf::from).collect(),
+ },
+ }
+}
+
+fn macro_tool(id: &str, name: &str, input: serde_json::Value, status: ToolStatus) -> MessagePart {
+ MessagePart::ToolUse {
+ id: ToolUseId(id.to_owned()),
+ name: ToolName::native(name),
+ status,
+ detail: ToolDetail::Macro {
+ input,
+ output: None,
+ error: None,
+ },
+ }
+}
+
+fn permission(id: i64, outcome: PermissionOutcome) -> MessagePart {
+ MessagePart::Permission {
+ request_id: AgentRequestId::Number(id),
+ tool_call: ToolUseId(format!("call-{id}")),
+ options: Vec::new(),
+ outcome,
+ }
+}
+
+fn kinds(segments: &[Segment]) -> Vec<(SegmentKind, bool)> {
+ segments
+ .iter()
+ .map(|segment| (segment.kind, segment.sealed))
+ .collect()
+}
+
+#[test]
+fn an_unfinished_passage_is_the_one_open_segment() {
+ let parts = [text("Looking into it")];
+ assert_eq!(
+ kinds(&segments(&parts, false)),
+ [(SegmentKind::Prose, false)]
+ );
+ assert_eq!(kinds(&segments(&parts, true)), [(SegmentKind::Prose, true)]);
+}
+
+#[test]
+fn narration_work_and_answer_are_three_segments_with_the_steps_grouped() {
+ let parts = [
+ text("Checking the tests first."),
+ run("a", "cargo test", ToolStatus::Completed),
+ read("b", &["/repo/src/lib.rs"], ToolStatus::Completed),
+ text("All green."),
+ ];
+ let segments = segments(&parts, true);
+ assert_eq!(
+ kinds(&segments),
+ [
+ (SegmentKind::Prose, true),
+ (SegmentKind::Activity, true),
+ (SegmentKind::Prose, true),
+ ]
+ );
+ assert_eq!((segments[1].start, segments[1].end), (1, 3));
+ assert_eq!(
+ segments[1].rows,
+ [
+ ActivityRow {
+ id: "a".to_owned(),
+ label: "Ran".to_owned(),
+ detail: Some("cargo test".to_owned()),
+ status: ActivityStatus::Completed,
+ },
+ ActivityRow {
+ id: "b".to_owned(),
+ label: "Read".to_owned(),
+ detail: Some("lib.rs".to_owned()),
+ status: ActivityStatus::Completed,
+ },
+ ]
+ );
+ assert_eq!(
+ segments.iter().map(|s| s.index).collect::<Vec<_>>(),
+ [0, 1, 2]
+ );
+}
+
+#[test]
+fn a_blank_line_between_tool_calls_does_not_split_their_activity() {
+ let parts = [
+ run("a", "ls", ToolStatus::Completed),
+ text("\n\n"),
+ run("b", "pwd", ToolStatus::Running),
+ ];
+ let segments = segments(&parts, false);
+ assert_eq!(kinds(&segments), [(SegmentKind::Activity, false)]);
+ assert_eq!(segments[0].rows.len(), 2);
+ assert_eq!(segments[0].rows[1].label, "Running");
+}
+
+#[test]
+fn a_thought_inside_a_passage_belongs_to_no_segment() {
+ let parts = [text("First half."), thought("hmm"), text("Second half.")];
+ let segments = segments(&parts, true);
+ assert_eq!(kinds(&segments), [(SegmentKind::Prose, true)]);
+ assert_eq!(
+ prose_text(&parts, &segments[0]),
+ "First half.\n\nSecond half."
+ );
+}
+
+#[test]
+fn each_request_for_the_user_is_its_own_segment() {
+ let parts = [
+ permission(1, PermissionOutcome::Cancelled),
+ permission(2, PermissionOutcome::Pending),
+ ];
+ assert_eq!(
+ kinds(&segments(&parts, false)),
+ [
+ (SegmentKind::Interaction, true),
+ (SegmentKind::Interaction, false),
+ ]
+ );
+}
+
+#[test]
+fn a_step_still_running_when_the_turn_ended_is_interrupted() {
+ let parts = [run("a", "sleep 100", ToolStatus::Running)];
+ let row = &segments(&parts, true)[0].rows[0];
+ assert_eq!(row.status, ActivityStatus::Interrupted);
+ assert_eq!(row.label, "Ran");
+}
+
+#[test]
+fn only_sealed_prose_carries_its_text_to_the_server() {
+ let parts = [
+ text("Narration."),
+ run("a", "ls", ToolStatus::Running),
+ text("Answer in progress"),
+ ];
+ let open = project(&parts, false);
+ assert_eq!(open[0].text.as_deref(), Some("Narration."));
+ assert_eq!(open[1].text, None);
+ assert_eq!(open[2].text, None);
+ let closed = project(&parts, true);
+ assert_eq!(closed[2].text.as_deref(), Some("Answer in progress"));
+}
+
+#[test]
+fn the_phase_follows_the_last_thing_the_agent_did() {
+ assert_eq!(phase(&[], false), Some(TurnPhase::Thinking));
+ assert_eq!(phase(&[text("Hi")], false), Some(TurnPhase::Writing));
+ assert_eq!(
+ phase(&[text("Hi"), thought("now what")], false),
+ Some(TurnPhase::Thinking)
+ );
+ assert_eq!(
+ phase(&[run("a", "ls", ToolStatus::Running)], false),
+ Some(TurnPhase::Working)
+ );
+ assert_eq!(
+ phase(&[run("a", "ls", ToolStatus::Completed)], false),
+ Some(TurnPhase::Thinking)
+ );
+ assert_eq!(
+ phase(&[permission(1, PermissionOutcome::Pending)], false),
+ Some(TurnPhase::Waiting)
+ );
+ assert_eq!(phase(&[text("Done")], true), None);
+}
+
+#[test]
+fn a_pending_request_waits_even_when_its_tool_reports_after_it() {
+ // AskUser sends its question, then reports itself running.
+ let parts = [
+ permission(1, PermissionOutcome::Pending),
+ run("a", "ask", ToolStatus::Running),
+ ];
+ assert_eq!(phase(&parts, false), Some(TurnPhase::Waiting));
+ let answered = [
+ permission(
+ 1,
+ PermissionOutcome::Selected {
+ option_id: "allow".to_owned(),
+ },
+ ),
+ run("a", "ask", ToolStatus::Running),
+ ];
+ assert_eq!(phase(&answered, false), Some(TurnPhase::Working));
+}
+
+#[test]
+fn long_commands_keep_their_first_line_cut_to_length() {
+ let long = format!("echo {}\nsecond line", "x".repeat(200));
+ let parts = [run("a", &long, ToolStatus::Completed)];
+ let detail = segments(&parts, true)[0].rows[0].detail.clone().unwrap();
+ assert!(detail.ends_with('…'));
+ assert_eq!(detail.chars().count(), DETAIL_MAX_CHARS);
+ assert!(!detail.contains("second"));
+}
+
+#[test]
+fn several_files_are_counted_rather_than_listed() {
+ let parts = [read(
+ "a",
+ &["/a.rs", "/b.rs", "/c.rs"],
+ ToolStatus::Completed,
+ )];
+ assert_eq!(
+ segments(&parts, true)[0].rows[0].detail.as_deref(),
+ Some("3 files")
+ );
+}
+
+#[test]
+fn macro_tools_read_as_their_name_with_what_they_acted_on() {
+ let parts = [
+ macro_tool(
+ "a",
+ "SearchDocuments",
+ serde_json::json!({"query": "quarterly report", "limit": 5}),
+ ToolStatus::Completed,
+ ),
+ macro_tool(
+ "b",
+ "list_entities",
+ serde_json::json!({"limit": 5}),
+ ToolStatus::Failed,
+ ),
+ macro_tool(
+ "c",
+ "CreateDocument",
+ serde_json::json!({"documentName": "Launch FAQ", "fileContent": "..."}),
+ ToolStatus::Completed,
+ ),
+ ];
+ let rows = &segments(&parts, true)[0].rows;
+ assert_eq!(rows[0].label, "Search documents");
+ assert_eq!(rows[0].detail.as_deref(), Some("quarterly report"));
+ assert_eq!(rows[1].label, "List entities failed");
+ assert_eq!(rows[1].detail, None);
+ assert_eq!(rows[2].label, "Create document");
+ assert_eq!(rows[2].detail.as_deref(), Some("Launch FAQ"));
+}
+
+#[test]
+fn humanize_keeps_acronyms_and_splits_every_convention() {
+ assert_eq!(humanize("ListEntities"), "List entities");
+ assert_eq!(humanize("read_document"), "Read document");
+ assert_eq!(humanize("web-search"), "Web search");
+ assert_eq!(humanize("FetchURL"), "Fetch URL");
+ assert_eq!(humanize(""), "Tool");
+}
+
+#[test]
+fn session_activity_retains_command_and_tool_input_details_for_authorized_live_views() {
+ let command = "TOKEN=private-value run-report";
+ let query = "confidential acquisition";
+ let parts = [
+ run("terminal", command, ToolStatus::Completed),
+ macro_tool(
+ "search",
+ "search",
+ serde_json::json!({"query": query}),
+ ToolStatus::Completed,
+ ),
+ ];
+ let live = segments(&parts, true);
+ assert_eq!(live[0].rows[0].detail.as_deref(), Some(command));
+ assert_eq!(live[0].rows[1].detail.as_deref(), Some(query));
+}
diff --git a/crates/folds/agent_fold/src/domain/model/signal.rs b/crates/folds/agent_fold/src/domain/model/signal.rs
index fc2e0011cd..45a12590ff 100644
--- a/crates/folds/agent_fold/src/domain/model/signal.rs
+++ b/crates/folds/agent_fold/src/domain/model/signal.rs
@@ -3,7 +3,7 @@
use agent_runtime_protocol::domain::action::AgentActionId;
use serde::{Deserialize, Serialize};
-use super::{ElicitationRequestId, StopReason};
+use super::{ElicitationRequestId, ProjectedSegment, StopReason, TurnPhase};
use crate::domain::model::TurnId;
/// A turn-level fact the fold vouches for, derived from one pushed frame.
@@ -15,6 +15,25 @@ use crate::domain::model::TurnId;
/// dispatcher's knowledge and stays with it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TurnSignal {
+ /// The agent's reply for `turn` changed shape: a segment opened or
+ /// sealed, a step started or finished, or what the agent is doing
+ /// changed. Prose growing inside an open passage is not a change of
+ /// shape; that streams to viewers through the fold itself.
+ ///
+ /// Reported for a closing reply too, with every segment sealed, ahead of
+ /// its [`Self::TurnEnded`], so whoever posts the reply has its final
+ /// shape before it hears that the turn is over.
+ Progressed {
+ /// The turn whose reply changed.
+ turn: TurnId,
+ /// The prompt's action id, when the turn was opened by one this
+ /// server minted.
+ action_id: Option<AgentActionId>,
+ /// What the agent is doing now; `None` once the reply has closed.
+ phase: Option<TurnPhase>,
+ /// The reply's segments, sealed prose with its text.
+ segments: Vec<ProjectedSegment>,
+ },
/// The agent's message for `turn` closed.
TurnEnded {
/// The turn that closed.
diff --git a/crates/folds/agent_fold/src/domain/test/lifecycle.rs b/crates/folds/agent_fold/src/domain/test/lifecycle.rs
index fdc8950830..95b8af56c4 100644
--- a/crates/folds/agent_fold/src/domain/test/lifecycle.rs
+++ b/crates/folds/agent_fold/src/domain/test/lifecycle.rs
@@ -3,7 +3,9 @@ use super::util::{TURN, parse_log};
use crate::domain::fold::{FoldMachineImpl, fold};
use crate::domain::lifecycle::LifecycleFold;
use crate::domain::log::AgentSessionLog;
-use crate::domain::model::{FoldEvent, FoldedMessage, StopReason, TurnSignal};
+use crate::domain::model::{
+ FoldEvent, FoldedMessage, SegmentKind, StopReason, TurnPhase, TurnSignal,
+};
use crate::domain::ports::FoldMachine as _;
use crate::testing::fixtures::{ELICITATION_CLAUDE_SINGLE_SELECT, RESUMED_NO_PROMPT};
use serde_json::{Value, json};
@@ -38,8 +40,16 @@ fn update(kind: &str, text: &str) -> AgentSessionLog {
)
}
-/// Push a whole log live and collect every signal, in order.
+/// Push a whole log live and collect every lifecycle signal, in order. A
+/// reply's [`TurnSignal::Progressed`] reports are left out: they have their
+/// own tests below, and the lifecycle facts are what these assert.
fn signals_of(log: &[AgentSessionLog]) -> (LifecycleFold, Vec<TurnSignal>) {
+ let (machine, signals) = every_signal_of(log);
+ (machine, lifecycle_only(signals))
+}
+
+/// Push a whole log live and collect every signal, progress included.
+fn every_signal_of(log: &[AgentSessionLog]) -> (LifecycleFold, Vec<TurnSignal>) {
let mut machine = LifecycleFold::new();
let mut signals = Vec::new();
for entry in log {
@@ -48,6 +58,36 @@ fn signals_of(log: &[AgentSessionLog]) -> (LifecycleFold, Vec<TurnSignal>) {
(machine, signals)
}
+fn lifecycle_only(signals: Vec<TurnSignal>) -> Vec<TurnSignal> {
+ signals
+ .into_iter()
+ .filter(|signal| !matches!(signal, TurnSignal::Progressed { .. }))
+ .collect()
+}
+
+fn tool_call(id: &str, status: &str, command: &str) -> AgentSessionLog {
+ frame(
+ "to_server",
+ json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":id,"title":"Bash","kind":"execute","status":status,"rawInput":{"command":command}}}}),
+ )
+}
+
+fn tool_update(id: &str, status: &str) -> AgentSessionLog {
+ frame(
+ "to_server",
+ json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":id,"status":status}}}),
+ )
+}
+
+fn opened() -> Vec<AgentSessionLog> {
+ vec![
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/new", json!(1)),
+ frame("to_server", json!({"id":1,"result":{"sessionId":"s"}})),
+ ]
+}
+
fn apply(visible: &mut Vec<FoldedMessage>, event: FoldEvent<'_>) {
match event {
FoldEvent::MessagesReplaced(messages) => *visible = messages.into_owned(),
@@ -149,6 +189,7 @@ fn a_question_is_raised_then_cleared_before_the_turn_ends() {
TurnSignal::ElicitationRaised { .. } => "raised",
TurnSignal::ElicitationCleared { .. } => "cleared",
TurnSignal::TurnEnded { .. } => "ended",
+ TurnSignal::Progressed { .. } => unreachable!("filtered by signals_of"),
})
.collect();
assert_eq!(kinds, ["raised", "cleared", "ended"], "{signals:#?}");
@@ -190,14 +231,14 @@ fn history_pushed_and_ignored_leaves_a_live_turn_signalling_normally() {
"to_server",
json!({"id":7,"result":{"stopReason":"end_turn"}}),
));
+ let signals = lifecycle_only(pushed.signals);
assert!(
matches!(
- pushed.signals.as_slice(),
+ signals.as_slice(),
[TurnSignal::TurnEnded { stop: StopReason::EndTurn, last_text: Some(text), .. }]
if text == "again"
),
- "{:#?}",
- pushed.signals
+ "{signals:#?}"
);
}
@@ -212,7 +253,7 @@ fn a_load_replacement_signals_nothing_for_the_replaced_history() {
update("agent_message_chunk", "answer"),
result(load),
];
- let (machine, signals) = signals_of(&log);
+ let (machine, signals) = every_signal_of(&log);
assert!(signals.is_empty(), "{signals:#?}");
assert_eq!(machine.inner().messages().len(), 2);
@@ -223,7 +264,7 @@ fn a_load_replacement_signals_nothing_for_the_replaced_history() {
#[test]
fn a_resumed_sessions_history_signals_nothing() {
let log = parse_log(RESUMED_NO_PROMPT);
- let (machine, signals) = signals_of(&log);
+ let (machine, signals) = every_signal_of(&log);
assert!(signals.is_empty(), "{signals:#?}");
assert!(
@@ -263,3 +304,125 @@ fn an_unprompted_turn_ends_on_turn_complete_with_no_action_id() {
"{signals:#?}"
);
}
+
+/// A progress report as these tests read it: the phase, and each segment's
+/// kind and whether it is sealed.
+type Progress = (Option<TurnPhase>, Vec<(SegmentKind, bool)>);
+
+fn progress(signals: &[TurnSignal]) -> Vec<Progress> {
+ signals
+ .iter()
+ .filter_map(|signal| match signal {
+ TurnSignal::Progressed {
+ phase, segments, ..
+ } => Some((
+ *phase,
+ segments
+ .iter()
+ .map(|projected| (projected.segment.kind, projected.segment.sealed))
+ .collect(),
+ )),
+ _ => None,
+ })
+ .collect()
+}
+
+#[test]
+fn a_reply_reports_each_change_of_shape_but_not_each_streamed_chunk() {
+ let mut log = opened();
+ log.extend([
+ prompt(json!(7), "run the tests"),
+ update("agent_message_chunk", "Checking"),
+ update("agent_message_chunk", " the tests first."),
+ tool_call("t1", "in_progress", "cargo test"),
+ tool_update("t1", "completed"),
+ update("agent_message_chunk", "All "),
+ update("agent_message_chunk", "green."),
+ frame(
+ "to_server",
+ json!({"id":7,"result":{"stopReason":"end_turn"}}),
+ ),
+ ]);
+ let (_, signals) = every_signal_of(&log);
+
+ use SegmentKind::{Activity, Prose};
+ assert_eq!(
+ progress(&signals),
+ [
+ // The first chunk opens a passage; the second only lengthens it.
+ (Some(TurnPhase::Writing), vec![(Prose, false)]),
+ // The tool call seals the passage and opens the activity.
+ (
+ Some(TurnPhase::Working),
+ vec![(Prose, true), (Activity, false)]
+ ),
+ // The step finishing is a change of shape.
+ (
+ Some(TurnPhase::Thinking),
+ vec![(Prose, true), (Activity, false)]
+ ),
+ (
+ Some(TurnPhase::Writing),
+ vec![(Prose, true), (Activity, true), (Prose, false)]
+ ),
+ // The reply closing seals everything, before the turn ends.
+ (None, vec![(Prose, true), (Activity, true), (Prose, true)]),
+ ],
+ "{signals:#?}"
+ );
+ assert!(matches!(signals.last(), Some(TurnSignal::TurnEnded { .. })));
+}
+
+#[test]
+fn sealed_prose_carries_its_text_and_steps_carry_their_rows() {
+ let mut log = opened();
+ log.extend([
+ prompt(json!(7), "run the tests"),
+ update("agent_message_chunk", "Checking the tests first."),
+ tool_call("t1", "in_progress", "cargo test"),
+ ]);
+ let (_, signals) = every_signal_of(&log);
+ let Some(TurnSignal::Progressed { segments, .. }) = signals.last() else {
+ panic!("{signals:#?}");
+ };
+ assert_eq!(
+ segments[0].text.as_deref(),
+ Some("Checking the tests first.")
+ );
+ assert_eq!(segments[1].text, None);
+ assert_eq!(
+ segments[1]
+ .segment
+ .rows
+ .iter()
+ .map(|row| (row.label.as_str(), row.detail.as_deref()))
+ .collect::<Vec<_>>(),
+ [("Running", Some("cargo test"))]
+ );
+}
+
+#[test]
+fn a_closed_reply_reports_nothing_more() {
+ let mut log = opened();
+ log.extend([
+ prompt(json!(7), "hi"),
+ update("agent_message_chunk", "hello"),
+ frame(
+ "to_server",
+ json!({"id":7,"result":{"stopReason":"end_turn"}}),
+ ),
+ ]);
+ let mut machine = LifecycleFold::new();
+ for entry in &log {
+ let _ = machine.push(entry.clone());
+ }
+ let late = machine.push(update("agent_message_chunk", " again"));
+ assert!(
+ !late
+ .signals
+ .iter()
+ .any(|signal| matches!(signal, TurnSignal::Progressed { turn, .. } if turn.0 == 0)),
+ "{:#?}",
+ late.signals
+ );
+}
diff --git a/crates/folds/agent_fold/src/inbound/wire.rs b/crates/folds/agent_fold/src/inbound/wire.rs
index 098d5f5d16..a2886c48f1 100644
--- a/crates/folds/agent_fold/src/inbound/wire.rs
+++ b/crates/folds/agent_fold/src/inbound/wire.rs
@@ -11,8 +11,8 @@
use crate::domain::log::AgentSessionId;
use crate::domain::model::{
- Author, FoldEvent, FoldedMessage as ModelFoldedMessage, MessagePart, SessionMetadata,
- StopReason,
+ Author, FoldEvent, FoldedMessage as ModelFoldedMessage, MessagePart, Segment, SessionMetadata,
+ StopReason, TurnPhase,
};
use serde::Serialize;
use specta::Type;
@@ -42,20 +42,38 @@ pub struct FoldedMessage {
/// confirmed. A reader shows it as sending; it flips off in place when
/// the confirmed frame arrives.
pending: bool,
+ /// How an agent's reply reads as a conversation, the same boundaries the
+ /// server posts channel messages by. Empty on a user's message.
+ segments: Vec<Segment>,
+ /// What an agent's unfinished reply is doing now; absent once its turn
+ /// has ended and on a user's message.
+ phase: Option<TurnPhase>,
}
impl FoldedMessage {
/// Build the browser form of `message`, keyed to `session`.
#[must_use]
pub fn new(session: AgentSessionId, message: ModelFoldedMessage) -> Self {
+ let parts = message.parts.into_inner();
+ let closed = message.stop.is_some();
+ let (segments, phase) = if matches!(message.author, Author::Agent) {
+ (
+ crate::domain::model::segments(&parts, closed),
+ crate::domain::model::phase(&parts, closed),
+ )
+ } else {
+ (Vec::new(), None)
+ };
Self {
agent_session_id: session.to_string(),
turn: message.id.0,
author: message.author,
request_id: message.request_id.map(|id| id.to_string()),
- parts: message.parts.into_inner(),
+ parts,
stop: message.stop,
pending: message.pending,
+ segments,
+ phase,
}
}
}
diff --git a/crates/folds/agent_fold/src/inbound/wire/test.rs b/crates/folds/agent_fold/src/inbound/wire/test.rs
index 28ac812518..eb67c17340 100644
--- a/crates/folds/agent_fold/src/inbound/wire/test.rs
+++ b/crates/folds/agent_fold/src/inbound/wire/test.rs
@@ -47,7 +47,21 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
}
}],
"stop": null,
- "pending": false
+ "pending": false,
+ "segments": [{
+ "index": 0,
+ "kind": "activity",
+ "start": 0,
+ "end": 1,
+ "sealed": false,
+ "rows": [{
+ "id": "tool-1",
+ "label": "Running",
+ "detail": "ls",
+ "status": "running"
+ }]
+ }],
+ "phase": "working"
})
);
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index 8f286d522e..5180cf9ca7 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -239,6 +239,67 @@ pub enum AgentChatReplyBody {
/// The prose, as channel markdown.
markdown: String,
},
+ /// The reply's segments in order: passages as written, and the steps
+ /// between them as a node viewers of the session see live.
+ Segments {
+ /// Passages and steps, in the order the agent produced them.
+ segments: Vec<AgentReplySegment>,
+ /// Show the spinner after the segments: the turn is still running.
+ pending: bool,
+ /// A closing line the harness wrote: stopped, failed, said nothing.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ footer: Option<String>,
+ },
+}
+
+/// One segment of an agent's reply, as a channel message shows it.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum AgentReplySegment {
+ /// A passage, posted as written.
+ Prose {
+ /// The passage, as channel markdown.
+ markdown: String,
+ },
+ /// The steps between two passages.
+ Activity {
+ /// The turn whose reply this is.
+ turn: u32,
+ /// The segment's index within the reply.
+ segment: u32,
+ /// The steps as the session's fold worded them.
+ rows: Vec<AgentActivityRow>,
+ /// Whether the segment can still gain steps.
+ sealed: bool,
+ },
+}
+
+/// One step of an agent's work, for the activity node's snapshot.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+pub struct AgentActivityRow {
+ /// The tool call's id.
+ pub id: String,
+ /// What happened, as a verb phrase.
+ pub label: String,
+ /// What it happened to, when safe to show.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub detail: Option<String>,
+ /// Where it got to.
+ pub status: AgentActivityStatus,
+}
+
+/// Where one step of an agent's work got to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum AgentActivityStatus {
+ /// Started and not finished.
+ Running,
+ /// Finished successfully.
+ Completed,
+ /// Finished unsuccessfully.
+ Failed,
+ /// Still running when its turn ended.
+ Interrupted,
}
/// A chat agent's thread message in one of its states.
@@ -248,6 +309,10 @@ pub struct AgentChatReply {
/// Session the message speaks for; linked ahead of the body.
pub session_id: String,
pub body: AgentChatReplyBody,
+ /// Whether to lead with the session link. Absent means yes; a private
+ /// conversation's messages are the session and repeat no link.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub link: Option<bool>,
}
#[derive(serde::Serialize)]
diff --git a/crates/macro_db_client/migrations/20261001131042_channel_agents.sql b/crates/macro_db_client/migrations/20261001131042_channel_agents.sql
new file mode 100644
index 0000000000..335f49d63d
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001131042_channel_agents.sql
@@ -0,0 +1,20 @@
+-- An agent persona that converses in a channel. A direct conversation is a
+-- private channel between one user and one persona; a member agent converses
+-- in a shared channel. Only direct conversations are created today.
+-- Bot ids include built-in personas without a bots row, so no bot FK is used.
+-- User cleanup deletes owned channels; deleting a channel removes its agents.
+CREATE TABLE comms_channel_agents (
+ channel_id UUID NOT NULL REFERENCES comms_channels(id) ON DELETE CASCADE,
+ bot_id UUID NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('direct', 'member')),
+ -- The owner of a direct conversation; member agents have none.
+ user_id TEXT,
+ PRIMARY KEY (channel_id, bot_id),
+ CHECK ((kind = 'direct') = (user_id IS NOT NULL))
+);
+
+-- One direct conversation per user and persona, with one persona in it.
+CREATE UNIQUE INDEX comms_channel_agents_direct_pair
+ ON comms_channel_agents (user_id, bot_id) WHERE kind = 'direct';
+CREATE UNIQUE INDEX comms_channel_agents_direct_channel
+ ON comms_channel_agents (channel_id) WHERE kind = 'direct';
diff --git a/crates/macro_db_client/migrations/20261001132005_agent_conversation_sessions.sql b/crates/macro_db_client/migrations/20261001132005_agent_conversation_sessions.sql
new file mode 100644
index 0000000000..96bf789695
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001132005_agent_conversation_sessions.sql
@@ -0,0 +1,17 @@
+-- An agent's conversation in a channel runs on one session at a time.
+-- The session id is reserved before its runtime is provisioned, so the
+-- session may not exist yet and session_id deliberately has no session FK.
+-- Earlier sessions stay associated with the conversation after starting fresh.
+CREATE TABLE agent_conversation_sessions (
+ session_id UUID PRIMARY KEY,
+ channel_id UUID NOT NULL REFERENCES comms_channels(id) ON DELETE CASCADE,
+ bot_id UUID NOT NULL,
+ is_current BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE UNIQUE INDEX agent_conversation_sessions_current
+ ON agent_conversation_sessions (channel_id, bot_id) WHERE is_current;
+
+CREATE INDEX agent_conversation_sessions_history
+ ON agent_conversation_sessions (channel_id, bot_id, created_at DESC, session_id DESC);
diff --git a/crates/macro_db_client/migrations/20261001135138_direct_agent_membership_invariant.sql b/crates/macro_db_client/migrations/20261001135138_direct_agent_membership_invariant.sql
new file mode 100644
index 0000000000..8fca66a2fc
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001135138_direct_agent_membership_invariant.sql
@@ -0,0 +1,23 @@
+-- Every participant mutation path (including bot installation) preserves a
+-- direct conversation's two-principal boundary. Agents are inserted before
+-- members.
+CREATE FUNCTION enforce_direct_agent_participant() RETURNS trigger
+LANGUAGE plpgsql AS $$
+DECLARE
+ direct_user TEXT;
+ direct_bot UUID;
+BEGIN
+ SELECT user_id, bot_id INTO direct_user, direct_bot
+ FROM comms_channel_agents WHERE channel_id = NEW.channel_id AND kind = 'direct';
+
+ IF FOUND AND NEW.user_id <> direct_user AND NEW.user_id <> 'bot|' || direct_bot::TEXT THEN
+ RAISE EXCEPTION 'A direct agent conversation only permits its owner and persona'
+ USING ERRCODE = '23514', CONSTRAINT = 'direct_agent_participants';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+CREATE TRIGGER direct_agent_participants
+BEFORE INSERT OR UPDATE OF channel_id, user_id ON comms_channel_participants
+FOR EACH ROW EXECUTE FUNCTION enforce_direct_agent_participant();
diff --git a/crates/macro_db_client/migrations/20261001141902_agent_conversation_turns.sql b/crates/macro_db_client/migrations/20261001141902_agent_conversation_turns.sql
new file mode 100644
index 0000000000..cb1bc164d7
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001141902_agent_conversation_turns.sql
@@ -0,0 +1,22 @@
+-- One row per channel message an agent answers: admitted before the broker
+-- event is acknowledged, then claimed, run and reconciled in order. Two agents
+-- in one channel each keep their own turn for the same message.
+CREATE TABLE agent_conversation_turns (
+ source_message_id UUID NOT NULL,
+ bot_id UUID NOT NULL,
+ session_id UUID NOT NULL REFERENCES agent_conversation_sessions(session_id) ON DELETE CASCADE,
+ channel_id UUID NOT NULL REFERENCES comms_channels(id) ON DELETE CASCADE,
+ action_id UUID NOT NULL UNIQUE,
+ command JSONB NOT NULL,
+ state TEXT NOT NULL DEFAULT 'queued' CHECK (state IN ('queued', 'running', 'succeeded', 'failed', 'stopped', 'interrupted')),
+ in_flight JSONB,
+ outcome JSONB,
+ reply_finalized BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (source_message_id, bot_id)
+);
+
+CREATE INDEX agent_conversation_turns_pending ON agent_conversation_turns(created_at, source_message_id) WHERE state = 'queued';
+CREATE INDEX agent_conversation_turns_channel ON agent_conversation_turns(channel_id, created_at);
+CREATE INDEX agent_conversation_turns_replies ON agent_conversation_turns(updated_at) WHERE outcome IS NOT NULL AND NOT reply_finalized;
diff --git a/crates/macro_db_client/migrations/20261001145822_agent_conversation_settings.sql b/crates/macro_db_client/migrations/20261001145822_agent_conversation_settings.sql
new file mode 100644
index 0000000000..1dee25d0aa
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261001145822_agent_conversation_settings.sql
@@ -0,0 +1,4 @@
+CREATE TABLE agent_conversation_settings (
+ session_id UUID PRIMARY KEY REFERENCES agent_conversation_sessions(session_id) ON DELETE CASCADE,
+ settings JSONB NOT NULL
+);
diff --git a/crates/macro_db_client/migrations/20261010152426_index_agent_conversation_turns_by_session.sql b/crates/macro_db_client/migrations/20261010152426_index_agent_conversation_turns_by_session.sql
new file mode 100644
index 0000000000..d4a1b96d07
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261010152426_index_agent_conversation_turns_by_session.sql
@@ -0,0 +1,4 @@
+-- Claims, recovery and Start fresh look up one session's unfinished turns
+-- while holding that session's advisory lock, so the lookup must not scan
+-- every conversation's history.
+CREATE INDEX agent_conversation_turns_session ON agent_conversation_turns(session_id, state, created_at, source_message_id);
diff --git a/crates/macro_db_client/migrations/20261010153219_keep_agent_conversation_reply_segments.sql b/crates/macro_db_client/migrations/20261010153219_keep_agent_conversation_reply_segments.sql
new file mode 100644
index 0000000000..4a1e9eb7bc
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261010153219_keep_agent_conversation_reply_segments.sql
@@ -0,0 +1,4 @@
+-- What a finished turn's reply shows, saved with its outcome so any replica
+-- can post the reply again exactly, including after the one that watched the
+-- turn has lost it.
+ALTER TABLE agent_conversation_turns ADD COLUMN reply_segments JSONB;
diff --git a/crates/macro_db_client/migrations/20261012203716_index_running_agent_conversation_turns.sql b/crates/macro_db_client/migrations/20261012203716_index_running_agent_conversation_turns.sql
new file mode 100644
index 0000000000..92155a6cba
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261012203716_index_running_agent_conversation_turns.sql
@@ -0,0 +1,8 @@
+-- no-transaction
+-- Every replica's recovery looks for turns left running by a replica that is
+-- gone, oldest first, every ten seconds; without this index it reads every
+-- turn ever answered.
+-- Must stay a single statement: sqlx sends no-transaction migrations as one
+-- batch, and CONCURRENTLY cannot run inside a transaction.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_conversation_turns_running
+ ON agent_conversation_turns (updated_at) WHERE state = 'running';
diff --git a/crates/macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.down.sql b/crates/macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.down.sql
new file mode 100644
index 0000000000..2fc6956223
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.down.sql
@@ -0,0 +1,9 @@
+-- Before reverting service code, restore visibility of DM contexts that were
+-- hidden after the default-off rollout gate was explicitly enabled.
+UPDATE agent_session s SET list_hidden = FALSE
+FROM agent_conversation_sessions c
+JOIN comms_channel_agents a ON a.channel_id = c.channel_id AND a.bot_id = c.bot_id AND a.kind = 'direct'
+WHERE s.id = c.session_id;
+DROP TRIGGER agent_session_legacy_warm_write ON agent_session;
+DROP FUNCTION agent_session_legacy_warm_write();
+ALTER TABLE agent_session DROP COLUMN for_warming;
diff --git a/crates/macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.up.sql b/crates/macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.up.sql
new file mode 100644
index 0000000000..85da05e5b9
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261015022720_separate_warm_session_lifecycle.up.sql
@@ -0,0 +1,24 @@
+-- Visibility and speculative runtime lifecycle are separate. No DM visibility
+-- changes during migration: old reapers still use the hidden/unthreaded predicate.
+ALTER TABLE agent_session ADD COLUMN for_warming BOOLEAN;
+UPDATE agent_session s
+SET for_warming = s.list_hidden AND s.thread_id IS NULL
+ AND NOT EXISTS (SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = s.id);
+
+-- Older writers omit the marker; older claimants only clear list_hidden.
+CREATE FUNCTION agent_session_legacy_warm_write() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF NEW.for_warming IS NULL THEN
+ NEW.for_warming := NEW.list_hidden AND NEW.thread_id IS NULL
+ AND NOT EXISTS (SELECT 1 FROM agent_conversation_sessions c WHERE c.session_id = NEW.id);
+ END IF;
+ IF NOT NEW.list_hidden OR NEW.thread_id IS NOT NULL THEN
+ NEW.for_warming := FALSE;
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER agent_session_legacy_warm_write
+BEFORE INSERT OR UPDATE OF list_hidden, thread_id ON agent_session FOR EACH ROW
+EXECUTE FUNCTION agent_session_legacy_warm_write();
+ALTER TABLE agent_session ALTER COLUMN for_warming SET NOT NULL;
diff --git a/crates/macro_db_client/migrations/20261015025624_index_warm_session_expiry.down.sql b/crates/macro_db_client/migrations/20261015025624_index_warm_session_expiry.down.sql
new file mode 100644
index 0000000000..5a06129738
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261015025624_index_warm_session_expiry.down.sql
@@ -0,0 +1 @@
+DROP INDEX agent_session_warm_expiry;
diff --git a/crates/macro_db_client/migrations/20261015025624_index_warm_session_expiry.up.sql b/crates/macro_db_client/migrations/20261015025624_index_warm_session_expiry.up.sql
new file mode 100644
index 0000000000..281a99ec6e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261015025624_index_warm_session_expiry.up.sql
@@ -0,0 +1,4 @@
+-- Reapers visit only speculative hidden/unthreaded sessions, oldest first.
+-- No existing session index covers created_at or this expiry predicate.
+CREATE INDEX agent_session_warm_expiry ON agent_session (created_at)
+WHERE for_warming AND list_hidden AND thread_id IS NULL;
diff --git a/crates/messages/src/domain/api.rs b/crates/messages/src/domain/api.rs
index 8a4b6d3f55..a046b4b142 100644
--- a/crates/messages/src/domain/api.rs
+++ b/crates/messages/src/domain/api.rs
@@ -102,6 +102,20 @@ pub trait MessageCommands: Send + Sync + 'static {
active: bool,
nonce: Option<String>,
) -> Result<(), MessageError>;
+ /// Publish an agent session typing through the bot that speaks for it.
+ ///
+ /// Defaults to plain typing, which drops the session: an adapter that
+ /// cannot carry it still shows the bot typing.
+ async fn agent_typing(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ root: Option<Uuid>,
+ active: bool,
+ agent: AgentTyping,
+ ) -> Result<(), MessageError> {
+ let _ = agent;
+ self.typing(access, root, active, None).await
+ }
/// Update entity discussion state or detach removed document Markdown text.
async fn patch_thread(
&self,
@@ -227,6 +241,15 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageCommands for Message
) -> Result<(), MessageError> {
MessageService::typing(self, access, root, active, nonce).await
}
+ async fn agent_typing(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ root: Option<Uuid>,
+ active: bool,
+ agent: AgentTyping,
+ ) -> Result<(), MessageError> {
+ MessageService::agent_typing(self, access, root, active, agent).await
+ }
async fn patch_thread(
&self,
access: EntityAccessReceipt<MessageWrite>,
diff --git a/crates/messages/src/domain/effects/test.rs b/crates/messages/src/domain/effects/test.rs
index 2ebffad169..accab477be 100644
--- a/crates/messages/src/domain/effects/test.rs
+++ b/crates/messages/src/domain/effects/test.rs
@@ -64,6 +64,7 @@ async fn typing_only_reaches_the_parent_transport() {
.publish(event(MessageChange::Typing {
thread_id: None,
active: true,
+ agent: None,
}))
.await
.unwrap();
diff --git a/crates/messages/src/domain/ports.rs b/crates/messages/src/domain/ports.rs
index ad584a3e5b..1370217229 100644
--- a/crates/messages/src/domain/ports.rs
+++ b/crates/messages/src/domain/ports.rs
@@ -289,9 +289,41 @@ pub enum MessageChange {
thread_id: Option<Uuid>,
/// Whether the user is currently typing.
active: bool,
+ /// Present when an agent session is typing through the bot that
+ /// speaks for it. Names the session, so a viewer who can read it can
+ /// show the turn live in place of the bare indicator.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ agent: Option<AgentTyping>,
},
}
+/// An agent session typing through its bot.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct AgentTyping {
+ /// The session whose turn the bot is speaking for.
+ pub session_id: Uuid,
+ /// What the agent is doing. Deliberately coarse: a typing event reaches
+ /// everyone in the conversation, and which tool runs on what is for
+ /// viewers who can read the session itself.
+ pub phase: AgentTypingPhase,
+}
+
+/// What a typing agent is doing.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum AgentTypingPhase {
+ /// Working out what to do, or between steps.
+ Thinking,
+ /// Writing a reply.
+ Writing,
+ /// Using a tool.
+ Working,
+ /// Waiting on someone to answer a question or approve an action.
+ Waiting,
+}
+
/// Persisted reaction state and whether this operation changed membership.
pub struct ReactionResult {
/// Current message, including its reactions.
diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rs
index 3e382e7b32..79de613e5f 100644
--- a/crates/messages/src/domain/service.rs
+++ b/crates/messages/src/domain/service.rs
@@ -206,6 +206,36 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
root_id: Option<Uuid>,
active: bool,
nonce: Option<String>,
+ ) -> Result<(), MessageError> {
+ self.publish_typing(access, root_id, active, nonce, None)
+ .await
+ }
+
+ /// Publish an agent session typing through the bot that speaks for it.
+ /// Only a bot capability may say a session is typing: a person's typing
+ /// never names one.
+ #[tracing::instrument(err, skip(self, access))]
+ pub async fn agent_typing(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ root_id: Option<Uuid>,
+ active: bool,
+ agent: AgentTyping,
+ ) -> Result<(), MessageError> {
+ if !matches!(access.auth(), EntityAccessAuth::Bot(_)) {
+ return Err(MessageError::Forbidden);
+ }
+ self.publish_typing(access, root_id, active, None, Some(agent))
+ .await
+ }
+
+ async fn publish_typing(
+ &self,
+ access: EntityAccessReceipt<MessageWrite>,
+ root_id: Option<Uuid>,
+ active: bool,
+ nonce: Option<String>,
+ agent: Option<AgentTyping>,
) -> Result<(), MessageError> {
let parent = parent_from_receipt(&access)?;
let actor = actor_from_receipt(&access, &parent)?;
@@ -220,6 +250,7 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
change: MessageChange::Typing {
thread_id: root_id,
active,
+ agent,
},
})
.await;
@@ -438,6 +469,16 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {
input.attachments.as_deref().unwrap_or_default(),
)
.await?;
+ // Reconciliation may repeat a bot's final reply after a process died
+ // between patching it and recording success. Identical content must
+ // not produce another edit event or completion notification.
+ if actor.as_bot().is_some()
+ && input.content == current.content
+ && input.mentions == current.mentions
+ && input.attachments.is_none()
+ {
+ return Ok(current);
+ }
let notification_policy = input.notification_policy;
let nonce = input.nonce.clone();
let mentions = self.resolve_mentions(&parent, &input.mentions).await?;
diff --git a/crates/messages/src/domain/service/test.rs b/crates/messages/src/domain/service/test.rs
index c97d4a7ff9..55b2138d5b 100644
--- a/crates/messages/src/domain/service/test.rs
+++ b/crates/messages/src/domain/service/test.rs
@@ -1174,6 +1174,106 @@ async fn bot_posts_and_edits_extract_mentions_and_preserve_trusted_attribution_a
}
}
+#[tokio::test]
+async fn reconciling_an_unchanged_bot_reply_does_not_publish_a_second_completion() {
+ let mut repo = fixture();
+ let bot = bot_id::MACRO_AI_BOT_ID;
+ repo.message.sender_id = ChannelSender::new_from_bot(bot);
+ let receipt = EntityAccessReceipt::try_new_bot(
+ bot.into_storage_id(),
+ entity_access::domain::models::BotReceiptScope::User {
+ acting_user: "macro|[email protected]".to_string().try_into().unwrap(),
+ },
+ access("macro|[email protected]", "doc", AccessLevel::Comment)
+ .entity()
+ .clone(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ )
+ .unwrap();
+ let events = Events::default();
+ let service = MessageService::new(repo.clone(), events.clone());
+ let result = service
+ .patch(
+ receipt,
+ repo.message.id,
+ MessagePatch {
+ content: Some(repo.message.content.clone()),
+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.id, repo.message.id);
+ assert!(repo.edits.lock().unwrap().is_empty());
+ assert!(events.0.lock().unwrap().is_empty());
+}
+
+fn bot_receipt() -> EntityAccessReceipt<MessageWrite> {
+ EntityAccessReceipt::try_new_bot(
+ bot_id::MACRO_AI_BOT_ID.into_storage_id(),
+ entity_access::domain::models::BotReceiptScope::User {
+ acting_user: "macro|[email protected]".to_string().try_into().unwrap(),
+ },
+ access("macro|[email protected]", "doc", AccessLevel::Comment)
+ .entity()
+ .clone(),
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Comment,
+ },
+ )
+ .unwrap()
+}
+
+#[tokio::test]
+async fn an_agent_types_through_its_bot_naming_the_session() {
+ let repo = fixture();
+ let events = Events::default();
+ let service = MessageService::new(repo, events.clone());
+ let agent = AgentTyping {
+ session_id: Uuid::from_u128(77),
+ phase: AgentTypingPhase::Working,
+ };
+ service
+ .agent_typing(bot_receipt(), None, true, agent)
+ .await
+ .unwrap();
+ let published = events.0.lock().unwrap();
+ assert!(
+ matches!(
+ published.as_slice(),
+ [MessageEvent {
+ actor,
+ change: MessageChange::Typing { thread_id: None, active: true, agent: Some(sent) },
+ ..
+ }] if actor.starts_with("bot|") && *sent == agent
+ ),
+ "{published:?}"
+ );
+}
+
+#[tokio::test]
+async fn a_person_cannot_say_an_agent_session_is_typing() {
+ let repo = fixture();
+ let events = Events::default();
+ let service = MessageService::new(repo, events.clone());
+ let result = service
+ .agent_typing(
+ access("macro|[email protected]", "doc", AccessLevel::Comment),
+ None,
+ true,
+ AgentTyping {
+ session_id: Uuid::from_u128(77),
+ phase: AgentTypingPhase::Thinking,
+ },
+ )
+ .await;
+ assert!(matches!(result, Err(MessageError::Forbidden)));
+ assert!(events.0.lock().unwrap().is_empty());
+}
+
#[derive(Clone)]
struct StrictRepo {
inner: Repo,
diff --git a/crates/messages/src/outbound/broker/test.rs b/crates/messages/src/outbound/broker/test.rs
index 169b71e9e0..177be522d7 100644
--- a/crates/messages/src/outbound/broker/test.rs
+++ b/crates/messages/src/outbound/broker/test.rs
@@ -209,6 +209,7 @@ async fn deletions_publish_and_reactions_typing_and_thread_state_stay_off_the_to
MessageChange::Typing {
thread_id: Some(ROOT),
active: true,
+ agent: None,
},
MessageChange::ThreadUpdated {
state: crate::domain::models::ThreadState {
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index a4c2b71665..a8127a2fb8 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -240,6 +240,15 @@ mod tests {
assert!(session.contains("decided per"));
}
+ #[test]
+ fn session_tool_use_prompt_treats_a_private_conversation_like_the_session_view() {
+ // A DM with the agent is read live: its questions and review cards
+ // appear there, so the thread rule does not apply to it.
+ let session = SESSION_TOOL_USE_PROMPT.to_string();
+ assert!(session.contains("private conversation with the user is the exception"));
+ assert!(session.contains("like one typed in the agent session view"));
+ }
+
#[test]
fn session_tool_use_prompt_keeps_the_thread_mechanics_away_from_the_user() {
// The thread rule explains review cards and the session view so the
diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rs
index 9af27456e4..a22cac8f82 100644
--- a/crates/prompt/src/user_tools.rs
+++ b/crates/prompt/src/user_tools.rs
@@ -103,6 +103,11 @@ static SESSION_INSTRUCTIONS: &str = r##"- Booking links use conversational confi
create - look good?" or "Here's the email - want me to send it?" - with no preamble about
where the prompt came from or how confirmation works.
+- Your private conversation with the user is the exception. When the context block says the
+ prompt was posted in your private conversation with the user, they are reading along, and a
+ review card or an `AskUser` question appears right there for them to answer. Treat that prompt
+ like one typed in the agent session view.
+
- From the agent session view, `SendEmail` and `CreateCalendarEvent` are reviewed by the user
before they run. Calling one opens a review card in the session, the turn waits while the user
edits, confirms or declines, and the tool then returns what happened: the sent email or created
@@ -127,8 +132,9 @@ static SESSION_INTENT: &str = "The model checks where the newest prompt came fro
user tool: from a channel or document thread it states the whole email or event verbatim in its \
reply, asks, and sends or creates only on the user's approving reply through SendConfirmedEmail \
or CreateConfirmedCalendarEvent - without ever explaining the session, review card or thread \
-mechanics to the user; from the session view it calls SendEmail or CreateCalendarEvent and lets \
-the review card be the confirmation, never asking for confirmation in prose first.";
+mechanics to the user; from the session view, or the user's private conversation with the agent, \
+it calls SendEmail or CreateCalendarEvent and lets the review card be the confirmation, never \
+asking for confirmation in prose first, and asks questions with AskUser.";
/// The user-tools prompt section for an agent session, whose in-process
/// agent finishes user tools in the turn through a review elicitation.
diff --git a/crates/soup/src/outbound/pg_soup_repo/agent_session.rs b/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
index 5a78669b7d..df0d7d102f 100644
--- a/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/agent_session.rs
@@ -107,7 +107,7 @@ pub(super) async fn cursor_soup(
query.push(" AND (");
push_filter(&mut query, filter);
query.push(")");
- // Inline @macro sessions (`list_hidden`) are absent from broad lists. A
+ // Hidden inline mentions and DM contexts are absent from broad lists. A
// query that names the session still returns it, so favorites and direct
// id lookups keep working.
query.push(" AND (s.list_hidden = FALSE OR s.id = ANY(");
@@ -262,7 +262,7 @@ fn sort_sql(sort: SimpleSortMethod) -> &'static str {
/// Session ids the query asked for by name, ignoring ids under `NOT`.
/// Those stay visible even when the session is hidden from broad lists.
-fn explicitly_named_ids(expression: &Expr<AgentSessionLiteral>) -> Vec<Uuid> {
+pub(super) fn explicitly_named_ids(expression: &Expr<AgentSessionLiteral>) -> Vec<Uuid> {
fn walk(expression: &Expr<AgentSessionLiteral>, negated: bool, ids: &mut Vec<Uuid>) {
match expression {
Expr::Literal(AgentSessionLiteral::Id(id)) if !negated => ids.push(*id),
diff --git a/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs b/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs
index c6ce05a504..92cca053a5 100644
--- a/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/agent_session/test.rs
@@ -457,3 +457,64 @@ async fn hidden_sessions_stay_out_of_broad_lists(pool: PgPool) -> anyhow::Result
Ok(())
}
+
+/// Hidden unthreaded DM contexts use the same broad-list visibility boundary
+/// as inline mentions, without losing owner access by ID.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn hidden_dm_contexts_are_omitted_from_home_and_agents_but_open_by_id(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let fixture = seed(&pool).await?;
+ let dm = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO comms_channels (id, channel_type, owner_id) VALUES ($1, 'direct_message', $2)",
+ dm,
+ OWNER
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!("INSERT INTO comms_channel_participants (channel_id, user_id, role) VALUES ($1, $2, 'owner')", dm, OWNER)
+ .execute(&pool).await?;
+ sqlx::query!("INSERT INTO comms_channel_agents (channel_id, bot_id, kind, user_id) VALUES ($1, $2, 'direct', $3)", dm, BOT_ID, OWNER)
+ .execute(&pool).await?;
+ sqlx::query!("INSERT INTO agent_conversation_sessions (session_id, channel_id, bot_id) VALUES ($1, $2, $3)", fixture.shared, dm, BOT_ID)
+ .execute(&pool).await?;
+ // The session domain's enabled policy persists these two flags.
+ sqlx::query!(
+ "UPDATE agent_session SET list_hidden = TRUE, for_warming = FALSE WHERE id = $1",
+ fixture.shared
+ )
+ .execute(&pool)
+ .await?;
+ for literal in [
+ AgentSessionLiteral::Include,
+ AgentSessionLiteral::Owner(Owner::from_principal_str(OWNER)?),
+ ] {
+ let listed = cursor_soup(&pool, request(OWNER, Some(Expr::val(literal)))).await?;
+ assert_eq!(ids(&listed), vec![fixture.private]);
+ }
+ let named = cursor_soup(
+ &pool,
+ request(
+ OWNER,
+ Some(Expr::val(AgentSessionLiteral::Id(fixture.shared))),
+ ),
+ )
+ .await?;
+ assert_eq!(ids(&named), vec![fixture.shared]);
+ let entities = [EntityType::AgentSession.with_entity_string(fixture.shared.to_string())];
+ let opened = by_ids(
+ &pool,
+ AdvancedSortParams {
+ entities: &entities,
+ user_id: MacroUserIdStr::parse_from_str(OWNER)?,
+ },
+ )
+ .await?;
+ assert_eq!(ids(&opened), vec![fixture.shared]);
+ let channel = sqlx::query_scalar!("SELECT id FROM comms_channels WHERE id = $1", dm)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(channel, dm);
+ Ok(())
+}
diff --git a/crates/soup/src/outbound/pg_soup_repo/notified.rs b/crates/soup/src/outbound/pg_soup_repo/notified.rs
index 107ebd1d2f..6cef7318ca 100644
--- a/crates/soup/src/outbound/pg_soup_repo/notified.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/notified.rs
@@ -133,7 +133,21 @@ pub(super) fn foreign_entity_gate(filter: Option<&EntityFilterAst>) -> String {
/// Agent sessions are authorized through `entity_access`, whose sources are
/// the same user / channel / team ids the query's `user_source_ids` CTE
/// already collects - the predicate the agent-session leg's own queries use.
-pub(super) fn agent_session_gate() -> String {
+pub(super) fn agent_session_gate(filter: Option<&EntityFilterAst>) -> String {
+ // IDs come from the typed UUID AST, never raw request text. `only` is an
+ // internal refresh constraint and deliberately does not bypass visibility.
+ let named = filter
+ .and_then(|filter| filter.agent_session_filter.as_deref())
+ .map(super::agent_session::explicitly_named_ids)
+ .unwrap_or_default()
+ .into_iter()
+ .map(|id| format!("{ID_SQL}::uuid = '{id}'::uuid"))
+ .collect::<Vec<_>>();
+ let named = if named.is_empty() {
+ "FALSE".to_owned()
+ } else {
+ named.join(" OR ")
+ };
uuid_guarded(
ID_SQL,
format!(
@@ -142,6 +156,11 @@ pub(super) fn agent_session_gate() -> String {
WHERE ea.entity_id = {ID_SQL}::uuid
AND ea.entity_type = 'agent_session'
AND ea.source_id IN (SELECT source_id FROM user_source_ids)
+ ) AND (
+ ({named}) OR NOT EXISTS (
+ SELECT 1 FROM agent_session s
+ WHERE s.id = {ID_SQL}::uuid AND s.list_hidden
+ )
)"#
),
)
@@ -239,7 +258,7 @@ fn build_query(filter: Option<&EntityFilterAst>) -> String {
email_gate = email_gate(ID_SQL, filter),
calendar_event_gate = calendar_event_gate(filter),
foreign_entity_gate = foreign_entity_gate(filter),
- agent_session_gate = agent_session_gate(),
+ agent_session_gate = agent_session_gate(filter),
)
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/notified/test.rs b/crates/soup/src/outbound/pg_soup_repo/notified/test.rs
index b128c992cf..809811399c 100644
--- a/crates/soup/src/outbound/pg_soup_repo/notified/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/notified/test.rs
@@ -12,6 +12,7 @@ use std::sync::Arc;
use uuid::Uuid;
mod explain;
+mod hidden_sessions;
mod latest;
const USER_1: &str = "macro|[email protected]";
diff --git a/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs b/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs
new file mode 100644
index 0000000000..d863c65af8
--- /dev/null
+++ b/crates/soup/src/outbound/pg_soup_repo/notified/test/hidden_sessions.rs
@@ -0,0 +1,125 @@
+use super::*;
+use crate::domain::models::{WorkFeedCandidateRequest, WorkFeedSoupMode};
+use crate::outbound::pg_soup_repo::work_feed::work_feed_soup_page;
+
+fn work_request<'a>(
+ filter: &'a EntityFilterAst,
+ sources: &'a [SourceId],
+ mode: WorkFeedSoupMode,
+ only: Option<&'a [model_entity::Entity<'static>]>,
+) -> WorkFeedCandidateRequest<'a> {
+ WorkFeedCandidateRequest {
+ user_id: MacroUserIdStr::parse_from_str(USER_1).unwrap(),
+ limit: 50,
+ mode,
+ after: None,
+ types: &[EntityType::AgentSession],
+ filter: Some(filter),
+ link_ids: &[],
+ foreign_entity_sources: sources,
+ hydratable: EVERYTHING,
+ only,
+ }
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../../../fixtures", scripts("notified_at")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn hidden_contexts_with_notifications_and_activity_stay_out_of_broad_feeds(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let (mine, _) = seed_agent_sessions(&pool).await?;
+ let sources = sources();
+ let include = EntityFilterAst {
+ agent_session_filter: Some(Arc::new(Expr::val(AgentSessionLiteral::Include))),
+ ..Default::default()
+ };
+ sqlx::query!(
+ "INSERT INTO activity_events (id, actor_id, subject_id, action, entity_type, entity_id, occurred_at) VALUES ($1, $2, $2, 'edited', 'agent_session', $3, '2024-06-01 10:22:00+00')",
+ Uuid::now_v7(), USER_1, mine.to_string(),
+ ).execute(&pool).await?;
+ let before = work_feed_soup_page(
+ &pool,
+ work_request(&include, &sources, WorkFeedSoupMode::Work, None),
+ )
+ .await?;
+ assert_eq!(before.len(), 1);
+ assert!(before[0].attention_at.is_some() && before[0].touched_at.is_some());
+ sqlx::query!(
+ "UPDATE agent_session SET list_hidden = TRUE, for_warming = FALSE WHERE id = $1",
+ mine
+ )
+ .execute(&pool)
+ .await?;
+ let notified =
+ notified_soup_page(&pool, req(Some(&include), &[], &sources, EVERYTHING)).await?;
+ assert!(!keys(&notified).contains(&(EntityType::AgentSession, mine.to_string())));
+ for mode in [WorkFeedSoupMode::Work, WorkFeedSoupMode::Attention] {
+ assert!(
+ work_feed_soup_page(&pool, work_request(&include, &sources, mode, None))
+ .await?
+ .is_empty()
+ );
+ }
+ let only = [EntityType::AgentSession.with_entity_string(mine.to_string())];
+ assert!(
+ work_feed_soup_page(
+ &pool,
+ work_request(&include, &sources, WorkFeedSoupMode::Work, Some(&only))
+ )
+ .await?
+ .is_empty(),
+ "internal by-ID recomputation does not reopen broad-list visibility"
+ );
+ let named = EntityFilterAst {
+ agent_session_filter: Some(Arc::new(Expr::val(AgentSessionLiteral::Id(mine)))),
+ ..Default::default()
+ };
+ assert_eq!(
+ work_feed_soup_page(
+ &pool,
+ work_request(&named, &sources, WorkFeedSoupMode::Work, None)
+ )
+ .await?
+ .len(),
+ 1
+ );
+ let notified = notified_soup_page(&pool, req(Some(&named), &[], &sources, EVERYTHING)).await?;
+ assert!(keys(&notified).contains(&(EntityType::AgentSession, mine.to_string())));
+ // Favorites add positive ID constraints to the view's existing filter.
+ let favorite = EntityFilterAst {
+ agent_session_filter: Some(Arc::new(Expr::And(
+ Box::new(Expr::val(AgentSessionLiteral::Include)),
+ Box::new(Expr::val(AgentSessionLiteral::Id(mine))),
+ ))),
+ ..Default::default()
+ };
+ assert_eq!(
+ work_feed_soup_page(
+ &pool,
+ work_request(&favorite, &sources, WorkFeedSoupMode::Work, None)
+ )
+ .await?
+ .len(),
+ 1
+ );
+ let excluded = EntityFilterAst {
+ agent_session_filter: Some(Arc::new(Expr::And(
+ Box::new(Expr::val(AgentSessionLiteral::Include)),
+ Box::new(Expr::Not(Box::new(Expr::val(AgentSessionLiteral::Id(
+ mine,
+ ))))),
+ ))),
+ ..Default::default()
+ };
+ assert!(
+ work_feed_soup_page(
+ &pool,
+ work_request(&excluded, &sources, WorkFeedSoupMode::Work, None)
+ )
+ .await?
+ .is_empty()
+ );
+ Ok(())
+}
diff --git a/crates/soup/src/outbound/pg_soup_repo/work_feed.rs b/crates/soup/src/outbound/pg_soup_repo/work_feed.rs
index cc67a13588..1142b7fad1 100644
--- a/crates/soup/src/outbound/pg_soup_repo/work_feed.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/work_feed.rs
@@ -111,7 +111,7 @@ fn build_query(req: &WorkFeedCandidateRequest<'_>) -> String {
email_gate = email_gate(ID_SQL, filter),
calendar_event_gate = calendar_event_gate(filter),
foreign_entity_gate = foreign_entity_gate(filter),
- agent_session_gate = agent_session_gate(),
+ agent_session_gate = agent_session_gate(filter),
)
}
diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rs
index 352a1d9d0f..2c5c54bb02 100644
--- a/crates/trigger_context/src/lib.rs
+++ b/crates/trigger_context/src/lib.rs
@@ -22,6 +22,10 @@ pub enum TriggerContext {
Mentioned(DiscussionContext),
/// A further message in the discussion of a session that is already running.
FollowUp(FollowUpContext),
+ /// A message in the agent's private conversation with the person, who
+ /// reads the reply there as it is written. Earlier turns are the
+ /// session's own history, so the discussion carries no channel activity.
+ Conversation(DiscussionContext),
/// The agent was assigned a task.
TaskAssigned(TaskAssignedContext),
/// Someone opened the session from the composer. Their prompt arrives
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 5a7d2334e7..7f524a441d 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -7,7 +7,7 @@
3. For a team channel, click `Create`. For a private channel, select `Private — only specific people` and click `Create`. Creation navigates to the channel (as a split pane: `.../channel/<uuid>`); a system row `Channel <name> created` appears.
4. Step 3 of 3 is an optional invite dialog for either channel type. The recipient combobox searches people and saved agents by name; it also accepts complete email addresses. Select a suggestion or press **Enter** to tokenize it. An unknown complete email appears as **Invite** with a paper airplane icon. Raw text left in the input is not submitted. Click `Add` when recipients are selected, or `Skip for now` to finish without invitees. Selected agents are added through the channel's agent membership endpoint. For team channels, `Automatically add teammates` defaults on; turning it off leaves the channel discoverable without automatically adding current or future teammates. The switch choice is applied when the invite dialog is finished or closed.
-Team channels are always discoverable to the team. Private channels can only be viewed or joined by invitation. A DM is a channel between two users.
+Team channels are always discoverable to the team. Private channels can only be viewed or joined by invitation. A DM is a private conversation between two people, or between one person and an agent persona.
An external email can be selected as a channel participant. For an unregistered recipient, clicking `Add` sends an email invite.
The first message in a DM to an unregistered recipient sends an email saying
@@ -17,6 +17,99 @@ Named-channel invites still show `#<channel name>` and **Join channel**.
Verify both emails in local Mailpit using distinct, unregistered test addresses;
repeat with a plus-addressed DM recipient to check the email-name fallback.
+## Private conversations with an agent
+
+Agent DM discovery is enabled with the local/environment flag
+`VITE_ENABLE_AGENT_DMS=true`; it defaults off and has no PostHog flag. Set it
+before starting Vite or building the frontend. Disabling discovery does not
+delete existing conversations or cancel their work.
+
+Choose an agent in **Create → Message**, or click **Message** in its settings or
+bot profile. The picker offers your agents, eligible team agents, and Macro.
+Choosing an agent removes other recipients. Reopening the same persona returns
+to your existing private channel. Team ownership of an agent does not share
+your DM with teammates. Calls and additional participants are unavailable.
+
+With the backend rollout switch enabled, the backing context stays out of the
+standalone **Agents** and **Home** session lists, including earlier contexts
+and contexts started fresh through the API.
+The DM remains in Channels/DMs. Opening its session by ID still works for an
+authorized reader, including streaming, questions, approvals, and Stop. Verify
+that an ordinary standalone session still appears in Agents/Home, the DM stays
+available in Channels, and reopening the DM resumes the same context.
+
+DM session hiding has a separate backend rollout switch, initially disabled.
+Deploy the warm-marker migration and all updated harness replicas first; once
+no old warm reapers remain, set `HIDE_AGENT_DM_SESSIONS=true` for
+agent-harness-service and redeploy.
+New contexts are hidden immediately; a bounded startup/60-second backfill also
+hides existing contexts, including ones created by a replica still running with
+the switch off. The frontend discovery flag alone does not gate existing DMs
+or API callers. Until this backend switch is enabled, DM contexts retain their
+previous visibility. Before rolling back to code with the old warm predicate,
+restore DM visibility by reverting the migration before starting old service
+code; merely disabling the switch does not unhide existing contexts.
+Updated claim and cleanup require `for_warming` as well as hidden/unthreaded
+state, and exclude conversation reservations; genuine
+speculative sessions still expire normally.
+
+Send normally: no `@` mention is needed. Attachments, references, and quoted
+messages use the channel composer. While the agent works, a typing row with its
+avatar sits under the newest message: `<name> is thinking`, `is typing`,
+`is working`, or `is waiting for an answer`. Below that row, the owner sees the
+passage being written as it streams. They also see any live question or
+permission request and **Stop**, which cancels the active turn. Answer those
+controls to continue. If **Stop** fails, a failure toast appears and the control
+becomes available again so you can retry.
+
+The reply is posted as ordinary messages while the turn runs. Each finished
+passage becomes a message. The steps taken between passages show inside the
+message as compact rows: a status icon (spinner, check, cross, or warning for
+interrupted), a label such as `Ran`, `Read`, `Edited`, or `Searching`, and a
+short detail like the command or file name for readers with session access.
+Stored activity snapshots keep the status and label but omit commands and tool
+input details, in both shared threads and DMs. A long run shows its latest six
+steps behind an `N earlier steps` control. Rows tick live while the run is
+open, then freeze
+into the snapshot saved in the message. Readers without session access always
+see that snapshot. Only the turn's last message notifies. Previews and search
+quote the passages, not the steps. Typing refreshes every 3 seconds and clears
+on its own if the agent's replica dies. Follow-up messages queue in order, and
+the bar above the composer counts them (`1 queued`). Editing a sent message
+does not invoke the agent again. A reply inside a thread is not part of the
+conversation: the agent answers it only when mentioned there, in the thread,
+as in any channel.
+
+Each failed, stopped, or interrupted source message has its own **Retry message**
+action in the current context. Retry is explicit because an interrupted attempt
+may already have performed an external action. Refreshing or reopening the
+channel does not rerun completed messages. A disconnected live display offers
+**Reconnect** without issuing another prompt.
+
+The conversation has no control for resetting the agent's context; it
+continues in one context. A context keeps the persona instructions, model,
+tools, and permission choice it started with, across reconnects; later persona
+edits do not reach it. A
+harness operator can still revoke permission bypass. Contexts started earlier
+through the API stay marked by a divider before their first message.
+
+If access to the persona is revoked or the persona is deleted, the transcript
+remains readable and the composer explains that the agent is unavailable. New
+prompts, retries, and answers to pending approvals require current access.
+
+For rollout verification, cover a private persona, a team persona as two
+different users, simultaneous opens, queued follow-ups, reload during a turn
+(the typing row and live steps return without a duplicate reply), a multi-step
+turn whose steps tick from running to done, attachments, an inline question,
+an approval, and Stop/Retry.
+Check both desktop and a narrow viewport. Search the Channels view by persona
+name to reopen older DMs, including ones outside the currently loaded page.
+Harness traces use `macro.event.type=agent_trigger.conversation_message` and
+`agent.session.id`; the durable turn journal distinguishes queued, running,
+succeeded, failed, stopped, and interrupted attempts. Check completion latency,
+failed/interrupted turns, queue age, and duplicate source admissions during
+internal rollout. Model usage continues through the existing session metering.
+
## Imported Slack history
Import starts from the **Import from Slack** chip below the Chat sidebar tabs,
diff --git a/docs/agent-guide/home.md b/docs/agent-guide/home.md
index 6afe30f262..03e40fd0b4 100644
--- a/docs/agent-guide/home.md
+++ b/docs/agent-guide/home.md
@@ -94,6 +94,13 @@ working. A coding session adds a second line with repository, captured working
branch (when available), and PR number/status. Non-coding sessions stay on one
line. Their timestamps and unread dots stay visible. Missing repository metadata
is omitted.
+Once `HIDE_AGENT_DM_SESSIONS` is enabled after the warm-marker rollout, agent
+DM contexts stay out of broad Agents/Home lists, including work-feed and
+notification-driven candidates. Prior notifications or activity must not bring
+them back. The DM remains in Channels/DMs; authorized direct session links and
+explicitly saved favorites still open their context. Verify this alongside an
+ordinary standalone session, which remains listed.
+
The Agents workspace uses a single left dot for activity and unread state in
place of the sparkle. Opening a loaded session from Home or Agents marks its
notifications read after the viewing delay, including notifications arriving
diff --git a/packages/lexical-core/decoratorRegistry.ts b/packages/lexical-core/decoratorRegistry.ts
index ba7e6ae8ad..42f94ac06d 100644
--- a/packages/lexical-core/decoratorRegistry.ts
+++ b/packages/lexical-core/decoratorRegistry.ts
@@ -1,4 +1,8 @@
import type { Klass, LexicalNode } from 'lexical';
+import type {
+ AgentActivityDecoratorProps,
+ AgentActivityNode,
+} from './nodes/AgentActivityNode';
import type {
AgentContextDecoratorProps,
AgentContextNode,
@@ -207,6 +211,10 @@ export interface NodeDecoratorMap {
klass: typeof MagicChipNode;
props: MagicChipDecoratorProps;
};
+ AgentActivityNode: {
+ klass: typeof AgentActivityNode;
+ props: AgentActivityDecoratorProps;
+ };
CursorSystemNotificationNode: {
klass: typeof CursorSystemNotificationNode;
props: CursorSystemNotificationDecoratorProps;
diff --git a/packages/lexical-core/index.ts b/packages/lexical-core/index.ts
index 26bc030ce5..37ce3f050f 100644
--- a/packages/lexical-core/index.ts
+++ b/packages/lexical-core/index.ts
@@ -2,6 +2,7 @@ export * from './constants';
export * from './decoratorRegistry';
export * from './domFactoryRegistry';
export * from './node-list';
+export * from './nodes/AgentActivityNode';
export * from './nodes/AgentContextNode';
export * from './nodes/AgentSessionMentionNode';
export * from './nodes/AwaitNode';
diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.ts
index b6e357c1ee..465c034f06 100644
--- a/packages/lexical-core/node-list.ts
+++ b/packages/lexical-core/node-list.ts
@@ -13,6 +13,7 @@ import {
TabNode,
TextNode,
} from 'lexical';
+import { AgentActivityNode } from './nodes/AgentActivityNode';
import { AgentContextNode } from './nodes/AgentContextNode';
import { AgentSessionMentionNode } from './nodes/AgentSessionMentionNode';
import { AwaitNode } from './nodes/AwaitNode';
@@ -124,6 +125,7 @@ export const SupportedNodeTypes = [
UnknownMentionNode,
AwaitNode,
MagicChipNode,
+ AgentActivityNode,
AgentContextNode,
CursorSystemNotificationNode,
] as const;
diff --git a/packages/lexical-core/nodes/AgentActivityNode.ts b/packages/lexical-core/nodes/AgentActivityNode.ts
new file mode 100644
index 0000000000..2507e3ad72
--- /dev/null
+++ b/packages/lexical-core/nodes/AgentActivityNode.ts
@@ -0,0 +1,228 @@
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMConversionMap,
+ type EditorConfig,
+ type EditorThemeClasses,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+
+const VERSION = 1;
+
+export const AGENT_ACTIVITY_NODE_TYPE = 'agent-activity';
+
+/** Where one step of an agent's work got to. */
+export const AGENT_ACTIVITY_STATUSES = [
+ 'running',
+ 'completed',
+ 'failed',
+ 'interrupted',
+] as const;
+
+/** Where one step of an agent's work got to. */
+export type AgentActivityStatus = (typeof AGENT_ACTIVITY_STATUSES)[number];
+
+/** One step of work as the agent session's fold worded it. */
+export type AgentActivityRow = {
+ id: string;
+ label: string;
+ detail?: string;
+ status: AgentActivityStatus;
+};
+
+/**
+ * The steps an agent took between two passages of a reply: the activity
+ * segment `segment` of the reply to `turn` in `agentSessionId`.
+ *
+ * `rows` is the snapshot the server wrote when it last posted the message: what
+ * a reader without access to the session, a notification, or search sees. A
+ * viewer who can read the session renders the same segment live instead.
+ */
+export type AgentActivityData = {
+ agentSessionId: string;
+ turn: number;
+ segment: number;
+ rows: AgentActivityRow[];
+ /** Whether the segment can still gain steps. */
+ sealed: boolean;
+};
+
+export type SerializedAgentActivityNode = Spread<
+ AgentActivityData,
+ SerializedLexicalNode
+>;
+
+export type AgentActivityDecoratorProps = AgentActivityData & {
+ key: NodeKey;
+ theme: EditorThemeClasses;
+};
+
+export function isAgentActivityStatus(
+ value: unknown
+): value is AgentActivityStatus {
+ return (AGENT_ACTIVITY_STATUSES as readonly unknown[]).includes(value);
+}
+
+function isAgentActivityRow(value: unknown): value is AgentActivityRow {
+ if (!value || typeof value !== 'object') return false;
+ const row = value as Record<string, unknown>;
+ return (
+ typeof row.id === 'string' &&
+ typeof row.label === 'string' &&
+ (row.detail === undefined || typeof row.detail === 'string') &&
+ isAgentActivityStatus(row.status)
+ );
+}
+
+const isIndex = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isInteger(value) && value >= 0;
+
+/** Return whether a value is a well-formed activity payload. */
+export function isAgentActivityData(
+ value: unknown
+): value is AgentActivityData {
+ if (!value || typeof value !== 'object') return false;
+ const data = value as Record<string, unknown>;
+ return (
+ typeof data.agentSessionId === 'string' &&
+ isIndex(data.turn) &&
+ isIndex(data.segment) &&
+ Array.isArray(data.rows) &&
+ data.rows.every(isAgentActivityRow) &&
+ typeof data.sealed === 'boolean'
+ );
+}
+
+/** A plain-text line for each step: how the activity reads when copied. */
+export function agentActivityText(rows: readonly AgentActivityRow[]): string {
+ return rows
+ .map((row) => (row.detail ? `${row.label} ${row.detail}` : row.label))
+ .join('\n');
+}
+
+/** The steps of an agent reply, rendered live where the session is readable. */
+export class AgentActivityNode extends DecoratorNode<
+ DecoratorComponent<AgentActivityDecoratorProps> | undefined
+> {
+ __data: AgentActivityData;
+
+ __cachedDecoratorSignature?: string;
+ __cachedDecoratorComponent?: DecoratorComponent<AgentActivityDecoratorProps>;
+
+ static getType() {
+ return AGENT_ACTIVITY_NODE_TYPE;
+ }
+
+ static clone(node: AgentActivityNode) {
+ const clone = new AgentActivityNode(node.__data, node.__key);
+ clone.__cachedDecoratorSignature = node.__cachedDecoratorSignature;
+ clone.__cachedDecoratorComponent = node.__cachedDecoratorComponent;
+ return clone;
+ }
+
+ constructor(data: AgentActivityData, key?: NodeKey) {
+ super(key);
+ this.__data = data;
+ }
+
+ isInline(): boolean {
+ return false;
+ }
+
+ isKeyboardSelectable(): boolean {
+ return false;
+ }
+
+ static importJSON(serializedNode: SerializedAgentActivityNode) {
+ const node = $createAgentActivityNode({
+ agentSessionId: serializedNode.agentSessionId,
+ turn: serializedNode.turn,
+ segment: serializedNode.segment,
+ rows: serializedNode.rows,
+ sealed: serializedNode.sealed,
+ });
+ $applyIdFromSerialized(node, serializedNode);
+ return node;
+ }
+
+ exportJSON(): SerializedAgentActivityNode {
+ return {
+ ...super.exportJSON(),
+ ...this.exportComponentProps(),
+ type: AGENT_ACTIVITY_NODE_TYPE,
+ version: VERSION,
+ };
+ }
+
+ exportComponentProps(): AgentActivityData {
+ return this.__data;
+ }
+
+ createDOM(_config: EditorConfig): HTMLElement {
+ const element = document.createElement('div');
+ element.setAttribute('data-agent-activity', this.__data.agentSessionId);
+ return element;
+ }
+
+ updateDOM(): boolean {
+ return false;
+ }
+
+ exportDOM() {
+ const element = document.createElement('div');
+ element.setAttribute('data-agent-activity', this.__data.agentSessionId);
+ element.textContent = agentActivityText(this.__data.rows);
+ return { element };
+ }
+
+ static importDOM(): DOMConversionMap | null {
+ return null;
+ }
+
+ // Steps are not prose: a preview, a notification, or a search hit for an
+ // agent's reply quotes what it wrote, not every command it ran.
+ getTextContent(): string {
+ return '';
+ }
+
+ decorate(_: LexicalEditor, config: EditorConfig) {
+ const signature = JSON.stringify(this.__data);
+ if (
+ this.__cachedDecoratorComponent &&
+ this.__cachedDecoratorSignature === signature
+ )
+ return this.__cachedDecoratorComponent;
+ this.__cachedDecoratorSignature = signature;
+ const decorator =
+ getDecorator<AgentActivityDecoratorProps>(AgentActivityNode);
+ if (decorator) {
+ this.__cachedDecoratorComponent = () =>
+ decorator({
+ ...this.__data,
+ key: this.getKey(),
+ theme: config.theme,
+ });
+ return this.__cachedDecoratorComponent;
+ }
+ }
+}
+
+/** Create an agent activity node. */
+export function $createAgentActivityNode(
+ data: AgentActivityData
+): AgentActivityNode {
+ return $applyNodeReplacement(new AgentActivityNode(data));
+}
+
+/** Return whether a Lexical node is an agent activity node. */
+export function $isAgentActivityNode(
+ node: LexicalNode | null | undefined
+): node is AgentActivityNode {
+ return node instanceof AgentActivityNode;
+}
diff --git a/packages/lexical-core/tests/agent-activity-markdown.test.ts b/packages/lexical-core/tests/agent-activity-markdown.test.ts
new file mode 100644
index 0000000000..a30f1336c3
--- /dev/null
+++ b/packages/lexical-core/tests/agent-activity-markdown.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+import { composeAgentChatReply } from '../utils/agent-chat-reply';
+import { markdownToSerializedEditorStateWithIds } from '../utils/markdown-state';
+
+const SESSION = '00000000-0000-0000-0000-00000000000a';
+const LINE_SEPARATOR = String.fromCharCode(0x2028);
+const PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029);
+
+function activity(rows: { id: string; label: string; detail?: string }[]) {
+ return composeAgentChatReply({
+ sessionId: SESSION,
+ link: false,
+ body: {
+ kind: 'segments',
+ segments: [
+ {
+ kind: 'activity',
+ turn: 1,
+ segment: 0,
+ rows: rows.map((row) => ({ ...row, status: 'completed' as const })),
+ sealed: true,
+ },
+ ],
+ },
+ });
+}
+
+describe('agent activity markdown', () => {
+ it('keeps a step that names the closing tag inside its node', () => {
+ const rows = [
+ {
+ id: 't1',
+ label: 'Ran',
+ detail: "grep '</m-agent-activity><m-user-mention>x' notes.md",
+ },
+ ];
+ const markdown = activity(rows);
+ expect(markdown.match(/<\/m-agent-activity>/g)).toHaveLength(1);
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children).toHaveLength(1);
+ expect(state.root.children[0]).toMatchObject({
+ type: 'agent-activity',
+ rows: rows.map((row) => ({ ...row, status: 'completed' })),
+ });
+ });
+
+ it('keeps line and paragraph separators inside a step', () => {
+ const rows = [
+ {
+ id: 't1',
+ label: 'Read',
+ detail: `one${LINE_SEPARATOR}two${PARAGRAPH_SEPARATOR}three`,
+ },
+ ];
+ const markdown = activity(rows);
+ expect(markdown.includes(LINE_SEPARATOR)).toBe(false);
+ expect(markdown.includes(PARAGRAPH_SEPARATOR)).toBe(false);
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children[0]).toMatchObject({
+ type: 'agent-activity',
+ rows: rows.map((row) => ({ ...row, status: 'completed' })),
+ });
+ });
+
+ it('reads a payload written with raw line separators', () => {
+ const payload = JSON.stringify({
+ agentSessionId: SESSION,
+ turn: 1,
+ segment: 0,
+ rows: [
+ {
+ id: 't1',
+ label: 'Read',
+ detail: `a${LINE_SEPARATOR}b`,
+ status: 'completed',
+ },
+ ],
+ sealed: true,
+ });
+ const state = markdownToSerializedEditorStateWithIds(
+ `<m-agent-activity>${payload}</m-agent-activity>`
+ );
+ expect(state.root.children[0]?.type).toBe('agent-activity');
+ });
+});
diff --git a/packages/lexical-core/tests/agent-chat-reply.test.ts b/packages/lexical-core/tests/agent-chat-reply.test.ts
index 2fa2bf271f..ea1a9291f4 100644
--- a/packages/lexical-core/tests/agent-chat-reply.test.ts
+++ b/packages/lexical-core/tests/agent-chat-reply.test.ts
@@ -5,6 +5,7 @@ import {
PENDING_REPLY_TEXT,
} from '../utils/agent-chat-reply';
import { markdownToSerializedEditorStateWithIds } from '../utils/markdown-state';
+import { markdownToPlainText } from '../utils/parsers';
const SESSION = '00000000-0000-0000-0000-00000000000a';
const LINK = `<m-agent-session-mention>{"id":"${SESSION}","label":"${AGENT_SESSION_LINK_LABEL}"}</m-agent-session-mention>`;
@@ -68,3 +69,100 @@ describe('composeAgentChatReply', () => {
});
});
});
+
+describe('composeAgentChatReply with segments', () => {
+ const rows = [
+ {
+ id: 't1',
+ label: 'Ran',
+ detail: 'cargo test',
+ status: 'completed' as const,
+ },
+ { id: 't2', label: 'Reading', status: 'running' as const },
+ ];
+
+ it('interleaves passages as written with live steps, in order', () => {
+ const markdown = composeAgentChatReply({
+ sessionId: SESSION,
+ link: false,
+ body: {
+ kind: 'segments',
+ segments: [
+ { kind: 'prose', markdown: 'Checking the **tests** first.' },
+ { kind: 'activity', turn: 3, segment: 1, rows, sealed: false },
+ ],
+ },
+ });
+ expect(markdown.startsWith('Checking the **tests** first.\n\n')).toBe(true);
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children.map((child) => child.type)).toEqual([
+ 'paragraph',
+ 'agent-activity',
+ ]);
+ expect(state.root.children[1]).toMatchObject({
+ agentSessionId: SESSION,
+ turn: 3,
+ segment: 1,
+ rows,
+ sealed: false,
+ });
+ });
+
+ it('reads as its passages alone in plain text', () => {
+ const markdown = composeAgentChatReply({
+ sessionId: SESSION,
+ link: false,
+ body: {
+ kind: 'segments',
+ segments: [
+ { kind: 'activity', turn: 3, segment: 0, rows, sealed: true },
+ { kind: 'prose', markdown: 'All tests pass.' },
+ ],
+ },
+ });
+ expect(markdownToPlainText(markdown)).toBe('All tests pass.');
+ });
+
+ it('keeps the session link and spinner for a thread reply still running', () => {
+ const markdown = composeAgentChatReply({
+ sessionId: SESSION,
+ body: {
+ kind: 'segments',
+ segments: [
+ { kind: 'activity', turn: 0, segment: 0, rows, sealed: false },
+ ],
+ pending: true,
+ },
+ });
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(
+ state.root.children.map((child) =>
+ child.type === 'paragraph'
+ ? (child as { children: { type: string }[] }).children[0]?.type
+ : child.type
+ )
+ ).toEqual(['agent-session-mention', 'agent-activity', 'await']);
+ });
+
+ it('closes with the footer the harness wrote', () => {
+ const markdown = composeAgentChatReply({
+ sessionId: SESSION,
+ link: false,
+ body: {
+ kind: 'segments',
+ segments: [{ kind: 'prose', markdown: 'Partial answer' }],
+ footer: 'I stopped before finishing that.',
+ },
+ });
+ expect(markdown).toBe(
+ 'Partial answer\n\n_I stopped before finishing that._'
+ );
+ });
+
+ it('an invalid activity payload falls back instead of breaking the message', () => {
+ const state = markdownToSerializedEditorStateWithIds(
+ '<m-agent-activity>{"agentSessionId":"x"}</m-agent-activity>'
+ );
+ expect(state.root.children[0]?.type).not.toBe('agent-activity');
+ });
+});
diff --git a/packages/lexical-core/tests/agent-context.test.ts b/packages/lexical-core/tests/agent-context.test.ts
index 40de25efaf..5c8fd3f9ba 100644
--- a/packages/lexical-core/tests/agent-context.test.ts
+++ b/packages/lexical-core/tests/agent-context.test.ts
@@ -359,6 +359,30 @@ describe('composeAgentContextPrompt', () => {
expect(text?.match(/<\/thread>/g)).toHaveLength(1);
});
+ it('tells the agent a private conversation is read live', () => {
+ const text = composedContext({
+ promptMarkdown: 'what changed?',
+ trigger: {
+ kind: 'conversation',
+ surface: {
+ type: 'channel',
+ id: 'dm-1',
+ channel_type: 'direct_message',
+ },
+ prompt_message_id: 'm-1',
+ sender: { id: 'macro|[email protected]', name: 'Ada' },
+ reply_target: { kind: 'none' },
+ },
+ });
+
+ expect(text).toContain('<trigger kind="conversation">');
+ expect(text).toContain(
+ 'This prompt was posted in your private conversation with the user'
+ );
+ expect(text).toContain('AskUser');
+ expect(text).not.toContain(origin);
+ });
+
it('names the owner and says an owner prompt is theirs', () => {
const owner = { id: 'macro|[email protected]', name: '[email protected]' };
expect(
diff --git a/packages/lexical-core/transformers/agentActivity.ts b/packages/lexical-core/transformers/agentActivity.ts
new file mode 100644
index 0000000000..98ec1e3b4b
--- /dev/null
+++ b/packages/lexical-core/transformers/agentActivity.ts
@@ -0,0 +1,49 @@
+import type { ElementTransformer } from '@lexical/markdown';
+import type { ElementNode, LexicalNode } from 'lexical';
+import {
+ $createAgentActivityNode,
+ $isAgentActivityNode,
+ AgentActivityNode,
+ isAgentActivityData,
+} from '../nodes/AgentActivityNode';
+import {
+ replaceElementWithUnknownMention,
+ UnknownMentionNode,
+} from './unknownFallback';
+
+/**
+ * Escape what would end the tag or its line inside the JSON payload. Steps
+ * carry commands and file names as written, so `</m-agent-activity>` and
+ * line separators can appear in them; JSON.parse reads the escapes back.
+ */
+function escapeJsonEnvelopeCharacter(character: string): string {
+ if (character === '<') return '\\u003c';
+ if (character === '\u2028') return '\\u2028';
+ return '\\u2029';
+}
+
+/** Internal markdown transformer for an agent reply's steps. */
+export const I_AGENT_ACTIVITY: ElementTransformer = {
+ dependencies: [AgentActivityNode, UnknownMentionNode],
+ type: 'element',
+ regExp: /<m-agent-activity>(.*?)<\/m-agent-activity>/s,
+ export: (node: LexicalNode) => {
+ if (!$isAgentActivityNode(node)) return null;
+ const payload = JSON.stringify(node.exportComponentProps()).replace(
+ /[<\u2028\u2029]/g,
+ escapeJsonEnvelopeCharacter
+ );
+ return `<m-agent-activity>${payload}</m-agent-activity>`;
+ },
+ replace: (parent: ElementNode, _, match: string[]) => {
+ try {
+ const data: unknown = JSON.parse(match[1] ?? '');
+ if (!isAgentActivityData(data))
+ throw new Error('invalid agent activity data');
+ parent.replace($createAgentActivityNode(data));
+ } catch (error) {
+ console.error('Error in I_AGENT_ACTIVITY replace:', error);
+ replaceElementWithUnknownMention(parent, 'Unknown agent activity');
+ }
+ },
+};
diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.ts
index d4643cd2fa..703b7ee9d6 100644
--- a/packages/lexical-core/transformers/index.ts
+++ b/packages/lexical-core/transformers/index.ts
@@ -1,4 +1,5 @@
import type { Transformer } from '@lexical/markdown';
+import { I_AGENT_ACTIVITY } from './agentActivity';
import { I_AGENT_CONTEXT } from './agentContext';
import { I_AWAIT_NODE } from './await';
import { HTML_BLOCKQUOTE, I_MACRO_QUOTE } from './classedBlock';
@@ -91,6 +92,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_DATE_MENTION,
I_AWAIT_NODE,
I_MAGIC_CHIP,
+ I_AGENT_ACTIVITY,
I_REPLY_TARGET_NODE,
I_AGENT_CONTEXT,
I_TABLE_NODE,
@@ -194,6 +196,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
E_DATE_MENTION,
I_AWAIT_NODE,
I_MAGIC_CHIP,
+ I_AGENT_ACTIVITY,
I_REPLY_TARGET_NODE,
I_AGENT_CONTEXT,
I_MACRO_QUOTE,
diff --git a/packages/lexical-core/utils/agent-chat-reply.ts b/packages/lexical-core/utils/agent-chat-reply.ts
index ececbcd42d..2657c90ca0 100644
--- a/packages/lexical-core/utils/agent-chat-reply.ts
+++ b/packages/lexical-core/utils/agent-chat-reply.ts
@@ -2,6 +2,10 @@ import { createHeadlessEditor } from '@lexical/headless';
import { $convertToMarkdownString } from '@lexical/markdown';
import { $createParagraphNode, $getRoot } from 'lexical';
import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import {
+ $createAgentActivityNode,
+ type AgentActivityRow,
+} from '../nodes/AgentActivityNode';
import { $createAgentSessionMentionNode } from '../nodes/AgentSessionMentionNode';
import { $createAwaitNode } from '../nodes/AwaitNode';
import { ALL_TRANSFORMERS } from '../transformers';
@@ -15,23 +19,112 @@ export const AGENT_SESSION_LINK_LABEL = 'Agent session';
/** The spinner's caption while a chat agent's turn runs. */
export const PENDING_REPLY_TEXT = 'Thinking…';
+/**
+ * One segment of an agent's reply, as a message shows it: a passage as the
+ * agent wrote it, or the steps it took between passages.
+ */
+export type AgentReplySegment =
+ | { kind: 'prose'; markdown: string }
+ | {
+ kind: 'activity';
+ turn: number;
+ segment: number;
+ rows: AgentActivityRow[];
+ sealed: boolean;
+ };
+
/**
* What a chat agent's message says below its session link: the spinner
* while the turn runs, or prose - the answer, a fallback the harness wrote
- * for a turn that said nothing, a question the thread cannot answer.
+ * for a turn that said nothing, a question the thread cannot answer - or the
+ * reply's segments, passages and steps in the order the agent produced them.
*/
export type AgentChatReplyBody =
| { kind: 'pending' }
- | { kind: 'markdown'; markdown: string };
+ | { kind: 'markdown'; markdown: string }
+ | {
+ kind: 'segments';
+ segments: AgentReplySegment[];
+ /** Show the spinner after the segments: the turn is still running. */
+ pending?: boolean;
+ /** A closing line the harness wrote: stopped, failed, said nothing. */
+ footer?: string;
+ };
/** A chat agent's message in its thread, in one of its states. */
export type AgentChatReply = {
sessionId: string;
body: AgentChatReplyBody;
+ /**
+ * Lead with a link to the session. A thread reply does, so a reader can
+ * open the session the answer came from; a private conversation's
+ * messages are the session, and repeat no link. Defaults to true.
+ */
+ link?: boolean;
};
+function editor() {
+ return createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+}
+
+/** Serialize nodes built in `build` exactly as the editor's transformers do. */
+function serialize(build: () => void): string {
+ const headless = editor();
+ headless.update(build, { discrete: true });
+ return headless
+ .getEditorState()
+ .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
+}
+
+function chrome(reply: AgentChatReply, pending: boolean): string {
+ return serialize(() => {
+ const root = $getRoot();
+ if (reply.link !== false) {
+ root.append(
+ $createParagraphNode().append(
+ $createAgentSessionMentionNode({
+ id: reply.sessionId,
+ label: AGENT_SESSION_LINK_LABEL,
+ })
+ )
+ );
+ }
+ if (pending) {
+ root.append(
+ $createParagraphNode().append(
+ $createAwaitNode({ text: PENDING_REPLY_TEXT, inline: true })
+ )
+ );
+ }
+ });
+}
+
+function segmentMarkdown(
+ sessionId: string,
+ segment: AgentReplySegment
+): string {
+ if (segment.kind === 'prose') return segment.markdown;
+ return serialize(() => {
+ $getRoot().append(
+ $createAgentActivityNode({
+ agentSessionId: sessionId,
+ turn: segment.turn,
+ segment: segment.segment,
+ rows: segment.rows.map((row) =>
+ row.detail
+ ? row
+ : { id: row.id, label: row.label, status: row.status }
+ ),
+ sealed: segment.sealed,
+ })
+ );
+ });
+}
+
/**
- * Compose a chat agent's thread message: a link to its session as the
+ * Compose a chat agent's message: a link to its session as the
* agent-session mention node, alone in the first paragraph, then the body.
*
* The channel message view lifts a leading mention paragraph out of the body
@@ -45,34 +138,22 @@ export type AgentChatReply = {
* the agent's answer, and normalizing it is not this function's job.
*/
export function composeAgentChatReply(reply: AgentChatReply): string {
- const editor = createHeadlessEditor({
- nodes: [...SupportedNodeTypes, ...NodeReplacements],
- });
- editor.update(
- () => {
- const root = $getRoot();
- root.append(
- $createParagraphNode().append(
- $createAgentSessionMentionNode({
- id: reply.sessionId,
- label: AGENT_SESSION_LINK_LABEL,
- })
- )
- );
- if (reply.body.kind === 'pending') {
- root.append(
- $createParagraphNode().append(
- $createAwaitNode({ text: PENDING_REPLY_TEXT, inline: true })
- )
- );
- }
- },
- { discrete: true }
- );
- const chrome = editor
- .getEditorState()
- .read(() => $convertToMarkdownString(ALL_TRANSFORMERS));
- return reply.body.kind === 'pending'
- ? chrome
- : `${chrome}\n\n${reply.body.markdown}`;
+ const { body } = reply;
+ if (body.kind !== 'segments') {
+ const head = chrome(reply, body.kind === 'pending');
+ if (body.kind === 'pending') return head;
+ return [head, body.markdown].filter(Boolean).join('\n\n');
+ }
+ const head = chrome(reply, false);
+ const tail = body.pending ? chrome({ ...reply, link: false }, true) : '';
+ return [
+ head,
+ ...body.segments.map((segment) =>
+ segmentMarkdown(reply.sessionId, segment)
+ ),
+ body.footer ? `_${body.footer}_` : '',
+ tail,
+ ]
+ .filter((part) => part.trim().length > 0)
+ .join('\n\n');
}
diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.ts
index 91bf91f588..a4ecb45a81 100644
--- a/packages/lexical-core/utils/agent-context.ts
+++ b/packages/lexical-core/utils/agent-context.ts
@@ -20,6 +20,7 @@ import { markdownToEmbeddingText } from './parsers';
export type TriggerContext =
| ({ kind: 'mentioned' } & DiscussionContext)
| ({ kind: 'follow_up' } & FollowUpContext)
+ | ({ kind: 'conversation' } & DiscussionContext)
| ({ kind: 'task_assigned' } & TaskAssignedContext)
| ({ kind: 'requested' } & RequestedContext)
| ({ kind: 'dispatched' } & DispatchedContext)
@@ -702,6 +703,8 @@ type DiscussionReading = {
subject: 'prompt' | 'triggering message';
/** Whether the agent's reply is posted back into the discussion. */
repliesHere: boolean;
+ /** Where the reply goes, when it is not back into a thread. */
+ origin?: string;
};
type MessageMarker = { attribute: string; messageId: string };
@@ -940,7 +943,8 @@ function discussionNode(
? [
el('origin', [
text(
- `This ${reading.subject} was posted in ${surfaceDescription(discussion.surface)}, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.`
+ reading.origin ??
+ `This ${reading.subject} was posted in ${surfaceDescription(discussion.surface)}, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.`
),
]),
]
@@ -1119,6 +1123,25 @@ function followUpNode({ addressed_by, discussion }: FollowUpContext): FxpNode {
);
}
+function conversationNode(discussion: DiscussionContext): FxpNode {
+ return el(
+ 'trigger',
+ [
+ note(
+ `${discussion.sender.name} wrote to you in your private conversation with them. Their message is the prompt; the conversation before it is this session's history.`
+ ),
+ discussionNode(discussion, {
+ marker: 'wrote_to_you',
+ subject: 'prompt',
+ repliesHere: true,
+ origin:
+ 'This prompt was posted in your private conversation with the user, not the agent session view. They read it as you work: your reply is posted there, and a question you ask with AskUser or a draft you open for review appears there for them to answer.',
+ }),
+ ],
+ { kind: 'conversation' }
+ );
+}
+
function taskAssignedNode(context: TaskAssignedContext): FxpNode {
const assigner = context.assigned_by.name;
return el(
@@ -1331,6 +1354,7 @@ function triggerNode(trigger: TriggerContext): FxpNode {
return match(trigger)
.with({ kind: 'mentioned' }, mentionedNode)
.with({ kind: 'follow_up' }, followUpNode)
+ .with({ kind: 'conversation' }, conversationNode)
.with({ kind: 'task_assigned' }, taskAssignedNode)
.with({ kind: 'requested' }, requestedNode)
.with({ kind: 'dispatched' }, dispatchedNode)
diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.ts
index 0d7cec0dfc..40b61896d1 100644
--- a/packages/lexical-core/utils/parsers.ts
+++ b/packages/lexical-core/utils/parsers.ts
@@ -123,6 +123,17 @@ export function parseDatabaseQueries(text: string): string {
});
}
+/**
+ * An agent's steps are not prose: a preview of its reply quotes what it
+ * wrote, not every command it ran.
+ */
+export function parseAgentActivities(text: string): string {
+ return text.replace(
+ /<m-agent-activity>.*?<\/m-agent-activity>(?:\r?\n)*/gs,
+ ''
+ );
+}
+
/** A Cursor `<system_notification …>` block reads as its summary line. */
export function parseCursorSystemNotifications(text: string): string {
return text.replace(
@@ -246,9 +257,11 @@ export function stripAgentContext(text: string): string {
* - Links: text (fallback to url)
* - Reply targets: displayText
* - Cursor system notifications: the summary between the tags
+ * - Agent activity: nothing; the steps of a reply are not its text
*/
export function markdownToPlainText(markdown: string): string {
const transforms: Array<(text: string) => string> = [
+ parseAgentActivities,
parseUserMentions,
parseContactMentions,
parseDateMentions,
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 036477d220..2998fb8df0 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-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, 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, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, 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, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, 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, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, 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, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, 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, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index afcdde9ab8..54b429d23a 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 { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';
+import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -93,6 +93,48 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * The agent conversations in a channel the caller may see. Ordinary channels
+ * and other people's conversations list none.
+ */
+ public listAgentConversations<ThrowOnError extends boolean = false>(options: Options<ListAgentConversationsData, ThrowOnError>): RequestResult<ListAgentConversationsResponses, ListAgentConversationsErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<ListAgentConversationsResponses, ListAgentConversationsErrors, ThrowOnError>({
+ security: [{ scheme: 'bearer', type: 'http' }],
+ url: '/agent-conversations/{channel_id}',
+ ...options
+ });
+ }
+
+ /**
+ * Start a fresh agent context, retaining the channel transcript.
+ */
+ public startFreshAgentConversation<ThrowOnError extends boolean = false>(options: Options<StartFreshAgentConversationData, ThrowOnError>): RequestResult<StartFreshAgentConversationResponses, StartFreshAgentConversationErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<StartFreshAgentConversationResponses, StartFreshAgentConversationErrors, ThrowOnError>({
+ security: [{ scheme: 'bearer', type: 'http' }],
+ url: '/agent-conversations/{channel_id}/{bot_id}/start-fresh',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Explicitly retry a failed message in the conversation's current session.
+ */
+ public retryAgentConversationTurn<ThrowOnError extends boolean = false>(options: Options<RetryAgentConversationTurnData, ThrowOnError>): RequestResult<RetryAgentConversationTurnResponses, RetryAgentConversationTurnErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<RetryAgentConversationTurnResponses, RetryAgentConversationTurnErrors, ThrowOnError>({
+ security: [{ scheme: 'bearer', type: 'http' }],
+ url: '/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Probe one provider's model catalog without creating an agent session.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 6abd6e5bd2..ddc31a6a01 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -108,6 +108,107 @@ export type AgentConfigSelectOptionDto = {
value: string;
};
+/**
+ * An agent's conversation in a channel, as the person it is with sees it.
+ */
+export type AgentConversationDto = {
+ /**
+ * Whether the caller may currently send a new prompt.
+ */
+ available: boolean;
+ /**
+ * Optional persona avatar.
+ */
+ avatarUrl?: string | null;
+ /**
+ * Persona id (without the bot principal prefix).
+ */
+ botId: string;
+ /**
+ * The channel containing the visible transcript.
+ */
+ channelId: string;
+ /**
+ * Persona's historical display name.
+ */
+ name: string;
+ /**
+ * The sessions the conversation has run on, oldest first.
+ */
+ sessions: Array<AgentConversationSessionDto>;
+ /**
+ * Whether new persona settings are available to adopt explicitly.
+ */
+ settingsChanged: boolean;
+ /**
+ * Persistent state of each accepted message and its current attempt.
+ */
+ turns: Array<AgentConversationTurnDto>;
+};
+
+/**
+ * One session a conversation has run on; every channel message stays visible.
+ */
+export type AgentConversationSessionDto = {
+ /**
+ * When the session began.
+ */
+ createdAt: string;
+ /**
+ * Whether this is the current agent context.
+ */
+ isCurrent: boolean;
+ /**
+ * Session whose controls and live events belong to this context.
+ */
+ sessionId: string;
+};
+
+/**
+ * Execution status without exposing the persona prompt or stored credentials.
+ */
+export type AgentConversationTurnDto = {
+ /**
+ * Current runtime attempt identity.
+ */
+ actionId: string;
+ /**
+ * When the source message was first accepted.
+ */
+ createdAt: string;
+ /**
+ * The associated agent reply, if it has been posted.
+ */
+ replyMessageId?: string | null;
+ /**
+ * Whether Retry would be accepted now. A failed attempt is not retryable
+ * until its reply says how it ended.
+ */
+ retryable: boolean;
+ /**
+ * Session carrying this turn.
+ */
+ sessionId: string;
+ /**
+ * The user's message in the channel timeline.
+ */
+ sourceMessageId: string;
+ /**
+ * Durable execution state.
+ */
+ state: ConversationTurnState;
+};
+
+/**
+ * The agent conversations in a channel the caller may see.
+ */
+export type AgentConversationsDto = {
+ /**
+ * Empty for ordinary channels and other people's conversations.
+ */
+ conversations: Array<AgentConversationDto>;
+};
+
/**
* One model picker option.
*/
@@ -752,6 +853,11 @@ export type ControlResponse = {
*/
export type ControlStatusDto = 'sent' | 'queued';
+/**
+ * The state of one source message, retained after completion for deduplication.
+ */
+export type ConversationTurnState = 'queued' | 'running' | 'succeeded' | 'failed' | 'stopped' | 'interrupted';
+
/**
* Request body for `POST /agent-sessions`.
*
@@ -1321,6 +1427,16 @@ export type RenameAgentSessionRequest = {
name: string;
};
+/**
+ * The attempt the user saw and chose to retry; prevents double-click reruns.
+ */
+export type RetryAgentConversationTurnRequest = {
+ /**
+ * Current failed attempt identity.
+ */
+ actionId: string;
+};
+
/**
* Named compute tier for a managed sandbox.
*
@@ -1441,6 +1557,16 @@ export type SharePermissionV2 = {
teamShareAccessLevel?: null | AccessLevel;
};
+/**
+ * The session the user is choosing to leave behind.
+ */
+export type StartFreshAgentConversationRequest = {
+ /**
+ * Current session id shown in the conversation metadata.
+ */
+ sessionId: string;
+};
+
/**
* Public PKCE challenge and attempt handle; contains no verifier or provider tokens.
*/
@@ -1624,6 +1750,109 @@ export type PutAgentCodingPreferencesResponses = {
export type PutAgentCodingPreferencesResponse = PutAgentCodingPreferencesResponses[keyof PutAgentCodingPreferencesResponses];
+export type ListAgentConversationsData = {
+ body?: never;
+ path: {
+ /**
+ * Conversation channel
+ */
+ channel_id: string;
+ };
+ query?: never;
+ url: '/agent-conversations/{channel_id}';
+};
+
+export type ListAgentConversationsErrors = {
+ /**
+ * Conversations temporarily unavailable
+ */
+ 503: unknown;
+};
+
+export type ListAgentConversationsResponses = {
+ /**
+ * The caller's agent conversations in the channel
+ */
+ 200: AgentConversationsDto;
+};
+
+export type ListAgentConversationsResponse = ListAgentConversationsResponses[keyof ListAgentConversationsResponses];
+
+export type StartFreshAgentConversationData = {
+ body: StartFreshAgentConversationRequest;
+ path: {
+ channel_id: string;
+ /**
+ * Persona the conversation is with
+ */
+ bot_id: string;
+ };
+ query?: never;
+ url: '/agent-conversations/{channel_id}/{bot_id}/start-fresh';
+};
+
+export type StartFreshAgentConversationErrors = {
+ /**
+ * Conversation not found
+ */
+ 404: unknown;
+ /**
+ * Context is busy, stale or unavailable
+ */
+ 409: unknown;
+ /**
+ * Temporarily unavailable
+ */
+ 503: unknown;
+};
+
+export type StartFreshAgentConversationResponses = {
+ /**
+ * New context reserved
+ */
+ 204: void;
+};
+
+export type StartFreshAgentConversationResponse = StartFreshAgentConversationResponses[keyof StartFreshAgentConversationResponses];
+
+export type RetryAgentConversationTurnData = {
+ body: RetryAgentConversationTurnRequest;
+ path: {
+ channel_id: string;
+ /**
+ * Persona the conversation is with
+ */
+ bot_id: string;
+ source: string;
+ };
+ query?: never;
+ url: '/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry';
+};
+
+export type RetryAgentConversationTurnErrors = {
+ /**
+ * Conversation or turn not found
+ */
+ 404: unknown;
+ /**
+ * Attempt cannot be retried
+ */
+ 409: unknown;
+ /**
+ * Temporarily unavailable
+ */
+ 503: unknown;
+};
+
+export type RetryAgentConversationTurnResponses = {
+ /**
+ * Retry queued
+ */
+ 204: void;
+};
+
+export type RetryAgentConversationTurnResponse = RetryAgentConversationTurnResponses[keyof RetryAgentConversationTurnResponses];
+
export type LoadAgentModelsHandlerData = {
body: LoadAgentModelsRequest;
path?: never;
@@ -1956,6 +2185,10 @@ export type SetAgentSessionArchivedData = {
export type SetAgentSessionArchivedErrors = {
401: string;
403: string;
+ /**
+ * The session answers an agent conversation
+ */
+ 409: string;
500: string;
};
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index be48774276..b12c2a4baf 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 81e520d901..7b3699bb5a 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -183,6 +183,24 @@ export type AgentActionId = string;
*/
export type AgentChannelScope = 'all' | 'selected';
+/**
+ * Historical persona identity displayed beside a private conversation.
+ */
+export type AgentDmProfile = {
+ /**
+ * Persona avatar, when supplied.
+ */
+ avatar_url?: string | null;
+ /**
+ * Persona id without the bot principal prefix.
+ */
+ bot_id: string;
+ /**
+ * Persona display name.
+ */
+ name: string;
+};
+
/**
* One Pipedream app an agent lists under [`AgentMcpServers::Selected`].
*
@@ -320,6 +338,27 @@ export type AgentSessionLifecycleEvent = {
metadata: SessionDeletedMetadata;
};
+/**
+ * An agent session typing through its bot.
+ */
+export type AgentTyping = {
+ /**
+ * What the agent is doing. Deliberately coarse: a typing event reaches
+ * everyone in the conversation, and which tool runs on what is for
+ * viewers who can read the session itself.
+ */
+ phase: AgentTypingPhase;
+ /**
+ * The session whose turn the bot is speaking for.
+ */
+ session_id: string;
+};
+
+/**
+ * What a typing agent is doing.
+ */
+export type AgentTypingPhase = 'thinking' | 'writing' | 'working' | 'waiting';
+
export type Anchor = PdfAnchor;
export type AnchorId = PdfAnchorId & {
@@ -668,6 +707,7 @@ export type ApiChannelParticipant = {
* Channel list response item.
*/
export type ApiChannelWithLatest = {
+ agent_dm?: null | AgentDmProfile;
/**
* Whether team members automatically join the channel.
*/
@@ -7233,7 +7273,7 @@ export type GetOrCreateChannelResponse = {
*/
export type GetOrCreateDmRequest = {
/**
- * Recipient user id.
+ * Recipient user id (`macro|...`) or agent persona id (`bot|...`).
*/
recipient_id: string;
};
@@ -8910,6 +8950,7 @@ export type MessageChange = {
* Whether the user is currently typing.
*/
active: boolean;
+ agent?: null | AgentTyping;
/**
* Root being replied to, or no root for the parent composer.
*/
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 0c9e06eccc..e26c42b56a 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -148,6 +148,168 @@
}
}
},
+ "/agent-conversations/{channel_id}": {
+ "get": {
+ "tags": ["agent-conversations"],
+ "summary": "The agent conversations in a channel the caller may see. Ordinary channels\nand other people's conversations list none.",
+ "operationId": "list_agent_conversations",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "description": "Conversation channel",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "The caller's agent conversations in the channel",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentConversationsDto"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Conversations temporarily unavailable"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
+ "/agent-conversations/{channel_id}/{bot_id}/start-fresh": {
+ "post": {
+ "tags": ["agent-conversations"],
+ "summary": "Start a fresh agent context, retaining the channel transcript.",
+ "operationId": "start_fresh_agent_conversation",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "bot_id",
+ "in": "path",
+ "description": "Persona the conversation is with",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StartFreshAgentConversationRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "New context reserved"
+ },
+ "404": {
+ "description": "Conversation not found"
+ },
+ "409": {
+ "description": "Context is busy, stale or unavailable"
+ },
+ "503": {
+ "description": "Temporarily unavailable"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
+ "/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry": {
+ "post": {
+ "tags": ["agent-conversations"],
+ "summary": "Explicitly retry a failed message in the conversation's current session.",
+ "operationId": "retry_agent_conversation_turn",
+ "parameters": [
+ {
+ "name": "channel_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "bot_id",
+ "in": "path",
+ "description": "Persona the conversation is with",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "source",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RetryAgentConversationTurnRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": "Retry queued"
+ },
+ "404": {
+ "description": "Conversation or turn not found"
+ },
+ "409": {
+ "description": "Attempt cannot be retried"
+ },
+ "503": {
+ "description": "Temporarily unavailable"
+ }
+ },
+ "security": [
+ {
+ "bearerAuth": []
+ }
+ ]
+ }
+ },
"/agent-models/load": {
"post": {
"tags": ["agent-models"],
@@ -845,6 +1007,16 @@
}
}
},
+ "409": {
+ "description": "The session answers an agent conversation",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -2483,6 +2655,143 @@
}
}
},
+ "AgentConversationDto": {
+ "type": "object",
+ "description": "An agent's conversation in a channel, as the person it is with sees it.",
+ "required": [
+ "channelId",
+ "botId",
+ "name",
+ "available",
+ "settingsChanged",
+ "sessions",
+ "turns"
+ ],
+ "properties": {
+ "available": {
+ "type": "boolean",
+ "description": "Whether the caller may currently send a new prompt."
+ },
+ "avatarUrl": {
+ "type": ["string", "null"],
+ "description": "Optional persona avatar."
+ },
+ "botId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Persona id (without the bot principal prefix)."
+ },
+ "channelId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The channel containing the visible transcript."
+ },
+ "name": {
+ "type": "string",
+ "description": "Persona's historical display name."
+ },
+ "sessions": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentConversationSessionDto"
+ },
+ "description": "The sessions the conversation has run on, oldest first."
+ },
+ "settingsChanged": {
+ "type": "boolean",
+ "description": "Whether new persona settings are available to adopt explicitly."
+ },
+ "turns": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentConversationTurnDto"
+ },
+ "description": "Persistent state of each accepted message and its current attempt."
+ }
+ }
+ },
+ "AgentConversationSessionDto": {
+ "type": "object",
+ "description": "One session a conversation has run on; every channel message stays visible.",
+ "required": ["sessionId", "createdAt", "isCurrent"],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the session began."
+ },
+ "isCurrent": {
+ "type": "boolean",
+ "description": "Whether this is the current agent context."
+ },
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Session whose controls and live events belong to this context."
+ }
+ }
+ },
+ "AgentConversationTurnDto": {
+ "type": "object",
+ "description": "Execution status without exposing the persona prompt or stored credentials.",
+ "required": [
+ "sourceMessageId",
+ "actionId",
+ "sessionId",
+ "state",
+ "retryable",
+ "createdAt"
+ ],
+ "properties": {
+ "actionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Current runtime attempt identity."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the source message was first accepted."
+ },
+ "replyMessageId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The associated agent reply, if it has been posted."
+ },
+ "retryable": {
+ "type": "boolean",
+ "description": "Whether Retry would be accepted now. A failed attempt is not retryable\nuntil its reply says how it ended."
+ },
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Session carrying this turn."
+ },
+ "sourceMessageId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The user's message in the channel timeline."
+ },
+ "state": {
+ "$ref": "#/components/schemas/ConversationTurnState",
+ "description": "Durable execution state."
+ }
+ }
+ },
+ "AgentConversationsDto": {
+ "type": "object",
+ "description": "The agent conversations in a channel the caller may see.",
+ "required": ["conversations"],
+ "properties": {
+ "conversations": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AgentConversationDto"
+ },
+ "description": "Empty for ordinary channels and other people's conversations."
+ }
+ }
+ },
"AgentModelDto": {
"type": "object",
"description": "One model picker option.",
@@ -3295,6 +3604,18 @@
"description": "What accepting a control operation did with it, on the wire.",
"enum": ["sent", "queued"]
},
+ "ConversationTurnState": {
+ "type": "string",
+ "description": "The state of one source message, retained after completion for deduplication.",
+ "enum": [
+ "queued",
+ "running",
+ "succeeded",
+ "failed",
+ "stopped",
+ "interrupted"
+ ]
+ },
"CreateAgentSessionRequest": {
"type": "object",
"description": "Request body for `POST /agent-sessions`.\n\nCarries two shapes, told apart by `workspace`. Naming one asks for an\nexternal session: the runtime is the bot operator's, so the caller has to\nsay which bot and which directory, and must own that bot. Omitting it asks\nfor a managed session, whose runtime this deployment provisions. A managed\nrequest may select an authorized persisted persona with `botId`; omitting\nit uses the deployment's default coding persona. Fields describing someone\nelse's runtime must still be omitted rather than quietly ignored. Mixing\nthe two shapes is refused rather than guessed at.\n\nClients serialize this, so both derives are used.",
@@ -3998,6 +4319,18 @@
}
}
},
+ "RetryAgentConversationTurnRequest": {
+ "type": "object",
+ "description": "The attempt the user saw and chose to retry; prevents double-click reruns.",
+ "required": ["actionId"],
+ "properties": {
+ "actionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Current failed attempt identity."
+ }
+ }
+ },
"SandboxSize": {
"type": "string",
"description": "Named compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.",
@@ -4186,6 +4519,18 @@
}
}
},
+ "StartFreshAgentConversationRequest": {
+ "type": "object",
+ "description": "The session the user is choosing to leave behind.",
+ "required": ["sessionId"],
+ "properties": {
+ "sessionId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Current session id shown in the conversation metadata."
+ }
+ }
+ },
"StartResponse": {
"type": "object",
"description": "Public PKCE challenge and attempt handle; contains no verifier or provider tokens.",
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 63b50faa39..36a859f01b 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -18149,6 +18149,25 @@
"description": "Whether an agent is available everywhere or only in selected channels.",
"enum": ["all", "selected"]
},
+ "AgentDmProfile": {
+ "type": "object",
+ "description": "Historical persona identity displayed beside a private conversation.",
+ "required": ["bot_id", "name"],
+ "properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Persona avatar, when supplied."
+ },
+ "bot_id": {
+ "type": "string",
+ "description": "Persona id without the bot principal prefix."
+ },
+ "name": {
+ "type": "string",
+ "description": "Persona display name."
+ }
+ }
+ },
"AgentMcpServer": {
"type": "object",
"description": "One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.",
@@ -18397,6 +18416,27 @@
],
"description": "Events publishable to [`MacroAgentSessionLifecycleTopic`].\n\nThe serde tag and [`AgentSessionLifecycleEventName`] spell the same wire\nnames: subscribers filter on them, so they are API. The\n`event_names_match_the_wire` test holds the two in step. Exhaustive on\npurpose: a consumer's match should break when a variant is added."
},
+ "AgentTyping": {
+ "type": "object",
+ "description": "An agent session typing through its bot.",
+ "required": ["session_id", "phase"],
+ "properties": {
+ "phase": {
+ "$ref": "#/components/schemas/AgentTypingPhase",
+ "description": "What the agent is doing. Deliberately coarse: a typing event reaches\neveryone in the conversation, and which tool runs on what is for\nviewers who can read the session itself."
+ },
+ "session_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The session whose turn the bot is speaking for."
+ }
+ }
+ },
+ "AgentTypingPhase": {
+ "type": "string",
+ "description": "What a typing agent is doing.",
+ "enum": ["thinking", "writing", "working", "waiting"]
+ },
"Anchor": {
"oneOf": [
{
@@ -18958,6 +18998,17 @@
"is_participant"
],
"properties": {
+ "agent_dm": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AgentDmProfile",
+ "description": "Persona identity when this is the viewer's private agent DM."
+ }
+ ]
+ },
"auto_join_team": {
"type": "boolean",
"description": "Whether team members automatically join the channel."
@@ -29193,7 +29244,7 @@
"properties": {
"recipient_id": {
"type": "string",
- "description": "Recipient user id."
+ "description": "Recipient user id (`macro|...`) or agent persona id (`bot|...`)."
}
}
},
@@ -31679,6 +31730,17 @@
"type": "boolean",
"description": "Whether the user is currently typing."
},
+ "agent": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/AgentTyping",
+ "description": "Present when an agent session is typing through the bot that\nspeaks for it. Names the session, so a viewer who can read it can\nshow the turn live in place of the bare indicator."
+ }
+ ]
+ },
"thread_id": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 7145cdd51f..00e96d3a2c 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -42,6 +42,10 @@ export const agentHarnessExcluded = [
export const agentHarnessBacklog = [
'answerAgentSessionToolApproval',
'getAgentSessionPermissions',
+ // Agent conversation controls (DMs are flag-gated in the web app); not wrapped yet.
+ 'listAgentConversations',
+ 'retryAgentConversationTurn',
+ 'startFreshAgentConversation',
'updateAgentSessionPermissions',
] as const satisfies readonly (keyof AgentHarnessSdk)[];
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index 1a881635b3..c8163c5650 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -13,6 +13,10 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/agent-activity/components/**
+ - apps/web/src/features/agent-dms/components/**
+ - apps/web/src/features/agent-conversations/components/**
+ - apps/web/src/features/agent-interactions/components/**
- apps/web/src/features/billing-lab/components/**
- apps/web/src/features/paywall/components/ai-usage-limit-dialog*
- apps/web/src/features/calendar-team/components/**
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 0ae28093c5..587c1d1f45 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -15,6 +15,10 @@ note: |-
The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/agent-activity/core/**
+ - apps/web/src/features/agent-dms/core/**
+ - apps/web/src/features/agent-conversations/core/**
+ - apps/web/src/features/agent-interactions/core/**
- apps/web/src/features/billing-lab/core/**
- apps/web/src/features/calendar-team/core/**
- apps/web/src/features/tasks-view/core/task-board*
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index a9fae4dcfc..b3106751b6 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -11,6 +11,14 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/agent-activity/queries/**
+ - apps/web/src/features/agent-dms/queries/**
+ - apps/web/src/features/agent-conversations/queries/**
+ - apps/web/src/features/agent-activity/primitives/**
+ - apps/web/src/features/agent-dms/primitives/**
+ - apps/web/src/features/agent-conversations/primitives/**
+ - apps/web/src/features/agent-interactions/queries/**
+ - apps/web/src/features/agent-interactions/primitives/**
- apps/web/src/features/billing-lab/queries/**
- apps/web/src/features/billing-lab/primitives/**
- apps/web/src/features/calendar-team/queries/**
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 817fa1586f..d809bae784 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -15,6 +15,22 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/agent-activity/queries/**
+ - apps/web/src/features/agent-dms/queries/**
+ - apps/web/src/features/agent-conversations/queries/**
+ - apps/web/src/features/agent-activity/primitives/**
+ - apps/web/src/features/agent-dms/primitives/**
+ - apps/web/src/features/agent-conversations/primitives/**
+ - apps/web/src/features/agent-activity/components/**
+ - apps/web/src/features/agent-dms/components/**
+ - apps/web/src/features/agent-conversations/components/**
+ - apps/web/src/features/agent-activity/views/**
+ - apps/web/src/features/agent-dms/views/**
+ - apps/web/src/features/agent-conversations/views/**
+ - apps/web/src/features/agent-interactions/queries/**
+ - apps/web/src/features/agent-interactions/primitives/**
+ - apps/web/src/features/agent-interactions/components/**
+ - apps/web/src/features/agent-interactions/views/**
- apps/web/src/features/billing-lab/context/**
- apps/web/src/features/billing-lab/queries/**
- apps/web/src/features/billing-lab/primitives/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index ce5fafca9b..bff7c9e2b5 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -13,6 +13,10 @@ note: |-
untyped wire JSON for property-changed rows. In block-agent, `ui/` is
the presentation layer and `component/` is the composition layer.
files:
+ - apps/web/src/features/agent-activity/components/**
+ - apps/web/src/features/agent-dms/components/**
+ - apps/web/src/features/agent-conversations/components/**
+ - apps/web/src/features/agent-interactions/components/**
- apps/web/src/features/billing-lab/components/**
- apps/web/src/features/paywall/components/ai-usage-limit-dialog*
- apps/web/src/features/calendar-team/components/**
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index 4a29b665c8..aaa63069b5 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -15,6 +15,10 @@ note: |-
The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.
Block-agent names its rendering layers `ui/` and `component/`.
files:
+ - apps/web/src/features/agent-activity/core/**
+ - apps/web/src/features/agent-dms/core/**
+ - apps/web/src/features/agent-conversations/core/**
+ - apps/web/src/features/agent-interactions/core/**
- apps/web/src/features/billing-lab/core/**
- apps/web/src/features/calendar-team/core/**
- apps/web/src/features/tasks-view/core/task-board*
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 9f63ba2c75..c6931ab9fa 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -11,6 +11,14 @@ note: |-
with fake clients and controllers with fake capabilities; neither imports
rendering code, including block-agent’s `ui/` and `component/` layers.
files:
+ - apps/web/src/features/agent-activity/queries/**
+ - apps/web/src/features/agent-dms/queries/**
+ - apps/web/src/features/agent-conversations/queries/**
+ - apps/web/src/features/agent-activity/primitives/**
+ - apps/web/src/features/agent-dms/primitives/**
+ - apps/web/src/features/agent-conversations/primitives/**
+ - apps/web/src/features/agent-interactions/queries/**
+ - apps/web/src/features/agent-interactions/primitives/**
- apps/web/src/features/billing-lab/queries/**
- apps/web/src/features/billing-lab/primitives/**
- apps/web/src/features/calendar-team/queries/**
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index d7cc83994f..928ade58d8 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -15,6 +15,22 @@ note: |-
`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` for
presentation and `component/` for composition.
files:
+ - apps/web/src/features/agent-activity/queries/**
+ - apps/web/src/features/agent-dms/queries/**
+ - apps/web/src/features/agent-conversations/queries/**
+ - apps/web/src/features/agent-activity/primitives/**
+ - apps/web/src/features/agent-dms/primitives/**
+ - apps/web/src/features/agent-conversations/primitives/**
+ - apps/web/src/features/agent-activity/components/**
+ - apps/web/src/features/agent-dms/components/**
+ - apps/web/src/features/agent-conversations/components/**
+ - apps/web/src/features/agent-activity/views/**
+ - apps/web/src/features/agent-dms/views/**
+ - apps/web/src/features/agent-conversations/views/**
+ - apps/web/src/features/agent-interactions/queries/**
+ - apps/web/src/features/agent-interactions/primitives/**
+ - apps/web/src/features/agent-interactions/components/**
+ - apps/web/src/features/agent-interactions/views/**
- apps/web/src/features/billing-lab/context/**
- apps/web/src/features/billing-lab/queries/**
- apps/web/src/features/billing-lab/primitives/**
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index c8771a8bad..1aeee7d695 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -74,6 +74,7 @@ pub struct ApiStates<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes
routine_sessions: Router,
coding_agents: Router,
capabilities: Router,
+ conversations: Router,
pull_requests: Router,
tool_approvals: Router,
changes: AgentChangesRouterState<Changes, Access, Auth>,
@@ -104,6 +105,7 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
routine_sessions: Router::new(),
coding_agents: Router::new(),
capabilities: Router::new(),
+ conversations: Router::new(),
pull_requests: Router::new(),
tool_approvals: Router::new(),
changes,
@@ -116,6 +118,12 @@ impl<T, R, Opener, Bots, Requests, Access, Auth, Models, Changes>
self
}
+ /// Attach owner-only agent conversation routes.
+ pub fn with_conversations(mut self, router: Router) -> Self {
+ self.conversations = router;
+ self
+ }
+
/// Attach the optional owner-authenticated Claude demo connection routes.
pub fn with_claude_auth(mut self, router: Router) -> Self {
self.claude_auth = router;
@@ -264,6 +272,7 @@ where
.merge(states.routine_sessions)
.merge(states.coding_agents)
.merge(states.capabilities)
+ .merge(states.conversations)
.nest("/runtime", runtime_gateway_router(states.gateway))
}
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 7bba8e97cc..6530110b76 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -90,6 +90,9 @@ impl Modify for SecurityAddon {
axum_router::put_agent_coding_preferences_handler,
model_load::load_agent_models_handler,
capability_discovery::discover_agent_capabilities_handler,
+ agent_harness::inbound::conversations::list_agent_conversations,
+ agent_harness::inbound::conversations::retry_agent_conversation_turn,
+ agent_harness::inbound::conversations::start_fresh_agent_conversation,
repositories::list_agent_repositories_handler,
repositories::list_agent_repository_branches_handler,
changes_router::get_agent_session_changes_handler,
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index 23cd48f1c1..6603dc3776 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -69,6 +69,10 @@ fn default_pipedream_environment() -> String {
#[derive(macro_config::MacroConfig)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub struct Config {
+ /// Hide agent DM contexts from standalone lists. Enable only after all
+ /// replicas use the independent for_warming lifecycle marker.
+ #[macro_config_default(false)]
+ pub hide_agent_dm_sessions: bool,
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rs
index 51877fd080..5e3223ee95 100644
--- a/services/agent_harness_service/src/containers.rs
+++ b/services/agent_harness_service/src/containers.rs
@@ -174,7 +174,7 @@ where
self.inmem()
.manager
.attach(*facts, Some(command.egress.session_token))
- .await,
+ .await?,
),
)),
Route::Sandbox => self
@@ -240,7 +240,7 @@ where
self.inmem()
.manager
.attach(*facts, Some(token.as_str().to_owned()))
- .await,
+ .await?,
),
))
}
diff --git a/services/agent_harness_service/src/conversation_admission.rs b/services/agent_harness_service/src/conversation_admission.rs
new file mode 100644
index 0000000000..cc3f2725a8
--- /dev/null
+++ b/services/agent_harness_service/src/conversation_admission.rs
@@ -0,0 +1,62 @@
+//! Journaling a conversation message before the broker event that carried it
+//! is acknowledged.
+
+use std::time::Duration;
+
+#[cfg(test)]
+mod test;
+
+/// How a message the journal refused is offered to it again.
+#[derive(Debug, Clone, Copy)]
+pub struct Retries {
+ /// Attempts in all, the first included.
+ pub attempts: u32,
+ /// The wait before the second attempt. Each later wait doubles.
+ pub first_wait: Duration,
+ /// The longest any wait grows.
+ pub longest_wait: Duration,
+}
+
+/// About twenty seconds of waits across six attempts: enough to ride out a
+/// dropped connection or a conversation briefly busy elsewhere, without
+/// holding every later event for long.
+pub const ADMISSION_RETRIES: Retries = Retries {
+ attempts: 6,
+ first_wait: Duration::from_secs(1),
+ longest_wait: Duration::from_secs(8),
+};
+
+/// Run `admit` until the journal takes the message, waiting longer after
+/// each failure.
+///
+/// The consumer acknowledges a conversation message's event only once the
+/// journal holds the message; recovery runs it from there. A failure is
+/// retried here rather than ending the consumer, which would stop every
+/// session this replica runs. The error of the last attempt is returned for
+/// the caller to report and acknowledge, since holding the event would hold
+/// every event behind it.
+pub async fn journal<T, E, F>(retries: Retries, mut admit: impl FnMut() -> F) -> Result<T, E>
+where
+ E: std::fmt::Debug,
+ F: Future<Output = Result<T, E>>,
+{
+ let mut wait = retries.first_wait;
+ let mut attempt = 1;
+ loop {
+ match admit().await {
+ Ok(admitted) => return Ok(admitted),
+ Err(error) if attempt < retries.attempts => {
+ tracing::warn!(
+ ?error,
+ attempt,
+ ?wait,
+ "could not journal a conversation message; retrying"
+ );
+ tokio::time::sleep(wait).await;
+ wait = (wait * 2).min(retries.longest_wait);
+ attempt += 1;
+ }
+ Err(error) => return Err(error),
+ }
+ }
+}
diff --git a/services/agent_harness_service/src/conversation_admission/test.rs b/services/agent_harness_service/src/conversation_admission/test.rs
new file mode 100644
index 0000000000..06a25b4f98
--- /dev/null
+++ b/services/agent_harness_service/src/conversation_admission/test.rs
@@ -0,0 +1,35 @@
+use super::*;
+use std::sync::atomic::{AtomicU32, Ordering};
+
+const QUICK: Retries = Retries {
+ attempts: 4,
+ first_wait: Duration::from_millis(1),
+ longest_wait: Duration::from_millis(2),
+};
+
+#[tokio::test]
+async fn a_refused_message_is_offered_again_until_the_journal_takes_it() {
+ let attempts = AtomicU32::new(0);
+ let admitted = journal(QUICK, || async {
+ if attempts.fetch_add(1, Ordering::SeqCst) < 2 {
+ Err("pool timed out")
+ } else {
+ Ok("journaled")
+ }
+ })
+ .await;
+ assert_eq!(admitted, Ok("journaled"));
+ assert_eq!(attempts.load(Ordering::SeqCst), 3);
+}
+
+#[tokio::test]
+async fn a_message_the_journal_keeps_refusing_is_returned_after_the_last_attempt() {
+ let attempts = AtomicU32::new(0);
+ let admitted: Result<(), _> = journal(QUICK, || async {
+ attempts.fetch_add(1, Ordering::SeqCst);
+ Err("conversation context stayed busy")
+ })
+ .await;
+ assert_eq!(admitted, Err("conversation context stayed busy"));
+ assert_eq!(attempts.load(Ordering::SeqCst), QUICK.attempts);
+}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index f7d2bb33aa..38b4fa3fc2 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -14,6 +14,7 @@ mod coding_agent;
mod coding_agents;
mod config;
mod containers;
+mod conversation_admission;
mod external_session_requests;
mod harness_bindings;
mod internal_mcp;
@@ -267,7 +268,12 @@ async fn run() -> anyhow::Result<()> {
// it happen.
let session_registrar =
OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone())));
- let session_repo = PgAgentSessionRepo::new(pool.clone(), session_registrar.clone());
+ let session_list_policy = agent_session::domain::list_visibility::SessionListPolicy {
+ hide_agent_dms: config.hide_agent_dm_sessions,
+ };
+ let session_repo = PgAgentSessionRepo::new(pool.clone(), session_registrar.clone())
+ .with_list_policy(session_list_policy);
+ session_list_policy.reconcile(&session_repo).await?;
let entity_access = Arc::new(
entity_access::domain::service::EntityAccessServiceImpl::new(
entity_access::outbound::PgAccessRepository::new(pool.clone()),
@@ -1024,8 +1030,24 @@ async fn run() -> anyhow::Result<()> {
// to speak through: it is the same service instance the harness routes
// commands with, and a clone shares its replica identity.
let draining_sessions = sessions.clone();
+ let conversation_turns = Arc::new(
+ agent_harness::outbound::conversation_turns::PgConversationTurnStore::new(pool.clone()),
+ );
+ let conversations_service = Arc::new(
+ agent_harness::domain::conversations::AgentConversationsService::new(
+ PgChannelsRepo::new(pool.clone()),
+ bots::domain::service::BotServiceImpl::new(
+ PgBotsRepo::new(pool.clone()),
+ macro_event_broker::NoopMacroEventBroker,
+ ),
+ PgBotsRepo::new(pool.clone()),
+ session_repo.clone(),
+ )
+ .with_turns(conversation_turns.clone()),
+ );
let harness = Arc::new(
AgentHarnessService::new(
+ Some(conversations_service.clone()),
sessions,
containers,
announcer,
@@ -1057,16 +1079,24 @@ async fn run() -> anyhow::Result<()> {
// notification ingress channel messages use.
IngressAgentSessionNotifier::new(Arc::clone(&notifications)),
)
+ .with_conversation_turns(conversation_turns)
.with_admission(admission.clone())
.with_repositories(open_repositories)
.with_warm_sessions(Arc::new(session_repo.clone()), tool_catalog),
);
let warm_cleanup = Arc::clone(&harness);
+ let session_visibility_repo = session_repo.clone();
tokio::spawn(async move {
let mut ticks = tokio::time::interval(std::time::Duration::from_secs(60));
loop {
ticks.tick().await;
warm_cleanup.reap_warm_sessions().await;
+ if let Err(error) = session_list_policy
+ .reconcile(&session_visibility_repo)
+ .await
+ {
+ tracing::warn!(?error, "could not reconcile agent DM session visibility");
+ }
}
});
let model_probe_timeout = std::time::Duration::from_secs(10);
@@ -1320,6 +1350,12 @@ async fn run() -> anyhow::Result<()> {
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
),
);
+ let conversations = agent_harness::inbound::conversations::agent_conversation_router(
+ agent_harness::inbound::conversations::AgentConversationRouterState::new(
+ conversations_service,
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ ),
+ );
let tool_approval_answers = tool_approvals_router(ToolApprovalsRouterState::new(
tool_approvals,
entity_access.clone(),
@@ -1339,6 +1375,7 @@ async fn run() -> anyhow::Result<()> {
.with_claude_auth(claude_auth)
.with_sharing(sharing)
.with_routine_sessions(routine_sessions)
+ .with_conversations(conversations)
.with_coding_agents(coding_agents)
.with_capabilities(capabilities)
.with_pull_requests(pull_requests)
@@ -1374,6 +1411,33 @@ async fn run() -> anyhow::Result<()> {
}
});
+ // Viewers drop a typing indicator nobody refreshes after a few seconds;
+ // every turn running here keeps its agent's indicator alive until it ends.
+ let typing_harness = harness.clone();
+ let typing_heartbeat = tokio::spawn(async move {
+ let mut ticker = tokio::time::interval(std::time::Duration::from_secs(3));
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ ticker.tick().await;
+ typing_harness.refresh_typing().await;
+ }
+ });
+
+ let recovery_harness = harness.clone();
+ let dm_recovery = tokio::spawn(async move {
+ let mut ticker = tokio::time::interval(std::time::Duration::from_secs(10));
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ ticker.tick().await;
+ if let Err(error) = recovery_harness.recover_conversations().await {
+ tracing::error!(
+ ?error,
+ "failed to reconcile durable agent conversation turns"
+ );
+ }
+ }
+ });
+
// A hard abort cannot emit a disconnect. Reconcile expired leases so
// viewers stop showing a turn as working without issuing another command.
let recovery_repo = session_repo.clone();
@@ -1519,12 +1583,44 @@ async fn run() -> anyhow::Result<()> {
let pending = match routed {
RoutedTrigger::Command(session_id, command) => {
+ let (session_id, command) = if let HarnessCommand::ConversationMessage(open) = command {
+ let admitted = {
+ let (harness, open) = (&harness, &open);
+ conversation_admission::journal(
+ conversation_admission::ADMISSION_RETRIES,
+ move || harness.admit_conversation_message(session_id, open.clone()),
+ )
+ .await
+ };
+ let admitted = match admitted {
+ Ok(admitted) => admitted,
+ Err(error) => {
+ // Not returned: ending the consumer would stop every
+ // session this replica runs, and holding the event
+ // would hold every event behind it. A message the
+ // journal did record is still run by recovery.
+ record_span_error(&tracing::Span::current(), &error);
+ tracing::error!(error = ?error, %session_id, "acknowledging a conversation message the journal could not take");
+ commit_message(&consumer, kafka_message)?;
+ return Ok(None);
+ }
+ };
+ let Some((session_id, open)) = admitted else {
+ // Its conversation is gone, or its sender may not
+ // prompt it: every redelivery would be refused too.
+ tracing::warn!(%session_id, "dropping a conversation message that can no longer be admitted");
+ commit_message(&consumer, kafka_message)?;
+ return Ok(None);
+ };
+ (session_id, HarnessCommand::ConversationMessage(open))
+ } else { (session_id, command) };
tracing::Span::current()
.record("agent.session.id", tracing::field::display(session_id));
let event_type = match &command {
HarnessCommand::Open(_) => "agent_trigger.new",
HarnessCommand::Deliver(_) => "agent_trigger.existing",
HarnessCommand::Delete => "agent_trigger.delete",
+ HarnessCommand::ConversationMessage(_) => "agent_trigger.conversation_message",
HarnessCommand::SetSandboxSize(_) => {
"agent_trigger.set_sandbox_size"
}
@@ -1581,8 +1677,8 @@ async fn run() -> anyhow::Result<()> {
}
};
- // Intentionally at-most-once: admission precedes commit, but
- // long-running harness work is independent of Kafka afterward.
+ // Conversation messages are journaled before commit and recovered independently
+ // of Kafka. Existing mention traffic keeps its admission policy.
commit_message(&consumer, kafka_message)?;
Ok(Some(pending))
}
@@ -1621,6 +1717,8 @@ async fn run() -> anyhow::Result<()> {
trigger.abort();
egress_http.abort();
heartbeat.abort();
+ dm_recovery.abort();
+ typing_heartbeat.abort();
recovery.abort();
runtime_commands.abort();
let stop_failures = container_shutdown.shutdown_all().await;
diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rs
index 04e73e6881..8cb600ac0e 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -213,6 +213,19 @@ async fn run(
),
),
)
+ .with_conversations(std::sync::Arc::new(
+ agent_trigger::domain::conversations::ConversationRouter::new(
+ PgChannelsRepo::new(pool.clone()),
+ bots::domain::service::BotServiceImpl::new(
+ PgBotsRepo::new(pool.clone()),
+ macro_event_broker::NoopMacroEventBroker,
+ ),
+ PgAgentSessionRepo::new(
+ pool.clone(),
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(PgBotsRepo::new(pool.clone()))),
+ ),
+ ),
+ ))
.with_admission(admission);
let channel_types = ChannelRepoTypeLookup::new(PgChannelsRepo::new(pool.clone()));
let publisher = MacroEventBrokerService::new(
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index ec15a1256e..209d00b3ff 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -27,6 +27,7 @@ local_auth = ["macro_authorization/local_auth"]
location_check = []
[dependencies]
+async-trait = { workspace = true }
ai_billing = { path = "../../crates/ai_billing" }
roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
diff --git a/services/document_storage_service/src/outbound/agent_dm_authorizer.rs b/services/document_storage_service/src/outbound/agent_dm_authorizer.rs
new file mode 100644
index 0000000000..5ddc9cdf45
--- /dev/null
+++ b/services/document_storage_service/src/outbound/agent_dm_authorizer.rs
@@ -0,0 +1,91 @@
+//! Persona eligibility through the owning bot service.
+
+use bot_id::BotId;
+use bots::domain::ports::BotRepo;
+use bots::domain::ports::{AgentDmEligibility, BotError};
+use channels::domain::agent_dm::{AgentDmProfile, AgentDmProfiles, AgentDmRepo};
+use channels::domain::{agent_dm::AgentDmAuthorizer, ports::ChannelMutationErr};
+use macro_user_id::user_id::MacroUserIdStr;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+/// Reads historical persona presentation through its owning domain port.
+pub struct AgentDmProfileReader<C, B> {
+ channels: C,
+ bots: B,
+}
+
+impl<C, B> AgentDmProfileReader<C, B> {
+ /// Compose channel binding and bot profile readers at the service root.
+ pub fn new(channels: C, bots: B) -> Self {
+ Self { channels, bots }
+ }
+}
+
+#[async_trait::async_trait]
+impl<C: AgentDmRepo, B: BotRepo> AgentDmProfiles for AgentDmProfileReader<C, B> {
+ async fn for_channels(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ channel_ids: &[Uuid],
+ ) -> Result<HashMap<Uuid, AgentDmProfile>, rootcause::Report> {
+ if channel_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+ let bindings: Vec<_> = self
+ .channels
+ .for_user(user_id)
+ .await
+ .map_err(|error| rootcause::report!(error))?
+ .into_iter()
+ .filter(|dm| channel_ids.contains(&dm.channel_id))
+ .collect();
+ let bot_ids: Vec<_> = bindings.iter().map(|dm| dm.bot_id).collect();
+ let profiles = self
+ .bots
+ .get_bot_profiles(&bot_ids)
+ .await
+ .map_err(|error| rootcause::report!(error.into()))?;
+ Ok(bindings
+ .into_iter()
+ .map(|dm| {
+ let profile = profiles.get(&dm.bot_id);
+ (
+ dm.channel_id,
+ AgentDmProfile {
+ bot_id: dm.bot_id,
+ name: profile
+ .map(|p| p.name.clone())
+ .unwrap_or_else(|| "Unavailable agent".to_owned()),
+ avatar_url: profile.and_then(|p| p.avatar_url.clone()),
+ },
+ )
+ })
+ .collect())
+ }
+}
+
+/// Adapts the bot service's authorized persona catalog to channel DM creation.
+pub struct BotServiceDmAuthorizer<B>(pub B);
+
+impl<B: AgentDmEligibility> AgentDmAuthorizer for BotServiceDmAuthorizer<B> {
+ async fn authorize(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<(), ChannelMutationErr> {
+ self.0
+ .authorize_agent_dm(user_id, bot_id)
+ .await
+ .map_err(|error| match error {
+ BotError::Unauthorized | BotError::NotFound(_) => {
+ ChannelMutationErr::Forbidden("This agent is unavailable to you".to_owned())
+ }
+ BotError::BadRequest(message) => ChannelMutationErr::BadRequest(message),
+ BotError::Unavailable(message) => {
+ ChannelMutationErr::Repo(anyhow::anyhow!(message))
+ }
+ BotError::Repo(error) => ChannelMutationErr::Repo(error),
+ })
+ }
+}
diff --git a/services/document_storage_service/src/outbound/mod.rs b/services/document_storage_service/src/outbound/mod.rs
index da4a69ca4f..259265df6d 100644
--- a/services/document_storage_service/src/outbound/mod.rs
+++ b/services/document_storage_service/src/outbound/mod.rs
@@ -1,3 +1,4 @@
//! Outbound adapters owned by document storage service composition.
+pub mod agent_dm_authorizer;
pub mod entity_mutation;
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index 0ac6f6975a..4cceef116a 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -482,12 +482,17 @@ pub async fn run() -> anyhow::Result<()> {
// Create the channel list service used by soup.
// Create the legacy channel list router state for routes mounted under /comms.
+ let agent_dm_profiles = Arc::new(outbound::agent_dm_authorizer::AgentDmProfileReader::new(
+ PgChannelsRepo::new(db.clone()),
+ PgBotsRepo::new(db.clone()),
+ ));
let channel_list_state = ChannelListRouterState::new(
ChannelListServiceImpl::new(
PgChannelsRepo::new(db.clone()),
PgChannelsRepo::new(db.clone()),
frecency_storage.clone(),
- ),
+ )
+ .with_agent_dm_profiles(agent_dm_profiles.clone()),
authorization_state.clone(),
);
@@ -1182,10 +1187,15 @@ pub async fn run() -> anyhow::Result<()> {
let channels_service = Arc::new(
ChannelServiceImpl::with_dependencies(
- channels_repo,
+ channels_repo.clone(),
SpawnedChannelEventDispatcher::new(channel_side_effects.clone()),
PgChannelReferenceSharePermissions::new(db.clone(), entity_access_service.clone()),
)
+ .with_agent_direct_messages(Arc::new(channels::domain::agent_dm::AgentDmService::new(
+ channels_repo,
+ outbound::agent_dm_authorizer::BotServiceDmAuthorizer(bots_service.clone()),
+ SpawnedChannelEventDispatcher::new(channel_side_effects.clone()),
+ )))
.with_picture_files(
channels::outbound::static_file_pictures::StaticFileChannelPictures::new(
static_file_service_client::StaticFileServiceClient::new(
@@ -1539,7 +1549,8 @@ pub async fn run() -> anyhow::Result<()> {
PgChannelsRepo::new(db.clone()),
PgChannelsRepo::new(db.clone()),
frecency_storage.clone(),
- ),
+ )
+ .with_agent_dm_profiles(agent_dm_profiles),
call::domain::service::CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone())),
crm_service.clone(),
GithubPullRequestServiceImpl::new(
@@ -1567,7 +1578,13 @@ pub async fn run() -> anyhow::Result<()> {
PgChannelsRepo::new(readonly_db.clone()),
PgChannelsRepo::new(readonly_db.clone()),
frecency_storage.clone(),
- ),
+ )
+ .with_agent_dm_profiles(Arc::new(
+ outbound::agent_dm_authorizer::AgentDmProfileReader::new(
+ PgChannelsRepo::new(readonly_db.clone()),
+ PgBotsRepo::new(readonly_db.clone()),
+ ),
+ )),
call::domain::service::CallRecordQueryServiceImpl::new(PgCallRepo::new(
readonly_db.clone(),
)),
diff --git a/services/lexical-service/src/endpoints/agent-announcement.test.ts b/services/lexical-service/src/endpoints/agent-announcement.test.ts
index a7d9c18eb3..4cf1b27fcd 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.test.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.test.ts
@@ -109,6 +109,36 @@ describe('agent announcements', () => {
markdown: `${link}\n\nSure.\n\n- done`,
});
});
+ it('composes a private reply from segments, with steps as a live node', async () => {
+ const response = await request({
+ chatReply: {
+ sessionId: 'session',
+ link: false,
+ body: {
+ kind: 'segments',
+ segments: [
+ { kind: 'prose', markdown: 'Checking first.' },
+ {
+ kind: 'activity',
+ turn: 2,
+ segment: 1,
+ sealed: true,
+ rows: [
+ { id: 't1', label: 'Ran', detail: 'ls', status: 'completed' },
+ { id: 't2', label: 'Read', detail: null, status: 'completed' },
+ ],
+ },
+ ],
+ footer: null,
+ },
+ },
+ });
+ expect(response.status).toBe(200);
+ const { markdown } = await response.json<{ markdown: string }>();
+ expect(markdown).toBe(
+ 'Checking first.\n\n<m-agent-activity>{"agentSessionId":"session","turn":2,"segment":1,"rows":[{"id":"t1","label":"Ran","status":"completed","detail":"ls"},{"id":"t2","label":"Read","status":"completed"}],"sealed":true}</m-agent-activity>'
+ );
+ });
it('rejects a chat reply body it does not know', async () => {
const response = await request({
chatReply: { sessionId: 'session', body: { kind: 'spinner' } },
diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.ts
index a973821dfe..b2192a0859 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.ts
@@ -1,3 +1,4 @@
+import { AGENT_ACTIVITY_STATUSES } from '@macro-inc/lexical-core/nodes/AgentActivityNode';
import { CONNECT_APP_TARGETS } from '@macro-inc/lexical-core/nodes/ConnectAppNode';
import {
MAGIC_CHIP_AUTHORS,
@@ -55,12 +56,37 @@ const sessionAnnouncementRequest = z.object({
* turn runs, or prose the harness patches in - the answer, a fallback for a
* turn that said nothing, a question only the session view can answer.
*/
+const activityRow = z.object({
+ id: z.string(),
+ label: z.string(),
+ detail: z.string().nullish(),
+ status: z.enum(AGENT_ACTIVITY_STATUSES),
+});
+
+const replySegment = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('prose'), markdown: z.string() }),
+ z.object({
+ kind: z.literal('activity'),
+ turn: z.number().int().nonnegative(),
+ segment: z.number().int().nonnegative(),
+ rows: z.array(activityRow),
+ sealed: z.boolean(),
+ }),
+]);
+
const chatReplyRequest = z.object({
chatReply: z.object({
sessionId: z.string().min(1),
+ link: z.boolean().optional(),
body: z.discriminatedUnion('kind', [
z.object({ kind: z.literal('pending') }),
z.object({ kind: z.literal('markdown'), markdown: z.string() }),
+ z.object({
+ kind: z.literal('segments'),
+ segments: z.array(replySegment),
+ pending: z.boolean().optional(),
+ footer: z.string().nullish(),
+ }),
]),
}),
});
@@ -121,7 +147,7 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
});
}
if ('chatReply' in body) {
- const { sessionId, body: replyBody } = body.chatReply;
+ const { sessionId, link, body: replyBody } = body.chatReply;
// The schema requires a body, but the discriminated union does not
// survive chanfana's OpenAPI round-trip as required, so it arrives
// typed as optional. Refuse rather than invent a state: a reply with
@@ -130,7 +156,31 @@ export class AgentAnnouncementEndpoint extends OpenAPIRoute {
throw new Error('chatReply needs a body');
}
return c.json({
- markdown: composeAgentChatReply({ sessionId, body: replyBody }),
+ markdown: composeAgentChatReply({
+ sessionId,
+ link,
+ body:
+ replyBody.kind === 'segments'
+ ? {
+ kind: 'segments',
+ pending: replyBody.pending,
+ footer: replyBody.footer ?? undefined,
+ segments: replyBody.segments.map((segment) =>
+ segment.kind === 'prose'
+ ? segment
+ : {
+ ...segment,
+ rows: segment.rows.map((row) => ({
+ id: row.id,
+ label: row.label,
+ status: row.status,
+ ...(row.detail ? { detail: row.detail } : {}),
+ })),
+ }
+ ),
+ }
+ : replyBody,
+ }),
});
}
const target = body.replyTarget;
diff --git a/services/lexical-service/src/endpoints/agent-context.test.ts b/services/lexical-service/src/endpoints/agent-context.test.ts
index 20bc7b4957..e8977c5382 100644
--- a/services/lexical-service/src/endpoints/agent-context.test.ts
+++ b/services/lexical-service/src/endpoints/agent-context.test.ts
@@ -30,4 +30,25 @@ describe('agent context', () => {
const { markdown } = await response.json<{ markdown: string }>();
expect(markdown).toContain(`conversation type=\\"${type}\\"`);
});
+
+ it('composes a turn of a private conversation', async () => {
+ const response = await request({
+ promptMarkdown: 'what changed?',
+ trigger: {
+ kind: 'conversation',
+ surface: {
+ type: 'channel',
+ id: 'dm-1',
+ channel_type: 'direct_message',
+ },
+ prompt_message_id: 'm-1',
+ sender: { id: 'macro|[email protected]', name: 'Ada' },
+ reply_target: { kind: 'none' },
+ },
+ });
+ expect(response.status).toBe(200);
+ const { markdown } = await response.json<{ markdown: string }>();
+ expect(markdown).toContain(`trigger kind=\\"conversation\\"`);
+ expect(markdown).toContain('your private conversation with the user');
+ });
});
diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.ts
index 7f23f13235..0f2d617ce5 100644
--- a/services/lexical-service/src/endpoints/agent-context.ts
+++ b/services/lexical-service/src/endpoints/agent-context.ts
@@ -324,6 +324,7 @@ const routineTrigger = z.discriminatedUnion('type', [
const triggerContextSchema = z.discriminatedUnion('kind', [
discussionContext.extend({ kind: z.literal('mentioned') }),
+ discussionContext.extend({ kind: z.literal('conversation') }),
z.object({
kind: z.literal('follow_up'),
addressed_by: z.enum(['mention', 'explicit_reply', 'inferred']),