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.

fix(cursor): recover missed runs safely (#6233)

Wolf Mermelsteind09a0005d2a8
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 5d854dfc87..dfe1cf8c2e 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1121,6 +1121,7 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/agent_session",
"crates/ai_toolset",
"crates/ai_usage",
"crates/analytics_client",
@@ -1128,6 +1129,7 @@
"crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
+ "crates/bots",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -2439,8 +2441,65 @@
"crates/workspace-hack"
],
"cursor_cloud_agents": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/agent_session",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/attachment",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/bots",
+ "crates/broadcast",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
"crates/cursor_cloud_agents",
+ "crates/document_sub_type",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/frecency",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/invite_email",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/prompt",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/share_permission_db_utils",
+ "crates/sqs_worker",
"crates/workspace-hack"
],
"database_env_vars": [
diff --git a/.sqlx/query-51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458.json b/.sqlx/query-06d9cc84b26980c300da2331e8682b812404c632d70179d2d94780496e1318ea.json
similarity index 88%
rename from .sqlx/query-51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458.json
rename to .sqlx/query-06d9cc84b26980c300da2331e8682b812404c632d70179d2d94780496e1318ea.json
index b352a54dc2..f67dac929a 100644
--- a/.sqlx/query-51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458.json
+++ b/.sqlx/query-06d9cc84b26980c300da2331e8682b812404c632d70179d2d94780496e1318ea.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",
"describe": {
"columns": [
{
@@ -122,6 +122,11 @@
"ordinal": 23,
"name": "external_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 24,
+ "name": "external_last_run_id?",
+ "type_info": "Text"
}
],
"parameters": {
@@ -153,8 +158,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "51442f5d740386b1d930feba1450f46991917be4d87a9774105daa1c245bd458"
+ "hash": "06d9cc84b26980c300da2331e8682b812404c632d70179d2d94780496e1318ea"
}
diff --git a/.sqlx/query-0ebb2e76d326903270315dda9a1502008a38e942445fe8b18a4c94671029d56b.json b/.sqlx/query-0ebb2e76d326903270315dda9a1502008a38e942445fe8b18a4c94671029d56b.json
new file mode 100644
index 0000000000..c73f29f1f7
--- /dev/null
+++ b/.sqlx/query-0ebb2e76d326903270315dda9a1502008a38e942445fe8b18a4c94671029d56b.json
@@ -0,0 +1,19 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE agent_session AS session\n SET history_start_log_id = boundary.id\n FROM agent_session_log AS boundary\n WHERE session.id = $1\n AND session.manager_replica_id = $2 AND session.manager_fence = $3\n AND boundary.id = $4 AND boundary.agent_session_id = session.id\n AND (boundary.created_at, boundary.id) <= ($5, $6)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Int8",
+ "Uuid",
+ "Timestamptz",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0ebb2e76d326903270315dda9a1502008a38e942445fe8b18a4c94671029d56b"
+}
diff --git a/.sqlx/query-18fd730ea7a2734ac0d674edec980025a77971dac52498a2adb9470e6dc73787.json b/.sqlx/query-18fd730ea7a2734ac0d674edec980025a77971dac52498a2adb9470e6dc73787.json
deleted file mode 100644
index 34ca00b9bf..0000000000
--- a/.sqlx/query-18fd730ea7a2734ac0d674edec980025a77971dac52498a2adb9470e6dc73787.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session_log (id, agent_session_id, user_id, direction, content)\n SELECT $1, $2, $3, $4, $5\n WHERE EXISTS (\n SELECT 1 FROM agent_session\n WHERE id = $2 AND manager_replica_id = $6 AND manager_fence = $7\n )\n RETURNING created_at\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "created_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid",
- "Text",
- "Text",
- "Jsonb",
- "Uuid",
- "Int8"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "18fd730ea7a2734ac0d674edec980025a77971dac52498a2adb9470e6dc73787"
-}
diff --git a/.sqlx/query-1cde65d3dac81774186bec91e2b2f0144945e2536724a934a78479034274327b.json b/.sqlx/query-1cde65d3dac81774186bec91e2b2f0144945e2536724a934a78479034274327b.json
deleted file mode 100644
index 8cc0be5575..0000000000
--- a/.sqlx/query-1cde65d3dac81774186bec91e2b2f0144945e2536724a934a78479034274327b.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n agent_session_id,\n user_id AS \"user_id: MacroUserIdStr\",\n direction,\n content,\n created_at\n FROM agent_session_log\n WHERE agent_session_id = $1\n ORDER BY created_at ASC, id ASC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "agent_session_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "user_id: MacroUserIdStr",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "direction",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "content",
- "type_info": "Jsonb"
- },
- {
- "ordinal": 4,
- "name": "created_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- false,
- false
- ]
- },
- "hash": "1cde65d3dac81774186bec91e2b2f0144945e2536724a934a78479034274327b"
-}
diff --git a/.sqlx/query-221709e79628a00db4a4a982ee3a6c4d8138634bc34e4405308fb0e0249623ce.json b/.sqlx/query-221709e79628a00db4a4a982ee3a6c4d8138634bc34e4405308fb0e0249623ce.json
new file mode 100644
index 0000000000..607ab38891
--- /dev/null
+++ b/.sqlx/query-221709e79628a00db4a4a982ee3a6c4d8138634bc34e4405308fb0e0249623ce.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE external_agent_session AS external\n SET last_run_id = $2,\n updated_at = now()\n FROM agent_session AS session\n WHERE external.agent_session_id = $1\n AND session.id = external.agent_session_id\n AND session.manager_replica_id = $3\n AND session.manager_fence = $4\n AND external.provider = 'cursor'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "221709e79628a00db4a4a982ee3a6c4d8138634bc34e4405308fb0e0249623ce"
+}
diff --git a/.sqlx/query-9c33b5ff424ef9992848b2bffb76ef196f081d13463019d3705b2aad59ba6a30.json b/.sqlx/query-2eb18e3f867722e5a6e3e25c6952c642da1055b3de09e3dbc843b5102849f488.json
similarity index 67%
rename from .sqlx/query-9c33b5ff424ef9992848b2bffb76ef196f081d13463019d3705b2aad59ba6a30.json
rename to .sqlx/query-2eb18e3f867722e5a6e3e25c6952c642da1055b3de09e3dbc843b5102849f488.json
index 15c6531312..a8589a5fe7 100644
--- a/.sqlx/query-9c33b5ff424ef9992848b2bffb76ef196f081d13463019d3705b2aad59ba6a30.json
+++ b/.sqlx/query-2eb18e3f867722e5a6e3e25c6952c642da1055b3de09e3dbc843b5102849f488.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT provider, external_id, external_name, external_url\n FROM external_agent_session\n WHERE agent_session_id = $1\n ",
+ "query": "\n SELECT provider, external_id, external_name, external_url, last_run_id\n FROM external_agent_session\n WHERE agent_session_id = $1\n ",
"describe": {
"columns": [
{
@@ -22,6 +22,11 @@
"ordinal": 3,
"name": "external_url",
"type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "last_run_id",
+ "type_info": "Text"
}
],
"parameters": {
@@ -33,8 +38,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "9c33b5ff424ef9992848b2bffb76ef196f081d13463019d3705b2aad59ba6a30"
+ "hash": "2eb18e3f867722e5a6e3e25c6952c642da1055b3de09e3dbc843b5102849f488"
}
diff --git a/.sqlx/query-25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a.json b/.sqlx/query-541351c610e04f6aea7c532c6b84aa117fd37024aca5a4c63afa1d05fc4eb6ce.json
similarity index 92%
rename from .sqlx/query-25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a.json
rename to .sqlx/query-541351c610e04f6aea7c532c6b84aa117fd37024aca5a4c63afa1d05fc4eb6ce.json
index 26aed33452..f57869a8c3 100644
--- a/.sqlx/query-25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a.json
+++ b/.sqlx/query-541351c610e04f6aea7c532c6b84aa117fd37024aca5a4c63afa1d05fc4eb6ce.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\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\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 ",
+ "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\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\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": [
{
@@ -122,6 +122,11 @@
"ordinal": 23,
"name": "external_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 24,
+ "name": "external_last_run_id?",
+ "type_info": "Text"
}
],
"parameters": {
@@ -169,8 +174,9 @@
null,
null,
null,
+ null,
null
]
},
- "hash": "25d453dc3dd34061e52118bbede9af5a4805fee76915e1692d78b6354e5be07a"
+ "hash": "541351c610e04f6aea7c532c6b84aa117fd37024aca5a4c63afa1d05fc4eb6ce"
}
diff --git a/.sqlx/query-7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9.json b/.sqlx/query-5d22cc9a4e9c7757ab0243e90dd70688af88535341e392ca653c0f88e1a2df89.json
similarity index 88%
rename from .sqlx/query-7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9.json
rename to .sqlx/query-5d22cc9a4e9c7757ab0243e90dd70688af88535341e392ca653c0f88e1a2df89.json
index 2d6b1e7b1b..7951ad26f3 100644
--- a/.sqlx/query-7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9.json
+++ b/.sqlx/query-5d22cc9a4e9c7757ab0243e90dd70688af88535341e392ca653c0f88e1a2df89.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -122,6 +122,11 @@
"ordinal": 23,
"name": "external_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 24,
+ "name": "external_last_run_id?",
+ "type_info": "Text"
}
],
"parameters": {
@@ -153,8 +158,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "7de3b94415bb892f1005f5090865337decd1a2a106f161b42ba4dd208e5e97e9"
+ "hash": "5d22cc9a4e9c7757ab0243e90dd70688af88535341e392ca653c0f88e1a2df89"
}
diff --git a/.sqlx/query-6052a544dcc99649a3df01c6027868ae55c4e32c85004811f3b038a2cacb0dfa.json b/.sqlx/query-6052a544dcc99649a3df01c6027868ae55c4e32c85004811f3b038a2cacb0dfa.json
new file mode 100644
index 0000000000..3afc3b987c
--- /dev/null
+++ b/.sqlx/query-6052a544dcc99649a3df01c6027868ae55c4e32c85004811f3b038a2cacb0dfa.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id\n FROM agent_session\n WHERE id = $1 AND manager_replica_id = $2 AND manager_fence = $3\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6052a544dcc99649a3df01c6027868ae55c4e32c85004811f3b038a2cacb0dfa"
+}
diff --git a/.sqlx/query-2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d.json b/.sqlx/query-6e1b1c4306ffa8bc8cc78db45bfc4fad462085f93d231ab89abc5729f9431cd8.json
similarity index 86%
rename from .sqlx/query-2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d.json
rename to .sqlx/query-6e1b1c4306ffa8bc8cc78db45bfc4fad462085f93d231ab89abc5729f9431cd8.json
index 1e7244b7a1..9c42ab41d9 100644
--- a/.sqlx/query-2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d.json
+++ b/.sqlx/query-6e1b1c4306ffa8bc8cc78db45bfc4fad462085f93d231ab89abc5729f9431cd8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -122,6 +122,11 @@
"ordinal": 23,
"name": "external_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 24,
+ "name": "external_last_run_id?",
+ "type_info": "Text"
}
],
"parameters": {
@@ -154,8 +159,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "2757506f01322f58baeea71fb6779b867143be6312ef20a1bfd51e0f0dcd974d"
+ "hash": "6e1b1c4306ffa8bc8cc78db45bfc4fad462085f93d231ab89abc5729f9431cd8"
}
diff --git a/.sqlx/query-83d5eb3d426d02bbada68aecf26ea69520ad546a8e65d4a8365e35e4bf360af1.json b/.sqlx/query-83d5eb3d426d02bbada68aecf26ea69520ad546a8e65d4a8365e35e4bf360af1.json
new file mode 100644
index 0000000000..5a34c6a93f
--- /dev/null
+++ b/.sqlx/query-83d5eb3d426d02bbada68aecf26ea69520ad546a8e65d4a8365e35e4bf360af1.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COALESCE(MAX(sequence), 0) AS \"high!\" FROM cursor_journal_input WHERE agent_session_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "high!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "83d5eb3d426d02bbada68aecf26ea69520ad546a8e65d4a8365e35e4bf360af1"
+}
diff --git a/.sqlx/query-897ec3e8b1ad0f3315115d7a3bb4008e999a670f280eb3dbc5edd89039fbef2c.json b/.sqlx/query-897ec3e8b1ad0f3315115d7a3bb4008e999a670f280eb3dbc5edd89039fbef2c.json
new file mode 100644
index 0000000000..522f0536e6
--- /dev/null
+++ b/.sqlx/query-897ec3e8b1ad0f3315115d7a3bb4008e999a670f280eb3dbc5edd89039fbef2c.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n log.id,\n log.agent_session_id,\n log.user_id AS \"user_id: MacroUserIdStr\",\n log.direction,\n log.content,\n log.created_at\n FROM agent_session_log AS log\n WHERE log.agent_session_id = $1\n AND (log.created_at, log.id) >= (\n COALESCE((SELECT boundary.created_at\n FROM agent_session AS session\n JOIN agent_session_log AS boundary ON boundary.id = session.history_start_log_id\n AND boundary.agent_session_id = session.id\n WHERE session.id = $1), '-infinity'::timestamptz),\n COALESCE((SELECT history_start_log_id FROM agent_session WHERE id = $1),\n '00000000-0000-0000-0000-000000000000'::uuid)\n )\n ORDER BY log.created_at ASC, log.id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "agent_session_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "user_id: MacroUserIdStr",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "direction",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "content",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "897ec3e8b1ad0f3315115d7a3bb4008e999a670f280eb3dbc5edd89039fbef2c"
+}
diff --git a/.sqlx/query-a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0.json b/.sqlx/query-986cf6d4c512f565acc0f01fea9c5fc3271e7ef5a5dada1645f8b6994c3feda4.json
similarity index 87%
rename from .sqlx/query-a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0.json
rename to .sqlx/query-986cf6d4c512f565acc0f01fea9c5fc3271e7ef5a5dada1645f8b6994c3feda4.json
index 73d614e9f5..a4f901bb3f 100644
--- a/.sqlx/query-a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0.json
+++ b/.sqlx/query-986cf6d4c512f565acc0f01fea9c5fc3271e7ef5a5dada1645f8b6994c3feda4.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
+ "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",
"describe": {
"columns": [
{
@@ -122,6 +122,11 @@
"ordinal": 23,
"name": "external_url?",
"type_info": "Text"
+ },
+ {
+ "ordinal": 24,
+ "name": "external_last_run_id?",
+ "type_info": "Text"
}
],
"parameters": {
@@ -153,8 +158,9 @@
false,
false,
true,
+ true,
true
]
},
- "hash": "a82f6bfedc84f43370145bf86222f10d1d83e53f5413f1c4fafcd122f052a2c0"
+ "hash": "986cf6d4c512f565acc0f01fea9c5fc3271e7ef5a5dada1645f8b6994c3feda4"
}
diff --git a/.sqlx/query-9e595b74206ab19e5d5fe85e7e730254799266365a092d62e246c0eddf6a63ab.json b/.sqlx/query-9e595b74206ab19e5d5fe85e7e730254799266365a092d62e246c0eddf6a63ab.json
new file mode 100644
index 0000000000..870cdca190
--- /dev/null
+++ b/.sqlx/query-9e595b74206ab19e5d5fe85e7e730254799266365a092d62e246c0eddf6a63ab.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT manager_fence FROM agent_session WHERE id = $1 AND manager_replica_id = $2 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "manager_fence",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "9e595b74206ab19e5d5fe85e7e730254799266365a092d62e246c0eddf6a63ab"
+}
diff --git a/.sqlx/query-c5342586b508b47ea90d6b891dd5303d319a4f659b0e5defbcb105bfc0968781.json b/.sqlx/query-c5342586b508b47ea90d6b891dd5303d319a4f659b0e5defbcb105bfc0968781.json
new file mode 100644
index 0000000000..f64e532fda
--- /dev/null
+++ b/.sqlx/query-c5342586b508b47ea90d6b891dd5303d319a4f659b0e5defbcb105bfc0968781.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO cursor_journal_input(agent_session_id, sequence, run_id, input) VALUES ($1, $2, $3, $4)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c5342586b508b47ea90d6b891dd5303d319a4f659b0e5defbcb105bfc0968781"
+}
diff --git a/.sqlx/query-ca1e31a71912f75337f5351eb6656ec4b9b2eb2929959b66dbd2c0beb6cd2ed1.json b/.sqlx/query-ca1e31a71912f75337f5351eb6656ec4b9b2eb2929959b66dbd2c0beb6cd2ed1.json
new file mode 100644
index 0000000000..ff9624b112
--- /dev/null
+++ b/.sqlx/query-ca1e31a71912f75337f5351eb6656ec4b9b2eb2929959b66dbd2c0beb6cd2ed1.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT sequence, run_id, input FROM cursor_journal_input WHERE agent_session_id = $1 ORDER BY sequence",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "sequence",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "run_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "input",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "ca1e31a71912f75337f5351eb6656ec4b9b2eb2929959b66dbd2c0beb6cd2ed1"
+}
diff --git a/Cargo.lock b/Cargo.lock
index e5c6aaec88..e9ce4179e2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -210,6 +210,7 @@ version = "0.1.0"
dependencies = [
"agent-client-protocol",
"agent_runtime_protocol",
+ "chrono",
"clap",
"insta",
"lazy-regex",
@@ -4524,6 +4525,9 @@ name = "cursor_cloud_agents"
version = "0.1.0"
dependencies = [
"agent-client-protocol",
+ "agent_fold",
+ "agent_runtime_protocol",
+ "agent_session",
"futures",
"insta",
"macro_env_var",
@@ -4531,12 +4535,14 @@ dependencies = [
"rootcause",
"serde",
"serde_json",
+ "sqlx",
"sse-core",
"thiserror 2.0.18",
"tokio",
"tokio-util",
"tracing",
"tracing-subscriber",
+ "uuid",
"workspace-hack",
"zeroize",
]
diff --git a/apps/web/scripts/agent-fold.test.ts b/apps/web/scripts/agent-fold.test.ts
new file mode 100644
index 0000000000..b887f53ffc
--- /dev/null
+++ b/apps/web/scripts/agent-fold.test.ts
@@ -0,0 +1,98 @@
+import { execFile } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { promisify } from 'node:util';
+import { beforeAll, expect, it } from 'vitest';
+import type { FoldStream } from '../src/lib/core/agent-fold/wasm-module';
+
+let Stream: new (session: string) => FoldStream;
+
+beforeAll(async () => {
+ // Keep the worker responsive to Vitest RPC while a cold WASM build runs.
+ await promisify(execFile)('just', ['build-agent-fold-wasm'], {
+ cwd: new URL('..', import.meta.url),
+ maxBuffer: 10 * 1024 * 1024,
+ });
+ const path = new URL('../src/lib/core/agent-fold/wasm/', import.meta.url);
+ const wasm = await import(/* @vite-ignore */ new URL('agent_fold.js', path).href);
+ await wasm.default({
+ module_or_path: readFileSync(new URL('agent_fold_bg.wasm', path)),
+ });
+ Stream = wasm.FoldStream;
+}, 300_000);
+
+it('decodes durable DTOs, reconciles overlap, and keeps raw frame consumers', () => {
+ const session = '00000000-0000-0000-0000-00000000000a';
+ const chunk = (text: string) => ({
+ direction: 'to_server' as const,
+ content: {
+ type: 'acp',
+ jsonrpc: '2.0',
+ method: 'session/update',
+ params: {
+ sessionId: 'runtime',
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text },
+ },
+ },
+ },
+ });
+ const boundary = {
+ ...chunk('same'),
+ id: '00000000-0000-0000-0000-000000000002',
+ createdAt: '2026-08-13T00:00:00.000002Z',
+ userId: 'macro|[email protected]',
+ };
+ const stream = new Stream(session);
+ const raw = new Stream(session);
+ try {
+ expect(stream.snapshot([boundary])).toEqual(raw.extend([boundary]));
+ expect(stream.push_rows([boundary, boundary])).toEqual([]);
+ expect(
+ stream.push_rows([
+ {
+ ...boundary,
+ id: '00000000-0000-0000-0000-000000000009',
+ createdAt: '2026-08-13T00:00:00.000001Z',
+ },
+ ])
+ ).toEqual([]);
+ const live = { ...boundary, id: '00000000-0000-0000-0000-000000000003' };
+ expect(stream.push_rows([live])).toEqual(raw.push(live));
+ expect(stream.messages()).toEqual(raw.messages());
+ // Raw protocol APIs still accept frames with no durable metadata.
+ raw.snapshot([]);
+ expect(raw.extend([chunk('raw')])).toHaveLength(1);
+ expect(raw.push(chunk(' tail'))).not.toEqual([]);
+ expect(stream.snapshot([])).toEqual([]);
+ expect(stream.push_rows([boundary])).not.toEqual([]);
+ } finally {
+ stream.free();
+ raw.free();
+ }
+});
+
+it('preserves replacement events and later updates within one durable batch', () => {
+ const session = '00000000-0000-0000-0000-00000000000a';
+ const rows = readFileSync(
+ new URL('../../../crates/agent_fold/fixtures/load_replacement.jsonl', import.meta.url),
+ 'utf8'
+ ).trim().split('\n').map((line, index) => ({
+ ...JSON.parse(line),
+ id: `00000000-0000-0000-0000-${index.toString(16).padStart(12, '0')}`,
+ createdAt: '2026-08-13T00:00:00Z',
+ }));
+ const stream = new Stream(session);
+ const raw = new Stream(session);
+ try {
+ stream.snapshot(rows.slice(0, 10));
+ raw.extend(rows.slice(0, 10));
+ const expected = rows.slice(10).flatMap((row) => raw.push(row));
+ expect(expected.some((event) => event.kind === 'replace')).toBe(true);
+ expect(stream.push_rows(rows.slice(5))).toEqual(expected);
+ expect(stream.messages()).toEqual(raw.messages());
+ } finally {
+ stream.free();
+ raw.free();
+ }
+});
diff --git a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md
index ce56d8b7a4..b224e15927 100644
--- a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md
+++ b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md
@@ -190,7 +190,7 @@ and each `*InTargetCaches` helper applies the change to all three cache families
`lookup` closure so only changed rows re-render. Resource resolves once; the store keeps updating.
- `agent-session-stream.ts`: the buffering seam. `beginAgentSessionStream(channelId)`
**before** the fetch, buffer frames, `followAgentSession` aligns buffer against snapshot
- (`dropOverlap`, :328 — longest buffered-prefix that is a suffix of the fetched log), one
+ (Rust `LogIngestion` reconciles durable snapshot/live row overlap), one
machine per session shared across split views, refcounted release.
Also `subscribeAgentSessionLog(sessionId, sink)` (:90) for raw-frame consumers.
- `agent-session-placeholders.ts`: synthesizes a placeholder comms row when the fold derives
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
index 6877867708..f61e9958ca 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
@@ -6,16 +6,19 @@
* ordered store without a refetch.
*/
-import type { FoldedMessage } from '@service-agent-fold/generated/types';
+import type {
+ FoldedMessage,
+ FoldedStreamEvent,
+} from '@service-agent-fold/generated/types';
import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
-import { createRoot } from 'solid-js';
+import { createComputed, createMemo, createRoot, mapArray } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const worker = vi.hoisted(() => ({
/** Messages the fold machine reports for the session. */
messages: [] as FoldedMessage[],
/** Events the next `pushSessionEntries` resolves with. */
- pushed: [] as { kind: string; message: FoldedMessage }[],
+ pushed: [] as FoldedStreamEvent[],
getSession: async (): Promise<{
isErr: () => boolean;
value: Partial<AgentSessionResponse>;
@@ -96,6 +99,190 @@ describe('createAgentSessionFeed live updates', () => {
vi.resetModules();
});
+ it('keeps committed messages during replay, replaces atomically, and accepts continuation', async () => {
+ const { createAgentSessionFeed } = await import(
+ './create-agent-session-feed'
+ );
+ const { handleAgentSessionLog } = await import(
+ '@queries/agent-session/session-fold'
+ );
+ worker.messages = [
+ message(0, 'user', 'old'),
+ message(0, 'agent', 'old answer'),
+ message(1, 'user', 'obsolete'),
+ ];
+ let dispose!: () => void;
+ const feed = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createAgentSessionFeed(() => 'session');
+ });
+ await flush();
+ await flush();
+ const emit = async () => {
+ handleAgentSessionLog({
+ agentSessionId: 'session',
+ direction: 'to_server',
+ content: { type: 'acp' },
+ } as never);
+ await flush();
+ };
+ // Staged and discarded frames produce no visible fold events.
+ await emit();
+ expect(feed.messages()).toHaveLength(3);
+ const replacement = [
+ message(0, 'user', 'replayed'),
+ message(0, 'agent', 'replayed answer', { kind: 'end_turn' }),
+ ];
+ worker.pushed = [{ kind: 'replace', messages: replacement }];
+ await emit();
+ expect([...feed.messages()]).toEqual(replacement);
+ expect(feed.working()).toBe(false);
+ const continuation = message(1, 'user', 'next');
+ worker.pushed = [{ kind: 'new', message: continuation }];
+ await emit();
+ expect([...feed.messages()]).toEqual([...replacement, continuation]);
+ worker.pushed = [{ kind: 'replace', messages: [] }];
+ await emit();
+ expect(feed.messages()).toHaveLength(0);
+ dispose();
+ });
+
+ it('remounts replay rows when the same message and tool IDs acquire different shapes', async () => {
+ const { createAgentSessionFeed } = await import(
+ './create-agent-session-feed'
+ );
+ const { handleAgentSessionLog } = await import(
+ '@queries/agent-session/session-fold'
+ );
+ const control: FoldedMessage = {
+ ...message(0, 'user', ''),
+ parts: [
+ {
+ kind: 'control',
+ control: { kind: 'stop' },
+ outcome: { kind: 'accepted' },
+ },
+ ],
+ };
+ const tool: FoldedMessage = {
+ ...message(0, 'agent', ''),
+ parts: [
+ {
+ kind: 'tool_use',
+ id: 'same-tool-id',
+ name: { kind: 'native', name: 'Bash' },
+ status: 'completed',
+ detail: {
+ kind: 'terminal',
+ command: 'old command',
+ output: null,
+ exitCode: 0,
+ },
+ },
+ ],
+ };
+ worker.messages = [control, tool, message(1, 'user', 'obsolete')];
+ let dispose!: () => void;
+ const feed = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createAgentSessionFeed(() => 'session');
+ });
+ await flush();
+ await flush();
+ const oldRows = [...feed.messages()];
+ const observed: string[][] = [];
+ let disposeReader!: () => void;
+ createRoot((cleanup) => {
+ disposeReader = cleanup;
+ // Like the transcript's For/Virtualizer and AgentMessagePart, select
+ // the union branch once per mounted object, then read its fields live.
+ const rows = mapArray(feed.messages, (row) =>
+ mapArray(
+ () => row.parts,
+ (part) => {
+ if (part.kind === 'control')
+ return createMemo(() => part.outcome.kind);
+ if (part.kind === 'text') return createMemo(() => part.text);
+ if (part.kind === 'tool_use') {
+ const detail = part.detail;
+ if (detail.kind === 'terminal')
+ return createMemo(() => detail.command);
+ if (detail.kind === 'read')
+ return createMemo(() => detail.paths.join(','));
+ }
+ throw new Error('unexpected fixture part');
+ }
+ )
+ );
+ createComputed(() => {
+ observed.push(
+ rows().map((parts) =>
+ parts()
+ .map((read) => read())
+ .join('|')
+ )
+ );
+ });
+ });
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const replacement: FoldedMessage[] = [
+ message(0, 'user', 'replayed prompt'),
+ {
+ ...tool,
+ stop: { kind: 'end_turn' },
+ parts: [
+ {
+ kind: 'tool_use',
+ id: 'same-tool-id',
+ name: { kind: 'native', name: 'Read' },
+ status: 'completed',
+ detail: { kind: 'read', paths: ['replayed.txt'] },
+ },
+ ],
+ },
+ ];
+ const emit = async (events: FoldedStreamEvent[]) => {
+ worker.pushed = events;
+ handleAgentSessionLog({
+ agentSessionId: 'session',
+ direction: 'to_server',
+ content: { type: 'acp' },
+ } as never);
+ await flush();
+ };
+ await emit([{ kind: 'replace', messages: replacement }]);
+ expect(errors).not.toHaveBeenCalled();
+ expect(observed).toEqual([
+ ['accepted', 'old command', 'obsolete'],
+ ['replayed prompt', 'replayed.txt'],
+ ]);
+ expect([...feed.messages()]).toEqual(replacement);
+ expect(feed.messages()[0]).not.toBe(oldRows[0]);
+ expect(feed.messages()[1]).not.toBe(oldRows[1]);
+ expect(oldRows).toEqual([control, tool, message(1, 'user', 'obsolete')]);
+ expect(feed.working()).toBe(false);
+
+ // Subsequent streaming updates still keep the new row and part alive.
+ const replayedRow = feed.messages()[0];
+ const replayedPart = replayedRow?.parts[0];
+ await emit([
+ { kind: 'update', message: message(0, 'user', 'continued prompt') },
+ ]);
+ expect(feed.messages()[0]).toBe(replayedRow);
+ expect(feed.messages()[0]?.parts[0]).toBe(replayedPart);
+ expect(observed.at(-1)).toEqual(['continued prompt', 'replayed.txt']);
+ await emit([{ kind: 'replace', messages: [] }]);
+ expect(observed.at(-1)).toEqual([]);
+ expect(feed.working()).toBe(false);
+ expect(errors).not.toHaveBeenCalled();
+ } finally {
+ errors.mockRestore();
+ disposeReader();
+ dispose();
+ }
+ });
+
it('applies a streamed frame without refetching', async () => {
const { createAgentSessionFeed } = await import(
'./create-agent-session-feed'
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
index 046458fb1b..ef3257b7d9 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
@@ -142,6 +142,15 @@ export function createAgentSessionFeed(
const fold = await acquireAgentSessionFold({
agentSessionId: id,
onChange: upsert,
+ onReplace: (messages) =>
+ setList(
+ produce((current: FoldedMessage[]) => {
+ // Replay can reuse turn/author and tool IDs for different part
+ // kinds. Replace row identities atomically so mounted parts
+ // cannot keep reading a union variant that reconcile removed.
+ current.splice(0, current.length, ...messages);
+ })
+ ),
onMetadata: setMetadata,
});
if (superseded()) {
diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.ts
index aa875e3026..b141edb61d 100644
--- a/apps/web/src/features/block-agent/debug/replay/driver.ts
+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts
@@ -4,7 +4,7 @@
* The driver owns a recording split in two: entries before `splitIndex` are
* served as the persisted log (`getLog`), the rest stream one at a time
* through the real realtime entry point, `handleAgentSessionLog` — so
- * buffering, `dropOverlap`, the worker fold, and the status projection all
+ * buffering, Rust row ingestion, the worker fold, and the status projection all
* run exactly as they do against the gateway.
*
* Two knobs exist purely to provoke the catch-up paths: `fetchDelayMs` holds
@@ -89,6 +89,7 @@ function sessionFixture(id: string): AgentSessionResponse {
/** The frame the harness would append for a prompt accepted over `control`. */
function promptEcho(prompt: string): AgentSessionLogEntryDto {
return {
+ id: crypto.randomUUID(),
createdAt: new Date().toISOString(),
userId: REPLAY_OWNER,
direction: 'to_runtime',
diff --git a/apps/web/src/features/block-agent/debug/replay/recording.test.ts b/apps/web/src/features/block-agent/debug/replay/recording.test.ts
index 269d7c1de5..6f84f19dd4 100644
--- a/apps/web/src/features/block-agent/debug/replay/recording.test.ts
+++ b/apps/web/src/features/block-agent/debug/replay/recording.test.ts
@@ -23,11 +23,13 @@ describe('parseRecording', () => {
expect(entries).toEqual([
{
+ id: '00000000-0000-0000-0000-000000000000',
createdAt: '2026-08-03T21:04:19.934Z',
direction: 'to_server',
content: { type: 'event', event: 'acp_ready' },
},
{
+ id: '00000000-0000-0000-0000-000000000002',
createdAt: '2026-08-03T21:04:20.000Z',
direction: 'to_runtime',
content: { type: 'acp', jsonrpc: '2.0', method: 'session/prompt' },
@@ -72,6 +74,7 @@ describe('parseRecording', () => {
describe('isPromptEntry', () => {
it('matches only session/prompt frames headed to the runtime', () => {
const prompt = {
+ id: '00000000-0000-0000-0000-000000000001',
createdAt: 't',
direction: 'to_runtime',
content: { type: 'acp', method: 'session/prompt' },
diff --git a/apps/web/src/features/block-agent/debug/replay/recording.ts b/apps/web/src/features/block-agent/debug/replay/recording.ts
index 5180f716f5..c1fcd4632e 100644
--- a/apps/web/src/features/block-agent/debug/replay/recording.ts
+++ b/apps/web/src/features/block-agent/debug/replay/recording.ts
@@ -11,6 +11,7 @@
import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';
type RecordedLine = {
+ id?: string;
ts?: string;
createdAt?: string;
userId?: string | null;
@@ -43,6 +44,9 @@ export function parseRecording(jsonl: string): AgentSessionLogEntryDto[] {
throw new Error(`recording line ${index + 1} has no content envelope`);
}
entries.push({
+ id:
+ parsed.id ??
+ `00000000-0000-0000-0000-${index.toString(16).padStart(12, '0')}`,
content: content as AgentSessionLogEntryDto['content'],
createdAt: parsed.createdAt ?? parsed.ts ?? new Date(0).toISOString(),
direction,
diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.ts b/apps/web/src/lib/core/agent-fold/fold.worker.ts
index 4872c50d77..a8e55b4d16 100644
--- a/apps/web/src/lib/core/agent-fold/fold.worker.ts
+++ b/apps/web/src/lib/core/agent-fold/fold.worker.ts
@@ -15,7 +15,6 @@
* a `push` concurrently would fold frames out of order.
*/
-import type { FoldedStreamEvent } from '@service-agent-fold/generated/types';
import { match } from 'ts-pattern';
import type { FoldRequest, FoldResponse } from './protocol';
import { type FoldStream, loadAgentFoldWasm } from './wasm-module';
@@ -51,16 +50,17 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {
// snapshot from the top of the log, so replaying them into a machine
// that has already seen them would duplicate every message.
streams.get(sessionId)?.free();
+ streams.delete(sessionId);
const stream = new wasm.FoldStream(sessionId);
- streams.set(sessionId, stream);
- const messages = stream.extend(entries);
- return {
- id,
- kind,
- ok: true as const,
- messages,
- metadata: stream.metadata(),
- };
+ try {
+ const messages = stream.snapshot(entries);
+ const metadata = stream.metadata();
+ streams.set(sessionId, stream);
+ return { id, kind, ok: true as const, messages, metadata };
+ } catch (error) {
+ stream.free();
+ throw error;
+ }
})
.with({ kind: 'push' }, ({ id, kind, sessionId, entries }) => {
const stream = streams.get(sessionId);
@@ -68,10 +68,7 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {
// a log folds a session that never happened, and a caller that has lost
// its machine needs to refetch, not to keep pushing.
if (!stream) throw new Error(`no open fold for session ${sessionId}`);
- const changes: FoldedStreamEvent[] = [];
- for (const entry of entries) {
- changes.push(...stream.push(entry));
- }
+ const changes = stream.push_rows(entries);
return { id, kind, ok: true as const, changes };
})
.with({ kind: 'messages' }, ({ id, kind, sessionId }) => {
diff --git a/apps/web/src/lib/core/agent-fold/wasm-module.ts b/apps/web/src/lib/core/agent-fold/wasm-module.ts
index 4555e82fe8..052ce7801c 100644
--- a/apps/web/src/lib/core/agent-fold/wasm-module.ts
+++ b/apps/web/src/lib/core/agent-fold/wasm-module.ts
@@ -25,6 +25,10 @@ import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/s
* second one beside it.
*/
export interface FoldStream {
+ /** Replace with durable history; retain row metadata for live overlap. */
+ snapshot: (entries: AgentSessionLogEntryDto[]) => FoldedMessage[];
+ /** Reconcile durable rows against the snapshot, preserving delivery order. */
+ push_rows: (entries: AgentSessionLogEntryDto[]) => FoldedStreamEvent[];
/**
* Fold a run of frames and answer with every message derived so far.
*
@@ -33,14 +37,18 @@ export interface FoldStream {
* over and over, so replaying a fetched log one frame at a time would
* serialize thousands of whole messages to produce a handful.
*/
- extend: (entries: AgentSessionLogEntryDto[]) => FoldedMessage[];
+ extend: (
+ entries: Pick<AgentSessionLogEntryDto, 'direction' | 'content' | 'userId'>[]
+ ) => FoldedMessage[];
/**
* Fold one more frame, reporting the changes it implied.
*
* Empty for the frames that change nothing renderable — handshakes, token
* accounting — which is most of them.
*/
- push: (entry: AgentSessionLogEntryDto) => FoldedStreamEvent[];
+ push: (
+ entry: Pick<AgentSessionLogEntryDto, 'direction' | 'content' | 'userId'>
+ ) => FoldedStreamEvent[];
/** Every message folded so far, oldest first. */
messages: () => FoldedMessage[];
/**
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 1dca324290..d21550d8f4 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
@@ -67,11 +67,36 @@ describe('createMagicChipModel', () => {
expect(sessionFold.acquireAgentSessionFold).toHaveBeenCalledWith({
agentSessionId: 'session',
onChange: expect.any(Function),
+ onReplace: expect.any(Function),
});
dispose();
});
+ it('replaces the referenced answer after a successful load', async () => {
+ let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];
+ const dispose = createRoot((rootDispose) => {
+ presentation = createMagicChipModel(props).presentation;
+ return rootDispose;
+ });
+ await Promise.resolve();
+ const callbacks = sessionFold.acquireAgentSessionFold.mock.calls[0]![0];
+ callbacks.onReplace([
+ prompt,
+ { ...response, parts: [{ kind: 'text', text: 'Reconstructed answer' }] },
+ ]);
+ expect(presentation()).toEqual({
+ kind: 'settled',
+ markdown: 'Reconstructed answer',
+ });
+ callbacks.onReplace([]);
+ expect(presentation()).not.toEqual({
+ kind: 'settled',
+ markdown: 'Reconstructed answer',
+ });
+ dispose();
+ });
+
it('hydrates a disconnected status from the session', async () => {
sessionFold.acquireAgentSessionFold.mockResolvedValue({
messages: [],
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 c248888701..fd534fd488 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
@@ -75,6 +75,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
void acquireAgentSessionFold({
agentSessionId: props.agentSessionId,
+ onReplace: setMessages,
onChange: (changed) => {
setMessages((current) =>
changed.reduce(
diff --git a/apps/web/src/lib/queries/agent-session/session-fold.test.ts b/apps/web/src/lib/queries/agent-session/session-fold.test.ts
index 7dced3738c..0f772f9115 100644
--- a/apps/web/src/lib/queries/agent-session/session-fold.test.ts
+++ b/apps/web/src/lib/queries/agent-session/session-fold.test.ts
@@ -22,14 +22,14 @@ vi.mock('@service-agent-harness/client', () => ({
import {
acquireAgentSessionFold,
- dropOverlap,
handleAgentSessionLog,
subscribeAgentSessionLog,
} from './session-fold';
function frame(n: number): AgentSessionLogEntryDto {
return {
- createdAt: `2026-08-13T00:00:0${n}Z`,
+ id: `00000000-0000-0000-0000-${n.toString(16).padStart(12, '0')}`,
+ createdAt: new Date(Date.UTC(2026, 7, 13, 0, 0, n)).toISOString(),
direction: 'to_server',
content: { type: 'acp', jsonrpc: '2.0', id: n },
} as unknown as AgentSessionLogEntryDto;
@@ -57,61 +57,8 @@ beforeEach(() => {
harness.getLog.mockResolvedValue(ok({ bot, entries: [] }));
});
-describe('buffer overlap', () => {
- const log = Array.from({ length: 10 }, (_, n) => frame(n));
-
- it('drops the longest buffered prefix already in the snapshot', () => {
- expect(dropOverlap(log.slice(0, 8), log.slice(5))).toEqual(log.slice(8));
- expect(
- dropOverlap([frame(1), frame(2), frame(2)], [frame(2), frame(2)])
- ).toEqual([]);
- });
-
- it('keeps frames that start after the snapshot or do not overlap', () => {
- expect(dropOverlap(log.slice(0, 6), log.slice(6))).toEqual(log.slice(6));
- expect(dropOverlap(log.slice(0, 4), [frame(99)])).toEqual([frame(99)]);
- });
-
- it('reconciles gaps, ordering, and duplicate occurrences', () => {
- expect(
- dropOverlap([frame(1), frame(2), frame(3)], [frame(3), frame(1)])
- ).toEqual([]);
- expect(dropOverlap([frame(1)], [frame(1), frame(1)])).toEqual([frame(1)]);
- });
-
- it('matches one entry whose object keys came back in another order', () => {
- // The persisted log is read from jsonb, which reorders keys; the
- // realtime frame for the same row keeps the runtime's order.
- const stored = {
- createdAt: '2026-08-13T00:00:05Z',
- direction: 'to_server',
- content: {
- type: 'acp',
- jsonrpc: '2.0',
- id: 5,
- method: 'session/prompt',
- params: { prompt: [{ text: 'hi', type: 'text' }], sessionId: 's' },
- },
- } as unknown as AgentSessionLogEntryDto;
- const live = {
- content: {
- jsonrpc: '2.0',
- id: 5,
- method: 'session/prompt',
- params: { sessionId: 's', prompt: [{ type: 'text', text: 'hi' }] },
- type: 'acp',
- },
- direction: 'to_server',
- createdAt: '2026-08-13T00:00:05Z',
- } as unknown as AgentSessionLogEntryDto;
-
- expect(JSON.stringify(stored)).not.toBe(JSON.stringify(live));
- expect(dropOverlap([stored], [live])).toEqual([]);
- });
-});
-
describe('shared session folds', () => {
- it('buffers realtime overlap while fetching and replays only its suffix', async () => {
+ it('passes buffered overlap to the durable fold after fetching', async () => {
// This test verifies that buffered entries are replayed during opening.
// Sinks are registered AFTER getting the snapshot to prevent duplicate
// notifications: replayed entries update the worker but don't notify sinks,
@@ -135,29 +82,74 @@ describe('shared session folds', () => {
frame(2),
]);
expect(fold.pushSessionEntries).toHaveBeenCalledWith('session-a', [
+ frame(2),
frame(3),
]);
(await acquired).release();
});
- it('skips a late realtime frame the fetched log already held', async () => {
- harness.getLog.mockResolvedValue(
- ok({ bot, entries: [frame(1), frame(2)] })
+ it('drains every raced row to Rust in delivery order before becoming ready', async () => {
+ let resolveFetch!: (
+ value: Result<AgentSessionLogResponse, unknown>
+ ) => void;
+ harness.getLog.mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve;
+ })
);
- const acquired = await acquireAgentSessionFold({
- agentSessionId: 'session-a',
+ const oldChunk = {
+ ...frame(1),
+ content: {
+ type: 'acp',
+ jsonrpc: '2.0',
+ method: 'session/update',
+ params: {
+ sessionId: 'runtime',
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'obsolete' },
+ },
+ },
+ },
+ };
+ const oldLifecycle = {
+ ...frame(2),
+ content: { type: 'event', event: 'disconnected' },
+ };
+ const snapshot = [frame(3), frame(4), frame(5)];
+ const acquired = acquireAgentSessionFold({
+ agentSessionId: 'boundary-race',
});
-
- // The gateway delivers the second row after the HTTP fetch returned it.
- handleAgentSessionLog(event('session-a', 2));
- handleAgentSessionLog(event('session-a', 3));
- await Promise.resolve();
-
- expect(fold.pushSessionEntries).toHaveBeenCalledTimes(1);
- expect(fold.pushSessionEntries).toHaveBeenCalledWith('session-a', [
- frame(3),
+ handleAgentSessionLog({ agentSessionId: 'boundary-race', ...oldChunk });
+ handleAgentSessionLog({ agentSessionId: 'boundary-race', ...oldLifecycle });
+ handleAgentSessionLog(event('boundary-race', 4));
+ handleAgentSessionLog(event('boundary-race', 6));
+ // The successful load selects row 3 while GET is in flight. More obsolete
+ // and overlapping delivery arrives during both opening and pushing.
+ fold.openSession.mockImplementationOnce(async () => {
+ handleAgentSessionLog({ agentSessionId: 'boundary-race', ...oldChunk });
+ handleAgentSessionLog(event('boundary-race', 5));
+ });
+ fold.pushSessionEntries.mockImplementationOnce(async () => {
+ handleAgentSessionLog({
+ agentSessionId: 'boundary-race',
+ ...oldLifecycle,
+ });
+ handleAgentSessionLog(event('boundary-race', 4));
+ handleAgentSessionLog(event('boundary-race', 7));
+ return [];
+ });
+ resolveFetch(ok({ bot, entries: snapshot }));
+ const result = await acquired;
+ expect(fold.openSession).toHaveBeenCalledWith('boundary-race', snapshot);
+ expect(fold.pushSessionEntries.mock.calls).toEqual([
+ [
+ 'boundary-race',
+ [oldChunk, oldLifecycle, frame(4), frame(6), oldChunk, frame(5)],
+ ],
+ ['boundary-race', [oldLifecycle, frame(4), frame(7)]],
]);
- acquired.release();
+ result.release();
});
it('isolates raw and folded events by session', async () => {
@@ -220,6 +212,37 @@ describe('shared session folds', () => {
acquired.release();
});
+ it('delivers replacements in order, including empty replacements, only to the matching session', async () => {
+ const seen: unknown[] = [];
+ const other = vi.fn();
+ const acquired = await acquireAgentSessionFold({
+ agentSessionId: 'session-a',
+ onChange: (messages) => seen.push(['change', messages]),
+ onReplace: (messages) => seen.push(['replace', messages]),
+ });
+ const second = await acquireAgentSessionFold({
+ agentSessionId: 'session-b',
+ onReplace: other,
+ });
+ fold.pushSessionEntries.mockResolvedValue([
+ { kind: 'new', message },
+ { kind: 'replace', messages: [] },
+ { kind: 'replace', messages: [message] },
+ { kind: 'update', message },
+ ]);
+ handleAgentSessionLog(event('session-a', 1));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(seen).toEqual([
+ ['change', [message]],
+ ['replace', []],
+ ['replace', [message]],
+ ['change', [message]],
+ ]);
+ expect(other).not.toHaveBeenCalled();
+ acquired.release();
+ second.release();
+ });
+
it('releases a failed acquisition without retaining shared state', async () => {
harness.getLog.mockResolvedValueOnce(
err([{ code: 'HTTP_ERROR', message: 'nope' }])
diff --git a/apps/web/src/lib/queries/agent-session/session-fold.ts b/apps/web/src/lib/queries/agent-session/session-fold.ts
index 8241a3ec84..9629ca0134 100644
--- a/apps/web/src/lib/queries/agent-session/session-fold.ts
+++ b/apps/web/src/lib/queries/agent-session/session-fold.ts
@@ -29,10 +29,9 @@ type SessionState = {
bot?: SessionBot;
buffered: AgentSessionLogEntryDto[];
foldedSinks: Set<FoldedMessageSink>;
+ replacementSinks: Set<FoldedMessageSink>;
metadataSinks: Set<SessionMetadataSink>;
opening?: Promise<void>;
- /** Drops realtime frames the fetched log already contained. */
- overlap?: OverlapFilter;
ready: boolean;
references: number;
};
@@ -65,6 +64,7 @@ export function subscribeAgentSessionLog(
export async function acquireAgentSessionFold(args: {
agentSessionId: string;
onChange?: FoldedMessageSink;
+ onReplace?: FoldedMessageSink;
onMetadata?: SessionMetadataSink;
}): Promise<{
bot: SessionBot;
@@ -72,11 +72,12 @@ export async function acquireAgentSessionFold(args: {
metadata: SessionMetadata;
release: () => void;
}> {
- const { agentSessionId, onChange, onMetadata } = args;
+ const { agentSessionId, onChange, onReplace, onMetadata } = args;
const state = sessions.get(agentSessionId) ?? {
agentSessionId,
buffered: [],
foldedSinks: new Set<FoldedMessageSink>(),
+ replacementSinks: new Set<FoldedMessageSink>(),
metadataSinks: new Set<SessionMetadataSink>(),
ready: false,
references: 0,
@@ -89,6 +90,7 @@ export async function acquireAgentSessionFold(args: {
if (released) return;
released = true;
if (onChange) state.foldedSinks.delete(onChange);
+ if (onReplace) state.replacementSinks.delete(onReplace);
if (onMetadata) state.metadataSinks.delete(onMetadata);
state.references -= 1;
releaseState(state);
@@ -106,6 +108,7 @@ export async function acquireAgentSessionFold(args: {
// notify the sinks, and then the caller would also process the snapshot
// (which includes those same messages).
if (onChange) state.foldedSinks.add(onChange);
+ if (onReplace) state.replacementSinks.add(onReplace);
if (onMetadata) state.metadataSinks.add(onMetadata);
return {
@@ -129,7 +132,6 @@ async function open(state: SessionState): Promise<void> {
}
state.bot = result.value.bot;
- state.overlap = createOverlapFilter(result.value.entries);
await openSession(state.agentSessionId, result.value.entries);
machineOpen = true;
@@ -138,8 +140,7 @@ async function open(state: SessionState): Promise<void> {
while (state.buffered.length > 0) {
const buffered = state.buffered;
state.buffered = [];
- const replay = state.overlap(buffered);
- if (replay.length > 0) await push(state, replay);
+ await push(state, buffered);
}
state.ready = true;
} catch (error) {
@@ -173,11 +174,7 @@ export function handleAgentSessionLog(event: AgentSessionLogEvent): void {
state.buffered.push(entry);
return;
}
- // The gateway can deliver a frame after the HTTP log that already held it
- // was fetched; folding it again would open a second turn for one prompt.
- const fresh = state.overlap?.([entry]) ?? [entry];
- if (fresh.length === 0) return;
- void push(state, fresh).catch((error: unknown) => {
+ void push(state, [entry]).catch((error: unknown) => {
console.error('[agent-fold] live frame could not be folded', error);
});
}
@@ -188,74 +185,18 @@ async function push(
): Promise<void> {
const events = await pushSessionEntries(state.agentSessionId, entries);
if (sessions.get(state.agentSessionId) !== state) return;
- const messages = events.flatMap((event) =>
- event.kind === 'metadata' ? [] : [event.message]
- );
- // Metadata is carried whole per event, latest-wins — only the last matters.
+ // Apply in order: a replacement invalidates every earlier message event,
+ // and later live updates must land on the newly committed conversation.
+ for (const event of events) {
+ if (event.kind === 'metadata') continue;
+ if (event.kind === 'replace') {
+ for (const sink of state.replacementSinks) sink(event.messages);
+ } else {
+ for (const sink of state.foldedSinks) sink([event.message]);
+ }
+ }
const metadata = events.findLast((event) => event.kind === 'metadata');
if (metadata) {
for (const sink of state.metadataSinks) sink(metadata.metadata);
}
- if (messages.length === 0) return;
- for (const sink of state.foldedSinks) sink(messages);
-}
-
-type OverlapFilter = (
- entries: AgentSessionLogEntryDto[]
-) => AgentSessionLogEntryDto[];
-
-/**
- * A key under which the same log row compares equal however it travelled.
- *
- * The fetched log comes out of a jsonb column, which stores object keys in
- * its own order; realtime frames are serialized from memory in insertion
- * order. `JSON.stringify` therefore differs for one and the same entry, so
- * keys are sorted before comparing.
- */
-function canonical(value: unknown): string {
- return JSON.stringify(value, (_key, inner: unknown) => {
- if (!inner || typeof inner !== 'object' || Array.isArray(inner)) {
- return inner;
- }
- return Object.fromEntries(
- Object.entries(inner as Record<string, unknown>).sort(([a], [b]) =>
- a < b ? -1 : a > b ? 1 : 0
- )
- );
- });
-}
-
-/**
- * Build a filter that drops each fetched occurrence once, so realtime frames
- * that duplicate the snapshot are skipped whenever they arrive, while a
- * genuinely new frame with the same content later still passes.
- */
-export function createOverlapFilter(
- fetched: AgentSessionLogEntryDto[]
-): OverlapFilter {
- const remaining = new Map<string, number>();
- for (const entry of fetched) {
- const key = canonical(entry);
- remaining.set(key, (remaining.get(key) ?? 0) + 1);
- }
-
- return (entries) => {
- if (remaining.size === 0) return entries;
- return entries.filter((entry) => {
- const key = canonical(entry);
- const count = remaining.get(key);
- if (!count) return true;
- if (count === 1) remaining.delete(key);
- else remaining.set(key, count - 1);
- return false;
- });
- };
-}
-
-/** Return buffered frame occurrences not already present in the snapshot. */
-export function dropOverlap(
- fetched: AgentSessionLogEntryDto[],
- buffered: AgentSessionLogEntryDto[]
-): AgentSessionLogEntryDto[] {
- return createOverlapFilter(fetched)(buffered);
}
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 2de3be4058..a077e55c89 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
@@ -123,6 +123,12 @@ export type FoldedStreamEvent =
/** The message as it now stands. */
message: FoldedMessage;
}
+ /** Replace all messages for this session, including removal of old rows. */
+ | {
+ kind: 'replace';
+ /** The complete committed conversation. */
+ messages: FoldedMessage[];
+ }
/** The session's metadata changed; here it is in full. */
| {
kind: 'metadata';
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 ee51050968..fa8a5d09f9 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
@@ -414,9 +414,9 @@ export const controlAgentSession = async (
};
/**
- * Served unfolded, and whole: the fold is a left fold over the frames from
-the beginning, so a reader that skipped any of them would derive different
-turn numbering.
+ * Served unfolded from the latest successful load initialization, or the
+beginning when no load succeeded. Consumers stage load attempts so failed
+or interrupted replay does not become visible conversation content.
An unknown session is an error: the response has to name the session's
agent, and a session that never existed has none to name.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogEntryDtoAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogEntryDtoAllOf.ts
index 2d23ec576b..df06fbe5aa 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogEntryDtoAllOf.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogEntryDtoAllOf.ts
@@ -14,6 +14,8 @@ what a reader has to order these against anything else it is showing
beside them - the fold derives an order among the messages of one
session and nothing more. */
createdAt: string;
+ /** Durable transport row identity; together with `createdAt`, its order cursor. */
+ id: string;
/** The user whose action produced the frame, absent when no user did.
Only prompts carry one, and only when the frame was attributed at the
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogResponse.ts
index 53ddb58bb6..b9bb6d7477 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogResponse.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionLogResponse.ts
@@ -22,6 +22,9 @@ Here because a client renders those messages and cannot otherwise work
out who sent them: the sender of an agent message is this session's
bot, and nothing else names it. */
bot: SessionBot;
- /** Every logged frame, oldest first. Folding depends on this order. */
+ /** Effective history in ascending `(createdAt, id)` order.
+The first row is the inclusive history boundary cursor: buffered rows
+before it are obsolete. Reconcile snapshot overlap by row ID, never content.
+An empty history has no boundary or overlapping rows. */
entries: AgentSessionLogEntryDto[];
}
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 39f203e4bc..46518c953e 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
@@ -375,7 +375,7 @@
"get": {
"tags": ["agent-sessions"],
"summary": "The raw protocol log of one agent session.",
- "description": "Served unfolded, and whole: the fold is a left fold over the frames from\nthe beginning, so a reader that skipped any of them would derive different\nturn numbering.\n\nAn unknown session is an error: the response has to name the session's\nagent, and a session that never existed has none to name.",
+ "description": "Served unfolded from the latest successful load initialization, or the\nbeginning when no load succeeded. Consumers stage load attempts so failed\nor interrupted replay does not become visible conversation content.\n\nAn unknown session is an error: the response has to name the session's\nagent, and a session that never existed has none to name.",
"operationId": "get_agent_session_log",
"parameters": [
{
@@ -897,13 +897,18 @@
},
{
"type": "object",
- "required": ["createdAt"],
+ "required": ["id", "createdAt"],
"properties": {
"createdAt": {
"type": "string",
"format": "date-time",
"description": "When the log recorded the frame.\n\nThe frame itself carries no time, so this comes from the log row. It is\nwhat a reader has to order these against anything else it is showing\nbeside them - the fold derives an order among the messages of one\nsession and nothing more."
},
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Durable transport row identity; together with `createdAt`, its order cursor."
+ },
"userId": {
"type": ["string", "null"],
"description": "The user whose action produced the frame, absent when no user did.\n\nOnly prompts carry one, and only when the frame was attributed at the\ntime - a replayed or recorded session's are anonymous."
@@ -927,7 +932,7 @@
"items": {
"$ref": "#/components/schemas/AgentSessionLogEntryDto"
},
- "description": "Every logged frame, oldest first. Folding depends on this order."
+ "description": "Effective history in ascending `(createdAt, id)` order.\nThe first row is the inclusive history boundary cursor: buffered rows\nbefore it are obsolete. Reconcile snapshot overlap by row ID, never content.\nAn empty history has no boundary or overlapping rows."
}
}
},
diff --git a/crates/agent_fold/Cargo.toml b/crates/agent_fold/Cargo.toml
index 4c64287dba..9b4d878a20 100644
--- a/crates/agent_fold/Cargo.toml
+++ b/crates/agent_fold/Cargo.toml
@@ -42,6 +42,7 @@ agent-client-protocol = { workspace = true }
# which is what lets this crate reach wasm. Native builds are unaffected:
# whoever else needs the transport turns it back on, and cargo unifies.
agent_runtime_protocol = { path = "../agent_runtime_protocol", default-features = false }
+chrono = { workspace = true }
clap = { workspace = true, optional = true }
lazy-regex = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
diff --git a/crates/agent_fold/fixtures/load_replacement.jsonl b/crates/agent_fold/fixtures/load_replacement.jsonl
new file mode 100644
index 0000000000..0d92fb63fd
--- /dev/null
+++ b/crates/agent_fold/fixtures/load_replacement.jsonl
@@ -0,0 +1,53 @@
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":20,"method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"old"}]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"old answer"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":20,"result":{"stopReason":"end_turn"}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"session/load","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"discard failed"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"partial"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"failed"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late discarded replay"}}}}}
+{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late discarded handshake replay"}}}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":0,"method":"initialize","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late discarded handshake replay"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":0,"result":{}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"session/load","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"question"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"thinking"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"tool","title":"Read file","kind":"read","status":"pending","rawInput":{"path":"file.txt"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"tool","status":"completed","rawOutput":"contents"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"answer"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":1,"result":{}}}
+{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":0,"method":"initialize","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":0,"result":{}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"session/load","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"question"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"thinking"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"tool","title":"Read file","kind":"read","status":"pending","rawInput":{"path":"file.txt"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"tool","status":"completed","rawOutput":"contents"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"answer"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":1,"result":{}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":2,"method":"session/resume","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":2,"result":{}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":21,"method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"next"}]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"continued"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":21,"result":{"stopReason":"end_turn"}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"session/load","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"discard disconnected"}}}}}
+{"direction":"to_server","content":{"type":"event","event":"disconnected"}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late discarded replay"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":1,"result":{}}}
+{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late discarded handshake replay"}}}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":0,"method":"initialize","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late discarded handshake replay"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":0,"result":{}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"session/load","params":{"sessionId":"s"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"user_message_chunk","content":{"type":"text","text":"discard incomplete"}}}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":1}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late abandoned replay"}}}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":7,"method":"session/load","params":{"sessionId":"s","cwd":"/","mcpServers":[]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"malformed candidate"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":7,"result":false}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"late malformed replay"}}}}}
diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rs
index 365795dabf..7adc8dec01 100644
--- a/crates/agent_fold/src/domain/fold.rs
+++ b/crates/agent_fold/src/domain/fold.rs
@@ -67,6 +67,8 @@ mod convert;
mod permission;
/// The agent's plan (todo list).
mod plan;
+/// Transactional generic ACP history replacement.
+mod replay;
/// The fold's state and the per-frame dispatch.
mod state;
/// Delegated agents and the calls nested under them.
@@ -114,6 +116,7 @@ fn fold_machine(log: impl IntoIterator<Item = AgentSessionLog>) -> FoldMachineIm
#[derive(Debug, Default)]
pub struct FoldMachineImpl {
state: FoldState,
+ replay: replay::Replay,
}
impl FoldMachineImpl {
@@ -123,7 +126,9 @@ impl FoldMachineImpl {
Self::default()
}
- /// Every message derived so far, oldest first.
+ /// Every committed message, oldest first. A pending load is invisible here.
+ /// The candidate remains in the machine so snapshot catch-up can continue
+ /// through its eventual success or failure on the live stream.
///
/// Includes the open turn's agent message, still being appended to. There
/// is nothing to finalize: a message is complete the moment no further
@@ -155,7 +160,16 @@ impl FoldMachineImpl {
impl FoldMachine for FoldMachineImpl {
fn push(&mut self, log: AgentSessionLog) -> Vec<FoldEvent<'_>> {
- let changes = self.state.step(log);
+ let changes = match self.replay.step(&mut self.state, log) {
+ replay::Outcome::Changes(changes) => changes,
+ replay::Outcome::Staged => return Vec::new(),
+ replay::Outcome::Replaced => {
+ return vec![
+ FoldEvent::MessagesReplaced(Cow::Borrowed(&self.state.messages)),
+ FoldEvent::MetadataUpdated(Cow::Borrowed(&self.state.metadata)),
+ ];
+ }
+ };
changes
.into_iter()
.filter_map(|change| match change {
diff --git a/crates/agent_fold/src/domain/fold/content.rs b/crates/agent_fold/src/domain/fold/content.rs
index 49c7ccc1bb..fff9bc6ae5 100644
--- a/crates/agent_fold/src/domain/fold/content.rs
+++ b/crates/agent_fold/src/domain/fold/content.rs
@@ -19,6 +19,9 @@ impl FoldState {
/// Append agent prose, extending the trailing text part when there is one.
pub(super) fn append_text(&mut self, text: String) -> Option<Changed> {
+ if text.is_empty() {
+ return None;
+ }
if let Some((message, parts)) = self.agent_parts_mut()
&& let MessagePart::Text { text: existing } = parts.last_mut()
{
diff --git a/crates/agent_fold/src/domain/fold/replay.rs b/crates/agent_fold/src/domain/fold/replay.rs
new file mode 100644
index 0000000000..a966975c76
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/replay.rs
@@ -0,0 +1,266 @@
+//! A load is a transaction over the visible projection, not new activity.
+
+use agent_client_protocol::schema::v1::{
+ AGENT_METHOD_NAMES, InitializeRequest, LoadSessionRequest, LoadSessionResponse,
+ NewSessionRequest, NewSessionResponse, PromptRequest, RequestId, Response,
+ ResumeSessionRequest, ResumeSessionResponse,
+};
+use agent_client_protocol::{JsonRpcMessage, JsonRpcResponse, RawJsonRpcMessage, RawJsonRpcParams};
+use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
+
+use super::convert::param;
+use super::state::{FoldState, StepChange};
+use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};
+
+#[derive(Debug, Default)]
+pub(super) struct Replay {
+ session: Option<AgentSessionId>,
+ initialization: FoldState,
+ transaction: Option<Transaction>,
+ disconnected: bool,
+ // A failed/abandoned load may still have queued notifications. Handshake
+ // markers invalidate correlations, but do not prove those frames are live.
+ quarantined: bool,
+ replay_session: Option<String>,
+ pending_open: Option<(RequestId, Opening)>,
+}
+
+#[derive(Debug)]
+enum Opening {
+ New,
+ Resume,
+}
+
+impl Opening {
+ fn accepts(&self, response: &Response<serde_json::Value>) -> bool {
+ let Response::Result { result, .. } = response else {
+ return false;
+ };
+ match self {
+ Self::New => {
+ NewSessionResponse::from_value(AGENT_METHOD_NAMES.session_new, result.clone())
+ .is_ok()
+ }
+ Self::Resume => {
+ ResumeSessionResponse::from_value(AGENT_METHOD_NAMES.session_resume, result.clone())
+ .is_ok()
+ }
+ }
+ }
+}
+
+#[derive(Debug)]
+struct Transaction {
+ request: RequestId,
+ session: String,
+ metadata: crate::domain::model::SessionMetadata,
+ pending_initialize: Option<RequestId>,
+ entries: Vec<AgentSessionLog>,
+}
+
+pub(super) enum Outcome {
+ Changes(Vec<StepChange>),
+ Staged,
+ Replaced,
+}
+
+impl Replay {
+ fn loading(&self) -> bool {
+ self.transaction.is_some()
+ }
+
+ fn commit(&mut self, committed: &mut FoldState, completion: AgentSessionLog) -> Outcome {
+ let mut transaction = self.transaction.take().expect("matched transaction");
+ transaction.entries.push(completion);
+ let mut state = FoldState {
+ metadata: transaction.metadata,
+ pending_initialize: transaction.pending_initialize,
+ replaying: true,
+ ..FoldState::default()
+ };
+ for entry in transaction.entries {
+ state.step(entry);
+ }
+ state.replaying = false;
+ *committed = state;
+ Outcome::Replaced
+ }
+
+ pub(super) fn step(&mut self, committed: &mut FoldState, entry: AgentSessionLog) -> Outcome {
+ // One machine per Macro session. A multiplexed transport must route
+ // frames before folding; a foreign response must never commit a load.
+ if self
+ .session
+ .is_some_and(|session| session != entry.agent_session_id)
+ {
+ return Outcome::Staged;
+ }
+ self.session = Some(entry.agent_session_id);
+ if let Message::ToServer(ToServerMessage::Event { event }) = &entry.content {
+ if matches!(event, SystemEvent::AcpReady | SystemEvent::Disconnected) {
+ self.quarantined |=
+ self.transaction.is_some() || matches!(event, SystemEvent::Disconnected);
+ self.transaction = None;
+ self.pending_open = None;
+ self.initialization = FoldState::default();
+ self.disconnected = matches!(event, SystemEvent::Disconnected);
+ committed.clear_pending();
+ }
+ self.initialization.step(entry.clone());
+ if let Some(candidate) = &mut self.transaction {
+ candidate.entries.push(entry.clone());
+ }
+ return Outcome::Changes(committed.step(entry));
+ }
+ if let Message::ToRuntime(ToRuntimeMessage::Acp(acp)) = &entry.content
+ && let RawJsonRpcMessage::Request(request) = &acp.0
+ {
+ if InitializeRequest::matches_method(&request.method) {
+ // Initialization starts a correlation epoch, but does not
+ // erase committed messages or imply a successful restore.
+ self.quarantined |= self.loading();
+ self.transaction = None;
+ self.pending_open = None;
+ self.disconnected = false;
+ self.initialization = FoldState::default();
+ self.initialization.metadata.status = Some("acp_ready".to_owned());
+ committed.clear_pending();
+ self.initialization.step(entry.clone());
+ } else if !self.disconnected && LoadSessionRequest::matches_method(&request.method) {
+ let Some(session) =
+ param(request.params.as_ref(), "sessionId").and_then(|v| v.as_str())
+ else {
+ return Outcome::Staged;
+ };
+ self.pending_open = None;
+ self.replay_session = Some(session.to_owned());
+ self.transaction = Some(Transaction {
+ request: request.id.clone(),
+ session: session.to_owned(),
+ metadata: self.initialization.metadata.clone(),
+ pending_initialize: self.initialization.pending_initialize.clone(),
+ entries: vec![entry],
+ });
+ return Outcome::Staged;
+ } else if !self.disconnected
+ && self.quarantined
+ && !self.loading()
+ && let Some(RawJsonRpcParams::Object(params)) = request.params.as_ref()
+ {
+ match request.method.as_ref() {
+ method
+ if PromptRequest::matches_method(method)
+ && PromptRequest::parse_message(method, params).is_ok()
+ && self.matches_replay_session(request.params.as_ref()) =>
+ {
+ // Only dispatched prompts enter the log; SessionMachine
+ // dispatches them after the handshake reaches Live.
+ self.quarantined = false;
+ self.pending_open = None;
+ committed.clear_pending();
+ }
+ method
+ if NewSessionRequest::matches_method(method)
+ && NewSessionRequest::parse_message(method, params).is_ok() =>
+ {
+ self.pending_open = Some((request.id.clone(), Opening::New));
+ return Outcome::Changes(committed.step(entry));
+ }
+ method
+ if ResumeSessionRequest::matches_method(method)
+ && ResumeSessionRequest::parse_message(method, params).is_ok()
+ && self.matches_replay_session(request.params.as_ref()) =>
+ {
+ self.pending_open = Some((request.id.clone(), Opening::Resume));
+ return Outcome::Changes(committed.step(entry));
+ }
+ _ => {}
+ }
+ }
+ }
+ if self.disconnected {
+ return Outcome::Staged;
+ }
+ if let Message::ToServer(ToServerMessage::Acp(acp)) = &entry.content
+ && let RawJsonRpcMessage::Response(response) = &acp.0
+ {
+ let id = match response {
+ Response::Result { id, .. } | Response::Error { id, .. } => id,
+ };
+ if self.initialization.pending_initialize.as_ref() == Some(id) {
+ self.initialization.step(entry.clone());
+ if self.transaction.is_none() {
+ return Outcome::Changes(committed.step(entry));
+ }
+ }
+ if self
+ .transaction
+ .as_ref()
+ .is_some_and(|candidate| &candidate.request == id)
+ {
+ // Match SessionMachine::on_session_opened exactly: JSON-RPC
+ // success alone is insufficient; the ACP result must decode.
+ if !matches!(response, Response::Result { result, .. }
+ if LoadSessionResponse::from_value(AGENT_METHOD_NAMES.session_load, result.clone()).is_ok())
+ {
+ self.transaction = None;
+ self.quarantined = true;
+ return Outcome::Staged;
+ }
+ self.quarantined = false;
+ // Load completion is not turn completion. Keep the last replayed
+ // turn open so live chunks after the high-water mark append to it.
+ return self.commit(committed, entry);
+ }
+ if self
+ .pending_open
+ .as_ref()
+ .is_some_and(|(pending, _)| pending == id)
+ {
+ let (_, opening) = self.pending_open.take().expect("matched opening request");
+ if opening.accepts(response) {
+ self.quarantined = false;
+ } else {
+ committed.pending_config_requests.remove(id);
+ return Outcome::Staged;
+ }
+ }
+ }
+ if let Some(candidate) = &mut self.transaction {
+ let params = match &entry.content {
+ Message::ToServer(ToServerMessage::Acp(acp))
+ | Message::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {
+ RawJsonRpcMessage::Request(request) => request.params.as_ref(),
+ RawJsonRpcMessage::Notification(notification) => notification.params.as_ref(),
+ _ => None,
+ },
+ _ => None,
+ };
+ if param(params, "sessionId")
+ .and_then(|v| v.as_str())
+ .is_some_and(|session| session != candidate.session)
+ {
+ return Outcome::Staged;
+ }
+ candidate.entries.push(entry);
+ return Outcome::Staged;
+ }
+ if self.quarantined {
+ return Outcome::Staged;
+ }
+ Outcome::Changes(committed.step(entry))
+ }
+
+ fn matches_replay_session(
+ &self,
+ params: Option<&agent_client_protocol::RawJsonRpcParams>,
+ ) -> bool {
+ param(params, "sessionId")
+ .and_then(|value| value.as_str())
+ .is_some_and(|session| {
+ self.replay_session
+ .as_deref()
+ .is_none_or(|expected| session == expected)
+ })
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/state.rs b/crates/agent_fold/src/domain/fold/state.rs
index 490d717b02..3d6ee5d700 100644
--- a/crates/agent_fold/src/domain/fold/state.rs
+++ b/crates/agent_fold/src/domain/fold/state.rs
@@ -78,6 +78,8 @@ pub(super) struct FoldState {
/// Every message derived so far, oldest first - including the open turn's
/// agent message, which is appended to in place as the agent talks.
pub(super) messages: Vec<FoldedMessage>,
+ /// User notifications are authoritative only inside a staged load.
+ pub(super) replaying: bool,
/// The session the entry currently being folded belongs to, for
/// [`State::warn`]. Set fresh from each log entry, so it is always
/// current even though it rarely changes within one fold.
@@ -158,6 +160,15 @@ pub(super) struct Turn {
}
impl FoldState {
+ /// Forget request correlations at a connection boundary without clearing history.
+ pub(super) fn clear_pending(&mut self) {
+ self.pending_initialize = None;
+ self.pending_config_requests.clear();
+ self.pending_permissions.clear();
+ self.pending_controls.clear();
+ self.close_turn(None);
+ }
+
/// Advance by one log entry, returning what it changed in emission order.
///
/// One entry changes at most one message today - see [`FoldEvent`]
@@ -222,6 +233,35 @@ impl FoldState {
}
Message::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {
+ RawJsonRpcMessage::Notification(notification)
+ if notification.method.as_ref() == "_session/turn_complete" =>
+ {
+ use agent_runtime_protocol::domain::turn::{
+ TurnCompleteNotification, TurnOutcome,
+ };
+ // A real pending prompt completes only through its correlated
+ // response. Historical facts may finish replay or an unprompted
+ // continuation, never an unrelated pending user request.
+ if !self.replaying
+ && self
+ .turn
+ .as_ref()
+ .is_some_and(|turn| turn.prompt_id.is_some())
+ {
+ return Vec::new();
+ }
+ let stop = super::convert::deserialize_params::<TurnCompleteNotification>(
+ notification.params.as_ref(),
+ )
+ .map(|fact| match fact.outcome {
+ TurnOutcome::Finished => crate::domain::model::StopReason::EndTurn,
+ TurnOutcome::Cancelled => crate::domain::model::StopReason::Cancelled,
+ TurnOutcome::Failed { message } => {
+ crate::domain::model::StopReason::Failed { message }
+ }
+ });
+ StepChange::message(stop.and_then(|stop| self.close_turn(Some(stop))))
+ }
// The bulk of the log: streamed content and tool activity.
RawJsonRpcMessage::Notification(notification)
if SessionNotification::matches_method(&notification.method) =>
@@ -333,8 +373,19 @@ impl FoldState {
SessionUpdate::AgentThoughtChunk(chunk) => StepChange::message(
content_block_text(chunk.content).and_then(|text| self.append_thought(text)),
),
- // The agent replaying the user's own message. The prompt frame is
- // the authoritative copy, so this is dropped.
+ // Replay has no original prompt requests: user chunks are its
+ // authoritative prompts. Outside load, ignore prompt echoes.
+ SessionUpdate::UserMessageChunk(chunk)
+ if self.replaying
+ || self
+ .turn
+ .as_ref()
+ .is_none_or(|turn| turn.prompt_id.is_none()) =>
+ {
+ StepChange::message(
+ content_block_text(chunk.content).and_then(|text| self.replay_user_text(text)),
+ )
+ }
SessionUpdate::UserMessageChunk(_) => Vec::new(),
SessionUpdate::ToolCall(call) => {
let mut changes =
diff --git a/crates/agent_fold/src/domain/fold/turn.rs b/crates/agent_fold/src/domain/fold/turn.rs
index cc2a150fd9..446c431d7b 100644
--- a/crates/agent_fold/src/domain/fold/turn.rs
+++ b/crates/agent_fold/src/domain/fold/turn.rs
@@ -14,6 +14,33 @@ use super::convert::{content_block_text, deserialize_params};
use super::state::{Changed, FoldState, Turn};
impl FoldState {
+ /// Adjacent user chunks form one replayed prompt; agent activity separates turns.
+ pub(super) fn replay_user_text(&mut self, text: String) -> Option<Changed> {
+ if text.is_empty() {
+ return None;
+ }
+ if self.turn.as_ref().is_some_and(|turn| turn.agent.is_none())
+ && let Some(message) = self.messages.last_mut()
+ && matches!(message.author, Author::User { .. })
+ && let Some(MessagePart::Text { text: held }) = message.parts.get_mut(0)
+ {
+ held.push_str(&text);
+ return Some(Changed::updated(self.messages.len() - 1));
+ }
+ self.close_turn(Some(StopReason::EndTurn));
+ self.begin_turn_without_prompt();
+ let id = self.open_turn().id;
+ let message = self.messages.len();
+ self.messages.push(FoldedMessage {
+ id,
+ author: Author::User { user_id: None },
+ request_id: None,
+ parts: NonEmpty::one(MessagePart::Text { text }),
+ stop: None,
+ });
+ Some(Changed::new(message))
+ }
+
/// Handle a `session/prompt`: emit the user's message, open a turn.
pub(super) fn begin_turn(
&mut self,
diff --git a/crates/agent_fold/src/domain/ingestion.rs b/crates/agent_fold/src/domain/ingestion.rs
new file mode 100644
index 0000000000..b7c4225c18
--- /dev/null
+++ b/crates/agent_fold/src/domain/ingestion.rs
@@ -0,0 +1,61 @@
+//! Reconcile a durable effective-history snapshot with overlapping live rows.
+//!
+//! Row identity is not ACP identity: distinct rows may intentionally replay the
+//! same protocol content. Only snapshot row IDs and rows before its inclusive
+//! history boundary are excluded. Live rows retain delivery order.
+
+use super::fold::FoldMachineImpl;
+use super::log::AgentSessionLog;
+use super::model::FoldEvent;
+use super::ports::FoldMachine;
+use chrono::{DateTime, Utc};
+use macro_uuid::Uuid;
+use serde::Deserialize;
+use std::collections::HashSet;
+
+#[cfg(test)]
+mod test;
+
+/// Repository ordering key, preserving Postgres submillisecond precision.
+#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
+#[serde(rename_all = "camelCase")]
+pub struct LogCursor {
+ /// Durable insertion timestamp, compared before the row ID.
+ pub created_at: DateTime<Utc>,
+ /// Durable row identity and equal-timestamp tie breaker.
+ pub id: Uuid,
+}
+
+/// One snapshot-backed fold. Retained reconciliation state is bounded by the
+/// snapshot size; following a long-running stream never grows an ID cache.
+#[derive(Default)]
+pub struct LogIngestion {
+ /// The append-only protocol machine, also usable without durable metadata.
+ pub machine: FoldMachineImpl,
+ boundary: Option<LogCursor>,
+ snapshot_ids: HashSet<Uuid>,
+}
+
+impl LogIngestion {
+ /// Replace the machine with an authoritative snapshot in repository order.
+ pub fn replace_snapshot(&mut self, rows: Vec<(LogCursor, AgentSessionLog)>) {
+ self.machine = FoldMachineImpl::new();
+ self.boundary = rows.first().map(|(cursor, _)| *cursor);
+ self.snapshot_ids = rows.iter().map(|(cursor, _)| cursor.id).collect();
+ for (_, row) in rows {
+ let _ = self.machine.push(row);
+ }
+ }
+
+ /// Append a live row unless already represented or excluded by the snapshot.
+ /// Never compare against a moving high-water mark: live delivery order is
+ /// authoritative, and a late distinct row must not disappear.
+ pub fn push(&mut self, cursor: LogCursor, row: AgentSessionLog) -> Vec<FoldEvent<'_>> {
+ if self.boundary.is_some_and(|boundary| cursor < boundary)
+ || self.snapshot_ids.contains(&cursor.id)
+ {
+ return Vec::new();
+ }
+ self.machine.push(row)
+ }
+}
diff --git a/crates/agent_fold/src/domain/ingestion/test.rs b/crates/agent_fold/src/domain/ingestion/test.rs
new file mode 100644
index 0000000000..864abfd3f1
--- /dev/null
+++ b/crates/agent_fold/src/domain/ingestion/test.rs
@@ -0,0 +1,62 @@
+use super::*;
+use crate::testing::parse_log;
+
+fn row() -> AgentSessionLog {
+ parse_log(r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"runtime","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"same"}}}}}"#).remove(0)
+}
+
+fn cursor(id: u128, timestamp: &str) -> LogCursor {
+ LogCursor {
+ id: Uuid::from_u128(id),
+ created_at: timestamp.parse().unwrap(),
+ }
+}
+
+#[test]
+fn snapshot_overlap_is_row_identity_not_protocol_content() {
+ let a = cursor(2, "2026-08-13T00:00:00.000002Z");
+ let b = cursor(3, "2026-08-13T00:00:00.000003Z");
+ let mut ingestion = LogIngestion::default();
+ ingestion.replace_snapshot(vec![(a, row()), (b, row())]);
+ for duplicate in [b, a, b] {
+ assert!(ingestion.push(duplicate, row()).is_empty());
+ }
+ assert!(
+ ingestion
+ .push(cursor(9, "2026-08-13T00:00:00.000001Z"), row())
+ .is_empty()
+ );
+ assert!(
+ !ingestion
+ .push(cursor(1, "2026-08-13T00:00:00.000004Z"), row())
+ .is_empty()
+ );
+ // A distinct late row remains valid even behind the latest delivery.
+ assert!(
+ !ingestion
+ .push(cursor(4, "2026-08-13T00:00:00.000003Z"), row())
+ .is_empty()
+ );
+ assert_eq!(ingestion.snapshot_ids.len(), 2);
+}
+
+#[test]
+fn equal_timestamps_use_uuid_order_and_variable_precision_is_equal() {
+ let boundary = cursor(2, "2026-08-13T00:00:00Z");
+ let mut ingestion = LogIngestion::default();
+ ingestion.replace_snapshot(vec![(boundary, row())]);
+ assert!(
+ ingestion
+ .push(cursor(1, "2026-08-13T00:00:00.000000Z"), row())
+ .is_empty()
+ );
+ assert!(
+ !ingestion
+ .push(cursor(3, "2026-08-13T00:00:00.000000Z"), row())
+ .is_empty()
+ );
+ ingestion.replace_snapshot(Vec::new());
+ assert!(ingestion.machine.messages().is_empty());
+ assert!(ingestion.snapshot_ids.is_empty());
+ assert!(!ingestion.push(boundary, row()).is_empty());
+}
diff --git a/crates/agent_fold/src/domain/mod.rs b/crates/agent_fold/src/domain/mod.rs
index 5ab4a88a27..83cce2079f 100644
--- a/crates/agent_fold/src/domain/mod.rs
+++ b/crates/agent_fold/src/domain/mod.rs
@@ -7,6 +7,8 @@ mod error;
pub mod fold;
/// Harness-specific `_meta` and raw-input extraction.
pub mod harness;
+/// Durable snapshot and live-row ingestion around the append-only protocol fold.
+pub mod ingestion;
/// The raw log vocabulary the fold consumes.
pub mod log;
/// The renderable message vocabulary.
diff --git a/crates/agent_fold/src/domain/model/event.rs b/crates/agent_fold/src/domain/model/event.rs
index 83bd99079c..cc12c3775d 100644
--- a/crates/agent_fold/src/domain/model/event.rs
+++ b/crates/agent_fold/src/domain/model/event.rs
@@ -18,6 +18,9 @@ pub enum FoldEvent<'a> {
NewMessage(Cow<'a, FoldedMessage>),
/// A message the machine had already reported, whose content changed.
MessageUpdate(Cow<'a, FoldedMessage>),
+ /// A successful load atomically replaced the entire conversation. Consumers
+ /// must remove old messages, including when this list is empty.
+ MessagesReplaced(Cow<'a, [FoldedMessage]>),
/// The metadata changed - restating identical metadata reports nothing.
MetadataUpdated(Cow<'a, SessionMetadata>),
}
@@ -32,7 +35,7 @@ impl FoldEvent<'_> {
pub fn message(&self) -> Option<&FoldedMessage> {
match self {
Self::NewMessage(message) | Self::MessageUpdate(message) => Some(message.as_ref()),
- Self::MetadataUpdated(_) => None,
+ Self::MetadataUpdated(_) | Self::MessagesReplaced(_) => None,
}
}
@@ -44,6 +47,9 @@ impl FoldEvent<'_> {
Self::MessageUpdate(message) => {
FoldEvent::MessageUpdate(Cow::Owned(message.into_owned()))
}
+ Self::MessagesReplaced(messages) => {
+ FoldEvent::MessagesReplaced(Cow::Owned(messages.into_owned()))
+ }
Self::MetadataUpdated(metadata) => {
FoldEvent::MetadataUpdated(Cow::Owned(metadata.into_owned()))
}
diff --git a/crates/agent_fold/src/domain/ports.rs b/crates/agent_fold/src/domain/ports.rs
index 9921000a6f..05ac965b36 100644
--- a/crates/agent_fold/src/domain/ports.rs
+++ b/crates/agent_fold/src/domain/ports.rs
@@ -32,8 +32,10 @@ use std::collections::VecDeque;
/// The one capability folding needs from storage, named by this crate in its
/// own vocabulary - see the module docs.
pub trait LogRepo {
- /// A session's log rows, oldest first. A session with no log returns an
- /// empty queue.
+ /// Effective ACP history in deterministic log order, beginning at the
+ /// initialization preceding the latest successful load (or the beginning
+ /// if none succeeded). Failed/incomplete load frames remain in this window;
+ /// the fold stages and discards them. A session with no log returns an empty queue.
fn list_by_session(
&self,
session: AgentSessionId,
@@ -74,6 +76,17 @@ pub trait FoldSession {
pub trait FoldMachine {
/// Advance the machine by one log entry, reporting every change it
/// implied in order - empty for a frame that changes nothing.
+ ///
+ /// One machine consumes one session in log order. Forward `initialize`,
+ /// `acp_ready`, and `disconnected` to delimit request-correlation epochs;
+ /// the session owner must reject frames from superseded connections before
+ /// appending them. Load candidates stay invisible until their matching
+ /// response decodes as `LoadSessionResponse`, when `MessagesReplaced`
+ /// replaces all prior messages. Failed/abandoned attempts quarantine late
+ /// notifications across handshake markers until a valid load/open response
+ /// or a dispatched prompt establishes live traffic.
+ /// An incomplete candidate remains available for subsequent streaming,
+ /// while batch readers see only the previous committed projection.
fn push(&mut self, log: AgentSessionLog) -> Vec<FoldEvent<'_>>;
}
diff --git a/crates/agent_fold/src/domain/test.rs b/crates/agent_fold/src/domain/test.rs
index 7a4bb7ef9c..4661bc36c1 100644
--- a/crates/agent_fold/src/domain/test.rs
+++ b/crates/agent_fold/src/domain/test.rs
@@ -12,3 +12,5 @@ mod service;
mod subagent;
mod tool_name;
mod util;
+
+mod replay;
diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rs
index a70a0a6ae2..233ff960db 100644
--- a/crates/agent_fold/src/domain/test/fold.rs
+++ b/crates/agent_fold/src/domain/test/fold.rs
@@ -473,6 +473,15 @@ fn folds_nothing() {
assert_eq!(warnings, vec![]);
}
+#[test]
+fn an_empty_agent_chunk_does_not_create_a_message() {
+ let log = parse_log(
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":""}}}}}"#,
+ );
+
+ assert_eq!(fold(log), vec![]);
+}
+
/// How many `session/update` notifications a log carries - the frames that
/// stream the agent's own content, and so the sign that a recording has
/// something for the fold to find.
diff --git a/crates/agent_fold/src/domain/test/machine.rs b/crates/agent_fold/src/domain/test/machine.rs
index 47baf8c13e..ba0472b369 100644
--- a/crates/agent_fold/src/domain/test/machine.rs
+++ b/crates/agent_fold/src/domain/test/machine.rs
@@ -45,6 +45,10 @@ impl Consumer {
FoldEvent::NewMessage(message) => (true, message.into_owned()),
FoldEvent::MessageUpdate(message) => (false, message.into_owned()),
FoldEvent::MetadataUpdated(_) => return,
+ FoldEvent::MessagesReplaced(messages) => {
+ self.messages = messages.into_owned();
+ return;
+ }
};
let id = message.id();
self.reports.push((is_new, id));
@@ -272,23 +276,16 @@ fn content_without_a_prompt_still_folds() {
"\n",
r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"picking up where we left off"}}}}}"#,
"\n",
- // Closed by a response to the prompt that lives in the resumed
- // session's own log - not by the load response, which carries config
- // options rather than a stop reason.
- r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#,
+ // Replay becomes visible only when the matching load succeeds.
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"l","result":{}}}"#,
));
let consumer = Consumer::drive(resumed);
- let agent_side = MessageId {
- turn: TurnId(0),
- author: AuthorKind::Agent,
- };
- assert_eq!(
- consumer.reports,
- vec![(true, agent_side), (false, agent_side)],
- "the agent's side is announced and then closed; there is no prompt to \
- derive a user side from"
+ assert!(
+ consumer.reports.is_empty(),
+ "replay is delivered as a replacement, not new activity"
);
+ assert_eq!(consumer.messages.len(), 1);
let agent = &consumer.messages[0];
assert_eq!(
@@ -298,9 +295,8 @@ fn content_without_a_prompt_still_folds() {
}]
);
assert_eq!(
- agent.stop,
- Some(StopReason::EndTurn),
- "a turn nothing prompted is closed by the first response that stops"
+ agent.stop, None,
+ "load completion does not imply that the last replayed turn finished"
);
}
diff --git a/crates/agent_fold/src/domain/test/real_recordings.rs b/crates/agent_fold/src/domain/test/real_recordings.rs
index 2a2e994c25..d750b19d4c 100644
--- a/crates/agent_fold/src/domain/test/real_recordings.rs
+++ b/crates/agent_fold/src/domain/test/real_recordings.rs
@@ -53,11 +53,8 @@ fn every_real_fixture_folds_without_warnings() {
});
}
-/// The regression pin: a log that opens with `session/load` and carries no
-/// `session/prompt` still derives the agent's side. Before
-/// `begin_turn_without_prompt`, every frame in a log shaped like this had no
-/// open turn to belong to, and the fold silently derived nothing - see that
-/// function's docs.
+/// A successful load reconstructs both sides without session/prompt requests:
+/// the replayed user_message_chunk frames supply the historical prompts.
#[test]
fn resumed_no_prompt_still_derives_the_agents_reply() {
let (messages, warnings) = capturing_warnings(|| fold(parse_log(RESUMED_NO_PROMPT)));
@@ -74,19 +71,16 @@ fn resumed_no_prompt_still_derives_the_agents_reply() {
"no agent message was derived from a log that is nothing but agent content: {messages:#?}"
);
assert!(
- !messages
+ messages
.iter()
.filter(|message| message.author.kind() == crate::domain::model::AuthorKind::User)
.flat_map(|message| message.parts.iter())
.any(|part| matches!(part, crate::domain::model::MessagePart::Text { .. })),
- "this recording carries no session/prompt, so it should derive no user text"
+ "successful load reconstructs user text from user_message_chunk notifications"
);
}
-/// A resumed session that goes on to take fresh prompts in the same log: the
-/// turn that resumed with no prompt of its own, and the turns that follow it
-/// with real prompts, must both derive correctly in one fold. Neither the
-/// pure-resume nor the pure-fresh-session fixtures cover this mix.
+/// Replayed prompts and subsequent live requests share the same turn numbering.
#[test]
fn resumed_and_continued_derives_both_the_resumed_and_the_fresh_turns() {
let (messages, warnings) = capturing_warnings(|| fold(parse_log(RESUMED_AND_CONTINUED)));
@@ -100,10 +94,9 @@ fn resumed_and_continued_derives_both_the_resumed_and_the_fresh_turns() {
.iter()
.filter(|message| message.author == Author::Agent)
.count();
- assert!(
- agent_messages > user_messages,
- "the resumed turn has an agent side but no prompt of its own, so agent \
- messages ({agent_messages}) should outnumber user messages ({user_messages})"
+ assert_eq!(
+ agent_messages, user_messages,
+ "replayed user prompts and fresh prompts both survive"
);
}
@@ -135,15 +128,8 @@ fn streaming_a_real_recording_matches_folding_it() {
});
}
-/// What only `long_multi_resume` can prove: turn numbering stays unique
-/// across three separate `session/load` boundaries in one fold, not just
-/// one. `TurnId` is a single counter for the whole fold
-/// ([`State::turns_opened`](crate::domain::fold::State)) rather than
-/// anything that resets per resume, but a log with only one resume - like
-/// `resumed_no_prompt` - cannot tell that apart from a counter that happens
-/// to reset correctly the one time it is asked to. Three resumes in one log
-/// can: a reset-per-resume bug would collide the second and third resumed
-/// turn onto ids the first one already used.
+/// Multiple load attempts still produce unique keys in the committed history.
+/// A successful load replaces earlier keys rather than appending duplicates.
#[test]
fn three_resumes_in_one_log_derive_distinct_message_ids() {
let (messages, warnings) = capturing_warnings(|| fold(parse_log(LONG_MULTI_RESUME)));
diff --git a/crates/agent_fold/src/domain/test/replay.rs b/crates/agent_fold/src/domain/test/replay.rs
new file mode 100644
index 0000000000..457105fec1
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/replay.rs
@@ -0,0 +1,694 @@
+//! Transactional load semantics shared by server and browser folds.
+use super::util::{TURN, parse_log};
+use crate::domain::fold::{FoldMachineImpl, fold};
+use crate::domain::log::{AgentSessionId, AgentSessionLog};
+use crate::domain::model::{FoldEvent, FoldedMessage, MessagePart};
+use crate::domain::ports::FoldMachine;
+use serde_json::{Value, json};
+
+fn frame(direction: &str, body: Value) -> AgentSessionLog {
+ let mut content = body;
+ content["type"] = json!("acp");
+ content["jsonrpc"] = json!("2.0");
+ parse_log(&json!({"direction":direction,"content":content}).to_string())
+ .pop()
+ .unwrap()
+}
+fn request(method: &str, id: Value) -> AgentSessionLog {
+ frame(
+ "to_runtime",
+ json!({"id":id,"method":method,"params":{"sessionId":"s","cwd":"/","mcpServers":[]}}),
+ )
+}
+fn result(id: Value) -> AgentSessionLog {
+ frame("to_server", json!({"id":id,"result":{}}))
+}
+fn update(kind: &str, text: &str) -> AgentSessionLog {
+ frame(
+ "to_server",
+ json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":kind,"content":{"type":"text","text":text}}}}),
+ )
+}
+fn event(name: &str) -> AgentSessionLog {
+ parse_log(&json!({"direction":"to_server","content":{"type":"event","event":name}}).to_string())
+ .pop()
+ .unwrap()
+}
+fn replay(id: Value) -> Vec<AgentSessionLog> {
+ vec![
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/load", id.clone()),
+ update("user_message_chunk", "question"),
+ update("user_message_chunk", " one"),
+ update("agent_thought_chunk", "thinking"),
+ update("agent_message_chunk", "answer one"),
+ update("user_message_chunk", "question two"),
+ update("agent_message_chunk", "answer two"),
+ result(id),
+ ]
+}
+fn apply(visible: &mut Vec<FoldedMessage>, event: FoldEvent<'_>) {
+ match event {
+ FoldEvent::MessagesReplaced(messages) => *visible = messages.into_owned(),
+ FoldEvent::NewMessage(message) => visible.push(message.into_owned()),
+ FoldEvent::MessageUpdate(message) => {
+ let at = visible
+ .iter()
+ .position(|old| old.id() == message.id())
+ .unwrap();
+ visible[at] = message.into_owned();
+ }
+ FoldEvent::MetadataUpdated(_) => {}
+ }
+}
+#[test]
+fn repeated_loads_replace_and_every_incremental_prefix_matches_batch() {
+ let mut log: Vec<_> = parse_log(TURN).into_iter().collect();
+ let boundary = log.len();
+ log.extend(replay(json!(1)));
+ log.extend(replay(json!(1)));
+ let mut machine = FoldMachineImpl::new();
+ let mut visible = vec![];
+ let mut replacements = 0;
+ for (i, entry) in log.iter().enumerate() {
+ for event in machine.push(entry.clone()) {
+ replacements += usize::from(matches!(event, FoldEvent::MessagesReplaced(_)));
+ apply(&mut visible, event.into_owned());
+ }
+ assert_eq!(visible, machine.messages());
+ assert_eq!(visible, fold(log[..=i].iter().cloned()));
+ }
+ assert_eq!(replacements, 2);
+ assert_eq!(visible, fold(log[boundary..].iter().cloned()));
+ assert_eq!(visible.len(), 4);
+ assert_eq!(
+ visible[0].parts.first(),
+ Some(&MessagePart::Text {
+ text: "question one".into()
+ })
+ );
+ assert!(visible[1].stop.is_some());
+ assert!(visible[3].stop.is_none());
+ assert_eq!(machine.next_turn_id().0, 2);
+}
+#[test]
+fn incomplete_failed_and_disconnected_loads_preserve_committed_history() {
+ let old: Vec<_> = parse_log(TURN).into_iter().collect();
+ for ending in [
+ None,
+ Some(frame(
+ "to_server",
+ json!({"id":1,"error":{"code":-32603,"message":"failed"}}),
+ )),
+ Some(event("disconnected")),
+ Some(event("acp_ready")),
+ Some(request("initialize", json!(0))),
+ ] {
+ let mut log = old.clone();
+ let mut candidate = replay(json!(1));
+ candidate.pop();
+ log.extend(candidate);
+ if let Some(ending) = ending {
+ log.push(ending);
+ }
+ assert_eq!(fold(log), fold(old.clone()));
+ }
+}
+#[test]
+fn initialization_new_and_resume_do_not_replace_history() {
+ for method in ["initialize", "session/new", "session/resume"] {
+ let mut log: Vec<_> = parse_log(TURN).into_iter().collect();
+ let old = fold(log.clone());
+ log.extend([request(method, json!(42)), result(json!(42))]);
+ assert_eq!(fold(log), old);
+ }
+}
+#[test]
+fn response_correlation_is_scoped_to_direction_session_and_connection() {
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(TURN) {
+ machine.push(entry);
+ }
+ let old = machine.messages().to_vec();
+ machine.push(request("session/load", json!(7)));
+ machine.push(update("agent_message_chunk", "hidden"));
+ let mut other = result(json!(7));
+ other.agent_session_id = AgentSessionId::TEST_B;
+ assert!(machine.push(other).is_empty());
+ assert!(
+ machine
+ .push(frame("to_runtime", json!({"id":7,"result":{}})))
+ .is_empty()
+ );
+ assert!(machine.push(result(json!(8))).is_empty());
+ assert_eq!(machine.messages(), old);
+ machine.push(event("disconnected"));
+ machine.push(result(json!(7)));
+ machine.push(event("acp_ready"));
+ machine.push(request("session/resume", json!(7)));
+ machine.push(result(json!(7)));
+ assert_eq!(machine.messages(), old);
+ // Reusing an ID on a fresh connection commits only the new candidate.
+ machine.push(request("session/load", json!(7)));
+ machine.push(update("agent_message_chunk", "fresh"));
+ assert!(matches!(
+ machine.push(result(json!(7)))[0],
+ FoldEvent::MessagesReplaced(_)
+ ));
+ assert_eq!(machine.messages().len(), 1);
+}
+#[test]
+fn foreign_acp_session_updates_do_not_enter_candidate_and_empty_load_clears_history() {
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(TURN) {
+ machine.push(entry);
+ }
+ machine.push(request("session/load", json!(3)));
+ machine.push(frame("to_server", json!({"method":"session/update","params":{"sessionId":"other","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"foreign"}}}})));
+ let events = machine.push(result(json!(3)));
+ assert!(matches!(&events[0], FoldEvent::MessagesReplaced(messages) if messages.is_empty()));
+ assert!(machine.messages().is_empty());
+}
+
+#[test]
+fn shared_browser_fixture_commits_only_completed_loads_and_keeps_tools() {
+ let log = parse_log(include_str!("../../../fixtures/load_replacement.jsonl"));
+ let messages = fold(log);
+ let texts: Vec<_> = messages
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .filter_map(|part| match part {
+ MessagePart::Text { text } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(texts, ["question", "answer", "next", "continued"]);
+ assert!(
+ messages
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .any(|part| matches!(
+ part,
+ MessagePart::ToolUse {
+ status: crate::domain::model::ToolStatus::Completed,
+ ..
+ }
+ ))
+ );
+ assert_eq!(messages.len(), 4);
+}
+
+#[test]
+fn replay_metadata_is_staged_and_replaces_old_metadata_only_on_success() {
+ let info = |title| {
+ frame(
+ "to_server",
+ json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"session_info_update","title":title}}}),
+ )
+ };
+ let mut machine = FoldMachineImpl::new();
+ machine.push(info("old"));
+ machine.push(request("session/load", json!(9)));
+ assert!(machine.push(info("failed candidate")).is_empty());
+ assert_eq!(machine.metadata().title.as_deref(), Some("old"));
+ machine.push(frame(
+ "to_server",
+ json!({"id":9,"error":{"code":-32603,"message":"failed"}}),
+ ));
+ assert_eq!(machine.metadata().title.as_deref(), Some("old"));
+ machine.push(request("session/load", json!(9)));
+ machine.push(info("committed"));
+ machine.push(result(json!(9)));
+ assert_eq!(machine.metadata().title.as_deref(), Some("committed"));
+ machine.push(request("session/load", json!(10)));
+ machine.push(result(json!(10)));
+ assert_eq!(
+ machine.metadata().title,
+ None,
+ "old metadata does not leak into a fresh replay"
+ );
+}
+
+#[test]
+fn live_chunks_after_load_continue_the_last_replayed_turn() {
+ let mut machine = FoldMachineImpl::new();
+ for entry in replay(json!(1)) {
+ machine.push(entry);
+ }
+ machine.push(update("agent_message_chunk", " continued"));
+ assert_eq!(machine.messages().len(), 4);
+ assert_eq!(machine.next_turn_id().0, 2);
+ assert_eq!(
+ machine.messages()[3].parts.first(),
+ Some(&MessagePart::Text {
+ text: "answer two continued".into()
+ })
+ );
+}
+
+#[test]
+fn malformed_load_results_match_session_machine_rejection_and_quarantine_late_frames() {
+ use agent_client_protocol::schema::v1::LoadSessionResponse;
+ for malformed in [json!(null), json!(42), json!("invalid"), json!(false)] {
+ assert!(serde_json::from_value::<LoadSessionResponse>(malformed.clone()).is_err());
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(TURN) {
+ machine.push(entry);
+ }
+ let old = machine.messages().to_vec();
+ machine.push(request("session/load", json!(7)));
+ machine.push(update("user_message_chunk", "partial"));
+ assert!(
+ machine
+ .push(frame("to_server", json!({"id":7,"result":malformed})))
+ .is_empty()
+ );
+ // Neither a late chunk nor a second result can resurrect this attempt.
+ assert!(
+ machine
+ .push(update("agent_message_chunk", "late"))
+ .is_empty()
+ );
+ assert!(machine.push(result(json!(7))).is_empty());
+ assert_eq!(machine.messages(), old);
+ machine.push(request("session/load", json!(7)));
+ machine.push(update("agent_message_chunk", "valid retry"));
+ assert!(matches!(
+ machine.push(result(json!(7)))[0],
+ FoldEvent::MessagesReplaced(_)
+ ));
+ }
+}
+
+#[test]
+fn late_replay_is_quarantined_after_failure_disconnect_and_initialization_at_every_prefix() {
+ for boundary in [
+ frame(
+ "to_server",
+ json!({"id":7,"error":{"code":-32603,"message":"failed"}}),
+ ),
+ event("disconnected"),
+ event("acp_ready"),
+ request("initialize", json!(0)),
+ ] {
+ let mut log = parse_log(TURN);
+ let old = fold(log.clone());
+ log.extend([
+ request("session/load", json!(7)), update("user_message_chunk", "partial"), boundary,
+ update("agent_message_chunk", "late after boundary"),
+ event("acp_ready"), update("agent_message_chunk", "late after ready"),
+ request("initialize", json!(0)), result(json!(0)),
+ update("agent_thought_chunk", "late after init"),
+ frame("to_server", json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"late","title":"late tool","kind":"read","status":"pending"}}})),
+ frame("to_server", json!({"method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"session_info_update","title":"late title"}}})),
+ result(json!(7)),
+ ]);
+ let mut machine = FoldMachineImpl::new();
+ let mut visible = vec![];
+ for (index, entry) in log.iter().enumerate() {
+ for event in machine.push(entry.clone()) {
+ apply(&mut visible, event);
+ }
+ assert_eq!(visible, fold(log[..=index].iter().cloned()));
+ }
+ assert_eq!(visible, old);
+ assert_ne!(machine.metadata().title.as_deref(), Some("late title"));
+ // Reuse the same request ID in the new epoch; only the new replay commits.
+ machine.push(request("session/load", json!(7)));
+ machine.push(update("agent_message_chunk", "fresh replay"));
+ machine.push(result(json!(7)));
+ assert_eq!(machine.messages().len(), 1);
+ }
+}
+
+#[test]
+fn quarantine_ends_only_at_a_valid_live_boundary_without_resetting_history() {
+ for method in ["session/prompt", "session/new", "session/resume"] {
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(TURN) {
+ machine.push(entry);
+ }
+ let old = machine.messages().to_vec();
+ machine.push(request("session/load", json!(7)));
+ machine.push(frame(
+ "to_server",
+ json!({"id":7,"error":{"code":-32603,"message":"failed"}}),
+ ));
+ machine.push(event("acp_ready"));
+ machine.push(request("initialize", json!(0)));
+ machine.push(result(json!(0)));
+ if method == "session/prompt" {
+ // An invalid or foreign-session prompt does not release quarantine.
+ machine.push(request(method, json!(8)));
+ machine.push(frame(
+ "to_runtime",
+ json!({"id":8,"method":method,"params":{"sessionId":"other","prompt":[]}}),
+ ));
+ assert!(
+ machine
+ .push(update("agent_message_chunk", "still late"))
+ .is_empty()
+ );
+ machine.push(frame("to_runtime", json!({"id":8,"method":method,"params":{"sessionId":"s","prompt":[{"type":"text","text":"live prompt"}]}})));
+ } else {
+ machine.push(request(method, json!(8)));
+ assert!(
+ machine
+ .push(update("agent_message_chunk", "late before open response"))
+ .is_empty()
+ );
+ machine.push(frame("to_server", json!({"id":8,"result":false})));
+ assert!(
+ machine
+ .push(update(
+ "agent_message_chunk",
+ "late after malformed open response"
+ ))
+ .is_empty()
+ );
+ machine.push(request(method, json!(8)));
+ assert!(machine.push(result(json!(99))).is_empty());
+ let body = if method == "session/new" {
+ json!({"sessionId":"s"})
+ } else {
+ json!({})
+ };
+ machine.push(frame("to_server", json!({"id":8,"result":body})));
+ assert_eq!(machine.messages(), old);
+ }
+ assert!(
+ !machine
+ .push(update("agent_message_chunk", "live reply"))
+ .is_empty()
+ );
+ assert_eq!(&machine.messages()[..old.len()], &old);
+ }
+}
+
+#[test]
+fn load_optional_field_fallback_matches_generic_session_machine() {
+ // ACP's schema defaults malformed optional fields rather than rejecting
+ // the response. The fold must not be stricter than SessionMachine.
+ for body in [
+ json!({}),
+ json!({"configOptions":"invalid"}),
+ json!({"modes":false}),
+ ] {
+ assert!(
+ serde_json::from_value::<agent_client_protocol::schema::v1::LoadSessionResponse>(
+ body.clone()
+ )
+ .is_ok()
+ );
+ let mut machine = FoldMachineImpl::new();
+ machine.push(request("session/load", json!(7)));
+ machine.push(update("agent_message_chunk", "replayed"));
+ assert!(matches!(
+ machine.push(frame("to_server", json!({"id":7,"result":body})))[0],
+ FoldEvent::MessagesReplaced(_)
+ ));
+ }
+}
+
+#[test]
+fn failed_hydration_preserves_full_history_until_empty_load() {
+ let mut log = parse_log(TURN);
+ let expected = fold(log.clone());
+ assert!(!expected.is_empty());
+ log.push(event("disconnected"));
+ log.push(request("initialize", json!(0)));
+ log.push(result(json!(0)));
+ log.extend([
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/load", json!(1)),
+ update("user_message_chunk", "partial hydration"),
+ update("agent_message_chunk", "must not appear"),
+ frame(
+ "to_server",
+ json!({"id":1,"error":{"code":-32603,"message":"history unavailable"}}),
+ ),
+ ]);
+ assert_eq!(fold(log.clone()), expected);
+ // No provider identity or proprietary marker is needed, even for an empty replay.
+ log.extend([
+ request("initialize", json!(0)),
+ result(json!(0)),
+ request("session/load", json!(1)),
+ result(json!(1)),
+ ]);
+ let mut machine = FoldMachineImpl::new();
+ let mut visible = vec![];
+ let mut replacements = 0;
+ for (index, entry) in log.iter().enumerate() {
+ for event in machine.push(entry.clone()) {
+ replacements += usize::from(matches!(event, FoldEvent::MessagesReplaced(_)));
+ apply(&mut visible, event.into_owned());
+ }
+ assert_eq!(visible, fold(log[..=index].iter().cloned()));
+ }
+ assert_eq!(replacements, 1);
+ assert!(visible.is_empty());
+}
+
+#[test]
+fn generic_terminal_facts_restore_stops_without_changing_load_success_semantics() {
+ use crate::domain::model::StopReason;
+ for (outcome, expected) in [
+ (json!({"kind":"finished"}), StopReason::EndTurn),
+ (json!({"kind":"cancelled"}), StopReason::Cancelled),
+ (
+ json!({"kind":"failed","message":"provider failed"}),
+ StopReason::Failed {
+ message: "provider failed".into(),
+ },
+ ),
+ ] {
+ let mut log = vec![
+ request("session/load", json!(1)),
+ update("user_message_chunk", "question"),
+ update("agent_message_chunk", "answer"),
+ ];
+ log.push(frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":outcome}}),
+ ));
+ log.push(result(json!(1)));
+ let mut machine = FoldMachineImpl::new();
+ let mut visible = Vec::new();
+ for (i, entry) in log.iter().enumerate() {
+ for event in machine.push(entry.clone()) {
+ apply(&mut visible, event.into_owned());
+ }
+ assert_eq!(visible, fold(log[..=i].iter().cloned()));
+ }
+ assert_eq!(visible[1].stop, Some(expected));
+ // A subsequent ordinary successful empty load still clears history.
+ log.extend([request("session/load", json!(2)), result(json!(2))]);
+ assert!(fold(log).is_empty());
+ }
+}
+
+#[test]
+fn absent_terminal_fact_retains_partial_tail_for_continuation_and_failed_load_discards_facts() {
+ let mut log = vec![
+ request("session/load", json!(1)),
+ update("user_message_chunk", "question"),
+ update("agent_message_chunk", "hel"),
+ result(json!(1)),
+ ];
+ assert_eq!(fold(log.clone())[1].stop, None);
+ log.push(update("agent_message_chunk", "lo"));
+ let complete = frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}),
+ );
+ log.push(complete.clone());
+ let finished = fold(log.clone());
+ assert_eq!(finished.len(), 2);
+ assert_eq!(
+ finished[1].parts.first(),
+ Some(&MessagePart::Text {
+ text: "hello".into()
+ })
+ );
+ assert_eq!(
+ finished[1].stop,
+ Some(crate::domain::model::StopReason::EndTurn)
+ );
+ log.extend([
+ request("session/load", json!(2)),
+ update("user_message_chunk", "wrong"),
+ update("agent_message_chunk", "wrong"),
+ complete,
+ frame(
+ "to_server",
+ json!({"id":2,"error":{"code":-32603,"message":"failed"}}),
+ ),
+ ]);
+ assert_eq!(fold(log), finished);
+}
+
+#[test]
+fn recovered_user_boundaries_open_new_turns_and_never_echo_a_correlated_prompt() {
+ let mut log = vec![
+ request("session/load", json!(1)),
+ update("user_message_chunk", "older"),
+ update("agent_message_chunk", "answer"),
+ result(json!(1)),
+ frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}),
+ ),
+ update("user_message_chunk", "newer"),
+ update("agent_message_chunk", "next answer"),
+ frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}),
+ ),
+ ];
+ let recovered = fold(log.clone());
+ assert_eq!(recovered.len(), 4);
+ assert_eq!(recovered[0].id, recovered[1].id);
+ assert_eq!(recovered[2].id, recovered[3].id);
+ assert_ne!(recovered[0].id, recovered[2].id);
+ log.push(frame("to_runtime", json!({"id":9,"method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"local"}]}})));
+ log.push(update("user_message_chunk", "local"));
+ log.push(update("agent_message_chunk", "live answer"));
+ log.push(frame("to_server", json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}})));
+ let pending = fold(log.clone());
+ assert_eq!(pending.len(), 6);
+ assert!(
+ pending[5].stop.is_none(),
+ "a lifecycle fact cannot complete a correlated pending prompt"
+ );
+ log.push(frame(
+ "to_server",
+ json!({"id":9,"result":{"stopReason":"end_turn"}}),
+ ));
+ assert_eq!(
+ fold(log)[5].stop,
+ Some(crate::domain::model::StopReason::EndTurn)
+ );
+}
+
+#[test]
+fn initialization_during_load_is_staged_until_commit() {
+ use crate::domain::model::Harness;
+
+ let mut machine = FoldMachineImpl::new();
+ machine.push(request("initialize", json!(0)));
+ machine.push(request("session/load", json!(1)));
+ assert!(machine.push(frame(
+ "to_server",
+ json!({"id":0,"result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"cursor","version":"1"}}}),
+ )).is_empty());
+ assert_eq!(machine.metadata().harness, Harness::Unknown);
+ let events = machine.push(result(json!(1)));
+ assert!(matches!(&events[0], FoldEvent::MessagesReplaced(_)));
+ assert!(
+ matches!(&events[1], FoldEvent::MetadataUpdated(metadata) if metadata.harness == Harness::Cursor)
+ );
+ assert_eq!(machine.metadata().harness, Harness::Cursor);
+}
+
+#[test]
+fn load_keeps_live_status_and_ready_aborts_replacement() {
+ for status in ["custom_status", "acp_ready"] {
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(TURN) {
+ machine.push(entry);
+ }
+ let old = machine.messages().to_vec();
+ machine.push(event("before_load"));
+ machine.push(request("session/load", json!(1)));
+ machine.push(update("agent_message_chunk", "replacement"));
+ assert!(
+ matches!(&machine.push(event(status))[0], FoldEvent::MetadataUpdated(metadata) if metadata.status.as_deref() == Some(status))
+ );
+ assert_eq!(machine.messages(), old);
+ let events = machine.push(result(json!(1)));
+ if status == "acp_ready" {
+ assert!(events.is_empty());
+ assert!(
+ machine
+ .push(update("agent_message_chunk", "late"))
+ .is_empty()
+ );
+ assert_eq!(machine.messages(), old);
+ } else {
+ assert!(matches!(&events[0], FoldEvent::MessagesReplaced(_)));
+ assert_ne!(machine.messages(), old);
+ }
+ assert_eq!(machine.metadata().status.as_deref(), Some(status));
+ }
+}
+
+#[test]
+fn recovered_history_appears_only_through_a_later_standard_load() {
+ // A pending prompt's turn stays open while older provider history is
+ // recovered out of band; nothing changes until the client loads.
+ let mut log = vec![frame(
+ "to_runtime",
+ json!({"id":31,"method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"new question"}]}}),
+ )];
+ log.extend([
+ update("agent_message_chunk", "new answer"),
+ frame(
+ "to_server",
+ json!({"id":31,"result":{"stopReason":"end_turn"}}),
+ ),
+ ]);
+ let live = fold(log.clone());
+ assert_eq!(live.len(), 2);
+ log.extend([
+ request("session/load", json!(32)),
+ update("user_message_chunk", "old question"),
+ update("agent_message_chunk", "old answer"),
+ frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}),
+ ),
+ update("user_message_chunk", "new question"),
+ update("agent_message_chunk", "new answer"),
+ frame(
+ "to_server",
+ json!({"method":"_session/turn_complete","params":{"sessionId":"s","outcome":{"kind":"finished"}}}),
+ ),
+ ]);
+ assert_eq!(
+ fold(log.clone()),
+ live,
+ "history is hidden until the load succeeds"
+ );
+ log.push(result(json!(32)));
+ let mut machine = FoldMachineImpl::new();
+ let mut visible = Vec::new();
+ for (i, entry) in log.iter().enumerate() {
+ for event in machine.push(entry.clone()) {
+ apply(&mut visible, event.into_owned());
+ }
+ assert_eq!(visible, fold(log[..=i].iter().cloned()));
+ }
+ assert_eq!(visible.len(), 4);
+ assert_eq!(visible[0].id, visible[1].id);
+ assert_eq!(visible[2].id, visible[3].id);
+ assert_ne!(visible[0].id, visible[2].id);
+ assert_eq!(
+ visible[0].parts.first(),
+ Some(&MessagePart::Text {
+ text: "old question".into()
+ })
+ );
+ assert_eq!(
+ visible[2].parts.first(),
+ Some(&MessagePart::Text {
+ text: "new question".into()
+ })
+ );
+ assert_eq!(
+ visible[3].stop,
+ Some(crate::domain::model::StopReason::EndTurn)
+ );
+}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
index c3d9891af7..0733100ef7 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
@@ -4,6 +4,23 @@ expression: messages
input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
---
[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "the example at [@agent_session_recorder.rs](file:///Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs) has a path in the .target dir to configure against zed. update the command to install this bin and update the zed to use the installed version. this will work better\n<context ref=\"file:///Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs\">\n//! Record a live agent session as [`Message`]-per-line JSONL fixtures.\n//!\n//! An ACP client (e.g. Zed) spawns this example as its agent server and\n//! speaks ACP over stdio. Internally the process is both sides of an\n//! Agent Runtime Protocol connection over a loopback WebSocket:\n//!\n//! - the service side accepts the runtime connection, records every logical\n//! protocol message crossing the wire, and bridges the connection's ACP\n//! channel to stdio;\n//! - a Tokio task stands in for a container, connects its runtime to the\n//! service, announces `acp_ready`, and starts the official Claude Code ACP\n//! adapter (`@agentclientprotocol/claude-agent-acp`) with `npx`.\n//!\n//! Each run records its one connection to\n//! `~/.agent_runtime_sessions/<utc-timestamp>.jsonl`, one JSON object per\n//! line: a timestamp flattened together with this crate's own\n//! [`Message`] serialization, so each line parses straight back into\n//! [`Message`]:\n//!\n//! ```text\n//! {\"ts\": \"2026-08-03T14:22:07.123Z\", \"direction\": \"to_server\" | \"to_runtime\", \"content\": <envelope>}\n//! ```\n//!\n//! Prerequisites:\n//!\n//! - Node.js and `npx` must be installed;\n//! - Claude Code credentials: either a subscription login (`claude /login`)\n//! or `ANTHROPIC_API_KEY` in the environment. The API key takes precedence\n//! over the subscription login when both are present.\n//!\n//! Build the recorder, then point an ACP client at the binary:\n//!\n//! ```text\n//! cargo build -p agent_session --example agent_session_recorder\n//! ```\n//!\n//! Zed `settings.json` (use an absolute path - Zed does not expand `~`; the\n//! `env -u` strips a stray API key from the environment so the session uses\n//! the subscription login):\n//!\n//! ```text\n//! \"agent_servers\": {\n//! \"Recorded Claude\": {\n//! \"type\": \"custom\",\n//! \"command\": \"/bin/bash\",\n//! \"args\": [\n//! \"-c\",\n//! \"exec env -u ANTHROPIC_API_KEY <repo>/target/debug/examples/agent_session_recorder\"\n//! ]\n//! }\n//! }\n//! ```\n//!\n//! All diagnostics go to stderr: stdout carries the ACP stream.\n\nuse std::error::Error;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse agent_client_protocol::{AcpAgent, Agent, Client, ConnectTo, Stdio};\nuse agent_runtime_protocol::domain::channel::Channel;\nuse agent_runtime_protocol::domain::connection::{\n RuntimeConnection, ServerChannel, ServerConnection,\n};\nuse agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};\nuse agent_runtime_protocol::outbound::websocket::{ServerTransport, connect_runtime};\nuse agent_session::domain::model::Message;\nuse chrono::{DateTime, SecondsFormat, Utc};\nuse serde::Serialize;\nuse tokio::io::AsyncWriteExt;\nuse tokio::sync::mpsc;\n\n#[cfg(test)]\n#[path = \"agent_session_recorder/test.rs\"]\nmod test;\n\ntype AnyError = Box<dyn Error + Send + Sync>;\n\nconst CLAUDE_AGENT_ACP: &str = \"@agentclientprotocol/[email protected]\";\n\n#[tokio::main]\nasync fn main() -> Result<(), AnyError> {\n let path = recording_path(\n &std::env::home_dir().ok_or(\"cannot determine home directory\")?,\n Utc::now(),\n );\n let (sink, lines) = mpsc::unbounded_channel();\n let writer = tokio::spawn(run_writer(path.clone(), lines));\n\n let carrier: Arc<ServerTransport<ToRuntimeMessage, ToServerMessage>> =\n Arc::new(ServerTransport::new());\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:0\").await?;\n let address = listener.local_addr()?;\n let app = Arc::clone(&carrier).into_router();\n let websocket_handle = tokio::spawn(async move { axum::serve(listener, app).await });\n eprintln!(\"recorder: service listening on ws://{address}\");\n\n let mut container = tokio::spawn(run_container(format!(\"ws://{address}\")));\n let incoming = accept_runtime(&carrier, &mut container).await?;\n eprintln!(\n \"recorder: runtime connected, recording to {}\",\n path.display()\n );\n\n let (service, acp) = ServerConnection::connect(record_channel(incoming, sink), ());\n\n // Bridge the ACP client on stdio to this connection's agent. The client\n // drives the whole session; this future completes when it closes stdio.\n let bridge = ConnectTo::<Agent>::connect_to(Stdio::new(), acp);\n tokio::pin!(bridge);\n let result: Result<(), AnyError> = tokio::select! {\n result = &mut bridge => {\n container.abort();\n let _ = container.await;\n result.map_err(Into::into)\n }\n container_result = &mut container => Err(container_error(container_result)),\n };\n\n // Tear the connection down, then let the writer drain what was recorded.\n drop(service);\n websocket_handle.abort();\n match writer.await {\n Ok(Ok(())) => eprintln!(\"recorder: session saved to {}\", path.display()),\n Ok(Err(error)) => eprintln!(\"recorder: writing the recording failed: {error}\"),\n Err(error) => eprintln!(\"recorder: recording writer panicked: {error}\"),\n }\n result\n}\n\n/// Where a session started at `now` is recorded for the user whose home\n/// directory is `home`.\nfn recording_path(home: &Path, now: DateTime<Utc>) -> PathBuf {\n home.join(\".agent_runtime_sessions\")\n .join(format!(\"{}.jsonl\", now.format(\"%Y-%m-%dT%H-%M-%SZ\")))\n}\n\n/// Append recorded lines to the session file until every sink handle drops.\n///\n/// Flushes after every line so a session killed mid-run keeps its data.\nasync fn run_writer(\n path: PathBuf,\n mut lines: mpsc::UnboundedReceiver<String>,\n) -> std::io::Result<()> {\n if let Some(parent) = path.parent() {\n tokio::fs::create_dir_all(parent).await?;\n }\n let mut file = tokio::fs::File::create(&path).await?;\n while let Some(line) = lines.recv().await {\n file.write_all(line.as_bytes()).await?;\n file.write_all(b\"\\n\").await?;\n file.flush().await?;\n }\n file.flush().await\n}\n\n/// Interpose a recording tap on the service side of a logical connection.\n///\n/// Every message crossing the channel is appended to `sink` as one JSONL\n/// line before being forwarded unchanged. Recording is best-effort: a\n/// message that fails to serialize is reported on stderr and forwarded\n/// anyway, and a closed sink never tears down the session.\nfn record_channel(inner: ServerChannel, sink: mpsc::UnboundedSender<String>) -> ServerChannel {\n let (outer, bridge) = Channel::duplex();\n let Channel {\n tx: inner_tx,\n rx: mut inner_rx,\n } = inner;\n let Channel {\n tx: bridge_tx,\n rx: mut bridge_rx,\n }: Channel<ToServerMessage, ToRuntimeMessage> = bridge;\n\n let to_runtime_sink = sink.clone();\n tokio::spawn(async move {\n while let Some(message) = bridge_rx.recv().await {\n record(&to_runtime_sink, &Message::ToRuntime(message.clone()));\n if inner_tx.send(message).is_err() {\n break;\n }\n }\n });\n tokio::spawn(async move {\n while let Some(message) = inner_rx.recv().await {\n record(&sink, &Message::ToServer(message.clone()));\n if bridge_tx.send(message).is_err() {\n break;\n }\n }\n });\n\n outer\n}\n\n/// One recorded JSONL line: a timestamp flattened alongside [`Message`]'s\n/// own `direction`/`content` serialization.\n#[derive(Serialize)]\nstruct RecordedLine<'a> {\n ts: String,\n #[serde(flatten)]\n message: &'a Message,\n}\n\nfn record(sink: &mpsc::UnboundedSender<String>, message: &Message) {\n match record_line(message) {\n Ok(line) => {\n let _ = sink.send(line);\n }\n Err(error) => eprintln!(\"recorder: dropping unserializable message: {error}\"),\n }\n}\n\nfn record_line(message: &Message) -> serde_json::Result<String> {\n serde_json::to_string(&RecordedLine {\n ts: Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),\n message,\n })\n}\n\nasync fn accept_runtime(\n carrier: &ServerTransport<ToRuntimeMessage, ToServerMessage>,\n container: &mut tokio::task::JoinHandle<Result<(), AnyError>>,\n) -> Result<ServerChannel, AnyError> {\n tokio::select! {\n incoming = carrier.accept() => incoming\n .ok_or_else(|| \"container disconnected before connecting\".into()),\n result = &mut *container => Err(container_error(result)),\n }\n}\n\nfn container_error(result: Result<Result<(), AnyError>, tokio::task::JoinError>) -> AnyError {\n match result {\n Ok(Ok(())) => \"container exited unexpectedly\".into(),\n Ok(Err(error)) => error,\n Err(error) => Box::new(error),\n }\n}\n\nasync fn run_container(websocket_url: String) -> Result<(), AnyError> {\n let (stream, _response) = tokio_tungstenite::connect_async(websocket_url).await?;\n let channel = connect_runtime::<ToServerMessage, ToRuntimeMessage, _>(stream);\n let (runtime, acp) = RuntimeConnection::connect(channel);\n // Announce readiness over the wire like a real Agent Runtime would, so\n // the recording contains the acp_ready event that production logs carry.\n runtime.system_event(SystemEvent::AcpReady)?;\n\n let claude_code = AcpAgent::from_args([\"npx\", \"-y\", CLAUDE_AGENT_ACP])?;\n ConnectTo::<Client>::connect_to(claude_code, acp)\n .await\n .map_err(Into::into)\n}\n\n</context>",
+ },
+ ],
+ },
+ stop: None,
+ },
FoldedMessage {
id: TurnId(
0,
@@ -242,7 +259,26 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
},
Text {
- text: "Done. The recorder is now installed at `~/.cargo/bin/agent_session_recorder` and Zed points at it instead of the debug build in `target/`.\n\nThree changes:\n\n1. **Doc comment** in `crates/agent_session/examples/agent_session_recorder.rs` — the build command is now `cargo install --locked --path crates/agent_session --example agent_session_recorder`, and the sample Zed config uses `\"$HOME/.cargo/bin/agent_session_recorder\"` (bash expands `$HOME`, so no hardcoded repo path).\n2. **`~/.config/zed/settings.json`** — the \"Recorded Claude\" agent server now execs the installed binary via `$HOME/.cargo/bin` instead of `/Users/eric/Code/macro/target/debug/examples/...`.\n3. **Ran the install** — it succeeded and the binary is in place. One wrinkle worth knowing: plain `cargo install` failed because it ignores `Cargo.lock` and resolved an `aws-types` that needs rustc 1.94.1 (the repo pins 1.94.0). `--locked` fixes that, which is why it's in the documented command.\n\nAfter future changes to the recorder, re-run the install command to refresh the binary — Zed no longer picks up `cargo build` output automatically.Yes — in your user-level Zed settings at `~/.config/zed/settings.json` (the `agent_servers` block wasn't in the project's `.zed/settings.json`). The \"Recorded Claude\" entry's command changed from:\n\n```\nexec env -u ANTHROPIC_API_KEY /Users/eric/Code/macro/target/debug/examples/agent_session_recorder\n```\n\nto:\n\n```\nexec env -u ANTHROPIC_API_KEY \"$HOME/.cargo/bin/agent_session_recorder\"\n```\n\nEverything else in the file is untouched. You may need to restart the agent server in Zed (or reopen the panel) for it to pick up the new command.",
+ text: "Done. The recorder is now installed at `~/.cargo/bin/agent_session_recorder` and Zed points at it instead of the debug build in `target/`.\n\nThree changes:\n\n1. **Doc comment** in `crates/agent_session/examples/agent_session_recorder.rs` — the build command is now `cargo install --locked --path crates/agent_session --example agent_session_recorder`, and the sample Zed config uses `\"$HOME/.cargo/bin/agent_session_recorder\"` (bash expands `$HOME`, so no hardcoded repo path).\n2. **`~/.config/zed/settings.json`** — the \"Recorded Claude\" agent server now execs the installed binary via `$HOME/.cargo/bin` instead of `/Users/eric/Code/macro/target/debug/examples/...`.\n3. **Ran the install** — it succeeded and the binary is in place. One wrinkle worth knowing: plain `cargo install` failed because it ignores `Cargo.lock` and resolved an `aws-types` that needs rustc 1.94.1 (the repo pins 1.94.0). `--locked` fixes that, which is why it's in the documented command.\n\nAfter future changes to the recorder, re-run the install command to refresh the binary — Zed no longer picks up `cargo build` output automatically.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+ FoldedMessage {
+ id: TurnId(
+ 1,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "did u update my zed settings?",
},
],
},
@@ -252,6 +288,21 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: TurnId(
1,
),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "Yes — in your user-level Zed settings at `~/.config/zed/settings.json` (the `agent_servers` block wasn't in the project's `.zed/settings.json`). The \"Recorded Claude\" entry's command changed from:\n\n```\nexec env -u ANTHROPIC_API_KEY /Users/eric/Code/macro/target/debug/examples/agent_session_recorder\n```\n\nto:\n\n```\nexec env -u ANTHROPIC_API_KEY \"$HOME/.cargo/bin/agent_session_recorder\"\n```\n\nEverything else in the file is untouched. You may need to restart the agent server in Zed (or reopen the panel) for it to pick up the new command.",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 2,
+ ),
author: User {
user_id: Some(
@@ -273,7 +324,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
FoldedMessage {
id: TurnId(
- 1,
+ 2,
),
author: Agent,
request_id: None,
@@ -290,7 +341,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
FoldedMessage {
id: TurnId(
- 2,
+ 3,
),
author: User {
user_id: Some(
@@ -313,7 +364,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
FoldedMessage {
id: TurnId(
- 2,
+ 3,
),
author: Agent,
request_id: None,
@@ -380,7 +431,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
FoldedMessage {
id: TurnId(
- 3,
+ 4,
),
author: User {
user_id: Some(
@@ -403,7 +454,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
FoldedMessage {
id: TurnId(
- 3,
+ 4,
),
author: Agent,
request_id: None,
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
index 787942d4a5..2189be3504 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
@@ -4,6 +4,23 @@ expression: messages
input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
---
[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "We're going to start work on the [@/Users/eric/Code/macro/crates/agent_fold/](file:///Users/eric/Code/macro/crates/agent_fold/) crate. the idea here is that this crate \"folds\" [@/Users/eric/Code/macro/crates/agent_runtime_protocol/](file:///Users/eric/Code/macro/crates/agent_runtime_protocol/) messages into a message type we can render. we're going to render these messages as channel messages so the type we can render will be channel messages. I think there's lots of ways to write this, and I stubbed out a trait but this could change pretty significantly. \n\nTo kick us off I started recording my claude code sessions (including this one) in @~/.agent_session_recordings/. No need to read these yet but these will be super useful for testing / iterating.\n\nto start we should think about how we're going to extend the comms message types to support AI messages. lets find these models",
+ },
+ ],
+ },
+ stop: None,
+ },
FoldedMessage {
id: TurnId(
0,
@@ -454,6 +471,37 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
),
},
},
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+ FoldedMessage {
+ id: TurnId(
+ 1,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "[Request interrupted by user for tool use]you can pretty much forget / ignore the existing AI models. this is a parallel system. You can also ignore the storage (for now). We aren't going to store these messages as all. Instead we're going to derive them from the log of acp messages stored in the log table (defined in [@20260731223955_agent_session_log.up.sql](file:///Users/eric/Code/macro/crates/macro_db_client/migrations/20260731223955_agent_session_log.up.sql)). We are just going to live in make-believe / type land. we get to define our own message types that we'll figure out how to render on the frontned. We'll likely update the type of comms message to contain our new enum of ai message types, but we can hold off on that\n<context ref=\"file:///Users/eric/Code/macro/crates/macro_db_client/migrations/20260731223955_agent_session_log.up.sql\">\n-- One row per message exchanged on an agent session's logical protocol\n-- stream (see agent_runtime_protocol::domain::schema::v0 and\n-- agent_session::domain::model::{Message, AgentSessionLog}). direction +\n-- content together round-trip the Message enum (ToServer/ToRuntime); user_id\n-- is set only when the entry is ACP traffic that originated from a user.\nCREATE TABLE agent_session_log (\n id UUID PRIMARY KEY,\n agent_session_id UUID NOT NULL REFERENCES agent_session(id) ON DELETE CASCADE,\n user_id TEXT,\n direction TEXT NOT NULL CHECK (direction IN ('to_server', 'to_runtime')),\n content JSONB NOT NULL,\n created_at TIMESTAMPTZ NOT NULL DEFAULT now()\n);\n\n-- list_by_session reads a session's log in chronological order.\nCREATE INDEX agent_session_log_session_order\n ON agent_session_log (agent_session_id, created_at, id);\n\n</context>",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 1,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
Text {
text: "Right — pure derivation. Let me ground the design in what's actually in the log.",
},
@@ -568,7 +616,41 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
},
Text {
- text: "Now I have what I need. The recordings are the real spec here, and they surfaced four things that change the design:\n\n**1. Tool calls dominate.** 406 of ~450 ACP frames are `session/update`; within those, 175 `tool_call_update` vs 46 `tool_call` — ~4 patches per call. The fold is mostly a correlate-and-patch loop keyed on `toolCallId`, not a text accumulator.\n\n**2. `usage_update` is 81 frames of noise.** Nothing renderable. Drop, or aggregate once per turn.\n\n**3. The interesting data is in `_meta`, not in ACP.** ACP normalizes tools to a coarse `kind` (`execute`/`read`/`edit`). The actual tool name lives at `_meta.claudeCode.toolName` (`Bash`, `Write`, `Read`). Terminal output streams via `_meta.terminal_output` — **with raw ANSI escapes** — and the exit code via `_meta.terminal_exit`. None of that is standard ACP.\n\nSo a faithful fold **cannot be pure ACP**. It needs a harness-specific extension layer. I'd quarantine that explicitly rather than let `_meta` reads leak through the whole fold — one `ClaudeCodeMeta` extraction step, so a future harness slots in beside it instead of rewriting the core.\n\n**4. Frames arrive underspecified and get patched.** The `Write` tool call opens as `{\"rawInput\":{},\"status\":\"pending\",\"content\":[],\"locations\":[]}` — title is literally just `\"Write\"`. Everything useful arrives later. And `session/request_permission` is a request/response pair correlated by JSON-RPC **id**, not `toolCallId` — a pending permission is a renderable state that later resolves.\n\n## Proposed vocabulary\n\n```rust\n/// One renderable message. Derived, never stored.\npub struct AgentMessage {\n pub turn: TurnId, // prompt → stopReason\n pub parts: NonEmpty<AgentMessagePart>,\n}\n\npub enum AgentMessagePart {\n Text(Markdown),\n Thought(Markdown),\n ToolUse(ToolUse),\n Permission(PermissionPrompt), // pending | resolved(outcome)\n}\n\npub struct ToolUse {\n pub id: ToolUseId, // ACP toolCallId\n pub label: String, // _meta tool name, else title\n pub status: ToolStatus, // Pending | Running | Completed | Failed\n pub detail: ToolDetail,\n}\n\npub enum ToolDetail {\n Terminal { command: String, output: AnsiText, exit_code: Option<i32> },\n FileEdit { path: PathBuf, diff: Option<Diff> },\n FileRead { path: PathBuf },\n Other { kind: String, input: serde_json::Value },\n}\n```\n\n`AnsiText` as its own type because that decision has to land somewhere — strip at fold time or preserve and render client-side. I'd preserve; stripping is lossy and the frontend can decide.\n\n## Two consequences for what you stubbed\n\n**The fold is pure and infallible.** The log's `content` jsonb is already deserialized into `agent_session::domain::model::Message` by the repo (`crates/agent_session/src/domain/model.rs:60`), so the fold's input is typed on arrival. Unknown/irrelevant frames are skipped, not errored. That makes `domain/error.rs` dead — signature is just:\n\n```rust\nfn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Vec<AgentMessage>\n```\n\n**There's no port to define.** A pure fold does no I/O; the log source is already `agent_session`'s repo. So `agent_fold` wants to be a plain library with a free function and a `test.rs` replaying those three `.jsonl` files — not a hex crate with `domain/ports.rs`. Your trait stub is probably worth deleting rather than filling in.\n\nOne thing I'd want your call on before writing types: **granularity within a turn.** One `AgentMessage` per turn with parts in order (frontend collapses runs of `ToolUse` into an activity group) reads best as a channel message and is what I'd default to — but it means a turn is one big message that grows. The alternative is splitting a new message each time text follows tool activity, which gives a more conversational channel feel at the cost of a fuzzier boundary rule.Empirically answerable — let me check whether the log actually produces orphans.",
+ text: "Now I have what I need. The recordings are the real spec here, and they surfaced four things that change the design:\n\n**1. Tool calls dominate.** 406 of ~450 ACP frames are `session/update`; within those, 175 `tool_call_update` vs 46 `tool_call` — ~4 patches per call. The fold is mostly a correlate-and-patch loop keyed on `toolCallId`, not a text accumulator.\n\n**2. `usage_update` is 81 frames of noise.** Nothing renderable. Drop, or aggregate once per turn.\n\n**3. The interesting data is in `_meta`, not in ACP.** ACP normalizes tools to a coarse `kind` (`execute`/`read`/`edit`). The actual tool name lives at `_meta.claudeCode.toolName` (`Bash`, `Write`, `Read`). Terminal output streams via `_meta.terminal_output` — **with raw ANSI escapes** — and the exit code via `_meta.terminal_exit`. None of that is standard ACP.\n\nSo a faithful fold **cannot be pure ACP**. It needs a harness-specific extension layer. I'd quarantine that explicitly rather than let `_meta` reads leak through the whole fold — one `ClaudeCodeMeta` extraction step, so a future harness slots in beside it instead of rewriting the core.\n\n**4. Frames arrive underspecified and get patched.** The `Write` tool call opens as `{\"rawInput\":{},\"status\":\"pending\",\"content\":[],\"locations\":[]}` — title is literally just `\"Write\"`. Everything useful arrives later. And `session/request_permission` is a request/response pair correlated by JSON-RPC **id**, not `toolCallId` — a pending permission is a renderable state that later resolves.\n\n## Proposed vocabulary\n\n```rust\n/// One renderable message. Derived, never stored.\npub struct AgentMessage {\n pub turn: TurnId, // prompt → stopReason\n pub parts: NonEmpty<AgentMessagePart>,\n}\n\npub enum AgentMessagePart {\n Text(Markdown),\n Thought(Markdown),\n ToolUse(ToolUse),\n Permission(PermissionPrompt), // pending | resolved(outcome)\n}\n\npub struct ToolUse {\n pub id: ToolUseId, // ACP toolCallId\n pub label: String, // _meta tool name, else title\n pub status: ToolStatus, // Pending | Running | Completed | Failed\n pub detail: ToolDetail,\n}\n\npub enum ToolDetail {\n Terminal { command: String, output: AnsiText, exit_code: Option<i32> },\n FileEdit { path: PathBuf, diff: Option<Diff> },\n FileRead { path: PathBuf },\n Other { kind: String, input: serde_json::Value },\n}\n```\n\n`AnsiText` as its own type because that decision has to land somewhere — strip at fold time or preserve and render client-side. I'd preserve; stripping is lossy and the frontend can decide.\n\n## Two consequences for what you stubbed\n\n**The fold is pure and infallible.** The log's `content` jsonb is already deserialized into `agent_session::domain::model::Message` by the repo (`crates/agent_session/src/domain/model.rs:60`), so the fold's input is typed on arrival. Unknown/irrelevant frames are skipped, not errored. That makes `domain/error.rs` dead — signature is just:\n\n```rust\nfn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Vec<AgentMessage>\n```\n\n**There's no port to define.** A pure fold does no I/O; the log source is already `agent_session`'s repo. So `agent_fold` wants to be a plain library with a free function and a `test.rs` replaying those three `.jsonl` files — not a hex crate with `domain/ports.rs`. Your trait stub is probably worth deleting rather than filling in.\n\nOne thing I'd want your call on before writing types: **granularity within a turn.** One `AgentMessage` per turn with parts in order (frontend collapses runs of `ToolUse` into an activity group) reads best as a channel message and is what I'd default to — but it means a turn is one big message that grows. The alternative is splitting a new message each time text follows tool activity, which gives a more conversational channel feel at the cost of a fuzzier boundary rule.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+ FoldedMessage {
+ id: TurnId(
+ 2,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "yes this will definitely be a plain lib the error / failure I have in the fold method could happen if a folder matches on an event but is missing parts. I think this could happen, but maybe not (ie tool call but no response?\n)",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 2,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "Empirically answerable — let me check whether the log actually produces orphans.",
},
ToolUse {
id: ToolUseId(
@@ -734,7 +816,41 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
},
Text {
- text: "Checked the ordering hazard: log ids are `generate_uuid_v7()` (`crates/agent_session/src/outbound/postgres/mod.rs:247`) and the read is `ORDER BY created_at ASC, id ASC` (line 270). v7 is time-ordered, so the tie-break is chronological, and `created_at` comes from per-statement `now()` at microsecond resolution. Ordering is sound — frames can't reorder. Good, because the recordings pack up to 19 frames into a single millisecond.\n\nThat means your \"missing parts\" case is a small enumerable set, not chaos. Here's what the data says about each:\n\n**Tool call with no response — real, 2 of 46.** Both at lines 296–299 of a 299-line log: the live session. So this isn't corruption, it's the *in-flight* state. It also becomes permanent when a session dies (`SessionStatus::Disconnected` already exists at `agent_session/src/domain/model.rs:32`). Not an error — `ToolStatus::Pending` with no output is a thing you want to render, as a spinner or \"interrupted\".\n\n**Orphan patch (update before open) — 0 of 45.** Only reachable through `session/load` resume, where the log legitimately starts mid-stream. There's one `session/load` in the recordings.\n\n**Unpaired permission request — 0 of 1.** Same story: in-flight, not error.\n\n**Partial open frame — common, and this is the one that actually bites.** The `Write` call opens as `{\"rawInput\":{},\"title\":\"Write\",\"content\":[],\"locations\":[]}`. Every renderable field is absent and arrives later. If the type demands them at construction, this frame fails — and it's *normal traffic*.\n\n## So I'd argue against `Result` here\n\nBecause these messages are derived on every read, a fold error means **the channel renders blank**. Failing is the worst available outcome for a render path — a partially-known tool call is strictly better than nothing. Every case above is legitimately representable:\n\n```rust\nfn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Fold;\n\npub struct Fold {\n pub messages: Vec<AgentMessage>,\n pub anomalies: Vec<Anomaly>, // observability, not failure\n}\n\npub enum Anomaly {\n PatchBeforeOpen { tool_call: ToolUseId },\n UnknownSessionUpdate { kind: String },\n UnknownToolKind { kind: String },\n}\n```\n\nPush \"missing parts\" into the *type* — optionals inside `ToolUse`, so a call with nothing known still renders as a bare \"used a tool\" row — and surface the weirdness through `anomalies` instead of `Err`.\n\nThe payoff is in testing: your replay tests assert `anomalies.is_empty()` against the recorded fixtures, so protocol drift fails CI loudly, while production degrades gracefully instead of showing an empty channel. You get strictness where it's cheap and leniency where it's expensive.\n\nWant me to write the vocabulary into the crate now, with a `test.rs` that replays the three `.jsonl` files? I'd need your call on the turn-granularity question from before — one `AgentMessage` per turn is still my default.No `Result`, one explicit match. That kills the ports trait too. Let me check the one thing that decides the match's shape — how we get from a log row to typed ACP.",
+ text: "Checked the ordering hazard: log ids are `generate_uuid_v7()` (`crates/agent_session/src/outbound/postgres/mod.rs:247`) and the read is `ORDER BY created_at ASC, id ASC` (line 270). v7 is time-ordered, so the tie-break is chronological, and `created_at` comes from per-statement `now()` at microsecond resolution. Ordering is sound — frames can't reorder. Good, because the recordings pack up to 19 frames into a single millisecond.\n\nThat means your \"missing parts\" case is a small enumerable set, not chaos. Here's what the data says about each:\n\n**Tool call with no response — real, 2 of 46.** Both at lines 296–299 of a 299-line log: the live session. So this isn't corruption, it's the *in-flight* state. It also becomes permanent when a session dies (`SessionStatus::Disconnected` already exists at `agent_session/src/domain/model.rs:32`). Not an error — `ToolStatus::Pending` with no output is a thing you want to render, as a spinner or \"interrupted\".\n\n**Orphan patch (update before open) — 0 of 45.** Only reachable through `session/load` resume, where the log legitimately starts mid-stream. There's one `session/load` in the recordings.\n\n**Unpaired permission request — 0 of 1.** Same story: in-flight, not error.\n\n**Partial open frame — common, and this is the one that actually bites.** The `Write` call opens as `{\"rawInput\":{},\"title\":\"Write\",\"content\":[],\"locations\":[]}`. Every renderable field is absent and arrives later. If the type demands them at construction, this frame fails — and it's *normal traffic*.\n\n## So I'd argue against `Result` here\n\nBecause these messages are derived on every read, a fold error means **the channel renders blank**. Failing is the worst available outcome for a render path — a partially-known tool call is strictly better than nothing. Every case above is legitimately representable:\n\n```rust\nfn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Fold;\n\npub struct Fold {\n pub messages: Vec<AgentMessage>,\n pub anomalies: Vec<Anomaly>, // observability, not failure\n}\n\npub enum Anomaly {\n PatchBeforeOpen { tool_call: ToolUseId },\n UnknownSessionUpdate { kind: String },\n UnknownToolKind { kind: String },\n}\n```\n\nPush \"missing parts\" into the *type* — optionals inside `ToolUse`, so a call with nothing known still renders as a bare \"used a tool\" row — and surface the weirdness through `anomalies` instead of `Err`.\n\nThe payoff is in testing: your replay tests assert `anomalies.is_empty()` against the recorded fixtures, so protocol drift fails CI loudly, while production degrades gracefully instead of showing an empty channel. You get strictness where it's cheap and leniency where it's expensive.\n\nWant me to write the vocabulary into the crate now, with a `test.rs` that replays the three `.jsonl` files? I'd need your call on the turn-granularity question from before — one `AgentMessage` per turn is still my default.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+ FoldedMessage {
+ id: TurnId(
+ 3,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "ok no result. I also think that we should implement this as an explicity match statement rather than a registry with match checks this will let us be more explicit about how / where we match on ACP messages",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 3,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "No `Result`, one explicit match. That kills the ports trait too. Let me check the one thing that decides the match's shape — how we get from a log row to typed ACP.",
},
ToolUse {
id: ToolUseId(
@@ -1785,6 +1901,37 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
],
},
},
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+ FoldedMessage {
+ id: TurnId(
+ 4,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "this should still be a hex crate. we're going to pretend that our derived messages are stored in a db. we're going to have api's to query them as if they are",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 4,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
ToolUse {
id: ToolUseId(
"toolu_01KKDkPymKKwqZRd1qmfEHEk",
@@ -2571,7 +2718,41 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
},
Text {
- text: "Restructured into a hex crate with the pretend-DB made explicit. **Hexagonal boundary checked** (via the architecture skill): domain imports only other domain models (`agent_session::domain::model`), protocol schema, and `tracing` — no axum/sqlx/transport anywhere; the one adapter lives in `outbound/`. There's no authz or business policy in this crate yet — queries are scoped by `AgentSessionId`, and access control (who may read a session's messages) stays with whatever inbound surface eventually calls the repo, minting its receipt against the session's thread/channel.\n\n**The shape now:**\n\n```\nsrc/domain/\n message.rs FoldedMessage vocabulary + MessageId natural key (turn, AuthorKind)\n fold.rs the pure total fold — unchanged semantics, now eats AgentSessionLog directly\n meta.rs quarantined Claude-Code _meta readers\n ports.rs SessionLogStore (driven) · FoldedMessageRepo (driving)\n service.rs FoldedMessageService: folds on every read, warns anomalies\nsrc/outbound/\n memory.rs InMemoryLogStore — what make-believe runs on\n```\n\n**Key decisions in the restructure:**\n- **The duplication went away.** My `LogEntry`/`LogMessage` were `agent_session::domain::model::{AgentSessionLog, Message}` re-invented — the fold now consumes the real model, so the eventual Postgres adapter is `AgentSessionLogRepo::list_by_session` output passed straight through.\n- **`FoldedMessageRepo` is the fiction.** Repo-shaped API (`list_by_session`, `get(session, id)`), styled after the channels crate: RPITIT `+ Send`, `rootcause::Report`, `#[tracing::instrument(err, skip(self))]`. Callers can't tell nothing is stored; if messages ever materialize, only the implementation moves.\n- **Messages got a natural key.** No rows means no surrogate ids, but the fold's shape gives one for free: `(turn, author side)` — deterministic across re-derivation, so `get` and future streaming reconciliation have something stable to address.\n- **Anomalies stay out of the query API.** A DB read doesn't fail because one row is odd — the service `tracing::warn!`s them; tests still assert-empty via the bare fold.\n- **Deferred:** the real Postgres adapter (belongs at the composition root — a generic wrapper over `AgentSessionLogRepo` can't prove `Send` since that trait doesn't bound its futures) and the `inbound/` comms adapter, per your earlier hold-off.\n\n12 tests + doctest green (fold suite, new service suite covering session scoping / get-by-id / service≡fold equivalence, recordings replay), strict clippy (`-Dwarnings`) clean, and `fold_recording` now exercises the full hexagon: recording → `InMemoryLogStore` → service → rendered turns.Two clear changes. Let me check what I need for both.",
+ text: "Restructured into a hex crate with the pretend-DB made explicit. **Hexagonal boundary checked** (via the architecture skill): domain imports only other domain models (`agent_session::domain::model`), protocol schema, and `tracing` — no axum/sqlx/transport anywhere; the one adapter lives in `outbound/`. There's no authz or business policy in this crate yet — queries are scoped by `AgentSessionId`, and access control (who may read a session's messages) stays with whatever inbound surface eventually calls the repo, minting its receipt against the session's thread/channel.\n\n**The shape now:**\n\n```\nsrc/domain/\n message.rs FoldedMessage vocabulary + MessageId natural key (turn, AuthorKind)\n fold.rs the pure total fold — unchanged semantics, now eats AgentSessionLog directly\n meta.rs quarantined Claude-Code _meta readers\n ports.rs SessionLogStore (driven) · FoldedMessageRepo (driving)\n service.rs FoldedMessageService: folds on every read, warns anomalies\nsrc/outbound/\n memory.rs InMemoryLogStore — what make-believe runs on\n```\n\n**Key decisions in the restructure:**\n- **The duplication went away.** My `LogEntry`/`LogMessage` were `agent_session::domain::model::{AgentSessionLog, Message}` re-invented — the fold now consumes the real model, so the eventual Postgres adapter is `AgentSessionLogRepo::list_by_session` output passed straight through.\n- **`FoldedMessageRepo` is the fiction.** Repo-shaped API (`list_by_session`, `get(session, id)`), styled after the channels crate: RPITIT `+ Send`, `rootcause::Report`, `#[tracing::instrument(err, skip(self))]`. Callers can't tell nothing is stored; if messages ever materialize, only the implementation moves.\n- **Messages got a natural key.** No rows means no surrogate ids, but the fold's shape gives one for free: `(turn, author side)` — deterministic across re-derivation, so `get` and future streaming reconciliation have something stable to address.\n- **Anomalies stay out of the query API.** A DB read doesn't fail because one row is odd — the service `tracing::warn!`s them; tests still assert-empty via the bare fold.\n- **Deferred:** the real Postgres adapter (belongs at the composition root — a generic wrapper over `AgentSessionLogRepo` can't prove `Send` since that trait doesn't bound its futures) and the `inbound/` comms adapter, per your earlier hold-off.\n\n12 tests + doctest green (fold suite, new service suite covering session scoping / get-by-id / service≡fold equivalence, recordings replay), strict clippy (`-Dwarnings`) clean, and `fold_recording` now exercises the full hexagon: recording → `InMemoryLogStore` → service → rendered turns.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+ FoldedMessage {
+ id: TurnId(
+ 5,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "Better. Some changes\n1. we can do this in a beautiful / abstract way that doesn't inject / depend on comms messages at all in the domain. We can define the actual fold from `agent_runtime_protocol` to comms message in an inbound module\n2. the log store already exists in the agent_session crate. you can expand this crate as needed to support this crate",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 5,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "Two clear changes. Let me check what I need for both.",
},
ToolUse {
id: ToolUseId(
@@ -3455,7 +3636,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
FoldedMessage {
id: TurnId(
- 1,
+ 6,
),
author: User {
user_id: None,
diff --git a/crates/agent_fold/src/inbound/wasm.rs b/crates/agent_fold/src/inbound/wasm.rs
index 13fa024319..f7bd50413a 100644
--- a/crates/agent_fold/src/inbound/wasm.rs
+++ b/crates/agent_fold/src/inbound/wasm.rs
@@ -23,7 +23,8 @@
//! serialize 6500 whole messages to produce one. `extend` folds them all and
//! serializes the answer once.
-use crate::domain::fold::{FoldMachineImpl, fold};
+use crate::domain::fold::fold;
+use crate::domain::ingestion::{LogCursor, LogIngestion};
use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};
use crate::domain::model::{FoldedMessage as ModelFoldedMessage, SessionMetadata};
use crate::domain::ports::FoldMachine;
@@ -55,12 +56,13 @@ pub fn fold_session(session_id: &str, entries: JsValue) -> Result<JsValue, JsVal
/// One live session's fold, held open between frames.
///
/// The streaming counterpart to [`fold_session`], wrapping the same
-/// [`FoldMachineImpl`] the server folds with. A caller following a session
+/// [`crate::domain::fold::FoldMachineImpl`] the server folds with. A caller following a session
/// keeps one of these per session for as long as the session lasts: frames
-/// must arrive in log order, and the machine only ever grows.
+/// must arrive in log order. Successful loads replace its committed history.
///
-/// A client that opens a channel mid-session catches up with [`Self::extend`]
-/// and then follows with [`Self::push`] on the *same* machine. Refolding the
+/// A durable-log client catches up with [`Self::snapshot`] and follows with
+/// [`Self::push_rows`]. Raw recording consumers use [`Self::extend`] and
+/// [`Self::push`] without requiring row metadata. Refolding the
/// fetched log into a throwaway and then pushing live frames into a second
/// machine would derive the same messages twice from different halves of the
/// log; there is one machine per session precisely so that cannot happen.
@@ -69,11 +71,47 @@ pub struct FoldStream {
/// Half of the composite id every message this machine derives is keyed
/// by, and the reason the session id is taken once rather than per frame.
session: AgentSessionId,
- machine: FoldMachineImpl,
+ ingestion: LogIngestion,
}
#[wasm_bindgen]
impl FoldStream {
+ /// Replace this fold with a durable effective-history snapshot.
+ ///
+ /// # Errors
+ /// Returns a JS string if any durable row cannot be read.
+ pub fn snapshot(&mut self, entries: JsValue) -> Result<JsValue, JsValue> {
+ let entries: Vec<DurableEntry> = serde_wasm_bindgen::from_value(entries)
+ .map_err(|error| JsValue::from_str(&format!("log rows are not readable: {error}")))?;
+ self.ingestion.replace_snapshot(
+ entries
+ .into_iter()
+ .map(|entry| (entry.cursor, entry.frame.into_log(self.session)))
+ .collect(),
+ );
+ self.messages()
+ }
+
+ /// Ingest durable live rows in delivery order, including snapshot overlap.
+ ///
+ /// # Errors
+ /// Returns a JS string if any row cannot be read or events cannot be encoded.
+ pub fn push_rows(&mut self, entries: JsValue) -> Result<JsValue, JsValue> {
+ let entries: Vec<DurableEntry> = serde_wasm_bindgen::from_value(entries)
+ .map_err(|error| JsValue::from_str(&format!("log rows are not readable: {error}")))?;
+ let mut events = Vec::new();
+ for entry in entries {
+ events.extend(
+ self.ingestion
+ .push(entry.cursor, entry.frame.into_log(self.session))
+ .into_iter()
+ .map(|event| FoldedStreamEvent::new(self.session, event)),
+ );
+ }
+ encode(&events)
+ .map_err(|error| JsValue::from_str(&format!("fold events are not encodable: {error}")))
+ }
+
/// A machine for `session_id` that has folded nothing.
///
/// # Errors
@@ -83,7 +121,7 @@ impl FoldStream {
pub fn new(session_id: &str) -> Result<FoldStream, JsValue> {
Ok(Self {
session: parse_session(session_id)?,
- machine: FoldMachineImpl::new(),
+ ingestion: LogIngestion::default(),
})
}
@@ -96,13 +134,14 @@ impl FoldStream {
/// Returns a JS string when the entries are not log frames.
pub fn extend(&mut self, entries: JsValue) -> Result<JsValue, JsValue> {
for entry in parse_log(self.session, entries)? {
- let _ = self.machine.push(entry);
+ let _ = self.ingestion.machine.push(entry);
}
self.messages()
}
/// Fold one more frame, reporting the changes it implied as an array of
- /// `{kind: "new" | "update", message}` and `{kind: "metadata", metadata}`
+ /// `{kind: "new" | "update", message}`, `{kind: "replace", messages}`,
+ /// and `{kind: "metadata", metadata}`
/// events - empty for a frame that changes nothing, which is most of
/// them.
///
@@ -114,6 +153,7 @@ impl FoldStream {
.map_err(|error| JsValue::from_str(&format!("log entry is not readable: {error}")))?;
let events: Vec<FoldedStreamEvent> = self
+ .ingestion
.machine
.push(entry.into_log(self.session))
.into_iter()
@@ -132,7 +172,7 @@ impl FoldStream {
///
/// Returns a JS string describing what could not be encoded.
pub fn metadata(&self) -> Result<JsValue, JsValue> {
- let metadata: SessionMetadata = self.machine.metadata().clone().into();
+ let metadata: SessionMetadata = self.ingestion.machine.metadata().clone().into();
encode(&metadata).map_err(|error| {
JsValue::from_str(&format!("session metadata is not encodable: {error}"))
})
@@ -149,6 +189,7 @@ impl FoldStream {
/// Returns a JS string describing what could not be encoded.
pub fn messages(&self) -> Result<JsValue, JsValue> {
let messages: Vec<FoldedMessage> = self
+ .ingestion
.machine
.messages()
.iter()
@@ -217,6 +258,14 @@ struct LogEntry {
message: Message,
}
+#[derive(Deserialize)]
+struct DurableEntry {
+ #[serde(flatten)]
+ cursor: LogCursor,
+ #[serde(flatten)]
+ frame: LogEntry,
+}
+
impl LogEntry {
fn into_log(self, session: AgentSessionId) -> AgentSessionLog {
AgentSessionLog {
diff --git a/crates/agent_fold/src/inbound/wire.rs b/crates/agent_fold/src/inbound/wire.rs
index ba1fa3406c..c8beb9cbe3 100644
--- a/crates/agent_fold/src/inbound/wire.rs
+++ b/crates/agent_fold/src/inbound/wire.rs
@@ -73,6 +73,11 @@ pub enum FoldedStreamEvent {
/// The message as it now stands.
message: FoldedMessage,
},
+ /// Replace all messages for this session, including removal of old rows.
+ Replace {
+ /// The complete committed conversation.
+ messages: Vec<FoldedMessage>,
+ },
/// The session's metadata changed; here it is in full.
Metadata {
/// The metadata as it now stands.
@@ -91,6 +96,13 @@ impl FoldedStreamEvent {
FoldEvent::MessageUpdate(message) => Self::Update {
message: FoldedMessage::new(session, message.into_owned()),
},
+ FoldEvent::MessagesReplaced(messages) => Self::Replace {
+ messages: messages
+ .into_owned()
+ .into_iter()
+ .map(|message| FoldedMessage::new(session, message))
+ .collect(),
+ },
FoldEvent::MetadataUpdated(metadata) => Self::Metadata {
metadata: metadata.into_owned(),
},
diff --git a/crates/agent_fold/src/inbound/wire/test.rs b/crates/agent_fold/src/inbound/wire/test.rs
index f3b410fec2..0e1f862732 100644
--- a/crates/agent_fold/src/inbound/wire/test.rs
+++ b/crates/agent_fold/src/inbound/wire/test.rs
@@ -93,3 +93,14 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
})
);
}
+
+#[test]
+fn empty_replacement_is_an_explicit_browser_event() {
+ let event = FoldEvent::MessagesReplaced(std::borrow::Cow::Owned(vec![])).into_owned();
+ assert!(event.message().is_none());
+ let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));
+ assert_eq!(
+ serde_json::to_value(FoldedStreamEvent::new(session, event)).unwrap(),
+ json!({"kind":"replace", "messages":[]})
+ );
+}
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 33041993d8..a6103a8da4 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -220,7 +220,9 @@ pub trait ContainerManager: Send + Sync + 'static {
fn spawn(
&self,
command: SpawnContainer,
- ) -> impl Future<Output = Result<Self::Transport>> + Send;
+ ) -> impl Future<
+ Output = Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>>,
+ > + Send;
/// How this manager applies a change from `from` to `to`.
///
@@ -245,7 +247,9 @@ pub trait ContainerManager: Send + Sync + 'static {
fn resume(
&self,
session: AgentSessionId,
- ) -> impl Future<Output = Result<Self::Transport>> + Send;
+ ) -> impl Future<
+ Output = Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>>,
+ > + Send;
/// The raw egress session token the session's container holds, if this
/// provider's containers hold one.
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index fcc4956cf3..7a022dfa43 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -64,7 +64,7 @@ async fn container_session_runs_and_logs_end_to_end() {
NoOpRealtime,
));
let containers = MockContainerManager::new();
- let container = containers
+ let attachment = containers
.spawn(SpawnContainer {
session_id: id,
kind: AgentKind::SandboxedCoder,
@@ -73,13 +73,11 @@ async fn container_session_runs_and_logs_end_to_end() {
})
.await
.unwrap();
+ let container = containers.container(id).unwrap();
let agent = container.agent();
let record = sessions.create_session(params(id)).await.unwrap();
- sessions
- .attach_session(id, RuntimeAttachment::solo(container.clone()))
- .await
- .unwrap();
+ sessions.attach_session(id, attachment).await.unwrap();
assert_eq!(record.id, id);
assert_eq!(containers.spawned(), 1);
assert!(agent.received_requests().is_empty());
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 502938c027..ad29c0f771 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -24,7 +24,6 @@ mod queue;
use std::sync::Arc;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
-use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::SessionManagement;
use agent_session::domain::model::{
diff --git a/crates/agent_harness/src/domain/service/deliver.rs b/crates/agent_harness/src/domain/service/deliver.rs
index d60e82a0c9..f556da63f9 100644
--- a/crates/agent_harness/src/domain/service/deliver.rs
+++ b/crates/agent_harness/src/domain/service/deliver.rs
@@ -58,10 +58,7 @@ where
.resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)
.await?;
self.sessions
- .attach_session(
- session_id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
+ .attach_session(session_id, container.mcp_servers(mcp_servers))
.await?;
} else {
// An external runtime is not ours to start - only its
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
index 0fb0818667..951914ddd9 100644
--- a/crates/agent_harness/src/domain/service/lifecycle.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -249,10 +249,7 @@ where
.resumed_mcp_servers(session_id, &session.owner_id, &session.mcp_servers)
.await?;
self.sessions
- .attach_session(
- session_id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
+ .attach_session(session_id, container.mcp_servers(mcp_servers))
.await?;
}
}
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index 36faffa7cf..4e6214276b 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -172,10 +172,7 @@ where
};
self.inner
.sessions
- .attach_session(
- session.id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
+ .attach_session(session.id, container.mcp_servers(mcp_servers))
.await?;
// Raw, through the session's own command worker: dispatch is where a
@@ -323,10 +320,7 @@ where
}
};
self.sessions
- .attach_session(
- session_id,
- RuntimeAttachment::solo(container).mcp_servers(mcp_servers),
- )
+ .attach_session(session_id, container.mcp_servers(mcp_servers))
.await?;
// The first prompt goes through the same door as every later one:
// queued raw, then dispatched - which is where it is composed with
diff --git a/crates/agent_harness/src/outbound/containers.rs b/crates/agent_harness/src/outbound/containers.rs
index ea55e80058..4c5598c8a1 100644
--- a/crates/agent_harness/src/outbound/containers.rs
+++ b/crates/agent_harness/src/outbound/containers.rs
@@ -52,10 +52,19 @@ impl HarnessContainers {
impl ContainerManager for HarnessContainers {
type Transport = HarnessContainer;
- async fn spawn(&self, command: SpawnContainer) -> Result<Self::Transport> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
match self {
- Self::Daytona(manager) => manager.spawn(command).await.map(HarnessContainer::Daytona),
- Self::Local(manager) => manager.spawn(command).await.map(HarnessContainer::Local),
+ Self::Daytona(manager) => manager
+ .spawn(command)
+ .await
+ .map(|attachment| attachment.map_transport(HarnessContainer::Daytona)),
+ Self::Local(manager) => manager
+ .spawn(command)
+ .await
+ .map(|attachment| attachment.map_transport(HarnessContainer::Local)),
}
}
@@ -73,10 +82,19 @@ impl ContainerManager for HarnessContainers {
}
}
- async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
match self {
- Self::Daytona(manager) => manager.resume(session).await.map(HarnessContainer::Daytona),
- Self::Local(manager) => manager.resume(session).await.map(HarnessContainer::Local),
+ Self::Daytona(manager) => manager
+ .resume(session)
+ .await
+ .map(|attachment| attachment.map_transport(HarnessContainer::Daytona)),
+ Self::Local(manager) => manager
+ .resume(session)
+ .await
+ .map(|attachment| attachment.map_transport(HarnessContainer::Local)),
}
}
diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rs
index 320b6bcb42..1317d49a27 100644
--- a/crates/agent_harness/src/outbound/cursor/manager.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager.rs
@@ -23,7 +23,7 @@ use std::path::Path;
use std::sync::Arc;
use agent_client_protocol::schema::v1::SessionId;
-use agent_session::domain::model::{AgentSession, AgentSessionId, ExternalSession};
+use agent_session::domain::model::{AgentSession, AgentSessionId, ExternalSession, ReplicaId};
use agent_session::domain::ports::{AgentSessionRepo, ExternalSessionRepo};
use cursor_cloud_agents::api::{ApiKey, CursorClient, CursorConfig};
use cursor_cloud_agents::domain::model::RepoUrl as CursorRepoUrl;
@@ -85,6 +85,10 @@ const CURSOR_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(
/// for reclaiming two idle tasks is nothing.
const CURSOR_IDLE_CHECK_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
+fn should_reap_cursor_pipe(idle: std::time::Duration, active_turn: bool) -> bool {
+ idle >= CURSOR_IDLE_TIMEOUT && !active_turn
+}
+
/// The ref new agents start their work from.
const DEFAULT_STARTING_REF: &str = "main";
@@ -122,6 +126,18 @@ pub struct CursorContainerManager<Sessions, Keys> {
base_url: String,
repo: CursorRepoUrl,
sessions: Sessions,
+ journal_storage: JournalStorage,
+}
+
+/// Hosted sessions always use durable storage; tests select memory explicitly.
+#[derive(Clone)]
+enum JournalStorage {
+ Postgres {
+ pool: sqlx::PgPool,
+ replica: ReplicaId,
+ },
+ #[cfg(test)]
+ Memory,
}
/// What a resumed session gets back at restore time.
@@ -136,6 +152,8 @@ struct RestoredCursorSession {
agent: Option<CursorAgentId>,
/// The model id the session last reported, from the projected column.
model_id: Option<String>,
+ /// The last Cursor run whose output reached Macro's session log.
+ last_run: Option<CursorRunId>,
}
impl<Sessions, Keys> CursorContainerManager<Sessions, Keys>
@@ -143,14 +161,37 @@ where
Sessions: AgentSessionRepo + ExternalSessionRepo + Clone,
Keys: CursorApiKeys,
{
- /// Build the manager over the key source, the API it talks to, and the
- /// repository every session works on.
- pub fn new(keys: Keys, base_url: String, repo: CursorRepoUrl, sessions: Sessions) -> Self {
+ /// Build a manager with required durable journal storage and replica identity.
+ pub fn new(
+ keys: Keys,
+ base_url: String,
+ repo: CursorRepoUrl,
+ sessions: Sessions,
+ pool: sqlx::PgPool,
+ replica: ReplicaId,
+ ) -> Self {
+ Self {
+ keys,
+ base_url,
+ repo,
+ sessions,
+ journal_storage: JournalStorage::Postgres { pool, replica },
+ }
+ }
+
+ #[cfg(test)]
+ fn with_memory_journal(
+ keys: Keys,
+ base_url: String,
+ repo: CursorRepoUrl,
+ sessions: Sessions,
+ ) -> Self {
Self {
keys,
base_url,
repo,
sessions,
+ journal_storage: JournalStorage::Memory,
}
}
@@ -185,13 +226,44 @@ where
///
/// `restore` carries what a resumed session gets back; a fresh spawn
/// passes `None`.
- fn serve_session(
+ async fn serve_session(
&self,
client: CursorClient,
default_model_id: Option<String>,
session_id: AgentSessionId,
restore: Option<RestoredCursorSession>,
- ) -> PipeTransport {
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<PipeTransport>> {
+ let owner_binding: Option<agent_session::domain::connection::AttachmentActivation>;
+ let journal: Arc<dyn cursor_cloud_agents::domain::journal::CursorJournal> = match &self
+ .journal_storage
+ {
+ JournalStorage::Postgres { pool, replica } => {
+ let journal = Arc::new(
+ cursor_cloud_agents::outbound::postgres_journal::PgCursorJournal::new(
+ pool.clone(),
+ session_id,
+ *replica,
+ ),
+ );
+ let activated = journal.clone();
+ owner_binding = Some(Box::new(move |claim| {
+ activated
+ .activate(claim.session, claim.replica, claim.fence)
+ .map_err(|e| {
+ agent_runtime_protocol::domain::ports::TransportError::Client(
+ e.to_string(),
+ )
+ .into()
+ })
+ }));
+ journal
+ }
+ #[cfg(test)]
+ JournalStorage::Memory => {
+ owner_binding = None;
+ Arc::new(cursor_cloud_agents::outbound::memory_journal::MemoryJournal::default())
+ }
+ };
let (ours, theirs) = tokio::io::duplex(PIPE_CAPACITY);
let (agent_reader, agent_writer) = tokio::io::split(theirs);
let cursor = RecordingCursor {
@@ -199,20 +271,27 @@ where
session_id,
sessions: self.sessions.clone(),
};
- let notifier = AcpNotifier::new();
+ let (reload_tx, reload_rx) = tokio::sync::mpsc::unbounded_channel();
+ let notifier = AcpNotifier::new().with_reload(reload_tx);
// The user's chosen model seeds the session as its default: a fresh
// session starts on it, and a resumed one still prefers whatever it
// was actually last using (carried in `restore.model_id`) over this.
let service = Arc::new(
- CursorSessionService::new(cursor, notifier.clone(), FixedRepo(self.repo.clone()))
- .with_default_model(default_model_id),
+ CursorSessionService::new(
+ cursor,
+ notifier.clone(),
+ FixedRepo(self.repo.clone()),
+ journal,
+ )
+ .with_default_model(default_model_id),
);
if let Some(restored) = restore {
- service.restore_session(
+ service.restore_session_with_watermark(
restored.acp_session,
restored.agent,
Some(self.repo.clone()),
restored.model_id,
+ restored.last_run,
);
}
let pipe_closed = tokio_util::sync::CancellationToken::new();
@@ -241,11 +320,19 @@ where
tokio::select! {
() = pipe_closed.cancelled() => break,
_ = reaper.tick() => {
- let idle = last_activity
+ let observed_at = *last_activity
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let active_turn = sync_service.has_active_turn();
+ let activity = last_activity
.lock()
- .expect("activity clock poisoned")
- .elapsed();
- if idle >= CURSOR_IDLE_TIMEOUT {
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ // Recheck under the activity lock after inspecting the
+ // turn gate. A prompt frame arriving in that window
+ // changes the instant and prevents a stale idle reap.
+ if *activity == observed_at
+ && should_reap_cursor_pipe(activity.elapsed(), active_turn)
+ {
tracing::info!(%session_id, "idle cursor session; closing its pipe");
reaper_shutdown.cancel();
break;
@@ -255,13 +342,22 @@ where
}
}
});
- PipeTransport::connect_observed(
+ let transport = PipeTransport::connect_recoverable(
ours,
move || {
- *observed.lock().expect("activity clock poisoned") = tokio::time::Instant::now();
+ *observed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) =
+ tokio::time::Instant::now();
},
shutdown,
- )
+ Some(reload_rx),
+ );
+ let mut attachment = agent_session::domain::connection::RuntimeAttachment::solo(transport);
+ if let Some(binding) = owner_binding {
+ attachment = attachment.on_activate(binding);
+ }
+ Ok(attachment)
}
}
@@ -272,7 +368,10 @@ where
{
type Transport = PipeTransport;
- async fn spawn(&self, command: SpawnContainer) -> Result<PipeTransport> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<PipeTransport>> {
// The session row is read for its owner alone: spawning is the first
// moment we can tell whether the person who mentioned @cursor has
// connected an account, and refusing here is what turns "the bot
@@ -283,10 +382,14 @@ where
// itself. The harness's session actor names them in `session/new`,
// and the in-process adapter forwards them to Cursor's API - the same
// rail every other transport uses.
- Ok(self.serve_session(client, default_model_id, command.session_id, None))
+ self.serve_session(client, default_model_id, command.session_id, None)
+ .await
}
- async fn resume(&self, session: AgentSessionId) -> Result<PipeTransport> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<PipeTransport>> {
// The identity lives in Postgres in two halves that appear at
// different moments: the ACP session id lands when `session/new`
// answers, the Cursor agent only when the first prompt mints it. A
@@ -299,9 +402,10 @@ where
let (client, default_model_id) = self.client_for(&stored).await?;
let restore = match &stored.acp_session_id {
Some(acp) => {
- let agent = ExternalSessionRepo::get(&self.sessions, session)
- .await?
- .map(|external| CursorAgentId::new(external.external_id));
+ let external = ExternalSessionRepo::get(&self.sessions, session).await?;
+ let agent = external
+ .as_ref()
+ .map(|external| CursorAgentId::new(external.external_id.clone()));
Some(RestoredCursorSession {
acp_session: acp.clone(),
agent,
@@ -311,6 +415,9 @@ where
// harness seeded it with, which the wrapper resolves to
// "no opinion" rather than trusting.
model_id: Some(stored.model.clone()),
+ last_run: external
+ .and_then(|external| external.last_run_id)
+ .map(CursorRunId::new),
})
}
None => None,
@@ -322,7 +429,8 @@ where
// died with the process (only its hash is persisted). The one session
// this loses servers for is one restored before its first prompt ever
// landed, which then creates its agent bare rather than not at all.
- Ok(self.serve_session(client, default_model_id, session, restore))
+ self.serve_session(client, default_model_id, session, restore)
+ .await
}
/// A Cursor session has no container of ours to hold a token: the raw
@@ -397,6 +505,14 @@ impl<Sessions> CursorAgents for RecordingCursor<Sessions>
where
Sessions: ExternalSessionRepo + Clone,
{
+ async fn raw_result(
+ &self,
+ agent: &CursorAgentId,
+ run: &CursorRunId,
+ ) -> std::result::Result<String, rootcause::Report> {
+ self.client.raw_result(agent, run).await
+ }
+
#[tracing::instrument(skip_all, err, fields(
session = %self.session_id,
mcp_servers = mcp_servers.len(),
@@ -428,6 +544,7 @@ where
external_id: agent.to_string(),
external_name: summary.as_ref().map(|summary| summary.name.clone()),
external_url: summary.map(|summary| summary.url),
+ last_run_id: None,
},
)
.await
@@ -456,21 +573,13 @@ where
self.client.cancel_run(agent, run).await
}
- async fn run_result(
- &self,
- agent: &CursorAgentId,
- run: &CursorRunId,
- ) -> std::result::Result<cursor_cloud_agents::domain::model::RunOutcome, rootcause::Report>
- {
- self.client.run_result(agent, run).await
- }
-
async fn list_runs(
&self,
agent: &CursorAgentId,
+ through: Option<&CursorRunId>,
) -> std::result::Result<Vec<cursor_cloud_agents::domain::model::RunListing>, rootcause::Report>
{
- self.client.list_runs(agent).await
+ self.client.list_runs(agent, through).await
}
}
@@ -478,19 +587,19 @@ impl<Sessions> RunStream for RecordingCursor<Sessions>
where
Sessions: ExternalSessionRepo + Clone,
{
- async fn stream(
+ async fn raw_stream(
&self,
agent: &CursorAgentId,
run: &CursorRunId,
) -> std::result::Result<
impl Stream<
Item = std::result::Result<
- cursor_cloud_agents::domain::event::CursorEvent,
+ cursor_cloud_agents::domain::journal::NativeRecord,
rootcause::Report,
>,
> + Send,
rootcause::Report,
> {
- self.client.stream(agent, run).await
+ self.client.raw_stream(agent, run).await
}
}
diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rs
index 547d4b9bfa..2a19c6cb21 100644
--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs
+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs
@@ -4,7 +4,9 @@ use crate::domain::model::AgentKind;
use crate::testing::helpers::egress::test_egress;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::ports::{Transport as _, TransportSender as _};
-use agent_runtime_protocol::domain::schema::v0::{AcpMessage, ToRuntimeMessage, ToServerMessage};
+use agent_runtime_protocol::domain::schema::v0::{
+ AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
+};
use agent_session::domain::error::Result as SessionResult;
use agent_session::domain::model::{
AgentSession, ChannelSession, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME,
@@ -14,6 +16,7 @@ use bot_id::BotId;
use cursor_api_key::cipher::CursorApiKey;
use macro_user_id::user_id::MacroUserIdStr;
use std::collections::HashMap;
+use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
use std::sync::{Arc, Mutex};
/// In-memory sessions double: a real map for the external rows, a canned row
@@ -212,6 +215,38 @@ async fn fake_cursor_api() -> (
}))
}),
)
+ .route("/v1/agents/{id}/runs", {
+ // `bc-idle` grows a foreign run after the listing `session/load`
+ // hydrates from; `bc-busy` grows one only once a follow-up run is
+ // created, so its discovery is the prompt's own backfill and not a
+ // mirror tick racing it.
+ let listings = Arc::new(AtomicUsize::new(0));
+ let follow_ups = Arc::new(AtomicUsize::new(0));
+ axum::routing::get({
+ let (listings, follow_ups) = (listings.clone(), follow_ups.clone());
+ move |axum::extract::Path(id): axum::extract::Path<String>| {
+ let first_listing = listings.fetch_add(1, SeqCst) == 0;
+ let prompted = follow_ups.load(SeqCst) > 0;
+ let runs = match id.as_str() {
+ "bc-restored" => vec!["run-delivered"],
+ "bc-idle" if first_listing => vec!["run-delivered"],
+ "bc-idle" => vec!["run-foreign", "run-delivered"],
+ "bc-busy" if prompted => vec!["run-test-2", "run-foreign", "run-delivered"],
+ "bc-busy" => vec!["run-delivered"],
+ _ => Vec::new(),
+ };
+ let items: Vec<_> = runs
+ .into_iter()
+ .map(|run| serde_json::json!({"id": run, "status": "FINISHED"}))
+ .collect();
+ async move { axum::Json(serde_json::json!({"items": items})) }
+ }
+ })
+ .post(move || {
+ follow_ups.fetch_add(1, SeqCst);
+ async { axum::Json(serde_json::json!({"id":"run-test-2"})) }
+ })
+ })
.route(
"/v1/agents/{id}/archive",
axum::routing::post(move |axum::extract::Path(id): axum::extract::Path<String>| {
@@ -257,6 +292,8 @@ async fn fake_cursor_api() -> (
"event: status\n",
"data: {\"runId\":\"run-test-1\",\"status\":\"RUNNING\"}\n",
"\n",
+ "event: interaction_update\n",
+ "data: {\"type\":\"user-message-appended\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"original\"}]}}\n\n",
"event: assistant\n",
"data: {\"text\":\"done\"}\n",
"\n",
@@ -340,7 +377,7 @@ fn manager_with_keys(
keys: StubKeys,
) -> CursorContainerManager<StubSessions, StubKeys> {
let repo = CursorRepoUrl::parse("https://github.com/macro-inc/macro").expect("valid repo");
- CursorContainerManager::new(keys, base_url, repo, sessions)
+ CursorContainerManager::with_memory_journal(keys, base_url, repo, sessions)
}
async fn next_acp(
@@ -384,7 +421,9 @@ async fn spawning_and_prompting_records_the_minted_agent() {
})
.await
.expect("spawn");
- let (sender, mut receiver) = transport.split();
+ let mut halves = None;
+ transport.map_transport(|pipe| halves = Some(pipe.split()));
+ let (sender, mut receiver) = halves.unwrap();
send_acp(
&sender,
@@ -462,7 +501,9 @@ async fn spawn_uses_the_owners_default_model() {
})
.await
.expect("spawn");
- let (sender, mut receiver) = transport.split();
+ let mut halves = None;
+ transport.map_transport(|pipe| halves = Some(pipe.split()));
+ let (sender, mut receiver) = halves.unwrap();
send_acp(
&sender,
@@ -522,7 +563,9 @@ async fn session_new_mcp_servers_reach_the_created_agent() {
})
.await
.expect("spawn");
- let (sender, mut receiver) = transport.split();
+ let mut halves = None;
+ transport.map_transport(|pipe| halves = Some(pipe.split()));
+ let (sender, mut receiver) = halves.unwrap();
send_acp(
&sender,
@@ -595,41 +638,8 @@ async fn session_new_mcp_servers_reach_the_created_agent() {
#[tokio::test]
async fn resume_restores_the_persisted_identity() {
let (base_url, _, _) = fake_cursor_api().await;
- let sessions = StubSessions::default();
- let session_id = AgentSessionId::new();
- ExternalSessionRepo::upsert(
- &sessions,
- session_id,
- ExternalSession {
- provider: CURSOR_PROVIDER.to_owned(),
- external_id: "bc-restored".to_owned(),
- external_name: None,
- external_url: None,
- },
- )
- .await
- .expect("seed row");
- *sessions.acp_session_id.lock().expect("stub poisoned") = Some("cursor-acp-1".to_owned());
- let manager = manager(base_url, sessions.clone());
-
- let transport = manager.resume(session_id).await.expect("resume");
- let (sender, mut receiver) = transport.split();
-
- send_acp(
- &sender,
- serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}),
- )
- .await;
- next_acp(&mut receiver).await;
- send_acp(
- &sender,
- serde_json::json!({"jsonrpc":"2.0","id":2,"method":"session/load","params":{
- "sessionId":"cursor-acp-1","cwd":"/workspace","mcpServers":[]}}),
- )
- .await;
- let loaded = next_acp(&mut receiver).await;
- assert_eq!(loaded["id"], 2);
- assert!(loaded.get("error").is_none(), "got {loaded}");
+ let (_, _, history) = resume_delivered_session(base_url, "bc-restored").await;
+ assert_eq!(count(&history, "/method", "_session/turn_complete"), 1);
}
/// A session that died between `session/new` and its first prompt has an
@@ -644,7 +654,9 @@ async fn resume_answers_session_load_even_before_an_agent_was_minted() {
let manager = manager(base_url, sessions.clone());
let transport = manager.resume(session_id).await.expect("resume");
- let (sender, mut receiver) = transport.split();
+ let mut halves = None;
+ transport.map_transport(|pipe| halves = Some(pipe.split()));
+ let (sender, mut receiver) = halves.unwrap();
send_acp(
&sender,
@@ -705,7 +717,9 @@ async fn an_idle_pipe_is_shut_down() {
})
.await
.expect("spawn");
- let (_sender, mut receiver) = transport.split();
+ let mut halves = None;
+ transport.map_transport(|pipe| halves = Some(pipe.split()));
+ let (_sender, mut receiver) = halves.unwrap();
// The ready marker arrives; then nothing ever does, and after the idle
// timeout (paused clock, so instantly) the stream ends instead of
@@ -717,6 +731,12 @@ async fn an_idle_pipe_is_shut_down() {
);
}
+#[test]
+fn a_pipe_is_not_idle_while_cursor_is_running_a_turn() {
+ assert!(!should_reap_cursor_pipe(CURSOR_IDLE_TIMEOUT, true));
+ assert!(should_reap_cursor_pipe(CURSOR_IDLE_TIMEOUT, false));
+}
+
/// Teardown archives the agent on cursor.com and forgets the mapping; a
/// session that never minted an agent tears down without any API call.
#[tokio::test]
@@ -738,6 +758,7 @@ async fn teardown_archives_and_forgets() {
external_id: "bc-doomed".to_owned(),
external_name: None,
external_url: None,
+ last_run_id: None,
},
)
.await
@@ -801,6 +822,7 @@ async fn teardown_forgets_the_session_even_when_the_key_is_gone() {
external_id: "bc-orphaned".to_owned(),
external_name: None,
external_url: None,
+ last_run_id: None,
},
)
.await
@@ -820,3 +842,253 @@ async fn teardown_forgets_the_session_even_when_the_key_is_gone() {
"the row is ours to forget even when the agent is not ours to archive"
);
}
+
+/// Every message up to and including the first one `stop` accepts, in arrival
+/// order: ACP frames as JSON, `ReloadRequired` as `"reload_required"`, other
+/// runtime events dropped. Recovery has no history replacement protocol, so a
+/// `_session/history*` frame anywhere fails the test.
+async fn collect_until(
+ receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
+ stop: impl Fn(&serde_json::Value) -> bool,
+) -> Vec<serde_json::Value> {
+ let mut seen = Vec::new();
+ loop {
+ let message = tokio::time::timeout(std::time::Duration::from_secs(30), receiver.recv())
+ .await
+ .expect("a message before the timeout")
+ .expect("the pipe stays open");
+ let value = match message {
+ ToServerMessage::Acp(AcpMessage(frame)) => {
+ serde_json::to_value(frame).expect("serializable")
+ }
+ ToServerMessage::Event {
+ event: SystemEvent::ReloadRequired,
+ } => serde_json::json!("reload_required"),
+ ToServerMessage::Event { .. } => continue,
+ other => panic!("unexpected runtime message {other:?}"),
+ };
+ assert!(
+ !value["method"]
+ .as_str()
+ .unwrap_or_default()
+ .starts_with("_session/history"),
+ "recovery must not push a history replacement, got {value}"
+ );
+ let done = stop(&value);
+ seen.push(value);
+ if done {
+ return seen;
+ }
+ }
+}
+
+/// Frames whose JSON `pointer` holds the string `value`.
+fn count(frames: &[serde_json::Value], pointer: &str, value: &str) -> usize {
+ frames
+ .iter()
+ .filter(|frame| frame.pointer(pointer).and_then(|found| found.as_str()) == Some(value))
+ .count()
+}
+
+/// The recovery handshake as the session actor performs it: `initialize`,
+/// then `session/load`. Returns the history replayed before the load's
+/// response after asserting the load succeeded and only history preceded it.
+async fn reload(
+ sender: &super::super::pipe::PipeSender,
+ receiver: &mut tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
+ first_id: u64,
+) -> Vec<serde_json::Value> {
+ send_acp(
+ sender,
+ serde_json::json!({"jsonrpc":"2.0","id":first_id,"method":"initialize","params":{"protocolVersion":1}}),
+ )
+ .await;
+ let initialized = collect_until(receiver, |message| message["id"] == first_id).await;
+ assert_eq!(
+ initialized.len(),
+ 1,
+ "nothing precedes initialize's answer: {initialized:?}"
+ );
+ let load_id = first_id + 1;
+ send_acp(
+ sender,
+ serde_json::json!({"jsonrpc":"2.0","id":load_id,"method":"session/load","params":{
+ "sessionId":"cursor-acp-1","cwd":"/workspace","mcpServers":[]}}),
+ )
+ .await;
+ let mut replayed = collect_until(receiver, |message| message["id"] == load_id).await;
+ let loaded = replayed.pop().expect("the load response");
+ assert!(
+ loaded.get("error").is_none(),
+ "load must succeed, got {loaded}"
+ );
+ for frame in &replayed {
+ assert!(
+ matches!(
+ frame["method"].as_str(),
+ Some("session/update" | "_session/turn_complete")
+ ),
+ "only history travels before a load's response, got {frame}"
+ );
+ }
+ replayed
+}
+
+/// Resume a session whose Cursor agent is `agent` with `run-delivered` already
+/// in Macro's log, then `initialize` + `session/load` it; the third element is
+/// what that first load replayed.
+async fn resume_delivered_session(
+ base_url: String,
+ agent: &str,
+) -> (
+ super::super::pipe::PipeSender,
+ tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>,
+ Vec<serde_json::Value>,
+) {
+ let sessions = StubSessions::default();
+ let session_id = AgentSessionId::new();
+ ExternalSessionRepo::upsert(
+ &sessions,
+ session_id,
+ ExternalSession {
+ provider: CURSOR_PROVIDER.to_owned(),
+ external_id: agent.to_owned(),
+ external_name: None,
+ external_url: None,
+ last_run_id: Some("run-delivered".to_owned()),
+ },
+ )
+ .await
+ .expect("seed row");
+ *sessions.acp_session_id.lock().expect("stub poisoned") = Some("cursor-acp-1".to_owned());
+ let transport = manager(base_url, sessions)
+ .resume(session_id)
+ .await
+ .expect("resume");
+ let mut halves = None;
+ transport.map_transport(|pipe| halves = Some(pipe.split()));
+ let (sender, mut receiver) = halves.unwrap();
+ let history = reload(&sender, &mut receiver, 1).await;
+ (sender, receiver, history)
+}
+
+/// A run driven from cursor.com while the Macro session sits idle: the mirror
+/// captures it silently and asks the host to reload. The host's standard
+/// `initialize` + `session/load` then shows both runs, a repeated load shows
+/// exactly the same, and the mirror asks for nothing more.
+#[tokio::test]
+async fn an_idle_foreign_run_is_recovered_through_a_client_load() {
+ let (base_url, _, _) = fake_cursor_api().await;
+ let (sender, mut receiver, before) = resume_delivered_session(base_url, "bc-idle").await;
+ assert_eq!(count(&before, "/method", "_session/turn_complete"), 1);
+
+ let idle = collect_until(&mut receiver, |message| message == "reload_required").await;
+ assert_eq!(
+ idle.len(),
+ 1,
+ "an idle mirror asks for a reload and publishes no frames: {idle:?}"
+ );
+
+ let recovered = reload(&sender, &mut receiver, 3).await;
+ assert_eq!(
+ count(&recovered, "/method", "_session/turn_complete"),
+ 2,
+ "both runs are history: {recovered:?}"
+ );
+ assert_eq!(
+ count(
+ &recovered,
+ "/params/update/sessionUpdate",
+ "user_message_chunk"
+ ),
+ 2
+ );
+ assert!(
+ recovered.len() > before.len(),
+ "history grows, it is not replaced"
+ );
+
+ let again = reload(&sender, &mut receiver, 5).await;
+ assert_eq!(
+ again, recovered,
+ "a repeated load replays the same history once"
+ );
+
+ // Two further mirror ticks pass without another reload: what was loaded
+ // is checkpointed, not rediscovered.
+ let quiet = tokio::time::timeout(std::time::Duration::from_millis(2500), receiver.recv()).await;
+ assert!(
+ quiet.is_err(),
+ "nothing more may arrive after recovery, got {quiet:?}"
+ );
+}
+
+/// A run driven from cursor.com discovered by a prompt's own backfill: the
+/// reload requirement reaches the host before the prompt's response, the live
+/// turn streams only its own frames, and the load that follows shows the
+/// delivered run, the foreign run and the prompt just answered.
+#[tokio::test]
+async fn a_foreign_run_found_by_a_prompt_is_recovered_after_its_response() {
+ let (base_url, _, _) = fake_cursor_api().await;
+ let (sender, mut receiver, before) = resume_delivered_session(base_url, "bc-busy").await;
+ assert_eq!(count(&before, "/method", "_session/turn_complete"), 1);
+
+ send_acp(
+ &sender,
+ serde_json::json!({"jsonrpc":"2.0","id":3,"method":"session/prompt","params":{
+ "sessionId": "cursor-acp-1",
+ "prompt": [{"type":"text","text":"follow up"}],
+ }}),
+ )
+ .await;
+ let turn = collect_until(&mut receiver, |message| message["id"] == 3).await;
+ let response = turn.last().expect("the prompt response");
+ assert_eq!(
+ response["result"]["stopReason"], "end_turn",
+ "got {response}"
+ );
+ let reload_at = turn
+ .iter()
+ .position(|message| message == "reload_required")
+ .expect("the prompt's backfill requires a reload");
+ assert!(
+ reload_at < turn.len() - 1,
+ "the requirement precedes the response"
+ );
+ assert_eq!(
+ count(&turn, "/params/update/sessionUpdate", "user_message_chunk"),
+ 0,
+ "neither the foreign run's prompt nor our own is echoed live: {turn:?}"
+ );
+ assert_eq!(
+ count(&turn, "/params/update/content/text", "done"),
+ 1,
+ "only the live run's text streams; the foreign run waits for load: {turn:?}"
+ );
+
+ let recovered = reload(&sender, &mut receiver, 4).await;
+ assert_eq!(
+ count(&recovered, "/method", "_session/turn_complete"),
+ 3,
+ "delivered, foreign, and ours: {recovered:?}"
+ );
+ assert_eq!(
+ count(
+ &recovered,
+ "/params/update/sessionUpdate",
+ "user_message_chunk"
+ ),
+ 3
+ );
+ assert_eq!(
+ count(&recovered, "/params/update/content/text", "follow up"),
+ 1,
+ "the prompt just answered is part of the loaded history: {recovered:?}"
+ );
+
+ let again = reload(&sender, &mut receiver, 6).await;
+ assert_eq!(
+ again, recovered,
+ "a repeated load replays the same history once"
+ );
+}
diff --git a/crates/agent_harness/src/outbound/cursor/pipe.rs b/crates/agent_harness/src/outbound/cursor/pipe.rs
index 1b341a1b9e..56bf2ed8fc 100644
--- a/crates/agent_harness/src/outbound/cursor/pipe.rs
+++ b/crates/agent_harness/src/outbound/cursor/pipe.rs
@@ -69,6 +69,21 @@ impl PipeTransport {
on_frame: Observer,
shutdown: CancellationToken,
) -> Self
+ where
+ Pipe: AsyncRead + AsyncWrite + Unpin + Send + 'static,
+ Observer: Fn() + Send + 'static,
+ {
+ Self::connect_recoverable(pipe, on_frame, shutdown, None)
+ }
+
+ /// Receive recovery requirements for this solo attachment's hosted session.
+ #[must_use]
+ pub(crate) fn connect_recoverable<Pipe, Observer>(
+ pipe: Pipe,
+ on_frame: Observer,
+ shutdown: CancellationToken,
+ reload: Option<mpsc::UnboundedReceiver<agent_client_protocol::schema::v1::SessionId>>,
+ ) -> Self
where
Pipe: AsyncRead + AsyncWrite + Unpin + Send + 'static,
Observer: Fn() + Send + 'static,
@@ -83,7 +98,14 @@ impl PipeTransport {
};
let _ = inbound_tx.send(ready);
- tokio::spawn(pump(pipe, outbound_rx, inbound_tx, on_frame, shutdown));
+ tokio::spawn(pump(
+ pipe,
+ outbound_rx,
+ inbound_tx,
+ on_frame,
+ shutdown,
+ reload,
+ ));
Self {
outbound: outbound_tx,
@@ -133,6 +155,7 @@ async fn pump<Pipe, Observer>(
inbound: mpsc::UnboundedSender<ToServerMessage>,
on_frame: Observer,
shutdown: CancellationToken,
+ mut reload: Option<mpsc::UnboundedReceiver<agent_client_protocol::schema::v1::SessionId>>,
) where
Pipe: AsyncRead + AsyncWrite + Unpin + Send + 'static,
Observer: Fn() + Send + 'static,
@@ -142,9 +165,30 @@ async fn pump<Pipe, Observer>(
loop {
tokio::select! {
+ // Recovery is enqueued before the prompt response. Observe it
+ // first even when that response is already readable on the pipe.
+ biased;
() = shutdown.cancelled() => break,
+ signal = async {
+ match reload.as_mut() {
+ Some(receiver) => receiver.recv().await,
+ None => std::future::pending().await,
+ }
+ } => {
+ if signal.is_none() {
+ reload = None;
+ } else if inbound.send(ToServerMessage::Event {
+ event: SystemEvent::ReloadRequired,
+ }).is_err() {
+ break;
+ }
+ }
outgoing = outbound.recv() => {
let Some(Outbound { frame, completed }) = outgoing else { break };
+ // Activity begins when a frame is accepted for delivery, not
+ // after I/O completes: the idle reaper must not close a prompt
+ // already waiting to be written.
+ on_frame();
let mut json = match serde_json::to_string(&frame) {
Ok(json) => json,
Err(error) => {
@@ -164,7 +208,6 @@ async fn pump<Pipe, Observer>(
let _ = completed.send(Err(TransportError::Client(error.to_string())));
break;
}
- on_frame();
let _ = completed.send(Ok(()));
}
incoming = lines.next_line() => {
@@ -180,9 +223,11 @@ async fn pump<Pipe, Observer>(
if line.trim().is_empty() {
continue;
}
+ // A complete inbound line was accepted from the peer. Mark it
+ // before parsing so a reaper cannot win on the activity lock.
+ on_frame();
match serde_json::from_str::<RawJsonRpcMessage>(&line) {
Ok(frame) => {
- on_frame();
let message = ToServerMessage::Acp(AcpMessage(frame));
if inbound.send(message).is_err() {
break; // receiver dropped: the session is gone
diff --git a/crates/agent_harness/src/outbound/daytona/manager.rs b/crates/agent_harness/src/outbound/daytona/manager.rs
index 95284fc979..abb39819d9 100644
--- a/crates/agent_harness/src/outbound/daytona/manager.rs
+++ b/crates/agent_harness/src/outbound/daytona/manager.rs
@@ -354,7 +354,10 @@ impl ContainerManager for DaytonaContainerManager {
skip(self),
fields(agent.container.provider = "daytona")
)]
- async fn spawn(&self, command: SpawnContainer) -> Result<DaytonaContainer> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<DaytonaContainer>> {
let SpawnContainer {
session_id,
size,
@@ -395,7 +398,9 @@ impl ContainerManager for DaytonaContainerManager {
}
match self.align_size_then_bring_up(&id, size).await {
- Ok(container) => Ok(container),
+ Ok(container) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ container,
+ )),
Err(error) => {
self.managed.containers.remove(&id);
if !self.discard(&id).await {
@@ -455,7 +460,10 @@ impl ContainerManager for DaytonaContainerManager {
}
#[tracing::instrument(err, skip(self))]
- async fn resume(&self, session: AgentSessionId) -> Result<DaytonaContainer> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<DaytonaContainer>> {
let id = DaytonaSandboxId::new(
self.client
.find_by_label(SESSION_LABEL, &session.to_string())
@@ -480,7 +488,9 @@ impl ContainerManager for DaytonaContainerManager {
return Err(unavailable(error));
}
match self.bring_up(&id).await {
- Ok(container) => Ok(container),
+ Ok(container) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ container,
+ )),
Err(error) => {
self.managed.containers.remove(&id);
if !stop_sandbox(&self.client, &id, "failed sandbox resume").await {
diff --git a/crates/agent_harness/src/outbound/local/manager.rs b/crates/agent_harness/src/outbound/local/manager.rs
index 7b915ff28f..450693b073 100644
--- a/crates/agent_harness/src/outbound/local/manager.rs
+++ b/crates/agent_harness/src/outbound/local/manager.rs
@@ -194,7 +194,10 @@ impl ContainerManager for LocalContainerManager {
// `skip_all`: `SpawnContainer` carries the egress session token; nothing
// secret-bearing may be Debug-recorded into the span.
#[tracing::instrument(err, skip_all, fields(session_id = %command.session_id))]
- async fn spawn(&self, command: SpawnContainer) -> Result<Self::Transport> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
let SpawnContainer {
session_id,
// Routing already consumed the kind; every spawn that reaches
@@ -239,7 +242,9 @@ impl ContainerManager for LocalContainerManager {
tracing::info!(container = %container.name, session = %session_id, "container created");
match self.bring_up(&container).await {
- Ok(transport) => Ok(transport),
+ Ok(transport) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ transport,
+ )),
Err(error) => {
self.discard(&container).await;
Err(error)
@@ -258,7 +263,10 @@ impl ContainerManager for LocalContainerManager {
}
#[tracing::instrument(err, skip(self))]
- async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
let container = self.find(session).await?.ok_or_else(|| {
HarnessError::Container(format!("session {session} has no container to resume"))
})?;
@@ -266,7 +274,9 @@ impl ContainerManager for LocalContainerManager {
// Idempotent: docker starts a stopped container and says nothing about
// one already running.
self.docker.start(&container).await.map_err(unavailable)?;
- self.bring_up(&container).await
+ self.bring_up(&container)
+ .await
+ .map(agent_session::domain::connection::RuntimeAttachment::solo)
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/agent_harness/src/outbound/namespace/manager.rs b/crates/agent_harness/src/outbound/namespace/manager.rs
index 118251cca2..dea7f896dc 100644
--- a/crates/agent_harness/src/outbound/namespace/manager.rs
+++ b/crates/agent_harness/src/outbound/namespace/manager.rs
@@ -100,7 +100,10 @@ impl ContainerManager for NamespaceContainerManager {
session_id = %command.session_id,
)
)]
- async fn spawn(&self, command: SpawnContainer) -> Result<Self::Transport> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
let mut env = Vec::new();
env.extend(command.egress.environment());
let container = ContainerSpec {
@@ -117,7 +120,9 @@ impl ContainerManager for NamespaceContainerManager {
let instance_id = instance.id.clone();
match self.bring_up(instance).await {
- Ok(container) => Ok(container),
+ Ok(container) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ container,
+ )),
Err(error) => {
if let Err(destroy_error) = self.client.destroy_instance(&instance_id).await {
tracing::error!(
@@ -141,7 +146,10 @@ impl ContainerManager for NamespaceContainerManager {
))
}
- async fn resume(&self, _session: AgentSessionId) -> Result<Self::Transport> {
+ async fn resume(
+ &self,
+ _session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
todo!("resuming Namespace instances is not implemented yet")
}
diff --git a/crates/agent_harness/src/outbound/routing.rs b/crates/agent_harness/src/outbound/routing.rs
index b9af6ee46a..0eae018737 100644
--- a/crates/agent_harness/src/outbound/routing.rs
+++ b/crates/agent_harness/src/outbound/routing.rs
@@ -54,29 +54,48 @@ where
{
type Transport = RoutedTransport<Sandbox::Transport, Cursor::Transport>;
- async fn spawn(&self, command: SpawnContainer) -> Result<Self::Transport> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
match command.kind {
- AgentKind::Cursor => Ok(RoutedTransport::Cursor(self.cursor.spawn(command).await?)),
- AgentKind::SandboxedCoder | AgentKind::InMemory => {
- Ok(RoutedTransport::Sandbox(self.sandbox.spawn(command).await?))
- }
+ AgentKind::Cursor => Ok(self
+ .cursor
+ .spawn(command)
+ .await?
+ .map_transport(RoutedTransport::Cursor)),
+ AgentKind::SandboxedCoder | AgentKind::InMemory => Ok(self
+ .sandbox
+ .spawn(command)
+ .await?
+ .map_transport(RoutedTransport::Sandbox)),
AgentKind::External => Err(external_is_unroutable()),
}
}
- async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
let row = self.sessions.get(session).await?;
match AgentKind::for_session(row.bot_id, &row.harness) {
- AgentKind::Cursor => Ok(RoutedTransport::Cursor(self.cursor.resume(session).await?)),
- AgentKind::SandboxedCoder | AgentKind::InMemory => Ok(RoutedTransport::Sandbox(
- self.sandbox.resume(session).await?,
- )),
+ AgentKind::Cursor => Ok(self
+ .cursor
+ .resume(session)
+ .await?
+ .map_transport(RoutedTransport::Cursor)),
+ AgentKind::SandboxedCoder | AgentKind::InMemory => Ok(self
+ .sandbox
+ .resume(session)
+ .await?
+ .map_transport(RoutedTransport::Sandbox)),
AgentKind::External => Err(external_is_unroutable()),
}
}
async fn session_token(&self, session: AgentSessionId) -> Result<Option<String>> {
- match AgentKind::of(self.sessions.get(session).await?.bot_id) {
+ let row = self.sessions.get(session).await?;
+ match AgentKind::for_session(row.bot_id, &row.harness) {
AgentKind::Cursor => self.cursor.session_token(session).await,
AgentKind::SandboxedCoder | AgentKind::InMemory => {
self.sandbox.session_token(session).await
diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rs
index c67665b610..bc73ad74f7 100644
--- a/crates/agent_harness/src/outbound/routing/test.rs
+++ b/crates/agent_harness/src/outbound/routing/test.rs
@@ -56,14 +56,24 @@ impl TaggedManager {
impl ContainerManager for TaggedManager {
type Transport = TaggedTransport;
- async fn spawn(&self, _command: SpawnContainer) -> Result<TaggedTransport> {
+ async fn spawn(
+ &self,
+ _command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<TaggedTransport>> {
self.record("spawn");
- Ok(TaggedTransport)
+ Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ TaggedTransport,
+ ))
}
- async fn resume(&self, _session: AgentSessionId) -> Result<TaggedTransport> {
+ async fn resume(
+ &self,
+ _session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<TaggedTransport>> {
self.record("resume");
- Ok(TaggedTransport)
+ Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ TaggedTransport,
+ ))
}
async fn session_token(&self, _session: AgentSessionId) -> Result<Option<String>> {
@@ -212,12 +222,12 @@ async fn the_cursor_bot_routes_to_cursor_and_everything_else_to_the_sandbox() {
.spawn(spawn_for(AgentKind::Cursor))
.await
.expect("spawn");
- assert!(matches!(spawned, RoutedTransport::Cursor(_)));
+ spawned.map_transport(|transport| assert!(matches!(transport, RoutedTransport::Cursor(_))));
let spawned = router
.spawn(spawn_for(AgentKind::SandboxedCoder))
.await
.expect("spawn");
- assert!(matches!(spawned, RoutedTransport::Sandbox(_)));
+ spawned.map_transport(|transport| assert!(matches!(transport, RoutedTransport::Sandbox(_))));
assert_eq!(cursor.calls(), ["cursor:spawn"]);
assert_eq!(sandbox.calls(), ["sandbox:spawn"]);
}
@@ -253,7 +263,11 @@ async fn a_database_backed_cursor_agent_routes_by_its_stored_harness() {
let session = AgentSessionId::new();
router.resume(session).await.expect("resume");
+ router.session_token(session).await.expect("session token");
router.teardown(session).await.expect("teardown");
- assert_eq!(cursor.calls(), ["cursor:resume", "cursor:teardown"]);
+ assert_eq!(
+ cursor.calls(),
+ ["cursor:resume", "cursor:session_token", "cursor:teardown"]
+ );
assert!(sandbox.calls().is_empty());
}
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index d71ff594f6..8d4a9a4c6a 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -282,7 +282,11 @@ impl MockContainerManager {
impl ContainerManager for MockContainerManager {
type Transport = ContainerMock;
- async fn spawn(&self, command: SpawnContainer) -> Result<ContainerMock, HarnessError> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<ContainerMock>, HarnessError>
+ {
if let Some(message) = self
.spawn_error
.lock()
@@ -297,7 +301,9 @@ impl ContainerManager for MockContainerManager {
.push(command.size);
let container = ContainerMock::default();
self.lock().insert(command.session_id, container.clone());
- Ok(container)
+ Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ container,
+ ))
}
fn resize_effect(&self, from: SandboxSize, to: SandboxSize) -> SandboxResizeEffect {
@@ -326,7 +332,11 @@ impl ContainerManager for MockContainerManager {
Ok(())
}
- async fn resume(&self, session: AgentSessionId) -> Result<ContainerMock, HarnessError> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<ContainerMock>, HarnessError>
+ {
self.resumes.fetch_add(1, Ordering::Relaxed);
let mut containers = self.lock();
if !containers.contains_key(&session) {
@@ -336,7 +346,9 @@ impl ContainerManager for MockContainerManager {
}
let container = ContainerMock::default();
containers.insert(session, container.clone());
- Ok(container)
+ Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ container,
+ ))
}
/// The fixed token every mock container "holds", for sessions that were
diff --git a/crates/agent_runtime_protocol/src/domain/mod.rs b/crates/agent_runtime_protocol/src/domain/mod.rs
index f0ce8c7f3c..e95b69d8e8 100644
--- a/crates/agent_runtime_protocol/src/domain/mod.rs
+++ b/crates/agent_runtime_protocol/src/domain/mod.rs
@@ -12,3 +12,6 @@ pub mod connection;
pub mod ports;
/// Versioned protocol message types.
pub mod schema;
+
+/// Agent-neutral reconstructed turn lifecycle.
+pub mod turn;
diff --git a/crates/agent_runtime_protocol/src/domain/schema/v0.rs b/crates/agent_runtime_protocol/src/domain/schema/v0.rs
index c53171f0ea..fb4515becc 100644
--- a/crates/agent_runtime_protocol/src/domain/schema/v0.rs
+++ b/crates/agent_runtime_protocol/src/domain/schema/v0.rs
@@ -43,6 +43,8 @@ pub enum SystemEvent {
AcpReady,
/// The session transport closed or failed and no more frames will arrive.
Disconnected,
+ /// The hosted provider recovered history; the client must reload when idle.
+ ReloadRequired,
/// An application-defined event name with no protocol-level meaning yet.
Unknown(String),
}
@@ -54,6 +56,7 @@ impl SystemEvent {
match self {
Self::AcpReady => "acp_ready",
Self::Disconnected => "disconnected",
+ Self::ReloadRequired => "reload_required",
Self::Unknown(name) => name,
}
}
@@ -76,6 +79,7 @@ impl<'de> Deserialize<'de> for SystemEvent {
Ok(match String::deserialize(deserializer)?.as_str() {
"acp_ready" => Self::AcpReady,
"disconnected" => Self::Disconnected,
+ "reload_required" => Self::ReloadRequired,
name => Self::Unknown(name.to_owned()),
})
}
diff --git a/crates/agent_runtime_protocol/src/domain/turn.rs b/crates/agent_runtime_protocol/src/domain/turn.rs
new file mode 100644
index 0000000000..282ad9221a
--- /dev/null
+++ b/crates/agent_runtime_protocol/src/domain/turn.rs
@@ -0,0 +1,32 @@
+//! Optional agent-neutral lifecycle facts for reconstructed conversation turns.
+use agent_client_protocol::JsonRpcNotification;
+use agent_client_protocol::schema::v1::SessionId;
+use serde::{Deserialize, Serialize};
+
+/// Completes the currently projected turn without inventing a prompt response.
+/// This optional extension conveys history facts; it does not certify a load,
+/// change load success semantics, or imply completion when absent.
+#[derive(Debug, Clone, Serialize, Deserialize, JsonRpcNotification)]
+#[notification(method = "_session/turn_complete")]
+#[serde(rename_all = "camelCase")]
+pub struct TurnCompleteNotification {
+ /// ACP session whose current projected turn ended.
+ pub session_id: SessionId,
+ /// The recorded terminal outcome.
+ pub outcome: TurnOutcome,
+}
+
+/// Recorded terminal outcome of a reconstructed turn.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum TurnOutcome {
+ /// The agent completed its work.
+ Finished,
+ /// The turn was cancelled.
+ Cancelled,
+ /// The turn failed.
+ Failed {
+ /// Failure description supplied by the adapter.
+ message: String,
+ },
+}
diff --git a/crates/agent_session/src/domain/connection.rs b/crates/agent_session/src/domain/connection.rs
index 11c82402c6..ca0d0aae62 100644
--- a/crates/agent_session/src/domain/connection.rs
+++ b/crates/agent_session/src/domain/connection.rs
@@ -34,7 +34,7 @@ use dashmap::DashMap;
use tokio::sync::{Mutex, mpsc, watch};
use tokio_util::sync::CancellationToken;
-use crate::domain::model::AgentSessionId;
+use crate::domain::model::{AgentSessionId, SessionClaim};
use crate::domain::session::HandshakeStatus;
#[cfg(test)]
@@ -134,6 +134,7 @@ fn acp_session_of(frame: &RawJsonRpcMessage) -> Option<SessionId> {
/// gate so exactly one session per connection runs `initialize` and the rest
/// are told its result.
pub struct RuntimeAttachment<Connector> {
+ pub(crate) activation: Option<AttachmentActivation>,
pub(crate) connector: Connector,
pub(crate) handshake: watch::Sender<HandshakeStatus>,
/// MCP servers the agent is told to connect to when this attachment's
@@ -146,6 +147,10 @@ pub struct RuntimeAttachment<Connector> {
pub(crate) mcp_servers: Vec<McpServer>,
}
+/// Activate attachment-owned resources with the exact acquired ownership claim.
+pub type AttachmentActivation =
+ Box<dyn FnOnce(SessionClaim) -> crate::domain::error::Result<()> + Send + Sync>;
+
impl<Connector> RuntimeAttachment<Connector> {
/// A transport carrying exactly one session, so its handshake is its own.
///
@@ -154,12 +159,30 @@ impl<Connector> RuntimeAttachment<Connector> {
pub fn solo(connector: Connector) -> Self {
let (handshake, _) = watch::channel(HandshakeStatus::Pending);
Self {
+ activation: None,
connector,
handshake,
mcp_servers: Vec::new(),
}
}
+ /// Run once after ownership acquisition, before the session actor starts.
+ #[must_use]
+ pub fn on_activate(mut self, activation: AttachmentActivation) -> Self {
+ self.activation = Some(activation);
+ self
+ }
+
+ /// Change the carrier without losing its handshake or activation lifecycle.
+ pub fn map_transport<T>(self, map: impl FnOnce(Connector) -> T) -> RuntimeAttachment<T> {
+ RuntimeAttachment {
+ connector: map(self.connector),
+ handshake: self.handshake,
+ mcp_servers: self.mcp_servers,
+ activation: self.activation,
+ }
+ }
+
/// The MCP servers the agent is handed when this attachment's session is
/// established.
#[must_use]
@@ -279,6 +302,7 @@ where
}
RuntimeAttachment {
+ activation: None,
connector: SessionChannel {
connection: Arc::clone(self),
session,
diff --git a/crates/agent_session/src/domain/connection/test.rs b/crates/agent_session/src/domain/connection/test.rs
index 47fb9a645a..8a2e3bc41e 100644
--- a/crates/agent_session/src/domain/connection/test.rs
+++ b/crates/agent_session/src/domain/connection/test.rs
@@ -9,6 +9,32 @@ use agent_runtime_protocol::domain::schema::v0::SystemEvent;
const OTHER: AgentSessionId = AgentSessionId::TEST_B;
+#[test]
+fn mapping_an_attachment_preserves_activation_and_handshake() {
+ use crate::domain::model::{ManagerFence, ReplicaId};
+ let claim = SessionClaim {
+ session: OTHER,
+ replica: ReplicaId::from_uuid(macro_uuid::Uuid::from_u128(2)),
+ fence: ManagerFence(7),
+ };
+ let called = Arc::new(AtomicBool::new(false));
+ let observed = called.clone();
+ let attachment = RuntimeAttachment::solo(1).on_activate(Box::new(move |actual| {
+ assert_eq!(actual.session, claim.session);
+ assert_eq!(actual.replica, claim.replica);
+ assert_eq!(actual.fence, claim.fence);
+ observed.store(true, Ordering::SeqCst);
+ Ok(())
+ }));
+ let handshake = attachment.handshake.clone();
+ let mut mapped = attachment.map_transport(|n| n.to_string());
+ assert_eq!(mapped.connector, "1");
+ assert!(mapped.handshake.same_channel(&handshake));
+ mapped.activation.take().unwrap()(claim).unwrap();
+ assert!(mapped.activation.is_none());
+ assert!(called.load(Ordering::SeqCst));
+}
+
fn request(id: &str, method: &str, params: serde_json::Value) -> ToServerMessage {
ToServerMessage::Acp(AcpMessage(
RawJsonRpcMessage::request(method.to_owned(), params, RequestId::Str(id.to_owned()))
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index ba92a32f66..c805eb0b14 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -274,6 +274,8 @@ pub struct ExternalSession {
pub external_name: Option<String>,
/// The agent's page on the provider's site, for opening it there.
pub external_url: Option<String>,
+ /// The last provider run whose output was delivered to this session.
+ pub last_run_id: Option<String>,
}
/// The agent behind a session, as much of it as rendering a message needs.
@@ -332,7 +334,7 @@ impl From<super::ports::QueuedControl> for QueuedActionDto {
/// One frame appended to a live session's log, for anyone watching.
///
-/// The streaming counterpart of [`SessionLog`]: that is the whole log
+/// The streaming counterpart of [`SessionLog`]: that is the selected history window
/// for a reader arriving late, this is one frame for a reader already here.
/// Both carry the same entry shape, so a client folds them the same way -
/// catching up on the log and then following it is one fold, not two.
@@ -358,13 +360,17 @@ pub struct LogAppended {
/// a session's messages against anything else still has something to order by.
#[derive(Debug, Clone)]
pub struct StoredAgentSessionLog {
+ /// Durable row identity, used to select a replay history boundary.
+ pub id: Uuid,
/// When the entry was appended to the log.
pub created_at: DateTime<Utc>,
/// The frame, exactly as the log stored it.
pub entry: AgentSessionLog,
}
-/// A session's raw protocol log.
+/// A session's effective ACP history, from its latest successful load initialization.
+/// With no successful load, history starts at the beginning. Failed attempts
+/// remain in the stream and must be staged/discarded by fold consumers.
///
/// Served rather than the messages it derives: the reader folds it. The web
/// client runs the same fold compiled to WASM, so a streamed session and a
@@ -399,3 +405,11 @@ pub enum ChannelSession {
/// The bot's session was created from the incoming thread.
CreatedFromThread(AgentSession),
}
+
+/// Initialization selected by a matching successful load in the session machine.
+/// Persistence must append the response and select this row in one fenced transaction.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct HistoryBoundary {
+ /// Initialization row in this session's log.
+ pub initialization_log_id: Uuid,
+}
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index bfcd3ac657..d9868abdf6 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -342,7 +342,7 @@ pub trait AgentSessionLogRepo: Send + Sync + 'static {
/// session's current fence.
///
/// This is the write half of the fencing contract: the check and the
- /// append are one atomic statement, so a replica that stalled past its
+ /// append are one atomic operation, so a replica that stalled past its
/// heartbeat and was superseded cannot interleave frames no matter when
/// it wakes - its append matches nothing and fails with
/// [`FencedOut`](super::error::AgentSessionError::FencedOut), which the
@@ -353,7 +353,20 @@ pub trait AgentSessionLogRepo: Send + Sync + 'static {
claim: &SessionClaim,
) -> impl Future<Output = Result<StoredAgentSessionLog>> + Send;
- /// List all log entries for a session, in chronological order.
+ /// Append a successful load response and select its initialization atomically,
+ /// under the current ownership fence. The boundary must belong to this session.
+ fn create_fenced_with_boundary(
+ &self,
+ log: AgentSessionLog,
+ claim: &SessionClaim,
+ boundary: Option<HistoryBoundary>,
+ ) -> impl Future<Output = Result<StoredAgentSessionLog>> + Send;
+
+ /// List effective ACP history in deterministic `(created_at, id)` order.
+ /// Starts at the latest successfully loaded initialization, or the beginning.
+ /// Raw failed/partial replay frames remain; consumers must stage load attempts.
+ /// The first returned row is the inclusive transport reconciliation cursor;
+ /// buffered rows ordered before it are obsolete. An empty result has none.
///
/// Entries come back stamped with when the log recorded them: the frame
/// itself carries no time, and a reader ordering or merging a session's
@@ -367,7 +380,17 @@ pub trait AgentSessionLogRepo: Send + Sync + 'static {
/// Sequential live log writer owned by one session actor.
pub trait AgentSessionLogWriter: Send + 'static {
/// Persist and fold one frame into this connection's live projection.
- fn append(&mut self, log: AgentSessionLog) -> impl Future<Output = Result<()>> + Send;
+ fn append(&mut self, log: AgentSessionLog) -> impl Future<Output = Result<Uuid>> + Send {
+ self.append_with_boundary(log, None)
+ }
+
+ /// Persist a frame and optional successful-load boundary in one transaction.
+ /// Returns its durable row identity before the actor continues.
+ fn append_with_boundary(
+ &mut self,
+ log: AgentSessionLog,
+ boundary: Option<HistoryBoundary>,
+ ) -> impl Future<Output = Result<Uuid>> + Send;
}
/// A session's queue changed; this is the whole queue as it stands now.
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 1872cad6d6..68ccad7910 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -194,7 +194,7 @@ pub trait AgentSessionService: Send + Sync + 'static {
id: AgentSessionId,
) -> impl Future<Output = Result<MessageId>> + Send;
- /// The raw protocol log of one session, oldest first, with the agent
+ /// The effective ACP history of one session, oldest first, with the agent
/// whose messages it derives.
///
/// Served unfolded because nothing here folds for a reader any more: the
@@ -380,7 +380,7 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
async fn activate_reserved<Connector>(
&self,
session: AgentSession,
- attachment: RuntimeAttachment<Connector>,
+ mut attachment: RuntimeAttachment<Connector>,
reservation: AttachReservation,
claim: SessionClaim,
) -> Result<()>
@@ -401,6 +401,9 @@ impl<R, Folds, Rt, Namer> AgentSessionServiceImpl<R, Folds, Rt, Namer> {
if !Arc::ptr_eq(&active.marker, &reservation.marker) || active.stopping {
return Err(AgentSessionError::Disconnected(id));
}
+ if let Some(activate) = attachment.activation.take() {
+ activate(claim)?;
+ }
active.commands = Some(commands.clone());
drop(active);
let (marker, stopped_tx) = reservation.commit();
@@ -636,6 +639,7 @@ where
)
.await
.unwrap_or(Err(AgentSessionError::LogTimedOut(id)))
+ .map(|_| ())
}
async fn attach_session<Connector>(
@@ -892,7 +896,11 @@ where
R: AgentSessionRepo + AgentSessionLogRepo + Clone,
Rt: AgentSessionRealtime + Send + Sync + 'static,
{
- async fn append(&mut self, log: AgentSessionLog) -> Result<()> {
+ async fn append_with_boundary(
+ &mut self,
+ log: AgentSessionLog,
+ boundary: Option<crate::domain::model::HistoryBoundary>,
+ ) -> Result<macro_uuid::Uuid> {
let session = log.agent_session_id;
// The wire tap: every frame of every session, both directions,
@@ -913,7 +921,12 @@ where
// Durable first: projections are rebuildable, but a frame omitted from
// session history is not.
let stored = match &self.claim {
- Some(claim) => self.repo.create_fenced(log.clone(), claim).await?,
+ Some(claim) => {
+ self.repo
+ .create_fenced_with_boundary(log.clone(), claim, boundary)
+ .await?
+ }
+ None if boundary.is_some() => return Err(AgentSessionError::FencedOut(session)),
None => AgentSessionLogRepo::create(&self.repo, log.clone()).await?,
};
@@ -951,6 +964,7 @@ where
// Best-effort once the durable append has succeeded: the port drops
// frames by contract, and the log this was derived from is already
// durable, so the worst a failure costs is a viewer who has to reload.
+ let id = stored.id;
if let Err(error) = self.stream(session, stored).await {
tracing::error!(
error = ?error,
@@ -958,7 +972,7 @@ where
"failed to stream agent session frame"
);
}
- Ok(())
+ Ok(id)
}
}
diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rs
index 4fcb3dce3e..66a86477b0 100644
--- a/crates/agent_session/src/domain/service/test.rs
+++ b/crates/agent_session/src/domain/service/test.rs
@@ -145,10 +145,22 @@ struct BlockingPromptLogs {
entered: Arc<Notify>,
release: Arc<Notify>,
hang_disconnect: bool,
+ fail_restore_log: Option<RestoreLogFailure>,
+}
+
+#[derive(Clone, Copy)]
+enum RestoreLogFailure {
+ InitializeRequest,
+ InitializeResponse,
+ LoadResponse,
}
impl AgentSessionLogWriter for BlockingPromptLogs {
- async fn append(&mut self, log: AgentSessionLog) -> Result<()> {
+ async fn append_with_boundary(
+ &mut self,
+ log: AgentSessionLog,
+ _boundary: Option<crate::domain::model::HistoryBoundary>,
+ ) -> Result<macro_uuid::Uuid> {
let is_prompt = matches!(
&log.content,
Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(
@@ -159,8 +171,7 @@ impl AgentSessionLogWriter for BlockingPromptLogs {
self.entered.notify_one();
self.release.notified().await;
}
- AgentSessionLogRepo::create(&self.repo, log).await?;
- Ok(())
+ Ok(AgentSessionLogRepo::create(&self.repo, log).await?.id)
}
}
@@ -438,6 +449,38 @@ impl SessionOwnership for BlockingPromptLogs {
}
impl AgentSessionLogRepo for BlockingPromptLogs {
+ async fn create_fenced_with_boundary(
+ &self,
+ log: AgentSessionLog,
+ claim: &SessionClaim,
+ boundary: Option<crate::domain::model::HistoryBoundary>,
+ ) -> Result<StoredAgentSessionLog> {
+ let fail = match self.fail_restore_log {
+ Some(RestoreLogFailure::InitializeRequest) => matches!(&log.content,
+ Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(agent_client_protocol::RawJsonRpcMessage::Request(request))))
+ if request.method.as_ref() == "initialize"),
+ Some(RestoreLogFailure::InitializeResponse) => {
+ boundary.is_none()
+ && matches!(
+ &log.content,
+ Message::ToServer(ToServerMessage::Acp(AcpMessage(
+ agent_client_protocol::RawJsonRpcMessage::Response(_)
+ )))
+ )
+ }
+ Some(RestoreLogFailure::LoadResponse) => boundary.is_some(),
+ None => false,
+ };
+ if fail {
+ return Err(AgentSessionError::Handshake(
+ "injected restore log failure".into(),
+ ));
+ }
+ self.repo
+ .create_fenced_with_boundary(log, claim, boundary)
+ .await
+ }
+
async fn create_fenced(
&self,
log: AgentSessionLog,
@@ -492,7 +535,7 @@ impl TransportReceiver<ToServerMessage> for PendingReceiver {
async fn open_test_session(
inbound: &mpsc::Sender<ToServerMessage>,
outbound: &mut mpsc::Receiver<ToRuntimeMessage>,
- session: AgentSessionId,
+ _session: AgentSessionId,
) {
inbound
.send(ToServerMessage::Event {
@@ -500,13 +543,16 @@ async fn open_test_session(
})
.await
.unwrap();
- let _initialize = outbound.recv().await.expect("initialize request");
+ let ToRuntimeMessage::Acp(AcpMessage(agent_client_protocol::RawJsonRpcMessage::Request(
+ initialize,
+ ))) = outbound.recv().await.expect("initialize request")
+ else {
+ panic!("expected initialize")
+ };
inbound
.send(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::response(
- agent_client_protocol::schema::v1::RequestId::Str(format!(
- "agent_session:{session}:0"
- )),
+ initialize.id,
Ok(serde_json::to_value(
agent_client_protocol::schema::v1::InitializeResponse::new(PROTOCOL_VERSION),
)
@@ -515,13 +561,15 @@ async fn open_test_session(
)))
.await
.unwrap();
- let _open = outbound.recv().await.expect("session/new request");
+ let ToRuntimeMessage::Acp(AcpMessage(agent_client_protocol::RawJsonRpcMessage::Request(open))) =
+ outbound.recv().await.expect("session/new request")
+ else {
+ panic!("expected session/new")
+ };
inbound
.send(ToServerMessage::Acp(AcpMessage(
agent_client_protocol::RawJsonRpcMessage::response(
- agent_client_protocol::schema::v1::RequestId::Str(format!(
- "agent_session:{session}:1"
- )),
+ open.id,
Ok(serde_json::to_value(
agent_client_protocol::schema::v1::NewSessionResponse::new("acp-1"),
)
@@ -704,6 +752,7 @@ async fn cancellation_does_not_drop_an_effect_batch_after_machine_mutation() {
entered: entered.clone(),
release: release.clone(),
hang_disconnect: false,
+ fail_restore_log: None,
};
let (outbound_tx, mut outbound_rx) = mpsc::channel(8);
let (inbound_tx, inbound_rx) = mpsc::channel(8);
@@ -783,6 +832,7 @@ async fn live_inbound_logs_do_not_reuse_the_expired_handshake_deadline() {
entered: entered.clone(),
release: release.clone(),
hang_disconnect: false,
+ fail_restore_log: None,
};
let (outbound_tx, mut outbound_rx) = mpsc::channel(8);
let (inbound_tx, inbound_rx) = mpsc::channel(8);
@@ -974,6 +1024,7 @@ async fn marking_disconnected_is_bounded_when_persistence_hangs() {
entered: Arc::new(Notify::new()),
release: Arc::new(Notify::new()),
hang_disconnect: true,
+ fail_restore_log: None,
};
let service =
AgentSessionServiceImpl::new(hanging, FoldedMessageService::new(repo), NoOpRealtime);
@@ -1213,3 +1264,298 @@ async fn appending_a_config_response_projects_the_model() {
.expect("get session");
assert_eq!(session.model, "sonnet", "the rejected change moved nothing");
}
+
+#[tokio::test]
+async fn shared_transport_copies_durable_initialization_before_load() {
+ use crate::domain::session::Input;
+ use agent_client_protocol::RawJsonRpcMessage;
+ use agent_client_protocol::schema::v1::{AgentCapabilities, InitializeResponse};
+ let repo = InMemoryAgentSessionRepo::new();
+ let first = AgentSessionId::new();
+ let second = AgentSessionId::new();
+ for id in [first, second] {
+ repo.insert_session(test_agent_session(id));
+ }
+ let (handshake, _) = watch::channel(HandshakeStatus::Pending);
+ let (send, mut received) = mpsc::channel(8);
+ let (_inbound, inbound) = mpsc::channel(8);
+ let (_commands, commands) = mpsc::channel(8);
+ let claim = claim_for_test(&repo, first).await;
+ let mut actor = SessionActor::new(
+ first,
+ Some("first-acp".into()),
+ "/workspace".into(),
+ vec![],
+ RecordingTransport {
+ outbound: send,
+ inbound,
+ },
+ LiveSessionLogWriter::fenced(repo.clone(), NoOpRealtime, claim),
+ commands,
+ handshake.clone(),
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
+ );
+ actor
+ .dispatch(Input::Inbound(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ }))
+ .await;
+ let init_request = received.recv().await.unwrap();
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(init))) = &init_request else {
+ panic!("initialize request")
+ };
+ let init_response = ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
+ init.id.clone(),
+ Ok(serde_json::to_value(
+ InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true)),
+ )
+ .unwrap()),
+ )));
+ actor.dispatch(Input::Inbound(init_response.clone())).await;
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(load))) =
+ received.recv().await.unwrap()
+ else {
+ panic!("load request")
+ };
+ actor
+ .dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
+ ))))
+ .await;
+ let first_history = AgentSessionLogRepo::list_by_session(&repo, first)
+ .await
+ .unwrap();
+ assert_eq!(first_history.len(), 4);
+
+ // A late-bound second session uses the retained actual handshake, with local row IDs.
+ let (send, mut received) = mpsc::channel(8);
+ let (_inbound, inbound) = mpsc::channel(8);
+ let (_commands, commands) = mpsc::channel(8);
+ let claim = claim_for_test(&repo, second).await;
+ let mut actor = SessionActor::new(
+ second,
+ Some("second-acp".into()),
+ "/workspace".into(),
+ vec![],
+ RecordingTransport {
+ outbound: send,
+ inbound,
+ },
+ LiveSessionLogWriter::fenced(repo.clone(), NoOpRealtime, claim),
+ commands,
+ handshake,
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
+ );
+ let ready = actor.next_input().await;
+ assert!(matches!(ready, Input::SharedReady { .. }));
+ actor.dispatch(ready).await;
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(load))) =
+ received.recv().await.unwrap()
+ else {
+ panic!("load request")
+ };
+ assert_eq!(load.method.as_ref(), "session/load");
+ actor
+ .dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
+ ))))
+ .await;
+ let history = AgentSessionLogRepo::list_by_session(&repo, second)
+ .await
+ .unwrap();
+ assert_eq!(history.len(), 4);
+ assert_ne!(history[0].id, first_history[0].id);
+ assert!(
+ history
+ .iter()
+ .all(|row| row.entry.agent_session_id == second)
+ );
+ assert_eq!(
+ serde_json::to_value(&history[0].entry.content).unwrap(),
+ serde_json::to_value(Message::ToRuntime(init_request)).unwrap()
+ );
+ assert_eq!(
+ serde_json::to_value(&history[1].entry.content).unwrap(),
+ serde_json::to_value(Message::ToServer(init_response)).unwrap()
+ );
+}
+
+#[tokio::test]
+async fn shared_initialization_append_failure_stops_before_sending_queued_prompt() {
+ for failure in [
+ RestoreLogFailure::InitializeRequest,
+ RestoreLogFailure::InitializeResponse,
+ ] {
+ assert_restore_persistence_failure_does_not_send_prompt(failure).await;
+ }
+}
+
+#[tokio::test]
+async fn successful_load_response_append_failure_stops_before_sending_queued_prompt() {
+ assert_restore_persistence_failure_does_not_send_prompt(RestoreLogFailure::LoadResponse).await;
+}
+
+async fn assert_restore_persistence_failure_does_not_send_prompt(failure: RestoreLogFailure) {
+ use crate::domain::model::HistoryBoundary;
+ use crate::domain::session::actors::Stepped;
+ use crate::domain::session::{InitializationContext, Input, SessionRestoreSupport};
+ use agent_client_protocol::{
+ RawJsonRpcMessage,
+ schema::v1::{AgentCapabilities, InitializeResponse, RequestId},
+ };
+
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = AgentSessionId::new();
+ repo.insert_session(test_agent_session(session));
+ let claim = claim_for_test(&repo, session).await;
+ // A prior committed boundary must survive both failure paths.
+ repo.create_fenced(any_event(session), &claim)
+ .await
+ .unwrap();
+ let previous = repo
+ .create_fenced(any_event(session), &claim)
+ .await
+ .unwrap();
+ repo.create_fenced_with_boundary(
+ any_event(session),
+ &claim,
+ Some(HistoryBoundary {
+ initialization_log_id: previous.id,
+ }),
+ )
+ .await
+ .unwrap();
+ let logs = BlockingPromptLogs {
+ repo: repo.clone(),
+ entered: Arc::new(Notify::new()),
+ release: Arc::new(Notify::new()),
+ hang_disconnect: false,
+ fail_restore_log: Some(failure),
+ };
+ let (handshake, _) = watch::channel(HandshakeStatus::Pending);
+ let (send, mut received) = mpsc::channel(8);
+ let (_inbound, inbound) = mpsc::channel(8);
+ let (commands, command_rx) = mpsc::channel(8);
+ let mut actor = SessionActor::new(
+ session,
+ Some("restored-acp".into()),
+ "/workspace".into(),
+ vec![],
+ RecordingTransport {
+ outbound: send,
+ inbound,
+ },
+ LiveSessionLogWriter::fenced(logs, NoOpRealtime, claim),
+ command_rx,
+ handshake.clone(),
+ Arc::new(crate::domain::ports::NoOpTurnObserver),
+ );
+ let (completed, completion) = oneshot::channel();
+ commands
+ .send(SessionCommand {
+ user_id: None,
+ action: AgentAction::prompt("must remain unsent"),
+ action_id: AgentActionId::mint(),
+ completed,
+ span: tracing::Span::none(),
+ enqueued_at: tokio::time::Instant::now(),
+ })
+ .await
+ .unwrap();
+ let queued = actor.next_input().await;
+ assert!(matches!(queued, Input::Command { .. }));
+ assert_eq!(actor.dispatch(queued).await, Stepped::Continue);
+ assert!(received.try_recv().is_err());
+
+ let init_id = RequestId::Str("shared-transport-initialization".into());
+ handshake
+ .send(HandshakeStatus::ReadyWithContext {
+ restore: SessionRestoreSupport {
+ resume: false,
+ load: true,
+ },
+ context: Arc::new(InitializationContext {
+ request: ToRuntimeMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::request(
+ "initialize".to_owned(),
+ serde_json::json!({"protocolVersion": 1}),
+ init_id.clone(),
+ )
+ .unwrap(),
+ )),
+ response: ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
+ init_id,
+ Ok(serde_json::to_value(
+ InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true)),
+ )
+ .unwrap()),
+ ))),
+ }),
+ })
+ .unwrap();
+ let ready = actor.next_input().await;
+ assert!(matches!(ready, Input::SharedReady { .. }));
+ let step = actor.dispatch(ready).await;
+ let mut failed_response_id = None;
+ if matches!(failure, RestoreLogFailure::LoadResponse) {
+ assert_eq!(step, Stepped::Continue);
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(load))) =
+ received.try_recv().unwrap()
+ else {
+ panic!("load request")
+ };
+ assert_eq!(load.method.as_ref(), "session/load");
+ failed_response_id = Some(load.id.clone());
+ assert_eq!(
+ actor
+ .dispatch(Input::Inbound(ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::response(load.id, Ok(serde_json::json!({}))),
+ ))))
+ .await,
+ Stepped::Stopped
+ );
+ } else {
+ assert_eq!(
+ step,
+ Stepped::Stopped,
+ "initialization failure stops before load"
+ );
+ }
+ assert!(
+ received.try_recv().is_err(),
+ "no queued prompt reached the transport"
+ );
+ let result = tokio::time::timeout(std::time::Duration::from_secs(1), completion)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(result.is_err(), "queued prompt must not report delivery");
+ let history = AgentSessionLogRepo::list_by_session(&repo, session)
+ .await
+ .unwrap();
+ assert_eq!(
+ history[0].id, previous.id,
+ "prior boundary remains selected"
+ );
+ assert!(
+ history.iter().all(|row| !matches!(&row.entry.content,
+ Message::ToRuntime(ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))))
+ if request.method.as_ref() == "session/prompt")),
+ "queued prompt was not appended"
+ );
+ if let Some(failed_id) = failed_response_id {
+ assert!(history.iter().all(|row| !matches!(&row.entry.content,
+ Message::ToServer(ToServerMessage::Acp(AcpMessage(frame))) if frame.response_id() == Some(&failed_id))),
+ "failed load response append must not be durable");
+ }
+ assert!(matches!(
+ history.last().unwrap().entry.content,
+ Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::Disconnected
+ })
+ ));
+}
+
+mod owner_binding;
diff --git a/crates/agent_session/src/domain/service/test/owner_binding.rs b/crates/agent_session/src/domain/service/test/owner_binding.rs
new file mode 100644
index 0000000000..644f929d67
--- /dev/null
+++ b/crates/agent_session/src/domain/service/test/owner_binding.rs
@@ -0,0 +1,42 @@
+use super::*;
+
+struct RejectOwner;
+
+impl Transport<ToRuntimeMessage, ToServerMessage> for RejectOwner {
+ type Sender = PendingSender;
+ type Receiver = PendingReceiver;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ panic!("a rejected attachment must never start an actor")
+ }
+}
+
+#[tokio::test]
+async fn owner_activation_failure_releases_reservation_without_starting_actor() {
+ let fx = fixture();
+ let reservation = fx.service.reserve_attach(fx.session).await.unwrap();
+ let session = fx.repo.get(fx.session).await.unwrap();
+ let claim = claim_for_test(&fx.repo, fx.session).await;
+ let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let observed = called.clone();
+ let result = fx
+ .service
+ .activate_reserved(
+ session,
+ RuntimeAttachment::solo(RejectOwner).on_activate(Box::new(move |actual| {
+ assert_eq!(actual.session, claim.session);
+ assert_eq!(actual.replica, claim.replica);
+ assert_eq!(actual.fence, claim.fence);
+ observed.store(true, std::sync::atomic::Ordering::SeqCst);
+ Err(TransportError::Client("stale attachment".into()).into())
+ })),
+ reservation,
+ claim,
+ )
+ .await;
+ assert!(matches!(result, Err(AgentSessionError::Transport(_))));
+ assert!(called.load(std::sync::atomic::Ordering::SeqCst));
+ assert!(!fx.service.active.contains_key(&fx.session));
+ assert!(fx.service.tasks.is_empty());
+ assert!(fx.service.reserve_attach(fx.session).await.is_ok());
+}
diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rs
index 5dc28cf54a..301fa7fdf5 100644
--- a/crates/agent_session/src/domain/session/actors.rs
+++ b/crates/agent_session/src/domain/session/actors.rs
@@ -68,6 +68,8 @@ pub(crate) enum Stepped {
/// machine, and executes the effects - nothing else.
pub(crate) struct SessionActor<Connector: AgentConnector, Logs> {
machine: SessionMachine<SessionCompletion>,
+ initialization_request: Option<ToRuntimeMessage>,
+ initialization_response: Option<ToServerMessage>,
/// The carrier's halves. Sending is shared with whoever else is on the
/// same connection; receiving is this actor's alone, which is why it can
/// be read with `&mut` and needs no lock.
@@ -122,6 +124,8 @@ where
);
Self {
+ initialization_request: None,
+ initialization_response: None,
outbound,
inbound,
handshake_seen,
@@ -129,7 +133,8 @@ where
machine: match acp_session_id {
None => SessionMachine::new(id, workspace, mcp_servers),
Some(session_id) => SessionMachine::resume(id, session_id, workspace, mcp_servers),
- },
+ }
+ .with_connection_context(macro_uuid::generate_uuid_v7()),
logs,
commands,
handshake_span: Some(handshake_span),
@@ -190,8 +195,8 @@ where
// A handshake somebody else ran. The machine ignores it unless it
// is still booting, which is what makes the session that ran the
// handshake ignore its own result coming back.
- Ok(()) = self.handshake_seen.changed() => match *self.handshake_seen.borrow_and_update() {
- HandshakeStatus::Ready(restore) => Input::Ready { restore },
+ Ok(()) = self.handshake_seen.changed() => match self.handshake_seen.borrow_and_update().clone() {
+ HandshakeStatus::ReadyWithContext { restore, context } => Input::SharedReady { restore, context },
// Nothing to act on yet, but the wait must resume.
HandshakeStatus::Pending | HandshakeStatus::InFlight => continue,
},
@@ -213,13 +218,17 @@ where
/// back in - so a `Complete` never fires for an action that was not sent,
/// and the machine (not this loop) decides what failure means.
pub(crate) async fn dispatch(&mut self, input: Input<SessionCompletion>) -> Stepped {
- let handshake_deadline = self.handshake_deadline;
+ let was_live = matches!(self.machine.status(), RuntimeStatus::Live { .. });
let mut handshake_span = self.handshake_span.clone();
let produced = match &handshake_span {
Some(span) => span.in_scope(|| self.machine.handle(input)),
None => self.machine.handle(input),
};
let mut effects = VecDeque::from(produced);
+ if was_live && matches!(self.machine.status(), RuntimeStatus::Handshaking) {
+ self.handshake_deadline = Instant::now() + HANDSHAKE_TIMEOUT;
+ }
+ let handshake_deadline = self.handshake_deadline;
self.finish_handshake_if_complete();
if self.handshake_span.is_none() {
handshake_span = None;
@@ -289,8 +298,23 @@ where
self.finish_handshake_if_complete();
}
}
- Effect::Log { message } => {
- let log = self.log(None, Message::ToServer(message));
+ Effect::Log { message, boundary } => {
+ if let Some(ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(
+ request,
+ )))) = &self.initialization_request
+ && let ToServerMessage::Acp(AcpMessage(frame)) = &message
+ && frame.response_id() == Some(&request.id)
+ {
+ self.initialization_response = Some(message.clone());
+ }
+ let log = self.logs.append_with_boundary(
+ AgentSessionLog {
+ agent_session_id: self.machine.id(),
+ user_id: None,
+ content: Message::ToServer(message),
+ },
+ boundary,
+ );
let (result, close_reason) = match handshake_span.as_ref() {
Some(span) => match tokio::time::timeout_at(
handshake_deadline,
@@ -326,6 +350,28 @@ where
self.finish_handshake_if_complete();
}
}
+ Effect::EstablishInitialization { context } => {
+ let establish = async {
+ let id = self
+ .logs
+ .append(AgentSessionLog {
+ agent_session_id: self.machine.id(),
+ user_id: None,
+ content: Message::ToRuntime(context.request.clone()),
+ })
+ .await?;
+ self.machine.initialization_persisted(id);
+ self.log(None, Message::ToServer(context.response.clone()))
+ .await
+ };
+ let result = tokio::time::timeout_at(handshake_deadline, establish)
+ .await
+ .unwrap_or_else(|_| Err(AgentSessionError::LogTimedOut(self.machine.id())));
+ if let Err(error) = result {
+ self.fail_remaining_completions(&mut effects, error);
+ effects.extend(self.machine.handle(Input::Closed(CloseReason::LogFailed)));
+ }
+ }
Effect::PersistAcpSession { session_id } => {
let result = tokio::time::timeout(
COMMAND_DELIVERY_TIMEOUT,
@@ -344,10 +390,22 @@ where
}
}
Effect::Initialized { restore } => {
- // Nothing waits on this today; a failed send would mean
- // every receiver is gone, which cannot happen while this
- // actor holds one.
- let _ = self.handshake.send(HandshakeStatus::Ready(restore));
+ let request = self
+ .initialization_request
+ .as_ref()
+ .expect("initialization request persisted before its response");
+ let response = self
+ .initialization_response
+ .as_ref()
+ .expect("Initialized follows logging the matching response");
+ // The actor retains a receiver, so publication cannot fail.
+ let _ = self.handshake.send(HandshakeStatus::ReadyWithContext {
+ restore,
+ context: std::sync::Arc::new(super::InitializationContext {
+ request: request.clone(),
+ response: response.clone(),
+ }),
+ });
}
Effect::TurnEnded { action_id } => {
tracing::info!(
@@ -420,7 +478,18 @@ where
tracing::Span::current().record("rpc.system.name", "jsonrpc");
tracing::Span::current().record("rpc.method", method);
}
- self.log(from, Message::ToRuntime(message.clone())).await?;
+ let id = self
+ .logs
+ .append(AgentSessionLog {
+ agent_session_id: self.machine.id(),
+ user_id: from,
+ content: Message::ToRuntime(message.clone()),
+ })
+ .await?;
+ if acp_method(&message) == Some("initialize") {
+ self.machine.initialization_persisted(id);
+ self.initialization_request = Some(message.clone());
+ }
self.outbound.send(message).await?;
Ok(())
}
@@ -437,6 +506,7 @@ where
content,
})
.await
+ .map(|_| ())
}
async fn persist_acp_session(&self, acp_session_id: SessionId) -> Result<()> {
@@ -484,6 +554,7 @@ where
effect @ Effect::Stop { .. } => stop = Some(effect),
Effect::Send { .. }
| Effect::Log { .. }
+ | Effect::EstablishInitialization { .. }
| Effect::PersistAcpSession { .. }
| Effect::Initialized { .. }
| Effect::TurnEnded { .. } => {}
diff --git a/crates/agent_session/src/domain/session/mod.rs b/crates/agent_session/src/domain/session/mod.rs
index d904e6752f..5eb2e3d175 100644
--- a/crates/agent_session/src/domain/session/mod.rs
+++ b/crates/agent_session/src/domain/session/mod.rs
@@ -12,5 +12,6 @@ mod tests;
pub use session::SessionMachine;
pub use types::{
- CloseReason, Effect, HandshakeStatus, Input, RuntimeStatus, SessionRestoreSupport, StopReason,
+ CloseReason, Effect, HandshakeStatus, InitializationContext, Input, RuntimeStatus,
+ SessionRestoreSupport, StopReason,
};
diff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rs
index bdb1437225..20643b4290 100644
--- a/crates/agent_session/src/domain/session/session.rs
+++ b/crates/agent_session/src/domain/session/session.rs
@@ -31,8 +31,10 @@ const INITIAL_REQUEST_NUM: u64 = 0;
/// See the [module docs](super) for scope and the sans-IO contract.
pub struct SessionMachine<Token> {
id: AgentSessionId,
+ initialization: Option<crate::domain::model::HistoryBoundary>,
phase: SessionPhase,
next_request: u64,
+ connection_context: Option<macro_uuid::Uuid>,
/// Held outside the phase so a partial flush strands nothing.
pending: VecDeque<PendingAction<Token>>,
/// The newest turn-occupying request the runtime has not answered yet.
@@ -43,6 +45,7 @@ pub struct SessionMachine<Token> {
/// [`Effect::TurnEnded`].
in_flight_turn: Option<(RequestId, AgentActionId)>,
resume_session_id: Option<SessionId>,
+ reload_required: bool,
/// Directory the agent works in, snapshotted on the session row at
/// creation; `session/new`, `session/resume`, and `session/load` all
/// carry it, so a reconnect re-enters the directory the session
@@ -59,11 +62,14 @@ impl<Token> SessionMachine<Token> {
pub fn new(id: AgentSessionId, workspace: String, mcp_servers: Vec<McpServer>) -> Self {
Self {
id,
+ initialization: None,
phase: SessionPhase::Booting,
next_request: INITIAL_REQUEST_NUM,
+ connection_context: None,
pending: VecDeque::new(),
in_flight_turn: None,
resume_session_id: None,
+ reload_required: false,
workspace,
mcp_servers,
}
@@ -78,11 +84,14 @@ impl<Token> SessionMachine<Token> {
) -> Self {
Self {
id,
+ initialization: None,
phase: SessionPhase::Booting,
next_request: INITIAL_REQUEST_NUM,
+ connection_context: None,
pending: VecDeque::new(),
in_flight_turn: None,
resume_session_id: Some(session_id),
+ reload_required: false,
workspace,
mcp_servers,
}
@@ -93,6 +102,19 @@ impl<Token> SessionMachine<Token> {
self.id
}
+ /// Namespace request IDs for a fresh actor on a potentially shared transport.
+ pub(crate) fn with_connection_context(mut self, context: macro_uuid::Uuid) -> Self {
+ self.connection_context = Some(context);
+ self
+ }
+
+ /// Retain the durable initialization identity for this actor's connection.
+ pub fn initialization_persisted(&mut self, id: macro_uuid::Uuid) {
+ self.initialization = Some(crate::domain::model::HistoryBoundary {
+ initialization_log_id: id,
+ });
+ }
+
/// Current phase.
pub fn status(&self) -> RuntimeStatus {
match &self.phase {
@@ -123,6 +145,14 @@ impl<Token> SessionMachine<Token> {
} => self.on_command(from, action, action_id, token),
Input::Inbound(message) => self.on_inbound(message),
Input::Ready { restore } => self.on_connection_ready(restore),
+ Input::SharedReady { restore, context } => {
+ if !matches!(self.phase, SessionPhase::Booting) {
+ return vec![];
+ }
+ let mut effects = vec![Effect::EstablishInitialization { context }];
+ self.begin_opening(restore, &mut effects);
+ effects
+ }
Input::Closed(reason) => self.on_closed(reason),
}
}
@@ -185,9 +215,27 @@ impl<Token> SessionMachine<Token> {
}
fn on_inbound(&mut self, message: ToServerMessage) -> Vec<Effect<Token>> {
+ // Host-local recovery is a command to this machine, not a user-facing
+ // runtime status or a history replacement frame.
+ if matches!(
+ message,
+ ToServerMessage::Event {
+ event: SystemEvent::ReloadRequired
+ }
+ ) {
+ let mut effects = Vec::new();
+ if !matches!(self.phase, SessionPhase::Dead) {
+ self.reload_required = true;
+ if self.in_flight_turn.is_none() {
+ self.begin_reload(&mut effects);
+ }
+ }
+ return effects;
+ }
// Every inbound message is logged, before anything reacts to it: the
// log stream is the session's history, not a digest of it.
let mut effects = vec![Effect::Log {
+ boundary: None,
message: message.clone(),
}];
@@ -211,6 +259,16 @@ impl<Token> SessionMachine<Token> {
effects
}
+ fn begin_reload(&mut self, effects: &mut Vec<Effect<Token>>) {
+ let SessionPhase::Live { session_id } = &self.phase else {
+ return;
+ };
+ self.resume_session_id = Some(session_id.clone());
+ self.initialization = None;
+ self.phase = SessionPhase::Booting;
+ self.begin_handshake(effects);
+ }
+
/// Ready starts initialization; actions remain queued until `session/new` completes.
fn begin_handshake(&mut self, effects: &mut Vec<Effect<Token>>) {
if !matches!(self.phase, SessionPhase::Booting) {
@@ -245,6 +303,9 @@ impl<Token> SessionMachine<Token> {
.take()
.expect("checked just above; nothing between the check and the take");
effects.push(Effect::TurnEnded { action_id });
+ if self.reload_required {
+ self.begin_reload(effects);
+ }
return;
}
self.respond_to_permission_request(&frame, effects);
@@ -292,12 +353,17 @@ impl<Token> SessionMachine<Token> {
// connection needs the same answer, and only this machine was told it.
effects.push(Effect::Initialized { restore });
self.begin_opening(restore, effects);
+ // The load about to start covers every recovery observed so far. A
+ // later signal while its reply is queued requires another load.
+ self.reload_required = false;
}
/// Ask the agent for this session, however it has to be established.
fn begin_opening(&mut self, restore: SessionRestoreSupport, effects: &mut Vec<Effect<Token>>) {
let opening = match self.resume_session_id.clone() {
- Some(session_id) if restore.resume => self.build_resume_session_request(session_id),
+ Some(session_id) if restore.resume && !self.reload_required => {
+ self.build_resume_session_request(session_id)
+ }
Some(session_id) if restore.load => self.build_load_session_request(session_id),
Some(_) => {
self.resume_unsupported(effects);
@@ -364,6 +430,15 @@ impl<Token> SessionMachine<Token> {
);
return;
}
+ let Some(initialization) = self.initialization else {
+ self.die(StopReason::InitializationNotPersisted, effects);
+ return;
+ };
+ // Only a matching, well-formed successful load selects history.
+ // The actor executes this log effect before any readiness side effect.
+ if let Some(Effect::Log { boundary, .. }) = effects.first_mut() {
+ *boundary = Some(initialization);
+ }
(session_id, false)
}
};
@@ -376,6 +451,10 @@ impl<Token> SessionMachine<Token> {
session_id: session_id.clone(),
});
}
+ if self.reload_required {
+ self.begin_reload(effects);
+ return;
+ }
self.flush(&session_id, effects);
}
@@ -572,7 +651,10 @@ impl<Token> SessionMachine<Token> {
/// carries the session, so sessions sharing one connection cannot collide
/// with each other either.
fn next_id(&mut self) -> RequestId {
- let id = RequestId::Str(format!("agent_session:{}:{}", self.id, self.next_request));
+ let id = RequestId::Str(match self.connection_context {
+ Some(context) => format!("agent_session:{}:{context}:{}", self.id, self.next_request),
+ None => format!("agent_session:{}:{}", self.id, self.next_request),
+ });
self.next_request += 1;
id
}
diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rs
index 4b2f28111d..74f0232054 100644
--- a/crates/agent_session/src/domain/session/tests.rs
+++ b/crates/agent_session/src/domain/session/tests.rs
@@ -148,6 +148,67 @@ fn a_command_while_booting_queues_silently() {
assert_eq!(machine.status(), RuntimeStatus::Booting);
}
+#[test]
+fn recovery_waits_for_prompt_then_loads_with_a_new_durable_boundary() {
+ for active in [false, true] {
+ let mut machine = machine();
+ begin_opening(&mut machine);
+ machine.handle(session_opened("cursor-session"));
+ machine.initialization_persisted(macro_uuid::generate_uuid_v7());
+ let prompt = if active {
+ Some(sent_request_ids(&machine.handle(command("current", 1)))[0].clone())
+ } else {
+ None
+ };
+ let mut effects = machine.handle(Input::Inbound(ToServerMessage::Event {
+ event: SystemEvent::ReloadRequired,
+ }));
+ if let Some(prompt) = prompt {
+ assert!(sent_methods(&effects).is_empty());
+ assert!(matches!(machine.status(), RuntimeStatus::Live { .. }));
+ effects = machine.handle(frame(RawJsonRpcMessage::response(
+ prompt,
+ Ok(serde_json::json!({"stopReason":"end_turn"})),
+ )));
+ assert!(
+ effects
+ .iter()
+ .any(|effect| matches!(effect, Effect::TurnEnded { .. }))
+ );
+ }
+ assert_eq!(sent_methods(&effects), ["initialize"]);
+ let initialize = sent_request_ids(&effects)[0].clone();
+ assert!(machine.handle(command("queued", 2)).is_empty());
+ let boundary = macro_uuid::generate_uuid_v7();
+ machine.initialization_persisted(boundary);
+ let response = InitializeResponse::new(PROTOCOL_VERSION).agent_capabilities(
+ AgentCapabilities::new()
+ .load_session(true)
+ .session_capabilities(
+ SessionCapabilities::new().resume(SessionResumeCapabilities::new()),
+ ),
+ );
+ let opening = machine.handle(frame(RawJsonRpcMessage::response(
+ initialize,
+ Ok(serde_json::to_value(response).unwrap()),
+ )));
+ assert_eq!(
+ sent_methods(&opening),
+ ["session/load"],
+ "recovery must not prefer generic resume"
+ );
+ let load = sent_request_ids(&opening)[0].clone();
+ let committed = machine.handle(frame(RawJsonRpcMessage::response(
+ load,
+ Ok(serde_json::json!({})),
+ )));
+ assert!(
+ matches!(&committed[0], Effect::Log { boundary: Some(selected), .. } if selected.initialization_log_id == boundary)
+ );
+ assert_eq!(sent_methods(&committed), ["session/prompt"]);
+ }
+}
+
#[test]
fn acp_ready_logs_then_sends_initialize() {
let mut machine = machine();
@@ -160,6 +221,36 @@ fn acp_ready_logs_then_sends_initialize() {
assert_eq!(machine.status(), RuntimeStatus::Handshaking);
}
+#[test]
+fn recovery_while_a_load_reply_is_queued_loads_again_before_dispatch() {
+ let mut machine = machine();
+ begin_opening(&mut machine);
+ machine.handle(session_opened("cursor-session"));
+ let requirement = || {
+ Input::Inbound(ToServerMessage::Event {
+ event: SystemEvent::ReloadRequired,
+ })
+ };
+ let initialize = sent_request_ids(&machine.handle(requirement()))[0].clone();
+ machine.initialization_persisted(macro_uuid::generate_uuid_v7());
+ let opening = machine.handle(frame(RawJsonRpcMessage::response(
+ initialize,
+ Ok(serde_json::to_value(
+ InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true)),
+ )
+ .unwrap()),
+ )));
+ assert!(machine.handle(requirement()).is_empty());
+ assert!(machine.handle(command("queued", 1)).is_empty());
+ let again = machine.handle(frame(RawJsonRpcMessage::response(
+ sent_request_ids(&opening)[0].clone(),
+ Ok(serde_json::json!({})),
+ )));
+ assert_eq!(sent_methods(&again), ["initialize"]);
+ assert_eq!(machine.pending_count(), 1);
+}
+
#[test]
fn initialize_success_sends_session_new() {
let mut machine = machine();
@@ -930,3 +1021,174 @@ fn the_handshake_result_is_announced_for_the_connection() {
})
);
}
+
+#[test]
+fn only_matching_successful_load_selects_its_connection_initialization() {
+ for resume in [false, true] {
+ let mut machine: SessionMachine<u32> = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".into(),
+ vec![],
+ );
+ machine.handle(acp_ready());
+ let initialization_log_id = macro_uuid::generate_uuid_v7();
+ machine.initialization_persisted(initialization_log_id);
+ let capabilities = if resume {
+ AgentCapabilities::new()
+ .load_session(true)
+ .session_capabilities(
+ SessionCapabilities::new().resume(SessionResumeCapabilities::new()),
+ )
+ } else {
+ AgentCapabilities::new().load_session(true)
+ };
+ machine.handle(initialized_with(
+ InitializeResponse::new(PROTOCOL_VERSION).agent_capabilities(capabilities),
+ ));
+ let unrelated = machine.handle(frame(RawJsonRpcMessage::response(
+ RequestId::Str("another-session:1".into()),
+ Ok(serde_json::json!({})),
+ )));
+ assert!(matches!(unrelated[0], Effect::Log { boundary: None, .. }));
+ let completed = machine.handle(frame(RawJsonRpcMessage::response(
+ request_id(1),
+ Ok(serde_json::json!({})),
+ )));
+ match &completed[0] {
+ Effect::Log { boundary, .. } => assert_eq!(
+ *boundary,
+ (!resume).then_some(crate::domain::model::HistoryBoundary {
+ initialization_log_id
+ })
+ ),
+ _ => panic!("response must be logged first"),
+ }
+ // Reused response IDs once live cannot select a boundary again.
+ let duplicate = machine.handle(frame(RawJsonRpcMessage::response(
+ request_id(1),
+ Ok(serde_json::json!({})),
+ )));
+ assert!(matches!(duplicate[0], Effect::Log { boundary: None, .. }));
+ }
+}
+
+#[test]
+fn failed_or_interrupted_load_never_selects_history() {
+ for response in [
+ Err(agent_client_protocol::Error::internal_error()),
+ Ok(serde_json::json!(false)),
+ ] {
+ let mut machine: SessionMachine<u32> = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".into(),
+ vec![],
+ );
+ machine.handle(acp_ready());
+ machine.initialization_persisted(macro_uuid::generate_uuid_v7());
+ machine.handle(initialized_with(
+ InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true)),
+ ));
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(request_id(1), response)));
+ assert!(matches!(effects[0], Effect::Log { boundary: None, .. }));
+ assert_eq!(machine.status(), RuntimeStatus::Dead);
+ }
+ let mut machine: SessionMachine<u32> = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".into(),
+ vec![],
+ );
+ machine.handle(acp_ready());
+ machine.initialization_persisted(macro_uuid::generate_uuid_v7());
+ machine.handle(initialized_with(
+ InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true)),
+ ));
+ machine.handle(Input::Closed(CloseReason::TransportClosed));
+ let late = machine.handle(frame(RawJsonRpcMessage::response(
+ request_id(1),
+ Ok(serde_json::json!({})),
+ )));
+ assert!(matches!(late[0], Effect::Log { boundary: None, .. }));
+}
+
+#[test]
+fn load_without_durable_initialization_cannot_become_live() {
+ let mut machine: SessionMachine<u32> = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".into(),
+ vec![],
+ );
+ machine.handle(acp_ready());
+ machine.handle(initialized_with(
+ InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true)),
+ ));
+ let effects = machine.handle(frame(RawJsonRpcMessage::response(
+ request_id(1),
+ Ok(serde_json::json!({})),
+ )));
+ assert!(matches!(
+ effects.as_slice(),
+ [
+ Effect::Log { boundary: None, .. },
+ Effect::Stop {
+ reason: StopReason::InitializationNotPersisted
+ }
+ ]
+ ));
+ assert_eq!(machine.status(), RuntimeStatus::Dead);
+}
+
+#[test]
+fn late_load_response_from_a_previous_actor_cannot_select_history() {
+ fn start() -> (SessionMachine<u32>, RequestId, macro_uuid::Uuid) {
+ let mut machine = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".into(),
+ vec![],
+ )
+ .with_connection_context(macro_uuid::generate_uuid_v7());
+ let initialization = macro_uuid::generate_uuid_v7();
+ machine.initialization_persisted(initialization);
+ let effects = machine.handle(Input::Ready {
+ restore: SessionRestoreSupport {
+ resume: false,
+ load: true,
+ },
+ });
+ let Effect::Send {
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))),
+ ..
+ } = &effects[0]
+ else {
+ panic!("load request")
+ };
+ let id = request.id.clone();
+ (machine, id, initialization)
+ }
+ let (_, old_id, _) = start();
+ let (mut current, new_id, initialization_log_id) = start();
+ assert_ne!(old_id, new_id);
+ let late = current.handle(frame(RawJsonRpcMessage::response(
+ old_id,
+ Ok(serde_json::json!({})),
+ )));
+ assert!(matches!(
+ late.as_slice(),
+ [Effect::Log { boundary: None, .. }]
+ ));
+ assert_eq!(current.status(), RuntimeStatus::Handshaking);
+ let completed = current.handle(frame(RawJsonRpcMessage::response(
+ new_id,
+ Ok(serde_json::json!({})),
+ )));
+ assert!(
+ matches!(completed[0], Effect::Log { boundary: Some(crate::domain::model::HistoryBoundary { initialization_log_id: id }), .. } if id == initialization_log_id)
+ );
+}
diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rs
index 02c0bfa203..0074b92551 100644
--- a/crates/agent_session/src/domain/session/types.rs
+++ b/crates/agent_session/src/domain/session/types.rs
@@ -6,6 +6,7 @@ use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessa
use macro_user_id::user_id::MacroUserIdStr;
use crate::domain::error::Result;
+use crate::domain::model::HistoryBoundary;
/// An action accepted before there was a live ACP session to send it through.
#[derive(Debug)]
@@ -48,8 +49,8 @@ pub(super) enum SessionOpening {
/// from the `initialize` response.
///
/// Only these two facts decide how a session opens, and one connection's
-/// answer serves every session on it - so this is what gets shared, rather
-/// than the protocol's whole capability set.
+/// answer serves every session on it. The handshake also retains its frames
+/// so each session can establish its own durable initialization context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionRestoreSupport {
/// The agent offers `session/resume`.
@@ -68,14 +69,19 @@ pub struct SessionRestoreSupport {
/// The states are a claim as much as a status: exactly one session may run
/// the handshake, so moving `Pending` to `InFlight` is how a session takes
/// that job and how every other session knows not to.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone)]
pub enum HandshakeStatus {
/// Nobody has started initializing this connection.
Pending,
/// A session is initializing it; the rest wait rather than initialize too.
InFlight,
- /// The connection is initialized and sessions may open.
- Ready(SessionRestoreSupport),
+ /// Durable handshake frames copied into each later session on this transport.
+ ReadyWithContext {
+ /// Negotiated restore support.
+ restore: SessionRestoreSupport,
+ /// Original initialize request and response, retained for this connection.
+ context: std::sync::Arc<InitializationContext>,
+ },
}
/// Observable phase of a session connection.
@@ -167,6 +173,13 @@ pub enum Input<Token> {
/// What that handshake learned about restoring sessions.
restore: SessionRestoreSupport,
},
+ /// A shared transport supplies the actual initialization frames to persist locally.
+ SharedReady {
+ /// Negotiated capabilities.
+ restore: SessionRestoreSupport,
+ /// Handshake from this transport.
+ context: std::sync::Arc<InitializationContext>,
+ },
/// The connection is over. Idempotent: a dead machine ignores it.
Closed(CloseReason),
}
@@ -182,9 +195,16 @@ pub enum Effect<Token> {
},
/// Persist an inbound message to the session's log stream.
Log {
+ /// Successful load history selection, committed with this frame.
+ boundary: Option<HistoryBoundary>,
/// The envelope to persist.
message: ToServerMessage,
},
+ /// Record a shared handshake in this session before opening it.
+ EstablishInitialization {
+ /// The connection's actual handshake frames.
+ context: std::sync::Arc<InitializationContext>,
+ },
/// Persist the ACP session id before allowing prompts onto the wire.
PersistAcpSession {
/// Agent-assigned session identifier.
@@ -230,6 +250,8 @@ pub enum StopReason {
/// The handshake could not even be serialized; the detail is the
/// serializer's.
HandshakeNotBuildable(String),
+ /// A load cannot become live without a durable initialization boundary.
+ InitializationNotPersisted,
/// The agent refused `initialize`.
InitializationRefused,
/// The agent answered `initialize` with an invalid response.
@@ -250,6 +272,9 @@ impl std::fmt::Display for StopReason {
Self::HandshakeNotBuildable(detail) => {
write!(formatter, "could not build the acp handshake: {detail}")
}
+ Self::InitializationNotPersisted => {
+ formatter.write_str("load has no durable initialization context")
+ }
Self::InitializationRefused => formatter.write_str("the agent refused initialize"),
Self::InitializationUnintelligible(detail) => {
write!(
@@ -270,3 +295,12 @@ impl std::fmt::Display for StopReason {
}
}
}
+
+/// Connection-level handshake that each session records before opening.
+#[derive(Debug, Clone)]
+pub struct InitializationContext {
+ /// Initialize request sent on this transport.
+ pub request: ToRuntimeMessage,
+ /// Its successful response.
+ pub response: ToServerMessage,
+}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index e843148a9a..9592e0f604 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -981,6 +981,8 @@ pub async fn put_agent_sandbox_size_handler<
/// decodes its own response type.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct AgentSessionLogEntryDto {
+ /// Durable transport row identity; together with `createdAt`, its order cursor.
+ pub id: Uuid,
/// When the log recorded the frame.
///
/// The frame itself carries no time, so this comes from the log row. It is
@@ -1035,6 +1037,7 @@ pub enum LogDirectionDto {
impl From<StoredAgentSessionLog> for AgentSessionLogEntryDto {
fn from(stored: StoredAgentSessionLog) -> Self {
Self {
+ id: stored.id,
created_at: stored.created_at,
user_id: stored.entry.user_id.map(|user| user.to_string()),
message: stored.entry.content,
@@ -1056,7 +1059,10 @@ pub struct AgentSessionLogResponse {
/// out who sent them: the sender of an agent message is this session's
/// bot, and nothing else names it.
pub bot: SessionBot,
- /// Every logged frame, oldest first. Folding depends on this order.
+ /// Effective history in ascending `(createdAt, id)` order.
+ /// The first row is the inclusive history boundary cursor: buffered rows
+ /// before it are obsolete. Reconcile snapshot overlap by row ID, never content.
+ /// An empty history has no boundary or overlapping rows.
pub entries: Vec<AgentSessionLogEntryDto>,
}
@@ -1075,9 +1081,9 @@ pub struct AgentSessionLogResponse {
)]
/// The raw protocol log of one agent session.
///
-/// Served unfolded, and whole: the fold is a left fold over the frames from
-/// the beginning, so a reader that skipped any of them would derive different
-/// turn numbering.
+/// Served unfolded from the latest successful load initialization, or the
+/// beginning when no load succeeded. Consumers stage load attempts so failed
+/// or interrupted replay does not become visible conversation content.
///
/// An unknown session is an error: the response has to name the session's
/// agent, and a session that never existed has none to name.
diff --git a/crates/agent_session/src/outbound/connection_gateway_realtime.rs b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
index c77dca727f..bb5a3d662f 100644
--- a/crates/agent_session/src/outbound/connection_gateway_realtime.rs
+++ b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
@@ -68,6 +68,8 @@ pub const AGENT_SESSION_QUEUE: &str = "agent_session_queue";
/// contract.
#[derive(Debug, Serialize)]
pub struct AgentSessionLogEvent {
+ /// Durable row identity, matching the GET log entry and breaking timestamp ties.
+ pub id: Uuid,
/// The session the frame belongs to, and half of the composite id its
/// folded messages are keyed by.
#[serde(rename = "agentSessionId")]
@@ -133,6 +135,7 @@ impl AgentSessionLogEvent {
#[must_use]
pub fn new(event: LogAppended) -> Self {
let StoredAgentSessionLog {
+ id,
created_at,
entry: AgentSessionLog {
user_id, content, ..
@@ -140,6 +143,7 @@ impl AgentSessionLogEvent {
} = event.entry;
Self {
+ id,
agent_session_id: event.agent_session_id.as_uuid(),
created_at,
user_id: user_id.map(|user| user.to_string()),
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index 81fe35074c..efbe79c7a2 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -97,6 +97,31 @@ fn parse_message(direction: &str, content: serde_json::Value) -> anyhow::Result<
}
}
+fn cursor_run_checkpoint(message: &Message) -> Option<String> {
+ let Message::ToServer(ToServerMessage::Acp(
+ agent_runtime_protocol::domain::schema::v0::AcpMessage(frame),
+ )) = message
+ else {
+ return None;
+ };
+ let value = serde_json::to_value(frame).ok()?;
+ if value.get("method")?.as_str()? != "session/update" {
+ return None;
+ }
+ let params = value.get("params")?;
+ let update = params.get("update")?;
+ if update.get("sessionUpdate")?.as_str()? != "agent_message_chunk"
+ || !update.get("content")?.get("text")?.as_str()?.is_empty()
+ {
+ return None;
+ }
+ params
+ .get("_meta")?
+ .get("macroCursorRunCheckpoint")?
+ .as_str()
+ .map(str::to_owned)
+}
+
struct AgentSessionRow {
id: Uuid,
name: String,
@@ -118,6 +143,7 @@ struct AgentSessionRow {
external_id: Option<String>,
external_name: Option<String>,
external_url: Option<String>,
+ external_last_run_id: Option<String>,
status: String,
status_event_name: Option<String>,
created_at: DateTime<Utc>,
@@ -158,6 +184,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {
external_id,
external_name: row.external_name,
external_url: row.external_url,
+ last_run_id: row.external_last_run_id,
}),
status,
created_at: row.created_at,
@@ -215,7 +242,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
AS "thread_channel_id?",
-- A row being created cannot have an external identity yet.
NULL::TEXT AS "external_provider?", NULL::TEXT AS "external_id?",
- NULL::TEXT AS "external_name?", NULL::TEXT AS "external_url?"
+ NULL::TEXT AS "external_name?", NULL::TEXT AS "external_url?",
+ NULL::TEXT AS "external_last_run_id?"
"#,
id.as_uuid(),
owner_id.as_ref(),
@@ -307,7 +335,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
- ext.external_name AS "external_name?", ext.external_url AS "external_url?"
+ ext.external_name AS "external_name?", ext.external_url AS "external_url?",
+ ext.last_run_id AS "external_last_run_id?"
FROM agent_session
LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id
WHERE id = $1
@@ -340,7 +369,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
- ext.external_name AS "external_name?", ext.external_url AS "external_url?"
+ ext.external_name AS "external_name?", ext.external_url AS "external_url?",
+ ext.last_run_id AS "external_last_run_id?"
FROM agent_session
LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id
WHERE egress_token_hash = $1
@@ -379,7 +409,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
- ext.external_name AS "external_name?", ext.external_url AS "external_url?"
+ ext.external_name AS "external_name?", ext.external_url AS "external_url?",
+ ext.last_run_id AS "external_last_run_id?"
FROM agent_session
LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id
WHERE thread_id = $1 AND bot_id = $2
@@ -411,7 +442,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?",
ext.provider AS "external_provider?", ext.external_id AS "external_id?",
- ext.external_name AS "external_name?", ext.external_url AS "external_url?"
+ ext.external_name AS "external_name?", ext.external_url AS "external_url?",
+ ext.last_run_id AS "external_last_run_id?"
FROM agent_session
LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id
WHERE thread_id = $1
@@ -640,6 +672,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
}
struct AgentSessionLogRow {
+ id: Uuid,
agent_session_id: Uuid,
user_id: Option<MacroUserIdStr<'static>>,
direction: String,
@@ -652,6 +685,7 @@ impl TryFrom<AgentSessionLogRow> for StoredAgentSessionLog {
fn try_from(row: AgentSessionLogRow) -> anyhow::Result<Self> {
Ok(Self {
+ id: row.id,
created_at: row.created_at,
entry: AgentSessionLog {
agent_session_id: AgentSessionId::new_from_uuid(row.agent_session_id),
@@ -694,7 +728,7 @@ impl ExternalSessionRepo for PgAgentSessionRepo {
async fn get(&self, id: AgentSessionId) -> Result<Option<ExternalSession>> {
let row = sqlx::query!(
r#"
- SELECT provider, external_id, external_name, external_url
+ SELECT provider, external_id, external_name, external_url, last_run_id
FROM external_agent_session
WHERE agent_session_id = $1
"#,
@@ -708,6 +742,7 @@ impl ExternalSessionRepo for PgAgentSessionRepo {
external_id: row.external_id,
external_name: row.external_name,
external_url: row.external_url,
+ last_run_id: row.last_run_id,
}))
}
@@ -738,13 +773,14 @@ impl AgentSessionLogRepo for PgAgentSessionRepo {
.begin()
.await
.context("begin agent session log create")?;
+ let id = macro_uuid::generate_uuid_v7();
let created_at = sqlx::query_scalar!(
r#"
INSERT INTO agent_session_log (id, agent_session_id, user_id, direction, content)
VALUES ($1, $2, $3, $4, $5)
RETURNING created_at
"#,
- macro_uuid::generate_uuid_v7(),
+ id,
log.agent_session_id.as_uuid(),
log.user_id.as_ref().map(|user_id| user_id.as_ref()),
direction,
@@ -779,6 +815,7 @@ impl AgentSessionLogRepo for PgAgentSessionRepo {
.context("commit agent session log create")?;
Ok(StoredAgentSessionLog {
+ id,
created_at,
entry: log,
})
@@ -789,45 +826,122 @@ impl AgentSessionLogRepo for PgAgentSessionRepo {
log: AgentSessionLog,
claim: &SessionClaim,
) -> Result<StoredAgentSessionLog> {
+ self.create_fenced_with_boundary(log, claim, None).await
+ }
+
+ async fn create_fenced_with_boundary(
+ &self,
+ log: AgentSessionLog,
+ claim: &SessionClaim,
+ boundary: Option<crate::domain::model::HistoryBoundary>,
+ ) -> Result<StoredAgentSessionLog> {
+ if claim.session != log.agent_session_id {
+ return Err(AgentSessionError::FencedOut(log.agent_session_id));
+ }
let event_status = match &log.content {
Message::ToServer(ToServerMessage::Event { event }) => {
Some(SessionStatus::Event(event.clone()))
}
_ => None,
};
+ let checkpoint = cursor_run_checkpoint(&log.content);
let (direction, content) = message_columns(&log.content)?;
let mut transaction = self
.pool
.begin()
.await
.context("begin fenced agent session log create")?;
- // The fencing contract: the guard and the append are one statement,
- // so there is no instant between "checked we still hold the lease"
- // and "wrote" for a takeover to slip into.
+
+ // Hold the session row through commit. A takeover updates this same
+ // row, so it cannot supersede the claim between our check and append.
+ let locked_session = sqlx::query_scalar!(
+ r#"
+ SELECT id
+ FROM agent_session
+ WHERE id = $1 AND manager_replica_id = $2 AND manager_fence = $3
+ FOR UPDATE
+ "#,
+ log.agent_session_id.as_uuid(),
+ claim.replica.as_uuid(),
+ claim.fence.0,
+ )
+ .fetch_optional(&mut *transaction)
+ .await
+ .context("lock fenced agent session")?;
+ if locked_session.is_none() {
+ return Err(AgentSessionError::FencedOut(log.agent_session_id));
+ }
+
+ let id = macro_uuid::generate_uuid_v7();
let created_at = sqlx::query_scalar!(
r#"
INSERT INTO agent_session_log (id, agent_session_id, user_id, direction, content)
- SELECT $1, $2, $3, $4, $5
- WHERE EXISTS (
- SELECT 1 FROM agent_session
- WHERE id = $2 AND manager_replica_id = $6 AND manager_fence = $7
- )
+ VALUES ($1, $2, $3, $4, $5)
RETURNING created_at
"#,
- macro_uuid::generate_uuid_v7(),
+ id,
log.agent_session_id.as_uuid(),
log.user_id.as_ref().map(|user_id| user_id.as_ref()),
direction,
content,
- claim.replica.as_uuid(),
- claim.fence.0,
)
- .fetch_optional(&mut *transaction)
+ .fetch_one(&mut *transaction)
.await
.context("failed to create fenced agent session log entry")?;
- let Some(created_at) = created_at else {
- return Err(AgentSessionError::FencedOut(log.agent_session_id));
- };
+
+ if let Some(boundary) = boundary {
+ let updated = sqlx::query!(
+ r#"
+ UPDATE agent_session AS session
+ SET history_start_log_id = boundary.id
+ FROM agent_session_log AS boundary
+ WHERE session.id = $1
+ AND session.manager_replica_id = $2 AND session.manager_fence = $3
+ AND boundary.id = $4 AND boundary.agent_session_id = session.id
+ AND (boundary.created_at, boundary.id) <= ($5, $6)
+ "#,
+ log.agent_session_id.as_uuid(),
+ claim.replica.as_uuid(),
+ claim.fence.0,
+ boundary.initialization_log_id,
+ created_at,
+ id,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("select successful load history boundary")?;
+ if updated.rows_affected() != 1 {
+ return Err(AgentSessionError::Handshake(
+ "invalid history boundary".into(),
+ ));
+ }
+ }
+
+ if let Some(run_id) = checkpoint {
+ let updated = sqlx::query!(
+ r#"
+ UPDATE external_agent_session AS external
+ SET last_run_id = $2,
+ updated_at = now()
+ FROM agent_session AS session
+ WHERE external.agent_session_id = $1
+ AND session.id = external.agent_session_id
+ AND session.manager_replica_id = $3
+ AND session.manager_fence = $4
+ AND external.provider = 'cursor'
+ "#,
+ log.agent_session_id.as_uuid(),
+ run_id,
+ claim.replica.as_uuid(),
+ claim.fence.0,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("checkpoint cursor run with fenced log entry")?;
+ if updated.rows_affected() == 0 {
+ return Err(AgentSessionError::FencedOut(log.agent_session_id));
+ }
+ }
if let Some(status) = event_status {
let (status, status_event_name) = status_columns(&status);
@@ -854,6 +968,7 @@ impl AgentSessionLogRepo for PgAgentSessionRepo {
.context("commit fenced agent session log create")?;
Ok(StoredAgentSessionLog {
+ id,
created_at,
entry: log,
})
@@ -867,14 +982,24 @@ impl AgentSessionLogRepo for PgAgentSessionRepo {
AgentSessionLogRow,
r#"
SELECT
- agent_session_id,
- user_id AS "user_id: MacroUserIdStr",
- direction,
- content,
- created_at
- FROM agent_session_log
- WHERE agent_session_id = $1
- ORDER BY created_at ASC, id ASC
+ log.id,
+ log.agent_session_id,
+ log.user_id AS "user_id: MacroUserIdStr",
+ log.direction,
+ log.content,
+ log.created_at
+ FROM agent_session_log AS log
+ WHERE log.agent_session_id = $1
+ AND (log.created_at, log.id) >= (
+ COALESCE((SELECT boundary.created_at
+ FROM agent_session AS session
+ JOIN agent_session_log AS boundary ON boundary.id = session.history_start_log_id
+ AND boundary.agent_session_id = session.id
+ WHERE session.id = $1), '-infinity'::timestamptz),
+ COALESCE((SELECT history_start_log_id FROM agent_session WHERE id = $1),
+ '00000000-0000-0000-0000-000000000000'::uuid)
+ )
+ ORDER BY log.created_at ASC, log.id ASC
"#,
agent_session_id.as_uuid(),
)
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index db1342d81d..140f9cc15c 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -844,6 +844,7 @@ fn cursor_external(agent: &str) -> ExternalSession {
external_id: agent.to_string(),
external_name: Some("Add README".to_string()),
external_url: Some(format!("https://cursor.com/agents/{agent}")),
+ last_run_id: None,
}
}
@@ -971,6 +972,27 @@ fn fenced_log(id: AgentSessionId) -> AgentSessionLog {
}
}
+fn cursor_checkpoint_log(id: AgentSessionId, run: &str) -> AgentSessionLog {
+ AgentSessionLog {
+ agent_session_id: id,
+ user_id: None,
+ content: Message::ToServer(ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::notification(
+ "session/update".to_owned(),
+ serde_json::json!({
+ "sessionId": "cursor-acp-1",
+ "update": {
+ "sessionUpdate": "agent_message_chunk",
+ "content": {"type": "text", "text": ""}
+ },
+ "_meta": {"macroCursorRunCheckpoint": run}
+ }),
+ )
+ .expect("valid checkpoint notification"),
+ ))),
+ }
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn claiming_is_reentrant_and_every_claim_bumps_the_fence(pool: PgPool) {
let repo = PgAgentSessionRepo::new(pool.clone());
@@ -1076,3 +1098,439 @@ async fn a_fenced_append_rejects_a_superseded_writer(pool: PgPool) {
"exactly the two live-holder appends are in the log"
);
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn cursor_checkpoint_advances_atomically_under_the_session_fence(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot_id = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot_id, None, None)).await;
+ ExternalSessionRepo::upsert(&repo, session.id, cursor_external("bc-1"))
+ .await
+ .expect("external row");
+ let zombie = ReplicaId::mint();
+ let successor = ReplicaId::mint();
+ let old_claim = claimed(repo.claim(session.id, zombie).await.expect("claim"));
+
+ repo.create_fenced(cursor_checkpoint_log(session.id, "run-1"), &old_claim)
+ .await
+ .expect("live checkpoint");
+ assert_eq!(
+ ExternalSessionRepo::get(&repo, session.id)
+ .await
+ .expect("get")
+ .and_then(|external| external.last_run_id),
+ Some("run-1".to_owned())
+ );
+
+ let_heartbeat_go_stale(&pool, zombie).await;
+ let new_claim = claimed(repo.claim(session.id, successor).await.expect("takeover"));
+ assert!(matches!(
+ repo.create_fenced(cursor_checkpoint_log(session.id, "run-stale"), &old_claim)
+ .await,
+ Err(AgentSessionError::FencedOut(_))
+ ));
+ repo.create_fenced(cursor_checkpoint_log(session.id, "run-2"), &new_claim)
+ .await
+ .expect("successor checkpoint");
+ assert_eq!(
+ ExternalSessionRepo::get(&repo, session.id)
+ .await
+ .expect("get")
+ .and_then(|external| external.last_run_id),
+ Some("run-2".to_owned())
+ );
+}
+
+/// Exercise the generic boundary contract without asking persistence to inspect ACP JSON.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn history_boundary_selects_initialization_and_keeps_raw_audit(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());
+ repo.create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ assert_eq!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ for expected_raw in [4_i64, 7] {
+ let init = repo
+ .create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ repo.create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ let response = repo
+ .create_fenced_with_boundary(
+ fenced_log(session.id),
+ &claim,
+ Some(crate::domain::model::HistoryBoundary {
+ initialization_log_id: init.id,
+ }),
+ )
+ .await
+ .unwrap();
+ let history = AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap();
+ assert_eq!(history.len(), 3);
+ assert_eq!(history[0].id, init.id);
+ assert_eq!(history[2].id, response.id);
+ let raw = sqlx::query_scalar!(
+ "SELECT count(*) FROM agent_session_log WHERE agent_session_id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(raw, Some(expected_raw));
+ }
+ // An ordinary append (including resume/error/disconnect) never changes the boundary.
+ repo.create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ assert_eq!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .len(),
+ 4
+ );
+ AgentSessionRepo::delete(&repo, session.id).await.unwrap();
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT count(*) FROM agent_session_log WHERE agent_session_id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn history_boundary_rejects_foreign_rows_and_stale_claims_atomically(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let other = create_session(&repo, new_session(bot, None, None)).await;
+ let replica = ReplicaId::mint();
+ let claim = claimed(repo.claim(session.id, replica).await.unwrap());
+ let foreign = AgentSessionLogRepo::create(&repo, fenced_log(other.id))
+ .await
+ .unwrap();
+ let boundary = crate::domain::model::HistoryBoundary {
+ initialization_log_id: foreign.id,
+ };
+ assert!(
+ repo.create_fenced_with_boundary(fenced_log(session.id), &claim, Some(boundary))
+ .await
+ .is_err()
+ );
+ assert!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ let init = repo
+ .create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ let current = claimed(repo.claim(session.id, replica).await.unwrap());
+ let boundary = crate::domain::model::HistoryBoundary {
+ initialization_log_id: init.id,
+ };
+ assert!(matches!(
+ repo.create_fenced_with_boundary(fenced_log(session.id), &claim, Some(boundary))
+ .await,
+ Err(AgentSessionError::FencedOut(_))
+ ));
+ assert!(
+ repo.create_fenced_with_boundary(fenced_log(other.id), &current, Some(boundary))
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT history_start_log_id FROM agent_session WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ None
+ );
+ // The FK also rejects a direct cross-session update.
+ assert!(
+ sqlx::query!(
+ "UPDATE agent_session SET history_start_log_id = $2 WHERE id = $1",
+ session.id.as_uuid(),
+ foreign.id
+ )
+ .execute(&pool)
+ .await
+ .is_err()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn history_boundary_update_failure_rolls_back_response(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());
+ let init = repo
+ .create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ sqlx::raw_sql("CREATE FUNCTION reject_history_boundary() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected boundary failure'; END $$; CREATE TRIGGER reject_history_boundary BEFORE UPDATE OF history_start_log_id ON agent_session FOR EACH ROW EXECUTE FUNCTION reject_history_boundary();").execute(&pool).await.unwrap();
+ assert!(
+ repo.create_fenced_with_boundary(
+ fenced_log(session.id),
+ &claim,
+ Some(crate::domain::model::HistoryBoundary {
+ initialization_log_id: init.id
+ })
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT history_start_log_id FROM agent_session WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ None
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn history_boundary_insert_failure_keeps_previous_selection(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());
+ let init = repo
+ .create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ let boundary = crate::domain::model::HistoryBoundary {
+ initialization_log_id: init.id,
+ };
+ repo.create_fenced_with_boundary(fenced_log(session.id), &claim, Some(boundary))
+ .await
+ .unwrap();
+ let next = repo
+ .create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ sqlx::raw_sql("CREATE FUNCTION reject_history_append() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected append failure'; END $$; CREATE TRIGGER reject_history_append BEFORE INSERT ON agent_session_log FOR EACH ROW EXECUTE FUNCTION reject_history_append();").execute(&pool).await.unwrap();
+ assert!(
+ repo.create_fenced_with_boundary(
+ fenced_log(session.id),
+ &claim,
+ Some(crate::domain::model::HistoryBoundary {
+ initialization_log_id: next.id
+ })
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT history_start_log_id FROM agent_session WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(init.id)
+ );
+ assert_eq!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .len(),
+ 3
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn history_boundary_readers_see_response_and_selection_together(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ let claim = claimed(repo.claim(session.id, ReplicaId::mint()).await.unwrap());
+ repo.create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ let init = repo
+ .create_fenced(fenced_log(session.id), &claim)
+ .await
+ .unwrap();
+ // Pause the update after the response INSERT, while its transaction is uncommitted.
+ let mut blocker = pool.begin().await.unwrap();
+ sqlx::query!("SELECT 1 AS ignored FROM pg_advisory_xact_lock(1987213841)")
+ .fetch_one(&mut *blocker)
+ .await
+ .unwrap();
+ sqlx::raw_sql("CREATE FUNCTION pause_history_boundary() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(1987213841); RETURN NEW; END $$; CREATE TRIGGER pause_history_boundary BEFORE UPDATE OF history_start_log_id ON agent_session FOR EACH ROW EXECUTE FUNCTION pause_history_boundary();").execute(&pool).await.unwrap();
+ let writer = repo.clone();
+ let task = tokio::spawn(async move {
+ writer
+ .create_fenced_with_boundary(
+ fenced_log(session.id),
+ &claim,
+ Some(crate::domain::model::HistoryBoundary {
+ initialization_log_id: init.id,
+ }),
+ )
+ .await
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(10), async {
+ loop {
+ let blocked = sqlx::query_scalar!("SELECT EXISTS(SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND objid = 1987213841 AND NOT granted)").fetch_one(&pool).await.unwrap();
+ if blocked == Some(true) { break; }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ }).await.expect("writer reached boundary update");
+ let before = AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap();
+ assert_eq!(before.len(), 2);
+ assert_eq!(before[1].id, init.id);
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT history_start_log_id FROM agent_session WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ None
+ );
+ blocker.commit().await.unwrap();
+ let response = task.await.unwrap().unwrap();
+ let after = AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap();
+ assert_eq!(after.len(), 2);
+ assert_eq!(after[0].id, init.id);
+ assert_eq!(after[1].id, response.id);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn history_boundary_range_uses_order_index_and_uuid_tie_break(pool: PgPool) {
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ let session = create_session(&repo, new_session(bot, None, None)).await;
+ // Equal timestamps force ordering and selection to use the UUID tie-break.
+ sqlx::query!(
+ "INSERT INTO agent_session_log (id, agent_session_id, direction, content, created_at) SELECT lpad(to_hex(n), 32, '0')::uuid, $1, 'to_server', $2, '2026-01-01'::timestamptz FROM generate_series(1, 10000) n",
+ session.id.as_uuid(),
+ serde_json::to_value(ToServerMessage::Event { event: SystemEvent::AcpReady }).unwrap(),
+ ).execute(&pool).await.unwrap();
+ let boundary = Uuid::from_u128(9900);
+ sqlx::query!(
+ "UPDATE agent_session SET history_start_log_id = $2 WHERE id = $1",
+ session.id.as_uuid(),
+ boundary
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql("ANALYZE agent_session_log; ANALYZE agent_session;")
+ .execute(&pool)
+ .await
+ .unwrap();
+ let history = AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap();
+ assert_eq!(history.len(), 101);
+ assert_eq!(history[0].id, boundary);
+ assert_eq!(history[100].id, Uuid::from_u128(10000));
+ // GET and realtime must carry the same authoritative row cursor, including
+ // the UUID tie-break when all timestamps are equal.
+ for stored in &history {
+ let dto = crate::inbound::axum_router::AgentSessionLogEntryDto::from(stored.clone());
+ let event = crate::outbound::connection_gateway_realtime::AgentSessionLogEvent::new(
+ crate::domain::model::LogAppended {
+ agent_session_id: session.id,
+ entry: stored.clone(),
+ },
+ );
+ let dto = serde_json::to_value(dto).unwrap();
+ let event = serde_json::to_value(event).unwrap();
+ assert_eq!(dto["id"], stored.id.to_string());
+ assert_eq!(dto["id"], event["id"]);
+ assert_eq!(dto["createdAt"], event["createdAt"]);
+ }
+
+ // Explain the production query itself so this check cannot drift from the reader.
+ let source = include_str!("../postgres.rs");
+ let query_start = source
+ .find(" SELECT\n log.id,")
+ .unwrap();
+ let query = source[query_start..].split("\"#,").next().unwrap();
+ let explain = format!("EXPLAIN (ANALYZE, FORMAT TEXT) {query}");
+ #[expect(
+ clippy::disallowed_methods,
+ reason = "EXPLAIN is built from the production query source to verify its actual plan"
+ )]
+ let plan: Vec<(String,)> = sqlx::query_as(&explain)
+ .bind(session.id.as_uuid())
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ let plan = plan
+ .into_iter()
+ .map(|(line,)| line)
+ .collect::<Vec<_>>()
+ .join("\n");
+ println!("{plan}");
+ assert!(plan.contains("agent_session_log_session_order"), "{plan}");
+ assert!(
+ plan.contains("Index Cond:") && plan.contains("ROW(created_at, id) >= ROW("),
+ "{plan}"
+ );
+ // NULL boundaries use the same indexed range, from the beginning.
+ sqlx::query!(
+ "UPDATE agent_session SET history_start_log_id = NULL WHERE id = $1",
+ session.id.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ AgentSessionLogRepo::list_by_session(&repo, session.id)
+ .await
+ .unwrap()
+ .len(),
+ 10000
+ );
+}
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index a48822588b..4f3cc7892e 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -34,9 +34,8 @@ type ReplicaRow = (std::time::Instant, Option<ReplicaAddress>);
/// An in-memory [`AgentSessionRepo`] and [`AgentSessionLogRepo`].
///
/// Cheap to clone - clones share one store, so a handle kept for assertions
-/// sees writes made through the copy under test. Log entries are returned in
-/// insertion order, which is the chronology the real repo gets from
-/// `ORDER BY created_at, id`.
+/// sees writes made through the copy under test. History uses the same
+/// `(created_at, id)` ordering and inclusive boundary as the PostgreSQL repo.
#[derive(Debug, Clone, Default)]
pub struct InMemoryAgentSessionRepo {
sessions: Arc<Mutex<HashMap<AgentSessionId, AgentSession>>>,
@@ -44,6 +43,8 @@ pub struct InMemoryAgentSessionRepo {
/// unique partial index the real table carries.
egress_token_hashes: Arc<Mutex<HashMap<String, AgentSessionId>>>,
logs: Arc<Mutex<HashMap<AgentSessionId, Vec<StoredAgentSessionLog>>>>,
+ log_transaction: Arc<Mutex<()>>,
+ history_boundaries: Arc<Mutex<HashMap<AgentSessionId, macro_uuid::Uuid>>>,
user_sizes: Arc<Mutex<HashMap<String, SandboxSize>>>,
log_reads: Arc<AtomicUsize>,
session_reads: Arc<AtomicUsize>,
@@ -102,6 +103,7 @@ impl InMemoryAgentSessionRepo {
logs.entry(entry.agent_session_id)
.or_default()
.push(StoredAgentSessionLog {
+ id: macro_uuid::generate_uuid_v7(),
created_at: chrono::Utc::now(),
entry,
});
@@ -323,6 +325,8 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
}
async fn delete(&self, id: AgentSessionId) -> Result<()> {
+ let _transaction = self.log_transaction.lock().unwrap();
+ self.history_boundaries.lock().unwrap().remove(&id);
self.sessions
.lock()
.expect("in-memory session store is not poisoned")
@@ -428,8 +432,8 @@ impl SessionOwnership for InMemoryAgentSessionRepo {
}
}
-impl AgentSessionLogRepo for InMemoryAgentSessionRepo {
- async fn create(&self, log: AgentSessionLog) -> Result<StoredAgentSessionLog> {
+impl InMemoryAgentSessionRepo {
+ fn create_log(&self, log: AgentSessionLog) -> Result<StoredAgentSessionLog> {
let model_change = match &log.content {
crate::domain::model::Message::ToRuntime(message) => {
agent_runtime_protocol::domain::action::AgentSetModelAction::from_runtime(message)
@@ -444,6 +448,7 @@ impl AgentSessionLogRepo for InMemoryAgentSessionRepo {
};
let session_id = log.agent_session_id;
let stored = StoredAgentSessionLog {
+ id: macro_uuid::generate_uuid_v7(),
created_at: chrono::Utc::now(),
entry: log,
};
@@ -476,27 +481,66 @@ impl AgentSessionLogRepo for InMemoryAgentSessionRepo {
}
Ok(stored)
}
+}
+
+impl AgentSessionLogRepo for InMemoryAgentSessionRepo {
+ async fn create(&self, log: AgentSessionLog) -> Result<StoredAgentSessionLog> {
+ let _transaction = self.log_transaction.lock().unwrap();
+ self.create_log(log)
+ }
async fn create_fenced(
&self,
log: AgentSessionLog,
claim: &SessionClaim,
) -> Result<StoredAgentSessionLog> {
- let fenced_out = {
- let leases = self
- .leases
- .lock()
- .expect("in-memory lease store is not poisoned");
- !matches!(
- leases.get(&log.agent_session_id),
- Some((holder, fence))
+ self.create_fenced_with_boundary(log, claim, None).await
+ }
+
+ async fn create_fenced_with_boundary(
+ &self,
+ log: AgentSessionLog,
+ claim: &SessionClaim,
+ boundary: Option<crate::domain::model::HistoryBoundary>,
+ ) -> Result<StoredAgentSessionLog> {
+ let _transaction = self.log_transaction.lock().unwrap();
+ let leases = self.leases.lock().unwrap();
+ if claim.session != log.agent_session_id
+ || !matches!(
+ leases.get(&log.agent_session_id), Some((holder, fence))
if *holder == Some(claim.replica) && *fence == claim.fence.0
)
- };
- if fenced_out {
+ {
return Err(AgentSessionError::FencedOut(log.agent_session_id));
}
- AgentSessionLogRepo::create(self, log).await
+ if !self
+ .sessions
+ .lock()
+ .unwrap()
+ .contains_key(&log.agent_session_id)
+ {
+ return Err(AgentSessionError::FencedOut(log.agent_session_id));
+ }
+ if let Some(boundary) = boundary {
+ let logs = self.logs.lock().unwrap();
+ if !logs.get(&log.agent_session_id).is_some_and(|rows| {
+ rows.iter()
+ .any(|row| row.id == boundary.initialization_log_id)
+ }) {
+ return Err(AgentSessionError::Handshake(
+ "invalid history boundary".into(),
+ ));
+ }
+ }
+ let session = log.agent_session_id;
+ let stored = self.create_log(log)?;
+ if let Some(boundary) = boundary {
+ self.history_boundaries
+ .lock()
+ .unwrap()
+ .insert(session, boundary.initialization_log_id);
+ }
+ Ok(stored)
}
async fn list_by_session(
@@ -504,13 +548,20 @@ impl AgentSessionLogRepo for InMemoryAgentSessionRepo {
agent_session_id: AgentSessionId,
) -> Result<Vec<StoredAgentSessionLog>> {
self.log_reads.fetch_add(1, Ordering::Relaxed);
- Ok(self
- .logs
+ let _transaction = self.log_transaction.lock().unwrap();
+ let logs = self.logs.lock().unwrap();
+ let mut rows = logs.get(&agent_session_id).cloned().unwrap_or_default();
+ rows.sort_unstable_by_key(|row| (row.created_at, row.id));
+ let boundary = self
+ .history_boundaries
.lock()
- .expect("in-memory log store is not poisoned")
+ .unwrap()
.get(&agent_session_id)
- .cloned()
- .unwrap_or_default())
+ .copied();
+ let start = boundary
+ .and_then(|id| rows.iter().position(|row| row.id == id))
+ .unwrap_or(0);
+ Ok(rows.into_iter().skip(start).collect())
}
}
@@ -611,3 +662,6 @@ impl AgentSessionRealtime for RecordingRealtime {
Ok(())
}
}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/agent_session/src/testing/test.rs b/crates/agent_session/src/testing/test.rs
new file mode 100644
index 0000000000..578d40b52f
--- /dev/null
+++ b/crates/agent_session/src/testing/test.rs
@@ -0,0 +1,63 @@
+use super::*;
+use crate::domain::model::Message;
+use agent_runtime_protocol::domain::schema::v0::SystemEvent;
+
+#[tokio::test]
+async fn effective_history_orders_timestamps_and_uuid_ties_before_selecting_boundary() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let session = AgentSessionId::new();
+ let other = AgentSessionId::new();
+ let time = chrono::Utc::now();
+ let row = |id, seconds| StoredAgentSessionLog {
+ id: Uuid::from_u128(id),
+ created_at: time + chrono::Duration::seconds(seconds),
+ entry: AgentSessionLog {
+ agent_session_id: session,
+ user_id: None,
+ content: Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ }),
+ },
+ };
+ // Intentionally scrambled insertion order and UUIDs contrary to timestamp order.
+ repo.logs
+ .lock()
+ .unwrap()
+ .insert(session, vec![row(1, 2), row(4, 1), row(5, 0), row(3, 1)]);
+ repo.history_boundaries
+ .lock()
+ .unwrap()
+ .insert(other, Uuid::from_u128(4));
+ let ids = |rows: Vec<StoredAgentSessionLog>| {
+ rows.into_iter()
+ .map(|row| row.id.as_u128())
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(
+ ids(AgentSessionLogRepo::list_by_session(&repo, session)
+ .await
+ .unwrap()),
+ vec![5, 3, 4, 1]
+ );
+ repo.history_boundaries
+ .lock()
+ .unwrap()
+ .insert(session, Uuid::from_u128(4));
+ assert_eq!(
+ ids(AgentSessionLogRepo::list_by_session(&repo, session)
+ .await
+ .unwrap()),
+ vec![4, 1]
+ );
+ assert!(
+ AgentSessionLogRepo::list_by_session(&repo, other)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ repo.logs.lock().unwrap()[&session].len(),
+ 4,
+ "selection retains raw rows"
+ );
+}
diff --git a/crates/cursor_cloud_agents/Cargo.toml b/crates/cursor_cloud_agents/Cargo.toml
index 2567409739..9c82c9daaa 100644
--- a/crates/cursor_cloud_agents/Cargo.toml
+++ b/crates/cursor_cloud_agents/Cargo.toml
@@ -5,7 +5,8 @@ publish = false
version = "0.1.0"
[features]
-default = []
+default = ["postgres"]
+postgres = ["dep:agent_session"]
# In-memory port implementations and recorded fixtures, for crates that test
# against this one.
test-utils = []
@@ -14,6 +15,10 @@ test-utils = []
name = "cursor_cloud_agents"
[dependencies]
+agent_session = { path = "../agent_session", optional = true }
+agent_runtime_protocol = { path = "../agent_runtime_protocol", default-features = false }
+sqlx = { workspace = true }
+uuid = { workspace = true }
agent-client-protocol = { workspace = true }
futures = { workspace = true }
macro_env_var = { path = "../macro_env_var" }
@@ -38,5 +43,6 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
zeroize = { workspace = true }
[dev-dependencies]
+agent_fold = { path = "../agent_fold", default-features = false, features = ["test-utils"] }
insta = { version = "1.48.0", features = ["glob", "json"] }
tokio = { workspace = true, features = ["io-std", "io-util", "sync", "time", "test-util"] }
diff --git a/crates/cursor_cloud_agents/REPLAY.md b/crates/cursor_cloud_agents/REPLAY.md
new file mode 100644
index 0000000000..4e6bc6f354
--- /dev/null
+++ b/crates/cursor_cloud_agents/REPLAY.md
@@ -0,0 +1,40 @@
+# Cursor native journal and load
+
+The hosted Cursor adapter requires PostgreSQL journal storage. The harness supplies the authorized Macro session ID and its own replica ID. Before the actor starts, attachment activation binds the journal to the exact acquired session claim, including its management fence. Unactivated access and rebinding to another generation fail. Every read and append verifies that supplied fence while locking the session row. No new raw-history endpoint or provider-identity mapping is introduced. The standalone stdio binary uses an explicit process-local journal and cannot restore a previous process's sessions.
+
+`cursor_journal_input` orders inputs by `(agent_session_id, sequence)` and associates runs by the existing provider's run IDs. A prompt is recorded before execution; `PromptAccepted` links that original content sequence to the returned run. Raw SSE event names, original joined data text, provider IDs, polling response bodies, transport errors, local terminal decisions, and reconciliation markers are retained. Unknown SSE data is retained even when it cannot be decoded. There is no second ACP transcript here.
+
+Prompt intent sequence preserves pre-execution audit order. Accepted prompts are projected immediately before the run's first native observation, after older-run recovery, rather than at their intent or acceptance position. An accepted run with no observations stays deferred while an older captured tail remains unfinished; recovery publishes its prompt when it reaches that run. Cancellation state is established before pre-prompt recovery and remains effective after that recovery completes.
+
+All emitting paths use the same replay machine after append. Poll results reconcile against the captured final step's text, appending only its missing suffix. Cursor's `step-started` records distinguish final-answer text from earlier commentary. Divergent text fails rather than guessing an overlap. Completed runs are not ingested again. Reopening a partial stream verifies its captured content prefix before appending new content; status/heartbeat/error records are connection observations and do not participate in prefix matching. No `Last-Event-ID` request header is sent: provider IDs are retained, but remote resume support is not assumed.
+
+Foreign recovery captures its batch without publishing replacement frames. After validating that the captured history can be reconstructed, a typed host-local requirement asks the session domain to initiate `initialize` and standard `session/load` after any dispatched prompt responds. A pending-reload bit pauses only background capture until load completes, not prompts already dispatched by the host. Pending commands wait behind that handshake. Recovery discovered while a load response is queued triggers another load before commands are flushed. The requirement is not a durable status, an agent-initiated client request, or a second replacement protocol. Only a valid successful load commits full history; failed or incomplete loads preserve the selected window. Original user chunks and terminal facts are reconstructed from the journal, including cancelled prompts, without restoring a pending request over replacement history. Standalone clients without the host channel can retrieve captured recovery on their next standard load.
+
+Completed native turns emit the optional, agent-neutral `_session/turn_complete` notification after their reconstructed updates, with a finished, cancelled, or failed outcome. The generic fold maps that fact to its existing stop vocabulary. A partial replay tail has no terminal fact and remains open; subsequent recovery emits its completion when the provider finishes. Correlated live prompt responses remain authoritative. This extension does not certify loads: ordinary valid ACP load success still replaces history, including an empty replacement, and failed loads still discard their candidate.
+
+Load holds the session turn gate, validates and replays a stable journal snapshot with fresh translation state, and retains that state for continuation. The ACP adapter queues the load response before releasing the gate and enabling synchronization. Journal failures stop readiness and cannot be masked by cancellation. The delivered-run watermark remains separate: its existing ACP marker still goes through the host's fenced append/checkpoint transaction, only after notifications have been queued.
+
+## Recovery and rollout limits
+
+A session without complete journal history is hydrated by listing every provider run and fetching each native stream in chronological order. Every run must include its original user message and a terminal result. Hydration is capture-only until all history validates. Final-answer-only records, expired/truncated streams, prefix mismatches, missing user prompts, and unavailable history cause an explicit load error, preserving the committed projection. They never publish a successful incomplete replacement. Hydration performs reads only, never prompt or tool execution.
+
+There is no compatibility interpretation for historical lookup-only load successes: every valid correlated ACP load success replaces history, even with no replay frames. The consolidated migration does not create or backfill the unused `agent_session_log.legacy_load` column.
+
+A process loss between remote prompt acceptance and persisting the accepted run association can leave an unresolved prompt intent. Without a proven association, load fails explicitly instead of executing that prompt again or dropping its history. Likewise, a foreign run observed only by polling cannot later claim to contain its unavailable original prompt. Operators should retain old Macro history; this migration does not manufacture or backfill missing provider details from ACP frames.
+
+Apply the SQLx-generated `20260906060601_cursor_session_replay` migration and prepare SQLx metadata from the repository root before deploying. It adds the delivered-run watermark, session history boundary, and native journal in dependency order. No changes to provider resume negotiation are required. Cursor advertises ACP load only. The generic session/fold layers own successful-load history selection and failed-load staging. A realtime `replace` event means replay has committed while the client is connected, not that a new live turn has started.
+
+### Previously applied PR migrations
+
+PR #6233 consolidated these unreleased migrations into one UP/DOWN pair:
+
+- `20260905234752_cursor_run_watermark`
+- `20260906040138_agent_session_history_boundary`
+- `20260906040140_cursor_native_journal`
+- `20260906042344_agent_session_legacy_load_context`
+
+Fresh environments use the consolidated migration normally. For local environments that already applied the old files, do not reset the database or run their DOWN migrations: that would discard journal inputs and checkpoint values. Back up the database and inspect each database's `_sqlx_migrations` history, including test databases, before changing anything.
+
+For a database with all four old migrations successfully applied, verify their checksums against the old PR revision and compare its columns, defaults, constraints, and indexes with a fresh consolidated schema (excluding only `legacy_load`). In one transaction, lock the migration metadata and affected tables, capture row counts and content hashes, drop only the unused `legacy_load` column without CASCADE, verify the schema and retained data again, then replace exactly those four metadata rows with the consolidated UP version, description, and SHA-384 checksum. Preserve all unrelated migration records. Abort on any mismatch. Check `sqlx migrate run` afterward; it should be a no-op. Do not stamp a partially applied or divergent schema as migrated; finish and verify its missing schema changes first under a separately reviewed procedure.
+
+The combined DOWN is for deliberate rollback only: it drops the new journal and checkpoint columns. Test DOWN/UP on an isolated disposable database, never on an existing session database whose history must survive. This local reconciliation procedure is not an instruction to rewrite production migration history.
diff --git a/crates/cursor_cloud_agents/src/api.rs b/crates/cursor_cloud_agents/src/api.rs
index 8e4e30f808..71595ecf64 100644
--- a/crates/cursor_cloud_agents/src/api.rs
+++ b/crates/cursor_cloud_agents/src/api.rs
@@ -3,8 +3,8 @@
//! A plain reqwest wrapper over `api.cursor.com`'s Cloud Agents API — create
//! an agent, follow up with runs, cancel, and stream a run's SSE events. It
//! knows nothing about ACP; it implements the domain's
-//! [`CursorAgents`]/[`RunStream`] ports and speaks the domain's
-//! [`CursorEvent`] vocabulary at its boundary.
+//! [`CursorAgents`]/[`RunStream`] ports, retaining native SSE records for
+//! capture before the domain decodes them.
//!
//! Authentication is HTTP Basic with the API key as username and an empty
//! password, per Cursor's docs. The key is validated for shape at
@@ -24,12 +24,11 @@ use crate::api::record::SseRecording;
use crate::api::wire::{
AgentSummary, ArchiveAgentResponse, CreateAgentRequest, CreateAgentResponse, CreateRunRequest,
CreateRunResponse, ListAgentsResponse, ListModelsResponse, ListRunsResponse,
- McpServerSelection, MeResponse, ModelSelection, PromptBody, RepoSelection, RunDetail,
+ McpServerSelection, MeResponse, ModelSelection, PromptBody, RepoSelection,
};
-use crate::domain::event::CursorEvent;
use crate::domain::model::{
CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, ModelParam, ModelVariant,
- RepoUrl, RunListing, RunOutcome,
+ RepoUrl, RunListing,
};
use crate::domain::ports::{CursorAgents, RunStream};
use futures::{Stream, StreamExt as _};
@@ -208,6 +207,14 @@ impl CursorClient {
.await
.map_err(|error| rootcause::report!(error))?;
if !status.is_success() {
+ if status.is_client_error() && status != reqwest::StatusCode::REQUEST_TIMEOUT {
+ return Err(
+ rootcause::report!(crate::domain::error::PromptRejected(format!(
+ "cursor POST {path} -> {status}: {text}"
+ )))
+ .into_dynamic(),
+ );
+ }
return Err(rootcause::report!("cursor POST {path} -> {status}: {text}"));
}
serde_json::from_str(&text)
@@ -289,6 +296,28 @@ impl CursorClient {
}
impl CursorAgents for CursorClient {
+ async fn raw_result(
+ &self,
+ agent: &CursorAgentId,
+ run: &CursorRunId,
+ ) -> Result<String, rootcause::Report> {
+ let response = self
+ .http
+ .get(self.url(&format!("/v1/agents/{agent}/runs/{run}")))
+ .basic_auth(self.config.api_key.expose(), Some(""))
+ .send()
+ .await
+ .map_err(|e| rootcause::report!(e))?;
+ let status = response.status();
+ let text = response.text().await.map_err(|e| rootcause::report!(e))?;
+ if !status.is_success() {
+ return Err(rootcause::report!(
+ "Cursor run poll failed: {status}: {text}"
+ ));
+ }
+ Ok(text)
+ }
+
#[tracing::instrument(skip_all, err, fields(mcp_servers = mcp_servers.len()))]
async fn create_agent(
&self,
@@ -383,35 +412,60 @@ impl CursorAgents for CursorClient {
}
#[tracing::instrument(skip(self), err)]
- async fn run_result(
+ async fn list_runs(
&self,
agent: &CursorAgentId,
- run: &CursorRunId,
- ) -> Result<RunOutcome, rootcause::Report> {
- let detail: RunDetail = self
- .get_json(&format!("/v1/agents/{agent}/runs/{run}"))
- .await?;
- Ok(RunOutcome {
- status: detail.status,
- text: detail.result,
- })
- }
-
- #[tracing::instrument(skip(self), err)]
- async fn list_runs(&self, agent: &CursorAgentId) -> Result<Vec<RunListing>, rootcause::Report> {
- // One page is plenty: the caller walks back only to the last run it
- // drove itself, which is at most one cursor.com visit ago.
- let page: ListRunsResponse = self
- .get_json(&format!("/v1/agents/{agent}/runs?limit=20"))
- .await?;
- Ok(page
- .items
- .into_iter()
- .map(|item| RunListing {
+ through: Option<&CursorRunId>,
+ ) -> Result<Vec<RunListing>, rootcause::Report> {
+ let mut listings = Vec::new();
+ let mut cursor = None;
+ let mut seen_cursors = std::collections::HashSet::new();
+ loop {
+ let mut request = self
+ .http
+ .get(self.url(&format!("/v1/agents/{agent}/runs")))
+ .basic_auth(self.config.api_key.expose(), Some(""))
+ .query(&[("limit", "100")]);
+ if let Some(cursor) = cursor.as_deref() {
+ request = request.query(&[("cursor", cursor)]);
+ }
+ let response = request
+ .send()
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ let status = response.status();
+ let text = response
+ .text()
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ if !status.is_success() {
+ return Err(rootcause::report!(
+ "cursor GET /v1/agents/{agent}/runs -> {status}: {text}"
+ ));
+ }
+ let page: ListRunsResponse = serde_json::from_str(&text).map_err(|error| {
+ rootcause::report!("cursor run list: bad response body: {error}")
+ })?;
+ let reached = through
+ .is_some_and(|through| page.items.iter().any(|item| item.id == through.as_str()));
+ listings.extend(page.items.into_iter().map(|item| RunListing {
id: CursorRunId::new(item.id),
status: item.status,
- })
- .collect())
+ }));
+ if reached {
+ break;
+ }
+ let Some(next) = page.next_cursor else {
+ break;
+ };
+ if !seen_cursors.insert(next.clone()) {
+ return Err(rootcause::report!(
+ "cursor run list repeated pagination cursor"
+ ));
+ }
+ cursor = Some(next);
+ }
+ Ok(listings)
}
}
@@ -424,69 +478,29 @@ const STREAM_CONNECT_ATTEMPTS: usize = 5;
const STREAM_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(400);
impl RunStream for CursorClient {
- async fn stream(
+ async fn raw_stream(
&self,
agent: &CursorAgentId,
run: &CursorRunId,
- ) -> Result<impl Stream<Item = Result<CursorEvent, rootcause::Report>> + Send, rootcause::Report>
- {
- // A stream opened right after `POST …/runs` can answer
- // `stream_unavailable` before the run's stream is provisioned —
- // observed on follow-up runs, whose create-to-stream gap is much
- // shorter than a first run's, and in both shapes the endpoint uses:
- // a 200 whose first event is an `error`, and an outright 409. The
- // run itself is fine (it finishes server-side), so an unavailable
- // stream at the head is a reason to reconnect, not to fail the turn.
- // Only the head: the same error after real events means the stream
- // genuinely went away.
- let mut attempt = 1;
- loop {
- let mut stream = match self.connect_stream(agent, run).await {
- Ok(stream) => Box::pin(stream),
- Err(StreamConnectError::Unavailable(message))
- if attempt < STREAM_CONNECT_ATTEMPTS =>
- {
- tracing::info!(%agent, %run, attempt, %message, "run stream not up yet; reconnecting");
- attempt += 1;
- tokio::time::sleep(STREAM_RETRY_DELAY).await;
- continue;
+ ) -> Result<
+ impl Stream<Item = Result<crate::domain::journal::NativeRecord, rootcause::Report>> + Send,
+ rootcause::Report,
+ > {
+ // Only retry failed HTTP connects. Successful SSE records, including
+ // stream_unavailable, must reach the domain journal before inspection.
+ for attempt in 1..=STREAM_CONNECT_ATTEMPTS {
+ match self.connect_stream(agent, run).await {
+ Ok(stream) => return Ok(stream),
+ Err(StreamConnectError::Unavailable(_)) if attempt < STREAM_CONNECT_ATTEMPTS => {
+ tokio::time::sleep(STREAM_RETRY_DELAY).await
}
Err(StreamConnectError::Unavailable(message)) => {
- return Err(rootcause::report!(
- "cursor stream unavailable after {STREAM_CONNECT_ATTEMPTS} connects: {message}"
- ));
- }
- Err(StreamConnectError::Other(report)) => return Err(report),
- };
- let mut leading = Vec::new();
- let retry = loop {
- match stream.next().await {
- Some(Ok(event @ (CursorEvent::Status { .. } | CursorEvent::Heartbeat))) => {
- leading.push(Ok(event));
- }
- Some(Ok(CursorEvent::Error { code, message }))
- if code.as_deref() == Some("stream_unavailable")
- && attempt < STREAM_CONNECT_ATTEMPTS =>
- {
- tracing::info!(%agent, %run, attempt, %message, "run stream not up yet; reconnecting");
- break true;
- }
- Some(event) => {
- leading.push(event);
- break false;
- }
- None => break false,
+ return Err(rootcause::report!("Cursor stream unavailable: {message}"));
}
- };
- if retry {
- attempt += 1;
- tokio::time::sleep(STREAM_RETRY_DELAY).await;
- continue;
+ Err(StreamConnectError::Other(error)) => return Err(error),
}
- // The buffered head replays before the live remainder, so the
- // caller sees one uninterrupted stream.
- return Ok(futures::stream::iter(leading).chain(stream));
}
+ unreachable!("connect attempts are nonzero")
}
}
@@ -506,7 +520,9 @@ impl CursorClient {
agent: &CursorAgentId,
run: &CursorRunId,
) -> Result<
- impl Stream<Item = Result<CursorEvent, rootcause::Report>> + Send + use<>,
+ impl Stream<Item = Result<crate::domain::journal::NativeRecord, rootcause::Report>>
+ + Send
+ + use<>,
StreamConnectError,
> {
let response = self
@@ -550,7 +566,7 @@ impl CursorClient {
|(mut bytes, mut decoder, mut pending, mut recording)| async move {
loop {
if let Some(event) = pending.pop_front() {
- return Ok(Some((event, (bytes, decoder, pending, recording))));
+ return Ok(Some((event?, (bytes, decoder, pending, recording))));
}
match bytes.next().await {
Some(Ok(chunk)) => {
@@ -560,18 +576,27 @@ impl CursorClient {
// A payload past the limit is the run's
// problem, not this stream's shape: report it
// and stop rather than resync mid-record.
- let record = record.map_err(|error| {
- rootcause::report!(
- "cursor sse payload over {} bytes: {error}",
- MAX_SSE_PAYLOAD
- )
- })?;
+ let record = match record {
+ Ok(record) => record,
+ Err(error) => {
+ // Deliver every earlier complete record
+ // in this chunk before the decoder error.
+ pending.push_back(Err(rootcause::report!(
+ "cursor sse payload over {} bytes: {error}",
+ MAX_SSE_PAYLOAD
+ )
+ .into_dynamic()));
+ break;
+ }
+ };
let SseEvent::Message(message) = record else {
continue; // `retry:`; nothing reconnects yet
};
- let data = serde_json::from_str(&message.data)
- .unwrap_or(serde_json::Value::Null);
- pending.push_back(CursorEvent::from_wire(&message.event, data));
+ pending.push_back(Ok(crate::domain::journal::NativeRecord {
+ event: message.event.into_owned(),
+ data: message.data,
+ id: message.last_event_id.map(|id| id.to_string()),
+ }));
}
}
Some(Err(error)) => {
diff --git a/crates/cursor_cloud_agents/src/api/wire.rs b/crates/cursor_cloud_agents/src/api/wire.rs
index c9148a81b0..1adc3126f7 100644
--- a/crates/cursor_cloud_agents/src/api/wire.rs
+++ b/crates/cursor_cloud_agents/src/api/wire.rs
@@ -212,6 +212,9 @@ pub struct RunDetail {
pub struct ListRunsResponse {
/// The agent's runs, newest first.
pub items: Vec<RunListItem>,
+ /// Cursor for the next page, absent on the last page.
+ #[serde(default, rename = "nextCursor")]
+ pub next_cursor: Option<String>,
}
/// One run in a `GET /v1/agents/{id}/runs` page.
diff --git a/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs b/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs
index 4090f46d50..d22286d97c 100644
--- a/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs
+++ b/crates/cursor_cloud_agents/src/bin/cursor_cloud_agents.rs
@@ -146,8 +146,13 @@ async fn main() -> ExitCode {
// variant for that model, since Cursor rejects an id whose params are not a
// variant it knows. A client may change it per session from here.
let service = Arc::new(
- CursorSessionService::new(client, notifier.clone(), repos)
- .with_default_model(configured_model),
+ CursorSessionService::new(
+ client,
+ notifier.clone(),
+ repos,
+ Arc::new(cursor_cloud_agents::outbound::memory_journal::MemoryJournal::default()),
+ )
+ .with_default_model(configured_model),
);
match serve(service, notifier, tokio::io::stdin(), tokio::io::stdout()).await {
Ok(()) => ExitCode::SUCCESS,
diff --git a/crates/cursor_cloud_agents/src/domain/error.rs b/crates/cursor_cloud_agents/src/domain/error.rs
index 9c2f0ed999..7ec89f4de9 100644
--- a/crates/cursor_cloud_agents/src/domain/error.rs
+++ b/crates/cursor_cloud_agents/src/domain/error.rs
@@ -14,6 +14,9 @@ pub enum SessionError {
/// previous `session/prompt` to respond.
#[error("session {0} already has an active turn")]
TurnAlreadyActive(SessionId),
+ /// Native capture or replay processing failed; never masked by cancellation.
+ #[error("Cursor native journal failed: {0}")]
+ Journal(rootcause::Report),
/// The Cursor API or its stream failed.
#[error("{0}")]
Cursor(rootcause::Report),
@@ -24,3 +27,8 @@ impl From<rootcause::Report> for SessionError {
Self::Cursor(report)
}
}
+
+/// A provider response proving a prompt was rejected before execution.
+#[derive(Debug, Error)]
+#[error("{0}")]
+pub struct PromptRejected(pub String);
diff --git a/crates/cursor_cloud_agents/src/domain/event.rs b/crates/cursor_cloud_agents/src/domain/event.rs
index 8392152b1a..caaefde30c 100644
--- a/crates/cursor_cloud_agents/src/domain/event.rs
+++ b/crates/cursor_cloud_agents/src/domain/event.rs
@@ -14,11 +14,11 @@
mod test;
use crate::domain::model::{CursorRunId, RunStatus};
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
use serde_json::Value;
/// One decoded event from a run's stream.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CursorEvent {
/// The run's lifecycle status changed (also sent once on connect).
Status {
@@ -77,7 +77,7 @@ pub enum CursorEvent {
/// A `tool_call` event: Cursor sends the same event name for the opening
/// announcement and every later progress report, distinguished only by
/// whether the `callId` has been seen before.
-#[derive(Debug, Clone, PartialEq, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolCallEvent {
/// Cursor's id for the call. May contain a literal newline — see
@@ -114,7 +114,7 @@ pub struct ToolCallEvent {
/// `args` is included because it is the only other half there is to truncate;
/// no recording has shown it yet, so it defaults to false like any absent
/// field.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Truncation {
/// Cursor truncated the tool's input.
@@ -145,7 +145,7 @@ where
/// event does. `text-delta` and `thinking-delta` duplicate the `assistant`
/// and `thinking` events one-for-one — consuming both would double every
/// chunk — so they land in [`InteractionUpdate::Other`] and are ignored.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum InteractionUpdate {
/// The user's prompt echoed back into the stream. The one place the
/// stream states which prompt opened the turn.
diff --git a/crates/cursor_cloud_agents/src/domain/journal.rs b/crates/cursor_cloud_agents/src/domain/journal.rs
new file mode 100644
index 0000000000..a4e22b6323
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/domain/journal.rs
@@ -0,0 +1,248 @@
+//! Native capture contract and the shared live/load processing machine.
+use super::event::{CursorEvent, InteractionUpdate};
+use super::model::{CursorRunId, RunOutcome, RunStatus};
+use super::translate::TranslateMachine;
+use agent_client_protocol::schema::v1::{
+ ContentBlock, ContentChunk, SessionId, SessionUpdate, TextContent,
+};
+use futures::future::BoxFuture;
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+
+/// A complete SSE message, before JSON decoding. IDs are observations, never
+/// local sequence numbers or an assumed remote resume token.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct NativeRecord {
+ /// SSE event name.
+ pub event: String,
+ /// Original data lines joined by the SSE decoder.
+ pub data: String,
+ /// Provider's SSE last-event ID, when supplied.
+ pub id: Option<String>,
+}
+impl NativeRecord {
+ /// Whether this record participates in reconnect prefix matching. This
+ /// examines framing only; native payload decoding happens after append.
+ pub(crate) fn is_content(&self) -> bool {
+ !matches!(self.event.as_str(), "status" | "heartbeat" | "error")
+ }
+ /// Decode only after this record is durably captured.
+ pub fn decode(&self) -> CursorEvent {
+ CursorEvent::from_wire(
+ &self.event,
+ serde_json::from_str(&self.data).unwrap_or_default(),
+ )
+ }
+}
+
+/// Inputs, not a second ACP transcript. Every synthetic update has an input.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub enum JournalInput {
+ /// History is known from its beginning (fresh session or full hydration).
+ HistoryComplete,
+ /// Original ACP prompt blocks, associated with the run that accepted them.
+ Prompt(Vec<ContentBlock>),
+ /// Links a pre-execution prompt sequence to its accepted provider run.
+ PromptAccepted(i64),
+ /// A pre-execution prompt was cancelled/rejected without a run.
+ PromptAborted(i64),
+ /// Transport failure, retained without prematurely closing running tools.
+ TransportError(String),
+ /// Raw complete provider message, including unknown payloads.
+ Sse(NativeRecord),
+ /// Original successful polling response body.
+ Poll(String),
+ /// A local terminal decision (e.g. stop during a disconnected poll).
+ Interrupted(String),
+ /// Capture has reconciled this run; distinct from ACP delivery checkpoint.
+ Reconciled,
+}
+/// One input in explicit session order; run membership uses provider IDs.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct JournalEntry {
+ /// Monotonically increasing session sequence, starting at one.
+ pub sequence: i64,
+ /// Provider run; absent only for session-level facts.
+ pub run: Option<CursorRunId>,
+ /// The captured native input.
+ pub input: JournalInput,
+}
+/// Session-scoped durable storage. Implementations must reject stale owners
+/// and compare `expected` to the current high-water mark atomically with append.
+/// Reads and writes are never exposed as a public provider-history endpoint.
+pub trait CursorJournal: Send + Sync + std::fmt::Debug {
+ /// A stable ordered snapshot under the caller's session turn gate.
+ fn read<'a>(
+ &'a self,
+ session: &'a SessionId,
+ ) -> BoxFuture<'a, Result<Vec<JournalEntry>, rootcause::Report>>;
+ /// Append before processing; failure must leave both progress and output unchanged.
+ fn append<'a>(
+ &'a self,
+ session: &'a SessionId,
+ expected: i64,
+ run: Option<&'a CursorRunId>,
+ input: &'a JournalInput,
+ ) -> BoxFuture<'a, Result<JournalEntry, rootcause::Report>>;
+}
+
+#[derive(Debug, Default)]
+struct RunState {
+ prompt: bool,
+ text: String,
+ terminal: Option<RunStatus>,
+}
+/// Complete live/replay state, including user prompts and terminal tool cleanup.
+#[derive(Debug, Default)]
+pub struct ReplayMachine {
+ translator: TranslateMachine,
+ runs: HashMap<CursorRunId, RunState>,
+}
+impl ReplayMachine {
+ /// Whether the run's original prompt is reconstructable.
+ pub fn has_prompt(&self, run: &CursorRunId) -> bool {
+ self.runs.get(run).is_some_and(|s| s.prompt)
+ }
+ /// Whether native history contains a prompt and a terminal fact for a run.
+ pub fn complete(&self, run: &CursorRunId) -> bool {
+ self.runs
+ .get(run)
+ .is_some_and(|s| s.prompt && s.terminal.is_some())
+ }
+ /// Durable provider terminal status, independent of the reconciliation marker.
+ pub fn terminal_status(&self, run: &CursorRunId) -> Option<RunStatus> {
+ self.runs.get(run).and_then(|s| s.terminal.clone())
+ }
+ /// Process one journal input, identically during capture and replay.
+ pub fn push(
+ &mut self,
+ run: Option<&CursorRunId>,
+ input: &JournalInput,
+ ) -> Result<Vec<SessionUpdate>, rootcause::Report> {
+ let Some(run) = run else {
+ // Original requests also belong to history when they were stopped
+ // before a remote run existed. Acceptance later only binds state.
+ return Ok(match input {
+ JournalInput::Prompt(blocks) => blocks
+ .iter()
+ .cloned()
+ .map(|b| SessionUpdate::UserMessageChunk(ContentChunk::new(b)))
+ .collect(),
+ _ => Vec::new(),
+ });
+ };
+ let state = self.runs.entry(run.clone()).or_default();
+ match input {
+ JournalInput::Prompt(blocks) => {
+ if state.prompt {
+ return Ok(Vec::new());
+ }
+ state.prompt = true;
+ Ok(blocks
+ .iter()
+ .cloned()
+ .map(|b| SessionUpdate::UserMessageChunk(ContentChunk::new(b)))
+ .collect())
+ }
+ JournalInput::Sse(record) => self.event(run, record.decode()),
+ JournalInput::Poll(raw) => {
+ let value: serde_json::Value =
+ serde_json::from_str(raw).map_err(|e| rootcause::report!(e))?;
+ let status: RunStatus = serde_json::from_value(value["status"].clone())
+ .map_err(|e| rootcause::report!(e))?;
+ let text = value
+ .get("result")
+ .or_else(|| value.get("text"))
+ .and_then(|s| s.as_str())
+ .map(str::to_owned);
+ let outcome = RunOutcome {
+ status: status.clone(),
+ text: text.clone(),
+ };
+ if !outcome.is_terminal() {
+ return Ok(Vec::new());
+ }
+ self.event(
+ run,
+ CursorEvent::Result {
+ run_id: run.clone(),
+ status,
+ text,
+ duration_ms: None,
+ },
+ )
+ }
+ JournalInput::Interrupted(_) => {
+ // This closes local work, but does not claim remote capture is complete.
+ Ok(self.translator.close_open_calls())
+ }
+ JournalInput::HistoryComplete
+ | JournalInput::Reconciled
+ | JournalInput::PromptAccepted(_)
+ | JournalInput::PromptAborted(_)
+ | JournalInput::TransportError(_) => Ok(Vec::new()),
+ }
+ }
+ fn event(
+ &mut self,
+ run: &CursorRunId,
+ event: CursorEvent,
+ ) -> Result<Vec<SessionUpdate>, rootcause::Report> {
+ let state = self.runs.entry(run.clone()).or_default();
+ match event {
+ CursorEvent::Interaction(InteractionUpdate::Other { kind })
+ if kind == "step-started" =>
+ {
+ // Cursor's final result contains the final step, not earlier
+ // commentary emitted before tool execution in the same run.
+ state.text.clear();
+ Ok(Vec::new())
+ }
+ CursorEvent::Interaction(InteractionUpdate::UserMessage { text }) => {
+ if state.prompt {
+ return Ok(Vec::new());
+ }
+ state.prompt = true;
+ Ok(vec![SessionUpdate::UserMessageChunk(ContentChunk::new(
+ ContentBlock::Text(TextContent::new(text)),
+ ))])
+ }
+ CursorEvent::Assistant { text } => {
+ state.text.push_str(&text);
+ Ok(self.translator.push(CursorEvent::Assistant { text }))
+ }
+ CursorEvent::Result { status, text, .. } => {
+ if !matches!(
+ status,
+ RunStatus::Finished | RunStatus::Cancelled | RunStatus::Error
+ ) {
+ return Err(rootcause::report!("nonterminal Cursor result for {run}"));
+ }
+ let mut updates = Vec::new();
+ if let Some(text) = text {
+ // Polling can overlap an interrupted stream. Only append the
+ // missing suffix; divergent answers cannot safely be guessed.
+ if let Some(suffix) = text.strip_prefix(&state.text) {
+ if !suffix.is_empty() {
+ updates.extend(self.translator.push(CursorEvent::Assistant {
+ text: suffix.to_owned(),
+ }));
+ }
+ state.text = text;
+ } else if !state.text.is_empty() {
+ return Err(rootcause::report!(
+ "Cursor final text diverged from the captured stream for {run}"
+ ));
+ }
+ }
+ state.terminal = Some(status);
+ updates.extend(self.translator.close_open_calls());
+ Ok(updates)
+ }
+ event => Ok(self.translator.push(event)),
+ }
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/cursor_cloud_agents/src/domain/journal/test.rs b/crates/cursor_cloud_agents/src/domain/journal/test.rs
new file mode 100644
index 0000000000..dd0fff396c
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/domain/journal/test.rs
@@ -0,0 +1,181 @@
+use super::*;
+use crate::testing::fixture_sse;
+
+#[test]
+fn fake_wire_encoder_matches_recorded_vocabulary() {
+ for name in [
+ "multi_turn_1.sse",
+ "file_operations.sse",
+ "cancelled.sse",
+ "mcp_servers.sse",
+ ] {
+ for record in crate::testing::fixture_records(name) {
+ let event = record.decode();
+ let encoded = crate::testing::raw_record(event.clone());
+ assert_eq!(encoded.decode(), event, "{name}: {record:?}");
+ assert_eq!(encoded.event, record.event);
+ }
+ }
+ let user =
+ crate::testing::raw_record(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "hello".into(),
+ }));
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&user.data).unwrap(),
+ serde_json::json!({"type": "user-message-appended", "userMessage": {"text": "hello"}})
+ );
+ let result = crate::testing::raw_record(CursorEvent::Result {
+ run_id: CursorRunId::new("r"),
+ status: RunStatus::Finished,
+ text: Some("answer".into()),
+ duration_ms: Some(42),
+ });
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&result.data).unwrap(),
+ serde_json::json!({"runId": "r", "status": "FINISHED", "text": "answer", "durationMs": 42})
+ );
+}
+
+#[test]
+fn complete_native_fixtures_roundtrip_with_prompts_tools_and_terminal_states() {
+ for name in [
+ "multi_turn_1.sse",
+ "multi_turn_2.sse",
+ "file_operations.sse",
+ "cancelled.sse",
+ "mcp_servers.sse",
+ ] {
+ let run = CursorRunId::new(name);
+ let raw = fixture_sse(name);
+ let inputs: Vec<_> = crate::replay::records(&raw)
+ .into_iter()
+ .map(JournalInput::Sse)
+ .collect();
+ let mut live = ReplayMachine::default();
+ let live: Vec<_> = inputs
+ .iter()
+ .flat_map(|input| live.push(Some(&run), input).unwrap())
+ .collect();
+ let stored = serde_json::to_string(&inputs).unwrap();
+ let restored: Vec<JournalInput> = serde_json::from_str(&stored).unwrap();
+ let mut replay = ReplayMachine::default();
+ let replay: Vec<_> = restored
+ .iter()
+ .flat_map(|input| replay.push(Some(&run), input).unwrap())
+ .collect();
+ assert_eq!(live, replay, "{name}");
+ assert!(
+ live.iter()
+ .any(|u| matches!(u, SessionUpdate::UserMessageChunk(_))),
+ "original prompt missing in {name}"
+ );
+ assert_eq!(live, crate::replay::complete_updates(&raw, &run).unwrap());
+ }
+}
+
+#[test]
+fn polling_appends_only_missing_suffix_and_never_repeats_a_final_answer() {
+ let run = CursorRunId::new("r");
+ let mut machine = ReplayMachine::default();
+ machine
+ .push(
+ Some(&run),
+ &JournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {
+ text: "hel".into(),
+ })),
+ )
+ .unwrap();
+ let poll = JournalInput::Poll(
+ r#"{"status":"FINISHED","result":"hello","unknown":{"keep":true}}"#.into(),
+ );
+ let updates = machine.push(Some(&run), &poll).unwrap();
+ assert!(
+ matches!(&updates[..], [SessionUpdate::AgentMessageChunk(c)] if matches!(&c.content, ContentBlock::Text(t) if t.text == "lo"))
+ );
+ assert!(machine.push(Some(&run), &poll).unwrap().is_empty());
+ assert!(
+ machine
+ .push(
+ Some(&run),
+ &JournalInput::Poll(r#"{"status":"FINISHED","result":"different"}"#.into())
+ )
+ .is_err()
+ );
+}
+
+#[test]
+fn original_blocks_suppress_the_provider_prompt_echo_once_per_run() {
+ let run = CursorRunId::new("r");
+ let mut machine = ReplayMachine::default();
+ let blocks = vec![
+ ContentBlock::Text(TextContent::new("original")),
+ ContentBlock::Text(TextContent::new("content")),
+ ];
+ assert_eq!(
+ machine
+ .push(Some(&run), &JournalInput::Prompt(blocks))
+ .unwrap()
+ .len(),
+ 2
+ );
+ assert!(
+ machine
+ .push(
+ Some(&run),
+ &JournalInput::Sse(crate::testing::raw_record(CursorEvent::Interaction(
+ InteractionUpdate::UserMessage {
+ text: "original\ncontent".into()
+ }
+ )))
+ )
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[test]
+fn raw_unknown_data_and_ids_survive_chunked_decode_and_serialization() {
+ let raw = "id: provider-17\nevent: future-event\ndata: { this is not json\ndata: still original }\n\n";
+ let records = crate::replay::chunked(raw, 1);
+ assert_eq!(records, crate::replay::records(raw));
+ assert_eq!(records[0].id.as_deref(), Some("provider-17"));
+ assert_eq!(records[0].data, "{ this is not json\nstill original }");
+ let input = JournalInput::Sse(records[0].clone());
+ assert_eq!(
+ serde_json::from_str::<JournalInput>(&serde_json::to_string(&input).unwrap()).unwrap(),
+ input
+ );
+}
+
+#[test]
+fn result_requires_a_known_terminal_status_before_completeness_or_tool_cleanup() {
+ let run = CursorRunId::new("run");
+ for status in [
+ RunStatus::Running,
+ RunStatus::Creating,
+ RunStatus::Unknown("PAUSED".into()),
+ ] {
+ let mut machine = ReplayMachine::default();
+ machine
+ .push(
+ Some(&run),
+ &JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("go"))]),
+ )
+ .unwrap();
+ assert!(
+ machine
+ .push(
+ Some(&run),
+ &JournalInput::Sse(crate::testing::raw_record(CursorEvent::Result {
+ run_id: run.clone(),
+ status,
+ text: Some("not final".into()),
+ duration_ms: None
+ }))
+ )
+ .is_err()
+ );
+ assert!(!machine.complete(&run));
+ assert!(machine.terminal_status(&run).is_none());
+ }
+}
diff --git a/crates/cursor_cloud_agents/src/domain/mod.rs b/crates/cursor_cloud_agents/src/domain/mod.rs
index 6810c90723..982892f423 100644
--- a/crates/cursor_cloud_agents/src/domain/mod.rs
+++ b/crates/cursor_cloud_agents/src/domain/mod.rs
@@ -17,3 +17,6 @@ pub mod service;
/// The pure Cursor→ACP translation machine.
pub mod translate;
+
+/// Durable native inputs and their complete replay machine.
+pub mod journal;
diff --git a/crates/cursor_cloud_agents/src/domain/model.rs b/crates/cursor_cloud_agents/src/domain/model.rs
index d34707f0ba..6c1c96f63f 100644
--- a/crates/cursor_cloud_agents/src/domain/model.rs
+++ b/crates/cursor_cloud_agents/src/domain/model.rs
@@ -129,7 +129,7 @@ pub enum RunStatus {
}
/// A run's state as `GET /v1/agents/{id}/runs/{run}` reports it.
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunOutcome {
/// Where the run is in its lifecycle.
pub status: RunStatus,
diff --git a/crates/cursor_cloud_agents/src/domain/ports.rs b/crates/cursor_cloud_agents/src/domain/ports.rs
index e2db023d5e..64abeb2198 100644
--- a/crates/cursor_cloud_agents/src/domain/ports.rs
+++ b/crates/cursor_cloud_agents/src/domain/ports.rs
@@ -4,20 +4,28 @@
//! client ([`crate::api`]); [`SessionNotifier`] by whatever transport the
//! session's updates travel over (the ACP stdio connection today, anything
//! that can carry a `session/update` tomorrow); [`RepoResolver`] by the git
-//! adapter in [`crate::outbound`]. The service never sees HTTP, SSE framing,
-//! JSON-RPC, or a subprocess — only these contracts.
+//! adapter in [`crate::outbound`]. Native records and polling bodies cross these
+//! contracts for capture before decoding; HTTP I/O, SSE framing, JSON-RPC, and
+//! subprocesses remain outside the service.
-use crate::domain::event::CursorEvent;
use crate::domain::model::{
CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl, RunListing,
- RunOutcome,
};
use agent_client_protocol::schema::v1::{SessionId, SessionUpdate};
use futures::Stream;
use std::path::Path;
/// Create and control Cursor cloud agents.
-pub trait CursorAgents {
+pub trait CursorAgents: Sync {
+ /// Raw successful polling body, captured before interpretation, including
+ /// provider fields unknown to the domain. A turn whose stream is unavailable
+ /// falls back to polling this until the run is terminal.
+ fn raw_result(
+ &self,
+ agent: &CursorAgentId,
+ run: &CursorRunId,
+ ) -> impl Future<Output = Result<String, rootcause::Report>> + Send;
+
/// Create an agent with its first run. Cursor has no bare "create agent":
/// an agent only exists once there is a prompt to run, which is why this
/// returns both ids at once.
@@ -64,21 +72,6 @@ pub trait CursorAgents {
run: &CursorRunId,
) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
- /// The run's current status and, once terminal, its final answer text.
- ///
- /// The non-streaming read of what [`RunStream`] delivers live. It exists
- /// because the stream is the unreliable half of the API — observed
- /// answering `stream_unavailable` both in-stream and as a 409 in the
- /// seconds after a run's creation — while the run itself finishes fine
- /// server-side. A turn that cannot hold a stream falls back to polling
- /// this until the run is terminal, so flaky streaming degrades to a
- /// non-streamed answer instead of a lost one.
- fn run_result(
- &self,
- agent: &CursorAgentId,
- run: &CursorRunId,
- ) -> impl Future<Output = Result<RunOutcome, rootcause::Report>> + Send;
-
/// The agent's runs, newest first.
///
/// How a session finds out what happened to its agent while it was not
@@ -90,24 +83,25 @@ pub trait CursorAgents {
fn list_runs(
&self,
agent: &CursorAgentId,
+ through: Option<&CursorRunId>,
) -> impl Future<Output = Result<Vec<RunListing>, rootcause::Report>> + Send;
}
-/// Observe a run as a stream of decoded events.
+/// Observe a run as a stream of native SSE records.
///
/// The stream ends when the server closes it — normally just after a
-/// [`CursorEvent::Done`]. A consumer that never sees a terminal
-/// [`CursorEvent::Result`] must treat the run's outcome as unknown rather
+/// [`CursorEvent::Done`](super::event::CursorEvent::Done). A consumer that never sees a terminal
+/// [`CursorEvent::Result`](super::event::CursorEvent::Result) must treat the run's outcome as unknown rather
/// than successful.
-pub trait RunStream {
- /// The run's events, in arrival order.
- fn stream(
+pub trait RunStream: Sync {
+ /// Complete native records, captured before decoding or translation.
+ fn raw_stream(
&self,
agent: &CursorAgentId,
run: &CursorRunId,
) -> impl Future<
Output = Result<
- impl Stream<Item = Result<CursorEvent, rootcause::Report>> + Send,
+ impl Stream<Item = Result<super::journal::NativeRecord, rootcause::Report>> + Send,
rootcause::Report,
>,
> + Send;
@@ -121,6 +115,25 @@ pub trait SessionNotifier {
session: &SessionId,
update: SessionUpdate,
) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+ /// Ask the host to load recovered history after the current prompt completes.
+ /// This must only enqueue a signal: the caller holds the session writer gate.
+ fn require_reload(
+ &self,
+ session: &SessionId,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+ /// Emit a terminal lifecycle fact after the reconstructed turn's updates.
+ fn turn_complete(
+ &self,
+ session: &SessionId,
+ outcome: agent_runtime_protocol::domain::turn::TurnOutcome,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+ /// Emit a non-rendering marker after every update for `run` was delivered.
+ /// Durable hosts use it to atomically checkpoint the run with their log.
+ fn checkpoint(
+ &self,
+ session: &SessionId,
+ run: &CursorRunId,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
}
/// Resolve the repository a new session should attach to.
diff --git a/crates/cursor_cloud_agents/src/domain/service.rs b/crates/cursor_cloud_agents/src/domain/service.rs
index dec1a95db1..5f9d5f57d1 100644
--- a/crates/cursor_cloud_agents/src/domain/service.rs
+++ b/crates/cursor_cloud_agents/src/domain/service.rs
@@ -39,14 +39,14 @@
mod test;
use crate::domain::error::SessionError;
-use crate::domain::event::{CursorEvent, InteractionUpdate};
+use crate::domain::event::CursorEvent;
+use crate::domain::journal::{CursorJournal, JournalEntry, JournalInput, ReplayMachine};
use crate::domain::model::{
CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl, RunStatus,
};
use crate::domain::ports::{CursorAgents, RepoResolver, RunStream, SessionNotifier};
-use crate::domain::translate::TranslateMachine;
use agent_client_protocol::schema::v1::{
- ContentBlock, ContentChunk, SessionId, SessionUpdate, StopReason, TextContent,
+ ContentBlock, SessionId, SessionUpdate, StopReason, TextContent,
};
use futures::StreamExt as _;
use futures::pin_mut;
@@ -77,6 +77,25 @@ const STREAM_QUIET_TIMEOUT: std::time::Duration = std::time::Duration::from_secs
/// agent is drivable from cursor.com) before giving up, in poll intervals.
const BUSY_ATTEMPTS: usize = 450;
+#[derive(Clone, Copy)]
+struct IngestMode {
+ emit: bool,
+ strict: bool,
+ attempt: usize,
+}
+impl IngestMode {
+ const LIVE: Self = Self {
+ emit: true,
+ strict: false,
+ attempt: 0,
+ };
+ const HYDRATE: Self = Self {
+ emit: false,
+ strict: true,
+ attempt: 0,
+ };
+}
+
/// Wait out `duration`, unless the client cancels first. `true` means it did.
///
/// Every wait a turn can be parked in goes through this, so a cancel is felt
@@ -107,6 +126,13 @@ struct SessionState {
/// or restored session, whose history is already rendered or unknowable —
/// so nothing is backfilled rather than everything replayed.
last_run: Option<CursorRunId>,
+ /// Whether the ACP client has opened or loaded this session on the current
+ /// connection. Restored sessions must not emit recovered updates before
+ /// `session/load` re-establishes the host's routing for their session id.
+ ready_for_sync: bool,
+ /// Pause background capture while the host loads, without refusing prompts
+ /// it already dispatched before observing the recovery requirement.
+ reload_pending: bool,
/// Set by cancel; read by the turn when its stream ends.
///
/// The *verdict*, not the mechanism: a cancel that raced the stream's own
@@ -132,7 +158,11 @@ struct SessionState {
mcp_servers: Vec<McpServer>,
/// Carried across turns so tool-call ids stay deduplicated for the whole
/// session.
- translator: TranslateMachine,
+ machine: ReplayMachine,
+ journal_entries: Vec<JournalEntry>,
+ journal_loaded: bool,
+ fresh: bool,
+ capture_failed: bool,
}
/// A session shared between a streaming turn and a concurrent cancel.
@@ -154,13 +184,14 @@ struct Session {
/// cursor.com activity never interleaves its frames with a live turn's.
/// A prompt waits on it; a sync skips its tick instead. Never held by
/// `cancel`, which must land while a turn is streaming.
- turn_gate: tokio::sync::Mutex<()>,
+ turn_gate: Arc<tokio::sync::Mutex<()>>,
state: Mutex<SessionState>,
}
/// The service behind the ACP handlers.
#[derive(Debug)]
pub struct CursorSessionService<Cursor, Notifier, Repos> {
+ journal: Arc<dyn CursorJournal>,
cursor: Cursor,
notifier: Notifier,
repos: Repos,
@@ -182,8 +213,14 @@ where
Repos: RepoResolver,
{
/// Wire the service to its ports.
- pub fn new(cursor: Cursor, notifier: Notifier, repos: Repos) -> Self {
+ pub fn new(
+ cursor: Cursor,
+ notifier: Notifier,
+ repos: Repos,
+ journal: Arc<dyn CursorJournal>,
+ ) -> Self {
Self {
+ journal,
cursor,
notifier,
repos,
@@ -193,7 +230,6 @@ where
models: tokio::sync::Mutex::new(None),
}
}
-
/// Pin the model every new session starts on, by id.
///
/// The id alone, because a caller configuring this has only ever had an id
@@ -222,9 +258,11 @@ where
let session = Arc::new(Session {
repo,
restored_model_id: None,
- turn_gate: tokio::sync::Mutex::new(()),
+ turn_gate: Arc::new(tokio::sync::Mutex::new(())),
state: Mutex::new(SessionState {
mcp_servers,
+ ready_for_sync: true,
+ fresh: true,
..SessionState::default()
}),
});
@@ -395,6 +433,18 @@ where
}
}
+ /// Mark a restored session safe for background updates after load replies.
+ #[cfg(test)]
+ fn loaded(&self, session_id: &SessionId) -> Result<(), SessionError> {
+ let session = self.session(session_id)?;
+ session
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .ready_for_sync = true;
+ Ok(())
+ }
+
/// Run one prompt to completion, delivering updates as they stream.
///
/// Resolves with the turn's ACP stop reason once the run's stream ends.
@@ -403,6 +453,21 @@ where
&self,
session_id: &SessionId,
prompt: &str,
+ ) -> Result<StopReason, SessionError> {
+ self.prompt_content(
+ session_id,
+ prompt,
+ vec![ContentBlock::Text(TextContent::new(prompt))],
+ )
+ .await
+ }
+
+ /// Run a prompt retaining its original ACP blocks in the native journal.
+ pub async fn prompt_content(
+ &self,
+ session_id: &SessionId,
+ prompt: &str,
+ blocks: Vec<ContentBlock>,
) -> Result<StopReason, SessionError> {
let session = self.session(session_id)?;
// Wait behind an in-flight foreign-run mirror, so its frames and
@@ -425,52 +490,76 @@ where
}
};
- // Claim the turn before any network call so a racing second prompt
- // fails fast instead of creating a second agent.
- // Resolved before the turn commits to a path: both the create-agent
- // and the follow-up-run branch send it, and a mid-turn change must not
- // land on a run that is already going.
- let model = self.effective_model(session_id).await?;
-
- let (existing_agent, cancel) = {
+ if !session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .ready_for_sync
+ {
+ return Err(SessionError::Cursor(rootcause::report!(
+ "Cursor session must load successfully before prompting"
+ )));
+ }
+ // This pending prompt owns cancellation before any model lookup or
+ // historical recovery can wait. Recovery cannot clear a received stop.
+ let cancel = {
let mut state = session.state.lock().expect("session state poisoned");
- if state.active_run.is_some() {
- return Err(SessionError::TurnAlreadyActive(session_id.clone()));
- }
state.cancelled = false;
- // A fresh token per turn: the previous one may already be fired,
- // and reusing it would cancel this turn before it began.
state.cancel = tokio_util::sync::CancellationToken::new();
- (state.agent.clone(), state.cancel.clone())
+ state.cancel.clone()
};
+ // A failed model lookup proves no prompt was executed. Do it before
+ // reserving the durable intent, so load does not see false ambiguity.
+ let model = self.effective_model(session_id).await?;
+ self.ensure_journal(session_id, &session).await?;
+ let prior_agent = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .agent
+ .clone();
+ if let Some(agent) = &prior_agent {
+ self.backfill_foreign_runs(session_id, &session, agent, None)
+ .await?;
+ }
+ // Preserve original content before the provider creates remote work.
+ self.capture(
+ session_id,
+ &session,
+ None,
+ JournalInput::Prompt(blocks.clone()),
+ false,
+ )
+ .await?;
- let (agent, run) = match existing_agent {
+ let prompt_sequence = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .journal_entries
+ .last()
+ .expect("captured prompt")
+ .sequence;
+
+ if cancel.is_cancelled() {
+ self.capture(
+ session_id,
+ &session,
+ None,
+ JournalInput::PromptAborted(prompt_sequence),
+ false,
+ )
+ .await?;
+ return Ok(StopReason::Cancelled);
+ }
+
+ let created = match prior_agent {
Some(agent) => {
// Queue behind any run still going (the same agent advances
// from cursor.com too) instead of failing the prompt.
- let run = match self
- .create_run_when_free(&agent, prompt, model.as_ref(), &cancel)
- .await
- {
- Ok(run) => run,
- // The wait ended because the client asked to stop, which
- // ACP answers with a stop reason rather than an error.
- Err(_) if cancel.is_cancelled() => return Ok(StopReason::Cancelled),
- Err(error) => return Err(error),
- };
- // Catch the session's view up on whatever it missed while it
- // was not looking. After the create on purpose: creating
- // proved the agent free, so every missed run is terminal and
- // its text is readable — before it, a still-running
- // cursor.com run is invisible to the backfill and the
- // watermark then walks straight past it.
- if let Err(error) = self
- .backfill_foreign_runs(session_id, &session, &agent, Some(&run))
+ self.create_run_when_free(&agent, prompt, model.as_ref(), &cancel)
.await
- {
- tracing::warn!(%agent, %error, "could not backfill cursor.com runs");
- }
- (agent, run)
+ .map(|run| (agent, run))
}
None => {
// Snapshotted out of the lock: `create_agent` is a network
@@ -483,9 +572,43 @@ where
.clone();
self.cursor
.create_agent(prompt, session.repo.as_ref(), &mcp_servers, model.as_ref())
- .await?
+ .await
+ .map_err(SessionError::from)
+ }
+ };
+ let (agent, run) = match created {
+ Ok(created) => created,
+ Err(error) => {
+ if matches!(&error, SessionError::Cursor(report) if report.downcast_current_context::<crate::domain::error::PromptRejected>().is_some())
+ {
+ self.capture(
+ session_id,
+ &session,
+ None,
+ JournalInput::PromptAborted(prompt_sequence),
+ false,
+ )
+ .await?;
+ if cancel.is_cancelled() {
+ return Ok(StopReason::Cancelled);
+ }
+ }
+ return Err(error);
}
};
+ self.capture(
+ session_id,
+ &session,
+ Some(&run),
+ JournalInput::PromptAccepted(prompt_sequence),
+ false,
+ )
+ .await?;
+ session.state.lock().expect("session state poisoned").agent = Some(agent.clone());
+ // Acceptance is durable even if recovery of an older run fails. Do
+ // not observe/project the new run until every older run is reconciled.
+ self.backfill_foreign_runs(session_id, &session, &agent, Some(&run))
+ .await?;
tracing::info!(%agent, %run, "cursor run started");
let cancelled_before_the_run = {
let mut state = session.state.lock().expect("session state poisoned");
@@ -515,13 +638,50 @@ where
let cancelled = {
let mut state = session.state.lock().expect("session state poisoned");
state.active_run = None;
- state.last_run = Some(run.clone());
state.cancelled
};
+ if let Err(SessionError::Cursor(error)) = &outcome {
+ self.capture(
+ session_id,
+ &session,
+ Some(&run),
+ JournalInput::Interrupted(error.to_string()),
+ true,
+ )
+ .await?;
+ }
+ if cancelled && outcome.is_ok() {
+ self.capture(
+ session_id,
+ &session,
+ Some(&run),
+ JournalInput::Interrupted("user cancelled the turn".into()),
+ true,
+ )
+ .await?;
+ }
+ let reconciled = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .journal_entries
+ .iter()
+ .any(|e| e.run.as_ref() == Some(&run) && e.input == JournalInput::Reconciled);
+ if outcome.is_ok() && reconciled {
+ self.notifier
+ .checkpoint(session_id, &run)
+ .await
+ .map_err(SessionError::Cursor)?;
+ session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .last_run = Some(run.clone());
+ }
// A cancel that raced the stream's own ending still reports
// Cancelled: ACP requires it once the client sent `session/cancel`.
match outcome {
- _ if cancelled => Ok(StopReason::Cancelled),
+ Ok(_) | Err(SessionError::Cursor(_)) if cancelled => Ok(StopReason::Cancelled),
Ok(stop_reason) => Ok(stop_reason),
Err(error) => Err(error),
}
@@ -582,7 +742,7 @@ where
/// this client does not enforce, so every match is cancelled rather than
/// just the first — cheap insurance against it ever slipping.
async fn current_runs(&self, agent: &CursorAgentId) -> Vec<CursorRunId> {
- let listings = match self.cursor.list_runs(agent).await {
+ let listings = match self.cursor.list_runs(agent, None).await {
Ok(listings) => listings,
Err(error) => {
tracing::warn!(%agent, %error, "could not list runs to find one to cancel");
@@ -621,8 +781,8 @@ where
/// Seed a session a previous process created, so a `session/load` naming
/// it finds it live.
///
- /// The service is deliberately storage-free; whatever survives a restart
- /// is the host's business, and this is how the host hands it back. With
+ /// The host restores provider identity; the Cursor-owned journal restores
+ /// conversation state when the client subsequently loads the session. With
/// `Some(agent)` the next prompt opens a follow-up run on that agent;
/// with `None` it mints a fresh one — the state of a session that died
/// after `session/new` but before its first prompt, which must still
@@ -636,6 +796,18 @@ where
agent: Option<CursorAgentId>,
repo: Option<RepoUrl>,
model_id: Option<String>,
+ ) {
+ self.restore_session_with_watermark(id, agent, repo, model_id, None);
+ }
+
+ /// Restore a session together with its durable run-delivery checkpoint.
+ pub fn restore_session_with_watermark(
+ &self,
+ id: SessionId,
+ agent: Option<CursorAgentId>,
+ repo: Option<RepoUrl>,
+ model_id: Option<String>,
+ last_run: Option<CursorRunId>,
) {
// No MCP servers here on purpose: the host never had the truth to
// hand over — the list belongs to the ACP client, and the client
@@ -643,9 +815,10 @@ where
let session = Arc::new(Session {
repo,
restored_model_id: model_id,
- turn_gate: tokio::sync::Mutex::new(()),
+ turn_gate: Arc::new(tokio::sync::Mutex::new(())),
state: Mutex::new(SessionState {
agent,
+ last_run,
..SessionState::default()
}),
});
@@ -671,7 +844,7 @@ where
/// Streaming is the good path, not the only one. Cursor's stream endpoint
/// has been observed refusing connects for seconds after a run's creation
/// and dying mid-run, while the run itself finishes fine server-side — so
- /// any streaming failure here degrades to [`Self::poll_turn`] rather than
+ /// any streaming failure here degrades to the polling fallback rather than
/// failing the turn. A turn may lose its liveness; it must not lose its
/// answer.
async fn stream_turn(
@@ -682,177 +855,301 @@ where
run: &CursorRunId,
cancel: &tokio_util::sync::CancellationToken,
) -> Result<StopReason, SessionError> {
- let stream = match self.cursor.stream(agent, run).await {
- Ok(stream) => stream,
+ self.ingest_run(session_id, session, agent, run, cancel, IngestMode::LIVE)
+ .await
+ }
+
+ /// One ordered path for live, foreign, and hydration ingestion. Reconnect
+ /// starts at the beginning and verifies the captured content prefix. No
+ /// local sequence is sent to Cursor as a remote resume token.
+ async fn ingest_run(
+ &self,
+ session_id: &SessionId,
+ session: &Session,
+ agent: &CursorAgentId,
+ run: &CursorRunId,
+ cancel: &tokio_util::sync::CancellationToken,
+ mode: IngestMode,
+ ) -> Result<StopReason, SessionError> {
+ let IngestMode {
+ emit,
+ strict,
+ attempt,
+ } = mode;
+ // A crash can leave a terminal SSE/Poll durable but its following
+ // marker absent. Its text and terminal tool cleanup were reconstructed
+ // already; reconnecting the stream would append that suffix twice.
+ let terminal = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .machine
+ .terminal_status(run);
+ if let Some(status) = terminal {
+ if strict
+ && !session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .machine
+ .has_prompt(run)
+ {
+ return Err(
+ rootcause::report!("original Cursor prompt unavailable for {run}").into(),
+ );
+ }
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::Reconciled,
+ false,
+ )
+ .await?;
+ return match status {
+ RunStatus::Cancelled => Ok(StopReason::Cancelled),
+ RunStatus::Finished => Ok(StopReason::EndTurn),
+ _ if strict => Ok(StopReason::EndTurn),
+ status => Err(rootcause::report!("cursor run {run} ended in {status:?}").into()),
+ };
+ }
+ let captured: Vec<_> = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .journal_entries
+ .iter()
+ .filter(|e| e.run.as_ref() == Some(run))
+ .filter_map(|e| match &e.input {
+ JournalInput::Sse(r) if r.is_content() => Some(r.clone()),
+ _ => None,
+ })
+ .collect();
+ let mut matched = 0;
+ let mut terminal = None;
+ let mut saw_content = false;
+ let stream = match self.cursor.raw_stream(agent, run).await {
+ Ok(stream) => Some(stream),
Err(error) => {
- tracing::warn!(%agent, %run, %error, "run stream would not open; polling instead");
- return self
- .poll_turn(session_id, session, agent, run, false, cancel)
- .await;
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::TransportError(error.to_string()),
+ emit,
+ )
+ .await?;
+ None
}
};
- pin_mut!(stream);
-
- // The run's own verdict, set only by a `result` event. Every recorded
- // run ends with one (`fixtures/real/*.sse`), including the cancelled
- // one — which is why the terminal signal is the result rather than
- // the envelope's `turn-ended`, that being absent when a turn is cut
- // short.
- let mut outcome = None;
- // Whether any assistant text was delivered live, so a fallback knows
- // not to repeat it from the run's final result.
- let mut streamed_text = false;
- loop {
- // A client cancel is a notification already POSTed; it does not
- // outrank the stream. Cursor's `result` frame is what ends the
- // turn, including a cancelled one.
- let next = match tokio::time::timeout(STREAM_QUIET_TIMEOUT, stream.next()).await {
- Ok(next) => next,
- // The stream has gone quiet. If the run is already over, the
- // stream's terminal event is the only thing anyone is waiting
- // for — take the answer from the record instead of holding
- // the turn open for it.
- Err(_elapsed) => {
- match self.cursor.run_result(agent, run).await {
- Ok(outcome) if outcome.is_terminal() => {
- tracing::info!(
- %agent, %run, status = ?outcome.status,
- "run finished but its stream went quiet; closing the turn from the record"
- );
- return self
- .poll_turn(session_id, session, agent, run, streamed_text, cancel)
- .await;
- }
- // Still running: keep listening. Unless the client
- // stopped, in which case a silent stream and a run
- // the record says is still going is nothing left to
- // wait for.
- Ok(_) if cancel.is_cancelled() => {
- tracing::info!(%agent, %run, "stopped run's stream went quiet");
- self.close_open_tool_calls(session_id, session).await;
- return Ok(StopReason::Cancelled);
+ if let Some(stream) = stream {
+ pin_mut!(stream);
+ loop {
+ let record = match tokio::time::timeout(STREAM_QUIET_TIMEOUT, stream.next()).await {
+ Ok(Some(Ok(record))) => record,
+ Ok(Some(Err(error))) => {
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::TransportError(error.to_string()),
+ emit,
+ )
+ .await?;
+ break;
+ }
+ Ok(None) => break,
+ Err(_) if strict => break,
+ Err(_) => {
+ // Quiet streams are checked through the exact same raw
+ // polling/capture path as disconnected streams.
+ let status = self
+ .poll_once(session_id, session, agent, run, cancel, emit)
+ .await?;
+ if status.is_terminal() {
+ terminal = Some(status.status);
+ break;
}
- Ok(_) => continue,
- Err(error) => {
- tracing::warn!(%agent, %run, %error, "quiet-stream status check failed");
- continue;
+ if cancel.is_cancelled() {
+ break;
}
+ continue;
}
+ };
+ let content = record.is_content();
+ if content && matched < captured.len() {
+ if captured[matched] != record {
+ return Err(rootcause::report!("Cursor stream prefix cannot be reconciled for {run}; refusing incomplete history").into());
+ }
+ matched += 1;
+ if let CursorEvent::Result { status, .. } = record.decode() {
+ terminal = Some(status);
+ }
+ continue;
}
- };
- let Some(event) = next else { break };
- let event = match event {
- Ok(event) => event,
- Err(error) => {
- tracing::warn!(%agent, %run, %error, "run stream broke mid-turn; polling instead");
- return self
- .poll_turn(session_id, session, agent, run, streamed_text, cancel)
- .await;
- }
- };
- match &event {
- CursorEvent::Result { status, .. } => outcome = Some(status.clone()),
- CursorEvent::Assistant { .. } => streamed_text = true,
- CursorEvent::Error { code, message } => {
- tracing::warn!(
- %agent, %run, ?code, %message,
- "cursor reported a stream error mid-turn; polling instead"
- );
- return self
- .poll_turn(session_id, session, agent, run, streamed_text, cancel)
- .await;
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::Sse(record.clone()),
+ emit,
+ )
+ .await?;
+ saw_content |= content;
+ match record.decode() {
+ CursorEvent::Error { code, .. }
+ if code.as_deref() == Some("stream_unavailable")
+ && !saw_content
+ && attempt < 4 =>
+ {
+ if !sleep_unless_cancelled(cancel, std::time::Duration::from_millis(400))
+ .await
+ {
+ return Box::pin(self.ingest_run(
+ session_id,
+ session,
+ agent,
+ run,
+ cancel,
+ IngestMode {
+ attempt: attempt + 1,
+ ..mode
+ },
+ ))
+ .await;
+ }
+ break;
+ }
+ CursorEvent::Result { status, .. } => terminal = Some(status),
+ CursorEvent::Error { .. } => break,
+ CursorEvent::Done => break,
+ _ => {}
}
- _ => {}
}
- let done = matches!(event, CursorEvent::Done);
-
- let updates = {
- let mut state = session.state.lock().expect("session state poisoned");
- state.translator.push(event)
- };
- for update in updates {
- self.notifier.notify(session_id, update).await?;
+ }
+ if matched < captured.len() && strict {
+ return Err(rootcause::report!(
+ "Cursor no longer exposes the captured stream prefix for {run}"
+ )
+ .into());
+ }
+ if terminal.is_none() {
+ if strict {
+ return Err(rootcause::report!(
+ "Cursor cannot fully hydrate run {run}: complete native stream unavailable"
+ )
+ .into());
}
- if done {
- break;
+ for attempt in 0..POLL_ATTEMPTS {
+ if attempt > 0 && cancel.is_cancelled() {
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::Interrupted("cancelled while disconnected".into()),
+ emit,
+ )
+ .await?;
+ return Ok(StopReason::Cancelled);
+ }
+ match self
+ .poll_once(session_id, session, agent, run, cancel, emit)
+ .await
+ {
+ Ok(outcome) if outcome.is_terminal() => {
+ terminal = Some(outcome.status);
+ break;
+ }
+ Ok(_) => {}
+ Err(error) => {
+ // Journal/processing failures must never be retried as
+ // provider errors; poll_once distinguishes them.
+ return Err(error);
+ }
+ }
+ sleep_unless_cancelled(cancel, POLL_INTERVAL).await;
}
}
-
- // A stream that closed without ever saying how the run ended proves
- // nothing about the run; ask the API rather than guessing.
- if outcome.is_none() {
- tracing::warn!(%agent, %run, "run stream ended without a result; polling instead");
- return self
- .poll_turn(session_id, session, agent, run, streamed_text, cancel)
- .await;
+ let status = terminal
+ .ok_or_else(|| rootcause::report!("Cursor run {run} did not reach a terminal state"))?;
+ if strict
+ && !session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .machine
+ .complete(run)
+ {
+ return Err(rootcause::report!(
+ "Cursor cannot hydrate the original prompt for run {run}"
+ )
+ .into());
}
-
- match outcome {
- Some(RunStatus::Finished) => Ok(StopReason::EndTurn),
- Some(RunStatus::Cancelled) => {
- self.close_open_tool_calls(session_id, session).await;
- Ok(StopReason::Cancelled)
- }
- // A run that ended in any other state did not succeed, and ACP
- // answers a prompt with a stop reason or an error — there is no
- // stop reason for "it failed", so this is an error.
- //
- // `RunStatus::Unknown` lands here too, which is deliberate: it
- // absorbs any status Cursor adds, so treating it as a clean
- // finish would silently report success for an outcome nobody has
- // read. The cost is that renaming `FINISHED` upstream fails loud
- // instead of quiet, which is the right way round.
- Some(status) => Err(SessionError::Cursor(rootcause::report!(
- "cursor run {run} ended in {status:?}"
- ))),
- // See [`crate::domain::ports::RunStream`]: a consumer that never
- // sees a terminal result must treat the outcome as unknown rather
- // than successful. A dropped connection ends the stream exactly
- // here, with the run quite possibly still going server-side.
- None => Err(SessionError::Cursor(rootcause::report!(
- "cursor stream for run {run} ended without reporting a result"
- ))),
+ // A disconnected cancel did not get here: reconciliation is only
+ // marked after a real provider terminal fact, never on ACP delivery.
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::Reconciled,
+ emit,
+ )
+ .await?;
+ if strict {
+ return Ok(StopReason::EndTurn);
+ }
+ match status {
+ RunStatus::Finished => Ok(StopReason::EndTurn),
+ RunStatus::Cancelled => Ok(StopReason::Cancelled),
+ status => Err(rootcause::report!("cursor run {run} ended in {status:?}").into()),
}
}
- /// Wait out one poll interval, unless the client has stopped the turn.
- /// `true` means it has, and the turn is over.
- ///
- /// The only cancel check in the fallback poll. Ending here is not the
- /// local settle this service refuses elsewhere: the poll runs precisely
- /// because the stream is gone, so there are no frames left to abandon —
- /// only a record to stop re-reading on the user's behalf.
- async fn wait_unless_stopped(
+ async fn poll_once(
&self,
session_id: &SessionId,
session: &Session,
+ agent: &CursorAgentId,
+ run: &CursorRunId,
cancel: &tokio_util::sync::CancellationToken,
- ) -> bool {
- if !sleep_unless_cancelled(cancel, POLL_INTERVAL).await {
- return false;
- }
- tracing::info!("turn stopped while polling for its run's record");
- self.close_open_tool_calls(session_id, session).await;
- true
- }
-
- /// Close out every tool call still open when a turn ends cancelled.
- ///
- /// Cursor's `result` with `CANCELLED` is the terminal frame; it does not
- /// always include a completed `tool_call` for work that was mid-flight,
- /// so without this the client would render that call running forever.
- async fn close_open_tool_calls(&self, session_id: &SessionId, session: &Session) {
- let updates = session
- .state
- .lock()
- .expect("session state poisoned")
- .translator
- .close_open_calls();
- for update in updates {
- if let Err(error) = self.notifier.notify(session_id, update).await {
- tracing::warn!(%error, "could not close an open tool call after cancel");
+ emit: bool,
+ ) -> Result<crate::domain::model::RunOutcome, SessionError> {
+ let mut raw = None;
+ for attempt in 0..=POLL_ERROR_TOLERANCE {
+ match self.cursor.raw_result(agent, run).await {
+ Ok(value) => {
+ raw = Some(value);
+ break;
+ }
+ Err(error) if attempt == POLL_ERROR_TOLERANCE => return Err(error.into()),
+ Err(error) => {
+ tracing::warn!(error = ?error, "Cursor poll failed; retrying");
+ if sleep_unless_cancelled(cancel, POLL_INTERVAL).await {
+ return Err(SessionError::Cursor(error));
+ }
+ }
}
}
+ let raw = raw.expect("poll returned or failed");
+ self.capture(
+ session_id,
+ session,
+ Some(run),
+ JournalInput::Poll(raw.clone()),
+ emit,
+ )
+ .await?;
+ let value: serde_json::Value =
+ serde_json::from_str(&raw).map_err(|e| rootcause::report!(e).into_dynamic())?;
+ Ok(crate::domain::model::RunOutcome {
+ status: serde_json::from_value(value["status"].clone())
+ .map_err(|e| rootcause::report!(e).into_dynamic())?,
+ text: value
+ .get("result")
+ .or_else(|| value.get("text"))
+ .and_then(|s| s.as_str())
+ .map(str::to_owned),
+ })
}
/// Create a follow-up run, waiting out whatever run is already going.
@@ -871,44 +1168,40 @@ where
) -> Result<CursorRunId, SessionError> {
for _ in 0..BUSY_ATTEMPTS {
if cancel.is_cancelled() {
- return Err(SessionError::Cursor(rootcause::report!(
- "the prompt was cancelled while waiting for the agent to be free"
- )));
+ return Err(SessionError::Cursor(
+ rootcause::report!(crate::domain::error::PromptRejected(
+ "the prompt was cancelled while waiting for the agent to be free".into()
+ ))
+ .into_dynamic(),
+ ));
}
match self.cursor.create_run(agent, prompt, model).await {
Ok(run) => return Ok(run),
Err(error) if error.to_string().contains("agent_busy") => {
tracing::info!(%agent, "agent busy (a run is active, possibly from cursor.com); waiting");
if sleep_unless_cancelled(cancel, POLL_INTERVAL).await {
- return Err(SessionError::Cursor(rootcause::report!(
- "the prompt was cancelled while waiting for the agent to be free"
- )));
+ return Err(SessionError::Cursor(
+ rootcause::report!(crate::domain::error::PromptRejected(
+ "the prompt was cancelled while waiting for the agent to be free"
+ .into()
+ ))
+ .into_dynamic(),
+ ));
}
}
Err(error) => return Err(SessionError::Cursor(error)),
}
}
- Err(SessionError::Cursor(rootcause::report!(
- "the agent stayed busy for {} seconds",
- BUSY_ATTEMPTS as u64 * POLL_INTERVAL.as_secs()
- )))
+ Err(SessionError::Cursor(
+ rootcause::report!(crate::domain::error::PromptRejected(format!(
+ "the agent stayed busy for {} seconds",
+ BUSY_ATTEMPTS as u64 * POLL_INTERVAL.as_secs()
+ )))
+ .into_dynamic(),
+ ))
}
- /// Mirror runs something else drove since this session's last own turn —
- /// the cursor.com half of the conversation.
- ///
- /// Each unseen run is replayed through its own stream, so the mirror has
- /// the same fidelity as a live turn: the user's prompt (streams carry
- /// `user-message-appended`; run records do not), thoughts, tool calls,
- /// and the answer. A run still going is simply followed to its end. Only
- /// when the stream is gone (retention expired, connection refused past
- /// retries) does a run degrade to its recorded final text. Bounded by
- /// the session's own watermark: with none, nothing is mirrored, because
- /// a restored session cannot tell missed runs from already-rendered
- /// history. Best-effort by design — callers log and proceed, since a
- /// failed mirror must not block the prompt or the next tick.
- ///
- /// Callers hold the session's turn gate.
+ /// Catch up foreign runs through the same journal path as local prompts.
async fn backfill_foreign_runs(
&self,
session_id: &SessionId,
@@ -916,231 +1209,332 @@ where
agent: &CursorAgentId,
current_run: Option<&CursorRunId>,
) -> Result<bool, SessionError> {
- let Some(last_run) = session
+ self.ensure_journal(session_id, session).await?;
+ let last = session
.state
.lock()
.expect("session state poisoned")
.last_run
- .clone()
- else {
- return Ok(false);
+ .clone();
+ // Full provider order is needed when an accepted newer run is
+ // waiting behind an older failed backfill. Include journal-pending runs
+ // even AT/BEFORE the delivered watermark, which is not a capture cursor.
+ let listings = self.cursor.list_runs(agent, None).await?;
+ let (pending, reconciled) = {
+ let state = session.state.lock().expect("session state poisoned");
+ let reconciled: std::collections::HashSet<_> = state
+ .journal_entries
+ .iter()
+ .filter(|e| e.input == JournalInput::Reconciled)
+ .filter_map(|e| e.run.clone())
+ .collect();
+ let mut pending = Vec::new();
+ for run in state.journal_entries.iter().filter_map(|e| e.run.as_ref()) {
+ if !reconciled.contains(run) && !pending.contains(run) {
+ pending.push(run.clone());
+ }
+ }
+ (pending, reconciled)
};
-
- let listings = self
- .cursor
- .list_runs(agent)
- .await
- .map_err(SessionError::Cursor)?;
- // Newest first; keep what is newer than the watermark. A watermark
- // past the page's horizon means over a page of foreign runs — deliver
- // the page rather than nothing.
- let unseen: Vec<_> = listings
- .into_iter()
- .take_while(|listing| listing.id != last_run)
- // The run this prompt just created is newer than everything
- // foreign; its own turn delivers it.
- .filter(|listing| current_run != Some(&listing.id))
+ let newer: std::collections::HashSet<_> = listings
+ .iter()
+ .take_while(|r| Some(&r.id) != last.as_ref())
+ .map(|r| r.id.clone())
.collect();
- let mirrored = !unseen.is_empty();
-
- // Oldest first, the order the conversation actually happened.
- for listing in unseen.into_iter().rev() {
- tracing::info!(%agent, run = %listing.id, "mirroring a cursor.com run");
- self.mirror_foreign_run(session_id, session, agent, &listing.id)
+ let mut runs = Vec::new();
+ // A pending run omitted by the provider listing still has to recover.
+ for run in &pending {
+ if !listings.iter().any(|r| &r.id == run) && current_run != Some(run) {
+ runs.push(run.clone());
+ }
+ }
+ for listing in listings.into_iter().rev() {
+ if current_run != Some(&listing.id)
+ && (pending.contains(&listing.id) || newer.contains(&listing.id))
+ {
+ runs.push(listing.id);
+ }
+ }
+ let mirrored = !runs.is_empty();
+ for run in &runs {
+ if !reconciled.contains(run) {
+ // A cancelled prior prompt must not cancel its recovery.
+ self.ingest_run(
+ session_id,
+ session,
+ agent,
+ run,
+ &tokio_util::sync::CancellationToken::new(),
+ IngestMode {
+ emit: false,
+ ..IngestMode::LIVE
+ },
+ )
.await?;
- session
+ }
+ let complete = session
.state
.lock()
.expect("session state poisoned")
- .last_run = Some(listing.id);
+ .journal_entries
+ .iter()
+ .any(|e| e.run.as_ref() == Some(run) && e.input == JournalInput::Reconciled);
+ if !complete {
+ return Err(rootcause::report!("Cursor run {run} remains unreconciled").into());
+ }
+ }
+ if mirrored {
+ let notify = {
+ let mut state = session.state.lock().expect("session state poisoned");
+ if let Err(error) = history_projection(&state.journal_entries) {
+ tracing::warn!(error = ?error, %session_id, "captured recovery cannot replace history yet");
+ return Ok(mirrored);
+ }
+ !std::mem::replace(&mut state.reload_pending, true)
+ };
+ if notify {
+ self.notifier
+ .require_reload(session_id)
+ .await
+ .inspect_err(|_| {
+ session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .reload_pending = false;
+ })?;
+ }
}
Ok(mirrored)
}
- /// Replay one cursor.com run into the session, falling back to its
- /// recorded final text when the stream cannot be had.
- async fn mirror_foreign_run(
+ async fn ensure_journal(&self, id: &SessionId, session: &Session) -> Result<(), SessionError> {
+ if session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .journal_loaded
+ {
+ return Ok(());
+ }
+ let entries = self.journal.read(id).await?;
+ let mut machine = ReplayMachine::default();
+ for entry in &entries {
+ project_entry(&mut machine, entry, &entries)?;
+ }
+ let fresh = {
+ let mut state = session.state.lock().expect("session state poisoned");
+ state.journal_entries = entries;
+ state.machine = machine;
+ state.journal_loaded = true;
+ state.fresh
+ };
+ if fresh {
+ self.capture(id, session, None, JournalInput::HistoryComplete, false)
+ .await?;
+ session.state.lock().expect("session state poisoned").fresh = false;
+ }
+ Ok(())
+ }
+
+ /// The only route from provider input to translation and notifications.
+ /// Every caller holds the turn gate, including load/hydration and sync.
+ async fn capture(
&self,
- session_id: &SessionId,
+ id: &SessionId,
session: &Session,
- agent: &CursorAgentId,
- run: &CursorRunId,
+ run: Option<&CursorRunId>,
+ input: JournalInput,
+ emit: bool,
) -> Result<(), SessionError> {
- let replayed = match self.cursor.stream(agent, run).await {
- Ok(stream) => {
- pin_mut!(stream);
- let mut saw_result = false;
- loop {
- let event = match stream.next().await {
- Some(Ok(event)) => event,
- Some(Err(error)) => {
- tracing::warn!(%agent, %run, %error, "foreign run stream broke; falling back to its record");
- break false;
- }
- None => break saw_result,
- };
- match event {
- // The prompt typed on cursor.com. The translator
- // drops these (a live turn's prompt is already on
- // screen), but in a mirror it is the missing half of
- // the conversation — delivered quoted, since the log
- // renders everything here as the agent's.
- CursorEvent::Interaction(InteractionUpdate::UserMessage { text }) => {
- let quoted = text.replace('\n', "\n> ");
- self.notifier
- .notify(
- session_id,
- SessionUpdate::AgentMessageChunk(ContentChunk::new(
- ContentBlock::Text(TextContent::new(format!(
- "*(asked on cursor.com)*\n\n> {quoted}\n\n"
- ))),
- )),
- )
- .await?;
- }
- CursorEvent::Error { code, message } => {
- tracing::warn!(%agent, %run, ?code, %message, "foreign run stream errored; falling back to its record");
- break false;
- }
- event => {
- if matches!(event, CursorEvent::Result { .. }) {
- saw_result = true;
- }
- let done = matches!(event, CursorEvent::Done);
- let updates = {
- let mut state =
- session.state.lock().expect("session state poisoned");
- state.translator.push(event)
- };
- for update in updates {
- self.notifier.notify(session_id, update).await?;
- }
- if done {
- break saw_result;
- }
- }
- }
- }
- }
- Err(error) => {
- tracing::warn!(%agent, %run, %error, "foreign run stream unavailable; falling back to its record");
- false
+ let (expected, duplicate) = {
+ let state = session.state.lock().expect("session state poisoned");
+ if state.capture_failed {
+ return Err(SessionError::Journal(rootcause::report!(
+ "reload required after native journal failure"
+ )));
}
+ (
+ state.journal_entries.last().map_or(0, |e| e.sequence),
+ matches!(input, JournalInput::Poll(_))
+ && state
+ .journal_entries
+ .last()
+ .is_some_and(|e| e.run.as_ref() == run && e.input == input),
+ )
};
- if replayed {
+ if duplicate {
return Ok(());
}
-
- // The stream is gone (retention expired, or refused past the connect
- // retries). The run record still has the final answer.
- let outcome = self
- .cursor
- .run_result(agent, run)
+ let entry = self
+ .journal
+ .append(id, expected, run, &input)
.await
- .map_err(SessionError::Cursor)?;
- let mut events = Vec::new();
- if let Some(text) = outcome.text.clone() {
- events.push(CursorEvent::Assistant {
- text: format!("*(answered on cursor.com)*\n\n{text}"),
- });
- }
- events.push(CursorEvent::Result {
- run_id: run.clone(),
- status: outcome.status,
- text: None,
- duration_ms: None,
- });
- for event in events {
- let updates = {
+ .map_err(|error| {
let mut state = session.state.lock().expect("session state poisoned");
- state.translator.push(event)
+ state.capture_failed = true;
+ state.ready_for_sync = false;
+ SessionError::Journal(error)
+ })?;
+ let (updates, completion) = {
+ let mut state = session.state.lock().expect("session state poisoned");
+ let before = run.and_then(|run| state.machine.terminal_status(run));
+ state.journal_entries.push(entry.clone());
+ let SessionState {
+ machine,
+ journal_entries,
+ ..
+ } = &mut *state;
+ let updates = match project_entry(machine, &entry, journal_entries) {
+ Ok(updates) => updates,
+ Err(error) => {
+ state.capture_failed = true;
+ state.ready_for_sync = false;
+ return Err(SessionError::Journal(error));
+ }
+ };
+ // Local active prompts finish through their correlated response.
+ // A recovered tail has no pending response, so publish its fact.
+ let completion = if before.is_none() && run != state.active_run.as_ref() {
+ run.and_then(|run| state.machine.terminal_status(run))
+ .map(turn_outcome)
+ } else {
+ None
};
+ (updates, completion)
+ };
+ if emit {
+ // The live prompt request already carries these original blocks.
+ // Replay projects them at the run boundary; live must not echo them.
+ let local_prompt = run.is_some_and(|run| {
+ let state = session.state.lock().expect("session state poisoned");
+ state.active_run.as_ref() == Some(run)
+ && state.journal_entries.iter().any(|e| {
+ e.run.as_ref() == Some(run)
+ && matches!(e.input, JournalInput::PromptAccepted(_))
+ })
+ });
for update in updates {
- self.notifier.notify(session_id, update).await?;
+ if local_prompt && matches!(update, SessionUpdate::UserMessageChunk(_)) {
+ continue;
+ }
+ self.notifier.notify(id, update).await.map_err(|error| {
+ let mut state = session.state.lock().expect("session state poisoned");
+ state.capture_failed = true;
+ state.ready_for_sync = false;
+ SessionError::Journal(error)
+ })?;
+ }
+ if let Some(outcome) = completion {
+ self.notifier
+ .turn_complete(id, outcome)
+ .await
+ .map_err(|error| {
+ let mut state = session.state.lock().expect("session state poisoned");
+ state.capture_failed = true;
+ state.ready_for_sync = false;
+ SessionError::Journal(error)
+ })?;
}
}
Ok(())
}
- /// Finish a turn without a stream: poll the run until it is terminal,
- /// then deliver what streaming would have.
- ///
- /// `streamed_text` says whether any assistant text already reached the
- /// client live, so a turn whose stream died halfway does not repeat the
- /// whole answer from the run's final result. Liveness is what this path
- /// gives up; tool-call detail too — the run record carries only the final
- /// text — but the turn ends with its answer delivered and its real
- /// outcome, which is the part that must not be lost.
- async fn poll_turn(
- &self,
- session_id: &SessionId,
- session: &Session,
- agent: &CursorAgentId,
- run: &CursorRunId,
- streamed_text: bool,
- cancel: &tokio_util::sync::CancellationToken,
- ) -> Result<StopReason, SessionError> {
- let mut consecutive_errors = 0;
- for _ in 0..POLL_ATTEMPTS {
- // Both waits below go through `wait_unless_stopped`, the one
- // place a stop ends this poll.
- let outcome = match self.cursor.run_result(agent, run).await {
- Ok(outcome) => outcome,
- // A blip mid-poll is survivable; the same failure over and
- // over is the API saying no.
- Err(error) if consecutive_errors < POLL_ERROR_TOLERANCE => {
- consecutive_errors += 1;
- tracing::warn!(%agent, %run, %error, consecutive_errors, "run poll failed");
- if self.wait_unless_stopped(session_id, session, cancel).await {
- return Ok(StopReason::Cancelled);
- }
- continue;
+ /// Reconstruct the entire session before allowing a successful load reply.
+ /// The returned guard serializes the reply itself with every live writer.
+ pub async fn replay_session(&self, id: &SessionId) -> Result<ReplayGuard, SessionError> {
+ let session = self.session(id)?;
+ let gate = Arc::clone(&session.turn_gate).lock_owned().await;
+ {
+ let mut state = session.state.lock().expect("session state poisoned");
+ state.ready_for_sync = false;
+ state.journal_loaded = false;
+ state.capture_failed = false;
+ }
+ self.ensure_journal(id, &session).await?;
+ let (agent, complete) = {
+ let state = session.state.lock().expect("session state poisoned");
+ (
+ state.agent.clone(),
+ state
+ .journal_entries
+ .iter()
+ .any(|e| e.input == JournalInput::HistoryComplete),
+ )
+ };
+ // Old sessions are only safe when every run can still be fetched in
+ // full (including its original user message), not just final answers.
+ if !complete {
+ if let Some(agent) = &agent {
+ let listings = self.cursor.list_runs(agent, None).await?;
+ if listings.is_empty() {
+ return Err(rootcause::report!(
+ "Cursor history unavailable for restored session"
+ )
+ .into());
}
- Err(error) => return Err(SessionError::Cursor(error)),
- };
- consecutive_errors = 0;
- if !outcome.is_terminal() {
- if self.wait_unless_stopped(session_id, session, cancel).await {
- return Ok(StopReason::Cancelled);
+ for listing in listings.into_iter().rev() {
+ let captured = {
+ let state = session.state.lock().expect("session state poisoned");
+ state.machine.complete(&listing.id)
+ && state.journal_entries.iter().any(|e| {
+ e.run.as_ref() == Some(&listing.id)
+ && e.input == JournalInput::Reconciled
+ })
+ };
+ if captured {
+ continue;
+ }
+ self.ingest_run(
+ id,
+ &session,
+ agent,
+ &listing.id,
+ &tokio_util::sync::CancellationToken::new(),
+ IngestMode::HYDRATE,
+ )
+ .await?;
}
- continue;
}
-
- tracing::info!(%agent, %run, status = ?outcome.status, "run finished; delivering its polled result");
- let mut events = Vec::new();
- if let (false, Some(text)) = (streamed_text, outcome.text.clone()) {
- events.push(CursorEvent::Assistant { text });
+ self.capture(id, &session, None, JournalInput::HistoryComplete, false)
+ .await?;
+ }
+ let entries = session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .journal_entries
+ .clone();
+ let (machine, updates) = history_projection(&entries)?;
+ for (batch, outcome) in updates {
+ for update in batch {
+ self.notifier.notify(id, update).await?;
}
- events.push(CursorEvent::Result {
- run_id: run.clone(),
- status: outcome.status.clone(),
- text: outcome.text,
- duration_ms: None,
- });
- for event in events {
- let updates = {
- let mut state = session.state.lock().expect("session state poisoned");
- state.translator.push(event)
- };
- for update in updates {
- self.notifier.notify(session_id, update).await?;
- }
+ if let Some(outcome) = outcome {
+ self.notifier.turn_complete(id, outcome).await?;
}
- return match outcome.status {
- RunStatus::Finished => Ok(StopReason::EndTurn),
- RunStatus::Cancelled => {
- self.close_open_tool_calls(session_id, session).await;
- Ok(StopReason::Cancelled)
- }
- status => Err(SessionError::Cursor(rootcause::report!(
- "cursor run {run} ended in {status:?}"
- ))),
- };
}
- Err(SessionError::Cursor(rootcause::report!(
- "cursor run {run} still not terminal after polling for {} seconds",
- POLL_ATTEMPTS as u64 * POLL_INTERVAL.as_secs()
- )))
+ if let Some(run) = entries.iter().rev().find_map(|entry| {
+ (entry.input == JournalInput::Reconciled)
+ .then_some(entry.run.as_ref())
+ .flatten()
+ }) {
+ self.notifier.checkpoint(id, run).await?;
+ session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .last_run = Some(run.clone());
+ }
+ session
+ .state
+ .lock()
+ .expect("session state poisoned")
+ .machine = machine;
+ Ok(ReplayGuard {
+ session,
+ _gate: gate,
+ })
}
/// Mirror cursor.com activity into every live session, once.
@@ -1148,8 +1542,7 @@ where
/// The host calls this on a timer while a session's transport is up, so
/// the cursor.com half of a conversation appears here within a tick of
/// happening rather than waiting for the next Macro prompt. A session
- /// mid-turn is skipped (the turn gate is held), as is one that never
- /// drove a run (no watermark to mirror from). Failures are logged per
+ /// mid-turn is skipped (the turn gate is held). Failures are logged per
/// session and never stop the sweep.
pub async fn sync_foreign_runs(&self) {
let sessions: Vec<(SessionId, Arc<Session>)> = self
@@ -1163,13 +1556,13 @@ where
let Ok(_turn) = session.turn_gate.try_lock() else {
continue;
};
- let Some(agent) = session
- .state
- .lock()
- .expect("session state poisoned")
- .agent
- .clone()
- else {
+ let agent = {
+ let state = session.state.lock().expect("session state poisoned");
+ (state.ready_for_sync && !state.reload_pending)
+ .then(|| state.agent.clone())
+ .flatten()
+ };
+ let Some(agent) = agent else {
continue;
};
if let Err(error) = self
@@ -1181,6 +1574,19 @@ where
}
}
+ /// Whether any session is currently executing a turn.
+ ///
+ /// Hosts use this to distinguish a genuinely idle connection from one
+ /// whose provider is still working without producing client updates.
+ #[must_use]
+ pub fn has_active_turn(&self) -> bool {
+ self.sessions
+ .lock()
+ .expect("session map poisoned")
+ .values()
+ .any(|session| session.turn_gate.try_lock().is_err())
+ }
+
fn session(&self, id: &SessionId) -> Result<Arc<Session>, SessionError> {
self.sessions
.lock()
@@ -1190,3 +1596,147 @@ where
.ok_or_else(|| SessionError::UnknownSession(id.clone()))
}
}
+
+/// Holds the session writer gate through queuing the ACP load response.
+pub struct ReplayGuard {
+ session: Arc<Session>,
+ _gate: tokio::sync::OwnedMutexGuard<()>,
+}
+impl ReplayGuard {
+ /// Enable continuation only after the response was successfully queued.
+ pub fn complete(self) {
+ let mut state = self.session.state.lock().expect("session state poisoned");
+ state.ready_for_sync = true;
+ state.reload_pending = false;
+ }
+}
+
+fn replay_input(
+ entry: &JournalEntry,
+ entries: &[JournalEntry],
+) -> Result<JournalInput, rootcause::Report> {
+ match entry.input {
+ JournalInput::PromptAccepted(sequence) => entries
+ .iter()
+ .find(|e| e.sequence == sequence && e.run.is_none())
+ .map(|e| e.input.clone())
+ .ok_or_else(|| rootcause::report!("missing original Cursor prompt").into_dynamic()),
+ _ => Ok(entry.input.clone()),
+ }
+}
+
+/// Project conversational facts independently of pre-execution intent order.
+fn project_entry(
+ machine: &mut ReplayMachine,
+ entry: &JournalEntry,
+ entries: &[JournalEntry],
+) -> Result<Vec<SessionUpdate>, rootcause::Report> {
+ if matches!(entry.input, JournalInput::PromptAccepted(_))
+ || (entry.run.is_none() && matches!(entry.input, JournalInput::Prompt(_)))
+ {
+ return Ok(Vec::new());
+ }
+ let mut updates = Vec::new();
+ if let Some(run) = &entry.run
+ && !machine.has_prompt(run)
+ && let Some(accepted) = entries.iter().find(|e| {
+ e.run.as_ref() == Some(run) && matches!(e.input, JournalInput::PromptAccepted(_))
+ })
+ {
+ updates.extend(machine.push(Some(run), &replay_input(accepted, entries)?)?);
+ }
+ if let JournalInput::PromptAborted(sequence) = entry.input
+ && let Some(intent) = entries.iter().find(|e| e.sequence == sequence)
+ {
+ updates.extend(machine.push(None, &intent.input)?);
+ }
+ updates.extend(machine.push(entry.run.as_ref(), &entry.input)?);
+ Ok(updates)
+}
+
+fn turn_outcome(status: RunStatus) -> agent_runtime_protocol::domain::turn::TurnOutcome {
+ use agent_runtime_protocol::domain::turn::TurnOutcome;
+ match status {
+ RunStatus::Finished => TurnOutcome::Finished,
+ RunStatus::Cancelled => TurnOutcome::Cancelled,
+ status => TurnOutcome::Failed {
+ message: format!("Agent run ended in {status:?}"),
+ },
+ }
+}
+
+type HistoryUpdates = Vec<(
+ Vec<SessionUpdate>,
+ Option<agent_runtime_protocol::domain::turn::TurnOutcome>,
+)>;
+
+fn history_projection(
+ entries: &[JournalEntry],
+) -> Result<(ReplayMachine, HistoryUpdates), SessionError> {
+ for entry in entries {
+ if entry.run.is_none()
+ && matches!(entry.input, JournalInput::Prompt(_))
+ && !entries.iter().any(|e| {
+ matches!(e.input, JournalInput::PromptAccepted(n) | JournalInput::PromptAborted(n) if n == entry.sequence)
+ })
+ {
+ return Err(rootcause::report!("Cursor prompt acceptance is unknown; refusing incomplete replacement history").into());
+ }
+ }
+ let mut machine = ReplayMachine::default();
+ // Validate the whole candidate before publishing even its first frame.
+ // Intent position is audit order, not conversation order. Accepted
+ // prompts project immediately before their first native run input.
+ let mut updates = Vec::new();
+ for entry in entries {
+ let before = entry
+ .run
+ .as_ref()
+ .and_then(|run| machine.terminal_status(run));
+ let projected = project_entry(&mut machine, entry, entries)?;
+ let terminal = entry
+ .run
+ .as_ref()
+ .and_then(|run| machine.terminal_status(run));
+ let outcome = if matches!(entry.input, JournalInput::PromptAborted(_)) {
+ Some(agent_runtime_protocol::domain::turn::TurnOutcome::Cancelled)
+ } else if before.is_none() {
+ terminal.map(turn_outcome)
+ } else {
+ None
+ };
+ updates.push((projected, outcome));
+ }
+ // Acceptance can be durable before the first stream observation. Its
+ // prompt belongs at the unfinished tail, after captured older runs.
+ // If an older tail is still incomplete, defer the queued prompt until
+ // recovery reaches its run; it must not steal the older turn boundary.
+ for entry in entries {
+ if let JournalInput::PromptAccepted(_) = entry.input
+ && let Some(run) = &entry.run
+ && !machine.has_prompt(run)
+ && !entries
+ .iter()
+ .filter_map(|e| e.run.as_ref())
+ .any(|other| other != run && machine.has_prompt(other) && !machine.complete(other))
+ {
+ updates.push((
+ machine.push(Some(run), &replay_input(entry, entries)?)?,
+ None,
+ ));
+ }
+ }
+ for run in entries.iter().filter_map(|e| e.run.as_ref()) {
+ let accepted_only = entries
+ .iter()
+ .filter(|e| e.run.as_ref() == Some(run))
+ .all(|e| matches!(e.input, JournalInput::PromptAccepted(_)));
+ if !machine.has_prompt(run) && !accepted_only {
+ return Err(rootcause::report!(
+ "Cursor original prompt unavailable for {run}; preserving existing history"
+ )
+ .into());
+ }
+ }
+ Ok((machine, updates))
+}
diff --git a/crates/cursor_cloud_agents/src/domain/service/test.rs b/crates/cursor_cloud_agents/src/domain/service/test.rs
index 97afd53486..5ddce9fe4a 100644
--- a/crates/cursor_cloud_agents/src/domain/service/test.rs
+++ b/crates/cursor_cloud_agents/src/domain/service/test.rs
@@ -17,10 +17,77 @@ fn service(repo: Option<RepoUrl>) -> (Arc<Service>, FakeCursor, RecordingNotifie
cursor.clone(),
notifier.clone(),
FixedRepos(repo),
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
));
(service, cursor, notifier)
}
+/// Agent text chunks, in delivery order.
+fn agent_texts(updates: &[(SessionId, SessionUpdate)]) -> Vec<String> {
+ updates
+ .iter()
+ .filter_map(|(_, update)| match update {
+ SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content {
+ ContentBlock::Text(text) => Some(text.text.clone()),
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect()
+}
+
+/// User text chunks, in delivery order.
+fn user_texts(updates: &[(SessionId, SessionUpdate)]) -> Vec<String> {
+ updates
+ .iter()
+ .filter_map(|(_, update)| match update {
+ SessionUpdate::UserMessageChunk(chunk) => match &chunk.content {
+ ContentBlock::Text(text) => Some(text.text.clone()),
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect()
+}
+
+fn ready_for_sync(service: &Service, id: &SessionId) -> bool {
+ service
+ .session(id)
+ .expect("session exists")
+ .state
+ .lock()
+ .expect("state poisoned")
+ .ready_for_sync
+}
+
+/// The session's run-delivery watermark.
+fn last_run(service: &Service, id: &SessionId) -> Option<CursorRunId> {
+ service
+ .session(id)
+ .expect("session exists")
+ .state
+ .lock()
+ .expect("state poisoned")
+ .last_run
+ .clone()
+}
+
+/// The client's standard load that a reload requirement asks for: the only
+/// path recovered history reaches the client through. Returns what it showed.
+async fn load(
+ service: &Service,
+ id: &SessionId,
+ notifier: &RecordingNotifier,
+) -> Vec<(SessionId, SessionUpdate)> {
+ let before = notifier.updates().len();
+ service.replay_session(id).await.expect("load").complete();
+ assert!(
+ ready_for_sync(service, id),
+ "a successful load re-enables sync"
+ );
+ notifier.updates()[before..].to_vec()
+}
+
fn finished(run: &str) -> CursorEvent {
CursorEvent::Result {
run_id: CursorRunId::new(run),
@@ -39,6 +106,18 @@ fn cancelled(run: &str) -> CursorEvent {
}
}
+#[tokio::test]
+async fn active_turn_is_reported_while_cursor_is_working() {
+ let (service, _cursor, _notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+ let stored = service.session(&session).expect("session exists");
+ let turn = stored.turn_gate.lock().await;
+ assert!(service.has_active_turn());
+
+ drop(turn);
+ assert!(!service.has_active_turn());
+}
+
#[tokio::test]
async fn first_prompt_creates_the_agent_with_the_session_repo() {
let repo = RepoUrl::parse("https://github.com/macro-inc/macro").expect("valid repo");
@@ -359,6 +438,17 @@ async fn a_stop_ends_the_fallback_poll_at_its_first_wait() {
.filter(|call| matches!(call, CursorCall::RunResult(..)))
.count();
assert_eq!(polls, 1, "one read of the record, then the stop ends it");
+ assert!(
+ service
+ .session(&session)
+ .unwrap()
+ .state
+ .lock()
+ .unwrap()
+ .last_run
+ .is_none(),
+ "local stop does not advance delivered watermark without reconciliation"
+ );
}
/// A stop that beats the run into existence.
@@ -445,6 +535,10 @@ async fn unknown_session_is_an_error() {
service.prompt(&missing, "hi").await,
Err(SessionError::UnknownSession(_))
));
+ assert!(matches!(
+ service.loaded(&missing),
+ Err(SessionError::UnknownSession(_))
+ ));
}
#[tokio::test]
@@ -570,7 +664,7 @@ async fn an_unknown_terminal_status_fails_the_turn() {
assert!(matches!(
service.prompt(&session, "hi").await,
- Err(SessionError::Cursor(_))
+ Err(SessionError::Journal(_))
));
}
@@ -741,6 +835,12 @@ async fn a_restored_session_prompts_its_existing_agent() {
None,
None,
);
+ crate::testing::script_legacy_history(&cursor);
+ service
+ .replay_session(&SessionId::new("cursor-acp-7"))
+ .await
+ .expect("full legacy history")
+ .complete();
assert!(service.has_session(&SessionId::new("cursor-acp-7")));
let events = cursor.script_stream();
@@ -898,6 +998,11 @@ async fn new_sessions_never_collide_with_restored_ids() {
async fn a_session_restored_without_an_agent_mints_one_on_the_next_prompt() {
let (service, cursor, _notifier) = service(None);
service.restore_session(SessionId::new("cursor-acp-9"), None, None, None);
+ service
+ .replay_session(&SessionId::new("cursor-acp-9"))
+ .await
+ .expect("empty session")
+ .complete();
assert!(service.has_session(&SessionId::new("cursor-acp-9")));
let events = cursor.script_stream();
@@ -940,27 +1045,25 @@ async fn a_prompt_waits_out_a_busy_agent() {
}
/// Runs driven from cursor.com since the session's own last turn are
-/// mirrored before the next prompt's output — full fidelity, oldest first:
-/// the stream replay carries the cursor.com user's prompt (quoted) and the
-/// agent's answer, so the client's view keeps up with the conversation its
-/// prompt is about to continue.
+/// captured into the journal before the next prompt executes, in full
+/// fidelity, oldest first. They never stream live: the prompt's own turn is
+/// all the client sees until the reload the recovery requires, after which
+/// the standard load shows the cursor.com user's prompt and the agent's
+/// answer ahead of the turn that was about to continue the conversation.
#[tokio::test]
-async fn foreign_runs_are_mirrored_before_the_next_prompt() {
+async fn foreign_runs_are_captured_before_the_next_prompt_and_shown_by_its_reload() {
let (service, cursor, notifier) = service(None);
let session = service.new_session(Path::new(""), Vec::new());
let events = cursor.script_stream();
events.send(finished("run-fake-1")).expect("stream open");
events.send(CursorEvent::Done).expect("stream open");
service.prompt(&session, "first").await.expect("first turn");
+ assert!(notifier.reloads().is_empty());
// One cursor.com run happened since run-fake-1. The page also contains
// the run this prompt itself is about to create — which must not be
- // mirrored, its own turn delivers it.
+ // recovered, its own turn delivers it.
cursor.script_run_listings(vec![
- RunListing {
- id: CursorRunId::new("run-fake-2"),
- status: RunStatus::Running,
- },
RunListing {
id: CursorRunId::new("run-foreign-1"),
status: RunStatus::Finished,
@@ -970,7 +1073,7 @@ async fn foreign_runs_are_mirrored_before_the_next_prompt() {
status: RunStatus::Finished,
},
]);
- // The streams `prompt("second")` consumes, in order: the mirror of the
+ // The streams `prompt("second")` consumes, in order: the capture of the
// foreign run, then the turn's own.
let foreign = cursor.script_stream();
foreign
@@ -999,32 +1102,82 @@ async fn foreign_runs_are_mirrored_before_the_next_prompt() {
.prompt(&session, "second")
.await
.expect("second turn");
- let texts: Vec<String> = notifier
- .updates()
- .iter()
- .filter_map(|(_, update)| match update {
- SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content {
- agent_client_protocol::schema::v1::ContentBlock::Text(text) => {
- Some(text.text.clone())
- }
- _ => None,
- },
- _ => None,
- })
- .collect();
- // The mirrored prompt (quoted, attributed), its answer, then the turn's.
+ assert_eq!(
+ agent_texts(&notifier.updates()),
+ vec!["own answer"],
+ "recovered history never streams live"
+ );
+ assert!(user_texts(&notifier.updates()).is_empty());
+ // The prompt path reconciles before and after acceptance; the requirement
+ // coalesces into one signal until the client loads.
+ assert_eq!(notifier.reloads(), vec![session.clone()]);
assert!(
- texts[0].contains("asked on cursor.com") && texts[0].contains("> but like what is macro"),
- "got {texts:?}"
+ ready_for_sync(&service, &session),
+ "the host owns the dispatch barrier; recovery does not close the session"
);
- assert_eq!(texts[1], "a team workspace", "got {texts:?}");
- assert_eq!(texts[2], "own answer", "got {texts:?}");
+
+ let loaded = load(&service, &session, &notifier).await;
+ assert_eq!(
+ user_texts(&loaded),
+ vec!["first", "but like what is macro", "second"]
+ );
+ assert_eq!(agent_texts(&loaded), vec!["a team workspace", "own answer"]);
+
+ // The load checkpointed the prompt's own run, which now heads Cursor's
+ // listing: the next tick recovers nothing and requires no reload.
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-fake-2"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: CursorRunId::new("run-foreign-1"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: CursorRunId::new("run-fake-1"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ let shown = notifier.updates().len();
+ service.sync_foreign_runs().await;
+ assert_eq!(notifier.updates().len(), shown);
+ assert_eq!(notifier.reloads().len(), 1);
+ assert!(ready_for_sync(&service, &session));
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("later"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: last_run(&service, &session).unwrap(),
+ status: RunStatus::Finished,
+ },
+ ]);
+ let later = cursor.script_stream();
+ later
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "later question".into(),
+ }))
+ .unwrap();
+ later.send(finished("later")).unwrap();
+ later.send(CursorEvent::Done).unwrap();
+ service.sync_foreign_runs().await;
+ assert_eq!(
+ notifier.reloads().len(),
+ 2,
+ "successful load re-arms recovery"
+ );
+ assert_eq!(notifier.updates().len(), shown);
+ let reloaded = load(&service, &session, &notifier).await;
+ assert_eq!(user_texts(&reloaded).last().unwrap(), "later question");
}
-/// The host's poll: cursor.com activity mirrors into a session within a
-/// tick, without any Macro prompt — and mirrors exactly once.
+/// The host's poll: cursor.com activity is captured into a session within a
+/// tick, without any Macro prompt — exactly once, and only ever shown through
+/// the standard load the capture requires.
#[tokio::test]
-async fn sync_mirrors_foreign_runs_once() {
+async fn sync_captures_foreign_runs_once_and_requires_one_load_to_show_them() {
let (service, cursor, notifier) = service(None);
let session = service.new_session(Path::new(""), Vec::new());
let events = cursor.script_stream();
@@ -1044,6 +1197,11 @@ async fn sync_mirrors_foreign_runs_once() {
},
]);
let foreign = cursor.script_stream();
+ foreign
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "asked over there".to_owned(),
+ }))
+ .expect("stream open");
foreign
.send(CursorEvent::Assistant {
text: "from over there".to_owned(),
@@ -1055,16 +1213,270 @@ async fn sync_mirrors_foreign_runs_once() {
foreign.send(CursorEvent::Done).expect("stream open");
service.sync_foreign_runs().await;
- let after_first = notifier.updates().len();
- assert!(after_first > before, "the foreign run must be delivered");
+ assert_eq!(
+ notifier.updates().len(),
+ before,
+ "recovered history never streams live"
+ );
+ assert_eq!(notifier.reloads(), vec![session.clone()]);
+ assert!(
+ ready_for_sync(&service, &session),
+ "the host owns the dispatch barrier; recovery does not close the session"
+ );
+ // While the requirement is pending, background ticks skip the session
+ // rather than signalling again.
+ service.sync_foreign_runs().await;
+ assert_eq!(notifier.reloads().len(), 1);
+ assert_eq!(notifier.updates().len(), before);
+
+ let loaded = load(&service, &session, &notifier).await;
+ assert_eq!(user_texts(&loaded), vec!["first", "asked over there"]);
+ assert_eq!(agent_texts(&loaded), vec!["from over there"]);
+
+ // The load moved the watermark: the same listing recovers nothing more
+ // and requires no further reload.
+ let shown = notifier.updates().len();
+ service.sync_foreign_runs().await;
+ assert_eq!(notifier.updates().len(), shown);
+ assert_eq!(notifier.reloads().len(), 1);
+ assert!(ready_for_sync(&service, &session));
+}
+
+#[tokio::test]
+async fn standalone_recovery_does_not_require_a_host_channel() {
+ crate::inbound::acp::AcpNotifier::new()
+ .require_reload(&SessionId::new("standalone"))
+ .await
+ .unwrap();
+}
+
+/// Restore seeds the durable watermark. The client's initial load hydrates the
+/// legacy run the watermark covers; only a run Cursor finished after it is
+/// recovered by sync — captured once, never streamed, then shown in provider
+/// order by the load the recovery requires, after which the tick is idempotent.
+#[tokio::test]
+async fn restore_recovers_runs_after_the_durable_watermark_once() {
+ let cursor = FakeCursor::new();
+ let notifier = RecordingNotifier::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ notifier.clone(),
+ FixedRepos(None),
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
+ );
+ let session = SessionId::new("cursor-acp-restored");
+ service.restore_session_with_watermark(
+ session.clone(),
+ Some(CursorAgentId::new("bc-restored")),
+ None,
+ None,
+ Some(CursorRunId::new("run-delivered")),
+ );
+ // The initial load hydrates the run this session delivered before the
+ // restart, from the provider's complete stream.
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("run-delivered"),
+ status: RunStatus::Finished,
+ }]);
+ let delivered = cursor.script_stream();
+ delivered
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "earlier question".to_owned(),
+ }))
+ .expect("stream open");
+ delivered
+ .send(CursorEvent::Assistant {
+ text: "earlier answer".to_owned(),
+ })
+ .expect("stream open");
+ delivered
+ .send(finished("run-delivered"))
+ .expect("stream open");
+ delivered.send(CursorEvent::Done).expect("stream open");
+ let initial = load(&service, &session, &notifier).await;
+ assert_eq!(user_texts(&initial), ["earlier question"]);
+ assert_eq!(agent_texts(&initial), ["earlier answer"]);
+ assert_eq!(
+ last_run(&service, &session),
+ Some(CursorRunId::new("run-delivered"))
+ );
+
+ // Then a run happens on cursor.com.
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-missed"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: CursorRunId::new("run-delivered"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ let missed = cursor.script_stream();
+ missed
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "missed question".to_owned(),
+ }))
+ .expect("stream open");
+ missed
+ .send(CursorEvent::Assistant {
+ text: "recovered answer".to_owned(),
+ })
+ .expect("stream open");
+ missed.send(finished("run-missed")).expect("stream open");
+ missed.send(CursorEvent::Done).expect("stream open");
+ service.sync_foreign_runs().await;
+ assert_eq!(
+ notifier.updates().len(),
+ initial.len(),
+ "recovered history never streams live"
+ );
+ assert_eq!(notifier.reloads(), vec![session.clone()]);
+ let captured = |run: &str| {
+ service
+ .session(&session)
+ .expect("session exists")
+ .state
+ .lock()
+ .expect("state poisoned")
+ .journal_entries
+ .iter()
+ .filter(|e| e.run.as_ref() == Some(&CursorRunId::new(run)))
+ .filter(|e| e.input == JournalInput::Reconciled)
+ .count()
+ };
+ assert_eq!(captured("run-missed"), 1);
+ assert_eq!(
+ captured("run-delivered"),
+ 1,
+ "the delivered run was hydrated by the load and is not recovered again"
+ );
+
+ let loaded = load(&service, &session, &notifier).await;
+ assert_eq!(user_texts(&loaded), ["earlier question", "missed question"]);
+ assert_eq!(agent_texts(&loaded), ["earlier answer", "recovered answer"]);
+ assert_eq!(
+ last_run(&service, &session),
+ Some(CursorRunId::new("run-missed")),
+ "the load checkpoints the newest reconciled run"
+ );
+ let shown = notifier.updates().len();
+ service.sync_foreign_runs().await;
+ assert_eq!(notifier.updates().len(), shown);
+ assert_eq!(notifier.reloads().len(), 1);
+}
+
+/// Sessions created before run checkpoints existed have no durable watermark.
+/// Their initial load hydrates every run Cursor lists, oldest first, and
+/// checkpoints the newest — so nothing is missed and the first sync tick
+/// afterwards recovers nothing.
+#[tokio::test]
+async fn restore_without_a_watermark_hydrates_every_run_on_load() {
+ let cursor = FakeCursor::new();
+ let notifier = RecordingNotifier::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ notifier.clone(),
+ FixedRepos(None),
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
+ );
+ let session = SessionId::new("cursor-acp-restored");
+ service.restore_session_with_watermark(
+ session.clone(),
+ Some(CursorAgentId::new("bc-restored")),
+ None,
+ None,
+ None,
+ );
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-latest"),
+ status: RunStatus::Finished,
+ },
+ RunListing {
+ id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ for (run, question, answer) in [
+ ("run-old", "old question", "old answer"),
+ ("run-latest", "latest question", "latest answer"),
+ ] {
+ let stream = cursor.script_stream();
+ stream
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: question.to_owned(),
+ }))
+ .expect("stream open");
+ stream
+ .send(CursorEvent::Assistant {
+ text: answer.to_owned(),
+ })
+ .expect("stream open");
+ stream.send(finished(run)).expect("stream open");
+ stream.send(CursorEvent::Done).expect("stream open");
+ }
+
+ let loaded = load(&service, &session, &notifier).await;
+ assert_eq!(user_texts(&loaded), ["old question", "latest question"]);
+ assert_eq!(agent_texts(&loaded), ["old answer", "latest answer"]);
+ assert_eq!(
+ last_run(&service, &session),
+ Some(CursorRunId::new("run-latest")),
+ "the load's checkpoint makes the next tick idempotent"
+ );
+ service.sync_foreign_runs().await;
+ assert_eq!(notifier.updates().len(), loaded.len());
+ assert!(notifier.reloads().is_empty());
+}
+
+/// The host cannot route session updates until `session/load` has rebound the
+/// restored ACP id. A mirror tick before then must leave the durable checkpoint
+/// untouched so the next tick can recover the run after load.
+#[tokio::test]
+async fn restore_waits_for_session_load_before_recovering_runs() {
+ let cursor = FakeCursor::new();
+ let notifier = RecordingNotifier::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ notifier.clone(),
+ FixedRepos(None),
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
+ );
+ let session = SessionId::new("cursor-acp-restored");
+ service.restore_session_with_watermark(
+ session.clone(),
+ Some(CursorAgentId::new("bc-restored")),
+ None,
+ None,
+ Some(CursorRunId::new("run-delivered")),
+ );
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("run-missed"),
+ status: RunStatus::Finished,
+ }]);
- // The watermark moved: the same listing mirrors nothing more.
service.sync_foreign_runs().await;
- assert_eq!(notifier.updates().len(), after_first);
+
+ assert!(notifier.updates().is_empty());
+ assert!(notifier.reloads().is_empty());
+ assert!(
+ service
+ .session(&session)
+ .expect("session exists")
+ .state
+ .lock()
+ .expect("state poisoned")
+ .journal_entries
+ .is_empty()
+ );
}
-/// A foreign run whose stream is gone (retention expired) still delivers its
-/// recorded final text rather than vanishing.
+/// A foreign run whose stream is gone (retention expired) is captured from
+/// its run record, so the recorded answer is durable. But the record carries
+/// no original prompt: recovery must not ask the client to reload a history
+/// it cannot project, and an explicit load must fail rather than invent one —
+/// the client's prior view stays in place until a load succeeds.
#[tokio::test(start_paused = true)]
async fn an_expired_foreign_stream_falls_back_to_the_run_record() {
let (service, cursor, notifier) = service(None);
@@ -1091,45 +1503,118 @@ async fn an_expired_foreign_stream_falls_back_to_the_run_record() {
text: Some("the old answer".to_owned()),
});
+ let before = notifier.updates().len();
service.sync_foreign_runs().await;
- let texts: Vec<String> = notifier
- .updates()
- .iter()
- .filter_map(|(_, update)| match update {
- SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content {
- agent_client_protocol::schema::v1::ContentBlock::Text(text) => {
- Some(text.text.clone())
- }
- _ => None,
- },
- _ => None,
- })
- .collect();
+ assert_eq!(notifier.updates().len(), before);
assert!(
- texts
+ notifier.reloads().is_empty(),
+ "an unprojectable recovery requires no reload"
+ );
+ assert!(ready_for_sync(&service, &session));
+ let foreign = CursorRunId::new("run-foreign-1");
+ let continuation = cursor.script_stream();
+ continuation.send(finished("run-fake-2")).unwrap();
+ continuation.send(CursorEvent::Done).unwrap();
+ service
+ .prompt(&session, "continue without replacing history")
+ .await
+ .unwrap();
+ assert!(notifier.reloads().is_empty());
+ let entries = service.journal.read(&session).await.expect("journal");
+ assert!(
+ entries.iter().any(|e| e.run.as_ref() == Some(&foreign)
+ && matches!(&e.input, JournalInput::Poll(raw) if raw.contains("the old answer"))),
+ "the recorded answer is durable"
+ );
+ assert!(
+ entries
.iter()
- .any(|text| text.contains("answered on cursor.com") && text.contains("the old answer")),
- "got {texts:?}"
+ .any(|e| e.run.as_ref() == Some(&foreign) && e.input == JournalInput::Reconciled)
+ );
+
+ let error = service
+ .replay_session(&session)
+ .await
+ .err()
+ .expect("a run without its original prompt cannot replace history");
+ assert!(
+ error.to_string().contains("original prompt unavailable"),
+ "{error}"
+ );
+ assert_eq!(
+ notifier.updates().len(),
+ before,
+ "a failed load publishes nothing: the prior view is retained"
+ );
+ assert!(
+ !ready_for_sync(&service, &session),
+ "nothing syncs or prompts until a load succeeds"
+ );
+ assert_eq!(
+ service.journal.read(&session).await.expect("journal"),
+ entries,
+ "the failed load discards nothing captured"
);
}
-/// A stream that delivers the answer and then hangs open must not hold the
-/// turn open with it — seen live: the terminal `result` arrived minutes
-/// after the text, and the client showed "writing" long after the answer.
-/// Once the run's record says terminal, the turn closes from the record.
-#[tokio::test(start_paused = true)]
-async fn a_quiet_stream_closes_the_turn_from_the_run_record() {
+/// A run that is still executing cannot become the watermark when its stream
+/// is unavailable, and requires no reload yet: the next sync must retry it
+/// after Cursor finishes.
+#[tokio::test]
+async fn a_running_foreign_run_is_not_checkpointed_after_stream_fallback() {
let (service, cursor, notifier) = service(None);
let session = service.new_session(Path::new(""), Vec::new());
+ let initial = cursor.script_stream();
+ initial.send(finished("run-fake-1")).expect("stream open");
+ initial.send(CursorEvent::Done).expect("stream open");
+ service.prompt(&session, "first").await.expect("first turn");
- let events = cursor.script_stream();
- events
- .send(CursorEvent::Assistant {
- text: "the whole answer".to_owned(),
- })
- .expect("stream open");
- // The sender stays alive: the stream is open and silent, exactly the
- // observed hang. The record already knows the run finished.
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-foreign-1"),
+ status: RunStatus::Running,
+ },
+ RunListing {
+ id: CursorRunId::new("run-fake-1"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ // No stream is queued, so recovery falls back to this still-running record.
+ cursor.script_run_result(RunOutcome {
+ status: RunStatus::Running,
+ text: None,
+ });
+
+ service.sync_foreign_runs().await;
+
+ assert_eq!(
+ last_run(&service, &session),
+ Some(CursorRunId::new("run-fake-1"))
+ );
+ assert!(notifier.reloads().is_empty());
+ assert!(
+ ready_for_sync(&service, &session),
+ "an unreconciled run leaves the session open to the next tick"
+ );
+}
+
+/// A stream that delivers the answer and then hangs open must not hold the
+/// turn open with it — seen live: the terminal `result` arrived minutes
+/// after the text, and the client showed "writing" long after the answer.
+/// Once the run's record says terminal, the turn closes from the record.
+#[tokio::test(start_paused = true)]
+async fn a_quiet_stream_closes_the_turn_from_the_run_record() {
+ let (service, cursor, notifier) = service(None);
+ let session = service.new_session(Path::new(""), Vec::new());
+
+ let events = cursor.script_stream();
+ events
+ .send(CursorEvent::Assistant {
+ text: "the whole answer".to_owned(),
+ })
+ .expect("stream open");
+ // The sender stays alive: the stream is open and silent, exactly the
+ // observed hang. The record already knows the run finished.
cursor.script_run_result(RunOutcome {
status: RunStatus::Finished,
text: Some("the whole answer".to_owned()),
@@ -1153,3 +1638,874 @@ async fn a_quiet_stream_closes_the_turn_from_the_run_record() {
.count();
assert_eq!(text_updates, 1);
}
+
+/// The same durable inputs restore every turn without any provider execution.
+#[tokio::test]
+async fn durable_multiturn_load_replays_full_history_and_supports_continuation() {
+ use crate::outbound::memory_journal::MemoryJournal;
+ let journal = Arc::new(MemoryJournal::default());
+ let cursor = FakeCursor::new();
+ let live = RecordingNotifier::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ live.clone(),
+ FixedRepos(None),
+ journal.clone(),
+ );
+ let id = service.new_session(Path::new(""), vec![]);
+ for (prompt, fixture) in [
+ ("first prompt", "multi_turn_1.sse"),
+ ("second prompt", "file_operations.sse"),
+ ] {
+ let tx = cursor.script_raw_stream();
+ for event in crate::testing::fixture_records(fixture) {
+ tx.send(event).unwrap();
+ }
+ drop(tx);
+ service.prompt(&id, prompt).await.unwrap();
+ }
+ let entries = journal.read(&id).await.unwrap();
+ assert!(
+ entries.iter().all(
+ |e| !matches!(e.input, JournalInput::Sse(ref r) if r.data.contains("sessionUpdate"))
+ )
+ );
+ let before = cursor.calls();
+ let replayed = RecordingNotifier::new();
+ let restored = Arc::new(CursorSessionService::new(
+ cursor.clone(),
+ replayed.clone(),
+ FixedRepos(None),
+ journal.clone(),
+ ));
+ restored.restore_session(id.clone(), Some(CursorAgentId::new("bc-fake")), None, None);
+ restored.replay_session(&id).await.unwrap().complete();
+ let first = replayed.updates();
+ let replay_without_users: Vec<_> = first
+ .iter()
+ .filter(|(_, u)| !matches!(u, SessionUpdate::UserMessageChunk(_)))
+ .cloned()
+ .collect();
+ assert_eq!(replay_without_users, live.updates());
+ assert_eq!(
+ first
+ .iter()
+ .filter(|(_, u)| matches!(u, SessionUpdate::UserMessageChunk(_)))
+ .count(),
+ 2
+ );
+ assert_eq!(
+ cursor.calls(),
+ before,
+ "load must not execute provider work"
+ );
+ restored.replay_session(&id).await.unwrap().complete();
+ assert_eq!(&replayed.updates()[first.len()..], first.as_slice());
+ assert_eq!(
+ journal.read(&id).await.unwrap(),
+ entries,
+ "load is a read, not recapture"
+ );
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Assistant {
+ text: "next".into(),
+ })
+ .unwrap();
+ tx.send(finished("run-fake-3")).unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+ restored.prompt(&id, "continue").await.unwrap();
+ assert!(
+ matches!(cursor.calls().last(), Some(CursorCall::CreateRun(_, prompt, _)) if prompt == "continue")
+ );
+}
+
+#[derive(Debug, Default)]
+struct FailingJournal {
+ inner: crate::outbound::memory_journal::MemoryJournal,
+ fail_sequence: std::sync::atomic::AtomicI64,
+}
+impl CursorJournal for FailingJournal {
+ fn read<'a>(
+ &'a self,
+ id: &'a SessionId,
+ ) -> futures::future::BoxFuture<'a, Result<Vec<JournalEntry>, rootcause::Report>> {
+ self.inner.read(id)
+ }
+ fn append<'a>(
+ &'a self,
+ id: &'a SessionId,
+ expected: i64,
+ run: Option<&'a CursorRunId>,
+ input: &'a JournalInput,
+ ) -> futures::future::BoxFuture<'a, Result<JournalEntry, rootcause::Report>> {
+ Box::pin(async move {
+ if expected + 1 == self.fail_sequence.load(std::sync::atomic::Ordering::SeqCst) {
+ return Err(rootcause::report!("injected durable append failure"));
+ }
+ self.inner.append(id, expected, run, input).await
+ })
+ }
+}
+
+#[tokio::test]
+async fn append_failure_publishes_nothing_and_never_advances_delivery_or_retries_a_prompt() {
+ let journal = Arc::new(FailingJournal::default());
+ journal
+ .fail_sequence
+ .store(4, std::sync::atomic::Ordering::SeqCst);
+ let cursor = FakeCursor::new();
+ let output = RecordingNotifier::new();
+ let service = CursorSessionService::new(
+ cursor.clone(),
+ output.clone(),
+ FixedRepos(None),
+ journal.clone(),
+ );
+ let id = service.new_session(Path::new(""), vec![]);
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Assistant {
+ text: "must never escape".into(),
+ })
+ .unwrap();
+ tx.send(finished("run-fake-1")).unwrap();
+ assert!(matches!(
+ service.prompt(&id, "go").await,
+ Err(SessionError::Journal(_))
+ ));
+ assert!(output.updates().is_empty());
+ assert!(
+ service
+ .session(&id)
+ .unwrap()
+ .state
+ .lock()
+ .unwrap()
+ .last_run
+ .is_none()
+ );
+ assert_eq!(journal.read(&id).await.unwrap().len(), 3);
+ assert!(service.prompt(&id, "retry").await.is_err());
+ assert_eq!(
+ cursor.calls().len(),
+ 1,
+ "no second remote execution after capture failure"
+ );
+}
+
+#[tokio::test]
+async fn partial_capture_reconnect_matches_the_prefix_without_duplicate_content() {
+ let (service, cursor, notifier) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ {
+ let _gate = session.turn_gate.lock().await;
+ service.ensure_journal(&id, &session).await.unwrap();
+ let run = CursorRunId::new("foreign");
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Sse(crate::testing::raw_record(CursorEvent::Interaction(
+ InteractionUpdate::UserMessage {
+ text: "asked elsewhere".into(),
+ },
+ ))),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {
+ text: "hel".into(),
+ })),
+ false,
+ )
+ .await
+ .unwrap();
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "asked elsewhere".into(),
+ }))
+ .unwrap();
+ tx.send(CursorEvent::Assistant { text: "hel".into() })
+ .unwrap();
+ tx.send(CursorEvent::Assistant { text: "lo".into() })
+ .unwrap();
+ tx.send(finished("foreign")).unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+ service
+ .ingest_run(
+ &id,
+ &session,
+ &CursorAgentId::new("agent"),
+ &run,
+ &tokio_util::sync::CancellationToken::new(),
+ IngestMode {
+ emit: true,
+ ..IngestMode::HYDRATE
+ },
+ )
+ .await
+ .unwrap();
+ }
+ assert!(
+ matches!(&notifier.updates()[..], [(_, SessionUpdate::AgentMessageChunk(c))] if matches!(&c.content, ContentBlock::Text(t) if t.text == "lo"))
+ );
+ let entries = service.journal.read(&id).await.unwrap();
+ assert_eq!(entries.iter().filter(|e| matches!(&e.input, JournalInput::Sse(r) if matches!(r.decode(), CursorEvent::Assistant { text } if text == "hel"))).count(), 1);
+}
+
+#[tokio::test]
+async fn restored_agent_without_provider_history_cannot_commit_empty_replacement() {
+ let (service, cursor, notifier) = service(None);
+ let id = SessionId::new("restored");
+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);
+ cursor.script_run_listings(vec![]);
+
+ assert!(service.replay_session(&id).await.is_err());
+ assert!(notifier.updates().is_empty());
+ assert!(service.journal.read(&id).await.unwrap().is_empty());
+ assert!(service.prompt(&id, "must not execute").await.is_err());
+ assert!(cursor.calls().is_empty());
+}
+
+#[tokio::test]
+async fn incomplete_legacy_hydration_emits_nothing_and_cannot_enable_sync() {
+ let (service, cursor, notifier) = service(None);
+ let id = SessionId::new("old");
+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ }]);
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Assistant {
+ text: "answer without original prompt".into(),
+ })
+ .unwrap();
+ tx.send(finished("run-old")).unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+ drop(tx);
+ assert!(service.replay_session(&id).await.is_err());
+ assert!(notifier.updates().is_empty());
+ assert!(!ready_for_sync(&service, &id));
+ assert!(
+ !service
+ .journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .any(|e| e.input == JournalInput::HistoryComplete)
+ );
+ assert!(service.prompt(&id, "must not execute").await.is_err());
+ assert!(cursor.calls().is_empty());
+}
+
+#[tokio::test]
+async fn load_guard_orders_continuation_after_the_queued_response() {
+ let (service, cursor, _notifier) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let guard = service.replay_session(&id).await.unwrap();
+ let tx = cursor.script_stream();
+ tx.send(finished("run-fake-1")).unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+ let next = tokio::spawn({
+ let service = service.clone();
+ let id = id.clone();
+ async move { service.prompt(&id, "next").await }
+ });
+ tokio::task::yield_now().await;
+ assert!(
+ cursor.calls().is_empty(),
+ "the load gate still owns emission"
+ );
+ guard.complete(); // the ACP adapter does this only after responder.respond
+ next.await.unwrap().unwrap();
+}
+
+#[tokio::test]
+async fn stream_unavailable_records_are_captured_before_retry() {
+ let (service, cursor, _notifier) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let first = cursor.script_stream();
+ first
+ .send(CursorEvent::Error {
+ code: Some("stream_unavailable".into()),
+ message: "starting".into(),
+ })
+ .unwrap();
+ let second = cursor.script_stream();
+ second.send(finished("run-fake-1")).unwrap();
+ second.send(CursorEvent::Done).unwrap();
+ service.prompt(&id, "go").await.unwrap();
+ assert!(service.journal.read(&id).await.unwrap().iter().any(|e| matches!(&e.input, JournalInput::Sse(r) if matches!(r.decode(), CursorEvent::Error { .. }))));
+}
+
+#[tokio::test]
+async fn aborted_prompt_is_retained_in_load_history_without_remote_execution() {
+ let (service, cursor, output) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ {
+ let _gate = session.turn_gate.lock().await;
+ service.ensure_journal(&id, &session).await.unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ None,
+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new(
+ "stopped before execution",
+ ))]),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(&id, &session, None, JournalInput::PromptAborted(2), false)
+ .await
+ .unwrap();
+ }
+ service.replay_session(&id).await.unwrap().complete();
+ assert!(
+ matches!(&output.updates()[..], [(_, SessionUpdate::UserMessageChunk(c))] if matches!(&c.content, ContentBlock::Text(t) if t.text == "stopped before execution"))
+ );
+ assert!(cursor.calls().is_empty());
+}
+
+#[tokio::test]
+async fn terminal_poll_crash_is_reconciled_without_reopening_or_duplicating_tools() {
+ let (service, cursor, output) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ let run = CursorRunId::new("R");
+ {
+ let _gate = session.turn_gate.lock().await;
+ service.ensure_journal(&id, &session).await.unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("go"))]),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {
+ text: "hel".into(),
+ })),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Sse(crate::testing::raw_record(CursorEvent::ToolCall(
+ ToolCallEvent {
+ call_id: "tool".into(),
+ name: "shell".into(),
+ args: None,
+ result: None,
+ status: None,
+ truncated: Truncation::default(),
+ },
+ ))),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Poll(r#"{"status":"FINISHED","result":"hello"}"#.into()),
+ false,
+ )
+ .await
+ .unwrap();
+ }
+ // Crash before Reconciled: replay restores hello plus terminal tool cleanup.
+ service.replay_session(&id).await.unwrap().complete();
+ let replay = output.updates();
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Assistant { text: "hel".into() })
+ .unwrap();
+ tx.send(CursorEvent::Assistant { text: "lo".into() })
+ .unwrap();
+ tx.send(finished("R")).unwrap();
+ cursor.script_run_listings(vec![RunListing {
+ id: run.clone(),
+ status: RunStatus::Finished,
+ }]);
+ session.state.lock().unwrap().agent = Some(CursorAgentId::new("agent"));
+ service.sync_foreign_runs().await;
+ assert_eq!(
+ output.updates(),
+ replay,
+ "no duplicated lo or repeated tool cleanup"
+ );
+ assert!(
+ service
+ .journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .any(|e| e.run.as_ref() == Some(&run) && e.input == JournalInput::Reconciled)
+ );
+ service.replay_session(&id).await.unwrap().complete();
+ assert_eq!(&output.updates()[replay.len()..], replay.as_slice());
+ assert!(
+ cursor.calls().is_empty(),
+ "terminal recovery requires no provider read/execution"
+ );
+}
+
+#[tokio::test]
+async fn capture_backlog_includes_the_run_at_the_delivered_watermark_after_restart() {
+ let (service, cursor, output) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ let run = CursorRunId::new("cancelled-run");
+ {
+ let _gate = session.turn_gate.lock().await;
+ service.ensure_journal(&id, &session).await.unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("go"))]),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {
+ text: "hel".into(),
+ })),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Interrupted("disconnected cancellation".into()),
+ false,
+ )
+ .await
+ .unwrap();
+ }
+ service.restore_session_with_watermark(
+ id.clone(),
+ Some(CursorAgentId::new("agent")),
+ None,
+ None,
+ Some(run.clone()),
+ );
+ service.replay_session(&id).await.unwrap().complete();
+ let before = output.updates().len();
+ cursor.script_run_listings(vec![RunListing {
+ id: run.clone(),
+ status: RunStatus::Finished,
+ }]);
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Assistant { text: "hel".into() })
+ .unwrap();
+ tx.send(CursorEvent::Assistant { text: "lo".into() })
+ .unwrap();
+ tx.send(finished("cancelled-run")).unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+ service.sync_foreign_runs().await;
+ assert_eq!(
+ output.updates().len(),
+ before,
+ "the backlog is captured, not streamed"
+ );
+ assert_eq!(output.reloads(), vec![id.clone()]);
+ assert!(
+ service
+ .journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .any(|e| e.input == JournalInput::Reconciled)
+ );
+ let loaded = load(&service, &id, &output).await;
+ assert_eq!(user_texts(&loaded), ["go"]);
+ assert_eq!(
+ agent_texts(&loaded),
+ ["hel", "lo"],
+ "the captured prefix is not repeated"
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_newly_accepted_run_waits_behind_a_failed_older_backfill() {
+ let (service, cursor, output) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ session.state.lock().unwrap().agent = Some(CursorAgentId::new("agent"));
+ let gate = cursor.script_create_gate();
+ let task = tokio::spawn({
+ let service = service.clone();
+ let id = id.clone();
+ async move { service.prompt(&id, "R2").await }
+ });
+ cursor
+ .wait_for_calls(1, |c| matches!(c, CursorCall::CreateRun(..)))
+ .await;
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-fake-1"),
+ status: RunStatus::Running,
+ },
+ RunListing {
+ id: CursorRunId::new("R1"),
+ status: RunStatus::Finished,
+ },
+ ]);
+ let opened = CursorEvent::ToolCall(ToolCallEvent {
+ call_id: "R1-tool".into(),
+ name: "shell".into(),
+ args: None,
+ result: None,
+ status: None,
+ truncated: Truncation::default(),
+ });
+ let partial = cursor.script_stream();
+ partial
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "R1 prompt".into(),
+ }))
+ .unwrap();
+ partial.send(opened.clone()).unwrap();
+ partial
+ .send(CursorEvent::Error {
+ code: None,
+ message: "transport interrupted".into(),
+ })
+ .unwrap();
+ drop(partial);
+ gate.send(()).unwrap();
+ assert!(
+ task.await.unwrap().is_err(),
+ "failed R1 prevents R2 ingestion"
+ );
+ assert!(
+ !output.updates().iter().any(|(_, u)| matches!(
+ u,
+ SessionUpdate::AgentMessageChunk(_) | SessionUpdate::ToolCallUpdate(_)
+ )),
+ "R2 cannot emit text or close R1's still-open tool"
+ );
+ let entries = service.journal.read(&id).await.unwrap();
+ assert!(
+ entries
+ .iter()
+ .any(|e| e.run.as_ref() == Some(&CursorRunId::new("run-fake-1"))
+ && matches!(e.input, JournalInput::PromptAccepted(_))),
+ "R2 acceptance remains recoverable"
+ );
+ let pending = fold::replay(service.journal.clone(), id.clone()).await;
+ assert_eq!(
+ pending.len(),
+ 2,
+ "queued R2 must not steal the incomplete R1 turn during load"
+ );
+ assert_eq!(
+ pending[0].parts.first(),
+ Some(&agent_fold::domain::model::MessagePart::Text {
+ text: "R1 prompt".into()
+ })
+ );
+ assert!(pending[1].stop.is_none());
+ for (run, text, user) in [("R1", "older", true), ("run-fake-1", "newer", false)] {
+ let tx = cursor.script_stream();
+ if user {
+ tx.send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "R1 prompt".into(),
+ }))
+ .unwrap();
+ }
+ if user {
+ tx.send(opened.clone()).unwrap();
+ let mut completed = match opened.clone() {
+ CursorEvent::ToolCall(call) => call,
+ _ => unreachable!(),
+ };
+ completed.status = Some("completed".into());
+ completed.result = Some(serde_json::json!("older tool finished"));
+ tx.send(CursorEvent::ToolCall(completed)).unwrap();
+ }
+ tx.send(CursorEvent::Assistant { text: text.into() })
+ .unwrap();
+ tx.send(finished(run)).unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+ }
+ service.sync_foreign_runs().await;
+ assert!(
+ agent_texts(&output.updates()).is_empty(),
+ "recovered runs are captured, never streamed"
+ );
+ assert_eq!(output.reloads(), vec![id.clone()]);
+ let messages = fold::replay(service.journal.clone(), id.clone()).await;
+ let text: Vec<_> = messages
+ .iter()
+ .map(|message| {
+ message
+ .parts
+ .iter()
+ .filter_map(|part| match part {
+ agent_fold::domain::model::MessagePart::Text { text } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect();
+ assert_eq!(text, ["R1 prompt", "older", "R2", "newer"]);
+ assert_eq!(messages[0].id, messages[1].id);
+ assert_eq!(messages[2].id, messages[3].id);
+ assert_ne!(messages[0].id, messages[2].id);
+ assert_eq!(
+ messages[1].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+ assert_eq!(
+ messages[3].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+}
+
+#[tokio::test]
+async fn model_resolution_precedes_intent_and_definite_rejection_aborts_it() {
+ let cursor = FakeCursor::new();
+ let journal = Arc::new(crate::outbound::memory_journal::MemoryJournal::default());
+ let service = Arc::new(
+ CursorSessionService::new(
+ cursor.clone(),
+ RecordingNotifier::new(),
+ FixedRepos(None),
+ journal.clone(),
+ )
+ .with_default_model(Some("model".into())),
+ );
+ let id = service.new_session(Path::new(""), vec![]);
+ let gate = cursor.script_model_gate();
+ cursor.script_rejection();
+ let task = tokio::spawn({
+ let service = service.clone();
+ let id = id.clone();
+ async move { service.prompt(&id, "rejected").await }
+ });
+ tokio::task::yield_now().await;
+ assert!(
+ journal.read(&id).await.unwrap().is_empty(),
+ "no intent during model resolution"
+ );
+ gate.send(()).unwrap();
+ assert!(task.await.unwrap().is_err());
+ assert!(
+ journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .any(|e| matches!(e.input, JournalInput::PromptAborted(_)))
+ );
+ service.replay_session(&id).await.unwrap().complete();
+}
+
+mod fold;
+
+#[tokio::test]
+async fn cancellation_during_pre_prompt_recovery_never_executes_the_pending_prompt() {
+ let (service, cursor, output) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ service.session(&id).unwrap().state.lock().unwrap().agent = Some(CursorAgentId::new("agent"));
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("older"),
+ status: RunStatus::Running,
+ }]);
+ let events = cursor.script_stream();
+ let task = tokio::spawn({
+ let service = service.clone();
+ let id = id.clone();
+ async move { service.prompt(&id, "must not execute").await }
+ });
+ events
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "old question".into(),
+ }))
+ .unwrap();
+ loop {
+ if service
+ .journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .any(|entry| matches!(entry.input, JournalInput::Sse(_)))
+ {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ service.cancel(&id).await.unwrap();
+ events
+ .send(CursorEvent::Assistant {
+ text: "old answer".into(),
+ })
+ .unwrap();
+ events.send(finished("older")).unwrap();
+ events.send(CursorEvent::Done).unwrap();
+ assert_eq!(task.await.unwrap().unwrap(), StopReason::Cancelled);
+ assert!(!cursor.calls().iter().any(|call| matches!(
+ call,
+ CursorCall::CreateAgent(..) | CursorCall::CreateRun(..)
+ )));
+ assert_eq!(output.reloads(), vec![id.clone()]);
+ assert!(output.updates().is_empty());
+ // The load shows the recovered older turn, then the aborted prompt as a
+ // cancelled turn that never reached the provider.
+ let messages = fold::replay(service.journal.clone(), id).await;
+ let texts: Vec<String> = messages
+ .iter()
+ .map(|message| {
+ message
+ .parts
+ .iter()
+ .filter_map(|part| match part {
+ agent_fold::domain::model::MessagePart::Text { text } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect()
+ })
+ .collect();
+ assert_eq!(
+ texts,
+ ["old question", "old answer", "must not execute", ""]
+ );
+ assert_eq!(messages[0].id, messages[1].id);
+ assert_eq!(messages[2].id, messages[3].id);
+ assert_eq!(
+ messages[1].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+ assert_eq!(
+ messages[3].stop,
+ Some(agent_fold::domain::model::StopReason::Cancelled)
+ );
+}
+
+#[tokio::test]
+async fn actual_load_frames_restore_terminal_outcomes_and_leave_partial_tail_open() {
+ use agent_fold::domain::model::StopReason as FoldStop;
+ for (status, expected) in [
+ (Some(RunStatus::Finished), Some(FoldStop::EndTurn)),
+ (Some(RunStatus::Cancelled), Some(FoldStop::Cancelled)),
+ (
+ Some(RunStatus::Error),
+ Some(FoldStop::Failed {
+ message: "Agent run ended in Error".into(),
+ }),
+ ),
+ (None, None),
+ ] {
+ let (service, _, _) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ service.ensure_journal(&id, &session).await.unwrap();
+ let run = CursorRunId::new("run");
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("question"))]),
+ false,
+ )
+ .await
+ .unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Sse(crate::testing::raw_record(CursorEvent::Assistant {
+ text: "answer".into(),
+ })),
+ false,
+ )
+ .await
+ .unwrap();
+ if let Some(status) = status {
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&run),
+ JournalInput::Poll(
+ serde_json::json!({"status":status,"result":"answer"}).to_string(),
+ ),
+ false,
+ )
+ .await
+ .unwrap();
+ }
+ let messages = fold::replay(service.journal.clone(), id.clone()).await;
+ assert_eq!(messages.len(), 2);
+ assert_eq!(messages[0].id, messages[1].id);
+ assert_eq!(messages[1].stop, expected);
+ if expected.is_none() {
+ let continued = fold::replay_with_tail(
+ service.journal.clone(),
+ id,
+ Some(vec![
+ CursorEvent::Assistant {
+ text: "answer".into(),
+ },
+ CursorEvent::Assistant {
+ text: " continued".into(),
+ },
+ finished("run"),
+ CursorEvent::Done,
+ ]),
+ )
+ .await;
+ assert_eq!(continued.len(), 2);
+ assert_eq!(continued[1].stop, Some(FoldStop::EndTurn));
+ assert_eq!(
+ continued[1].parts.first(),
+ Some(&agent_fold::domain::model::MessagePart::Text {
+ text: "answer continued".into()
+ })
+ );
+ }
+ }
+}
diff --git a/crates/cursor_cloud_agents/src/domain/service/test/fold.rs b/crates/cursor_cloud_agents/src/domain/service/test/fold.rs
new file mode 100644
index 0000000000..7aac4e5028
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/domain/service/test/fold.rs
@@ -0,0 +1,611 @@
+//! Actual served Cursor load frames, folded by the same generic machine as WASM.
+use super::*;
+use crate::inbound::acp::{AcpNotifier, serve_transport};
+use agent_client_protocol::{Channel, RawJsonRpcMessage, TransportFrame};
+use agent_fold::domain::log::{AgentSessionId, AgentSessionLog, Message};
+use agent_fold::domain::model::FoldedMessage;
+use agent_runtime_protocol::domain::schema::v0::{AcpMessage, ToRuntimeMessage, ToServerMessage};
+
+pub(super) async fn replay(journal: Arc<dyn CursorJournal>, id: SessionId) -> Vec<FoldedMessage> {
+ replay_with_tail(journal, id, None).await
+}
+
+pub(super) async fn replay_with_tail(
+ journal: Arc<dyn CursorJournal>,
+ id: SessionId,
+ tail: Option<Vec<CursorEvent>>,
+) -> Vec<FoldedMessage> {
+ replay_with_runs(
+ journal,
+ id,
+ tail.map(|events| vec![(CursorRunId::new("run"), events)]),
+ )
+ .await
+}
+
+pub(super) async fn replay_with_runs(
+ journal: Arc<dyn CursorJournal>,
+ id: SessionId,
+ runs: Option<Vec<(CursorRunId, Vec<CursorEvent>)>>,
+) -> Vec<FoldedMessage> {
+ let (reload_tx, mut reload_rx) = tokio::sync::mpsc::unbounded_channel();
+ let notifier = AcpNotifier::new().with_reload(reload_tx);
+ let cursor = FakeCursor::new();
+ let service = Arc::new(CursorSessionService::new(
+ cursor.clone(),
+ notifier.clone(),
+ FixedRepos(None),
+ journal,
+ ));
+ service.restore_session(id.clone(), Some(CursorAgentId::new("agent")), None, None);
+ let (agent, mut client) = Channel::duplex();
+ let task = tokio::spawn(serve_transport(service.clone(), notifier, agent));
+ let mut log = Vec::new();
+ let mut previous = None;
+ for request_id in [91, 92] {
+ load(&mut client, &mut log, &id, request_id).await;
+ assert_incremental_matches_batch(&log);
+ let messages = agent_fold::domain::fold::fold(log.clone());
+ if let Some(previous) = &previous {
+ assert_eq!(
+ previous,
+ &serde_json::to_value(&messages).unwrap(),
+ "repeated actual loads replace the same conversation"
+ );
+ }
+ previous = Some(serde_json::to_value(&messages).unwrap());
+ }
+ if let Some(runs) = runs {
+ cursor.script_run_listings(
+ runs.iter()
+ .rev()
+ .map(|(run, _)| RunListing {
+ id: run.clone(),
+ status: RunStatus::Finished,
+ })
+ .collect(),
+ );
+ for (_, tail) in runs {
+ let events = cursor.script_stream();
+ for event in tail {
+ events.send(event).unwrap();
+ }
+ drop(events);
+ }
+ service.sync_foreign_runs().await;
+ // Recovery is host-local: one reload requirement for this session and
+ // no frame on the wire until the client's own standard load.
+ assert_eq!(reload_rx.try_recv().ok(), Some(id.clone()));
+ assert!(reload_rx.try_recv().is_err());
+ assert_no_frame(&mut client).await;
+ load(&mut client, &mut log, &id, 93).await;
+ }
+ task.abort();
+ assert_incremental_matches_batch(&log);
+ agent_fold::domain::fold::fold(log)
+}
+
+/// One standard `session/load` on the served transport, recording every frame
+/// through its successful response into `log`.
+pub(super) async fn load(
+ client: &mut agent_client_protocol::Channel,
+ log: &mut Vec<AgentSessionLog>,
+ id: &SessionId,
+ request_id: u64,
+) {
+ let request: RawJsonRpcMessage = serde_json::from_value(serde_json::json!({
+ "jsonrpc":"2.0", "id":request_id, "method":"session/load",
+ "params":{"sessionId":id,"cwd":"/workspace","mcpServers":[]}
+ }))
+ .unwrap();
+ log.push(entry(Message::ToRuntime(ToRuntimeMessage::Acp(
+ AcpMessage(request.clone()),
+ ))));
+ client
+ .tx
+ .unbounded_send(TransportFrame::Single(request))
+ .unwrap();
+ loop {
+ let frame = tokio::time::timeout(std::time::Duration::from_secs(5), client.rx.next())
+ .await
+ .unwrap()
+ .unwrap();
+ let TransportFrame::Single(frame) = frame else {
+ panic!("single frame")
+ };
+ let value = serde_json::to_value(&frame).unwrap();
+ let response = value["id"] == request_id;
+ if response {
+ assert!(value.get("result").is_some(), "{value}");
+ } else {
+ assert!(
+ value.get("id").is_none() && value.get("method").is_some(),
+ "only history notifications precede the load response: {value}"
+ );
+ }
+ log.push(entry(Message::ToServer(ToServerMessage::Acp(AcpMessage(
+ frame,
+ )))));
+ if response {
+ break;
+ }
+ }
+}
+
+/// The served transport stays silent: recovered history never streams live.
+async fn assert_no_frame(client: &mut agent_client_protocol::Channel) {
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(100), client.rx.next())
+ .await
+ .is_err(),
+ "a frame left the agent without a client request"
+ );
+}
+
+fn entry(content: Message) -> AgentSessionLog {
+ AgentSessionLog {
+ agent_session_id: AgentSessionId::TEST_A,
+ user_id: None,
+ content,
+ }
+}
+
+fn assert_incremental_matches_batch(log: &[AgentSessionLog]) {
+ use agent_fold::domain::model::FoldEvent;
+ use agent_fold::domain::ports::FoldMachine;
+ let mut machine = agent_fold::domain::fold::FoldMachineImpl::new();
+ let mut visible: Vec<FoldedMessage> = Vec::new();
+ for (i, entry) in log.iter().enumerate() {
+ for event in machine.push(entry.clone()) {
+ match event {
+ FoldEvent::MessagesReplaced(messages) => visible = messages.into_owned(),
+ FoldEvent::NewMessage(message) => visible.push(message.into_owned()),
+ FoldEvent::MessageUpdate(message) => {
+ let at = visible
+ .iter()
+ .position(|old| old.id() == message.id())
+ .unwrap();
+ visible[at] = message.into_owned();
+ }
+ FoldEvent::MetadataUpdated(_) => {}
+ }
+ }
+ assert_eq!(
+ visible,
+ agent_fold::domain::fold::fold(log[..=i].iter().cloned()),
+ "actual Cursor wire prefix {i}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn actual_live_backfill_keeps_older_answer_out_of_pending_or_cancelled_prompt() {
+ for (cancel, late) in [(false, false), (true, false), (false, true)] {
+ let cursor = FakeCursor::new();
+ let (reload_tx, mut reload_rx) = tokio::sync::mpsc::unbounded_channel();
+ let notifier = AcpNotifier::new().with_reload(reload_tx);
+ let journal = Arc::new(crate::outbound::memory_journal::MemoryJournal::default());
+ let service = Arc::new(CursorSessionService::new(
+ cursor.clone(),
+ notifier.clone(),
+ FixedRepos(None),
+ journal.clone(),
+ ));
+ let id = service.new_session(Path::new(""), vec![]);
+ service.session(&id).unwrap().state.lock().unwrap().agent =
+ Some(CursorAgentId::new("agent"));
+ let late_gate = if late {
+ Some(cursor.script_create_gate())
+ } else {
+ None
+ };
+ if !late {
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("R1"),
+ status: RunStatus::Running,
+ }]);
+ }
+ let older = cursor.script_stream();
+ older
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "R1".into(),
+ }))
+ .unwrap();
+ older
+ .send(CursorEvent::Assistant {
+ text: "older".into(),
+ })
+ .unwrap();
+ if !cancel {
+ let newer = cursor.script_stream();
+ newer
+ .send(CursorEvent::Assistant {
+ text: "newer".into(),
+ })
+ .unwrap();
+ newer.send(finished("run-fake-1")).unwrap();
+ newer.send(CursorEvent::Done).unwrap();
+ }
+ let (agent, mut client) = Channel::duplex();
+ let task = tokio::spawn(serve_transport(service.clone(), notifier, agent));
+ let prompt: RawJsonRpcMessage = serde_json::from_value(serde_json::json!({"jsonrpc":"2.0","id":41,"method":"session/prompt","params":{"sessionId":id,"prompt":[{"type":"text","text":"R2"}]}})).unwrap();
+ let mut log = vec![entry(Message::ToRuntime(ToRuntimeMessage::Acp(
+ AcpMessage(prompt.clone()),
+ )))];
+ client
+ .tx
+ .unbounded_send(TransportFrame::Single(prompt))
+ .unwrap();
+ if let Some(gate) = late_gate {
+ cursor
+ .wait_for_calls(1, |call| matches!(call, CursorCall::CreateRun(..)))
+ .await;
+ cursor.script_run_listings(vec![
+ RunListing {
+ id: CursorRunId::new("run-fake-1"),
+ status: RunStatus::Running,
+ },
+ RunListing {
+ id: CursorRunId::new("R1"),
+ status: RunStatus::Running,
+ },
+ ]);
+ gate.send(()).unwrap();
+ }
+ loop {
+ if journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .any(|e| matches!(e.input, JournalInput::Sse(_)))
+ {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ if cancel {
+ let stop: RawJsonRpcMessage = serde_json::from_value(serde_json::json!({"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":id}})).unwrap();
+ log.push(entry(Message::ToRuntime(ToRuntimeMessage::Acp(
+ AcpMessage(stop.clone()),
+ ))));
+ client
+ .tx
+ .unbounded_send(TransportFrame::Single(stop))
+ .unwrap();
+ cursor
+ .wait_for_calls(1, |call| matches!(call, CursorCall::CancelRun(..)))
+ .await;
+ }
+ older.send(finished("R1")).unwrap();
+ older.send(CursorEvent::Done).unwrap();
+ loop {
+ let frame = tokio::time::timeout(std::time::Duration::from_secs(5), client.rx.next())
+ .await
+ .unwrap()
+ .unwrap();
+ let TransportFrame::Single(frame) = frame else {
+ panic!("single frame")
+ };
+ let value = serde_json::to_value(&frame).unwrap();
+ let done = value["id"] == 41;
+ if done {
+ assert!(value.get("result").is_some(), "{value}");
+ }
+ log.push(entry(Message::ToServer(ToServerMessage::Acp(AcpMessage(
+ frame,
+ )))));
+ if done {
+ break;
+ }
+ }
+ assert_incremental_matches_batch(&log);
+ // The older run was recovered while R2 was pending, but only into the
+ // journal: the live view holds nothing but the prompt's own turn.
+ assert_eq!(
+ conversation_texts(&agent_fold::domain::fold::fold(log.clone())),
+ if cancel {
+ vec!["R2", ""]
+ } else {
+ vec!["R2", "newer"]
+ }
+ );
+ assert_eq!(
+ reload_rx.try_recv().ok(),
+ Some(id.clone()),
+ "recovery requires a host-local reload"
+ );
+ assert!(
+ reload_rx.try_recv().is_err(),
+ "pre- and post-acceptance recovery coalesce into one requirement"
+ );
+ // The client's standard load, after the prompt response, shows the
+ // recovered older turn before the one it was pending behind.
+ load(&mut client, &mut log, &id, 42).await;
+ assert_incremental_matches_batch(&log);
+ let messages = agent_fold::domain::fold::fold(log);
+ let conversation: Vec<_> = messages
+ .iter()
+ .filter(|m| {
+ m.parts
+ .iter()
+ .any(|p| matches!(p, agent_fold::domain::model::MessagePart::Text { .. }))
+ })
+ .collect();
+ assert_eq!(
+ conversation_texts(&messages),
+ if cancel {
+ vec!["R1", "older", "R2", ""]
+ } else {
+ vec!["R1", "older", "R2", "newer"]
+ }
+ );
+ assert_eq!(conversation[0].id, conversation[1].id);
+ assert_eq!(conversation[2].id, conversation[3].id);
+ assert_ne!(conversation[0].id, conversation[2].id);
+ assert_eq!(
+ conversation[1].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+ assert_eq!(
+ conversation[3].stop,
+ Some(if cancel {
+ agent_fold::domain::model::StopReason::Cancelled
+ } else {
+ agent_fold::domain::model::StopReason::EndTurn
+ })
+ );
+ if cancel {
+ assert!(!cursor.calls().iter().any(|call| matches!(
+ call,
+ CursorCall::CreateRun(..) | CursorCall::CreateAgent(..)
+ )));
+ }
+ task.abort();
+ }
+}
+
+/// Text of every message carrying text, in conversation order.
+fn conversation_texts(messages: &[FoldedMessage]) -> Vec<String> {
+ messages
+ .iter()
+ .filter(|m| {
+ m.parts
+ .iter()
+ .any(|p| matches!(p, agent_fold::domain::model::MessagePart::Text { .. }))
+ })
+ .map(|m| {
+ m.parts
+ .iter()
+ .filter_map(|p| match p {
+ agent_fold::domain::model::MessagePart::Text { text } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect::<String>()
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn accepted_newer_run_survives_partial_crash_load_then_actual_sync_without_stealing_turn() {
+ let (service, _, _) = service(None);
+ let id = service.new_session(Path::new(""), vec![]);
+ let session = service.session(&id).unwrap();
+ service.ensure_journal(&id, &session).await.unwrap();
+ service
+ .capture(
+ &id,
+ &session,
+ None,
+ JournalInput::Prompt(vec![ContentBlock::Text(TextContent::new("R2"))]),
+ false,
+ )
+ .await
+ .unwrap();
+ let r1 = CursorRunId::new("R1");
+ let r2 = CursorRunId::new("R2");
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&r2),
+ JournalInput::PromptAccepted(2),
+ false,
+ )
+ .await
+ .unwrap();
+ let opened = CursorEvent::ToolCall(ToolCallEvent {
+ call_id: "old-tool".into(),
+ name: "shell".into(),
+ args: None,
+ result: None,
+ status: None,
+ truncated: Truncation::default(),
+ });
+ let prefix = vec![
+ CursorEvent::Interaction(InteractionUpdate::UserMessage { text: "R1".into() }),
+ CursorEvent::Assistant { text: "ol".into() },
+ opened.clone(),
+ ];
+ for event in &prefix {
+ service
+ .capture(
+ &id,
+ &session,
+ Some(&r1),
+ JournalInput::Sse(crate::testing::raw_record(event.clone())),
+ false,
+ )
+ .await
+ .unwrap();
+ }
+ let loaded = replay(service.journal.clone(), id.clone()).await;
+ assert_eq!(
+ loaded.len(),
+ 2,
+ "R2 must remain deferred beyond the unfinished R1"
+ );
+ assert_eq!(
+ loaded[0].parts.first(),
+ Some(&agent_fold::domain::model::MessagePart::Text { text: "R1".into() })
+ );
+ assert!(
+ loaded[1].stop.is_none(),
+ "a queued acceptance is not a terminal fact for R1"
+ );
+ let CursorEvent::ToolCall(mut completed) = opened else {
+ unreachable!()
+ };
+ completed.status = Some("completed".into());
+ completed.result = Some(serde_json::json!("done"));
+ let mut recovered = prefix;
+ recovered.extend([
+ CursorEvent::Assistant { text: "der".into() },
+ CursorEvent::ToolCall(completed),
+ finished("R1"),
+ CursorEvent::Done,
+ ]);
+ let messages = replay_with_runs(
+ service.journal.clone(),
+ id,
+ Some(vec![
+ (r1, recovered),
+ (
+ r2,
+ vec![
+ CursorEvent::Assistant {
+ text: "newer".into(),
+ },
+ finished("R2"),
+ CursorEvent::Done,
+ ],
+ ),
+ ]),
+ )
+ .await;
+ let texts: Vec<_> = messages
+ .iter()
+ .map(|m| {
+ m.parts
+ .iter()
+ .filter_map(|p| match p {
+ agent_fold::domain::model::MessagePart::Text { text } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(texts, ["R1", "older", "R2", "newer"]);
+ assert_eq!(messages[0].id, messages[1].id);
+ assert_eq!(messages[2].id, messages[3].id);
+ assert_ne!(messages[0].id, messages[2].id);
+ assert_eq!(
+ messages[1].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+ assert_eq!(
+ messages[3].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+}
+
+#[tokio::test]
+async fn load_waiting_for_an_active_backfill_replays_one_copy_through_fold() {
+ let cursor = FakeCursor::new();
+ let (reload_tx, mut reload_rx) = tokio::sync::mpsc::unbounded_channel();
+ let notifier = AcpNotifier::new().with_reload(reload_tx);
+ let journal = Arc::new(crate::outbound::memory_journal::MemoryJournal::default());
+ let service = Arc::new(CursorSessionService::new(
+ cursor.clone(),
+ notifier.clone(),
+ FixedRepos(None),
+ journal.clone(),
+ ));
+ let id = service.new_session(Path::new(""), vec![]);
+ service.session(&id).unwrap().state.lock().unwrap().agent = Some(CursorAgentId::new("agent"));
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("R1"),
+ status: RunStatus::Running,
+ }]);
+ let older = cursor.script_stream();
+ older
+ .send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "question".into(),
+ }))
+ .unwrap();
+ older
+ .send(CursorEvent::Assistant {
+ text: "answer".into(),
+ })
+ .unwrap();
+ let (agent, mut client) = Channel::duplex();
+ let task = tokio::spawn(serve_transport(service.clone(), notifier, agent));
+ let producer = tokio::spawn({
+ let service = service.clone();
+ async move { service.sync_foreign_runs().await }
+ });
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ if journal
+ .read(&id)
+ .await
+ .unwrap()
+ .iter()
+ .filter(|e| matches!(e.input, JournalInput::Sse(_)))
+ .count()
+ >= 2
+ {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .unwrap();
+ assert!(
+ service.has_active_turn(),
+ "the backfill holds the turn gate"
+ );
+ assert!(
+ reload_rx.try_recv().is_err(),
+ "no reload is required before the recovered run is reconciled"
+ );
+ // The load arrives mid-backfill and waits behind the gate; the run's
+ // completion is captured before the load reads the journal.
+ let mut log = Vec::new();
+ let loading = tokio::spawn(async move {
+ load(&mut client, &mut log, &id, 91).await;
+ (client, log, id)
+ });
+ older.send(finished("R1")).unwrap();
+ older.send(CursorEvent::Done).unwrap();
+ producer.await.unwrap();
+ let (mut client, log, id) = loading.await.unwrap();
+ assert_eq!(reload_rx.try_recv().ok(), Some(id.clone()));
+ assert!(reload_rx.try_recv().is_err());
+ assert_no_frame(&mut client).await;
+ task.abort();
+ assert_incremental_matches_batch(&log);
+ let messages = agent_fold::domain::fold::fold(log);
+ assert_eq!(
+ messages.len(),
+ 2,
+ "backfill and load must display one conversation copy"
+ );
+ assert_eq!(
+ messages[0].parts.iter().cloned().collect::<Vec<_>>(),
+ vec![agent_fold::domain::model::MessagePart::Text {
+ text: "question".into()
+ }]
+ );
+ assert_eq!(
+ messages[1].parts.iter().cloned().collect::<Vec<_>>(),
+ vec![agent_fold::domain::model::MessagePart::Text {
+ text: "answer".into()
+ }]
+ );
+ assert_eq!(
+ messages[1].stop,
+ Some(agent_fold::domain::model::StopReason::EndTurn)
+ );
+}
diff --git a/crates/cursor_cloud_agents/src/domain/translate.rs b/crates/cursor_cloud_agents/src/domain/translate.rs
index 308d94e762..27f1a34db3 100644
--- a/crates/cursor_cloud_agents/src/domain/translate.rs
+++ b/crates/cursor_cloud_agents/src/domain/translate.rs
@@ -159,8 +159,9 @@ impl TranslateMachine {
/// outcome for these, so `Completed` would claim a success nobody
/// witnessed.
pub fn close_open_calls(&mut self) -> Vec<SessionUpdate> {
- self.open
- .drain()
+ let mut open: Vec<_> = self.open.drain().collect();
+ open.sort();
+ open.into_iter()
.map(|call_id| {
SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
call_id,
diff --git a/crates/cursor_cloud_agents/src/inbound/acp.rs b/crates/cursor_cloud_agents/src/inbound/acp.rs
index bc180711e7..6ea39b9c52 100644
--- a/crates/cursor_cloud_agents/src/inbound/acp.rs
+++ b/crates/cursor_cloud_agents/src/inbound/acp.rs
@@ -34,14 +34,14 @@ use crate::domain::service::CursorSessionService;
use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::schema::v1::{
AgentCapabilities, AuthenticateRequest, AuthenticateResponse, CancelNotification,
- CloseSessionRequest, CloseSessionResponse, ContentBlock, Error as AcpError, HttpHeader,
- Implementation, InitializeRequest, InitializeResponse, LoadSessionRequest, LoadSessionResponse,
- McpCapabilities, McpServer as AcpMcpServer, NewSessionRequest, NewSessionResponse,
- PromptCapabilities, PromptRequest, PromptResponse, SessionConfigGroupId, SessionConfigId,
- SessionConfigKind, SessionConfigOption, SessionConfigSelect, SessionConfigSelectGroup,
- SessionConfigSelectOption, SessionConfigSelectOptions, SessionConfigValueId, SessionId,
- SessionNotification, SessionUpdate, SetSessionConfigOptionRequest,
- SetSessionConfigOptionResponse,
+ CloseSessionRequest, CloseSessionResponse, ContentBlock, ContentChunk, Error as AcpError,
+ HttpHeader, Implementation, InitializeRequest, InitializeResponse, LoadSessionRequest,
+ LoadSessionResponse, McpCapabilities, McpServer as AcpMcpServer, Meta, NewSessionRequest,
+ NewSessionResponse, PromptCapabilities, PromptRequest, PromptResponse, SessionConfigGroupId,
+ SessionConfigId, SessionConfigKind, SessionConfigOption, SessionConfigSelect,
+ SessionConfigSelectGroup, SessionConfigSelectOption, SessionConfigSelectOptions,
+ SessionConfigValueId, SessionId, SessionNotification, SessionUpdate,
+ SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, TextContent,
};
use agent_client_protocol::{
Agent, ByteStreams, Client, ConnectTo, ConnectionTo, on_receive_notification,
@@ -81,6 +81,8 @@ pub struct AcpNotifier {
/// Empty until the connection is up. Write-once: one notifier serves one
/// connection, exactly as one service does.
connection: Arc<OnceLock<ConnectionTo<Client>>>,
+ bound: Arc<tokio::sync::Notify>,
+ reload: Option<tokio::sync::mpsc::UnboundedSender<SessionId>>,
}
impl AcpNotifier {
@@ -90,11 +92,18 @@ impl AcpNotifier {
Self::default()
}
+ /// Deliver recovery requirements to the embedding ACP client, not the wire.
+ pub fn with_reload(mut self, reload: tokio::sync::mpsc::UnboundedSender<SessionId>) -> Self {
+ self.reload = Some(reload);
+ self
+ }
+
/// Attach the connection updates will travel over.
fn bind(&self, connection: ConnectionTo<Client>) {
// A second bind can only be a bug in `serve`; the first connection
// stays authoritative and the duplicate is dropped.
let _ = self.connection.set(connection);
+ self.bound.notify_waiters();
}
}
@@ -104,15 +113,72 @@ impl SessionNotifier for AcpNotifier {
session: &SessionId,
update: SessionUpdate,
) -> Result<(), rootcause::Report> {
- // Unreachable in practice: the binding runner starts with the
- // connection's event loop, before any handler can run a turn. Failing
- // loudly beats buffering updates nobody may ever collect.
+ let connection = loop {
+ let bound = self.bound.notified();
+ tokio::pin!(bound);
+ bound.as_mut().enable();
+ if let Some(connection) = self.connection.get() {
+ break connection;
+ }
+ bound.await;
+ };
+ connection
+ .send_notification(SessionNotification::new(session.clone(), update))
+ .map_err(|error| rootcause::report!("{error}"))
+ }
+
+ async fn require_reload(&self, session: &SessionId) -> Result<(), rootcause::Report> {
+ let Some(reload) = &self.reload else {
+ // Standalone ACP clients own their load lifecycle. Keep serving
+ // prompts without inventing a client request or pushing history.
+ tracing::warn!(%session, "recovered Cursor history is available on session/load");
+ return Ok(());
+ };
+ reload
+ .send(session.clone())
+ .map_err(|error| rootcause::report!("{error}"))
+ }
+
+ async fn turn_complete(
+ &self,
+ session: &SessionId,
+ outcome: agent_runtime_protocol::domain::turn::TurnOutcome,
+ ) -> Result<(), rootcause::Report> {
let connection = self
.connection
.get()
- .ok_or_else(|| rootcause::report!("session update before the acp connection was up"))?;
+ .ok_or_else(|| rootcause::report!("ACP connection is not bound"))?;
connection
- .send_notification(SessionNotification::new(session.clone(), update))
+ .send_notification(
+ agent_runtime_protocol::domain::turn::TurnCompleteNotification {
+ session_id: session.clone(),
+ outcome,
+ },
+ )
+ .map_err(|error| rootcause::report!("{error}"))
+ }
+
+ async fn checkpoint(
+ &self,
+ session: &SessionId,
+ run: &crate::domain::model::CursorRunId,
+ ) -> Result<(), rootcause::Report> {
+ // Standalone domain tests and embedders without a durable host have no
+ // connection to checkpoint through. The Macro host always binds first;
+ // there the metadata marker is persisted with the ordinary ACP log.
+ let Some(connection) = self.connection.get() else {
+ return Ok(());
+ };
+ let mut meta = Meta::new();
+ meta.insert(
+ "macroCursorRunCheckpoint".to_owned(),
+ serde_json::Value::String(run.to_string()),
+ );
+ let update = SessionUpdate::AgentMessageChunk(ContentChunk::new(ContentBlock::Text(
+ TextContent::new(""),
+ )));
+ connection
+ .send_notification(SessionNotification::new(session.clone(), update).meta(meta))
.map_err(|error| rootcause::report!("{error}"))
}
}
@@ -271,13 +337,14 @@ where
Notifier: SessionNotifier + Send + Sync + 'static,
Repos: RepoResolver + Send + Sync + 'static,
{
+ let startup_notifier = notifier.clone();
Agent
.builder()
.name("cursor-cloud-agents")
// Runs with the connection's event loop, so the notifier is bound
// before any handler can start a turn that would notify.
.with_spawned(move |connection| async move {
- notifier.bind(connection);
+ startup_notifier.bind(connection);
Ok(())
})
.on_receive_request(
@@ -305,7 +372,9 @@ where
.on_receive_request(
{
let service = Arc::clone(&service);
- async move |request: NewSessionRequest, responder, _connection| {
+ let notifier = notifier.clone();
+ async move |request: NewSessionRequest, responder, connection| {
+ notifier.bind(connection.clone());
let mcp_servers = forwardable_mcp_servers(request.mcp_servers);
let session = service.new_session(&request.cwd, mcp_servers);
let options = session_config_options(&service, &session).await;
@@ -317,7 +386,9 @@ where
.on_receive_request(
{
let service = Arc::clone(&service);
+ let notifier = notifier.clone();
async move |request: PromptRequest, responder, connection| {
+ notifier.bind(connection.clone());
// On its own task so the event loop keeps servicing
// cancels while the turn streams.
let service = Arc::clone(&service);
@@ -327,7 +398,10 @@ where
// A failed respond means the client is gone; failing
// the spawned task would tear down the (already
// closing) connection, so it is dropped instead.
- match service.prompt(&session, &text).await {
+ match service
+ .prompt_content(&session, &text, request.prompt)
+ .await
+ {
Ok(stop_reason) => {
let _ = responder.respond(PromptResponse::new(stop_reason));
}
@@ -346,29 +420,25 @@ where
.on_receive_request(
{
let service = Arc::clone(&service);
- async move |request: LoadSessionRequest, responder, _connection| {
- // Loading is a lookup, not a fetch: a host that restarts
- // restores its persisted (session -> agent) pairs with
- // `restore_session` before serving, so by the time a
- // `session/load` arrives the session either exists or
- // never will. No history is replayed — the hosts this
- // agent serves keep their own durable log of every frame,
- // and Cursor accumulates the conversation server-side, so
- // a replay would tell the client what it already knows.
+ let notifier = notifier.clone();
+ async move |request: LoadSessionRequest, responder, connection| {
+ notifier.bind(connection.clone());
let session = request.session_id;
- if service.has_session(&session) {
- // The MCP list is the client's, and a load restates
- // it — the one way a restored process, whose host
- // never persisted the list, learns it again.
- service.set_mcp_servers(
- &session,
- forwardable_mcp_servers(request.mcp_servers),
- );
- let options = session_config_options(&service, &session).await;
- responder.respond(LoadSessionResponse::new().config_options(options))
- } else {
- responder.respond_with_error(AcpError::invalid_params())
+ let guard = match service.replay_session(&session).await {
+ Ok(guard) => guard,
+ Err(error) => {
+ return responder
+ .respond_with_error(AcpError::new(-32603, error.to_string()));
+ }
+ };
+ service.set_mcp_servers(&session, forwardable_mcp_servers(request.mcp_servers));
+ let options = session_config_options(&service, &session).await;
+ let response =
+ responder.respond(LoadSessionResponse::new().config_options(options));
+ if response.is_ok() {
+ guard.complete();
}
+ response
}
},
on_receive_request!(),
diff --git a/crates/cursor_cloud_agents/src/inbound/acp/test.rs b/crates/cursor_cloud_agents/src/inbound/acp/test.rs
index 8b302f7ddc..7d5fa4c798 100644
--- a/crates/cursor_cloud_agents/src/inbound/acp/test.rs
+++ b/crates/cursor_cloud_agents/src/inbound/acp/test.rs
@@ -65,7 +65,19 @@ impl TestClient {
"method": method,
"params": params,
}));
- self.next_frame().await
+ loop {
+ let frame = self.next_frame().await;
+ if method != "session/load" || frame.get("id") == Some(&serde_json::json!(id)) {
+ return frame;
+ }
+ assert!(
+ matches!(
+ frame["method"].as_str(),
+ Some("session/update" | "_session/turn_complete")
+ ),
+ "load emits only replay facts before its response"
+ );
+ }
}
}
@@ -98,8 +110,13 @@ fn serve_over_channel_with_default_model(
) -> (Arc<Service>, TestClient) {
let notifier = AcpNotifier::new();
let service = Arc::new(
- CursorSessionService::new(cursor, notifier.clone(), FixedRepos(None))
- .with_default_model(default_model.map(str::to_owned)),
+ CursorSessionService::new(
+ cursor,
+ notifier.clone(),
+ FixedRepos(None),
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
+ )
+ .with_default_model(default_model.map(str::to_owned)),
);
configure(&service);
let (agent_end, client_end) = Channel::duplex();
@@ -356,6 +373,7 @@ async fn serve_runs_a_whole_conversation_over_an_in_process_pipe() {
cursor,
notifier.clone(),
FixedRepos(None),
+ Arc::new(crate::outbound::memory_journal::MemoryJournal::default()),
));
let serve_task = tokio::spawn(serve(service, notifier, agent_reader, agent_writer));
@@ -423,6 +441,13 @@ async fn serve_runs_a_whole_conversation_over_an_in_process_pipe() {
"the streamed assistant text must reach the client, in {update}"
);
+ let checkpoint = next_client_frame(&mut client_frames).await;
+ assert_eq!(checkpoint["method"], "session/update");
+ assert_eq!(
+ checkpoint["params"]["_meta"]["macroCursorRunCheckpoint"],
+ "run-fake-1"
+ );
+
let answered = next_client_frame(&mut client_frames).await;
assert_eq!(answered["id"], 3, "the response follows its own updates");
assert_eq!(answered["result"]["stopReason"], "end_turn");
@@ -649,7 +674,10 @@ async fn session_load_answers_for_restored_sessions_only() {
}),
)
.await;
- assert!(loaded.get("error").is_none(), "got {loaded}");
+ assert!(
+ loaded.get("error").is_some(),
+ "legacy session without native history must fail: {loaded}"
+ );
let unknown = client
.call(
@@ -930,6 +958,7 @@ async fn setting_an_unoffered_model_is_refused() {
async fn a_restored_session_keeps_its_model() {
let cursor = FakeCursor::new();
cursor.script_models(offered_models());
+ crate::testing::script_legacy_history(&cursor);
let (service, mut client) = serve_over_channel(cursor.clone(), |service| {
service.restore_session(
SessionId::new("cursor-acp-3"),
@@ -994,7 +1023,8 @@ async fn a_restored_session_keeps_its_model() {
async fn a_restored_deployment_slug_falls_back_to_cursors_default() {
let cursor = FakeCursor::new();
cursor.script_models(offered_models());
- let (service, _client) = serve_over_channel(cursor.clone(), |service| {
+ crate::testing::script_legacy_history(&cursor);
+ let (service, mut client) = serve_over_channel(cursor.clone(), |service| {
service.restore_session(
SessionId::new("cursor-acp-3"),
Some(crate::domain::model::CursorAgentId::new("bc-restored")),
@@ -1003,6 +1033,14 @@ async fn a_restored_deployment_slug_falls_back_to_cursors_default() {
);
});
+ let loaded = client
+ .call(
+ 1,
+ "session/load",
+ serde_json::json!({"sessionId":"cursor-acp-3", "cwd":"/workspace", "mcpServers":[]}),
+ )
+ .await;
+ expect_result(&loaded);
let events = cursor.script_stream();
events
.send(CursorEvent::Result {
@@ -1178,3 +1216,64 @@ async fn no_auto_entry_means_no_picker_rather_than_a_guess() {
"no resting value, no picker: {result}"
);
}
+
+#[tokio::test]
+async fn load_queues_all_native_history_before_its_response_and_repeats_without_execution() {
+ let cursor = FakeCursor::new();
+ cursor.script_run_listings(vec![crate::domain::model::RunListing {
+ id: CursorRunId::new("old-run"),
+ status: RunStatus::Finished,
+ }]);
+ let tx = cursor.script_raw_stream();
+ for event in crate::testing::fixture_records("file_operations.sse") {
+ tx.send(event).unwrap();
+ }
+ drop(tx);
+ let (service, mut client) = serve_over_channel(cursor.clone(), |service| {
+ service.restore_session(
+ SessionId::new("restored"),
+ Some(crate::domain::model::CursorAgentId::new("agent")),
+ None,
+ None,
+ );
+ });
+ let mut first = Vec::new();
+ for id in [11, 12] {
+ client.send(serde_json::json!({"jsonrpc":"2.0", "id":id, "method":"session/load", "params":{"sessionId":"restored", "cwd":"/workspace", "mcpServers":[]}}));
+ let mut replay = Vec::new();
+ loop {
+ let frame = client.next_frame().await;
+ if frame.get("id") == Some(&serde_json::json!(id)) {
+ expect_result(&frame);
+ break;
+ }
+ assert!(matches!(
+ frame["method"].as_str(),
+ Some("session/update" | "_session/turn_complete")
+ ));
+ replay.push(
+ frame["params"]
+ .get("update")
+ .cloned()
+ .unwrap_or_else(|| frame.clone()),
+ );
+ }
+ assert_eq!(replay[0]["sessionUpdate"], "user_message_chunk");
+ assert!(replay.iter().any(|u| u["sessionUpdate"] == "tool_call"));
+ assert!(
+ replay
+ .iter()
+ .any(|u| u["sessionUpdate"] == "tool_call_update")
+ );
+ if id == 11 {
+ first = replay;
+ } else {
+ assert_eq!(first, replay);
+ }
+ }
+ assert!(
+ cursor.calls().is_empty(),
+ "replay never executes provider actions"
+ );
+ assert!(service.has_session(&SessionId::new("restored")));
+}
diff --git a/crates/cursor_cloud_agents/src/lib.rs b/crates/cursor_cloud_agents/src/lib.rs
index 7724747e57..c40a439a48 100644
--- a/crates/cursor_cloud_agents/src/lib.rs
+++ b/crates/cursor_cloud_agents/src/lib.rs
@@ -22,10 +22,9 @@
//! - [`inbound`] is the ACP adapter: it parses newline-delimited JSON-RPC
//! frames from any reader, dispatches them to the session service, and
//! writes responses and notifications to any writer. Nothing else ever
-//! touches that writer. Stdio is one instantiation
-//! ([`inbound::acp::AcpWriter::stdio`]); an in-process client over a
+//! touches that writer. Stdio is one instantiation; an in-process client over a
//! `tokio::io::duplex` pipe is another.
-//! - [`outbound`] holds the remaining driven adapters — today, resolving a
+//! - [`outbound`] holds fenced journal storage and resolves a
//! checkout's origin remote so a session lands under the right repository
//! in the Cursor dashboard.
//!
diff --git a/crates/cursor_cloud_agents/src/outbound/memory_journal.rs b/crates/cursor_cloud_agents/src/outbound/memory_journal.rs
new file mode 100644
index 0000000000..970d10614d
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/outbound/memory_journal.rs
@@ -0,0 +1,47 @@
+//! Explicit process-local journal for standalone agents and tests.
+use crate::domain::journal::{CursorJournal, JournalEntry, JournalInput};
+use crate::domain::model::CursorRunId;
+use agent_client_protocol::schema::v1::SessionId;
+use futures::future::BoxFuture;
+use std::{collections::HashMap, sync::Mutex};
+/// Process-local storage; production harnesses must inject PostgreSQL storage.
+#[derive(Debug, Default)]
+pub struct MemoryJournal(Mutex<HashMap<SessionId, Vec<JournalEntry>>>);
+impl CursorJournal for MemoryJournal {
+ fn read<'a>(
+ &'a self,
+ session: &'a SessionId,
+ ) -> BoxFuture<'a, Result<Vec<JournalEntry>, rootcause::Report>> {
+ Box::pin(async move {
+ Ok(self
+ .0
+ .lock()
+ .expect("journal poisoned")
+ .get(session)
+ .cloned()
+ .unwrap_or_default())
+ })
+ }
+ fn append<'a>(
+ &'a self,
+ session: &'a SessionId,
+ expected: i64,
+ run: Option<&'a CursorRunId>,
+ input: &'a JournalInput,
+ ) -> BoxFuture<'a, Result<JournalEntry, rootcause::Report>> {
+ Box::pin(async move {
+ let mut all = self.0.lock().expect("journal poisoned");
+ let entries = all.entry(session.clone()).or_default();
+ if entries.last().map_or(0, |e| e.sequence) != expected {
+ return Err(rootcause::report!("journal writer superseded"));
+ }
+ let entry = JournalEntry {
+ sequence: expected + 1,
+ run: run.cloned(),
+ input: input.clone(),
+ };
+ entries.push(entry.clone());
+ Ok(entry)
+ })
+ }
+}
diff --git a/crates/cursor_cloud_agents/src/outbound/mod.rs b/crates/cursor_cloud_agents/src/outbound/mod.rs
index e08ee15599..9d5a637918 100644
--- a/crates/cursor_cloud_agents/src/outbound/mod.rs
+++ b/crates/cursor_cloud_agents/src/outbound/mod.rs
@@ -2,3 +2,9 @@
/// Repository resolution from a checkout's git remote.
pub mod git;
+
+/// Process-local journal for standalone agents and tests.
+pub mod memory_journal;
+/// Fenced durable journal for hosted sessions.
+#[cfg(feature = "postgres")]
+pub mod postgres_journal;
diff --git a/crates/cursor_cloud_agents/src/outbound/postgres_journal.rs b/crates/cursor_cloud_agents/src/outbound/postgres_journal.rs
new file mode 100644
index 0000000000..8d3408d1d9
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/outbound/postgres_journal.rs
@@ -0,0 +1,127 @@
+//! PostgreSQL native journal, fenced by the existing session management claim.
+use crate::domain::journal::{CursorJournal, JournalEntry, JournalInput};
+use crate::domain::model::CursorRunId;
+use agent_client_protocol::schema::v1::SessionId;
+use agent_session::domain::model::{AgentSessionId, ManagerFence, ReplicaId};
+use futures::future::BoxFuture;
+use sqlx::PgPool;
+
+/// Bound to exactly one authorized host session and its current management
+/// claim. A takeover updates the same locked row and invalidates this writer.
+#[derive(Debug)]
+pub struct PgCursorJournal {
+ pool: PgPool,
+ session: AgentSessionId,
+ replica: ReplicaId,
+ fence: std::sync::OnceLock<ManagerFence>,
+}
+impl PgCursorJournal {
+ /// Construct an inactive journal. The attachment must activate it with
+ /// its actual acquired claim before any read, append or provider action.
+ pub fn new(pool: PgPool, session: AgentSessionId, replica: ReplicaId) -> Self {
+ Self {
+ pool,
+ session,
+ replica,
+ fence: std::sync::OnceLock::new(),
+ }
+ }
+ /// Bind once to the exact generation acquired for this attachment.
+ /// Never infer or refresh authority from a database read.
+ pub fn activate(
+ &self,
+ session: AgentSessionId,
+ replica: ReplicaId,
+ fence: ManagerFence,
+ ) -> Result<(), rootcause::Report> {
+ if session != self.session || replica != self.replica {
+ return Err(rootcause::report!(
+ "Cursor journal attachment identity mismatch"
+ ));
+ }
+ if self.fence.set(fence).is_err() && self.fence.get() != Some(&fence) {
+ return Err(rootcause::report!(
+ "Cursor journal attachment cannot be rebound"
+ ));
+ }
+ Ok(())
+ }
+ async fn lock_owner(
+ &self,
+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
+ ) -> Result<(), rootcause::Report> {
+ // Dispatch fencing cannot stop an already-running stream or mirror
+ // poll. Hold the same row takeover updates until the journal commits;
+ // checking the claim before opening this transaction would race.
+ let expected = *self
+ .fence
+ .get()
+ .ok_or_else(|| rootcause::report!("Cursor journal attachment is not activated"))?;
+ let current = sqlx::query_scalar!("SELECT manager_fence FROM agent_session WHERE id = $1 AND manager_replica_id = $2 FOR UPDATE", self.session.as_uuid(), self.replica.as_uuid())
+ .fetch_optional(&mut **tx).await.map_err(|e| rootcause::report!(e))?
+ .ok_or_else(|| rootcause::report!("Cursor journal writer fenced out"))?;
+ if ManagerFence(current) != expected {
+ return Err(rootcause::report!("Cursor journal writer fenced out"));
+ }
+ Ok(())
+ }
+}
+impl CursorJournal for PgCursorJournal {
+ fn read<'a>(
+ &'a self,
+ _session: &'a SessionId,
+ ) -> BoxFuture<'a, Result<Vec<JournalEntry>, rootcause::Report>> {
+ Box::pin(async move {
+ // A read is scoped by the bound host identity, never by a caller's
+ // ACP ID, which is only unique within a transport.
+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;
+ self.lock_owner(&mut tx).await?;
+ let rows = sqlx::query!("SELECT sequence, run_id, input FROM cursor_journal_input WHERE agent_session_id = $1 ORDER BY sequence", self.session.as_uuid())
+ .fetch_all(&mut *tx).await.map_err(|e| rootcause::report!(e))?;
+ tx.commit().await.map_err(|e| rootcause::report!(e))?;
+ rows.into_iter()
+ .map(|r| {
+ Ok(JournalEntry {
+ sequence: r.sequence,
+ run: r.run_id.map(CursorRunId::new),
+ input: serde_json::from_value(r.input)
+ .map_err(|e| rootcause::report!(e))?,
+ })
+ })
+ .collect()
+ })
+ }
+ fn append<'a>(
+ &'a self,
+ _session: &'a SessionId,
+ expected: i64,
+ run: Option<&'a CursorRunId>,
+ input: &'a JournalInput,
+ ) -> BoxFuture<'a, Result<JournalEntry, rootcause::Report>> {
+ Box::pin(async move {
+ let mut tx = self.pool.begin().await.map_err(|e| rootcause::report!(e))?;
+ self.lock_owner(&mut tx).await?;
+ let high = sqlx::query_scalar!("SELECT COALESCE(MAX(sequence), 0) AS \"high!\" FROM cursor_journal_input WHERE agent_session_id = $1", self.session.as_uuid())
+ .fetch_one(&mut *tx).await.map_err(|e| rootcause::report!(e))?;
+ if high != expected {
+ return Err(rootcause::report!(
+ "Cursor journal sequence changed; reload required"
+ ));
+ }
+ let payload = serde_json::to_value(input).map_err(|e| rootcause::report!(e))?;
+ let sequence = expected + 1;
+ let run_id = run.map(CursorRunId::as_str);
+ sqlx::query!("INSERT INTO cursor_journal_input(agent_session_id, sequence, run_id, input) VALUES ($1, $2, $3, $4)", self.session.as_uuid(), sequence, run_id, payload)
+ .execute(&mut *tx).await.map_err(|e| rootcause::report!(e))?;
+ tx.commit().await.map_err(|e| rootcause::report!(e))?;
+ Ok(JournalEntry {
+ sequence,
+ run: run.cloned(),
+ input: input.clone(),
+ })
+ })
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/cursor_cloud_agents/src/outbound/postgres_journal/test.rs b/crates/cursor_cloud_agents/src/outbound/postgres_journal/test.rs
new file mode 100644
index 0000000000..04a0dada3b
--- /dev/null
+++ b/crates/cursor_cloud_agents/src/outbound/postgres_journal/test.rs
@@ -0,0 +1,145 @@
+use super::*;
+use uuid::Uuid;
+
+#[sqlx::test(migrations = false)]
+async fn append_is_ordered_fenced_and_session_scoped(pool: PgPool) {
+ sqlx::raw_sql(
+ "CREATE TABLE agent_session(id uuid PRIMARY KEY, manager_replica_id uuid, manager_fence bigint NOT NULL);
+ CREATE TABLE agent_session_log(id uuid PRIMARY KEY, agent_session_id uuid NOT NULL REFERENCES agent_session(id));
+ CREATE TABLE external_agent_session(agent_session_id uuid PRIMARY KEY REFERENCES agent_session(id));",
+ ).execute(&pool).await.unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260906060601_cursor_session_replay.up.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ let session = AgentSessionId::new_from_uuid(Uuid::from_u128(1));
+ let replica = ReplicaId::from_uuid(Uuid::from_u128(2));
+ let other = ReplicaId::from_uuid(Uuid::from_u128(3));
+ sqlx::query!(
+ "INSERT INTO agent_session (id, manager_replica_id, manager_fence) VALUES ($1, $2, 1)",
+ session.as_uuid(),
+ replica.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let journal = PgCursorJournal::new(pool.clone(), session, replica);
+ let id = SessionId::new("acp");
+ assert!(
+ journal.read(&id).await.is_err(),
+ "cannot operate before attachment activation"
+ );
+ assert!(journal.activate(session, other, ManagerFence(1)).is_err());
+ journal.activate(session, replica, ManagerFence(1)).unwrap();
+ let stale_before_io = PgCursorJournal::new(pool.clone(), session, replica);
+ stale_before_io
+ .activate(session, replica, ManagerFence(1))
+ .unwrap();
+ assert!(journal.read(&id).await.unwrap().is_empty());
+ journal
+ .append(&id, 0, None, &JournalInput::HistoryComplete)
+ .await
+ .unwrap();
+ assert!(
+ journal
+ .append(&id, 0, None, &JournalInput::HistoryComplete)
+ .await
+ .is_err()
+ );
+ let run = CursorRunId::new("run-1");
+ journal
+ .append(&id, 1, Some(&run), &JournalInput::Poll("raw".into()))
+ .await
+ .unwrap();
+ let rows = journal.read(&id).await.unwrap();
+ assert_eq!(rows.len(), 2);
+ assert_eq!(rows[1].run.as_ref(), Some(&run));
+ let timestamped = sqlx::query_scalar!(
+ "SELECT count(*) AS \"count!\" FROM cursor_journal_input WHERE inserted_at IS NOT NULL AND inserted_at <= now()"
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(
+ timestamped, 2,
+ "appends get a database timestamp by default"
+ );
+ let foreign = PgCursorJournal::new(pool.clone(), session, other);
+ foreign.activate(session, other, ManagerFence(1)).unwrap();
+ assert!(
+ foreign.read(&id).await.is_err(),
+ "must not adopt another replica's fence"
+ );
+ sqlx::query!(
+ "UPDATE agent_session SET manager_fence = 2 WHERE id = $1",
+ session.as_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ journal.read(&id).await.is_err(),
+ "read after takeover fails"
+ );
+ assert!(
+ journal
+ .append(&id, 2, None, &JournalInput::HistoryComplete)
+ .await
+ .is_err()
+ );
+ assert!(
+ stale_before_io.read(&id).await.is_err(),
+ "A's first IO must not adopt same-replica successor generation"
+ );
+ assert!(
+ stale_before_io
+ .append(&id, 2, None, &JournalInput::HistoryComplete)
+ .await
+ .is_err()
+ );
+ assert!(
+ stale_before_io
+ .activate(session, replica, ManagerFence(2))
+ .is_err(),
+ "cannot rebind old connection"
+ );
+ let successor = PgCursorJournal::new(pool.clone(), session, replica);
+ successor
+ .activate(session, replica, ManagerFence(2))
+ .unwrap();
+ assert_eq!(successor.read(&id).await.unwrap().len(), 2);
+ successor
+ .append(&id, 2, Some(&run), &JournalInput::Reconciled)
+ .await
+ .unwrap();
+ let (first, second) = tokio::join!(
+ successor.append(&id, 3, None, &JournalInput::HistoryComplete),
+ successor.append(&id, 3, None, &JournalInput::HistoryComplete),
+ );
+ assert_ne!(first.is_ok(), second.is_ok(), "only one append can win");
+ assert_eq!(successor.read(&id).await.unwrap().len(), 4);
+ sqlx::query!("DELETE FROM agent_session WHERE id = $1", session.as_uuid())
+ .execute(&pool)
+ .await
+ .unwrap();
+ let count: i64 = sqlx::query_scalar!("SELECT count(*) AS \"count!\" FROM cursor_journal_input")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(count, 0);
+
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260906060601_cursor_session_replay.down.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::raw_sql(include_str!(
+ "../../../../macro_db_client/migrations/20260906060601_cursor_session_replay.up.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+}
diff --git a/crates/cursor_cloud_agents/src/replay.rs b/crates/cursor_cloud_agents/src/replay.rs
index d2c47ae575..7b1e1f1a2c 100644
--- a/crates/cursor_cloud_agents/src/replay.rs
+++ b/crates/cursor_cloud_agents/src/replay.rs
@@ -22,19 +22,8 @@ use crate::domain::translate::TranslateMachine;
use agent_client_protocol::schema::v1::SessionUpdate;
use sse_core::SseEvent;
-/// One decoded record: the SSE event name and its payload.
-///
-/// `sse_core`'s `MessageEvent` also carries `last_event_id`, which nothing
-/// consumes yet — it is what a reconnect would resume from. Reduced to the
-/// two fields the translation reads so that comparing two decodings compares
-/// what matters.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Record {
- /// The `event:` name, defaulted to `message` by the spec.
- pub event: String,
- /// All `data:` lines, joined with newlines.
- pub data: String,
-}
+/// A complete native record, including the provider ID when present.
+pub use crate::domain::journal::NativeRecord as Record;
/// Decode a recording, feeding the decoder `chunk_size` bytes at a time.
///
@@ -61,6 +50,7 @@ pub fn chunked(sse: &str, chunk_size: usize) -> Vec<Record> {
SseEvent::Message(message) => records.push(Record {
event: message.event.into_owned(),
data: message.data,
+ id: message.last_event_id.map(|id| id.to_string()),
}),
// Cursor has never sent one; nothing reconnects on it yet.
SseEvent::Retry(_) => {}
@@ -85,10 +75,7 @@ pub fn records(sse: &str) -> Vec<Record> {
pub fn events(sse: &str) -> Vec<CursorEvent> {
records(sse)
.into_iter()
- .map(|record| {
- let data = serde_json::from_str(&record.data).unwrap_or(serde_json::Value::Null);
- CursorEvent::from_wire(&record.event, data)
- })
+ .map(|record| record.decode())
.collect()
}
@@ -101,3 +88,20 @@ pub fn updates(sse: &str) -> Vec<SessionUpdate> {
.flat_map(|event| machine.push(event))
.collect()
}
+
+/// Complete replay, including native user messages and terminal tool updates.
+/// Production capture and ACP load use this same machine.
+pub fn complete_updates(
+ sse: &str,
+ run: &crate::domain::model::CursorRunId,
+) -> Result<Vec<SessionUpdate>, rootcause::Report> {
+ let mut machine = crate::domain::journal::ReplayMachine::default();
+ let mut updates = Vec::new();
+ for record in records(sse) {
+ updates.extend(machine.push(
+ Some(run),
+ &crate::domain::journal::JournalInput::Sse(record),
+ )?);
+ }
+ Ok(updates)
+}
diff --git a/crates/cursor_cloud_agents/src/testing.rs b/crates/cursor_cloud_agents/src/testing.rs
index 2f9c8746a0..949f31d0da 100644
--- a/crates/cursor_cloud_agents/src/testing.rs
+++ b/crates/cursor_cloud_agents/src/testing.rs
@@ -1,6 +1,7 @@
//! In-memory port implementations and recorded fixtures, for tests.
use crate::domain::event::CursorEvent;
+use crate::domain::journal::NativeRecord;
use crate::domain::model::{
CursorAgentId, CursorModel, CursorRunId, McpServer, ModelChoice, RepoUrl, RunListing,
RunOutcome,
@@ -33,10 +34,85 @@ pub fn fixture_sse(name: &str) -> String {
.unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display()))
}
-/// Load a recorded fixture already decoded into domain events.
+/// Load original complete SSE records without decoding their payloads.
#[must_use]
-pub fn fixture_events(name: &str) -> Vec<CursorEvent> {
- crate::replay::events(&fixture_sse(name))
+pub fn fixture_records(name: &str) -> Vec<NativeRecord> {
+ crate::replay::records(&fixture_sse(name))
+}
+
+/// Build a fake provider record using Cursor's HTTP SSE payload shape, not
+/// serde's representation of the domain enum. Decoding remains production code.
+pub fn raw_record(event: CursorEvent) -> NativeRecord {
+ use crate::domain::event::InteractionUpdate;
+ use serde_json::json;
+ let (event, data) = match event {
+ CursorEvent::Status { run_id, status } => (
+ "status".to_owned(),
+ json!({"runId": run_id, "status": status}),
+ ),
+ CursorEvent::Assistant { text } => ("assistant".into(), json!({"text": text})),
+ CursorEvent::Thinking { text } => ("thinking".into(), json!({"text": text})),
+ CursorEvent::ToolCall(call) => (
+ "tool_call".into(),
+ json!({
+ "callId": call.call_id, "name": call.name, "status": call.status,
+ "args": call.args, "result": call.result, "truncated": call.truncated,
+ }),
+ ),
+ CursorEvent::Interaction(update) => (
+ "interaction_update".into(),
+ match update {
+ InteractionUpdate::UserMessage { text } => {
+ json!({"type": "user-message-appended", "userMessage": {"text": text}})
+ }
+ InteractionUpdate::ToolCallStarted { call_id, tool_type } => {
+ json!({"type": "tool-call-started", "callId": call_id, "toolCall": {"type": tool_type}})
+ }
+ InteractionUpdate::ToolCallCompleted { call_id, tool_type } => {
+ json!({"type": "tool-call-completed", "callId": call_id, "toolCall": {"type": tool_type}})
+ }
+ InteractionUpdate::TokenDelta { tokens } => {
+ json!({"type": "token-delta", "tokens": tokens})
+ }
+ InteractionUpdate::Other { kind } => json!({"type": kind}),
+ },
+ ),
+ CursorEvent::Result {
+ run_id,
+ status,
+ text,
+ duration_ms,
+ } => (
+ "result".into(),
+ json!({"runId": run_id, "status": status, "text": text, "durationMs": duration_ms}),
+ ),
+ CursorEvent::Heartbeat => ("heartbeat".into(), json!({})),
+ CursorEvent::Error { code, message } => {
+ ("error".into(), json!({"code": code, "message": message}))
+ }
+ CursorEvent::Done => ("done".into(), json!({})),
+ CursorEvent::Unknown { event, data } => (event, data),
+ };
+ NativeRecord {
+ event,
+ data: data.to_string(),
+ id: None,
+ }
+}
+
+/// Test-side wire encoder. The provider channel carries only native records.
+pub struct ScriptSender(mpsc::UnboundedSender<NativeRecord>);
+
+impl ScriptSender {
+ /// Whether the provider's stream receiver has been dropped.
+ pub fn is_closed(&self) -> bool {
+ self.0.is_closed()
+ }
+
+ /// Encode a desired event as a Cursor wire record before enqueueing it.
+ pub fn send(&self, event: CursorEvent) -> Result<(), mpsc::error::SendError<NativeRecord>> {
+ self.0.send(raw_record(event))
+ }
}
/// What a [`FakeCursor`] was asked to do.
@@ -64,8 +140,8 @@ pub struct FakeCursor {
struct FakeCursorState {
calls: Vec<CursorCall>,
next_run: u64,
- /// The receiver the next `stream()` call will drain.
- streams: Vec<mpsc::UnboundedReceiver<CursorEvent>>,
+ /// The receiver the next `raw_stream()` call will drain.
+ streams: Vec<mpsc::UnboundedReceiver<NativeRecord>>,
/// Answers for `run_result`, consumed in order.
run_results: Vec<RunOutcome>,
/// The answer every `list_runs` call gets.
@@ -76,6 +152,8 @@ struct FakeCursorState {
create_gate: Option<tokio::sync::oneshot::Receiver<()>>,
/// The answer every `list_models` call gets.
models: Vec<CursorModel>,
+ model_gate: Option<tokio::sync::oneshot::Receiver<()>>,
+ reject_create: bool,
}
impl FakeCursor {
@@ -87,9 +165,14 @@ impl FakeCursor {
/// Queue a stream for the next run and get its sending half.
///
- /// Each `stream()` call consumes one queued stream in order; the test
+ /// Each `raw_stream()` call consumes one queued stream in order; the test
/// drives the turn by sending events and dropping the sender to end it.
- pub fn script_stream(&self) -> mpsc::UnboundedSender<CursorEvent> {
+ pub fn script_stream(&self) -> ScriptSender {
+ ScriptSender(self.script_raw_stream())
+ }
+
+ /// Queue original native records, including recorded wire fixtures.
+ pub fn script_raw_stream(&self) -> mpsc::UnboundedSender<NativeRecord> {
let (sender, receiver) = mpsc::unbounded_channel();
self.inner
.lock()
@@ -131,6 +214,17 @@ impl FakeCursor {
sender
}
+ /// Hold model resolution to inspect pre-execution ordering.
+ pub fn script_model_gate(&self) -> tokio::sync::oneshot::Sender<()> {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ self.inner.lock().unwrap().model_gate = Some(rx);
+ tx
+ }
+ /// Reject the next create with a definite provider rejection.
+ pub fn script_rejection(&self) {
+ self.inner.lock().unwrap().reject_create = true;
+ }
+
/// Set the models `list_models` answers with.
pub fn script_models(&self, models: Vec<CursorModel>) {
self.inner.lock().expect("fake cursor poisoned").models = models;
@@ -213,6 +307,12 @@ impl CursorAgents for FakeCursor {
));
self.await_create_gate().await;
let mut state = self.inner.lock().expect("fake cursor poisoned");
+ if std::mem::take(&mut state.reject_create) {
+ return Err(rootcause::report!(crate::domain::error::PromptRejected(
+ "rejected".into()
+ ))
+ .into_dynamic());
+ }
state.next_run += 1;
Ok((
CursorAgentId::new("bc-fake"),
@@ -231,16 +331,27 @@ impl CursorAgents for FakeCursor {
prompt.to_owned(),
model.cloned(),
));
+ self.await_create_gate().await;
let mut state = self.inner.lock().expect("fake cursor poisoned");
if !state.create_run_errors.is_empty() {
let message = state.create_run_errors.remove(0);
return Err(rootcause::report!("{message}"));
}
+ if std::mem::take(&mut state.reject_create) {
+ return Err(rootcause::report!(crate::domain::error::PromptRejected(
+ "rejected".into()
+ ))
+ .into_dynamic());
+ }
state.next_run += 1;
Ok(CursorRunId::new(format!("run-fake-{}", state.next_run)))
}
async fn list_models(&self) -> Result<Vec<CursorModel>, rootcause::Report> {
+ let gate = self.inner.lock().unwrap().model_gate.take();
+ if let Some(gate) = gate {
+ let _ = gate.await;
+ }
Ok(self
.inner
.lock()
@@ -258,22 +369,27 @@ impl CursorAgents for FakeCursor {
Ok(())
}
- async fn run_result(
+ async fn raw_result(
&self,
agent: &CursorAgentId,
run: &CursorRunId,
- ) -> Result<RunOutcome, rootcause::Report> {
+ ) -> Result<String, rootcause::Report> {
self.record(CursorCall::RunResult(agent.clone(), run.clone()));
let mut state = self.inner.lock().expect("fake cursor poisoned");
if state.run_results.is_empty() {
return Err(rootcause::report!("no scripted run result queued"));
}
- Ok(state.run_results.remove(0))
+ let outcome = state.run_results.remove(0);
+ Ok(
+ serde_json::json!({"id": run, "status": outcome.status, "result": outcome.text})
+ .to_string(),
+ )
}
async fn list_runs(
&self,
_agent: &CursorAgentId,
+ _through: Option<&CursorRunId>,
) -> Result<Vec<RunListing>, rootcause::Report> {
Ok(self
.inner
@@ -285,11 +401,11 @@ impl CursorAgents for FakeCursor {
}
impl RunStream for FakeCursor {
- async fn stream(
+ async fn raw_stream(
&self,
_agent: &CursorAgentId,
_run: &CursorRunId,
- ) -> Result<impl Stream<Item = Result<CursorEvent, rootcause::Report>> + Send, rootcause::Report>
+ ) -> Result<impl Stream<Item = Result<NativeRecord, rootcause::Report>> + Send, rootcause::Report>
{
let receiver = {
let mut state = self.inner.lock().expect("fake cursor poisoned");
@@ -304,10 +420,14 @@ impl RunStream for FakeCursor {
}
}
-/// Records every update it is asked to deliver.
+type RecordedUpdates = Vec<(SessionId, SessionUpdate)>;
+
+/// Records live updates and host-local reload requirements.
+/// Tests of raw frame ordering use the served ACP transport instead.
#[derive(Debug, Clone, Default)]
pub struct RecordingNotifier {
- updates: Arc<Mutex<Vec<(SessionId, SessionUpdate)>>>,
+ updates: Arc<Mutex<RecordedUpdates>>,
+ reloads: Arc<Mutex<Vec<SessionId>>>,
delivered: Arc<tokio::sync::Notify>,
}
@@ -318,12 +438,17 @@ impl RecordingNotifier {
Self::default()
}
- /// Everything delivered so far, in order.
+ /// The selected history and live updates, in order.
#[must_use]
pub fn updates(&self) -> Vec<(SessionId, SessionUpdate)> {
self.updates.lock().expect("notifier poisoned").clone()
}
+ /// Sessions whose recovered history needs a client load.
+ pub fn reloads(&self) -> Vec<SessionId> {
+ self.reloads.lock().expect("notifier poisoned").clone()
+ }
+
/// Resolve once `at_least` updates have been delivered.
///
/// The way a test waits for a turn to have actually reached its stream.
@@ -356,6 +481,30 @@ impl SessionNotifier for RecordingNotifier {
self.delivered.notify_waiters();
Ok(())
}
+
+ async fn require_reload(&self, session: &SessionId) -> Result<(), rootcause::Report> {
+ self.reloads
+ .lock()
+ .expect("notifier poisoned")
+ .push(session.clone());
+ Ok(())
+ }
+
+ async fn turn_complete(
+ &self,
+ _session: &SessionId,
+ _outcome: agent_runtime_protocol::domain::turn::TurnOutcome,
+ ) -> Result<(), rootcause::Report> {
+ Ok(())
+ }
+
+ async fn checkpoint(
+ &self,
+ _session: &SessionId,
+ _run: &CursorRunId,
+ ) -> Result<(), rootcause::Report> {
+ Ok(())
+ }
}
/// Resolves every session to the same repository — or none.
@@ -367,3 +516,26 @@ impl RepoResolver for FixedRepos {
self.0.clone()
}
}
+
+/// Provide complete native history for a legacy restored-session test.
+pub fn script_legacy_history(cursor: &FakeCursor) {
+ use crate::domain::event::InteractionUpdate;
+ use crate::domain::model::RunStatus;
+ cursor.script_run_listings(vec![RunListing {
+ id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ }]);
+ let tx = cursor.script_stream();
+ tx.send(CursorEvent::Interaction(InteractionUpdate::UserMessage {
+ text: "original prompt".into(),
+ }))
+ .unwrap();
+ tx.send(CursorEvent::Result {
+ run_id: CursorRunId::new("run-old"),
+ status: RunStatus::Finished,
+ text: None,
+ duration_ms: None,
+ })
+ .unwrap();
+ tx.send(CursorEvent::Done).unwrap();
+}
diff --git a/crates/macro_db_client/migrations/20260906060601_cursor_session_replay.down.sql b/crates/macro_db_client/migrations/20260906060601_cursor_session_replay.down.sql
new file mode 100644
index 0000000000..1778411bb0
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260906060601_cursor_session_replay.down.sql
@@ -0,0 +1,9 @@
+DROP TABLE cursor_journal_input;
+
+ALTER TABLE agent_session DROP CONSTRAINT agent_session_history_start_fk;
+ALTER TABLE agent_session DROP COLUMN history_start_log_id;
+ALTER TABLE agent_session_log DROP CONSTRAINT agent_session_log_session_id_unique;
+
+ALTER TABLE external_agent_session
+DROP CONSTRAINT external_agent_session_last_run_id_not_empty,
+DROP COLUMN last_run_id;
diff --git a/crates/macro_db_client/migrations/20260906060601_cursor_session_replay.up.sql b/crates/macro_db_client/migrations/20260906060601_cursor_session_replay.up.sql
new file mode 100644
index 0000000000..a253975dc0
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260906060601_cursor_session_replay.up.sql
@@ -0,0 +1,27 @@
+ALTER TABLE external_agent_session
+ADD COLUMN last_run_id TEXT;
+
+ALTER TABLE external_agent_session
+ADD CONSTRAINT external_agent_session_last_run_id_not_empty
+CHECK (last_run_id IS NULL OR last_run_id <> '');
+
+ALTER TABLE agent_session ADD COLUMN history_start_log_id uuid;
+-- Composite identity prevents cross-session boundaries even outside the repository.
+ALTER TABLE agent_session_log ADD CONSTRAINT agent_session_log_session_id_unique UNIQUE (agent_session_id, id);
+ALTER TABLE agent_session ADD CONSTRAINT agent_session_history_start_fk
+ FOREIGN KEY (id, history_start_log_id)
+ REFERENCES agent_session_log (agent_session_id, id)
+ ON DELETE SET NULL (history_start_log_id);
+
+-- Cursor's native journal is separate from the ACP delivery watermark.
+-- Provider identity remains in external_agent_session. Inputs may precede
+-- creation of that mapping (e.g. a new, empty session).
+CREATE TABLE cursor_journal_input (
+ agent_session_id UUID NOT NULL REFERENCES agent_session(id) ON DELETE CASCADE,
+ sequence BIGINT NOT NULL CHECK (sequence > 0),
+ run_id TEXT CHECK (run_id <> ''),
+ input JSONB NOT NULL,
+ inserted_at timestamptz NOT NULL DEFAULT now(),
+ PRIMARY KEY (agent_session_id, sequence)
+);
+CREATE INDEX cursor_journal_input_run ON cursor_journal_input(agent_session_id, run_id, sequence);
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 494bb4b8ef..ee6311d254 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -90,6 +90,22 @@ scroll several screens up and confirm output does not pull you down. Scroll down
to reveal the overlay and return to latest. Repeat with a short session and on a
physical phone while opening/dismissing the keyboard, both at latest and in history.
+When a session reconnects using ACP load, the last committed conversation stays
+visible while history is reconstructed. A successful load replaces the transcript
+once, including prompts, thoughts, and tool results; it does not append another
+copy. Replayed rows can change content type under existing message or tool IDs;
+the live transcript must show the new content without an error or a reload.
+A failed or interrupted load leaves the previous conversation visible, and
+late replay notifications remain hidden across initialization/reconnect markers
+until a valid session open or dispatched prompt establishes live traffic. Reopening
+the session shows the same committed history. Initialization, creating a session, and ACP resume do
+not by themselves clear existing messages. Channel agent-reference previews follow
+the same replacement behavior. Every successful load can replace history with an
+empty transcript, including historical lookup-only Cursor load acknowledgments.
+If a load finishes while the browser
+is fetching history, buffered content from before the selected history boundary
+must stay hidden; subsequent live messages must still appear.
+
### Sending and queueing
- Sending is never blocked by a running turn. A prompt sent mid-turn is queued
diff --git a/docs/CURSOR_AGENT_TRANSPORT.md b/docs/CURSOR_AGENT_TRANSPORT.md
index 8e39f383f7..f1763c202c 100644
--- a/docs/CURSOR_AGENT_TRANSPORT.md
+++ b/docs/CURSOR_AGENT_TRANSPORT.md
@@ -410,6 +410,90 @@ discipline above is the cost of admission.
## Lifecycle mapping
+### Durable Load History
+
+Cursor restores through ACP `session/load`, not `session/resume`. The implementation
+captures original prompts, complete SSE records, polling bodies, and local
+lifecycle decisions before translating them. Loading uses the same processing
+machine as live delivery and never executes a provider prompt or tool again.
+
+Every replayed ACP frame is appended to `agent_session_log`, including repeated
+conversation content. Only a matching, valid, successfully persisted load
+response selects a new effective-history window, starting at that connection's
+initialization. The selection is atomic with the response under the session's
+ownership fence. The raw audit history is retained; the product log endpoint
+reads the selected indexed range. Generic server and browser folds stage load
+updates separately and replace visible history only on success. Failed or
+incomplete loads preserve the committed conversation; resume does not replace it.
+
+Live recovery uses this same load path. Cursor captures foreign or interrupted
+runs into its native journal without publishing replacement conversation frames.
+Its notifier enqueues a typed, host-local reload requirement; the pipe adapter
+delivers that requirement before a queued prompt response. The session domain
+waits for the current prompt response, queues subsequent commands, and initiates
+`initialize` followed by standard `session/load`. Each successful load therefore
+has its own durable initialization boundary. There is no agent-initiated client
+request or separate history replacement protocol. The notification never waits
+for load while holding Cursor's writer gate; the load reply remains serialized
+with live writers through `ReplayGuard`.
+The requirement is consumed internally, never persisted as a user-facing status.
+Already-dispatched prompts may finish while reload is pending; subsequent commands
+wait at the host's handshake gate. Recovery observed while a load reply is queued
+causes another load before those commands are flushed. Standalone ACP clients
+without the host channel continue serving prompts and expose captured history on
+their next client-initiated load, without unsolicited replacement traffic.
+One pending-reload bit suppresses further background capture until load completes,
+without rejecting already-dispatched prompts. Recovery validates the journal before
+requesting load; unavailable original prompts retain the old visible history rather
+than demanding a replacement known to be incomplete.
+
+Existing sessions without a complete native journal require provider-history
+hydration. If Cursor no longer exposes enough history to reconstruct the
+conversation, load must fail explicitly rather than select an incomplete
+replacement. Operators should account for this retention limitation before
+rollout. The delivered-run watermark remains separate from journal capture
+progress, and local journal sequence numbers are not remote SSE resume tokens.
+
+The journal's atomic owner fence is not a second ownership authority. The
+session service acquires the claim and binds that exact generation once through
+`activate_reserved` and `RuntimeAttachment::on_activate`, which receives the typed
+`SessionClaim` before actor startup. Container providers return attachments;
+transport mapping preserves the callback and shared handshake. Physical
+transports carry frames only. The journal never
+claims ownership or refreshes its fence from a database read.
+
+The browser forwards the effective-history snapshot and buffered/live durable
+rows to Rust `LogIngestion` through WASM `snapshot` and `push_rows`. Ingestion
+retains the snapshot IDs and inclusive `(created_at, id)` boundary, preserving
+Postgres timestamp precision without a JavaScript timestamp comparator. It drops
+only snapshot duplicates and excluded older rows, never distinct ACP replay
+rows, and preserves live delivery order without a moving high-water mark.
+The ID set stays bounded by snapshot size. `FoldMachine` remains append-only;
+raw recording consumers retain the existing `extend` and `push` API.
+
+Routing new commands away from a stale replica does not stop its existing work.
+`PgAgentSessionRepo::claim` can take over when the old replica's heartbeat is
+stale, without notifying its process. `activate_reserved` gives the actor a
+fenced ACP log writer; the next rejected append stops that actor. `run_session`
+then drops its transport, and the pipe pump closes asynchronously. Independently,
+`CursorContainerManager::serve_session` awaits `sync_foreign_runs` inside its
+timer branch: pipe cancellation is not polled again until that await finishes.
+A provider response can therefore reach the native journal after takeover even
+with no new command dispatched to the old replica.
+
+`PgCursorJournal::lock_owner` checks the bound replica/generation while holding
+the `agent_session` row lock through journal commit. Takeover updates that same
+row: either the old append commits before takeover, or it fails after takeover.
+The existing `SessionClaim` is a token, not a transaction-bound storage capability;
+the existing fenced ACP writer only covers ACP log appends. Wrapping a simple
+journal with a preflight ownership check would lose this atomicity. Retain the
+small storage fence rather than introduce a new generic transaction wrapper.
+
+Native SSE records contain only event name, original data, and provider ID.
+Scripted providers emit the same wire-shaped records through the production
+decoder; recorded fixtures retain their original payloads rather than being
+decoded and re-encoded as domain enums.
+
Most of the sandbox lifecycle is meaningless for Cursor. Stating what each port
method degenerates to, so the small implementation does not read as an
oversight:
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index f8509e85b5..ae78fdd4a5 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -132,9 +132,9 @@ export class Sdk extends HeyApiClient {
/**
* The raw protocol log of one agent session.
*
- * Served unfolded, and whole: the fold is a left fold over the frames from
- * the beginning, so a reader that skipped any of them would derive different
- * turn numbering.
+ * Served unfolded from the latest successful load initialization, or the
+ * beginning when no load succeeded. Consumers stage load attempts so failed
+ * or interrupted replay does not become visible conversation content.
*
* An unknown session is an error: the response has to name the session's
* agent, and a session that never existed has none to name.
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 737befe305..8093bc41ba 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -66,6 +66,10 @@ export type AgentSessionLogEntryDto = LogFrameDto & {
* session and nothing more.
*/
createdAt: string;
+ /**
+ * Durable transport row identity; together with `createdAt`, its order cursor.
+ */
+ id: string;
/**
* The user whose action produced the frame, absent when no user did.
*
@@ -92,7 +96,10 @@ export type AgentSessionLogResponse = {
*/
bot: SessionBot;
/**
- * Every logged frame, oldest first. Folding depends on this order.
+ * Effective history in ascending `(createdAt, id)` order.
+ * The first row is the inclusive history boundary cursor: buffered rows
+ * before it are obsolete. Reconcile snapshot overlap by row ID, never content.
+ * An empty history has no boundary or overlapping rows.
*/
entries: Array<AgentSessionLogEntryDto>;
};
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 39f203e4bc..46518c953e 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -375,7 +375,7 @@
"get": {
"tags": ["agent-sessions"],
"summary": "The raw protocol log of one agent session.",
- "description": "Served unfolded, and whole: the fold is a left fold over the frames from\nthe beginning, so a reader that skipped any of them would derive different\nturn numbering.\n\nAn unknown session is an error: the response has to name the session's\nagent, and a session that never existed has none to name.",
+ "description": "Served unfolded from the latest successful load initialization, or the\nbeginning when no load succeeded. Consumers stage load attempts so failed\nor interrupted replay does not become visible conversation content.\n\nAn unknown session is an error: the response has to name the session's\nagent, and a session that never existed has none to name.",
"operationId": "get_agent_session_log",
"parameters": [
{
@@ -897,13 +897,18 @@
},
{
"type": "object",
- "required": ["createdAt"],
+ "required": ["id", "createdAt"],
"properties": {
"createdAt": {
"type": "string",
"format": "date-time",
"description": "When the log recorded the frame.\n\nThe frame itself carries no time, so this comes from the log row. It is\nwhat a reader has to order these against anything else it is showing\nbeside them - the fold derives an order among the messages of one\nsession and nothing more."
},
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Durable transport row identity; together with `createdAt`, its order cursor."
+ },
"userId": {
"type": ["string", "null"],
"description": "The user whose action produced the frame, absent when no user did.\n\nOnly prompts carry one, and only when the frame was attributed at the\ntime - a replayed or recorded session's are anonymous."
@@ -927,7 +932,7 @@
"items": {
"$ref": "#/components/schemas/AgentSessionLogEntryDto"
},
- "description": "Every logged frame, oldest first. Folding depends on this order."
+ "description": "Effective history in ascending `(createdAt, id)` order.\nThe first row is the inclusive history boundary cursor: buffered rows\nbefore it are obsolete. Reconcile snapshot overlap by row ID, never content.\nAn empty history has no boundary or overlapping rows."
}
}
},
diff --git a/services/agent_harness_service/src/containers.rs b/services/agent_harness_service/src/containers.rs
index 95a884def6..373b9365b1 100644
--- a/services/agent_harness_service/src/containers.rs
+++ b/services/agent_harness_service/src/containers.rs
@@ -149,19 +149,24 @@ where
{
type Transport = RoutedTransport;
- async fn spawn(&self, command: SpawnContainer) -> Result<Self::Transport> {
+ async fn spawn(
+ &self,
+ command: SpawnContainer,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
match self.route(command.session_id).await? {
- Route::InMem(facts) => Ok(RoutedTransport::InMem(
- self.inmem()
- .manager
- .attach(facts, Some(command.egress.session_token))
- .await,
+ Route::InMem(facts) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ RoutedTransport::InMem(
+ self.inmem()
+ .manager
+ .attach(facts, Some(command.egress.session_token))
+ .await,
+ ),
)),
Route::Sandbox => self
.sandbox
.spawn(command)
.await
- .map(RoutedTransport::Sandbox),
+ .map(|attachment| attachment.map_transport(RoutedTransport::Sandbox)),
}
}
@@ -182,16 +187,19 @@ where
}
}
- async fn resume(&self, session: AgentSessionId) -> Result<Self::Transport> {
+ async fn resume(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<agent_session::domain::connection::RuntimeAttachment<Self::Transport>> {
match self.route(session).await? {
- Route::InMem(facts) => Ok(RoutedTransport::InMem(
- self.inmem().manager.attach(facts, None).await,
+ Route::InMem(facts) => Ok(agent_session::domain::connection::RuntimeAttachment::solo(
+ RoutedTransport::InMem(self.inmem().manager.attach(facts, None).await),
)),
Route::Sandbox => self
.sandbox
.resume(session)
.await
- .map(RoutedTransport::Sandbox),
+ .map(|attachment| attachment.map_transport(RoutedTransport::Sandbox)),
}
}
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 31e9cc9766..70331f4276 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -374,6 +374,8 @@ async fn run() -> anyhow::Result<()> {
CursorRepoUrl::parse(&config.cursor_repo_url)
.context("CURSOR_REPO_URL is not a valid repository url")?,
session_repo.clone(),
+ pool.clone(),
+ replica,
);
// Fixed system agents retain their deployment defaults. User/team agents
// are resolved from agent_configs for every trigger so newly-created or