Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(agents): review linked GitHub pull request diffs (#6626)

Eric Hayes1d75f3fd74a0
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index bf4038bb24..380ec4dc4b 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -43,6 +43,97 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "agent_changes": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_changes",
+ "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/comms_db_client",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/database_env_vars",
+ "crates/document_sub_type",
+ "crates/documents",
+ "crates/embedding",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/entity_registry/entity_registry_db_utils",
+ "crates/entity_registry/shared_entity_registry",
+ "crates/filter_ast",
+ "crates/foreign_entity",
+ "crates/frecency",
+ "crates/fusionauth",
+ "crates/genai_telemetry",
+ "crates/github",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/invite_email",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_sync_service_jwt",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_entity_access_management",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_sfs",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/notification_state",
+ "crates/prompt",
+ "crates/rate_limit",
+ "crates/remote_env_var",
+ "crates/s3_key",
+ "crates/secretsmanager_client",
+ "crates/share_permission_db_utils",
+ "crates/sqs_worker",
+ "crates/static_file_service_client",
+ "crates/sync_service",
+ "crates/sync_service_client",
+ "crates/system_properties",
+ "crates/system_skills",
+ "crates/task_dedup",
+ "crates/workspace-hack"
+ ],
"agent_egress": [
"crates/activity",
"crates/agent",
@@ -257,6 +348,7 @@
"agent_harness_service": [
"crates/activity",
"crates/agent",
+ "crates/agent_changes",
"crates/agent_egress",
"crates/agent_fold",
"crates/agent_harness",
diff --git a/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json b/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json
new file mode 100644
index 0000000000..30b8a29f8c
--- /dev/null
+++ b/.sqlx/query-03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM agent_session WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "03c1f300effe353d4fbd0edadb14d47d823a7b30fb531e515758ef72919cd9df"
+}
diff --git a/.sqlx/query-04497347961cee74a829f6367fee3a3545beb7cea74e5eb5fdab9aaf4984fa3f.json b/.sqlx/query-04497347961cee74a829f6367fee3a3545beb7cea74e5eb5fdab9aaf4984fa3f.json
new file mode 100644
index 0000000000..318d0550c2
--- /dev/null
+++ b/.sqlx/query-04497347961cee74a829f6367fee3a3545beb7cea74e5eb5fdab9aaf4984fa3f.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user_info (macro_user_id, first_name, last_name) VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "04497347961cee74a829f6367fee3a3545beb7cea74e5eb5fdab9aaf4984fa3f"
+}
diff --git a/.sqlx/query-071509888a88fa74d75735ba87cb18f03e0b441d1263f9cbf0899d9e386e6e03.json b/.sqlx/query-071509888a88fa74d75735ba87cb18f03e0b441d1263f9cbf0899d9e386e6e03.json
new file mode 100644
index 0000000000..20dd758b10
--- /dev/null
+++ b/.sqlx/query-071509888a88fa74d75735ba87cb18f03e0b441d1263f9cbf0899d9e386e6e03.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"ItemLastAccessed\" (\"item_id\", \"item_type\", \"last_accessed\") VALUES ($1, $2, NOW())\n RETURNING \"last_accessed\" as last_accessed\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "last_accessed",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "071509888a88fa74d75735ba87cb18f03e0b441d1263f9cbf0899d9e386e6e03"
+}
diff --git a/.sqlx/query-071aa384be7a68b05d05a735a85972ac5868ce6b06dcf867c58f5aa5b7c457a2.json b/.sqlx/query-071aa384be7a68b05d05a735a85972ac5868ce6b06dcf867c58f5aa5b7c457a2.json
new file mode 100644
index 0000000000..996972bffc
--- /dev/null
+++ b/.sqlx/query-071aa384be7a68b05d05a735a85972ac5868ce6b06dcf867c58f5aa5b7c457a2.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team (id, name, owner_id)\n VALUES\n ('dddddddd-dddd-dddd-dddd-000000000001', 'Chat owner team', 'user-1'),\n ('dddddddd-dddd-dddd-dddd-000000000002', 'Other team', 'user-2')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "071aa384be7a68b05d05a735a85972ac5868ce6b06dcf867c58f5aa5b7c457a2"
+}
diff --git a/.sqlx/query-0768e44184d2a54457e500d992b1ec9e89290590ce42eab4f5123c9060de917b.json b/.sqlx/query-0768e44184d2a54457e500d992b1ec9e89290590ce42eab4f5123c9060de917b.json
new file mode 100644
index 0000000000..23edf2157e
--- /dev/null
+++ b/.sqlx/query-0768e44184d2a54457e500d992b1ec9e89290590ce42eab4f5123c9060de917b.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT status, attempt_count FROM webhook_delivery WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "attempt_count",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "0768e44184d2a54457e500d992b1ec9e89290590ce42eab4f5123c9060de917b"
+}
diff --git a/.sqlx/query-0d0fd018b6a7f2f70289f795dca89d2e4d8774e97774f39f0e60fd98effe7f5b.json b/.sqlx/query-0d0fd018b6a7f2f70289f795dca89d2e4d8774e97774f39f0e60fd98effe7f5b.json
new file mode 100644
index 0000000000..044ad25149
--- /dev/null
+++ b/.sqlx/query-0d0fd018b6a7f2f70289f795dca89d2e4d8774e97774f39f0e60fd98effe7f5b.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES ($1, $2, 'DOCUMENT', $3, $4)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET values = $4\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0d0fd018b6a7f2f70289f795dca89d2e4d8774e97774f39f0e60fd98effe7f5b"
+}
diff --git a/.sqlx/query-0f9031fa93f6623c3121701b82477edf00672efe87149eb3d729afac70264cd8.json b/.sqlx/query-0f9031fa93f6623c3121701b82477edf00672efe87149eb3d729afac70264cd8.json
new file mode 100644
index 0000000000..7f18076709
--- /dev/null
+++ b/.sqlx/query-0f9031fa93f6623c3121701b82477edf00672efe87149eb3d729afac70264cd8.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT email FROM notification_email_unsubscribe WHERE email = 'new'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "0f9031fa93f6623c3121701b82477edf00672efe87149eb3d729afac70264cd8"
+}
diff --git a/.sqlx/query-0fa7ef02b9a876d94d603c2ec97afd1e65f3e12669b2a403dc6ea6735fd96804.json b/.sqlx/query-0fa7ef02b9a876d94d603c2ec97afd1e65f3e12669b2a403dc6ea6735fd96804.json
new file mode 100644
index 0000000000..71fa7ffe3f
--- /dev/null
+++ b/.sqlx/query-0fa7ef02b9a876d94d603c2ec97afd1e65f3e12669b2a403dc6ea6735fd96804.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT paying\n FROM team\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "paying",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "0fa7ef02b9a876d94d603c2ec97afd1e65f3e12669b2a403dc6ea6735fd96804"
+}
diff --git a/.sqlx/query-101a22ec0b29754f6e6e8fd86839b8fbf668639ba6ae3b11a9c606041e724a4d.json b/.sqlx/query-101a22ec0b29754f6e6e8fd86839b8fbf668639ba6ae3b11a9c606041e724a4d.json
new file mode 100644
index 0000000000..8178e842ec
--- /dev/null
+++ b/.sqlx/query-101a22ec0b29754f6e6e8fd86839b8fbf668639ba6ae3b11a9c606041e724a4d.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE webhook_delivery\n SET next_attempt_at = now() - INTERVAL '1 second'\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "101a22ec0b29754f6e6e8fd86839b8fbf668639ba6ae3b11a9c606041e724a4d"
+}
diff --git a/.sqlx/query-12f6f67c28024527342db6f87e5b9de6e16cd65729fb18c5713f281ff39f56c4.json b/.sqlx/query-12f6f67c28024527342db6f87e5b9de6e16cd65729fb18c5713f281ff39f56c4.json
new file mode 100644
index 0000000000..04cf548b0e
--- /dev/null
+++ b/.sqlx/query-12f6f67c28024527342db6f87e5b9de6e16cd65729fb18c5713f281ff39f56c4.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"Project\" (\"id\", \"name\", \"userId\") VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "12f6f67c28024527342db6f87e5b9de6e16cd65729fb18c5713f281ff39f56c4"
+}
diff --git a/.sqlx/query-16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644.json b/.sqlx/query-16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644.json
new file mode 100644
index 0000000000..03b1b3fb24
--- /dev/null
+++ b/.sqlx/query-16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'member')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "16d72a752357648effb2327791a771b02d72dd71725f71a90b4e7f05d87f2644"
+}
diff --git a/.sqlx/query-17bcd83046cf29fbe5a2a18bebb3ba0c983c9b861f5454579d44c676c13e89c5.json b/.sqlx/query-17bcd83046cf29fbe5a2a18bebb3ba0c983c9b861f5454579d44c676c13e89c5.json
new file mode 100644
index 0000000000..128dd7de20
--- /dev/null
+++ b/.sqlx/query-17bcd83046cf29fbe5a2a18bebb3ba0c983c9b861f5454579d44c676c13e89c5.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_changes (agent_session_id, attempt_started_at)\n VALUES ($1, $2)\n ON CONFLICT (agent_session_id) DO UPDATE SET\n attempt_started_at = EXCLUDED.attempt_started_at,\n attempt_finished_at = NULL,\n attempt_outcome = NULL,\n attempt_error = NULL,\n updated_at = now()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "17bcd83046cf29fbe5a2a18bebb3ba0c983c9b861f5454579d44c676c13e89c5"
+}
diff --git a/.sqlx/query-1806f429874e271fe817e54f60b6784f17845ef18ddce95bfc4154bfea8a941e.json b/.sqlx/query-1806f429874e271fe817e54f60b6784f17845ef18ddce95bfc4154bfea8a941e.json
new file mode 100644
index 0000000000..e1e6502426
--- /dev/null
+++ b/.sqlx/query-1806f429874e271fe817e54f60b6784f17845ef18ddce95bfc4154bfea8a941e.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE user_notification SET deleted_at = NOW() WHERE user_id = $1 AND notification_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1806f429874e271fe817e54f60b6784f17845ef18ddce95bfc4154bfea8a941e"
+}
diff --git a/.sqlx/query-19992234afc65ab0fee6e03978bdaccdac10436fad87e1b6b37ec348f64a94dd.json b/.sqlx/query-19992234afc65ab0fee6e03978bdaccdac10436fad87e1b6b37ec348f64a94dd.json
new file mode 100644
index 0000000000..4a62f1f9ac
--- /dev/null
+++ b/.sqlx/query-19992234afc65ab0fee6e03978bdaccdac10436fad87e1b6b37ec348f64a94dd.json
@@ -0,0 +1,55 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, user_id, device_token, device_endpoint, device_type as \"device_type:DeviceType\" \n FROM notification_user_device_registration \n WHERE id = '017d85a8-c7c6-7c40-b4f3-a6c1b3c0d1e4'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "device_token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "device_endpoint",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "device_type:DeviceType",
+ "type_info": {
+ "Custom": {
+ "name": "notification_device_type_option",
+ "kind": {
+ "Enum": [
+ "ios",
+ "android",
+ "iosvoip"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "19992234afc65ab0fee6e03978bdaccdac10436fad87e1b6b37ec348f64a94dd"
+}
diff --git a/.sqlx/query-19d9ffef89c520940b1275f8d2619d528926db849abc1c18362e7da7e671fe40.json b/.sqlx/query-19d9ffef89c520940b1275f8d2619d528926db849abc1c18362e7da7e671fe40.json
new file mode 100644
index 0000000000..01a5351d01
--- /dev/null
+++ b/.sqlx/query-19d9ffef89c520940b1275f8d2619d528926db849abc1c18362e7da7e671fe40.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"Thread\"\n SET \"deletedAt\" = NOW()\n WHERE \"id\" = 3001\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "19d9ffef89c520940b1275f8d2619d528926db849abc1c18362e7da7e671fe40"
+}
diff --git a/.sqlx/query-1b472b0b475a351d505afae3b2278bdc121db0b7795e7396d26f0ceaaafc21c3.json b/.sqlx/query-1b472b0b475a351d505afae3b2278bdc121db0b7795e7396d26f0ceaaafc21c3.json
new file mode 100644
index 0000000000..b6308e341f
--- /dev/null
+++ b/.sqlx/query-1b472b0b475a351d505afae3b2278bdc121db0b7795e7396d26f0ceaaafc21c3.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT attempt_count, first_attempt_at, last_attempt_at, next_attempt_at\n FROM webhook_delivery\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "attempt_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 1,
+ "name": "first_attempt_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "last_attempt_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "next_attempt_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "1b472b0b475a351d505afae3b2278bdc121db0b7795e7396d26f0ceaaafc21c3"
+}
diff --git a/.sqlx/query-204c6de853bb2ceb8b7c13f42931800be4092c170c7825ca61e218957395f00f.json b/.sqlx/query-204c6de853bb2ceb8b7c13f42931800be4092c170c7825ca61e218957395f00f.json
new file mode 100644
index 0000000000..96233900e5
--- /dev/null
+++ b/.sqlx/query-204c6de853bb2ceb8b7c13f42931800be4092c170c7825ca61e218957395f00f.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO microsoft_oauth_grants (\n fusionauth_user_id,\n email_address,\n refresh_token_ciphertext,\n encrypted_data_key,\n nonce,\n encryption_version,\n kms_key_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Bytea",
+ "Bytea",
+ "Bytea",
+ "Int4",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "204c6de853bb2ceb8b7c13f42931800be4092c170c7825ca61e218957395f00f"
+}
diff --git a/.sqlx/query-22cbb960de6d19f3533b1d61a111b6aaa5db90dcde1d3deb845353d15b47b901.json b/.sqlx/query-22cbb960de6d19f3533b1d61a111b6aaa5db90dcde1d3deb845353d15b47b901.json
new file mode 100644
index 0000000000..c3c209e521
--- /dev/null
+++ b/.sqlx/query-22cbb960de6d19f3533b1d61a111b6aaa5db90dcde1d3deb845353d15b47b901.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n \"id\"\n FROM \"User\"\n WHERE \"email\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "22cbb960de6d19f3533b1d61a111b6aaa5db90dcde1d3deb845353d15b47b901"
+}
diff --git a/.sqlx/query-23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522.json b/.sqlx/query-23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522.json
new file mode 100644
index 0000000000..5d0ad6f28b
--- /dev/null
+++ b/.sqlx/query-23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)\n VALUES ($1, $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "23d9f97b2e79c6cb15fc6cf68e74c892f7e0d561597bd7aaac3b7cb8694a4522"
+}
diff --git a/.sqlx/query-2556c2cf7833c3f764cc6f34f482370e1e16f1024fe838445befdb0d4a9183ba.json b/.sqlx/query-2556c2cf7833c3f764cc6f34f482370e1e16f1024fe838445befdb0d4a9183ba.json
new file mode 100644
index 0000000000..6166cbdea1
--- /dev/null
+++ b/.sqlx/query-2556c2cf7833c3f764cc6f34f482370e1e16f1024fe838445befdb0d4a9183ba.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_entity_mentions (id, source_entity_type, source_entity_id, entity_type, entity_id, user_id) VALUES (gen_random_uuid(), 'message', $1, 'doc', 'doc1', NULL)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Varchar"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2556c2cf7833c3f764cc6f34f482370e1e16f1024fe838445befdb0d4a9183ba"
+}
diff --git a/.sqlx/query-2601beb7d46f7f44b9e2cd62f330c5e7420290d55b8c4b4a8178abbb41601004.json b/.sqlx/query-2601beb7d46f7f44b9e2cd62f330c5e7420290d55b8c4b4a8178abbb41601004.json
new file mode 100644
index 0000000000..a60124e95c
--- /dev/null
+++ b/.sqlx/query-2601beb7d46f7f44b9e2cd62f330c5e7420290d55b8c4b4a8178abbb41601004.json
@@ -0,0 +1,57 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, user_id, device_token, device_endpoint, device_type as \"device_type:DeviceType\" \n FROM notification_user_device_registration \n WHERE device_endpoint = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "device_token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "device_endpoint",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "device_type:DeviceType",
+ "type_info": {
+ "Custom": {
+ "name": "notification_device_type_option",
+ "kind": {
+ "Enum": [
+ "ios",
+ "android",
+ "iosvoip"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "2601beb7d46f7f44b9e2cd62f330c5e7420290d55b8c4b4a8178abbb41601004"
+}
diff --git a/.sqlx/query-26a76b5eae7dfe22e53a40628be0a61971f6ea27caaa65b5df176056d34511b4.json b/.sqlx/query-26a76b5eae7dfe22e53a40628be0a61971f6ea27caaa65b5df176056d34511b4.json
new file mode 100644
index 0000000000..72a589b448
--- /dev/null
+++ b/.sqlx/query-26a76b5eae7dfe22e53a40628be0a61971f6ea27caaa65b5df176056d34511b4.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) as \"count!\" FROM \"Document\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "26a76b5eae7dfe22e53a40628be0a61971f6ea27caaa65b5df176056d34511b4"
+}
diff --git a/.sqlx/query-2a09a8b0399791b5acd489c0ad6fccca6a98327a1f043f7ca79584ab0d5720c0.json b/.sqlx/query-2a09a8b0399791b5acd489c0ad6fccca6a98327a1f043f7ca79584ab0d5720c0.json
new file mode 100644
index 0000000000..1074453cba
--- /dev/null
+++ b/.sqlx/query-2a09a8b0399791b5acd489c0ad6fccca6a98327a1f043f7ca79584ab0d5720c0.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (user_id, team_id, team_role)\n VALUES ($1, $2, 'member')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2a09a8b0399791b5acd489c0ad6fccca6a98327a1f043f7ca79584ab0d5720c0"
+}
diff --git a/.sqlx/query-2ba299b337299a1ce837f0042c3a8cf15ddd312d287f1018b8fc63cd0f5ea58e.json b/.sqlx/query-2ba299b337299a1ce837f0042c3a8cf15ddd312d287f1018b8fc63cd0f5ea58e.json
new file mode 100644
index 0000000000..ef7714031e
--- /dev/null
+++ b/.sqlx/query-2ba299b337299a1ce837f0042c3a8cf15ddd312d287f1018b8fc63cd0f5ea58e.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT \"documentId\" as \"document_id\" FROM \"InstructionsDocuments\" WHERE \"userId\" = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2ba299b337299a1ce837f0042c3a8cf15ddd312d287f1018b8fc63cd0f5ea58e"
+}
diff --git a/.sqlx/query-2fb8b1569f5e00a5029edb9189d0eede64152e2f1f91251b1532066417f9561c.json b/.sqlx/query-2fb8b1569f5e00a5029edb9189d0eede64152e2f1f91251b1532066417f9561c.json
new file mode 100644
index 0000000000..d67ed35fbd
--- /dev/null
+++ b/.sqlx/query-2fb8b1569f5e00a5029edb9189d0eede64152e2f1f91251b1532066417f9561c.json
@@ -0,0 +1,68 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \n ha.uuid, ha.page, ha.red, ha.green, ha.blue, ha.alpha,\n ha.type as highlight_type, ha.text, ha.\"threadId\"\n FROM \"PdfHighlightAnchor\" ha\n WHERE ha.\"documentId\" = 'document-with-comments'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "page",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 2,
+ "name": "red",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "green",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 4,
+ "name": "blue",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 5,
+ "name": "alpha",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 6,
+ "name": "highlight_type",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 7,
+ "name": "text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "threadId",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "2fb8b1569f5e00a5029edb9189d0eede64152e2f1f91251b1532066417f9561c"
+}
diff --git a/.sqlx/query-3038cc3e5fa2c21d249c10dc5a67edf050acaab06dcf8ca6e239a613812fb8eb.json b/.sqlx/query-3038cc3e5fa2c21d249c10dc5a67edf050acaab06dcf8ca6e239a613812fb8eb.json
new file mode 100644
index 0000000000..cbc4d2795c
--- /dev/null
+++ b/.sqlx/query-3038cc3e5fa2c21d249c10dc5a67edf050acaab06dcf8ca6e239a613812fb8eb.json
@@ -0,0 +1,21 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO webhook (\n id, workspace_id, namespace, name, endpoint_url, signing_secret,\n filters, created_by_user_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3038cc3e5fa2c21d249c10dc5a67edf050acaab06dcf8ca6e239a613812fb8eb"
+}
diff --git a/.sqlx/query-31ed0496ad3add328514f2e8732b69611987753114d2342c404b3da4c9055d5a.json b/.sqlx/query-31ed0496ad3add328514f2e8732b69611987753114d2342c404b3da4c9055d5a.json
new file mode 100644
index 0000000000..4b0b9175ea
--- /dev/null
+++ b/.sqlx/query-31ed0496ad3add328514f2e8732b69611987753114d2342c404b3da4c9055d5a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"User\" (id, email, macro_user_id) VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "31ed0496ad3add328514f2e8732b69611987753114d2342c404b3da4c9055d5a"
+}
diff --git a/.sqlx/query-3490a86ba541f1847bb70c46ad3ed56e5dceb23c2ae6dcb5904d037e43d6f36d.json b/.sqlx/query-3490a86ba541f1847bb70c46ad3ed56e5dceb23c2ae6dcb5904d037e43d6f36d.json
new file mode 100644
index 0000000000..b97578ec55
--- /dev/null
+++ b/.sqlx/query-3490a86ba541f1847bb70c46ad3ed56e5dceb23c2ae6dcb5904d037e43d6f36d.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"BlockedEmail\" (email)\n VALUES ('[email protected]')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "3490a86ba541f1847bb70c46ad3ed56e5dceb23c2ae6dcb5904d037e43d6f36d"
+}
diff --git a/.sqlx/query-39b7438988b5c9004055e16ecee679cc680f336685a776264832762dd2bdf6b4.json b/.sqlx/query-39b7438988b5c9004055e16ecee679cc680f336685a776264832762dd2bdf6b4.json
new file mode 100644
index 0000000000..1f4bc3c4a1
--- /dev/null
+++ b/.sqlx/query-39b7438988b5c9004055e16ecee679cc680f336685a776264832762dd2bdf6b4.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT name, \"fileType\" as \"file_type\", owner FROM \"Document\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "file_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "owner",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "39b7438988b5c9004055e16ecee679cc680f336685a776264832762dd2bdf6b4"
+}
diff --git a/.sqlx/query-3ac2cf269852e3147ca2f9f28c8087393f8e66e5056f5c49ef23005adb7f2b88.json b/.sqlx/query-3ac2cf269852e3147ca2f9f28c8087393f8e66e5056f5c49ef23005adb7f2b88.json
new file mode 100644
index 0000000000..4bc6bcd9b2
--- /dev/null
+++ b/.sqlx/query-3ac2cf269852e3147ca2f9f28c8087393f8e66e5056f5c49ef23005adb7f2b88.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"User\" (id, email, macro_user_id) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3ac2cf269852e3147ca2f9f28c8087393f8e66e5056f5c49ef23005adb7f2b88"
+}
diff --git a/.sqlx/query-3d1f314799b67cda36d303512abac16d099e398c3ea4581bdb95600a8dc409a2.json b/.sqlx/query-3d1f314799b67cda36d303512abac16d099e398c3ea4581bdb95600a8dc409a2.json
new file mode 100644
index 0000000000..8b9f0c6f68
--- /dev/null
+++ b/.sqlx/query-3d1f314799b67cda36d303512abac16d099e398c3ea4581bdb95600a8dc409a2.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) as \"count!\" FROM \"InstructionsDocuments\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "3d1f314799b67cda36d303512abac16d099e398c3ea4581bdb95600a8dc409a2"
+}
diff --git a/.sqlx/query-3d29e2ee55cab12719d0940b5d212b1855790f41bba1d92419ab49a15458566c.json b/.sqlx/query-3d29e2ee55cab12719d0940b5d212b1855790f41bba1d92419ab49a15458566c.json
new file mode 100644
index 0000000000..1261681752
--- /dev/null
+++ b/.sqlx/query-3d29e2ee55cab12719d0940b5d212b1855790f41bba1d92419ab49a15458566c.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.status,\n d.next_attempt_at,\n a.status AS attempt_status,\n a.completed_at,\n w.last_failure_at\n FROM webhook_delivery d\n JOIN webhook_delivery_attempt a ON a.webhook_delivery_id = d.id\n JOIN webhook w ON w.id = d.webhook_id\n WHERE d.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "next_attempt_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "attempt_status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "last_failure_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "3d29e2ee55cab12719d0940b5d212b1855790f41bba1d92419ab49a15458566c"
+}
diff --git a/.sqlx/query-406c70b57542e83e2be08e369d59fe361004eeec74353501ebcf39496d056b2a.json b/.sqlx/query-406c70b57542e83e2be08e369d59fe361004eeec74353501ebcf39496d056b2a.json
new file mode 100644
index 0000000000..28513a6e30
--- /dev/null
+++ b/.sqlx/query-406c70b57542e83e2be08e369d59fe361004eeec74353501ebcf39496d056b2a.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \n channel_id, \n access_level::text as \"access_level!\"\n FROM \"ChannelSharePermission\"\n WHERE \"share_permission_id\" = 'sp-p1'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "access_level!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "406c70b57542e83e2be08e369d59fe361004eeec74353501ebcf39496d056b2a"
+}
diff --git a/.sqlx/query-409e5f09ab3126ed9c799e4764d868e7ef5f099a49f3b792ddaedd57c34e14e6.json b/.sqlx/query-409e5f09ab3126ed9c799e4764d868e7ef5f099a49f3b792ddaedd57c34e14e6.json
new file mode 100644
index 0000000000..721204ee50
--- /dev/null
+++ b/.sqlx/query-409e5f09ab3126ed9c799e4764d868e7ef5f099a49f3b792ddaedd57c34e14e6.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"DocumentBom\" (\"documentId\") VALUES ($1) RETURNING id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "409e5f09ab3126ed9c799e4764d868e7ef5f099a49f3b792ddaedd57c34e14e6"
+}
diff --git a/.sqlx/query-41773e640798f98e03056f516a5df7e7ef225f967b477197924296d0a5f49c13.json b/.sqlx/query-41773e640798f98e03056f516a5df7e7ef225f967b477197924296d0a5f49c13.json
new file mode 100644
index 0000000000..e6aeb7771d
--- /dev/null
+++ b/.sqlx/query-41773e640798f98e03056f516a5df7e7ef225f967b477197924296d0a5f49c13.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, \"sha\", \"path\" FROM \"BomPart\"\n WHERE \"documentBomId\" = $1;\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "path",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "41773e640798f98e03056f516a5df7e7ef225f967b477197924296d0a5f49c13"
+}
diff --git a/.sqlx/query-43f8d11343322110949319887587bb6379e6347e180608651ac13a9574f1fb25.json b/.sqlx/query-43f8d11343322110949319887587bb6379e6347e180608651ac13a9574f1fb25.json
new file mode 100644
index 0000000000..ca08c25ef4
--- /dev/null
+++ b/.sqlx/query-43f8d11343322110949319887587bb6379e6347e180608651ac13a9574f1fb25.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO frecency_aggregates (\n entity_id, entity_type, user_id, event_count,\n frecency_score, first_event, recent_events\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Int4",
+ "Float8",
+ "Timestamptz",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "43f8d11343322110949319887587bb6379e6347e180608651ac13a9574f1fb25"
+}
diff --git a/.sqlx/query-498045cd57984700efe9304512e2619d629cec7f4df96a8424165984b4ff3d6a.json b/.sqlx/query-498045cd57984700efe9304512e2619d629cec7f4df96a8424165984b4ff3d6a.json
new file mode 100644
index 0000000000..c997f341a7
--- /dev/null
+++ b/.sqlx/query-498045cd57984700efe9304512e2619d629cec7f4df96a8424165984b4ff3d6a.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT (1) as exists\n FROM \"ThreadAnchor\"\n WHERE \"anchorId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "498045cd57984700efe9304512e2619d629cec7f4df96a8424165984b4ff3d6a"
+}
diff --git a/.sqlx/query-4b68bd9e023bf62f14bf8848f9f2d94fa59e692d412219a7e9edaec5f394cba3.json b/.sqlx/query-4b68bd9e023bf62f14bf8848f9f2d94fa59e692d412219a7e9edaec5f394cba3.json
new file mode 100644
index 0000000000..9fcddbaf9f
--- /dev/null
+++ b/.sqlx/query-4b68bd9e023bf62f14bf8848f9f2d94fa59e692d412219a7e9edaec5f394cba3.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM webhook_delivery_attempt WHERE webhook_delivery_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4b68bd9e023bf62f14bf8848f9f2d94fa59e692d412219a7e9edaec5f394cba3"
+}
diff --git a/.sqlx/query-4c54bcf9277edde8c40c993bde999e25c425d6f632af80043ad012bf29607629.json b/.sqlx/query-4c54bcf9277edde8c40c993bde999e25c425d6f632af80043ad012bf29607629.json
new file mode 100644
index 0000000000..a454b049e9
--- /dev/null
+++ b/.sqlx/query-4c54bcf9277edde8c40c993bde999e25c425d6f632af80043ad012bf29607629.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT values as \"values: serde_json::Value\"\n FROM entity_properties\n WHERE entity_id = $1 AND entity_type = 'DOCUMENT' AND property_definition_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "values: serde_json::Value",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "4c54bcf9277edde8c40c993bde999e25c425d6f632af80043ad012bf29607629"
+}
diff --git a/.sqlx/query-4cc8e9f875c58a30df475c97230a3621f63ab0d1c5551d9f88a4886d37df928a.json b/.sqlx/query-4cc8e9f875c58a30df475c97230a3621f63ab0d1c5551d9f88a4886d37df928a.json
new file mode 100644
index 0000000000..f3bc336012
--- /dev/null
+++ b/.sqlx/query-4cc8e9f875c58a30df475c97230a3621f63ab0d1c5551d9f88a4886d37df928a.json
@@ -0,0 +1,37 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH previous AS (\n SELECT patch_blob_key FROM agent_session_changes WHERE agent_session_id = $1\n )\n INSERT INTO agent_session_changes (\n agent_session_id, changeset_id, source, repository,\n base_ref, base_sha, head_ref, head_sha,\n files, additions, deletions, patch_blob_key, patch_bytes, truncated,\n captured_at, attempt_started_at, attempt_finished_at, attempt_outcome, attempt_error\n )\n VALUES (\n $1, $2, $3, $4,\n $5, $6, $7, $8,\n $9, $10, $11, $12, $13, $14,\n $15, $16, $16, 'captured', NULL\n )\n ON CONFLICT (agent_session_id) DO UPDATE SET\n changeset_id = EXCLUDED.changeset_id,\n source = EXCLUDED.source,\n repository = EXCLUDED.repository,\n base_ref = EXCLUDED.base_ref,\n base_sha = EXCLUDED.base_sha,\n head_ref = EXCLUDED.head_ref,\n head_sha = EXCLUDED.head_sha,\n files = EXCLUDED.files,\n additions = EXCLUDED.additions,\n deletions = EXCLUDED.deletions,\n patch_blob_key = EXCLUDED.patch_blob_key,\n patch_bytes = EXCLUDED.patch_bytes,\n truncated = EXCLUDED.truncated,\n captured_at = EXCLUDED.captured_at,\n attempt_finished_at = EXCLUDED.attempt_finished_at,\n attempt_outcome = 'captured',\n attempt_error = NULL,\n updated_at = now()\n RETURNING (SELECT patch_blob_key FROM previous) AS \"superseded?\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "superseded?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Int4",
+ "Int4",
+ "Text",
+ "Int8",
+ "Bool",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4cc8e9f875c58a30df475c97230a3621f63ab0d1c5551d9f88a4886d37df928a"
+}
diff --git a/.sqlx/query-4d90616f23512f6162c8a89b98b49224dd1e73823c74fe56eddfa4c761154982.json b/.sqlx/query-4d90616f23512f6162c8a89b98b49224dd1e73823c74fe56eddfa4c761154982.json
new file mode 100644
index 0000000000..70663f60ef
--- /dev/null
+++ b/.sqlx/query-4d90616f23512f6162c8a89b98b49224dd1e73823c74fe56eddfa4c761154982.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"createdAt\", \"updatedAt\" FROM \"Pin\" WHERE \"userId\" = $1 AND \"pinnedItemId\" = $2 and \"pinnedItemType\" = $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "createdAt",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 1,
+ "name": "updatedAt",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "4d90616f23512f6162c8a89b98b49224dd1e73823c74fe56eddfa4c761154982"
+}
diff --git a/.sqlx/query-4e2894aae898f12e69659f42fadb83c5594fc79a6da0cd357d9cd0a5133bdbf5.json b/.sqlx/query-4e2894aae898f12e69659f42fadb83c5594fc79a6da0cd357d9cd0a5133bdbf5.json
new file mode 100644
index 0000000000..1cb334cf80
--- /dev/null
+++ b/.sqlx/query-4e2894aae898f12e69659f42fadb83c5594fc79a6da0cd357d9cd0a5133bdbf5.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE call_records SET summary = $2 WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4e2894aae898f12e69659f42fadb83c5594fc79a6da0cd357d9cd0a5133bdbf5"
+}
diff --git a/.sqlx/query-4f6bc69f25cfeed8d5a9189ae95c0cb64117fd6672d92fd47369019b5e9638bb.json b/.sqlx/query-4f6bc69f25cfeed8d5a9189ae95c0cb64117fd6672d92fd47369019b5e9638bb.json
new file mode 100644
index 0000000000..20953c9ff4
--- /dev/null
+++ b/.sqlx/query-4f6bc69f25cfeed8d5a9189ae95c0cb64117fd6672d92fd47369019b5e9638bb.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"deletedAt\" FROM \"Thread\"\n WHERE id = 1001\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deletedAt",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "4f6bc69f25cfeed8d5a9189ae95c0cb64117fd6672d92fd47369019b5e9638bb"
+}
diff --git a/.sqlx/query-5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee.json b/.sqlx/query-5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee.json
new file mode 100644
index 0000000000..43c54438a5
--- /dev/null
+++ b/.sqlx/query-5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO calendar_accounts (\n id, owner_id, email_link_id, provider, provider_account_id\n )\n VALUES ($1, $2, $3, 'google', $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5244b960cd63a70408aef8ba2b4bc5a8c78819f16c5ff4dbd9dcc5525d3da5ee"
+}
diff --git a/.sqlx/query-530c0fb037a3cbe47247b1ead4652072630923c20f1b7579c57c212845216836.json b/.sqlx/query-530c0fb037a3cbe47247b1ead4652072630923c20f1b7579c57c212845216836.json
new file mode 100644
index 0000000000..acbd1fd347
--- /dev/null
+++ b/.sqlx/query-530c0fb037a3cbe47247b1ead4652072630923c20f1b7579c57c212845216836.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"Project\" (\"id\", \"name\", \"userId\", \"deletedAt\")\n VALUES ('p1', 'd', 'macro|[email protected]', '2019-10-16 00:00:00')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "530c0fb037a3cbe47247b1ead4652072630923c20f1b7579c57c212845216836"
+}
diff --git a/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json b/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json
new file mode 100644
index 0000000000..1b6e64017a
--- /dev/null
+++ b/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"UserApiKey\" (id, name, user_id, hash)\n VALUES ($1, $2, $3, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Bytea"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255"
+}
diff --git a/.sqlx/query-5404d007fe2d2b712c0ea9d037dbb7fb6a3887246f99d2de01eaa6e279d9fd43.json b/.sqlx/query-5404d007fe2d2b712c0ea9d037dbb7fb6a3887246f99d2de01eaa6e279d9fd43.json
new file mode 100644
index 0000000000..4d9369017b
--- /dev/null
+++ b/.sqlx/query-5404d007fe2d2b712c0ea9d037dbb7fb6a3887246f99d2de01eaa6e279d9fd43.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"Document\" (id, name, owner)\n VALUES ($1, $2, 'macro|[email protected]')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5404d007fe2d2b712c0ea9d037dbb7fb6a3887246f99d2de01eaa6e279d9fd43"
+}
diff --git a/.sqlx/query-54ba620d9d2e75a6cff4e824c769db16182a94cc30e5d69a9fc481a13dd08c49.json b/.sqlx/query-54ba620d9d2e75a6cff4e824c769db16182a94cc30e5d69a9fc481a13dd08c49.json
new file mode 100644
index 0000000000..828e110c77
--- /dev/null
+++ b/.sqlx/query-54ba620d9d2e75a6cff4e824c769db16182a94cc30e5d69a9fc481a13dd08c49.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)\n VALUES ($1, $2, 'member'::comms_participant_role, NULL)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "54ba620d9d2e75a6cff4e824c769db16182a94cc30e5d69a9fc481a13dd08c49"
+}
diff --git a/.sqlx/query-56cc24dab392220f41df911649f223d6b2793030ab7d1e3e300b815f1f8b0bd2.json b/.sqlx/query-56cc24dab392220f41df911649f223d6b2793030ab7d1e3e300b815f1f8b0bd2.json
new file mode 100644
index 0000000000..ddae577b81
--- /dev/null
+++ b/.sqlx/query-56cc24dab392220f41df911649f223d6b2793030ab7d1e3e300b815f1f8b0bd2.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT last_accessed FROM \"ItemLastAccessed\" WHERE item_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "last_accessed",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "56cc24dab392220f41df911649f223d6b2793030ab7d1e3e300b815f1f8b0bd2"
+}
diff --git a/.sqlx/query-599df539d2889d66508a84946336b400f8380a83bb912a0e65371fc5ea5ab26a.json b/.sqlx/query-599df539d2889d66508a84946336b400f8380a83bb912a0e65371fc5ea5ab26a.json
new file mode 100644
index 0000000000..5b0a087800
--- /dev/null
+++ b/.sqlx/query-599df539d2889d66508a84946336b400f8380a83bb912a0e65371fc5ea5ab26a.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO agent_session_changes (\n agent_session_id, attempt_started_at, attempt_finished_at, attempt_outcome, attempt_error\n )\n VALUES ($1, $4, $4, $2, $3)\n ON CONFLICT (agent_session_id) DO UPDATE SET\n attempt_finished_at = EXCLUDED.attempt_finished_at,\n attempt_outcome = EXCLUDED.attempt_outcome,\n attempt_error = EXCLUDED.attempt_error,\n updated_at = now()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "599df539d2889d66508a84946336b400f8380a83bb912a0e65371fc5ea5ab26a"
+}
diff --git a/.sqlx/query-5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e.json b/.sqlx/query-5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e.json
new file mode 100644
index 0000000000..443cd1a93f
--- /dev/null
+++ b/.sqlx/query-5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM email_links WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5b45457b0629b66ab1694e99d7ef5119f136035f6b8489934c845c7321eade6e"
+}
diff --git a/.sqlx/query-5bf079123e6ce402809dd9659eda17854525d30a39bb92c7c9b2a2fe315e947f.json b/.sqlx/query-5bf079123e6ce402809dd9659eda17854525d30a39bb92c7c9b2a2fe315e947f.json
new file mode 100644
index 0000000000..9007aa1bab
--- /dev/null
+++ b/.sqlx/query-5bf079123e6ce402809dd9659eda17854525d30a39bb92c7c9b2a2fe315e947f.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n \"documentId\" as \"document_id\",\n \"content\" as \"content\",\n \"tokenCount\" as \"token_count\"\n FROM \"DocumentText\"\n WHERE \"documentId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "token_count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "5bf079123e6ce402809dd9659eda17854525d30a39bb92c7c9b2a2fe315e947f"
+}
diff --git a/.sqlx/query-5c6b90097e9d8079a185a6b481201628eba37b86c378363299474e6774b9edd4.json b/.sqlx/query-5c6b90097e9d8079a185a6b481201628eba37b86c378363299474e6774b9edd4.json
new file mode 100644
index 0000000000..f5948d3b96
--- /dev/null
+++ b/.sqlx/query-5c6b90097e9d8079a185a6b481201628eba37b86c378363299474e6774b9edd4.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"Document\"\n SET \"deletedAt\" = NOW()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5c6b90097e9d8079a185a6b481201628eba37b86c378363299474e6774b9edd4"
+}
diff --git a/.sqlx/query-5f8417de25d85852d915bf9111b6bd1e4c0f2bb3f3ac205e8428b4ee504d24da.json b/.sqlx/query-5f8417de25d85852d915bf9111b6bd1e4c0f2bb3f3ac205e8428b4ee504d24da.json
new file mode 100644
index 0000000000..f7724686fa
--- /dev/null
+++ b/.sqlx/query-5f8417de25d85852d915bf9111b6bd1e4c0f2bb3f3ac205e8428b4ee504d24da.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT first_name, last_name FROM macro_user_info WHERE macro_user_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "first_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "last_name",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "5f8417de25d85852d915bf9111b6bd1e4c0f2bb3f3ac205e8428b4ee504d24da"
+}
diff --git a/.sqlx/query-63da48ff0a9e0b8704d8964d7cecabf075a58597fee1c6e46f5091adcd1aa257.json b/.sqlx/query-63da48ff0a9e0b8704d8964d7cecabf075a58597fee1c6e46f5091adcd1aa257.json
new file mode 100644
index 0000000000..f6162c9b2e
--- /dev/null
+++ b/.sqlx/query-63da48ff0a9e0b8704d8964d7cecabf075a58597fee1c6e46f5091adcd1aa257.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE harnesses SET deleted_at = now()",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "63da48ff0a9e0b8704d8964d7cecabf075a58597fee1c6e46f5091adcd1aa257"
+}
diff --git a/.sqlx/query-6495146fc7e78a00ea9599f800d59f7e0f4f94b67031420f701712bbeebbf4a0.json b/.sqlx/query-6495146fc7e78a00ea9599f800d59f7e0f4f94b67031420f701712bbeebbf4a0.json
new file mode 100644
index 0000000000..edeeae7624
--- /dev/null
+++ b/.sqlx/query-6495146fc7e78a00ea9599f800d59f7e0f4f94b67031420f701712bbeebbf4a0.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"createdAt\" as created_at, \"updatedAt\" as updated_at FROM \"UserHistory\" WHERE \"userId\" = $1 AND \"itemId\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_at",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "6495146fc7e78a00ea9599f800d59f7e0f4f94b67031420f701712bbeebbf4a0"
+}
diff --git a/.sqlx/query-64e6a529200262f372307a69d2519d6b233260545e5bc3b0061855e89081e990.json b/.sqlx/query-64e6a529200262f372307a69d2519d6b233260545e5bc3b0061855e89081e990.json
new file mode 100644
index 0000000000..9967f7c84b
--- /dev/null
+++ b/.sqlx/query-64e6a529200262f372307a69d2519d6b233260545e5bc3b0061855e89081e990.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO macro_user (id, username, email, stripe_customer_id)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "64e6a529200262f372307a69d2519d6b233260545e5bc3b0061855e89081e990"
+}
diff --git a/.sqlx/query-659bebbcf15938148caa9f03f65239736f0af5de54395445c605555f02c66692.json b/.sqlx/query-659bebbcf15938148caa9f03f65239736f0af5de54395445c605555f02c66692.json
new file mode 100644
index 0000000000..df9230e7f6
--- /dev/null
+++ b/.sqlx/query-659bebbcf15938148caa9f03f65239736f0af5de54395445c605555f02c66692.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COUNT(*) as count FROM \"Comment\"\n WHERE \"threadId\" = 1001 AND \"deletedAt\" IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "659bebbcf15938148caa9f03f65239736f0af5de54395445c605555f02c66692"
+}
diff --git a/.sqlx/query-67809c28827bd163e23a02284f0e90f4649aa8d50d5fb4d088e01cfd25b59738.json b/.sqlx/query-67809c28827bd163e23a02284f0e90f4649aa8d50d5fb4d088e01cfd25b59738.json
new file mode 100644
index 0000000000..42dc2bb6f2
--- /dev/null
+++ b/.sqlx/query-67809c28827bd163e23a02284f0e90f4649aa8d50d5fb4d088e01cfd25b59738.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT m.entity_id, m.entity_type\n FROM comms_entity_mentions m\n WHERE m.source_entity_type = 'message' AND m.source_entity_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_id",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_type",
+ "type_info": "Varchar"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "67809c28827bd163e23a02284f0e90f4649aa8d50d5fb4d088e01cfd25b59738"
+}
diff --git a/.sqlx/query-67c59263594eeadbfd225f2d4134443f9a9044209ec08de331bfb4afbde371ee.json b/.sqlx/query-67c59263594eeadbfd225f2d4134443f9a9044209ec08de331bfb4afbde371ee.json
new file mode 100644
index 0000000000..84e969f239
--- /dev/null
+++ b/.sqlx/query-67c59263594eeadbfd225f2d4134443f9a9044209ec08de331bfb4afbde371ee.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO team_user (user_id, team_id, team_role)\n VALUES\n ('user-1', 'dddddddd-dddd-dddd-dddd-000000000001', 'owner'),\n ('user-3', 'dddddddd-dddd-dddd-dddd-000000000001', 'member'),\n ('user-2', 'dddddddd-dddd-dddd-dddd-000000000002', 'owner'),\n ('user-public-access-only', 'dddddddd-dddd-dddd-dddd-000000000002', 'member')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "67c59263594eeadbfd225f2d4134443f9a9044209ec08de331bfb4afbde371ee"
+}
diff --git a/.sqlx/query-68a503269b2fe1df96fc697738ae8fbc1007a335d1c96b4614287a72f194a1fd.json b/.sqlx/query-68a503269b2fe1df96fc697738ae8fbc1007a335d1c96b4614287a72f194a1fd.json
new file mode 100644
index 0000000000..910c07db22
--- /dev/null
+++ b/.sqlx/query-68a503269b2fe1df96fc697738ae8fbc1007a335d1c96b4614287a72f194a1fd.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)\n VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "68a503269b2fe1df96fc697738ae8fbc1007a335d1c96b4614287a72f194a1fd"
+}
diff --git a/.sqlx/query-692980d5dad75638ccfdec21b7d319914b45acb3eb3923f8e2d427d1ea0cbb7f.json b/.sqlx/query-692980d5dad75638ccfdec21b7d319914b45acb3eb3923f8e2d427d1ea0cbb7f.json
new file mode 100644
index 0000000000..edc21badfe
--- /dev/null
+++ b/.sqlx/query-692980d5dad75638ccfdec21b7d319914b45acb3eb3923f8e2d427d1ea0cbb7f.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user (id, username, email, stripe_customer_id)\n VALUES ($1, $2, $3, $4)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "692980d5dad75638ccfdec21b7d319914b45acb3eb3923f8e2d427d1ea0cbb7f"
+}
diff --git a/.sqlx/query-6a5e78ae2a24b1c443a38d9ecc41184b8cd192359c2aabcd8b4e2f8375ac493f.json b/.sqlx/query-6a5e78ae2a24b1c443a38d9ecc41184b8cd192359c2aabcd8b4e2f8375ac493f.json
new file mode 100644
index 0000000000..a599a60781
--- /dev/null
+++ b/.sqlx/query-6a5e78ae2a24b1c443a38d9ecc41184b8cd192359c2aabcd8b4e2f8375ac493f.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT values as \"values!: serde_json::Value\"\n FROM entity_properties\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "values!: serde_json::Value",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD",
+ "CALENDAR_EVENT"
+ ]
+ }
+ }
+ },
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "6a5e78ae2a24b1c443a38d9ecc41184b8cd192359c2aabcd8b4e2f8375ac493f"
+}
diff --git a/.sqlx/query-6c1fa70775136bab3e911de94d21e2e153a080065475f0eb056e0fffb3c188a2.json b/.sqlx/query-6c1fa70775136bab3e911de94d21e2e153a080065475f0eb056e0fffb3c188a2.json
new file mode 100644
index 0000000000..5616c68fb5
--- /dev/null
+++ b/.sqlx/query-6c1fa70775136bab3e911de94d21e2e153a080065475f0eb056e0fffb3c188a2.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO macro_user (id, stripe_customer_id, username, email) VALUES ($1, 'bogus', 'username', 'bogus')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6c1fa70775136bab3e911de94d21e2e153a080065475f0eb056e0fffb3c188a2"
+}
diff --git a/.sqlx/query-6de05cde9a5cffbadd9bead5c5598f418d441eff7740591d4be5a77cbba699d1.json b/.sqlx/query-6de05cde9a5cffbadd9bead5c5598f418d441eff7740591d4be5a77cbba699d1.json
new file mode 100644
index 0000000000..6c655cf0af
--- /dev/null
+++ b/.sqlx/query-6de05cde9a5cffbadd9bead5c5598f418d441eff7740591d4be5a77cbba699d1.json
@@ -0,0 +1,44 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT pa.\"threadId\", pa.uuid, pa.page, pa.\"originalPage\", pa.\"originalIndex\"\n FROM \"PdfPlaceableCommentAnchor\" pa\n JOIN \"Thread\" t ON pa.\"threadId\" = t.id\n WHERE t.\"documentId\" = 'document-with-comments'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "threadId",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "page",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "originalPage",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 4,
+ "name": "originalIndex",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "6de05cde9a5cffbadd9bead5c5598f418d441eff7740591d4be5a77cbba699d1"
+}
diff --git a/.sqlx/query-70fd335b1cc501c338da576cff3f572d57395ee6a80ee5e4429598f701ac407b.json b/.sqlx/query-70fd335b1cc501c338da576cff3f572d57395ee6a80ee5e4429598f701ac407b.json
new file mode 100644
index 0000000000..9312e25478
--- /dev/null
+++ b/.sqlx/query-70fd335b1cc501c338da576cff3f572d57395ee6a80ee5e4429598f701ac407b.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM \"DocumentInstance\" WHERE \"documentId\" = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "70fd335b1cc501c338da576cff3f572d57395ee6a80ee5e4429598f701ac407b"
+}
diff --git a/.sqlx/query-71c5ff27eb1944132a86b81e2964dddac097803db77a4ae9d28fd1fb1a7fc71a.json b/.sqlx/query-71c5ff27eb1944132a86b81e2964dddac097803db77a4ae9d28fd1fb1a7fc71a.json
new file mode 100644
index 0000000000..fd4f407316
--- /dev/null
+++ b/.sqlx/query-71c5ff27eb1944132a86b81e2964dddac097803db77a4ae9d28fd1fb1a7fc71a.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"createdAt\" as created_at, \"updatedAt\" as updated_at\n FROM \"UserHistory\"\n WHERE \"userId\" = $1 AND \"itemId\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_at",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "71c5ff27eb1944132a86b81e2964dddac097803db77a4ae9d28fd1fb1a7fc71a"
+}
diff --git a/.sqlx/query-72c2ed48dc5d85817736b825130c1f1e0a4de0aee2b5a48ba27a18389c393260.json b/.sqlx/query-72c2ed48dc5d85817736b825130c1f1e0a4de0aee2b5a48ba27a18389c393260.json
new file mode 100644
index 0000000000..177cd9e6ae
--- /dev/null
+++ b/.sqlx/query-72c2ed48dc5d85817736b825130c1f1e0a4de0aee2b5a48ba27a18389c393260.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n c.id\n FROM\n \"Chat\" c\n WHERE\n c.\"userId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "72c2ed48dc5d85817736b825130c1f1e0a4de0aee2b5a48ba27a18389c393260"
+}
diff --git a/.sqlx/query-7309f0457ffb25a6b31704ed43c8cd72a5f55d1e09c6fce5bb7bd5c7a69eaa22.json b/.sqlx/query-7309f0457ffb25a6b31704ed43c8cd72a5f55d1e09c6fce5bb7bd5c7a69eaa22.json
new file mode 100644
index 0000000000..904ee7ade6
--- /dev/null
+++ b/.sqlx/query-7309f0457ffb25a6b31704ed43c8cd72a5f55d1e09c6fce5bb7bd5c7a69eaa22.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"PdfPlaceableCommentAnchor\"\n SET \"wasDeleted\" = TRUE\n WHERE \"uuid\" = '91111111-1111-1111-1111-111111111111'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "7309f0457ffb25a6b31704ed43c8cd72a5f55d1e09c6fce5bb7bd5c7a69eaa22"
+}
diff --git a/.sqlx/query-740e15829bf180a5550efd55337e753f8e3b94e5c66178e084e096d3a4fe2b92.json b/.sqlx/query-740e15829bf180a5550efd55337e753f8e3b94e5c66178e084e096d3a4fe2b92.json
new file mode 100644
index 0000000000..69e6d1be8e
--- /dev/null
+++ b/.sqlx/query-740e15829bf180a5550efd55337e753f8e3b94e5c66178e084e096d3a4fe2b92.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT t.id, t.resolved, t.\"documentId\"\n FROM \"Thread\" t\n WHERE t.\"documentId\" = 'document-with-comments'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "resolved",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "documentId",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "740e15829bf180a5550efd55337e753f8e3b94e5c66178e084e096d3a4fe2b92"
+}
diff --git a/.sqlx/query-74e5932e2f1a971bbe2a60749dd96f9a68d19a6f5e7afe4f15803d3f23a5d1fe.json b/.sqlx/query-74e5932e2f1a971bbe2a60749dd96f9a68d19a6f5e7afe4f15803d3f23a5d1fe.json
new file mode 100644
index 0000000000..7da698713c
--- /dev/null
+++ b/.sqlx/query-74e5932e2f1a971bbe2a60749dd96f9a68d19a6f5e7afe4f15803d3f23a5d1fe.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"deletedAt\" FROM \"Thread\"\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deletedAt",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "74e5932e2f1a971bbe2a60749dd96f9a68d19a6f5e7afe4f15803d3f23a5d1fe"
+}
diff --git a/.sqlx/query-75b5be3dd7cb58382235b5b6a6efd05128ee36a118dfb2c95a4fa3cbccc0543d.json b/.sqlx/query-75b5be3dd7cb58382235b5b6a6efd05128ee36a118dfb2c95a4fa3cbccc0543d.json
new file mode 100644
index 0000000000..a806f5dcc5
--- /dev/null
+++ b/.sqlx/query-75b5be3dd7cb58382235b5b6a6efd05128ee36a118dfb2c95a4fa3cbccc0543d.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"itemId\" as item_id FROM \"UserHistory\" WHERE \"userId\" = $1 AND \"itemId\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "item_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "75b5be3dd7cb58382235b5b6a6efd05128ee36a118dfb2c95a4fa3cbccc0543d"
+}
diff --git a/.sqlx/query-7a1b46ab8909534cab7572ba5c031df2cb4a9a35c882f112fc79ce4429b5aa13.json b/.sqlx/query-7a1b46ab8909534cab7572ba5c031df2cb4a9a35c882f112fc79ce4429b5aa13.json
new file mode 100644
index 0000000000..b9feade6b2
--- /dev/null
+++ b/.sqlx/query-7a1b46ab8909534cab7572ba5c031df2cb4a9a35c882f112fc79ce4429b5aa13.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT email FROM notification_email_unsubscribe WHERE email = 'a'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "7a1b46ab8909534cab7572ba5c031df2cb4a9a35c882f112fc79ce4429b5aa13"
+}
diff --git a/.sqlx/query-7b9ab815fcc51927f17f3fa838a0a13ebcc05049fe61d74eda708f22172b0ac7.json b/.sqlx/query-7b9ab815fcc51927f17f3fa838a0a13ebcc05049fe61d74eda708f22172b0ac7.json
new file mode 100644
index 0000000000..51d69aa8bf
--- /dev/null
+++ b/.sqlx/query-7b9ab815fcc51927f17f3fa838a0a13ebcc05049fe61d74eda708f22172b0ac7.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT uploaded, \"contentState\", \"contentLocation\"\n FROM \"Document\"\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "uploaded",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "contentState",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "contentLocation",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "7b9ab815fcc51927f17f3fa838a0a13ebcc05049fe61d74eda708f22172b0ac7"
+}
diff --git a/.sqlx/query-7cd8404cd175b06f3a86492d2ce09d38912394428377ae29149586cba067c6af.json b/.sqlx/query-7cd8404cd175b06f3a86492d2ce09d38912394428377ae29149586cba067c6af.json
new file mode 100644
index 0000000000..6145c5a09d
--- /dev/null
+++ b/.sqlx/query-7cd8404cd175b06f3a86492d2ce09d38912394428377ae29149586cba067c6af.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO document_sub_type (document_id, sub_type)\n VALUES ($1, 'task'), ($2, 'snippet')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7cd8404cd175b06f3a86492d2ce09d38912394428377ae29149586cba067c6af"
+}
diff --git a/.sqlx/query-7e7a4d40b0d7008dcff499ce33bf78da6f46946f61a20006fd0b05d181d083e5.json b/.sqlx/query-7e7a4d40b0d7008dcff499ce33bf78da6f46946f61a20006fd0b05d181d083e5.json
new file mode 100644
index 0000000000..e5597bc5b2
--- /dev/null
+++ b/.sqlx/query-7e7a4d40b0d7008dcff499ce33bf78da6f46946f61a20006fd0b05d181d083e5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) as \"count!\" FROM property_options WHERE property_definition_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "7e7a4d40b0d7008dcff499ce33bf78da6f46946f61a20006fd0b05d181d083e5"
+}
diff --git a/.sqlx/query-8060554f4ebb4875e06e40ad1bd4777c4d8069e54d785b91a5ef710e33aa5ad3.json b/.sqlx/query-8060554f4ebb4875e06e40ad1bd4777c4d8069e54d785b91a5ef710e33aa5ad3.json
new file mode 100644
index 0000000000..3512af53dd
--- /dev/null
+++ b/.sqlx/query-8060554f4ebb4875e06e40ad1bd4777c4d8069e54d785b91a5ef710e33aa5ad3.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT (1) as exists\n FROM \"ThreadAnchor\"\n WHERE \"threadId\" = $1 AND \"anchorId\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "8060554f4ebb4875e06e40ad1bd4777c4d8069e54d785b91a5ef710e33aa5ad3"
+}
diff --git a/.sqlx/query-809a1435a81112b0569446f0e938aaae2504e5609f31840e263d4c0849a9333d.json b/.sqlx/query-809a1435a81112b0569446f0e938aaae2504e5609f31840e263d4c0849a9333d.json
new file mode 100644
index 0000000000..8697e5c56a
--- /dev/null
+++ b/.sqlx/query-809a1435a81112b0569446f0e938aaae2504e5609f31840e263d4c0849a9333d.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT patch_blob_key FROM agent_session_changes WHERE agent_session_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "patch_blob_key",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "809a1435a81112b0569446f0e938aaae2504e5609f31840e263d4c0849a9333d"
+}
diff --git a/.sqlx/query-831ea954f15db76b05365d7f49ab47b32249f716aa8c14c1b53bbb30ccfd7547.json b/.sqlx/query-831ea954f15db76b05365d7f49ab47b32249f716aa8c14c1b53bbb30ccfd7547.json
new file mode 100644
index 0000000000..b21c2061f1
--- /dev/null
+++ b/.sqlx/query-831ea954f15db76b05365d7f49ab47b32249f716aa8c14c1b53bbb30ccfd7547.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE webhook SET deleted_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "831ea954f15db76b05365d7f49ab47b32249f716aa8c14c1b53bbb30ccfd7547"
+}
diff --git a/.sqlx/query-870db7495d7a1d85a58a9684a67ff16330fdd1bb88e2bff2bcdf94f9d026b45a.json b/.sqlx/query-870db7495d7a1d85a58a9684a67ff16330fdd1bb88e2bff2bcdf94f9d026b45a.json
new file mode 100644
index 0000000000..9aea9fe1a4
--- /dev/null
+++ b/.sqlx/query-870db7495d7a1d85a58a9684a67ff16330fdd1bb88e2bff2bcdf94f9d026b45a.json
@@ -0,0 +1,69 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, user_id, device_token, device_endpoint, device_type as \"device_type:DeviceType\" \n FROM notification_user_device_registration \n WHERE device_token = $1 AND device_type = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "device_token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "device_endpoint",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "device_type:DeviceType",
+ "type_info": {
+ "Custom": {
+ "name": "notification_device_type_option",
+ "kind": {
+ "Enum": [
+ "ios",
+ "android",
+ "iosvoip"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "notification_device_type_option",
+ "kind": {
+ "Enum": [
+ "ios",
+ "android",
+ "iosvoip"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "870db7495d7a1d85a58a9684a67ff16330fdd1bb88e2bff2bcdf94f9d026b45a"
+}
diff --git a/.sqlx/query-87676ed37d3c69cad81b0b81fa54abd0804a9168c202103afac5653fdeb10304.json b/.sqlx/query-87676ed37d3c69cad81b0b81fa54abd0804a9168c202103afac5653fdeb10304.json
new file mode 100644
index 0000000000..751bcd311c
--- /dev/null
+++ b/.sqlx/query-87676ed37d3c69cad81b0b81fa54abd0804a9168c202103afac5653fdeb10304.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO notification_email_unsubscribe_code(email, code)\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "87676ed37d3c69cad81b0b81fa54abd0804a9168c202103afac5653fdeb10304"
+}
diff --git a/.sqlx/query-942f94d3e0fca40e63e754acce88e8f57b6a9585154e9726e48c50385faff96c.json b/.sqlx/query-942f94d3e0fca40e63e754acce88e8f57b6a9585154e9726e48c50385faff96c.json
new file mode 100644
index 0000000000..1f79555f27
--- /dev/null
+++ b/.sqlx/query-942f94d3e0fca40e63e754acce88e8f57b6a9585154e9726e48c50385faff96c.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"pinnedItemId\" as \"pinned_item_id\" FROM \"Pin\"\n WHERE \"userId\" = $1\n ORDER BY \"pinIndex\" ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pinned_item_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "942f94d3e0fca40e63e754acce88e8f57b6a9585154e9726e48c50385faff96c"
+}
diff --git a/.sqlx/query-9675e7e8a3682d7f8d324fad5420a939f33331a4d7abbea4a71afd91402e2172.json b/.sqlx/query-9675e7e8a3682d7f8d324fad5420a939f33331a4d7abbea4a71afd91402e2172.json
new file mode 100644
index 0000000000..009ab4ca0b
--- /dev/null
+++ b/.sqlx/query-9675e7e8a3682d7f8d324fad5420a939f33331a4d7abbea4a71afd91402e2172.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT last_failure_at FROM webhook WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "last_failure_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "9675e7e8a3682d7f8d324fad5420a939f33331a4d7abbea4a71afd91402e2172"
+}
diff --git a/.sqlx/query-98c8bee947ac1133f6301e2f7aeb41e1465842b591438ed83a85c9fd5bfee0c8.json b/.sqlx/query-98c8bee947ac1133f6301e2f7aeb41e1465842b591438ed83a85c9fd5bfee0c8.json
new file mode 100644
index 0000000000..bbd9e2c72e
--- /dev/null
+++ b/.sqlx/query-98c8bee947ac1133f6301e2f7aeb41e1465842b591438ed83a85c9fd5bfee0c8.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"SharePermission\"\n SET \"linkShare\" = 'TEAM', \"linkShareAccessLevel\" = 'comment'\n WHERE id = 'sp-public-edit'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "98c8bee947ac1133f6301e2f7aeb41e1465842b591438ed83a85c9fd5bfee0c8"
+}
diff --git a/.sqlx/query-98dccab5beb0b73399e455341f71f7555bff0b06c63ae7e0e77fbc177d56636d.json b/.sqlx/query-98dccab5beb0b73399e455341f71f7555bff0b06c63ae7e0e77fbc177d56636d.json
new file mode 100644
index 0000000000..63a3ffc25b
--- /dev/null
+++ b/.sqlx/query-98dccab5beb0b73399e455341f71f7555bff0b06c63ae7e0e77fbc177d56636d.json
@@ -0,0 +1,88 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.status,\n d.delivered_at,\n a.status AS attempt_status,\n a.completed_at,\n a.duration_ms,\n a.response_status,\n a.response_headers_redacted,\n a.response_body_preview,\n a.error_kind,\n a.error_message,\n w.last_success_at,\n w.last_failure_at\n FROM webhook_delivery d\n JOIN webhook_delivery_attempt a ON a.webhook_delivery_id = d.id\n JOIN webhook w ON w.id = d.webhook_id\n WHERE d.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "delivered_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "attempt_status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "duration_ms",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 5,
+ "name": "response_status",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 6,
+ "name": "response_headers_redacted",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "response_body_preview",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "error_kind",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "error_message",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "last_success_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 11,
+ "name": "last_failure_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "98dccab5beb0b73399e455341f71f7555bff0b06c63ae7e0e77fbc177d56636d"
+}
diff --git a/.sqlx/query-99b2dd7ad2eea5488c441faee7021a0839d34a7d2cbe5d47d7f60a8538432d28.json b/.sqlx/query-99b2dd7ad2eea5488c441faee7021a0839d34a7d2cbe5d47d7f60a8538432d28.json
new file mode 100644
index 0000000000..1f6a0d3f2d
--- /dev/null
+++ b/.sqlx/query-99b2dd7ad2eea5488c441faee7021a0839d34a7d2cbe5d47d7f60a8538432d28.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO document_sub_type (document_id, sub_type) VALUES ($1, 'task')",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "99b2dd7ad2eea5488c441faee7021a0839d34a7d2cbe5d47d7f60a8538432d28"
+}
diff --git a/.sqlx/query-99c1afe678447276f96470657a80b018d73395ce772073ccac806029fcd5079b.json b/.sqlx/query-99c1afe678447276f96470657a80b018d73395ce772073ccac806029fcd5079b.json
new file mode 100644
index 0000000000..a1c5922448
--- /dev/null
+++ b/.sqlx/query-99c1afe678447276f96470657a80b018d73395ce772073ccac806029fcd5079b.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n request_url,\n request_headers_redacted,\n request_body,\n event,\n event_schema_version,\n event_entity_type,\n event_entity_id,\n event_ordering_key\n FROM webhook_delivery\n WHERE webhook_id = $1 AND event_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "request_url",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "request_headers_redacted",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "request_body",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "event",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "event_schema_version",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 5,
+ "name": "event_entity_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "event_entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "event_ordering_key",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "99c1afe678447276f96470657a80b018d73395ce772073ccac806029fcd5079b"
+}
diff --git a/.sqlx/query-9aa41ed19b65f711651fc74586ca2660fa9dacd52f3bceb44a7fcd16a61a8b7b.json b/.sqlx/query-9aa41ed19b65f711651fc74586ca2660fa9dacd52f3bceb44a7fcd16a61a8b7b.json
new file mode 100644
index 0000000000..77776f3bf8
--- /dev/null
+++ b/.sqlx/query-9aa41ed19b65f711651fc74586ca2660fa9dacd52f3bceb44a7fcd16a61a8b7b.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO harness_tokens (id, harness_id, token_hash, token_prefix)\n VALUES ($1, $2, $3, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bytea",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9aa41ed19b65f711651fc74586ca2660fa9dacd52f3bceb44a7fcd16a61a8b7b"
+}
diff --git a/.sqlx/query-9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e.json b/.sqlx/query-9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e.json
new file mode 100644
index 0000000000..4aff03b59d
--- /dev/null
+++ b/.sqlx/query-9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n l.macro_id,\n l.email_address::text AS \"email_address!\",\n COALESCE(g.granted_scopes, '{}') AS \"granted_scopes!\",\n COALESCE(g.grant_version, 0) AS \"grant_version!\",\n g.calendar_disabled_at\n FROM email_links l\n LEFT JOIN email_link_google_scopes g ON g.link_id = l.id\n WHERE l.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "email_address!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "granted_scopes!",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 3,
+ "name": "grant_version!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 4,
+ "name": "calendar_disabled_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null,
+ null,
+ true
+ ]
+ },
+ "hash": "9e3e9a5ba74600ee544a3a930bf54da41abaed6e7d7695e7fac88b65c4a3361e"
+}
diff --git a/.sqlx/query-a02284dd792ffd9ab316f10c5db6be68daf45af8e8348da0ed2dbbcbf9a1d902.json b/.sqlx/query-a02284dd792ffd9ab316f10c5db6be68daf45af8e8348da0ed2dbbcbf9a1d902.json
new file mode 100644
index 0000000000..92aae96c4f
--- /dev/null
+++ b/.sqlx/query-a02284dd792ffd9ab316f10c5db6be68daf45af8e8348da0ed2dbbcbf9a1d902.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) as \"count!\" FROM entity_properties WHERE property_definition_id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "a02284dd792ffd9ab316f10c5db6be68daf45af8e8348da0ed2dbbcbf9a1d902"
+}
diff --git a/.sqlx/query-a07f0622de5a2491d3561e87eff3e856f48779041f64fee910a5dade485c25a8.json b/.sqlx/query-a07f0622de5a2491d3561e87eff3e856f48779041f64fee910a5dade485c25a8.json
new file mode 100644
index 0000000000..a70ed472ac
--- /dev/null
+++ b/.sqlx/query-a07f0622de5a2491d3561e87eff3e856f48779041f64fee910a5dade485c25a8.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO comms_entity_mentions (id, source_entity_type, source_entity_id, entity_type, entity_id, user_id) VALUES (gen_random_uuid(), 'doc', 'doc_source_mixed', 'doc', 'doc1', NULL)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "a07f0622de5a2491d3561e87eff3e856f48779041f64fee910a5dade485c25a8"
+}
diff --git a/.sqlx/query-a19b4fe99206d243a850ab886248b487961a5d91bdcb8ae08211ebe3fcf4275f.json b/.sqlx/query-a19b4fe99206d243a850ab886248b487961a5d91bdcb8ae08211ebe3fcf4275f.json
new file mode 100644
index 0000000000..bf748c2cb8
--- /dev/null
+++ b/.sqlx/query-a19b4fe99206d243a850ab886248b487961a5d91bdcb8ae08211ebe3fcf4275f.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"projectId\" as project_id FROM \"Document\" WHERE \"id\" = 'document-one'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "project_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "a19b4fe99206d243a850ab886248b487961a5d91bdcb8ae08211ebe3fcf4275f"
+}
diff --git a/.sqlx/query-a1f487c1d017d637934627933947fb7768f94043d7c307b535144199dc71579e.json b/.sqlx/query-a1f487c1d017d637934627933947fb7768f94043d7c307b535144199dc71579e.json
new file mode 100644
index 0000000000..23c9624cf9
--- /dev/null
+++ b/.sqlx/query-a1f487c1d017d637934627933947fb7768f94043d7c307b535144199dc71579e.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"EmailThreadPermission\" (\"threadId\", \"sharePermissionId\", \"userId\")\n VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a1f487c1d017d637934627933947fb7768f94043d7c307b535144199dc71579e"
+}
diff --git a/.sqlx/query-a4d206e8adf143e77bcc98f24841d63031a3ec89c8722b39c2e5f29fc5138480.json b/.sqlx/query-a4d206e8adf143e77bcc98f24841d63031a3ec89c8722b39c2e5f29fc5138480.json
new file mode 100644
index 0000000000..0fa68904be
--- /dev/null
+++ b/.sqlx/query-a4d206e8adf143e77bcc98f24841d63031a3ec89c8722b39c2e5f29fc5138480.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT input\n FROM cursor_journal_input\n WHERE agent_session_id = $1 AND (input ? 'Sse' OR input ? 'Poll')\n ORDER BY sequence DESC\n LIMIT $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "input",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a4d206e8adf143e77bcc98f24841d63031a3ec89c8722b39c2e5f29fc5138480"
+}
diff --git a/.sqlx/query-a70062bdf42e20f590b22dc0f84c2bec53b1722779bdde82317bc8aa59a471e6.json b/.sqlx/query-a70062bdf42e20f590b22dc0f84c2bec53b1722779bdde82317bc8aa59a471e6.json
new file mode 100644
index 0000000000..96907667d6
--- /dev/null
+++ b/.sqlx/query-a70062bdf42e20f590b22dc0f84c2bec53b1722779bdde82317bc8aa59a471e6.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"deletedAt\", \"threadId\"\n FROM \"PdfHighlightAnchor\"\n WHERE uuid = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deletedAt",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 1,
+ "name": "threadId",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "a70062bdf42e20f590b22dc0f84c2bec53b1722779bdde82317bc8aa59a471e6"
+}
diff --git a/.sqlx/query-a79fb60be1082cb56c5313fa53ea3de248735636835c6f0a46a1c5e7f736f332.json b/.sqlx/query-a79fb60be1082cb56c5313fa53ea3de248735636835c6f0a46a1c5e7f736f332.json
new file mode 100644
index 0000000000..61de543969
--- /dev/null
+++ b/.sqlx/query-a79fb60be1082cb56c5313fa53ea3de248735636835c6f0a46a1c5e7f736f332.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"documentId\" FROM \"UploadJob\" WHERE \"jobId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "documentId",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "a79fb60be1082cb56c5313fa53ea3de248735636835c6f0a46a1c5e7f736f332"
+}
diff --git a/.sqlx/query-a7baf370108371fedbc9eec0287181a1581a3cc2c483b49f0b7579dd7338bd22.json b/.sqlx/query-a7baf370108371fedbc9eec0287181a1581a3cc2c483b49f0b7579dd7338bd22.json
new file mode 100644
index 0000000000..90d0e8b42c
--- /dev/null
+++ b/.sqlx/query-a7baf370108371fedbc9eec0287181a1581a3cc2c483b49f0b7579dd7338bd22.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT share_permission_id FROM call_records WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a7baf370108371fedbc9eec0287181a1581a3cc2c483b49f0b7579dd7338bd22"
+}
diff --git a/.sqlx/query-a7dfb6458b8d45a9db74a18fe006b1cc470cec88050afedd5043b96e942fccee.json b/.sqlx/query-a7dfb6458b8d45a9db74a18fe006b1cc470cec88050afedd5043b96e942fccee.json
new file mode 100644
index 0000000000..c72a28ca98
--- /dev/null
+++ b/.sqlx/query-a7dfb6458b8d45a9db74a18fe006b1cc470cec88050afedd5043b96e942fccee.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT status::text AS \"status!\" FROM email_backfill_jobs WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "a7dfb6458b8d45a9db74a18fe006b1cc470cec88050afedd5043b96e942fccee"
+}
diff --git a/.sqlx/query-ad4df630fb2c69f9114b8781a05436ea3cb67fcdd2e5eae565e8611178e744fb.json b/.sqlx/query-ad4df630fb2c69f9114b8781a05436ea3cb67fcdd2e5eae565e8611178e744fb.json
new file mode 100644
index 0000000000..51dae586cc
--- /dev/null
+++ b/.sqlx/query-ad4df630fb2c69f9114b8781a05436ea3cb67fcdd2e5eae565e8611178e744fb.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO frecency_aggregates (\n entity_id, entity_type, user_id, event_count,\n frecency_score, first_event, recent_events\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Int4",
+ "Float8",
+ "Timestamptz",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "ad4df630fb2c69f9114b8781a05436ea3cb67fcdd2e5eae565e8611178e744fb"
+}
diff --git a/.sqlx/query-af468f414a9aa17d5a4048ef54b103881675c7b38ae8d2d02e82b40f1e97a5d5.json b/.sqlx/query-af468f414a9aa17d5a4048ef54b103881675c7b38ae8d2d02e82b40f1e97a5d5.json
new file mode 100644
index 0000000000..e3a4b30636
--- /dev/null
+++ b/.sqlx/query-af468f414a9aa17d5a4048ef54b103881675c7b38ae8d2d02e82b40f1e97a5d5.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"Document\" SET \"projectId\" = 'p1' WHERE \"id\" = 'document-one'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "af468f414a9aa17d5a4048ef54b103881675c7b38ae8d2d02e82b40f1e97a5d5"
+}
diff --git a/.sqlx/query-af7e834bad00fbad177bfc3d71cc2551cd8b57be67c6452fdb76309b752b5302.json b/.sqlx/query-af7e834bad00fbad177bfc3d71cc2551cd8b57be67c6452fdb76309b752b5302.json
new file mode 100644
index 0000000000..0ffc648e47
--- /dev/null
+++ b/.sqlx/query-af7e834bad00fbad177bfc3d71cc2551cd8b57be67c6452fdb76309b752b5302.json
@@ -0,0 +1,118 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT changeset_id, source, repository, base_ref, base_sha, head_ref, head_sha,\n files, additions, deletions, patch_bytes, truncated, captured_at,\n attempt_started_at, attempt_finished_at, attempt_outcome, attempt_error\n FROM agent_session_changes\n WHERE agent_session_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "changeset_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "source",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "repository",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "base_ref",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "base_sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "head_ref",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "head_sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "files",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 8,
+ "name": "additions",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 9,
+ "name": "deletions",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 10,
+ "name": "patch_bytes",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 11,
+ "name": "truncated",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "captured_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 13,
+ "name": "attempt_started_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "attempt_finished_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "attempt_outcome",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 16,
+ "name": "attempt_error",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "af7e834bad00fbad177bfc3d71cc2551cd8b57be67c6452fdb76309b752b5302"
+}
diff --git a/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json b/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json
new file mode 100644
index 0000000000..ac476c9a0b
--- /dev/null
+++ b/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT history_start_log_id FROM agent_session WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "history_start_log_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7"
+}
diff --git a/.sqlx/query-b20c680d854d0716e27502fadcc79a21efcbf4a382e4f17cb95d6f98ee151cc4.json b/.sqlx/query-b20c680d854d0716e27502fadcc79a21efcbf4a382e4f17cb95d6f98ee151cc4.json
new file mode 100644
index 0000000000..7fad6d690f
--- /dev/null
+++ b/.sqlx/query-b20c680d854d0716e27502fadcc79a21efcbf4a382e4f17cb95d6f98ee151cc4.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"PdfHighlightAnchor\"\n SET \"threadId\" = $1\n WHERE uuid = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b20c680d854d0716e27502fadcc79a21efcbf4a382e4f17cb95d6f98ee151cc4"
+}
diff --git a/.sqlx/query-b2f707c8cdaba371d500519622534989e673ace8260a422bd418f014d6b5d390.json b/.sqlx/query-b2f707c8cdaba371d500519622534989e673ace8260a422bd418f014d6b5d390.json
new file mode 100644
index 0000000000..949917485d
--- /dev/null
+++ b/.sqlx/query-b2f707c8cdaba371d500519622534989e673ace8260a422bd418f014d6b5d390.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"deletedAt\" FROM \"PdfHighlightAnchor\"\n WHERE uuid = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deletedAt",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "b2f707c8cdaba371d500519622534989e673ace8260a422bd418f014d6b5d390"
+}
diff --git a/.sqlx/query-b5361358a7530ee5c9381fd6d3b00ad9b667d71ec9b3bf925e7fc16ea99653f3.json b/.sqlx/query-b5361358a7530ee5c9381fd6d3b00ad9b667d71ec9b3bf925e7fc16ea99653f3.json
new file mode 100644
index 0000000000..9e0a10a964
--- /dev/null
+++ b/.sqlx/query-b5361358a7530ee5c9381fd6d3b00ad9b667d71ec9b3bf925e7fc16ea99653f3.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_access (\n entity_id,\n entity_type,\n source_id,\n source_type,\n access_level\n )\n VALUES (\n 'cccccccc-cccc-cccc-cccc-000000000001',\n 'chat',\n 'user-3',\n 'user',\n 'view'\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "b5361358a7530ee5c9381fd6d3b00ad9b667d71ec9b3bf925e7fc16ea99653f3"
+}
diff --git a/.sqlx/query-b905a7b3100f7cff2d8b8ef1d316005ab28b52c3103384562bf26751b973958f.json b/.sqlx/query-b905a7b3100f7cff2d8b8ef1d316005ab28b52c3103384562bf26751b973958f.json
new file mode 100644
index 0000000000..4058cfa8a4
--- /dev/null
+++ b/.sqlx/query-b905a7b3100f7cff2d8b8ef1d316005ab28b52c3103384562bf26751b973958f.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT created_at\n FROM channel_notification_email_sent\n WHERE channel_id = $1\n AND user_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_at",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "b905a7b3100f7cff2d8b8ef1d316005ab28b52c3103384562bf26751b973958f"
+}
diff --git a/.sqlx/query-bacb14adfca8cf154de66a71df2a397482a74f60bc37f8548cf68e8aed95214e.json b/.sqlx/query-bacb14adfca8cf154de66a71df2a397482a74f60bc37f8548cf68e8aed95214e.json
new file mode 100644
index 0000000000..41a9c5fc1d
--- /dev/null
+++ b/.sqlx/query-bacb14adfca8cf154de66a71df2a397482a74f60bc37f8548cf68e8aed95214e.json
@@ -0,0 +1,32 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, item_id, item_type FROM user_notification_item_unsubscribe WHERE item_id = 'document-one' AND user_id = 'macro|[email protected]'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "item_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "item_type",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "bacb14adfca8cf154de66a71df2a397482a74f60bc37f8548cf68e8aed95214e"
+}
diff --git a/.sqlx/query-bb3e095a9da280495a2c7979e4a4b1d86d442dd8e49c66ecc6e7d414145c281c.json b/.sqlx/query-bb3e095a9da280495a2c7979e4a4b1d86d442dd8e49c66ecc6e7d414145c281c.json
new file mode 100644
index 0000000000..c692649fe5
--- /dev/null
+++ b/.sqlx/query-bb3e095a9da280495a2c7979e4a4b1d86d442dd8e49c66ecc6e7d414145c281c.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT seat_count FROM team WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "seat_count",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bb3e095a9da280495a2c7979e4a4b1d86d442dd8e49c66ecc6e7d414145c281c"
+}
diff --git a/.sqlx/query-bb9c322f601c8672e364dc9e2700de834ed8b6abf3330c251b085538739db7cb.json b/.sqlx/query-bb9c322f601c8672e364dc9e2700de834ed8b6abf3330c251b085538739db7cb.json
new file mode 100644
index 0000000000..025c3aa1c7
--- /dev/null
+++ b/.sqlx/query-bb9c322f601c8672e364dc9e2700de834ed8b6abf3330c251b085538739db7cb.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO user_notification (user_id, notification_id, created_at, seen_at, state)\n VALUES ($1, $2, NOW(), NULL, 'unseen'), ($1, $3, NOW(), NOW(), 'done')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bb9c322f601c8672e364dc9e2700de834ed8b6abf3330c251b085538739db7cb"
+}
diff --git a/.sqlx/query-bca4c5ebcfe4b6716bd20d8a031735081e3a2e2181b5c52b5c42a9506310bfc8.json b/.sqlx/query-bca4c5ebcfe4b6716bd20d8a031735081e3a2e2181b5c52b5c42a9506310bfc8.json
new file mode 100644
index 0000000000..1b1e23ff3d
--- /dev/null
+++ b/.sqlx/query-bca4c5ebcfe4b6716bd20d8a031735081e3a2e2181b5c52b5c42a9506310bfc8.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"macro_user_id\" as \"macro_user_id!\" FROM \"User\" WHERE \"macro_user_id\" = $1 AND \"id\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bca4c5ebcfe4b6716bd20d8a031735081e3a2e2181b5c52b5c42a9506310bfc8"
+}
diff --git a/.sqlx/query-bcec006efa10df748a886c294b809ccc4f8cea4c74f21363e4eb22595bb73d78.json b/.sqlx/query-bcec006efa10df748a886c294b809ccc4f8cea4c74f21363e4eb22595bb73d78.json
new file mode 100644
index 0000000000..320062f619
--- /dev/null
+++ b/.sqlx/query-bcec006efa10df748a886c294b809ccc4f8cea4c74f21363e4eb22595bb73d78.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE webhook\n SET\n endpoint_url = $2,\n headers = $3,\n updated_at = now()\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bcec006efa10df748a886c294b809ccc4f8cea4c74f21363e4eb22595bb73d78"
+}
diff --git a/.sqlx/query-bff01581339088cabd0406aa4cb27cc932fd5a1f483533ac0c315bd9d0680675.json b/.sqlx/query-bff01581339088cabd0406aa4cb27cc932fd5a1f483533ac0c315bd9d0680675.json
new file mode 100644
index 0000000000..c5dc3ca39b
--- /dev/null
+++ b/.sqlx/query-bff01581339088cabd0406aa4cb27cc932fd5a1f483533ac0c315bd9d0680675.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT needs_reauth FROM email_links WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "needs_reauth",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bff01581339088cabd0406aa4cb27cc932fd5a1f483533ac0c315bd9d0680675"
+}
diff --git a/.sqlx/query-c2feb2efcd21ec4ef8443ec663402831785fff899698e235ab7aae509e6dee6a.json b/.sqlx/query-c2feb2efcd21ec4ef8443ec663402831785fff899698e235ab7aae509e6dee6a.json
new file mode 100644
index 0000000000..89583f3272
--- /dev/null
+++ b/.sqlx/query-c2feb2efcd21ec4ef8443ec663402831785fff899698e235ab7aae509e6dee6a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT (1) as exists\n FROM \"ThreadAnchor\"\n WHERE \"threadId\" = $1 AND \"anchorId\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c2feb2efcd21ec4ef8443ec663402831785fff899698e235ab7aae509e6dee6a"
+}
diff --git a/.sqlx/query-c3aa57ab0a5b982c0020f3e2eecc3432e627ddbfb37aa39c79c58d8cbf328a8c.json b/.sqlx/query-c3aa57ab0a5b982c0020f3e2eecc3432e627ddbfb37aa39c79c58d8cbf328a8c.json
new file mode 100644
index 0000000000..1362efb11a
--- /dev/null
+++ b/.sqlx/query-c3aa57ab0a5b982c0020f3e2eecc3432e627ddbfb37aa39c79c58d8cbf328a8c.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id FROM user_mute_notification WHERE user_id = 'A'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "c3aa57ab0a5b982c0020f3e2eecc3432e627ddbfb37aa39c79c58d8cbf328a8c"
+}
diff --git a/.sqlx/query-c46e24f291443a9a4ef367198bb899bc5e427aa314c2e8ff7e8472509b07e478.json b/.sqlx/query-c46e24f291443a9a4ef367198bb899bc5e427aa314c2e8ff7e8472509b07e478.json
new file mode 100644
index 0000000000..27b32c583d
--- /dev/null
+++ b/.sqlx/query-c46e24f291443a9a4ef367198bb899bc5e427aa314c2e8ff7e8472509b07e478.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO webhook (\n id,\n workspace_id,\n namespace,\n name,\n endpoint_url,\n signing_secret,\n headers,\n filters,\n status,\n is_valid,\n created_by_user_id,\n deleted_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, true, $10, $11)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Jsonb",
+ "Text",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c46e24f291443a9a4ef367198bb899bc5e427aa314c2e8ff7e8472509b07e478"
+}
diff --git a/.sqlx/query-c4ef2d7794fbee599582073bb2901ad347f7f570db4b3bd02dd0e348e1d65815.json b/.sqlx/query-c4ef2d7794fbee599582073bb2901ad347f7f570db4b3bd02dd0e348e1d65815.json
new file mode 100644
index 0000000000..51257cfaa1
--- /dev/null
+++ b/.sqlx/query-c4ef2d7794fbee599582073bb2901ad347f7f570db4b3bd02dd0e348e1d65815.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT attempt_number, status\n FROM webhook_delivery_attempt\n WHERE webhook_delivery_id = $1\n ORDER BY attempt_number\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "attempt_number",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 1,
+ "name": "status",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "c4ef2d7794fbee599582073bb2901ad347f7f570db4b3bd02dd0e348e1d65815"
+}
diff --git a/.sqlx/query-c7907437d0fbb4862daece91db17e3e9c9c32fca6d1813c4e4262f6f3f7ed3a1.json b/.sqlx/query-c7907437d0fbb4862daece91db17e3e9c9c32fca6d1813c4e4262f6f3f7ed3a1.json
new file mode 100644
index 0000000000..95bdb8fedc
--- /dev/null
+++ b/.sqlx/query-c7907437d0fbb4862daece91db17e3e9c9c32fca6d1813c4e4262f6f3f7ed3a1.json
@@ -0,0 +1,55 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, user_id, device_token, device_endpoint, device_type as \"device_type:DeviceType\" \n FROM notification_user_device_registration \n WHERE id = '017d85a8-c7c6-7c40-b4f3-a6c1b3c0d1e2'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "device_token",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "device_endpoint",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "device_type:DeviceType",
+ "type_info": {
+ "Custom": {
+ "name": "notification_device_type_option",
+ "kind": {
+ "Enum": [
+ "ios",
+ "android",
+ "iosvoip"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "c7907437d0fbb4862daece91db17e3e9c9c32fca6d1813c4e4262f6f3f7ed3a1"
+}
diff --git a/.sqlx/query-c7dadf94cc6550c04c89c1d0ef87be2a8d6f7b02e5ab0e1056f98cbd9ecd8232.json b/.sqlx/query-c7dadf94cc6550c04c89c1d0ef87be2a8d6f7b02e5ab0e1056f98cbd9ecd8232.json
new file mode 100644
index 0000000000..37fdad5867
--- /dev/null
+++ b/.sqlx/query-c7dadf94cc6550c04c89c1d0ef87be2a8d6f7b02e5ab0e1056f98cbd9ecd8232.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"macro_user\" (\"id\", \"email\", \"stripe_customer_id\", \"username\")\n VALUES ($1, $2, $3, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c7dadf94cc6550c04c89c1d0ef87be2a8d6f7b02e5ab0e1056f98cbd9ecd8232"
+}
diff --git a/.sqlx/query-c8968c57a19b05560e7c1e75b2fbed66848724cce22282cc1cfdd930f89f8058.json b/.sqlx/query-c8968c57a19b05560e7c1e75b2fbed66848724cce22282cc1cfdd930f89f8058.json
new file mode 100644
index 0000000000..d198005021
--- /dev/null
+++ b/.sqlx/query-c8968c57a19b05560e7c1e75b2fbed66848724cce22282cc1cfdd930f89f8058.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM \"PdfHighlightRect\"\n WHERE \"id\" = 1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "c8968c57a19b05560e7c1e75b2fbed66848724cce22282cc1cfdd930f89f8058"
+}
diff --git a/.sqlx/query-cb1be54c1f4c697551f959823955639bd8446ecb4ee9a4359fa0ce1cd05b04b5.json b/.sqlx/query-cb1be54c1f4c697551f959823955639bd8446ecb4ee9a4359fa0ce1cd05b04b5.json
new file mode 100644
index 0000000000..e82217b378
--- /dev/null
+++ b/.sqlx/query-cb1be54c1f4c697551f959823955639bd8446ecb4ee9a4359fa0ce1cd05b04b5.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT attempt_number, status, completed_at\n FROM webhook_delivery_attempt\n WHERE webhook_delivery_id = $1\n ORDER BY attempt_number\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "attempt_number",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 1,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "cb1be54c1f4c697551f959823955639bd8446ecb4ee9a4359fa0ce1cd05b04b5"
+}
diff --git a/.sqlx/query-cc916073ea39cc7814ef3bbaa7a86f912bc4c14ef62f597a99c1350367ddd8dc.json b/.sqlx/query-cc916073ea39cc7814ef3bbaa7a86f912bc4c14ef62f597a99c1350367ddd8dc.json
new file mode 100644
index 0000000000..86b12e41cd
--- /dev/null
+++ b/.sqlx/query-cc916073ea39cc7814ef3bbaa7a86f912bc4c14ef62f597a99c1350367ddd8dc.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT last_success_at, last_failure_at FROM webhook WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "last_success_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 1,
+ "name": "last_failure_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "cc916073ea39cc7814ef3bbaa7a86f912bc4c14ef62f597a99c1350367ddd8dc"
+}
diff --git a/.sqlx/query-cc9bce558e79c8f411d6ecf90aae3eb9ed6a6dd0723fd36f603b7b747cf8d164.json b/.sqlx/query-cc9bce558e79c8f411d6ecf90aae3eb9ed6a6dd0723fd36f603b7b747cf8d164.json
new file mode 100644
index 0000000000..5651e17342
--- /dev/null
+++ b/.sqlx/query-cc9bce558e79c8f411d6ecf90aae3eb9ed6a6dd0723fd36f603b7b747cf8d164.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"account_merge_request\" (\"id\", \"macro_user_id\", \"to_merge_macro_user_id\", \"code\", \"created_at\")\n VALUES ($1, $2, $3, $4, NOW())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "cc9bce558e79c8f411d6ecf90aae3eb9ed6a6dd0723fd36f603b7b747cf8d164"
+}
diff --git a/.sqlx/query-ce412ec518979bbde55cfa89c941aa25611aef717cfae6c9a6be3cef969cfe15.json b/.sqlx/query-ce412ec518979bbde55cfa89c941aa25611aef717cfae6c9a6be3cef969cfe15.json
new file mode 100644
index 0000000000..4d17041acf
--- /dev/null
+++ b/.sqlx/query-ce412ec518979bbde55cfa89c941aa25611aef717cfae6c9a6be3cef969cfe15.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.status,\n d.delivered_at,\n d.attempt_count,\n a.status AS attempt_status,\n a.completed_at,\n w.last_success_at,\n w.last_failure_at\n FROM webhook_delivery d\n JOIN webhook_delivery_attempt a ON a.webhook_delivery_id = d.id\n JOIN webhook w ON w.id = d.webhook_id\n WHERE d.id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "delivered_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "attempt_count",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "attempt_status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "completed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "last_success_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "last_failure_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ true,
+ true,
+ true
+ ]
+ },
+ "hash": "ce412ec518979bbde55cfa89c941aa25611aef717cfae6c9a6be3cef969cfe15"
+}
diff --git a/.sqlx/query-d102f557380f9ffe4922043745bd81c4a3a7c34924af6db91242f12304bf4da6.json b/.sqlx/query-d102f557380f9ffe4922043745bd81c4a3a7c34924af6db91242f12304bf4da6.json
new file mode 100644
index 0000000000..d620d09221
--- /dev/null
+++ b/.sqlx/query-d102f557380f9ffe4922043745bd81c4a3a7c34924af6db91242f12304bf4da6.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM webhook_delivery WHERE webhook_id = $1 AND event_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "d102f557380f9ffe4922043745bd81c4a3a7c34924af6db91242f12304bf4da6"
+}
diff --git a/.sqlx/query-d1386571f515c3eed3ae97d71660c9d6d76cda1f180f2cd14338729c82a12201.json b/.sqlx/query-d1386571f515c3eed3ae97d71660c9d6d76cda1f180f2cd14338729c82a12201.json
new file mode 100644
index 0000000000..10cf47bc05
--- /dev/null
+++ b/.sqlx/query-d1386571f515c3eed3ae97d71660c9d6d76cda1f180f2cd14338729c82a12201.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO webhook (\n id, workspace_id, namespace, name, endpoint_url, signing_secret,\n filters, status, is_valid, created_by_user_id, deleted_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Text",
+ "Bool",
+ "Text",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d1386571f515c3eed3ae97d71660c9d6d76cda1f180f2cd14338729c82a12201"
+}
diff --git a/.sqlx/query-d2436d56842caa18e8b58e18c40a20a428e76153260009a757c6aefa4f6a4ce3.json b/.sqlx/query-d2436d56842caa18e8b58e18c40a20a428e76153260009a757c6aefa4f6a4ce3.json
new file mode 100644
index 0000000000..bc47dc3549
--- /dev/null
+++ b/.sqlx/query-d2436d56842caa18e8b58e18c40a20a428e76153260009a757c6aefa4f6a4ce3.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"Document\" (id, name, owner, \"fileType\")\n VALUES ($1, 'Empty Test Document', 'macro|[email protected]', 'pdf')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d2436d56842caa18e8b58e18c40a20a428e76153260009a757c6aefa4f6a4ce3"
+}
diff --git a/.sqlx/query-d2eea4a2fdebe87e15ad31d83ae7ad53ee171854154d1decaa2ca6ccfe138c7c.json b/.sqlx/query-d2eea4a2fdebe87e15ad31d83ae7ad53ee171854154d1decaa2ca6ccfe138c7c.json
new file mode 100644
index 0000000000..d927ca77cf
--- /dev/null
+++ b/.sqlx/query-d2eea4a2fdebe87e15ad31d83ae7ad53ee171854154d1decaa2ca6ccfe138c7c.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"Comment\"\n SET \"deletedAt\" = NOW()\n WHERE \"id\" = 10001\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "d2eea4a2fdebe87e15ad31d83ae7ad53ee171854154d1decaa2ca6ccfe138c7c"
+}
diff --git a/.sqlx/query-decf8e840e13bfe975576b35ff48779f7e243d461d37cbe0fff1678955a988bb.json b/.sqlx/query-decf8e840e13bfe975576b35ff48779f7e243d461d37cbe0fff1678955a988bb.json
new file mode 100644
index 0000000000..f226e79a6b
--- /dev/null
+++ b/.sqlx/query-decf8e840e13bfe975576b35ff48779f7e243d461d37cbe0fff1678955a988bb.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE bots SET deleted_at = now()",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "decf8e840e13bfe975576b35ff48779f7e243d461d37cbe0fff1678955a988bb"
+}
diff --git a/.sqlx/query-e154e97b6351beaf07d91407a01e5040dcbfcd1992ec71924771c7840c22b18a.json b/.sqlx/query-e154e97b6351beaf07d91407a01e5040dcbfcd1992ec71924771c7840c22b18a.json
new file mode 100644
index 0000000000..f91e81d7c0
--- /dev/null
+++ b/.sqlx/query-e154e97b6351beaf07d91407a01e5040dcbfcd1992ec71924771c7840c22b18a.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO team (id, owner_id, name) VALUES ($1, $2, $3)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e154e97b6351beaf07d91407a01e5040dcbfcd1992ec71924771c7840c22b18a"
+}
diff --git a/.sqlx/query-e233b0f2888b75bd70f9b6ecc11593c8be6cf5d43c234873dbc6f3b3296c8f00.json b/.sqlx/query-e233b0f2888b75bd70f9b6ecc11593c8be6cf5d43c234873dbc6f3b3296c8f00.json
new file mode 100644
index 0000000000..a9fc472b29
--- /dev/null
+++ b/.sqlx/query-e233b0f2888b75bd70f9b6ecc11593c8be6cf5d43c234873dbc6f3b3296c8f00.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT share_permission_id FROM calls WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "share_permission_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "e233b0f2888b75bd70f9b6ecc11593c8be6cf5d43c234873dbc6f3b3296c8f00"
+}
diff --git a/.sqlx/query-e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b.json b/.sqlx/query-e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b.json
new file mode 100644
index 0000000000..82f38da2f6
--- /dev/null
+++ b/.sqlx/query-e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "e67fda05dacea7a0b6290e8b69932ad27e5a0dd128af9273d1d6179e60f9ea0b"
+}
diff --git a/.sqlx/query-e715a947e31ba6dcdc8ca7243ca374ce8c2d8e52e8cad5edd2b43b6d541f9e81.json b/.sqlx/query-e715a947e31ba6dcdc8ca7243ca374ce8c2d8e52e8cad5edd2b43b6d541f9e81.json
new file mode 100644
index 0000000000..2779a5d081
--- /dev/null
+++ b/.sqlx/query-e715a947e31ba6dcdc8ca7243ca374ce8c2d8e52e8cad5edd2b43b6d541f9e81.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"deletedAt\" FROM \"Comment\"\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deletedAt",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "e715a947e31ba6dcdc8ca7243ca374ce8c2d8e52e8cad5edd2b43b6d541f9e81"
+}
diff --git a/.sqlx/query-e747ad81c61092baaa02154932db84aaf63c40af65d09e4d4f054077d2833d29.json b/.sqlx/query-e747ad81c61092baaa02154932db84aaf63c40af65d09e4d4f054077d2833d29.json
new file mode 100644
index 0000000000..d64b93c725
--- /dev/null
+++ b/.sqlx/query-e747ad81c61092baaa02154932db84aaf63c40af65d09e4d4f054077d2833d29.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO \"User\" (id, email) VALUES ($1, $2) ON CONFLICT (id) DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e747ad81c61092baaa02154932db84aaf63c40af65d09e4d4f054077d2833d29"
+}
diff --git a/.sqlx/query-ecbff9fb72d7a078d4be0999ea3877350f0efbd33ddbdcdf33f29e96ed02041a.json b/.sqlx/query-ecbff9fb72d7a078d4be0999ea3877350f0efbd33ddbdcdf33f29e96ed02041a.json
new file mode 100644
index 0000000000..be33fc0f08
--- /dev/null
+++ b/.sqlx/query-ecbff9fb72d7a078d4be0999ea3877350f0efbd33ddbdcdf33f29e96ed02041a.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT email FROM \"OrganizationInvitation\" WHERE email=$1 AND organization_id = $2",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "email",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int4"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "ecbff9fb72d7a078d4be0999ea3877350f0efbd33ddbdcdf33f29e96ed02041a"
+}
diff --git a/.sqlx/query-ecc7c047b0576142b51f47f047e5768c4c3f3093b7762a1ffee52e2a53f181f8.json b/.sqlx/query-ecc7c047b0576142b51f47f047e5768c4c3f3093b7762a1ffee52e2a53f181f8.json
new file mode 100644
index 0000000000..517b5059fa
--- /dev/null
+++ b/.sqlx/query-ecc7c047b0576142b51f47f047e5768c4c3f3093b7762a1ffee52e2a53f181f8.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"Project\" (\"id\", \"name\", \"userId\")\n VALUES ('p1', 'd', 'macro|[email protected]')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "ecc7c047b0576142b51f47f047e5768c4c3f3093b7762a1ffee52e2a53f181f8"
+}
diff --git a/.sqlx/query-ed615756aac4510ac1d99e11f5b15d299db90c1a75d82b726d27043c23ba6abf.json b/.sqlx/query-ed615756aac4510ac1d99e11f5b15d299db90c1a75d82b726d27043c23ba6abf.json
new file mode 100644
index 0000000000..cded2dd5ba
--- /dev/null
+++ b/.sqlx/query-ed615756aac4510ac1d99e11f5b15d299db90c1a75d82b726d27043c23ba6abf.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n \"macro_user_id\",\n \"email\",\n \"is_verified\"\n FROM \"macro_user_email_verification\"\n WHERE \"macro_user_id\" = $1 AND \"email\" = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "is_verified",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "ed615756aac4510ac1d99e11f5b15d299db90c1a75d82b726d27043c23ba6abf"
+}
diff --git a/.sqlx/query-edb3749d85688451e8988bd5de13ce7787c0420468511f9ed0cb8f4fb37cd3c0.json b/.sqlx/query-edb3749d85688451e8988bd5de13ce7787c0420468511f9ed0cb8f4fb37cd3c0.json
new file mode 100644
index 0000000000..4bea9a8790
--- /dev/null
+++ b/.sqlx/query-edb3749d85688451e8988bd5de13ce7787c0420468511f9ed0cb8f4fb37cd3c0.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT COUNT(*) FROM webhook_delivery",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "edb3749d85688451e8988bd5de13ce7787c0420468511f9ed0cb8f4fb37cd3c0"
+}
diff --git a/.sqlx/query-f1914d52a5540be6b76b4a787d98e61fab3dc24dc8b62223d412c913b415a433.json b/.sqlx/query-f1914d52a5540be6b76b4a787d98e61fab3dc24dc8b62223d412c913b415a433.json
new file mode 100644
index 0000000000..4e6ceeff95
--- /dev/null
+++ b/.sqlx/query-f1914d52a5540be6b76b4a787d98e61fab3dc24dc8b62223d412c913b415a433.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"ThreadAnchor\" (\"threadId\", \"anchorId\", \"anchorTableName\")\n VALUES ($1, $2, $3::\"anchor_table_name\")\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Uuid",
+ {
+ "Custom": {
+ "name": "anchor_table_name",
+ "kind": {
+ "Enum": [
+ "PdfPlaceableCommentAnchor",
+ "PdfHighlightAnchor"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f1914d52a5540be6b76b4a787d98e61fab3dc24dc8b62223d412c913b415a433"
+}
diff --git a/.sqlx/query-f308b4c145ee2a10958b9b29e2eba74dcd9741e73a4936c16791dbc0534b1698.json b/.sqlx/query-f308b4c145ee2a10958b9b29e2eba74dcd9741e73a4936c16791dbc0534b1698.json
new file mode 100644
index 0000000000..2837699c0c
--- /dev/null
+++ b/.sqlx/query-f308b4c145ee2a10958b9b29e2eba74dcd9741e73a4936c16791dbc0534b1698.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentPermission\" (\"documentId\", \"sharePermissionId\")\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f308b4c145ee2a10958b9b29e2eba74dcd9741e73a4936c16791dbc0534b1698"
+}
diff --git a/.sqlx/query-f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c.json b/.sqlx/query-f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c.json
new file mode 100644
index 0000000000..ab57db9444
--- /dev/null
+++ b/.sqlx/query-f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"User\" (id, email, macro_user_id)\n VALUES ($1, $2, $3)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f400e52fd81e057c31a80c0bb4f4835481bf9952c8e4518d927f05212457585c"
+}
diff --git a/.sqlx/query-f4a4117466186462642204b171c3b730bb1bbcffa0fe3abac3f824788e60788c.json b/.sqlx/query-f4a4117466186462642204b171c3b730bb1bbcffa0fe3abac3f824788e60788c.json
new file mode 100644
index 0000000000..1e0d58694a
--- /dev/null
+++ b/.sqlx/query-f4a4117466186462642204b171c3b730bb1bbcffa0fe3abac3f824788e60788c.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO document_sub_type (document_id, sub_type)\n VALUES ($1, 'task')\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f4a4117466186462642204b171c3b730bb1bbcffa0fe3abac3f824788e60788c"
+}
diff --git a/.sqlx/query-f797988fe49930127473abeb1b991c80066104f6be12f96a0a61de9df2d7181b.json b/.sqlx/query-f797988fe49930127473abeb1b991c80066104f6be12f96a0a61de9df2d7181b.json
new file mode 100644
index 0000000000..4cd9cb2488
--- /dev/null
+++ b/.sqlx/query-f797988fe49930127473abeb1b991c80066104f6be12f96a0a61de9df2d7181b.json
@@ -0,0 +1,12 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"PdfHighlightAnchor\"\n SET \"deletedAt\" = NOW()\n WHERE \"uuid\" = '11111111-1111-1111-1111-111111111111'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": []
+ },
+ "hash": "f797988fe49930127473abeb1b991c80066104f6be12f96a0a61de9df2d7181b"
+}
diff --git a/.sqlx/query-f7f3b51b9f3d2f40e2fb3314b7cda8e9df42bee9c4dc3edc8d79475719232a5e.json b/.sqlx/query-f7f3b51b9f3d2f40e2fb3314b7cda8e9df42bee9c4dc3edc8d79475719232a5e.json
new file mode 100644
index 0000000000..904903738f
--- /dev/null
+++ b/.sqlx/query-f7f3b51b9f3d2f40e2fb3314b7cda8e9df42bee9c4dc3edc8d79475719232a5e.json
@@ -0,0 +1,29 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"createdAt\" as created_at, \"updatedAt\" as updated_at\n FROM \"UserHistory\"\n WHERE \"userId\" = $1 AND \"itemId\" = $2 AND \"itemType\" = 'project'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_at",
+ "type_info": "Timestamp"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "f7f3b51b9f3d2f40e2fb3314b7cda8e9df42bee9c4dc3edc8d79475719232a5e"
+}
diff --git a/.sqlx/query-f927882aed897d3b9ee33d9f00aac1277be01d316350db234551199780f75a48.json b/.sqlx/query-f927882aed897d3b9ee33d9f00aac1277be01d316350db234551199780f75a48.json
new file mode 100644
index 0000000000..6356a4176b
--- /dev/null
+++ b/.sqlx/query-f927882aed897d3b9ee33d9f00aac1277be01d316350db234551199780f75a48.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n p.id\n FROM\n \"Project\" p\n WHERE\n p.\"userId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "f927882aed897d3b9ee33d9f00aac1277be01d316350db234551199780f75a48"
+}
diff --git a/.sqlx/query-fa98cf64fc220fec5755e06433758c22eb832bd3437ea4aaa4ad385c0f412c04.json b/.sqlx/query-fa98cf64fc220fec5755e06433758c22eb832bd3437ea4aaa4ad385c0f412c04.json
new file mode 100644
index 0000000000..49e9eb8ce3
--- /dev/null
+++ b/.sqlx/query-fa98cf64fc220fec5755e06433758c22eb832bd3437ea4aaa4ad385c0f412c04.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"pinnedItemId\" FROM \"Pin\" WHERE \"userId\" = $1 AND \"pinnedItemId\" = $2 AND \"pinnedItemType\" = $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pinnedItemId",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "fa98cf64fc220fec5755e06433758c22eb832bd3437ea4aaa4ad385c0f412c04"
+}
diff --git a/.sqlx/query-fc81bf86933d8fea50f89c4827a31987b59b9cdfac94d5719ffe3e43465a8b49.json b/.sqlx/query-fc81bf86933d8fea50f89c4827a31987b59b9cdfac94d5719ffe3e43465a8b49.json
new file mode 100644
index 0000000000..26709d97d4
--- /dev/null
+++ b/.sqlx/query-fc81bf86933d8fea50f89c4827a31987b59b9cdfac94d5719ffe3e43465a8b49.json
@@ -0,0 +1,44 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \n hr.\"pdfHighlightAnchorId\", hr.top, hr.left, hr.width, hr.height\n FROM \"PdfHighlightRect\" hr\n JOIN \"PdfHighlightAnchor\" ha ON hr.\"pdfHighlightAnchorId\" = ha.uuid\n WHERE ha.\"documentId\" = 'document-with-comments'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pdfHighlightAnchorId",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "top",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 2,
+ "name": "left",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 3,
+ "name": "width",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 4,
+ "name": "height",
+ "type_info": "Float8"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "fc81bf86933d8fea50f89c4827a31987b59b9cdfac94d5719ffe3e43465a8b49"
+}
diff --git a/.sqlx/query-fd35175c2d4880a5e6188576b4adb0a7628bc97d4203d50aabdd43ad1b794d17.json b/.sqlx/query-fd35175c2d4880a5e6188576b4adb0a7628bc97d4203d50aabdd43ad1b794d17.json
new file mode 100644
index 0000000000..c3af15085e
--- /dev/null
+++ b/.sqlx/query-fd35175c2d4880a5e6188576b4adb0a7628bc97d4203d50aabdd43ad1b794d17.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"SharePermission\" (\n id,\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES ($1, NULL, NULL, NOW(), NOW())\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fd35175c2d4880a5e6188576b4adb0a7628bc97d4203d50aabdd43ad1b794d17"
+}
diff --git a/.sqlx/query-fde1e0c0715a20f7baf7ddccff5be85b0259368a74b8a41fdc3092e756b704da.json b/.sqlx/query-fde1e0c0715a20f7baf7ddccff5be85b0259368a74b8a41fdc3092e756b704da.json
new file mode 100644
index 0000000000..ff934961ae
--- /dev/null
+++ b/.sqlx/query-fde1e0c0715a20f7baf7ddccff5be85b0259368a74b8a41fdc3092e756b704da.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"deletedAt\" as deleted_at FROM \"Document\" WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deleted_at",
+ "type_info": "Timestamp"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "fde1e0c0715a20f7baf7ddccff5be85b0259368a74b8a41fdc3092e756b704da"
+}
diff --git a/.sqlx/query-fe76770c0a2d5e6329180d611ef43e18e2a3eabdb112ed1486e9095cba95a579.json b/.sqlx/query-fe76770c0a2d5e6329180d611ef43e18e2a3eabdb112ed1486e9095cba95a579.json
new file mode 100644
index 0000000000..60d47562ae
--- /dev/null
+++ b/.sqlx/query-fe76770c0a2d5e6329180d611ef43e18e2a3eabdb112ed1486e9095cba95a579.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM email_threads",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "fe76770c0a2d5e6329180d611ef43e18e2a3eabdb112ed1486e9095cba95a579"
+}
diff --git a/.sqlx/query-fea18f68b65b80b18afba85d68044579f79b3236177bf6c513d06a51fa91337d.json b/.sqlx/query-fea18f68b65b80b18afba85d68044579f79b3236177bf6c513d06a51fa91337d.json
new file mode 100644
index 0000000000..c2c1cf2ef5
--- /dev/null
+++ b/.sqlx/query-fea18f68b65b80b18afba85d68044579f79b3236177bf6c513d06a51fa91337d.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE \"Thread\"\n SET \"deletedAt\" = NOW()\n WHERE \"id\" = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fea18f68b65b80b18afba85d68044579f79b3236177bf6c513d06a51fa91337d"
+}
diff --git a/.sqlx/query-fedf501a2d6920b9918220f4cd89c8b70c05548f9c46a3ffc76a86886fca54b1.json b/.sqlx/query-fedf501a2d6920b9918220f4cd89c8b70c05548f9c46a3ffc76a86886fca54b1.json
new file mode 100644
index 0000000000..b3e39eb33c
--- /dev/null
+++ b/.sqlx/query-fedf501a2d6920b9918220f4cd89c8b70c05548f9c46a3ffc76a86886fca54b1.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"User\" (id, email, macro_user_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "fedf501a2d6920b9918220f4cd89c8b70c05548f9c46a3ffc76a86886fca54b1"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 99a1fa2500..1415a85298 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -173,6 +173,39 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "agent_changes"
+version = "0.1.0"
+dependencies = [
+ "agent_fold",
+ "agent_session",
+ "anyhow",
+ "aws-sdk-s3",
+ "axum",
+ "bot_id",
+ "chrono",
+ "dashmap",
+ "entity_access",
+ "github",
+ "macro_authorization",
+ "macro_db_migrator",
+ "macro_user_id",
+ "macro_uuid",
+ "reqwest 0.13.4",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "strum 0.27.2",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "url",
+ "utoipa",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "agent_egress"
version = "0.1.0"
@@ -309,6 +342,7 @@ name = "agent_harness_service"
version = "0.1.0"
dependencies = [
"agent-client-protocol",
+ "agent_changes",
"agent_egress",
"agent_fold",
"agent_harness",
diff --git a/Cargo.toml b/Cargo.toml
index c007320b1a..dfcb78beb0 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "2"
members = [
"crates/activity",
- "crates/agent", "crates/agent_egress", "crates/agent_fold",
+ "crates/agent", "crates/agent_changes", "crates/agent_egress", "crates/agent_fold",
"crates/agent_harness",
"crates/agent_inmem",
"crates/agent_runtime_protocol", "crates/agent_session",
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index 91d19d406e..eb48026d44 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -913,6 +913,11 @@ if (LOCAL_ONLY) {
lazy(() => import('@app/features/block-agent/debug/replay/Replay'))
);
+ registerComponent(
+ 'agent-changes-ui',
+ lazy(() => import('@app/features/agent-changes/debug/Gallery'))
+ );
+
registerComponent(
'linked-conversation',
withAuth(lazy(() => import('@core/linked-conversation/debug/Demo')))
diff --git a/apps/web/src/features/agent-changes/README.md b/apps/web/src/features/agent-changes/README.md
new file mode 100644
index 0000000000..b1c011e1ff
--- /dev/null
+++ b/apps/web/src/features/agent-changes/README.md
@@ -0,0 +1,22 @@
+# Pull request diff viewer
+
+`agent-changes.tsx` wires the viewer into agent sessions. The controller and views
+can also be mounted by a PR external entity without an `AgentSessionProvider`.
+
+A host supplies `ChangesSource` and `ChangesHost` from
+`context/agent-changes-context.ts`, creates a controller with `createAgentChanges`,
+and mounts `AgentChangesControllerProvider` around `ChangesPane` or
+`AgentChangesSplit`. Give each host a stable `scopeKey` (for example,
+`pr:<foreign-entity-id>`) to isolate its locally persisted collapse state and notes.
+The optional `agent` capability enables inline note creation and sending; omit it
+for a read-only PR viewer. Clipboard, external navigation, and notifications are
+host callbacks.
+
+The source owns fetching, cache identity, and conversion into the feature's core
+changeset types. A PR entity adapter should resolve its GitHub owner/repository/PR
+number and implement this same contract using shared queries. It does not need to
+construct an agent session. That adapter and its backend endpoint are not yet wired.
+
+Layout and diff style are controlled accessor/setter pairs. Hosts using the app
+router can use `url-diff-state.ts`; embedded viewers can provide local signals.
+The URL codec supports namespaced ids and preserves neighboring viewer entries.
diff --git a/apps/web/src/features/agent-changes/agent-changes.tsx b/apps/web/src/features/agent-changes/agent-changes.tsx
new file mode 100644
index 0000000000..22907db039
--- /dev/null
+++ b/apps/web/src/features/agent-changes/agent-changes.tsx
@@ -0,0 +1,80 @@
+/**
+ * Production entry point for the Changes pane.
+ *
+ * Builds the controller from the real adapters: the agent-harness changes
+ * queries, and the surrounding agent-session block for posting prompts and
+ * reading the linked pull request. Hosts mount `AgentChangesProvider`
+ * inside `AgentSessionProvider`, then place the split, the toggle, the
+ * hand-off card, and the notes chip where they belong.
+ */
+
+import { toast } from '@core/component/Toast/Toast';
+import { openExternalUrl } from '@core/util/url';
+import { createSignal, type ParentProps } from 'solid-js';
+import { useAgentSession } from '../block-agent/context/AgentSessionContext';
+import type { ChangesHost } from './context/agent-changes-context';
+import { AgentChangesControllerProvider } from './context/agent-changes-controller';
+import { createAgentChanges } from './primitives/create-agent-changes';
+import { createSessionChangesSource } from './queries/session-changes';
+import { createUrlDiffState } from './url-diff-state';
+
+export { AgentChangesSplit } from './views/AgentChangesSplit';
+export {
+ ChangesHandoff,
+ ChangesToggle,
+ ReviewNotesDock,
+} from './views/SessionChangesControls';
+
+async function copyText(text: string): Promise<boolean> {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function AgentChangesProvider(props: ParentProps) {
+ const session = useAgentSession();
+ const source = createSessionChangesSource(session.sessionId);
+ const sendPrompt = async (markdown: string) => {
+ try {
+ const result = await session.issue({ type: 'prompt', prompt: markdown });
+ if (!result || result.isErr()) {
+ toast.failure('The review notes could not be sent');
+ }
+ } catch {
+ toast.failure('The review notes could not be sent');
+ }
+ };
+ const host: ChangesHost = {
+ scopeKey: session.sessionId,
+ agent: {
+ send: (markdown) => void sendPrompt(markdown),
+ canSend: () =>
+ session.sessionId() !== undefined &&
+ !session.loadFailed() &&
+ (session.session()?.canEdit ?? true),
+ },
+ pullRequestUrl: () => session.session()?.pullRequestUrl ?? undefined,
+ openExternal: openExternalUrl,
+ copyText,
+ notify: (message, tone) => {
+ if (tone === 'success') toast.success(message);
+ else toast.failure(message);
+ },
+ };
+ const urlState = createUrlDiffState(session.sessionId);
+ const [dismissed, setDismissed] = createSignal<string>();
+ const controller = createAgentChanges({
+ context: { source, host },
+ paneLayout: [urlState.layout, urlState.setLayout],
+ diffStyle: [urlState.diffStyle, urlState.setDiffStyle],
+ dismissed: [dismissed, (id) => setDismissed(id)],
+ });
+ return (
+ <AgentChangesControllerProvider value={controller}>
+ {props.children}
+ </AgentChangesControllerProvider>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/ChangesHeader.tsx b/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
new file mode 100644
index 0000000000..28e5329e30
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/ChangesHeader.tsx
@@ -0,0 +1,117 @@
+import ArrowLeftIcon from '@phosphor/arrow-left.svg';
+import ArrowsClockwiseIcon from '@phosphor/arrows-clockwise.svg';
+import ArrowsInSimpleIcon from '@phosphor/arrows-in-simple.svg';
+import ArrowsOutSimpleIcon from '@phosphor/arrows-out-simple.svg';
+import GitBranchIcon from '@phosphor/git-branch.svg';
+import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
+import XIcon from '@phosphor/x.svg';
+import { Button, cn, SegmentedControl } from '@ui';
+import { Show } from 'solid-js';
+import { pullRequestNumber } from '../core/pull-request';
+
+export type DiffStyleValue = 'unified' | 'split';
+
+export function ChangesHeader(props: {
+ /** The pane fills the width; the session is off screen. */
+ spotlit: boolean;
+ /** `head → base`, when known. */
+ range: string | undefined;
+ diffStyle: DiffStyleValue;
+ onDiffStyle: (style: DiffStyleValue) => void;
+ /** The linked pull request, opened by the header action. */
+ pullRequestUrl: string | undefined;
+ onViewPullRequest: () => void;
+ refreshing: boolean;
+ onRefresh: () => void;
+ onBack: () => void;
+ onSpotlight: () => void;
+ onClose: () => void;
+}) {
+ const pill = () => {
+ const url = props.pullRequestUrl;
+ const number = url ? pullRequestNumber(url) : undefined;
+ if (!props.range) return undefined;
+ return number ? `#${number} · ${props.range}` : props.range;
+ };
+ return (
+ <header class="flex h-12 shrink-0 items-center gap-1.5 border-b border-edge pr-2 pl-2.5">
+ <Show when={props.spotlit}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Bring the session back"
+ onClick={() => props.onBack()}
+ >
+ <ArrowLeftIcon />
+ </Button>
+ </Show>
+ <div class="flex min-w-0 items-center gap-1.5">
+ <GitBranchIcon class="size-4 shrink-0 text-ink-subtle" />
+ <h2 class="truncate text-sm font-semibold text-ink">Changes</h2>
+ </div>
+ <Show when={pill()}>
+ {(text) => (
+ <span
+ class="inline-flex h-5.5 max-w-64 items-center truncate rounded-full border border-edge-muted px-2 font-mono text-[11px] text-ink-subtle max-lg:hidden"
+ title={text()}
+ >
+ {text()}
+ </span>
+ )}
+ </Show>
+ <span class="flex-1" />
+ <SegmentedControl
+ size="sm"
+ aria-label="Diff layout"
+ value={props.diffStyle}
+ options={[
+ { value: 'unified', label: 'Unified' },
+ { value: 'split', label: 'Split' },
+ ]}
+ onChange={props.onDiffStyle}
+ class="max-md:hidden"
+ />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Refresh pull request changes"
+ disabled={props.refreshing}
+ onClick={() => props.onRefresh()}
+ >
+ <ArrowsClockwiseIcon class={cn(props.refreshing && 'animate-spin')} />
+ </Button>
+ <Show when={props.pullRequestUrl}>
+ <Button
+ variant="outline"
+ size="sm"
+ class="gap-1.5"
+ onClick={props.onViewPullRequest}
+ >
+ <GitPullRequestIcon class="size-3.5" />
+ <span>View pull request</span>
+ </Button>
+ </Show>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-pressed={props.spotlit}
+ tooltip={
+ props.spotlit
+ ? 'Back to the split'
+ : 'Expand changes to the full width'
+ }
+ onClick={() => props.onSpotlight()}
+ >
+ {props.spotlit ? <ArrowsInSimpleIcon /> : <ArrowsOutSimpleIcon />}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Close the changes pane"
+ onClick={() => props.onClose()}
+ >
+ <XIcon />
+ </Button>
+ </header>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/ChangesNotice.tsx b/apps/web/src/features/agent-changes/components/ChangesNotice.tsx
new file mode 100644
index 0000000000..f8b441e671
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/ChangesNotice.tsx
@@ -0,0 +1,83 @@
+import ArrowsClockwiseIcon from '@phosphor/arrows-clockwise.svg';
+import CircleNotchIcon from '@phosphor/circle-notch.svg';
+import GitBranchIcon from '@phosphor/git-branch.svg';
+import WarningCircleIcon from '@phosphor/warning-circle.svg';
+import { Button } from '@ui';
+import { type JSX, Show } from 'solid-js';
+
+/** A full-pane message for the states with nothing to diff. */
+export function ChangesNotice(props: {
+ icon?: JSX.Element;
+ title: string;
+ detail?: string;
+ /** Show the retry action. */
+ onRefresh?: () => void;
+ refreshing?: boolean;
+}) {
+ return (
+ <div class="flex flex-1 flex-col items-center justify-center gap-2 px-6 py-10 text-center">
+ <span class="text-ink-placeholder [&>svg]:size-6">
+ {props.icon ?? <GitBranchIcon />}
+ </span>
+ <p class="text-sm font-medium text-ink">{props.title}</p>
+ <Show when={props.detail}>
+ <p class="max-w-sm text-xs leading-relaxed text-ink-muted">
+ {props.detail}
+ </p>
+ </Show>
+ <Show when={props.onRefresh}>
+ <Button
+ variant="outline"
+ size="sm"
+ class="mt-2 gap-1.5"
+ disabled={props.refreshing}
+ onClick={() => props.onRefresh?.()}
+ >
+ <ArrowsClockwiseIcon
+ class={props.refreshing ? 'animate-spin' : undefined}
+ />
+ <span>Refresh changes</span>
+ </Button>
+ </Show>
+ </div>
+ );
+}
+
+/** A thin strip over the diff stack while a capture runs or after one failed. */
+export function CaptureBanner(props: {
+ tone: 'progress' | 'failure';
+ text: string;
+ onRefresh?: () => void;
+ refreshing?: boolean;
+}) {
+ return (
+ <div
+ class={
+ props.tone === 'failure'
+ ? 'flex shrink-0 items-center gap-2 border-b border-edge-muted bg-failure-bg px-3 py-1.5 text-xs text-failure'
+ : 'flex shrink-0 items-center gap-2 border-b border-edge-muted bg-accent-bg px-3 py-1.5 text-xs text-accent'
+ }
+ role="status"
+ >
+ {props.tone === 'failure' ? (
+ <WarningCircleIcon class="size-3.5 shrink-0" />
+ ) : (
+ <CircleNotchIcon class="size-3.5 shrink-0 animate-spin" />
+ )}
+ <span class="min-w-0 flex-1 truncate" title={props.text}>
+ {props.text}
+ </span>
+ <Show when={props.onRefresh}>
+ <Button
+ variant="ghost"
+ size="xs"
+ class="text-current"
+ disabled={props.refreshing}
+ onClick={() => props.onRefresh?.()}
+ >
+ Try again
+ </Button>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx b/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx
new file mode 100644
index 0000000000..8d4942aa4e
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/ChangesReadyCard.tsx
@@ -0,0 +1,75 @@
+import GitBranchIcon from '@phosphor/git-branch.svg';
+import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
+import RowsIcon from '@phosphor/rows.svg';
+import XIcon from '@phosphor/x.svg';
+import { Button } from '@ui';
+import { Show } from 'solid-js';
+import { describeFileCount } from '../core/changeset';
+import { pullRequestNumber } from '../core/pull-request';
+import { DiffCounts } from './DiffCounts';
+
+/** The transcript's hand-off card into the Changes pane. */
+export function ChangesReadyCard(props: {
+ fileCount: number;
+ additions: number;
+ deletions: number;
+ linkedUrl: string | undefined;
+ onReview: () => void;
+ onViewPullRequest: () => void;
+ onDismiss: () => void;
+}) {
+ const linkedNumber = () =>
+ props.linkedUrl ? pullRequestNumber(props.linkedUrl) : undefined;
+ return (
+ <section
+ class="flex flex-col gap-2.5 rounded-xl bg-surface-1 p-3 shadow-[inset_0_0_0_1px_var(--color-edge-muted)]"
+ aria-label="Changes ready to review"
+ >
+ <div class="flex items-center gap-2">
+ <GitBranchIcon class="size-4 shrink-0 text-accent" />
+ <span class="text-[12.5px] font-semibold text-ink">
+ Changes ready to review
+ </span>
+ <span class="flex-1" />
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ tooltip="Dismiss"
+ onClick={() => props.onDismiss()}
+ >
+ <XIcon />
+ </Button>
+ </div>
+ <div class="flex items-center gap-2 font-mono text-[11px] text-ink-placeholder">
+ <span>{describeFileCount(props.fileCount)}</span>
+ <DiffCounts additions={props.additions} deletions={props.deletions} />
+ </div>
+ <div class="flex flex-wrap gap-1.5">
+ <Button
+ variant="outline"
+ size="sm"
+ class="gap-1.5"
+ onClick={() => props.onReview()}
+ >
+ <RowsIcon class="size-3.5" />
+ <span>Review changes</span>
+ </Button>
+ <Show when={props.linkedUrl}>
+ <Button
+ variant="outline"
+ size="sm"
+ class="gap-1.5"
+ onClick={props.onViewPullRequest}
+ >
+ <GitPullRequestIcon class="size-3.5" />
+ <span>
+ {linkedNumber()
+ ? `Pull request #${linkedNumber()}`
+ : 'Pull request'}
+ </span>
+ </Button>
+ </Show>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
new file mode 100644
index 0000000000..0657df05b3
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/ChangesToggleButton.tsx
@@ -0,0 +1,30 @@
+import SquareSplitHorizontalIcon from '@phosphor/square-split-horizontal.svg';
+import { Button, cn } from '@ui';
+import { DiffCounts } from './DiffCounts';
+
+/** Opens the changes pane and summarizes its added/deleted lines. */
+export function ChangesToggleButton(props: {
+ open: boolean;
+ additions: number;
+ deletions: number;
+ /** A capture is running, so the counts may move. */
+ capturing?: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <Button
+ variant="outline"
+ size="sm"
+ aria-pressed={props.open}
+ tooltip={props.open ? 'Hide the changes pane' : 'Show the changes pane'}
+ class={cn('gap-1.5 pr-1.5', props.open && 'bg-active text-ink')}
+ onClick={() => props.onToggle()}
+ >
+ <SquareSplitHorizontalIcon class="size-3.5" />
+ <span>Changes</span>
+ <span class={cn('text-xs', props.capturing && 'animate-pulse')}>
+ <DiffCounts additions={props.additions} deletions={props.deletions} />
+ </span>
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/DiffCounts.tsx b/apps/web/src/features/agent-changes/components/DiffCounts.tsx
new file mode 100644
index 0000000000..d1dec335fb
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/DiffCounts.tsx
@@ -0,0 +1,9 @@
+/** Numeric line totals shared by the viewer and its entry controls. */
+export function DiffCounts(props: { additions: number; deletions: number }) {
+ return (
+ <span class="inline-flex shrink-0 items-center gap-2 font-mono tabular-nums">
+ <span class="text-success">{`+${props.additions}`}</span>
+ <span class="text-failure">{`−${props.deletions}`}</span>
+ </span>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/FileCard.tsx b/apps/web/src/features/agent-changes/components/FileCard.tsx
new file mode 100644
index 0000000000..1032a243e3
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/FileCard.tsx
@@ -0,0 +1,129 @@
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import { Button, cn } from '@ui';
+import { type JSX, Show } from 'solid-js';
+import { splitPath } from '../core/changeset';
+import type { FileDiffEntry } from '../core/patch';
+import { DiffCounts } from './DiffCounts';
+import { StatusLetter } from './StatusLetter';
+
+/** Plain note shown in place of a diff body. */
+export function DiffNote(props: { children: JSX.Element }) {
+ return (
+ <div class="px-3 py-2.5 font-mono text-xs text-ink-placeholder">
+ {props.children}
+ </div>
+ );
+}
+
+/**
+ * One file in the stack: a sticky header with the review controls, and the
+ * diff (or a note about why there is none) beneath it.
+ */
+export function FileCard(props: {
+ entry: FileDiffEntry;
+ collapsed: boolean;
+ /** Briefly highlighted after the tree jumped here. */
+ flash: boolean;
+ onToggleCollapsed: () => void;
+ onCopyPath: () => void;
+ /** The diff body, supplied by the view so this card stays presentational. */
+ body: JSX.Element;
+ ref?: (element: HTMLElement) => void;
+}) {
+ const file = () => props.entry.file;
+ const path = () => splitPath(file().path);
+ const hidden = () =>
+ `${file().additions} ${file().additions === 1 ? 'addition' : 'additions'}, ${file().deletions} ${file().deletions === 1 ? 'deletion' : 'deletions'} hidden`;
+ return (
+ <article
+ ref={props.ref}
+ class={cn(
+ 'scroll-mt-2 shrink-0 overflow-hidden rounded-lg border border-edge-muted bg-surface transition-shadow',
+ props.flash && 'border-accent shadow-[0_0_0_3px_var(--color-selected)]'
+ )}
+ data-path={file().path}
+ >
+ <header class="sticky top-0 z-5 flex min-h-8.5 items-center gap-2 border-b border-edge-muted bg-surface-1 pr-2">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ class="ml-1"
+ aria-expanded={!props.collapsed}
+ aria-label={`${props.collapsed ? 'Show' : 'Hide'} ${path().base}`}
+ tooltip={props.collapsed ? 'Show this diff' : 'Hide this diff'}
+ onClick={() => props.onToggleCollapsed()}
+ >
+ <CaretRightIcon
+ class={cn(
+ 'transition-transform duration-100 motion-reduce:transition-none',
+ !props.collapsed && 'rotate-90'
+ )}
+ />
+ </Button>
+ <button
+ type="button"
+ class="flex min-w-0 flex-1 items-center gap-1.5 py-1.5 pr-1 text-left text-ink-muted hover:text-ink"
+ aria-expanded={!props.collapsed}
+ title={file().path}
+ onClick={() => props.onToggleCollapsed()}
+ >
+ <StatusLetter kind={file().kind} />
+ <span class="flex min-w-0 items-baseline font-mono text-[11.5px]">
+ <Show when={file().previousPath}>
+ {(previous) => (
+ <span class="truncate text-ink-placeholder">
+ {previous()}
+ <span class="px-1">→</span>
+ </span>
+ )}
+ </Show>
+ <span class="min-w-0 shrink truncate text-ink-placeholder">
+ {path().dir}
+ </span>
+ <span class="max-w-full shrink-0 truncate font-medium text-ink">
+ {path().base}
+ </span>
+ </span>
+ </button>
+ <span class="flex shrink-0 items-center gap-2 text-[11px]">
+ <DiffCounts
+ additions={file().additions}
+ deletions={file().deletions}
+ />
+ </span>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ tooltip="Copy path"
+ onClick={() => props.onCopyPath()}
+ >
+ <CopyIcon />
+ </Button>
+ </header>
+ <Show
+ when={!props.collapsed}
+ fallback={
+ <button
+ type="button"
+ class="flex w-full items-center gap-2 px-3 py-2.5 text-left font-mono text-[11.5px] text-ink-placeholder hover:bg-hover hover:text-ink-muted"
+ onClick={() => props.onToggleCollapsed()}
+ >
+ <CaretRightIcon class="size-3" />
+ <span class="font-sans font-medium text-ink-muted">
+ {props.entry.note ? 'Show' : 'Show diff'}
+ </span>
+ <span class="flex-1">{props.entry.note ?? hidden()}</span>
+ </button>
+ }
+ >
+ <Show
+ when={!props.entry.note}
+ fallback={<DiffNote>{props.entry.note}</DiffNote>}
+ >
+ {props.body}
+ </Show>
+ </Show>
+ </article>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/FileTree.tsx b/apps/web/src/features/agent-changes/components/FileTree.tsx
new file mode 100644
index 0000000000..8437b542c5
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/FileTree.tsx
@@ -0,0 +1,106 @@
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import { cn } from '@ui';
+import { createSignal, For, Show } from 'solid-js';
+import { describeFileCount } from '../core/changeset';
+import type { FileTreeDir, FileTreeNode } from '../core/file-tree';
+import { DiffCounts } from './DiffCounts';
+import { StatusLetter } from './StatusLetter';
+
+export type FileTreeProps = {
+ nodes: FileTreeNode[];
+ fileCount: number;
+ active: string | undefined;
+ onSelect: (path: string) => void;
+};
+
+function DirRow(props: {
+ dir: FileTreeDir;
+ active: string | undefined;
+ onSelect: (path: string) => void;
+}) {
+ const [open, setOpen] = createSignal(true);
+ return (
+ <>
+ <button
+ type="button"
+ class="flex min-h-6 w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-ink-placeholder hover:bg-hover"
+ aria-expanded={open()}
+ onClick={() => setOpen((value) => !value)}
+ >
+ <CaretRightIcon
+ class={cn(
+ 'size-3 shrink-0 transition-transform duration-100 motion-reduce:transition-none',
+ open() && 'rotate-90'
+ )}
+ />
+ <span class="min-w-0 flex-1 truncate font-mono text-[11px]">
+ {props.dir.name}
+ </span>
+ </button>
+ <Show when={open()}>
+ <div class="ml-[7px] flex flex-col gap-px border-l border-edge-muted pl-2.5">
+ <Rows
+ nodes={props.dir.children}
+ active={props.active}
+ onSelect={props.onSelect}
+ />
+ </div>
+ </Show>
+ </>
+ );
+}
+
+function Rows(props: {
+ nodes: FileTreeNode[];
+ active: string | undefined;
+ onSelect: (path: string) => void;
+}) {
+ return (
+ <For each={props.nodes}>
+ {(node) =>
+ node.kind === 'dir' ? (
+ <DirRow dir={node} active={props.active} onSelect={props.onSelect} />
+ ) : (
+ <button
+ type="button"
+ class={cn(
+ 'flex min-h-6 w-full items-center gap-1.5 rounded-md px-1.5 py-0.5 text-left text-xs text-ink-muted hover:bg-hover',
+ props.active === node.file.path && 'bg-selected text-ink'
+ )}
+ aria-current={props.active === node.file.path ? 'true' : undefined}
+ title={node.file.path}
+ onClick={() => props.onSelect(node.file.path)}
+ >
+ <StatusLetter kind={node.file.kind} />
+ <span class="min-w-0 flex-1 truncate font-mono text-[11.5px]">
+ {node.name}
+ </span>
+ <DiffCounts
+ additions={node.file.additions}
+ deletions={node.file.deletions}
+ />
+ </button>
+ )
+ }
+ </For>
+ );
+}
+
+/** The changed files, grouped by compressed directory, in patch order. */
+export function FileTree(props: FileTreeProps) {
+ return (
+ <nav
+ class="flex w-58 shrink-0 flex-col gap-px overflow-y-auto border-r border-edge-muted px-1.5 pt-2 pb-4 max-md:w-44"
+ aria-label="Changed files"
+ >
+ <div class="flex items-center gap-1.5 px-1.5 pt-0.5 pb-1.5 text-[10px] tracking-[0.07em] text-ink-placeholder uppercase">
+ <span class="flex-1">{describeFileCount(props.fileCount)}</span>
+ </div>
+ <Rows
+ nodes={props.nodes}
+ active={props.active}
+ onSelect={props.onSelect}
+ />
+ </nav>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx b/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx
new file mode 100644
index 0000000000..bcd0ec514a
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/NoteAnnotation.tsx
@@ -0,0 +1,120 @@
+import NoteIcon from '@phosphor/note.svg';
+import XIcon from '@phosphor/x.svg';
+import { Button, cn } from '@ui';
+import { createSignal, For, onMount, Show } from 'solid-js';
+import type { NoteAnchor, ReviewNote } from '../core/review-notes';
+
+/** The editor for a new note on one line. */
+function NoteEditor(props: {
+ anchor: NoteAnchor;
+ onAdd: (anchor: NoteAnchor, text: string) => void;
+ onCancel: () => void;
+}) {
+ const [text, setText] = createSignal('');
+ let textarea!: HTMLTextAreaElement;
+ onMount(() => textarea.focus());
+ const add = () => props.onAdd(props.anchor, text());
+ return (
+ <div class="flex flex-col gap-1.5">
+ <textarea
+ ref={textarea}
+ class="min-h-13 w-full resize-y rounded-md border border-edge bg-input px-2 py-1.5 font-sans text-xs text-ink outline-none placeholder:text-ink-placeholder focus:border-input-focus"
+ placeholder="What should the agent change here?"
+ aria-label="Review note"
+ value={text()}
+ onInput={(event) => setText(event.currentTarget.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ props.onCancel();
+ } else if (
+ event.key === 'Enter' &&
+ (event.metaKey || event.ctrlKey)
+ ) {
+ event.preventDefault();
+ add();
+ }
+ }}
+ />
+ <div class="flex items-center gap-1.5">
+ <Button
+ variant="cta"
+ size="xs"
+ class="h-6.5 px-2.5"
+ disabled={text().trim() === ''}
+ onClick={add}
+ >
+ Add note
+ </Button>
+ <Button
+ variant="outline"
+ size="xs"
+ class="h-6.5 px-2.5"
+ onClick={() => props.onCancel()}
+ >
+ Cancel
+ </Button>
+ <span class="flex-1" />
+ <span class="text-[11px] text-ink-placeholder">
+ Notes go to the agent, not to GitHub.
+ </span>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * What hangs under an annotated line: the notes already left there, and the
+ * editor when the reviewer is writing another.
+ */
+export function NoteAnnotation(props: {
+ notes: ReviewNote[];
+ composing: NoteAnchor | undefined;
+ onAdd: (anchor: NoteAnchor, text: string) => void;
+ onCancel: () => void;
+ onRemove: (id: string) => void;
+}) {
+ return (
+ <div class="flex flex-col gap-2 border-y border-edge-muted bg-surface-1 py-2 pr-2.5 pl-8 font-sans text-xs leading-normal text-ink-muted">
+ <For each={props.notes}>
+ {(note) => (
+ <div class="flex items-start gap-2">
+ <span class="mt-0.5 grid size-5 shrink-0 place-items-center rounded-full bg-violet text-accent-contrast">
+ <NoteIcon class="size-3" />
+ </span>
+ <span class="min-w-0 flex-1 whitespace-pre-wrap wrap-break-word">
+ {note.text}
+ <span
+ class={cn(
+ 'ml-1 text-[11px]',
+ note.sentAt ? 'text-ink-placeholder' : 'text-accent'
+ )}
+ >
+ · {note.sentAt ? 'sent to agent' : 'queued for the agent'}
+ </span>
+ </span>
+ <Show when={!note.sentAt}>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ tooltip="Remove note"
+ onClick={() => props.onRemove(note.id)}
+ >
+ <XIcon />
+ </Button>
+ </Show>
+ </div>
+ )}
+ </For>
+ <Show when={props.composing}>
+ {(anchor) => (
+ <NoteEditor
+ anchor={anchor()}
+ onAdd={props.onAdd}
+ onCancel={props.onCancel}
+ />
+ )}
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/PierreFileDiff.tsx b/apps/web/src/features/agent-changes/components/PierreFileDiff.tsx
new file mode 100644
index 0000000000..276d734edf
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/PierreFileDiff.tsx
@@ -0,0 +1,209 @@
+/**
+ * One file's diff rendered by Pierre's vanilla `FileDiff`, with Macro's
+ * review notes hung under their lines and Pierre's gutter utility (the "+"
+ * that appears on hover, draggable over a range) to leave one.
+ *
+ * Pierre renders inside a shadow root but slots annotation content from
+ * the light DOM, so the note UI here is ordinary Solid markup mounted with
+ * `render` into the elements Pierre asks for.
+ */
+
+import {
+ type DiffLineAnnotation,
+ FileDiff,
+ type FileDiffMetadata,
+ type FileDiffOptions,
+ type SelectedLineRange,
+} from '@pierre/diffs';
+import {
+ createEffect,
+ createMemo,
+ type JSX,
+ on,
+ onCleanup,
+ onMount,
+} from 'solid-js';
+import { render } from 'solid-js/web';
+import type { NoteAnchor, ReviewNote } from '../core/review-notes';
+import { NoteAnnotation } from './NoteAnnotation';
+
+export type DiffStyleValue = 'unified' | 'split';
+
+/** Options that never change for the pane's diffs. */
+const BASE_OPTIONS = {
+ diffIndicators: 'bars',
+ // The file card renders its own header.
+ disableFileHeader: true,
+ overflow: 'wrap',
+ hunkSeparators: 'line-info-basic',
+ lineDiffType: 'word-alt',
+ expansionLineCount: 20,
+ lineHoverHighlight: 'line',
+} satisfies FileDiffOptions<string>;
+
+/**
+ * CSS variables Pierre reads inside its shadow DOM, pointed at Macro's
+ * typography tokens so the diff matches the surrounding mono text.
+ */
+const DIFF_STYLE_VARIABLES: JSX.CSSProperties = {
+ '--diffs-font-family': 'var(--font-mono)',
+ '--diffs-font-size': '0.75rem',
+ '--diffs-line-height': '18px',
+ '--diffs-tab-size': '2',
+ '--diffs-gap-block': '0',
+ '--diffs-min-number-column-width': '4ch',
+};
+
+/** One annotation per annotated line: the anchor the notes hang from. */
+function annotationKey(side: NoteAnchor['side'], lineNumber: number): string {
+ return `${side}:${lineNumber}`;
+}
+
+export function PierreFileDiff(props: {
+ path: string;
+ diff: FileDiffMetadata;
+ diffStyle: DiffStyleValue;
+ themeType: 'light' | 'dark';
+ notes: ReviewNote[];
+ composing: NoteAnchor | undefined;
+ onOpenNote?: (anchor: NoteAnchor) => void;
+ onCancelNote: () => void;
+ onAddNote: (anchor: NoteAnchor, text: string) => void;
+ onRemoveNote: (id: string) => void;
+}) {
+ let container!: HTMLDivElement;
+ let instance: FileDiff<string> | undefined;
+ const roots = new Map<string, () => void>();
+
+ const disposeRoots = () => {
+ for (const dispose of roots.values()) dispose();
+ roots.clear();
+ };
+
+ // Notes hang from the last line of their range, like GitHub's review
+ // comments; the editor for a new note does the same.
+ const annotations = createMemo((): DiffLineAnnotation<string>[] => {
+ const keys = new Map<string, DiffLineAnnotation<string>>();
+ const add = (side: NoteAnchor['side'], lineNumber: number) => {
+ const key = annotationKey(side, lineNumber);
+ if (!keys.has(key)) keys.set(key, { side, lineNumber, metadata: key });
+ };
+ for (const note of props.notes) add(note.side, note.endLineNumber);
+ const composing = props.composing;
+ if (composing) add(composing.side, composing.endLineNumber);
+ return [...keys.values()].sort(
+ (a, b) => a.lineNumber - b.lineNumber || a.side.localeCompare(b.side)
+ );
+ });
+
+ const notesAt = (key: string) =>
+ props.notes.filter(
+ (note) => annotationKey(note.side, note.endLineNumber) === key
+ );
+ const composingAt = (key: string) => {
+ const composing = props.composing;
+ return composing &&
+ annotationKey(composing.side, composing.endLineNumber) === key
+ ? composing
+ : undefined;
+ };
+
+ const renderAnnotation = (annotation: DiffLineAnnotation<string>) => {
+ const key = annotation.metadata;
+ roots.get(key)?.();
+ const element = document.createElement('div');
+ roots.set(
+ key,
+ render(
+ () => (
+ <NoteAnnotation
+ notes={notesAt(key)}
+ composing={composingAt(key)}
+ onAdd={props.onAddNote}
+ onCancel={props.onCancelNote}
+ onRemove={props.onRemoveNote}
+ />
+ ),
+ element
+ )
+ );
+ return element;
+ };
+
+ const onGutterUtilityClick = (range: SelectedLineRange) => {
+ props.onOpenNote?.({
+ path: props.path,
+ side: range.side ?? 'additions',
+ lineNumber: Math.min(range.start, range.end),
+ endLineNumber: Math.max(range.start, range.end),
+ });
+ };
+
+ const currentOptions = (): FileDiffOptions<string> => ({
+ ...BASE_OPTIONS,
+ diffStyle: props.diffStyle,
+ themeType: props.themeType,
+ renderAnnotation,
+ enableGutterUtility: props.onOpenNote !== undefined,
+ onGutterUtilityClick: props.onOpenNote ? onGutterUtilityClick : undefined,
+ });
+
+ onMount(() => {
+ instance = new FileDiff<string>(currentOptions());
+ });
+
+ // A new diff or layout re-renders from scratch; a change to the notes
+ // re-renders too, since Pierre only stores annotations handed to
+ // `setLineAnnotations` and paints them on the next render. Elements for
+ // unchanged annotations are kept across renders. A layout change must be
+ // forced: Pierre otherwise treats unchanged content as a partial render.
+ createEffect(
+ on(
+ [() => props.diff, () => props.diffStyle, annotations],
+ ([diff, diffStyle, list], previous) => {
+ if (!instance) return;
+ instance.setOptions(currentOptions());
+ instance.render({
+ fileDiff: diff,
+ containerWrapper: container,
+ lineAnnotations: list,
+ forceRender: previous !== undefined && previous[1] !== diffStyle,
+ });
+ }
+ )
+ );
+
+ // Pierre keeps the gutter selection lit while the note editor is open;
+ // adding or cancelling the note lets the line go.
+ createEffect(
+ on(
+ () => props.composing,
+ (composing) => {
+ if (!composing) instance?.setSelectedLines(null);
+ },
+ { defer: true }
+ )
+ );
+
+ createEffect(
+ on(
+ () => props.themeType,
+ (themeType) => instance?.setThemeType(themeType),
+ { defer: true }
+ )
+ );
+
+ onCleanup(() => {
+ disposeRoots();
+ instance?.cleanUp();
+ instance = undefined;
+ });
+
+ return (
+ <div
+ ref={container}
+ class="overflow-hidden bg-surface"
+ style={DIFF_STYLE_VARIABLES}
+ />
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/ReviewBar.tsx b/apps/web/src/features/agent-changes/components/ReviewBar.tsx
new file mode 100644
index 0000000000..d688e46753
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/ReviewBar.tsx
@@ -0,0 +1,33 @@
+import ArrowsInSimpleIcon from '@phosphor/arrows-in-simple.svg';
+import ArrowsOutSimpleIcon from '@phosphor/arrows-out-simple.svg';
+import { Button } from '@ui';
+
+/** Bulk collapse and expand controls for the file diffs. */
+export function ReviewBar(props: {
+ anyExpanded: boolean;
+ onToggleCollapsed: () => void;
+}) {
+ return (
+ <div class="flex shrink-0 flex-wrap items-center gap-2.5 border-b border-edge-muted bg-surface-1 py-1.5 pr-2 pl-3">
+ <span class="flex-1" />
+ <Button
+ variant="outline"
+ size="xs"
+ class="h-6.5 gap-1.5 px-2 text-[11.5px]"
+ tooltip={
+ props.anyExpanded
+ ? 'Hide every diff, keeping just the file headers'
+ : 'Show every diff again'
+ }
+ onClick={() => props.onToggleCollapsed()}
+ >
+ {props.anyExpanded ? (
+ <ArrowsInSimpleIcon class="size-3" />
+ ) : (
+ <ArrowsOutSimpleIcon class="size-3" />
+ )}
+ <span>{props.anyExpanded ? 'Collapse all' : 'Expand all'}</span>
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/ReviewNotesChip.tsx b/apps/web/src/features/agent-changes/components/ReviewNotesChip.tsx
new file mode 100644
index 0000000000..b0dab2da61
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/ReviewNotesChip.tsx
@@ -0,0 +1,31 @@
+import NoteIcon from '@phosphor/note.svg';
+import { Button } from '@ui';
+
+/** The composer-dock chip for notes that have not gone to the agent yet. */
+export function ReviewNotesChip(props: {
+ count: number;
+ disabled?: boolean;
+ onSend: () => void;
+}) {
+ return (
+ <div
+ class="flex items-center gap-2 rounded-[10px] bg-selected px-2.5 py-1.5 text-xs text-ink-muted shadow-[inset_0_0_0_1px_color-mix(in_oklch,var(--color-accent)_30%,transparent)]"
+ role="status"
+ >
+ <NoteIcon class="size-3.5 shrink-0" />
+ <span class="flex-1">
+ <b class="font-semibold tabular-nums">{props.count}</b>{' '}
+ {props.count === 1 ? 'review note' : 'review notes'} queued
+ </span>
+ <Button
+ variant="ghost"
+ size="xs"
+ class="h-6 px-2 text-[11.5px] text-ink"
+ disabled={props.disabled}
+ onClick={() => props.onSend()}
+ >
+ Send to agent
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/components/StatusLetter.tsx b/apps/web/src/features/agent-changes/components/StatusLetter.tsx
new file mode 100644
index 0000000000..f495bcb709
--- /dev/null
+++ b/apps/web/src/features/agent-changes/components/StatusLetter.tsx
@@ -0,0 +1,30 @@
+import { cn } from '@ui';
+import type { FileChangeKind } from '../core/changeset';
+import { statusLetter } from '../core/changeset';
+
+const LABELS: Record<FileChangeKind, string> = {
+ added: 'Added',
+ modified: 'Modified',
+ deleted: 'Deleted',
+ renamed: 'Renamed',
+};
+
+/** The one-letter change status, coloured like the diff it describes. */
+export function StatusLetter(props: { kind: FileChangeKind; class?: string }) {
+ return (
+ <span
+ class={cn(
+ 'w-3 shrink-0 text-center font-mono text-[10px] font-medium',
+ props.kind === 'added' && 'text-success',
+ props.kind === 'modified' && 'text-blue',
+ props.kind === 'deleted' && 'text-failure',
+ props.kind === 'renamed' && 'text-violet',
+ props.class
+ )}
+ aria-label={LABELS[props.kind]}
+ title={LABELS[props.kind]}
+ >
+ {statusLetter(props.kind)}
+ </span>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/context/agent-changes-context.ts b/apps/web/src/features/agent-changes/context/agent-changes-context.ts
new file mode 100644
index 0000000000..deab771a4e
--- /dev/null
+++ b/apps/web/src/features/agent-changes/context/agent-changes-context.ts
@@ -0,0 +1,62 @@
+/**
+ * The capabilities the Changes pane needs from its host, and the contract
+ * its views consume.
+ *
+ * Production wiring (`../agent-changes.tsx`) builds these from the real
+ * queries and the agent-session block; tests hand in fakes. Nothing under
+ * `queries/`, `primitives/`, `components/`, or `views/` imports app
+ * singletons directly.
+ */
+
+import type { Accessor } from 'solid-js';
+import type { SessionChanges } from '../core/changeset';
+
+export type QueryStatus = 'idle' | 'pending' | 'error' | 'success';
+
+/** A patch read for one changeset id, started and stopped by the caller. */
+export type PatchRead = {
+ text: Accessor<string | undefined>;
+ status: Accessor<QueryStatus>;
+ retry: () => void;
+};
+
+/** How the pane reads and refreshes a pull request snapshot. */
+export type ChangesSource = {
+ /** The latest summary; undefined until the first read lands. */
+ summary: Accessor<SessionChanges | undefined>;
+ summaryStatus: Accessor<QueryStatus>;
+ /**
+ * Read the patch behind a changeset. Runs only while `enabled` is true, so
+ * a closed pane never pulls the diff.
+ */
+ patch: (
+ changesetId: Accessor<string | undefined>,
+ enabled: Accessor<boolean>
+ ) => PatchRead;
+ /** Ask for a fresh capture. Resolves once the request is accepted. */
+ refresh: () => Promise<void>;
+};
+
+/** Optional review-note handoff supplied by an agent host. */
+export type ChangesAgent = {
+ send: (markdown: string) => void;
+ canSend: Accessor<boolean>;
+};
+
+/** Host capabilities, independent of whether the host is a session or PR. */
+export type ChangesHost = {
+ /** Stable identity for local review state; use a namespaced id for PR entities. */
+ scopeKey: Accessor<string | undefined>;
+ /** Omit for a read-only viewer without agent note controls. */
+ agent?: ChangesAgent;
+ /** The pull request represented by the source. */
+ pullRequestUrl: Accessor<string | undefined>;
+ openExternal: (url: string) => void;
+ copyText: (text: string) => Promise<boolean>;
+ notify: (message: string, tone: 'success' | 'failure') => void;
+};
+
+export type AgentChangesContext = {
+ source: ChangesSource;
+ host: ChangesHost;
+};
diff --git a/apps/web/src/features/agent-changes/context/agent-changes-controller.tsx b/apps/web/src/features/agent-changes/context/agent-changes-controller.tsx
new file mode 100644
index 0000000000..b0eba0c005
--- /dev/null
+++ b/apps/web/src/features/agent-changes/context/agent-changes-controller.tsx
@@ -0,0 +1,25 @@
+/**
+ * Transport for the built controller: the entry point constructs it, views
+ * read it. Missing provider setup fails clearly instead of reaching real
+ * services.
+ */
+
+import { createContext, useContext } from 'solid-js';
+import type { AgentChangesController } from '../primitives/create-agent-changes';
+
+const Context = createContext<AgentChangesController>();
+
+export const AgentChangesControllerProvider = Context.Provider;
+
+export function useAgentChanges(): AgentChangesController {
+ const controller = useContext(Context);
+ if (!controller) {
+ throw new Error('AgentChangesControllerProvider is required');
+ }
+ return controller;
+}
+
+/** The controller when a host mounted one; undefined outside the pane. */
+export function useOptionalAgentChanges(): AgentChangesController | undefined {
+ return useContext(Context);
+}
diff --git a/apps/web/src/features/agent-changes/core/changeset.test.ts b/apps/web/src/features/agent-changes/core/changeset.test.ts
new file mode 100644
index 0000000000..8701dc9cca
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/changeset.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from 'vitest';
+import {
+ type Changeset,
+ changesState,
+ describeRange,
+ repositorySlug,
+ splitPath,
+ statusLetter,
+} from './changeset';
+
+function changeset(overrides: Partial<Changeset> = {}): Changeset {
+ return {
+ id: 'cs-1',
+ repository: 'https://github.com/macro-inc/macro',
+ base: { name: 'main' },
+ head: { name: 'agent/unread-archived-sessions' },
+ files: [
+ {
+ path: 'a.ts',
+ kind: 'modified',
+ additions: 3,
+ deletions: 1,
+ binary: false,
+ patchOmitted: false,
+ },
+ ],
+ additions: 3,
+ deletions: 1,
+ patchBytes: 120,
+ truncated: false,
+ capturedAt: '2026-09-15T00:00:00Z',
+ ...overrides,
+ };
+}
+
+describe('statusLetter', () => {
+ it('maps every kind to its letter', () => {
+ expect(statusLetter('added')).toBe('A');
+ expect(statusLetter('modified')).toBe('M');
+ expect(statusLetter('deleted')).toBe('D');
+ expect(statusLetter('renamed')).toBe('R');
+ });
+});
+
+describe('splitPath', () => {
+ it('keeps the trailing slash on the directory', () => {
+ expect(splitPath('apps/web/src/a.ts')).toEqual({
+ dir: 'apps/web/src/',
+ base: 'a.ts',
+ });
+ });
+
+ it('treats a bare name as having no directory', () => {
+ expect(splitPath('README.md')).toEqual({ dir: '', base: 'README.md' });
+ });
+});
+
+describe('repositorySlug', () => {
+ it('reads owner/name from a GitHub url', () => {
+ expect(repositorySlug('https://github.com/macro-inc/macro')).toBe(
+ 'macro-inc/macro'
+ );
+ expect(repositorySlug('https://github.com/macro-inc/macro.git')).toBe(
+ 'macro-inc/macro'
+ );
+ });
+
+ it('is undefined for anything else', () => {
+ expect(repositorySlug(undefined)).toBeUndefined();
+ expect(repositorySlug('https://example.com/x/y')).toBeUndefined();
+ });
+});
+
+describe('describeRange', () => {
+ it('reads head → base', () => {
+ expect(describeRange(changeset())).toBe(
+ 'agent/unread-archived-sessions → main'
+ );
+ });
+
+ it('falls back to short shas and to one side', () => {
+ expect(
+ describeRange(
+ changeset({ base: { sha: 'abcdef1234567' }, head: { name: 'x' } })
+ )
+ ).toBe('x → abcdef1');
+ expect(describeRange(changeset({ base: {} }))).toBe(
+ 'agent/unread-archived-sessions'
+ );
+ });
+});
+
+describe('changesState', () => {
+ it('is loading without a summary, and failed when the read errored', () => {
+ expect(changesState(undefined)).toEqual({ kind: 'loading' });
+ expect(changesState(undefined, 'pending')).toEqual({ kind: 'loading' });
+ expect(changesState(undefined, 'error')).toEqual({ kind: 'load_error' });
+ });
+
+ it('shows a running capture over the previous changeset', () => {
+ const previous = changeset();
+ expect(changesState({ changeset: previous, capturing: true })).toEqual({
+ kind: 'capturing',
+ previous,
+ });
+ });
+
+ it('is ready with files and empty without', () => {
+ expect(
+ changesState({ changeset: changeset(), capturing: false }).kind
+ ).toBe('ready');
+ expect(
+ changesState({ changeset: changeset({ files: [] }), capturing: false })
+ .kind
+ ).toBe('empty');
+ });
+
+ it('keeps the last changeset when a later capture fails', () => {
+ const previous = changeset();
+ expect(
+ changesState({
+ changeset: previous,
+ attempt: {
+ startedAt: 't',
+ finishedAt: 't',
+ outcome: 'failed',
+ error: 'GitHub said no',
+ },
+ capturing: false,
+ })
+ ).toEqual({ kind: 'failed', message: 'GitHub said no', previous });
+ });
+
+ it('names not-ready outcomes', () => {
+ expect(
+ changesState({
+ attempt: { startedAt: 't', outcome: 'not_ready', error: 'No push yet' },
+ capturing: false,
+ })
+ ).toEqual({ kind: 'not_ready', message: 'No push yet' });
+ });
+
+ it('has nothing to say before the first attempt', () => {
+ expect(changesState({ capturing: false })).toEqual({ kind: 'none' });
+ });
+});
diff --git a/apps/web/src/features/agent-changes/core/changeset.ts b/apps/web/src/features/agent-changes/core/changeset.ts
new file mode 100644
index 0000000000..7893f46096
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/changeset.ts
@@ -0,0 +1,182 @@
+/**
+ * The vocabulary of a session's captured changes.
+ *
+ * Pure types and functions: what a changed file is, how a capture went, and
+ * the small derivations the pane shows (status letters, totals, path
+ * splitting). Wire decoding lives in `queries/`; rendering in `components/`.
+ */
+
+/** What happened to a file between the base and the head. */
+export type FileChangeKind = 'added' | 'modified' | 'deleted' | 'renamed';
+
+/** One changed file, as the summary reports it. */
+export type ChangedFile = {
+ /** The path after the change, or before it for a deletion. */
+ path: string;
+ /** Where a renamed file came from. */
+ previousPath?: string;
+ kind: FileChangeKind;
+ additions: number;
+ deletions: number;
+ /** The diff carries no text for this file. */
+ binary: boolean;
+ /** The file's hunks were left out of the patch to fit the size budget. */
+ patchOmitted: boolean;
+};
+
+/** A branch or commit on one side of the comparison. */
+export type GitRef = {
+ name?: string;
+ sha?: string;
+};
+
+/** One capture of a session's changes. */
+export type Changeset = {
+ /** Changes with every capture, so it doubles as a cache key for the patch. */
+ id: string;
+ /** `https://github.com/owner/name`, when known. */
+ repository?: string;
+ base: GitRef;
+ head: GitRef;
+ files: ChangedFile[];
+ additions: number;
+ deletions: number;
+ /** Zero when nothing changed. */
+ patchBytes: number;
+ /** Some files' hunks were left out of the patch. */
+ truncated: boolean;
+ capturedAt: string;
+};
+
+/** How the latest capture attempt ended. */
+export type CaptureOutcome = 'captured' | 'not_ready' | 'failed';
+
+/** The latest capture attempt, running or finished. */
+export type CaptureAttempt = {
+ startedAt: string;
+ finishedAt?: string;
+ outcome?: CaptureOutcome;
+ /** Why it did not capture, in a sentence the user can read. */
+ error?: string;
+};
+
+/** Everything the summary endpoint says about a session's changes. */
+export type SessionChanges = {
+ changeset?: Changeset;
+ attempt?: CaptureAttempt;
+ /** A capture is running right now. */
+ capturing: boolean;
+};
+
+/** The one-letter status the tree and file headers show. */
+export type StatusLetter = 'A' | 'M' | 'D' | 'R';
+
+export function statusLetter(kind: FileChangeKind): StatusLetter {
+ switch (kind) {
+ case 'added':
+ return 'A';
+ case 'modified':
+ return 'M';
+ case 'deleted':
+ return 'D';
+ case 'renamed':
+ return 'R';
+ }
+}
+
+/** A path split into the directory prefix (with trailing slash) and basename. */
+export function splitPath(path: string): { dir: string; base: string } {
+ const at = path.lastIndexOf('/');
+ if (at < 0) return { dir: '', base: path };
+ return { dir: path.slice(0, at + 1), base: path.slice(at + 1) };
+}
+
+/** `owner/name` from a `https://github.com/owner/name` url, when it is one. */
+export function repositorySlug(
+ repository: string | undefined
+): string | undefined {
+ if (!repository) return undefined;
+ const match = /^https?:\/\/github\.com\/([^/]+)\/([^/#?]+)/i.exec(repository);
+ if (!match) return undefined;
+ return `${match[1]}/${match[2]!.replace(/\.git$/, '')}`;
+}
+
+/** `head → base`, or whichever side is known, for the branch pill. */
+export function describeRange(changeset: Changeset): string | undefined {
+ const head = changeset.head.name ?? shortSha(changeset.head.sha);
+ const base = changeset.base.name ?? shortSha(changeset.base.sha);
+ if (head && base) return `${head} → ${base}`;
+ return head ?? base;
+}
+
+function shortSha(sha: string | undefined): string | undefined {
+ return sha ? sha.slice(0, 7) : undefined;
+}
+
+/** "6 files", "1 file". */
+export function describeFileCount(count: number): string {
+ return `${count} ${count === 1 ? 'file' : 'files'}`;
+}
+
+/**
+ * Which state the pane is in, from the summary. A capture that is running
+ * shows over a stale changeset; a failed one keeps the last good changeset
+ * on screen with a notice.
+ */
+export type ChangesState =
+ | { kind: 'loading' }
+ /** The summary could not be read at all; nothing is known. */
+ | { kind: 'load_error' }
+ | { kind: 'capturing'; previous: Changeset | undefined }
+ | { kind: 'ready'; changeset: Changeset }
+ | { kind: 'empty'; changeset: Changeset }
+ | { kind: 'not_ready'; message: string }
+ | { kind: 'failed'; message: string; previous: Changeset | undefined }
+ | { kind: 'none' };
+
+export function changesState(
+ summary: SessionChanges | undefined,
+ summaryStatus: 'idle' | 'pending' | 'error' | 'success' = summary
+ ? 'success'
+ : 'pending'
+): ChangesState {
+ if (!summary) {
+ return summaryStatus === 'error'
+ ? { kind: 'load_error' }
+ : { kind: 'loading' };
+ }
+ if (summary.capturing) {
+ return { kind: 'capturing', previous: summary.changeset };
+ }
+ const { changeset, attempt } = summary;
+ if (changeset) {
+ if (attempt?.outcome === 'failed') {
+ return {
+ kind: 'failed',
+ message: attempt.error ?? 'The last capture failed.',
+ previous: changeset,
+ };
+ }
+ return changeset.files.length > 0
+ ? { kind: 'ready', changeset }
+ : { kind: 'empty', changeset };
+ }
+ switch (attempt?.outcome) {
+ case 'not_ready':
+ return {
+ kind: 'not_ready',
+ message:
+ attempt.error ??
+ 'Link a GitHub pull request to this session to review its changes.',
+ };
+ case 'failed':
+ return {
+ kind: 'failed',
+ message: attempt.error ?? 'The last capture failed.',
+ previous: undefined,
+ };
+ case 'captured':
+ case undefined:
+ return { kind: 'none' };
+ }
+}
diff --git a/apps/web/src/features/agent-changes/core/file-tree.test.ts b/apps/web/src/features/agent-changes/core/file-tree.test.ts
new file mode 100644
index 0000000000..eb457c50f5
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/file-tree.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import type { ChangedFile } from './changeset';
+import { buildFileTree, flattenFiles } from './file-tree';
+
+function file(path: string): ChangedFile {
+ return {
+ path,
+ kind: 'modified',
+ additions: 1,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ };
+}
+
+describe('buildFileTree', () => {
+ it('compresses single-child directory chains', () => {
+ const tree = buildFileTree([
+ file('apps/web/src/a.ts'),
+ file('apps/web/src/b.ts'),
+ ]);
+ expect(tree).toHaveLength(1);
+ const dir = tree[0]!;
+ expect(dir.kind).toBe('dir');
+ if (dir.kind !== 'dir') return;
+ expect(dir.name).toBe('apps/web/src');
+ expect(dir.path).toBe('apps/web/src');
+ expect(dir.children.map((child) => child.name)).toEqual(['a.ts', 'b.ts']);
+ });
+
+ it('stops compressing where the tree branches', () => {
+ const tree = buildFileTree([
+ file('apps/web/src/a.ts'),
+ file('apps/web/test/b.ts'),
+ file('crates/x/src/lib.rs'),
+ ]);
+ expect(tree.map((node) => node.name)).toEqual(['apps/web', 'crates/x/src']);
+ const web = tree[0]!;
+ if (web.kind !== 'dir') throw new Error('expected dir');
+ expect(web.children.map((node) => node.name)).toEqual(['src', 'test']);
+ });
+
+ it('lists directories before files and keeps patch order', () => {
+ const tree = buildFileTree([
+ file('README.md'),
+ file('docs/guide.md'),
+ file('LICENSE'),
+ ]);
+ expect(tree.map((node) => `${node.kind}:${node.name}`)).toEqual([
+ 'dir:docs',
+ 'file:README.md',
+ 'file:LICENSE',
+ ]);
+ });
+
+ it('flattens back to the files in display order', () => {
+ const files = [file('b/y.ts'), file('a.ts'), file('b/x.ts')];
+ expect(flattenFiles(buildFileTree(files)).map((f) => f.path)).toEqual([
+ 'b/y.ts',
+ 'b/x.ts',
+ 'a.ts',
+ ]);
+ });
+});
diff --git a/apps/web/src/features/agent-changes/core/file-tree.ts b/apps/web/src/features/agent-changes/core/file-tree.ts
new file mode 100644
index 0000000000..299bf2504e
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/file-tree.ts
@@ -0,0 +1,99 @@
+/**
+ * The changed-files tree: directories compressed along single-child chains
+ * (`apps/web/src` reads as one row when nothing branches off it), files in
+ * patch order under their directory, directories before files.
+ */
+
+import type { ChangedFile } from './changeset';
+
+export type FileTreeDir = {
+ kind: 'dir';
+ /** The compressed segment, e.g. `apps/web/src`. */
+ name: string;
+ /** Full path of the directory, for a stable key. */
+ path: string;
+ children: FileTreeNode[];
+};
+
+export type FileTreeFile = {
+ kind: 'file';
+ /** Basename shown in the row. */
+ name: string;
+ file: ChangedFile;
+};
+
+export type FileTreeNode = FileTreeDir | FileTreeFile;
+
+type MutableDir = {
+ name: string;
+ path: string;
+ dirs: Map<string, MutableDir>;
+ files: FileTreeFile[];
+};
+
+function newDir(name: string, path: string): MutableDir {
+ return { name, path, dirs: new Map(), files: [] };
+}
+
+/**
+ * Build the tree from the files' paths. Order is preserved: directories
+ * appear in the order their first file appeared, files in patch order.
+ */
+export function buildFileTree(files: readonly ChangedFile[]): FileTreeNode[] {
+ const root = newDir('', '');
+ for (const file of files) {
+ const segments = file.path.split('/').filter((segment) => segment !== '');
+ const base = segments.pop() ?? file.path;
+ let node = root;
+ for (const segment of segments) {
+ let next = node.dirs.get(segment);
+ if (!next) {
+ next = newDir(segment, node.path ? `${node.path}/${segment}` : segment);
+ node.dirs.set(segment, next);
+ }
+ node = next;
+ }
+ node.files.push({ kind: 'file', name: base, file });
+ }
+ return [...compress(root).map(finish), ...root.files];
+}
+
+/** Fold a directory with exactly one child directory and no files into it. */
+function compress(dir: MutableDir): MutableDir[] {
+ const out: MutableDir[] = [];
+ for (let child of dir.dirs.values()) {
+ while (child.files.length === 0 && child.dirs.size === 1) {
+ const [only] = child.dirs.values();
+ child = {
+ name: `${child.name}/${only!.name}`,
+ path: only!.path,
+ dirs: only!.dirs,
+ files: only!.files,
+ };
+ }
+ out.push(child);
+ }
+ return out;
+}
+
+function finish(dir: MutableDir): FileTreeDir {
+ return {
+ kind: 'dir',
+ name: dir.name,
+ path: dir.path,
+ children: [...compress(dir).map(finish), ...dir.files],
+ };
+}
+
+/** Every file in the tree, depth first, in display order. */
+export function flattenFiles(nodes: readonly FileTreeNode[]): ChangedFile[] {
+ const out: ChangedFile[] = [];
+ const walk = (list: readonly FileTreeNode[]) => {
+ for (const node of list) {
+ if (node.kind === 'file') out.push(node.file);
+ else walk(node.children);
+ }
+ };
+ walk(nodes);
+ return out;
+}
diff --git a/apps/web/src/features/agent-changes/core/layout.test.ts b/apps/web/src/features/agent-changes/core/layout.test.ts
new file mode 100644
index 0000000000..a4cc83f1f1
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/layout.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+import {
+ clampChangesShare,
+ DEFAULT_CHANGES_SHARE,
+ ensureChangesVisible,
+ isChangesVisible,
+ isSessionVisible,
+ toggleChanges,
+ toggleSpotlight,
+} from './layout';
+
+describe('layout moves', () => {
+ it('toggles the pane from the session header', () => {
+ expect(toggleChanges('agent-only')).toBe('split');
+ expect(toggleChanges('split')).toBe('agent-only');
+ expect(toggleChanges('changes-only')).toBe('agent-only');
+ });
+
+ it('spotlights and comes back', () => {
+ expect(toggleSpotlight('split')).toBe('changes-only');
+ expect(toggleSpotlight('changes-only')).toBe('split');
+ expect(toggleSpotlight('agent-only')).toBe('changes-only');
+ });
+
+ it('only opens a closed pane', () => {
+ expect(ensureChangesVisible('agent-only')).toBe('split');
+ expect(ensureChangesVisible('changes-only')).toBe('changes-only');
+ expect(ensureChangesVisible('split')).toBe('split');
+ });
+
+ it('knows which panes are on screen', () => {
+ expect(isChangesVisible('agent-only')).toBe(false);
+ expect(isSessionVisible('changes-only')).toBe(false);
+ expect(isChangesVisible('split') && isSessionVisible('split')).toBe(true);
+ });
+});
+
+describe('clampChangesShare', () => {
+ it('keeps the share inside the bounds and recovers from junk', () => {
+ expect(clampChangesShare(10)).toBe(22);
+ expect(clampChangesShare(90)).toBe(74);
+ expect(clampChangesShare(50)).toBe(50);
+ expect(clampChangesShare(Number.NaN)).toBe(DEFAULT_CHANGES_SHARE);
+ });
+});
diff --git a/apps/web/src/features/agent-changes/core/layout.ts b/apps/web/src/features/agent-changes/core/layout.ts
new file mode 100644
index 0000000000..883088e10c
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/layout.ts
@@ -0,0 +1,43 @@
+/**
+ * The pane's three layouts and the moves between them.
+ *
+ * `split` shows the session and the changes side by side; `agent-only` hands
+ * the width back to the transcript; `changes-only` spotlights the review.
+ */
+
+export type DiffStyle = 'unified' | 'split';
+
+export type PaneLayout = 'split' | 'agent-only' | 'changes-only';
+
+/** Share of the width the changes pane takes when it first opens. */
+export const DEFAULT_CHANGES_SHARE = 58;
+export const MIN_CHANGES_SHARE = 22;
+export const MAX_CHANGES_SHARE = 74;
+
+export function isChangesVisible(layout: PaneLayout): boolean {
+ return layout !== 'agent-only';
+}
+
+export function isSessionVisible(layout: PaneLayout): boolean {
+ return layout !== 'changes-only';
+}
+
+/** The session header toggle: open the split, or close the pane. */
+export function toggleChanges(layout: PaneLayout): PaneLayout {
+ return layout === 'agent-only' ? 'split' : 'agent-only';
+}
+
+/** The pane's spotlight button: take the full width, or come back. */
+export function toggleSpotlight(layout: PaneLayout): PaneLayout {
+ return layout === 'changes-only' ? 'split' : 'changes-only';
+}
+
+/** Anything that needs the pane on screen goes through this first. */
+export function ensureChangesVisible(layout: PaneLayout): PaneLayout {
+ return layout === 'agent-only' ? 'split' : layout;
+}
+
+export function clampChangesShare(share: number): number {
+ if (!Number.isFinite(share)) return DEFAULT_CHANGES_SHARE;
+ return Math.min(MAX_CHANGES_SHARE, Math.max(MIN_CHANGES_SHARE, share));
+}
diff --git a/apps/web/src/features/agent-changes/core/patch.test.ts b/apps/web/src/features/agent-changes/core/patch.test.ts
new file mode 100644
index 0000000000..ee76b020ee
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/patch.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+import type { ChangedFile } from './changeset';
+import { matchFilesToDiffs, parsePatch } from './patch';
+
+const PATCH = `diff --git a/src/a.ts b/src/a.ts
+index 1111111..2222222 100644
+--- a/src/a.ts
++++ b/src/a.ts
+@@ -1,3 +1,3 @@
+ const a = 1;
+-const b = 2;
++const b = 3;
+ export { a, b };
+diff --git a/old.txt b/new.txt
+similarity index 100%
+rename from old.txt
+rename to new.txt
+`;
+
+function file(overrides: Partial<ChangedFile>): ChangedFile {
+ return {
+ path: 'src/a.ts',
+ kind: 'modified',
+ additions: 1,
+ deletions: 1,
+ binary: false,
+ patchOmitted: false,
+ ...overrides,
+ };
+}
+
+describe('parsePatch', () => {
+ it('keys parsed files by their new path', () => {
+ const diffs = parsePatch(PATCH);
+ expect(diffs.get('src/a.ts')?.type).toBe('change');
+ expect(diffs.get('src/a.ts')?.hunks).toHaveLength(1);
+ expect(diffs.get('new.txt')?.type).toBe('rename-pure');
+ });
+
+ it('is empty for an empty patch', () => {
+ expect(parsePatch(' \n').size).toBe(0);
+ });
+});
+
+describe('matchFilesToDiffs', () => {
+ it('pairs files with diffs and explains the ones without', () => {
+ const diffs = parsePatch(PATCH);
+ const entries = matchFilesToDiffs(
+ [
+ file({}),
+ file({ path: 'img.png', kind: 'added', binary: true }),
+ file({ path: 'big.json', patchOmitted: true }),
+ file({ path: 'missing.ts' }),
+ file({
+ path: 'new.txt',
+ previousPath: 'old.txt',
+ kind: 'renamed',
+ additions: 0,
+ deletions: 0,
+ }),
+ ],
+ diffs
+ );
+ expect(entries[0]!.diff?.name).toBe('src/a.ts');
+ expect(entries[1]!.note).toBe('Binary file');
+ expect(entries[2]!.note).toBe('Diff left out to fit the size budget');
+ expect(entries[3]!.note).toBe('No diff text for this file');
+ expect(entries[4]!.diff?.type).toBe('rename-pure');
+ });
+});
diff --git a/apps/web/src/features/agent-changes/core/patch.ts b/apps/web/src/features/agent-changes/core/patch.ts
new file mode 100644
index 0000000000..b36f71fac4
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/patch.ts
@@ -0,0 +1,56 @@
+/**
+ * The patch behind a changeset, parsed once into Pierre's per-file diffs and
+ * matched back to the summary's files by path.
+ */
+
+import { type FileDiffMetadata, parsePatchFiles } from '@pierre/diffs';
+import type { ChangedFile } from './changeset';
+
+/** One file's parsed diff, or why there is none to render. */
+export type FileDiffEntry = {
+ file: ChangedFile;
+ /** Absent when the patch has no text for the file. */
+ diff?: FileDiffMetadata;
+ /** Why the diff is absent, in a phrase the card can show. */
+ note?: string;
+};
+
+/** Parse a unified patch into Pierre file diffs, keyed by their new path. */
+export function parsePatch(patch: string): Map<string, FileDiffMetadata> {
+ const byPath = new Map<string, FileDiffMetadata>();
+ if (patch.trim() === '') return byPath;
+ for (const parsed of parsePatchFiles(patch)) {
+ for (const file of parsed.files) {
+ byPath.set(file.name, file);
+ if (file.type === 'deleted' && file.prevName)
+ byPath.set(file.prevName, file);
+ }
+ }
+ return byPath;
+}
+
+/** Pair each summary file with its parsed diff, in summary order. */
+export function matchFilesToDiffs(
+ files: readonly ChangedFile[],
+ diffs: ReadonlyMap<string, FileDiffMetadata>
+): FileDiffEntry[] {
+ return files.map((file) => {
+ if (file.binary) return { file, note: 'Binary file' };
+ if (file.patchOmitted) {
+ return { file, note: 'Diff left out to fit the size budget' };
+ }
+ const diff =
+ diffs.get(file.path) ??
+ (file.previousPath ? diffs.get(file.previousPath) : undefined);
+ if (!diff) {
+ return {
+ file,
+ note:
+ file.kind === 'renamed' && file.additions + file.deletions === 0
+ ? 'Renamed without changes'
+ : 'No diff text for this file',
+ };
+ }
+ return { file, diff };
+ });
+}
diff --git a/apps/web/src/features/agent-changes/core/pull-request.ts b/apps/web/src/features/agent-changes/core/pull-request.ts
new file mode 100644
index 0000000000..043235ee82
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/pull-request.ts
@@ -0,0 +1,4 @@
+export function pullRequestNumber(url: string): number | undefined {
+ const match = /\/pull\/(\d+)(?:[/?#]|$)/.exec(url);
+ return match ? Number(match[1]) : undefined;
+}
diff --git a/apps/web/src/features/agent-changes/core/review-notes.test.ts b/apps/web/src/features/agent-changes/core/review-notes.test.ts
new file mode 100644
index 0000000000..446fd2466f
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/review-notes.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+import {
+ formatNotesForAgent,
+ notesForFile,
+ queuedNotes,
+ type ReviewNote,
+} from './review-notes';
+
+function note(overrides: Partial<ReviewNote> = {}): ReviewNote {
+ return {
+ id: 'n1',
+ path: 'a.ts',
+ side: 'additions',
+ lineNumber: 10,
+ endLineNumber: 10,
+ text: 'Rename this',
+ createdAt: '2026-09-15T00:00:00Z',
+ ...overrides,
+ };
+}
+
+describe('queuedNotes', () => {
+ it('drops sent notes', () => {
+ expect(
+ queuedNotes([note(), note({ id: 'n2', sentAt: 't' })]).map((n) => n.id)
+ ).toEqual(['n1']);
+ });
+});
+
+describe('notesForFile', () => {
+ it('filters by path and sorts by line', () => {
+ const list = [
+ note({ id: 'a', lineNumber: 20, endLineNumber: 20 }),
+ note({ id: 'b', path: 'b.ts' }),
+ note({ id: 'c', lineNumber: 5, endLineNumber: 5 }),
+ ];
+ expect(notesForFile(list, 'a.ts').map((n) => n.id)).toEqual(['c', 'a']);
+ });
+});
+
+describe('formatNotesForAgent', () => {
+ it('is empty without notes', () => {
+ expect(formatNotesForAgent([])).toBe('');
+ });
+
+ it('writes one note as prose with its location', () => {
+ expect(formatNotesForAgent([note()])).toBe(
+ 'Review note on `a.ts`, line 10 (new):\n\nRename this'
+ );
+ });
+
+ it('numbers several notes in file and line order, naming ranges and sides', () => {
+ const text = formatNotesForAgent([
+ note({ id: 'b', path: 'b.ts', side: 'deletions', text: 'Keep this' }),
+ note({
+ id: 'a',
+ lineNumber: 3,
+ endLineNumber: 6,
+ text: ' Extract a helper ',
+ }),
+ ]);
+ expect(text).toBe(
+ [
+ 'Please address these 2 review notes on the current changes:',
+ '',
+ '1. `a.ts`, lines 3–6 (new): Extract a helper',
+ '2. `b.ts`, line 10 (old): Keep this',
+ ].join('\n')
+ );
+ });
+});
diff --git a/apps/web/src/features/agent-changes/core/review-notes.ts b/apps/web/src/features/agent-changes/core/review-notes.ts
new file mode 100644
index 0000000000..ccdbe972bf
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/review-notes.ts
@@ -0,0 +1,81 @@
+/**
+ * Line-level review notes: what the reviewer wants the agent to change, tied
+ * to a line of the current changeset, queued until sent as one prompt.
+ *
+ * Notes never go to GitHub. They are the reviewer's words for the agent, so
+ * `formatNotesForAgent` turns them into the markdown the session composer
+ * posts.
+ */
+
+/** Which side of the diff a line belongs to, in Pierre's vocabulary. */
+export type DiffSide = 'additions' | 'deletions';
+
+export type ReviewNote = {
+ id: string;
+ /** The file the note is on, by its current path. */
+ path: string;
+ side: DiffSide;
+ /** First line of the annotated range, in that side's numbering. */
+ lineNumber: number;
+ /** Last line, equal to `lineNumber` for a single line. */
+ endLineNumber: number;
+ text: string;
+ /** Set once the note has been posted to the agent. */
+ sentAt?: string;
+ createdAt: string;
+};
+
+/** Where a new note goes: the line the reviewer picked. */
+export type NoteAnchor = {
+ path: string;
+ side: DiffSide;
+ lineNumber: number;
+ endLineNumber: number;
+};
+
+export function noteAnchorKey(anchor: NoteAnchor): string {
+ return `${anchor.path}:${anchor.side}:${anchor.lineNumber}-${anchor.endLineNumber}`;
+}
+
+export function queuedNotes(notes: readonly ReviewNote[]): ReviewNote[] {
+ return notes.filter((note) => note.sentAt === undefined);
+}
+
+/** Notes on one file, in line order, queued first. */
+export function notesForFile(
+ notes: readonly ReviewNote[],
+ path: string
+): ReviewNote[] {
+ return notes
+ .filter((note) => note.path === path)
+ .sort((a, b) => a.lineNumber - b.lineNumber);
+}
+
+function describeLines(note: ReviewNote): string {
+ const version = note.side === 'additions' ? 'new' : 'old';
+ if (note.endLineNumber > note.lineNumber) {
+ return `lines ${note.lineNumber}–${note.endLineNumber} (${version})`;
+ }
+ return `line ${note.lineNumber} (${version})`;
+}
+
+/**
+ * The prompt that carries queued notes to the agent: one numbered item per
+ * note, each naming the file and line, in file order so the agent walks the
+ * diff the way the reviewer did.
+ */
+export function formatNotesForAgent(notes: readonly ReviewNote[]): string {
+ const ordered = [...notes].sort(
+ (a, b) => a.path.localeCompare(b.path) || a.lineNumber - b.lineNumber
+ );
+ if (ordered.length === 0) return '';
+ if (ordered.length === 1) {
+ const note = ordered[0]!;
+ return `Review note on \`${note.path}\`, ${describeLines(note)}:\n\n${note.text.trim()}`;
+ }
+ const items = ordered.map(
+ (note, index) =>
+ `${index + 1}. \`${note.path}\`, ${describeLines(note)}: ${note.text.trim()}`
+ );
+ return `Please address these ${ordered.length} review notes on the current changes:\n\n${items.join('\n')}`;
+}
diff --git a/apps/web/src/features/agent-changes/core/url-state.test.ts b/apps/web/src/features/agent-changes/core/url-state.test.ts
new file mode 100644
index 0000000000..6bd54eeb2f
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/url-state.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DEFAULT_DIFF_URL_STATE,
+ readDiffUrlState,
+ writeDiffUrlState,
+} from './url-state';
+
+describe('diff URL identities', () => {
+ it('round-trips namespaced PR ids and preserves adjacent sessions', () => {
+ const key = 'pr:macro-inc/macro/1482,revision%2';
+ const state = { layout: 'changes-only', diffStyle: 'split' } as const;
+ const value = writeDiffUrlState('session-1:split:unified', key, state);
+ expect(readDiffUrlState(value, key)).toEqual(state);
+ expect(readDiffUrlState(value, 'session-1')).toEqual({
+ layout: 'split',
+ diffStyle: 'unified',
+ });
+ expect(writeDiffUrlState(value, key, DEFAULT_DIFF_URL_STATE)).toBe(
+ 'session-1:split:unified'
+ );
+ });
+
+ it('ignores malformed escaping', () => {
+ expect(readDiffUrlState('%xx:split:unified', '%xx')).toEqual(
+ DEFAULT_DIFF_URL_STATE
+ );
+ });
+});
diff --git a/apps/web/src/features/agent-changes/core/url-state.ts b/apps/web/src/features/agent-changes/core/url-state.ts
new file mode 100644
index 0000000000..7c05181ab3
--- /dev/null
+++ b/apps/web/src/features/agent-changes/core/url-state.ts
@@ -0,0 +1,63 @@
+import type { DiffStyle, PaneLayout } from './layout';
+
+export type DiffUrlState = { layout: PaneLayout; diffStyle: DiffStyle };
+
+export const DEFAULT_DIFF_URL_STATE: DiffUrlState = {
+ layout: 'agent-only',
+ diffStyle: 'unified',
+};
+
+/** Each tuple belongs to a host, so adjacent viewers stay independent. */
+function entries(value: unknown): Map<string, DiffUrlState> {
+ const result = new Map<string, DiffUrlState>();
+ if (typeof value !== 'string') return result;
+ for (const entry of value.split(',')) {
+ const [scopeKey, layout, diffStyle, extra] = entry.split(':');
+ if (
+ !scopeKey ||
+ extra !== undefined ||
+ (layout !== 'agent-only' &&
+ layout !== 'split' &&
+ layout !== 'changes-only') ||
+ (diffStyle !== 'unified' && diffStyle !== 'split')
+ )
+ continue;
+ try {
+ result.set(decodeURIComponent(scopeKey), { layout, diffStyle });
+ } catch {
+ // Ignore malformed URL entries without disturbing the other viewers.
+ }
+ }
+ return result;
+}
+
+export function readDiffUrlState(
+ value: unknown,
+ scopeKey: string | undefined
+): DiffUrlState {
+ return (
+ (scopeKey ? entries(value).get(scopeKey) : undefined) ??
+ DEFAULT_DIFF_URL_STATE
+ );
+}
+
+export function writeDiffUrlState(
+ value: unknown,
+ scopeKey: string,
+ state: DiffUrlState
+): string | undefined {
+ const next = entries(value);
+ if (state.layout === 'agent-only' && state.diffStyle === 'unified') {
+ next.delete(scopeKey);
+ } else {
+ next.set(scopeKey, state);
+ }
+ return (
+ [...next]
+ .map(
+ ([id, state]) =>
+ `${encodeURIComponent(id)}:${state.layout}:${state.diffStyle}`
+ )
+ .join(',') || undefined
+ );
+}
diff --git a/apps/web/src/features/agent-changes/debug/Gallery.tsx b/apps/web/src/features/agent-changes/debug/Gallery.tsx
new file mode 100644
index 0000000000..37ffcfd95c
--- /dev/null
+++ b/apps/web/src/features/agent-changes/debug/Gallery.tsx
@@ -0,0 +1,90 @@
+/**
+ * Debug gallery for the Changes pane: the real controller and views over an
+ * in-memory source, so the split, tree, Pierre diffs, review notes, and the
+ * pull request link can be exercised without a backend. Registered as the
+ * `agent-changes-ui` component.
+ */
+
+import { Button } from '@ui';
+import { createSignal, For } from 'solid-js';
+import { AgentChangesControllerProvider } from '../context/agent-changes-controller';
+import { createAgentChanges } from '../primitives/create-agent-changes';
+import { createMockAgentChangesContext } from '../tests/mock-context';
+import { createUrlDiffState } from '../url-diff-state';
+import { AgentChangesSplit } from '../views/AgentChangesSplit';
+import {
+ ChangesHandoff,
+ ChangesToggle,
+ ReviewNotesDock,
+} from '../views/SessionChangesControls';
+import { GALLERY_PATCH, gallerySummary } from './gallery-fixture';
+
+export default function AgentChangesGallery() {
+ const context = createMockAgentChangesContext({
+ summary: gallerySummary(),
+ patch: GALLERY_PATCH,
+ sessionId: 'gallery-session',
+ });
+ const urlState = createUrlDiffState(context.host.scopeKey);
+ const [dismissed, setDismissed] = createSignal<string>();
+ const controller = createAgentChanges({
+ context,
+ paneLayout: [urlState.layout, urlState.setLayout],
+ diffStyle: [urlState.diffStyle, urlState.setDiffStyle],
+ dismissed: [dismissed, setDismissed],
+ });
+ const [transcript, setTranscript] = createSignal<string[]>([]);
+ // The mock host records prompts; surface them like a transcript would.
+ const originalSend = context.host.agent.send;
+ context.host.agent.send = (markdown) => {
+ originalSend(markdown);
+ setTranscript((lines) => [...lines, markdown]);
+ };
+
+ return (
+ <AgentChangesControllerProvider value={controller}>
+ <div class="flex h-full min-h-0 flex-col bg-panel">
+ <AgentChangesSplit>
+ <header class="flex h-12 shrink-0 items-center gap-2 border-b border-edge px-4">
+ <h2 class="min-w-0 flex-1 truncate text-sm font-semibold text-ink">
+ Stale unread dots on archived sessions
+ </h2>
+ <ChangesToggle />
+ </header>
+ <div class="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-4">
+ <p class="text-xs text-ink-muted">
+ Gallery session. Prompts sent from the Changes pane appear below;
+ use the button below to simulate linking a pull request.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ class="self-start"
+ onClick={() =>
+ context.setPullRequestUrl(
+ 'https://github.com/macro-inc/macro/pull/1482'
+ )
+ }
+ >
+ Simulate the agent linking PR #1482
+ </Button>
+ <For each={transcript()}>
+ {(line) => (
+ <pre class="rounded-lg bg-surface-1 p-3 font-mono text-xs whitespace-pre-wrap text-ink-muted">
+ {line}
+ </pre>
+ )}
+ </For>
+ </div>
+ <div class="mx-auto flex w-full max-w-4xl shrink-0 flex-col gap-2 px-4 pb-4">
+ <ChangesHandoff />
+ <ReviewNotesDock />
+ <div class="rounded-2xl border border-edge px-4 py-3 text-sm text-ink-placeholder">
+ Message the agent, @mention anything
+ </div>
+ </div>
+ </AgentChangesSplit>
+ </div>
+ </AgentChangesControllerProvider>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/debug/gallery-fixture.ts b/apps/web/src/features/agent-changes/debug/gallery-fixture.ts
new file mode 100644
index 0000000000..0037344cf4
--- /dev/null
+++ b/apps/web/src/features/agent-changes/debug/gallery-fixture.ts
@@ -0,0 +1,171 @@
+import type { SessionChanges } from '../core/changeset';
+
+/** A patch with several files, a rename, and a deletion for the gallery. */
+export const GALLERY_PATCH = `diff --git a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
+index 1111111..2222222 100644
+--- a/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
++++ b/apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts
+@@ -7,7 +7,8 @@
+ import { createMemo } from 'solid-js';
+
+ import { useAgentSessionsQuery } from '@queries/agent/sessions';
+-import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
++import { hasUnreadActivity } from '@block-agent/state/unread';
++import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
+
+ import type { SidebarItemId } from '../nav-items';
+
+@@ -19,12 +20,15 @@ const DOTTED: readonly SidebarItemId[] = ['inbox', 'channels', 'agents'];
+ export function useSidebarUnread(): (id: SidebarItemId) => boolean {
+ const sessions = useAgentSessionsQuery();
+
+- // Activity after the read marker lights the dot.
+- const agentsUnread = createMemo(() =>
+- (sessions.data ?? []).some(
+- (session: AgentSessionSummary) => session.lastEventAt > session.lastReadAt
+- )
+- );
++ // Archiving takes a session off the inbox, so its activity stops being
++ // news. The rail has to ask the same question the agents list asks,
++ // through the same predicate.
++ const agentsUnread = createMemo(() =>
++ (sessions.data ?? []).some((session: AgentSessionSummary) =>
++ hasUnreadActivity(session)
++ )
++ );
+
+ return (id) => (id === 'agents' ? agentsUnread() : false);
+ }
+diff --git a/apps/web/src/features/block-agent/state/unread.ts b/apps/web/src/features/block-agent/state/unread.ts
+new file mode 100644
+index 0000000..3333333
+--- /dev/null
++++ b/apps/web/src/features/block-agent/state/unread.ts
+@@ -0,0 +1,14 @@
++import type { AgentSessionSummary } from '@service-agent-fold/generated/types';
++
++/** An archived session is off the inbox, so its activity is not news. */
++export function isArchived(session: AgentSessionSummary): boolean {
++ return session.archivedAt != null;
++}
++
++export function hasUnreadActivity(session: AgentSessionSummary): boolean {
++ if (isArchived(session)) return false;
++ const lastEventAt = session.lastEventAt;
++ if (lastEventAt == null) return false;
++ return lastEventAt > (session.lastReadAt ?? 0);
++}
++
+diff --git a/crates/macro_agent_sessions/src/service.rs b/crates/macro_agent_sessions/src/service.rs
+index 4444444..5555555 100644
+--- a/crates/macro_agent_sessions/src/service.rs
++++ b/crates/macro_agent_sessions/src/service.rs
+@@ -85,8 +85,14 @@ impl SessionService {
+ #[instrument(skip(self), fields(session_id = %id))]
+ pub async fn archive(&self, id: AgentSessionId) -> Result<(), ArchiveError> {
+- self.repo.set_archived(id, Utc::now()).await?;
+- Ok(())
++ let now = Utc::now();
++ let mut tx = self.repo.begin().await?;
++
++ self.repo.set_archived(&mut tx, id, now).await?;
++ self.repo.mark_read(&mut tx, id, now).await?;
++
++ tx.commit().await?;
++ Ok(())
+ }
+
+ #[instrument(skip(self), fields(owner = %owner))]
+diff --git a/crates/macro_agent_sessions/src/legacy_unread.rs b/crates/macro_agent_sessions/src/legacy_unread.rs
+deleted file mode 100644
+index 6666666..0000000
+--- a/crates/macro_agent_sessions/src/legacy_unread.rs
++++ /dev/null
+@@ -1,3 +0,0 @@
+-pub fn unread(last_event_at: i64, last_read_at: i64) -> bool {
+- last_event_at > last_read_at
+-}
+diff --git a/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql b/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql
+new file mode 100644
+index 0000000..7777777
+--- /dev/null
++++ b/crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql
+@@ -0,0 +1,5 @@
++-- Archived sessions drop out of the unread count. Without a partial index
++-- the filter falls back to a sequential scan on long workspace histories.
++CREATE INDEX CONCURRENTLY IF NOT EXISTS agent_sessions_unread_active_idx
++ ON agent_sessions (owner_id, last_event_at DESC)
++ WHERE archived_at IS NULL;
+`;
+
+export function gallerySummary(): SessionChanges {
+ return {
+ capturing: false,
+ attempt: {
+ startedAt: '2026-09-15T00:00:00Z',
+ finishedAt: '2026-09-15T00:00:02Z',
+ outcome: 'captured',
+ },
+ changeset: {
+ id: 'gallery-changeset',
+ repository: 'https://github.com/macro-inc/macro',
+ base: { name: 'main' },
+ head: { name: 'agent/unread-archived-sessions' },
+ files: [
+ {
+ path: 'apps/web/src/components/app/sidebar-next/queries/use-sidebar-unread.ts',
+ kind: 'modified',
+ additions: 10,
+ deletions: 7,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'apps/web/src/features/block-agent/state/unread.ts',
+ kind: 'added',
+ additions: 14,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/macro_agent_sessions/src/service.rs',
+ kind: 'modified',
+ additions: 8,
+ deletions: 2,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/macro_agent_sessions/src/legacy_unread.rs',
+ kind: 'deleted',
+ additions: 0,
+ deletions: 3,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/macro_db_client/migrations/20260914042311_agent_session_archived_index.sql',
+ kind: 'added',
+ additions: 5,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'static_assets/logo.png',
+ kind: 'modified',
+ additions: 0,
+ deletions: 0,
+ binary: true,
+ patchOmitted: false,
+ },
+ ],
+ additions: 37,
+ deletions: 12,
+ patchBytes: GALLERY_PATCH.length,
+ truncated: false,
+ capturedAt: '2026-09-15T00:00:02Z',
+ },
+ };
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
new file mode 100644
index 0000000000..2ea7e90bf8
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-agent-changes.ts
@@ -0,0 +1,107 @@
+/**
+ * The pane's one controller: layout, model, and review
+ * built from the capability contract and handed to the views together.
+ */
+
+import type { Accessor } from 'solid-js';
+import type { AgentChangesContext } from '../context/agent-changes-context';
+import type { DiffStyle, PaneLayout } from '../core/layout';
+import { formatNotesForAgent } from '../core/review-notes';
+import { type ChangesModel, createChangesModel } from './create-changes-model';
+import {
+ createPaneLayout,
+ type PaneLayoutController,
+} from './create-pane-layout';
+import {
+ createReviewState,
+ type ReviewController,
+} from './create-review-state';
+
+export type { DiffStyle } from '../core/layout';
+
+export type AgentChangesController = {
+ context: AgentChangesContext;
+ layout: PaneLayoutController;
+ model: ChangesModel;
+ review: ReviewController;
+ diffStyle: Accessor<DiffStyle>;
+ setDiffStyle: (style: DiffStyle) => void;
+ /** Post every queued note to the agent as one prompt. */
+ sendQueuedNotes: () => void;
+ /** The handoff card was dismissed for the changeset on screen. */
+ handoffDismissed: Accessor<boolean>;
+ dismissHandoff: () => void;
+ copyPath: (path: string) => void;
+};
+
+export function createAgentChanges(options: {
+ context: AgentChangesContext;
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
+ /** Optional controlled pane layout, such as the URL state. */
+ paneLayout?: [get: Accessor<PaneLayout>, set: (layout: PaneLayout) => void];
+ /** Read and write the reviewer's diff layout preference. */
+ diffStyle: [get: Accessor<DiffStyle>, set: (style: DiffStyle) => void];
+ /** Per-session "dismissed for changeset id" memory. */
+ dismissed: [
+ get: Accessor<string | undefined>,
+ set: (changesetId: string | undefined) => void,
+ ];
+}): AgentChangesController {
+ const { source, host } = options.context;
+ const layout = createPaneLayout({
+ sessionId: host.scopeKey,
+ storage: options.storage,
+ layout: options.paneLayout,
+ });
+ const model = createChangesModel({
+ source,
+ changesVisible: layout.changesVisible,
+ });
+ const review = createReviewState({
+ sessionId: host.scopeKey,
+ changeset: model.changeset,
+ storage: options.storage,
+ });
+ const [diffStyle, setDiffStyle] = options.diffStyle;
+ const [dismissed, setDismissed] = options.dismissed;
+
+ const copyPath = async (path: string) => {
+ let copied = false;
+ try {
+ copied = await host.copyText(path);
+ } catch {
+ // Hosts may report clipboard failures by rejecting or returning false.
+ }
+ host.notify(
+ copied ? 'Path copied' : 'The path could not be copied',
+ copied ? 'success' : 'failure'
+ );
+ };
+
+ return {
+ context: options.context,
+ layout,
+ model,
+ review,
+ diffStyle,
+ setDiffStyle,
+ sendQueuedNotes: () => {
+ const agent = host.agent;
+ if (!agent) return;
+ const queued = review.queued();
+ if (queued.length === 0) return;
+ if (!agent.canSend()) {
+ host.notify('The agent cannot take a prompt right now.', 'failure');
+ return;
+ }
+ agent.send(formatNotesForAgent(queued));
+ review.markQueuedSent();
+ },
+ handoffDismissed: () => {
+ const id = model.changeset()?.id;
+ return id !== undefined && dismissed() === id;
+ },
+ dismissHandoff: () => setDismissed(model.changeset()?.id),
+ copyPath: (path) => void copyPath(path),
+ };
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts b/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts
new file mode 100644
index 0000000000..819115e7de
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-changes-model.test.ts
@@ -0,0 +1,139 @@
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import type {
+ ChangesSource,
+ PatchRead,
+ QueryStatus,
+} from '../context/agent-changes-context';
+import type { SessionChanges } from '../core/changeset';
+import { createChangesModel } from './create-changes-model';
+
+const PATCH = `diff --git a/a.ts b/a.ts
+--- a/a.ts
++++ b/a.ts
+@@ -1 +1 @@
+-x
++y
+`;
+
+function summaryWith(
+ files: string[],
+ patchBytes = PATCH.length
+): SessionChanges {
+ return {
+ capturing: false,
+ changeset: {
+ id: 'cs',
+ base: { name: 'main' },
+ head: { name: 'agent/x' },
+ files: files.map((path) => ({
+ path,
+ kind: 'modified',
+ additions: 1,
+ deletions: 1,
+ binary: false,
+ patchOmitted: false,
+ })),
+ additions: files.length,
+ deletions: files.length,
+ patchBytes,
+ truncated: false,
+ capturedAt: 't',
+ },
+ };
+}
+
+function setup() {
+ const [summary, setSummary] = createSignal<SessionChanges>();
+ const [patchText, setPatchText] = createSignal<string>();
+ const [patchStatus, setPatchStatus] = createSignal<QueryStatus>('idle');
+ const [visible, setVisible] = createSignal(false);
+ const enabledReads: boolean[] = [];
+ let refreshes = 0;
+ const source: ChangesSource = {
+ summary,
+ summaryStatus: () => (summary() ? 'success' : 'pending'),
+ patch: (_changesetId, enabled): PatchRead => {
+ // Model the query: it only has text once enabled.
+ return {
+ text: () => {
+ enabledReads.push(enabled());
+ return enabled() ? patchText() : undefined;
+ },
+ status: patchStatus,
+ retry: () => {},
+ };
+ },
+ refresh: async () => {
+ refreshes += 1;
+ },
+ };
+ const model = createChangesModel({ source, changesVisible: visible });
+ return {
+ model,
+ setSummary,
+ setPatchText,
+ setPatchStatus,
+ setVisible,
+ refreshes: () => refreshes,
+ };
+}
+
+describe('createChangesModel', () => {
+ it('derives the state, tree, and entries once the patch arrives', () => {
+ // Mutations run outside the root body, as event handlers would, so
+ // every derived value settles synchronously before it is read.
+ const { model, setSummary, setPatchText, setVisible, dispose } = createRoot(
+ (dispose) => ({ ...setup(), dispose })
+ );
+ expect(model.state().kind).toBe('loading');
+ expect(model.entries()).toEqual([]);
+
+ setSummary(summaryWith(['a.ts']));
+ expect(model.state().kind).toBe('ready');
+ expect(model.tree().map((node) => node.name)).toEqual(['a.ts']);
+ // Closed pane: no patch, so no entries yet.
+ expect(model.entries()).toBeUndefined();
+
+ setVisible(true);
+ setPatchText(PATCH);
+ const entries = model.entries();
+ expect(entries).toHaveLength(1);
+ expect(entries?.[0]?.diff?.name).toBe('a.ts');
+ dispose();
+ });
+
+ it('does not wait for a patch that has no bytes', () => {
+ createRoot((dispose) => {
+ const { model, setSummary, setVisible } = setup();
+ setVisible(true);
+ setSummary(summaryWith(['img.png'], 0));
+ const entries = model.entries();
+ expect(entries).toHaveLength(1);
+ expect(entries?.[0]?.note).toBe('No diff text for this file');
+ dispose();
+ });
+ });
+
+ it('keeps the previous changeset on screen while a capture runs', () => {
+ createRoot((dispose) => {
+ const { model, setSummary } = setup();
+ const ready = summaryWith(['a.ts']);
+ setSummary(ready);
+ setSummary({ ...ready, capturing: true });
+ expect(model.state().kind).toBe('capturing');
+ expect(model.changeset()?.id).toBe('cs');
+ dispose();
+ });
+ });
+
+ it('refreshes once at a time', async () => {
+ await createRoot(async (dispose) => {
+ const { model, refreshes } = setup();
+ await Promise.all([model.refresh(), model.refresh()]);
+ expect(refreshes()).toBe(1);
+ expect(model.refreshing()).toBe(false);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/agent-changes/primitives/create-changes-model.ts b/apps/web/src/features/agent-changes/primitives/create-changes-model.ts
new file mode 100644
index 0000000000..8305980283
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-changes-model.ts
@@ -0,0 +1,119 @@
+/**
+ * What the pane shows, derived from the source: the capture state, the
+ * changeset on screen (the latest good one, even while a newer capture runs
+ * or has failed), its files as a tree, and the parsed diff for each file.
+ */
+
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import type {
+ ChangesSource,
+ QueryStatus,
+} from '../context/agent-changes-context';
+import {
+ type ChangedFile,
+ type Changeset,
+ type ChangesState,
+ changesState,
+} from '../core/changeset';
+import { buildFileTree, type FileTreeNode } from '../core/file-tree';
+import {
+ type FileDiffEntry,
+ matchFilesToDiffs,
+ parsePatch,
+} from '../core/patch';
+
+export type ChangesModel = {
+ state: Accessor<ChangesState>;
+ /** The changeset on screen, if any. */
+ changeset: Accessor<Changeset | undefined>;
+ files: Accessor<ChangedFile[]>;
+ tree: Accessor<FileTreeNode[]>;
+ /** Files paired with their diffs; undefined until the patch has loaded. */
+ entries: Accessor<FileDiffEntry[] | undefined>;
+ patchStatus: Accessor<QueryStatus>;
+ retryPatch: () => void;
+ refresh: () => Promise<void>;
+ refreshing: Accessor<boolean>;
+ refreshError: Accessor<string | undefined>;
+};
+
+export function createChangesModel(options: {
+ source: ChangesSource;
+ /** Whether the pane is on screen; the patch is only read while it is. */
+ changesVisible: Accessor<boolean>;
+}): ChangesModel {
+ const { source } = options;
+ const state = createMemo(() =>
+ changesState(source.summary(), source.summaryStatus())
+ );
+ const changeset = createMemo((): Changeset | undefined => {
+ const current = state();
+ switch (current.kind) {
+ case 'ready':
+ case 'empty':
+ return current.changeset;
+ case 'capturing':
+ case 'failed':
+ return current.previous;
+ case 'loading':
+ case 'load_error':
+ case 'not_ready':
+ case 'none':
+ return undefined;
+ }
+ });
+ const files = createMemo(() => changeset()?.files ?? []);
+ const tree = createMemo(() => buildFileTree(files()));
+
+ const hasPatch = () => {
+ const current = changeset();
+ return current !== undefined && current.patchBytes > 0;
+ };
+ const patch = source.patch(
+ () => changeset()?.id,
+ () => options.changesVisible() && hasPatch()
+ );
+ const diffs = createMemo(() => {
+ const text = patch.text();
+ return text === undefined ? undefined : parsePatch(text);
+ });
+ const entries = createMemo((): FileDiffEntry[] | undefined => {
+ const current = files();
+ if (current.length === 0) return [];
+ // An empty patch body means every file is binary or omitted; there is
+ // nothing to wait for.
+ if (!hasPatch()) return matchFilesToDiffs(current, new Map());
+ const parsed = diffs();
+ return parsed === undefined
+ ? undefined
+ : matchFilesToDiffs(current, parsed);
+ });
+
+ const [refreshing, setRefreshing] = createSignal(false);
+ const [refreshError, setRefreshError] = createSignal<string>();
+ const refresh = async () => {
+ if (refreshing()) return;
+ setRefreshing(true);
+ setRefreshError(undefined);
+ try {
+ await source.refresh();
+ } catch {
+ setRefreshError('The changes could not be refreshed. Try again.');
+ } finally {
+ setRefreshing(false);
+ }
+ };
+
+ return {
+ state,
+ changeset,
+ files,
+ tree,
+ entries,
+ patchStatus: patch.status,
+ retryPatch: patch.retry,
+ refresh,
+ refreshing,
+ refreshError,
+ };
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts b/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts
new file mode 100644
index 0000000000..7648ab783b
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-pane-layout.ts
@@ -0,0 +1,82 @@
+/**
+ * Pane visibility can be controlled by the host URL; the split width stays
+ * local to the reviewer and session.
+ */
+
+import type { Accessor } from 'solid-js';
+import {
+ clampChangesShare,
+ DEFAULT_CHANGES_SHARE,
+ ensureChangesVisible,
+ isChangesVisible,
+ isSessionVisible,
+ type PaneLayout,
+ toggleChanges,
+ toggleSpotlight,
+} from '../core/layout';
+import { createPersistedSessionState } from './create-persisted-session-state';
+
+export type PaneLayoutController = {
+ layout: Accessor<PaneLayout>;
+ changesVisible: Accessor<boolean>;
+ sessionVisible: Accessor<boolean>;
+ /** Percent of the width the changes pane takes in the split. */
+ changesShare: Accessor<number>;
+ setChangesShare: (share: number) => void;
+ toggle: () => void;
+ spotlight: () => void;
+ open: () => void;
+ close: () => void;
+ backToSplit: () => void;
+};
+
+type StoredLayout = { layout: PaneLayout; share: number };
+
+const LAYOUTS: readonly PaneLayout[] = ['split', 'agent-only', 'changes-only'];
+
+function parseStored(raw: unknown): StoredLayout | undefined {
+ if (typeof raw !== 'object' || raw === null) return undefined;
+ const { layout, share } = raw as Partial<StoredLayout>;
+ if (!layout || !LAYOUTS.includes(layout)) return undefined;
+ return {
+ layout,
+ share: clampChangesShare(typeof share === 'number' ? share : Number.NaN),
+ };
+}
+
+export function createPaneLayout(options: {
+ sessionId: Accessor<string | undefined>;
+ layout?: [get: Accessor<PaneLayout>, set: (layout: PaneLayout) => void];
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
+}): PaneLayoutController {
+ const [stored, setStored] = createPersistedSessionState<StoredLayout>({
+ sessionId: options.sessionId,
+ namespace: 'agent-changes:layout',
+ initial: () => ({ layout: 'agent-only', share: DEFAULT_CHANGES_SHARE }),
+ parse: parseStored,
+ storage: options.storage,
+ });
+ const layout = () => (options.layout ? options.layout[0]() : stored().layout);
+ const setLayout = (next: (layout: PaneLayout) => PaneLayout) => {
+ if (options.layout) options.layout[1](next(layout()));
+ else
+ setStored((previous) => ({ ...previous, layout: next(previous.layout) }));
+ };
+
+ return {
+ layout,
+ changesVisible: () => isChangesVisible(layout()),
+ sessionVisible: () => isSessionVisible(layout()),
+ changesShare: () => stored().share,
+ setChangesShare: (share) =>
+ setStored((previous) => ({
+ ...previous,
+ share: clampChangesShare(share),
+ })),
+ toggle: () => setLayout(toggleChanges),
+ spotlight: () => setLayout(toggleSpotlight),
+ open: () => setLayout(ensureChangesVisible),
+ close: () => setLayout(() => 'agent-only'),
+ backToSplit: () => setLayout(() => 'split'),
+ };
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-persisted-session-state.test.ts b/apps/web/src/features/agent-changes/primitives/create-persisted-session-state.test.ts
new file mode 100644
index 0000000000..66b3de6c81
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-persisted-session-state.test.ts
@@ -0,0 +1,72 @@
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import { createPersistedSessionState } from './create-persisted-session-state';
+
+function memoryStorage() {
+ const map = new Map<string, string>();
+ return {
+ map,
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, value),
+ removeItem: (key: string) => void map.delete(key),
+ };
+}
+
+describe('createPersistedSessionState', () => {
+ it('writes under the session key and reloads per session', () => {
+ createRoot((dispose) => {
+ const storage = memoryStorage();
+ const [sessionId, setSessionId] = createSignal<string | undefined>('s1');
+ const [count, setCount] = createPersistedSessionState<number>({
+ sessionId,
+ namespace: 'test',
+ initial: () => 0,
+ parse: (raw) => (typeof raw === 'number' ? raw : undefined),
+ storage,
+ });
+ expect(count()).toBe(0);
+ setCount((n) => n + 2);
+ expect(count()).toBe(2);
+ expect(storage.map.get('test:s1')).toBe('2');
+
+ setSessionId('s2');
+ expect(count()).toBe(0);
+ setCount(5);
+ expect(storage.map.get('test:s2')).toBe('5');
+
+ setSessionId('s1');
+ expect(count()).toBe(2);
+ dispose();
+ });
+ });
+
+ it('ignores junk in storage and keeps working without a session', () => {
+ createRoot((dispose) => {
+ const storage = memoryStorage();
+ storage.map.set('test:s1', '{not json');
+ const [sessionId] = createSignal<string | undefined>('s1');
+ const [value, setValue] = createPersistedSessionState<number>({
+ sessionId,
+ namespace: 'test',
+ initial: () => 1,
+ parse: (raw) => (typeof raw === 'number' ? raw : undefined),
+ storage,
+ });
+ expect(value()).toBe(1);
+
+ const [none] = createSignal<string | undefined>(undefined);
+ const [memory, setMemory] = createPersistedSessionState<number>({
+ sessionId: none,
+ namespace: 'test',
+ initial: () => 1,
+ parse: (raw) => (typeof raw === 'number' ? raw : undefined),
+ storage,
+ });
+ setMemory(9);
+ setValue(3);
+ expect(memory()).toBe(9);
+ expect(storage.map.has('test:undefined')).toBe(false);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/agent-changes/primitives/create-persisted-session-state.ts b/apps/web/src/features/agent-changes/primitives/create-persisted-session-state.ts
new file mode 100644
index 0000000000..b87ac12d9c
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-persisted-session-state.ts
@@ -0,0 +1,77 @@
+/**
+ * A signal scoped to one session and mirrored into `localStorage`, so a
+ * reload keeps the reviewer's place: which diffs they collapsed, the
+ * notes they have not sent yet, how the panes were laid out.
+ *
+ * The value re-loads whenever the session id changes; a missing id keeps
+ * the state in memory only.
+ */
+
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+
+export type PersistedSessionStateOptions<T> = {
+ /** The session the state belongs to; undefined while it is unknown. */
+ sessionId: Accessor<string | undefined>;
+ /** Storage key prefix; the session id is appended. */
+ namespace: string;
+ initial: () => T;
+ /** Turn a stored JSON value back into state, or reject it with undefined. */
+ parse: (raw: unknown) => T | undefined;
+ /** Defaults to `window.localStorage`; tests pass their own. */
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
+};
+
+function defaultStorage():
+ | Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>
+ | undefined {
+ try {
+ return typeof localStorage === 'undefined' ? undefined : localStorage;
+ } catch {
+ return undefined;
+ }
+}
+
+export function createPersistedSessionState<T>(
+ options: PersistedSessionStateOptions<T>
+): [get: Accessor<T>, set: (next: T | ((previous: T) => T)) => void] {
+ const storage = options.storage ?? defaultStorage();
+ const keyFor = (sessionId: string) => `${options.namespace}:${sessionId}`;
+
+ const load = (sessionId: string | undefined): T => {
+ if (!sessionId || !storage) return options.initial();
+ try {
+ const raw = storage.getItem(keyFor(sessionId));
+ if (raw == null) return options.initial();
+ return options.parse(JSON.parse(raw)) ?? options.initial();
+ } catch {
+ return options.initial();
+ }
+ };
+
+ const save = (sessionId: string | undefined, value: T) => {
+ if (!sessionId || !storage) return;
+ try {
+ storage.setItem(keyFor(sessionId), JSON.stringify(value));
+ } catch {
+ // Storage full or unavailable: the in-memory state still works.
+ }
+ };
+
+ // One signal per session id: switching sessions swaps to a freshly loaded
+ // signal instead of writing one session's state under another's key.
+ const scoped = createMemo(() => {
+ const sessionId = options.sessionId();
+ const [value, setValue] = createSignal<T>(load(sessionId));
+ return { sessionId, value, setValue };
+ });
+
+ const get: Accessor<T> = () => scoped().value();
+ const set = (next: T | ((previous: T) => T)) => {
+ const { sessionId, value, setValue } = scoped();
+ const resolved =
+ typeof next === 'function' ? (next as (previous: T) => T)(value()) : next;
+ setValue(() => resolved);
+ save(sessionId, resolved);
+ };
+ return [get, set];
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts b/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts
new file mode 100644
index 0000000000..76452fd9ff
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-review-state.test.ts
@@ -0,0 +1,134 @@
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import type { Changeset } from '../core/changeset';
+import { createReviewState } from './create-review-state';
+
+function changeset(id: string, paths: string[]): Changeset {
+ return {
+ id,
+ base: { name: 'main' },
+ head: { name: 'agent/x' },
+ files: paths.map((path) => ({
+ path,
+ kind: 'modified',
+ additions: 1,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ })),
+ additions: paths.length,
+ deletions: 0,
+ patchBytes: 1,
+ truncated: false,
+ capturedAt: 't',
+ };
+}
+
+function memoryStorage() {
+ const map = new Map<string, string>();
+ return {
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, value),
+ removeItem: (key: string) => void map.delete(key),
+ };
+}
+
+function setup() {
+ const [current, setCurrent] = createSignal<Changeset | undefined>(
+ changeset('cs1', ['a.ts', 'b.ts'])
+ );
+ const review = createReviewState({
+ sessionId: () => 's1',
+ changeset: current,
+ storage: memoryStorage(),
+ now: () => 'T',
+ newId: (() => {
+ let n = 0;
+ return () => `n${++n}`;
+ })(),
+ });
+ return { review, setCurrent };
+}
+
+describe('createReviewState', () => {
+ it('collapses and reopens an individual file', () => {
+ createRoot((dispose) => {
+ const { review } = setup();
+ expect(review.isCollapsed('a.ts')).toBe(false);
+ review.toggleCollapsed('a.ts');
+ expect(review.isCollapsed('a.ts')).toBe(true);
+ review.toggleCollapsed('a.ts');
+ expect(review.isCollapsed('a.ts')).toBe(false);
+ dispose();
+ });
+ });
+
+ it('collapses and expands everything from the bar', () => {
+ createRoot((dispose) => {
+ const { review } = setup();
+ review.toggleAllCollapsed();
+ expect(review.anyExpanded()).toBe(false);
+ review.toggleAllCollapsed();
+ expect(review.anyExpanded()).toBe(true);
+ dispose();
+ });
+ });
+
+ it('expands files for a new capture but keeps notes', () => {
+ createRoot((dispose) => {
+ const { review, setCurrent } = setup();
+ review.toggleCollapsed('a.ts');
+ review.addNote(
+ { path: 'a.ts', side: 'additions', lineNumber: 3, endLineNumber: 3 },
+ 'Rename'
+ );
+ setCurrent(changeset('cs2', ['a.ts', 'b.ts', 'c.ts']));
+ expect(review.isCollapsed('a.ts')).toBe(false);
+ expect(review.anyExpanded()).toBe(true);
+ expect(review.notes()).toHaveLength(1);
+ review.toggleCollapsed('c.ts');
+ expect(review.isCollapsed('c.ts')).toBe(true);
+ dispose();
+ });
+ });
+
+ it('activating a file uncollapses it and points the stack at it', () => {
+ createRoot((dispose) => {
+ const { review } = setup();
+ review.toggleCollapsed('b.ts');
+ review.activate('b.ts');
+ expect(review.active()).toBe('b.ts');
+ expect(review.isCollapsed('b.ts')).toBe(false);
+ dispose();
+ });
+ });
+
+ it('queues, sends, and removes notes', () => {
+ createRoot((dispose) => {
+ const { review } = setup();
+ const anchor = {
+ path: 'a.ts',
+ side: 'additions' as const,
+ lineNumber: 10,
+ endLineNumber: 12,
+ };
+ review.openNote(anchor);
+ expect(review.composing()).toEqual(anchor);
+ review.addNote(anchor, ' ');
+ expect(review.composing()).toBeUndefined();
+ expect(review.notes()).toHaveLength(0);
+
+ review.addNote(anchor, 'Extract a helper');
+ review.addNote({ ...anchor, path: 'b.ts' }, 'Keep');
+ expect(review.queued().map((note) => note.id)).toEqual(['n1', 'n2']);
+
+ review.removeNote('n2');
+ const sent = review.markQueuedSent();
+ expect(sent.map((note) => note.id)).toEqual(['n1']);
+ expect(review.queued()).toEqual([]);
+ expect(review.notes()[0]?.sentAt).toBe('T');
+ expect(review.markQueuedSent()).toEqual([]);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/agent-changes/primitives/create-review-state.ts b/apps/web/src/features/agent-changes/primitives/create-review-state.ts
new file mode 100644
index 0000000000..7330b941aa
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-review-state.ts
@@ -0,0 +1,202 @@
+/**
+ * The reviewer's state for a changeset: collapsed diffs, the file the tree
+ * last pointed at, and the notes queued for the agent.
+ *
+ * Collapsed diffs belong to one capture: a new changeset expands them.
+ * Notes outlive captures, since they are the reviewer's words,
+ * and are only cleared by sending or deleting them.
+ */
+
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import type { Changeset } from '../core/changeset';
+import {
+ type NoteAnchor,
+ noteAnchorKey,
+ queuedNotes,
+ type ReviewNote,
+} from '../core/review-notes';
+import { createPersistedSessionState } from './create-persisted-session-state';
+
+export type ReviewController = {
+ collapsed: Accessor<ReadonlySet<string>>;
+ isCollapsed: (path: string) => boolean;
+ toggleCollapsed: (path: string) => void;
+ /** Collapse every diff, or expand them all when none is open. */
+ toggleAllCollapsed: () => void;
+ anyExpanded: Accessor<boolean>;
+
+ /** The file the tree last selected; the stack scrolls to it. */
+ active: Accessor<string | undefined>;
+ /** Select a file: it uncollapses and becomes the scroll target. */
+ activate: (path: string) => void;
+
+ notes: Accessor<ReviewNote[]>;
+ queued: Accessor<ReviewNote[]>;
+ /** Where a note is being written, if one is. */
+ composing: Accessor<NoteAnchor | undefined>;
+ openNote: (anchor: NoteAnchor) => void;
+ cancelNote: () => void;
+ addNote: (anchor: NoteAnchor, text: string) => void;
+ removeNote: (id: string) => void;
+ /** Stamp every queued note as sent, returning what was sent. */
+ markQueuedSent: () => ReviewNote[];
+};
+
+type StoredReview = {
+ /** The capture `collapsed` was made against. */
+ changesetId: string | undefined;
+ collapsed: string[];
+ notes: ReviewNote[];
+};
+
+const SIDES = new Set(['additions', 'deletions']);
+
+function isNote(raw: unknown): raw is ReviewNote {
+ if (typeof raw !== 'object' || raw === null) return false;
+ const note = raw as Record<string, unknown>;
+ return (
+ typeof note.id === 'string' &&
+ typeof note.path === 'string' &&
+ typeof note.side === 'string' &&
+ SIDES.has(note.side) &&
+ typeof note.lineNumber === 'number' &&
+ typeof note.endLineNumber === 'number' &&
+ typeof note.text === 'string' &&
+ typeof note.createdAt === 'string' &&
+ (note.sentAt === undefined || typeof note.sentAt === 'string')
+ );
+}
+
+function strings(raw: unknown): string[] {
+ return Array.isArray(raw)
+ ? raw.filter((item): item is string => typeof item === 'string')
+ : [];
+}
+
+function parseStored(raw: unknown): StoredReview | undefined {
+ if (typeof raw !== 'object' || raw === null) return undefined;
+ const stored = raw as Record<string, unknown>;
+ return {
+ changesetId:
+ typeof stored.changesetId === 'string' ? stored.changesetId : undefined,
+ collapsed: strings(stored.collapsed),
+ notes: Array.isArray(stored.notes) ? stored.notes.filter(isNote) : [],
+ };
+}
+
+function toggleIn(list: readonly string[], path: string): string[] {
+ return list.includes(path)
+ ? list.filter((item) => item !== path)
+ : [...list, path];
+}
+
+export function createReviewState(options: {
+ sessionId: Accessor<string | undefined>;
+ changeset: Accessor<Changeset | undefined>;
+ storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
+ now?: () => string;
+ newId?: () => string;
+}): ReviewController {
+ const now = options.now ?? (() => new Date().toISOString());
+ const newId =
+ options.newId ??
+ (() =>
+ typeof crypto !== 'undefined' && 'randomUUID' in crypto
+ ? crypto.randomUUID()
+ : `${Date.now()}-${Math.random().toString(36).slice(2)}`);
+
+ const [stored, setStored] = createPersistedSessionState<StoredReview>({
+ sessionId: options.sessionId,
+ namespace: 'agent-changes:review',
+ initial: () => ({
+ changesetId: undefined,
+ collapsed: [],
+ notes: [],
+ }),
+ parse: parseStored,
+ storage: options.storage,
+ });
+ const [active, setActive] = createSignal<string | undefined>();
+ const [composing, setComposing] = createSignal<NoteAnchor | undefined>();
+
+ const changesetId = () => options.changeset()?.id;
+ const paths = createMemo(
+ () => options.changeset()?.files.map((file) => file.path) ?? []
+ );
+
+ // Collapsed files from an older capture read as empty; the next write
+ // re-keys the stored state to the current capture.
+ const collapsed = createMemo(() => {
+ const current = stored();
+ return new Set(
+ current.changesetId === changesetId() ? current.collapsed : []
+ );
+ });
+ const writeCollapsed = (update: (paths: string[]) => string[]) =>
+ setStored((previous) => ({
+ ...previous,
+ changesetId: changesetId(),
+ collapsed: update([...collapsed()]),
+ }));
+
+ const anyExpanded = () => paths().some((path) => !collapsed().has(path));
+
+ const notes = () => stored().notes;
+
+ return {
+ collapsed,
+ isCollapsed: (path) => collapsed().has(path),
+ toggleCollapsed: (path) => writeCollapsed((paths) => toggleIn(paths, path)),
+ toggleAllCollapsed: () =>
+ writeCollapsed(() => (anyExpanded() ? [...paths()] : [])),
+ anyExpanded,
+
+ active,
+ activate: (path) => {
+ if (collapsed().has(path)) {
+ writeCollapsed((paths) => paths.filter((item) => item !== path));
+ }
+ // Re-selecting the same file must still scroll, so clear first.
+ setActive(undefined);
+ setActive(path);
+ },
+
+ notes,
+ queued: () => queuedNotes(notes()),
+ composing,
+ openNote: (anchor) => setComposing(anchor),
+ cancelNote: () => setComposing(undefined),
+ addNote: (anchor, text) => {
+ const trimmed = text.trim();
+ const current = composing();
+ if (current && noteAnchorKey(current) === noteAnchorKey(anchor)) {
+ setComposing(undefined);
+ }
+ if (trimmed === '') return;
+ setStored((previous) => ({
+ ...previous,
+ notes: [
+ ...previous.notes,
+ { id: newId(), ...anchor, text: trimmed, createdAt: now() },
+ ],
+ }));
+ },
+ removeNote: (id) =>
+ setStored((previous) => ({
+ ...previous,
+ notes: previous.notes.filter((note) => note.id !== id),
+ })),
+ markQueuedSent: () => {
+ const sent = queuedNotes(notes());
+ if (sent.length === 0) return [];
+ const sentAt = now();
+ setStored((previous) => ({
+ ...previous,
+ notes: previous.notes.map((note) =>
+ note.sentAt === undefined ? { ...note, sentAt } : note
+ ),
+ }));
+ return sent.map((note) => ({ ...note, sentAt }));
+ },
+ };
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-theme-type.ts b/apps/web/src/features/agent-changes/primitives/create-theme-type.ts
new file mode 100644
index 0000000000..f5712f09b3
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-theme-type.ts
@@ -0,0 +1,33 @@
+/**
+ * Macro's light/dark state as a signal for Pierre, tracked off the
+ * `data-theme-light` attribute the theme feature keeps on `<html>`.
+ */
+
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
+
+export type ThemeType = 'light' | 'dark';
+
+function currentThemeType(): ThemeType {
+ if (typeof document === 'undefined') return 'light';
+ return document.documentElement.dataset.themeLight === 'false'
+ ? 'dark'
+ : 'light';
+}
+
+export function createThemeType(): Accessor<ThemeType> {
+ const [themeType, setThemeType] = createSignal<ThemeType>(currentThemeType());
+ if (
+ typeof document !== 'undefined' &&
+ typeof MutationObserver !== 'undefined'
+ ) {
+ const observer = new MutationObserver(() =>
+ setThemeType(currentThemeType())
+ );
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme-light'],
+ });
+ onCleanup(() => observer.disconnect());
+ }
+ return themeType;
+}
diff --git a/apps/web/src/features/agent-changes/primitives/create-url-diff-state.test.tsx b/apps/web/src/features/agent-changes/primitives/create-url-diff-state.test.tsx
new file mode 100644
index 0000000000..e01a9919f0
--- /dev/null
+++ b/apps/web/src/features/agent-changes/primitives/create-url-diff-state.test.tsx
@@ -0,0 +1,115 @@
+import { createMemoryHistory, MemoryRouter, Route } from '@solidjs/router';
+import { render, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { describe, expect, it } from 'vitest';
+import { readDiffUrlState } from '../core/url-state';
+import { createMemoryStorage } from '../tests/memory-storage';
+import { createUrlDiffState } from '../url-diff-state';
+import { createPaneLayout } from './create-pane-layout';
+
+function setup(url: string) {
+ const history = createMemoryHistory();
+ history.set({ value: url, replace: true });
+ const [sessionId, setSessionId] = createSignal('s1');
+ let state!: ReturnType<typeof createUrlDiffState>;
+ let layout!: ReturnType<typeof createPaneLayout>;
+ const mounted = render(() => (
+ <MemoryRouter history={history}>
+ <Route
+ path="/session"
+ component={() => {
+ state = createUrlDiffState(sessionId);
+ layout = createPaneLayout({
+ sessionId,
+ storage: createMemoryStorage(),
+ layout: [state.layout, state.setLayout],
+ });
+ return (
+ <div>
+ {layout.layout()}:{state.diffStyle()}
+ </div>
+ );
+ }}
+ />
+ </MemoryRouter>
+ ));
+ return {
+ ...mounted,
+ history,
+ state: () => state,
+ layout: () => layout,
+ setSessionId,
+ };
+}
+
+describe('URL diff state', () => {
+ it('restores a shared view and follows browser history for open, spotlight, style, and close', async () => {
+ const { history, state, layout } = setup(
+ '/session?keep=1&diff=s1:split:unified#message'
+ );
+ expect(layout().changesVisible()).toBe(true);
+ expect(layout().sessionVisible()).toBe(true);
+ state().setDiffStyle('split');
+ await waitFor(() => expect(state().diffStyle()).toBe('split'));
+ layout().spotlight();
+ await waitFor(() => expect(layout().sessionVisible()).toBe(false));
+ const shared = new URL(history.get(), 'http://local');
+ expect(shared.searchParams.get('keep')).toBe('1');
+ expect(shared.hash).toBe('#message');
+ expect(readDiffUrlState(shared.searchParams.get('diff'), 's1')).toEqual({
+ layout: 'changes-only',
+ diffStyle: 'split',
+ });
+ layout().close();
+ await waitFor(() => expect(layout().changesVisible()).toBe(false));
+ history.back();
+ await waitFor(() => expect(layout().layout()).toBe('changes-only'));
+ history.back();
+ await waitFor(() => expect(layout().layout()).toBe('split'));
+ history.back();
+ await waitFor(() => expect(state().diffStyle()).toBe('unified'));
+ history.forward();
+ await waitFor(() => expect(state().diffStyle()).toBe('split'));
+ });
+
+ it('keeps session states separate and a plain URL closed', async () => {
+ const { history, state, layout, setSessionId } = setup(
+ '/session?diff=s2:changes-only:split'
+ );
+ expect(layout().changesVisible()).toBe(false);
+ layout().open();
+ await waitFor(() => expect(layout().layout()).toBe('split'));
+ expect(
+ readDiffUrlState(
+ new URL(history.get(), 'http://local').searchParams.get('diff'),
+ 's2'
+ )
+ ).toEqual({ layout: 'changes-only', diffStyle: 'split' });
+ layout().close();
+ await waitFor(() => expect(layout().changesVisible()).toBe(false));
+ expect(
+ new URL(history.get(), 'http://local').searchParams.get('diff')
+ ).toBe('s2:changes-only:split');
+ setSessionId('s2');
+ expect(layout().layout()).toBe('changes-only');
+ expect(state().diffStyle()).toBe('split');
+ setSessionId('s3');
+ expect(layout().changesVisible()).toBe(false);
+ });
+
+ it('ignores malformed values and does not put divider drags into history', async () => {
+ const { history, layout } = setup(
+ '/session?diff=s1:invalid:split,s2:split:invalid'
+ );
+ expect(layout().changesVisible()).toBe(false);
+ const before = history.get();
+ layout().setChangesShare(65);
+ expect(layout().changesShare()).toBe(65);
+ expect(history.get()).toBe(before);
+ layout().open();
+ await waitFor(() => expect(layout().layout()).toBe('split'));
+ expect(
+ new URL(history.get(), 'http://local').searchParams.get('diff')
+ ).toBe('s1:split:unified');
+ });
+});
diff --git a/apps/web/src/features/agent-changes/queries/session-changes.test.ts b/apps/web/src/features/agent-changes/queries/session-changes.test.ts
new file mode 100644
index 0000000000..af295b18d2
--- /dev/null
+++ b/apps/web/src/features/agent-changes/queries/session-changes.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+import { decodeSessionChanges } from './session-changes';
+
+describe('decodeSessionChanges', () => {
+ it('turns wire nulls into absent fields', () => {
+ const decoded = decodeSessionChanges({
+ capturing: false,
+ attempt: {
+ startedAt: 't0',
+ finishedAt: null,
+ outcome: null,
+ error: null,
+ },
+ changeset: {
+ id: 'cs',
+ source: 'github_pull_request',
+ repository: null,
+ base: { name: 'main', sha: null },
+ head: { name: null, sha: 'abc' },
+ files: [
+ {
+ path: 'a.ts',
+ previousPath: null,
+ kind: 'modified',
+ additions: 1,
+ deletions: 2,
+ binary: false,
+ patchOmitted: false,
+ },
+ ],
+ additions: 1,
+ deletions: 2,
+ patchBytes: 10,
+ truncated: false,
+ capturedAt: 't1',
+ },
+ });
+ expect(decoded.attempt).toEqual({ startedAt: 't0' });
+ expect(decoded.changeset?.repository).toBeUndefined();
+ expect(decoded.changeset?.base).toEqual({ name: 'main' });
+ expect(decoded.changeset?.head).toEqual({ sha: 'abc' });
+ expect(decoded.changeset?.files[0]).toEqual({
+ path: 'a.ts',
+ kind: 'modified',
+ additions: 1,
+ deletions: 2,
+ binary: false,
+ patchOmitted: false,
+ });
+ });
+});
diff --git a/apps/web/src/features/agent-changes/queries/session-changes.ts b/apps/web/src/features/agent-changes/queries/session-changes.ts
new file mode 100644
index 0000000000..d711ce1fc9
--- /dev/null
+++ b/apps/web/src/features/agent-changes/queries/session-changes.ts
@@ -0,0 +1,136 @@
+/**
+ * Adapts the agent-harness changes queries to the pane's `ChangesSource`:
+ * wire DTOs become core types here, and TanStack status becomes the small
+ * status vocabulary the primitives read.
+ */
+
+import {
+ useAgentSessionChangesPatchQuery,
+ useAgentSessionChangesQuery,
+ useRefreshAgentSessionChangesMutation,
+} from '@queries/agent-session/changes';
+import type {
+ AgentSessionChangesResponse,
+ CaptureAttemptDto,
+ ChangedFileDto,
+ ChangesetDto,
+ GitRefDto,
+} from '@service-agent-harness/generated/schemas';
+import type { Accessor } from 'solid-js';
+import type {
+ ChangesSource,
+ PatchRead,
+ QueryStatus,
+} from '../context/agent-changes-context';
+import type {
+ CaptureAttempt,
+ ChangedFile,
+ Changeset,
+ GitRef,
+ SessionChanges,
+} from '../core/changeset';
+
+function decodeRef(ref: GitRefDto): GitRef {
+ return {
+ name: ref.name ?? undefined,
+ sha: ref.sha ?? undefined,
+ };
+}
+
+function decodeFile(file: ChangedFileDto): ChangedFile {
+ return {
+ path: file.path,
+ previousPath: file.previousPath ?? undefined,
+ kind: file.kind,
+ additions: file.additions,
+ deletions: file.deletions,
+ binary: file.binary,
+ patchOmitted: file.patchOmitted,
+ };
+}
+
+export function decodeChangeset(dto: ChangesetDto): Changeset {
+ return {
+ id: dto.id,
+ repository: dto.repository ?? undefined,
+ base: decodeRef(dto.base),
+ head: decodeRef(dto.head),
+ files: dto.files.map(decodeFile),
+ additions: dto.additions,
+ deletions: dto.deletions,
+ patchBytes: dto.patchBytes,
+ truncated: dto.truncated,
+ capturedAt: dto.capturedAt,
+ };
+}
+
+function decodeAttempt(dto: CaptureAttemptDto): CaptureAttempt {
+ return {
+ startedAt: dto.startedAt,
+ finishedAt: dto.finishedAt ?? undefined,
+ outcome: dto.outcome ?? undefined,
+ error: dto.error ?? undefined,
+ };
+}
+
+export function decodeSessionChanges(
+ dto: AgentSessionChangesResponse
+): SessionChanges {
+ return {
+ changeset: dto.changeset ? decodeChangeset(dto.changeset) : undefined,
+ attempt: dto.attempt ? decodeAttempt(dto.attempt) : undefined,
+ capturing: dto.capturing,
+ };
+}
+
+function queryStatus(query: {
+ isPending: boolean;
+ isError: boolean;
+ isSuccess: boolean;
+ fetchStatus: string;
+}): QueryStatus {
+ if (query.isSuccess) return 'success';
+ if (query.isError) return 'error';
+ if (query.isPending && query.fetchStatus === 'idle') return 'idle';
+ return 'pending';
+}
+
+/** The production source: TanStack queries against the agent-harness service. */
+export function createSessionChangesSource(
+ sessionId: Accessor<string | undefined>
+): ChangesSource {
+ const summaryQuery = useAgentSessionChangesQuery(sessionId);
+ const refresh = useRefreshAgentSessionChangesMutation();
+
+ // Gate every `data` read on status: an unguarded read suspends the
+ // nearest boundary (apps/web/AGENTS.md).
+ const summary = () =>
+ summaryQuery.isSuccess
+ ? decodeSessionChanges(summaryQuery.data)
+ : undefined;
+
+ const patch = (
+ changesetId: Accessor<string | undefined>,
+ enabled: Accessor<boolean>
+ ): PatchRead => {
+ const query = useAgentSessionChangesPatchQuery(sessionId, () =>
+ enabled() ? changesetId() : undefined
+ );
+ return {
+ text: () => (query.isSuccess ? query.data.patch : undefined),
+ status: () => queryStatus(query),
+ retry: () => void query.refetch(),
+ };
+ };
+
+ return {
+ summary,
+ summaryStatus: () => queryStatus(summaryQuery),
+ patch,
+ refresh: async () => {
+ const id = sessionId();
+ if (!id) return;
+ await refresh.mutateAsync(id);
+ },
+ };
+}
diff --git a/apps/web/src/features/agent-changes/tests/memory-storage.ts b/apps/web/src/features/agent-changes/tests/memory-storage.ts
new file mode 100644
index 0000000000..eefd6429ea
--- /dev/null
+++ b/apps/web/src/features/agent-changes/tests/memory-storage.ts
@@ -0,0 +1,10 @@
+/** A `localStorage` stand-in for tests. */
+export function createMemoryStorage() {
+ const map = new Map<string, string>();
+ return {
+ map,
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, value),
+ removeItem: (key: string) => void map.delete(key),
+ };
+}
diff --git a/apps/web/src/features/agent-changes/tests/mock-context.ts b/apps/web/src/features/agent-changes/tests/mock-context.ts
new file mode 100644
index 0000000000..62fab19dfd
--- /dev/null
+++ b/apps/web/src/features/agent-changes/tests/mock-context.ts
@@ -0,0 +1,133 @@
+/**
+ * In-memory implementations of the pane's capabilities, so view and
+ * primitive tests run the real feature code against controllable data.
+ */
+
+import { createSignal } from 'solid-js';
+import type {
+ AgentChangesContext,
+ ChangesAgent,
+ ChangesHost,
+ ChangesSource,
+ PatchRead,
+ QueryStatus,
+} from '../context/agent-changes-context';
+import type { Changeset, SessionChanges } from '../core/changeset';
+
+export const MOCK_PATCH = `diff --git a/apps/web/src/a.ts b/apps/web/src/a.ts
+index 1111111..2222222 100644
+--- a/apps/web/src/a.ts
++++ b/apps/web/src/a.ts
+@@ -1,3 +1,3 @@
+ const a = 1;
+-const b = 2;
++const b = 3;
+ export { a, b };
+diff --git a/crates/x/src/lib.rs b/crates/x/src/lib.rs
+new file mode 100644
+index 0000000..3333333
+--- /dev/null
++++ b/crates/x/src/lib.rs
+@@ -0,0 +1,2 @@
++pub fn x() {}
++pub fn y() {}
+`;
+
+export function mockChangeset(overrides: Partial<Changeset> = {}): Changeset {
+ return {
+ id: 'cs-1',
+ repository: 'https://github.com/macro-inc/macro',
+ base: { name: 'main' },
+ head: { name: 'agent/unread-archived-sessions' },
+ files: [
+ {
+ path: 'apps/web/src/a.ts',
+ kind: 'modified',
+ additions: 1,
+ deletions: 1,
+ binary: false,
+ patchOmitted: false,
+ },
+ {
+ path: 'crates/x/src/lib.rs',
+ kind: 'added',
+ additions: 2,
+ deletions: 0,
+ binary: false,
+ patchOmitted: false,
+ },
+ ],
+ additions: 3,
+ deletions: 1,
+ patchBytes: MOCK_PATCH.length,
+ truncated: false,
+ capturedAt: '2026-09-15T00:00:00Z',
+ ...overrides,
+ };
+}
+
+export type MockAgentChangesContext = AgentChangesContext & {
+ host: ChangesHost & { agent: ChangesAgent };
+ setSummary: (summary: SessionChanges | undefined) => void;
+ setPatch: (patch: string | undefined) => void;
+ setPullRequestUrl: (url: string | undefined) => void;
+ sent: string[];
+ opened: string[];
+ notified: { message: string; tone: 'success' | 'failure' }[];
+ refreshes: () => number;
+};
+
+export function createMockAgentChangesContext(
+ options: {
+ summary?: SessionChanges;
+ patch?: string;
+ canSend?: boolean;
+ sessionId?: string;
+ } = {}
+): MockAgentChangesContext {
+ const [summary, setSummary] = createSignal<SessionChanges | undefined>(
+ options.summary
+ );
+ const [patch, setPatch] = createSignal<string | undefined>(options.patch);
+ const [pullRequestUrl, setPullRequestUrl] = createSignal<string>();
+ const sent: string[] = [];
+ const opened: string[] = [];
+ const notified: { message: string; tone: 'success' | 'failure' }[] = [];
+ let refreshes = 0;
+
+ const source: ChangesSource = {
+ summary,
+ summaryStatus: () => (summary() ? 'success' : 'pending'),
+ patch: (changesetId, enabled): PatchRead => ({
+ text: () => (enabled() && changesetId() ? patch() : undefined),
+ status: (): QueryStatus =>
+ !enabled() ? 'idle' : patch() === undefined ? 'pending' : 'success',
+ retry: () => {},
+ }),
+ refresh: async () => {
+ refreshes += 1;
+ },
+ };
+ const host: ChangesHost & { agent: ChangesAgent } = {
+ scopeKey: () => options.sessionId ?? 'session-1',
+ agent: {
+ send: (markdown) => void sent.push(markdown),
+ canSend: () => options.canSend ?? true,
+ },
+ pullRequestUrl,
+ openExternal: (url) => void opened.push(url),
+ copyText: async () => true,
+ notify: (message, tone) => void notified.push({ message, tone }),
+ };
+ return {
+ source,
+ host,
+ setSummary,
+ setPatch,
+ setPullRequestUrl,
+ sent,
+ opened,
+ notified,
+ refreshes: () => refreshes,
+ };
+}
diff --git a/apps/web/src/features/agent-changes/url-diff-state.ts b/apps/web/src/features/agent-changes/url-diff-state.ts
new file mode 100644
index 0000000000..dbafe3d6ef
--- /dev/null
+++ b/apps/web/src/features/agent-changes/url-diff-state.ts
@@ -0,0 +1,28 @@
+import { useSearchParams } from '@solidjs/router';
+import type { Accessor } from 'solid-js';
+import type { DiffStyle, PaneLayout } from './core/layout';
+import {
+ type DiffUrlState,
+ readDiffUrlState,
+ writeDiffUrlState,
+} from './core/url-state';
+
+/** Read directly from the router so reloads and Back/Forward restore the view. */
+export function createUrlDiffState(scopeKey: Accessor<string | undefined>) {
+ const [params, setParams] = useSearchParams();
+ const state = () => readDiffUrlState(params.diff, scopeKey());
+ const update = (patch: Partial<DiffUrlState>) => {
+ const id = scopeKey();
+ if (!id) return;
+ setParams(
+ { diff: writeDiffUrlState(params.diff, id, { ...state(), ...patch }) },
+ { replace: false, scroll: false }
+ );
+ };
+ return {
+ layout: () => state().layout,
+ setLayout: (layout: PaneLayout) => update({ layout }),
+ diffStyle: () => state().diffStyle,
+ setDiffStyle: (diffStyle: DiffStyle) => update({ diffStyle }),
+ };
+}
diff --git a/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx b/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
new file mode 100644
index 0000000000..d10c4d8b76
--- /dev/null
+++ b/apps/web/src/features/agent-changes/views/AgentChangesSplit.tsx
@@ -0,0 +1,56 @@
+/**
+ * The session and its Changes pane side by side, on a draggable divider.
+ * Closing the pane hands the width back to the session; spotlighting it
+ * takes the session's width away.
+ */
+
+import { Resize } from '@core/component/Resize';
+import type { ResizeZoneCtx } from '@core/component/Resize/types';
+import { type ParentProps, Show } from 'solid-js';
+import { useAgentChanges } from '../context/agent-changes-controller';
+import { ChangesPane } from './ChangesPane';
+
+const SESSION_MIN_PX = 320;
+const CHANGES_MIN_PX = 400;
+
+export function AgentChangesSplit(props: ParentProps) {
+ const { layout } = useAgentChanges();
+ let zone: ResizeZoneCtx | undefined;
+
+ return (
+ <Resize.Zone
+ direction="horizontal"
+ gutter={1}
+ resizable
+ captureResizeCtx={(ctx) => {
+ zone = ctx;
+ }}
+ >
+ {/* Panels mount and unmount with the layout: an unregistered panel
+ would still paint its content at the zone's left edge. */}
+ <Show when={layout.sessionVisible()}>
+ <Resize.Panel id="agent-session" minSize={SESSION_MIN_PX} index={0}>
+ <div class="flex h-full min-w-0 flex-col overflow-hidden">
+ {props.children}
+ </div>
+ </Resize.Panel>
+ </Show>
+ <Show when={layout.changesVisible()}>
+ <Resize.Panel
+ id="agent-changes"
+ minSize={CHANGES_MIN_PX}
+ index={1}
+ target={layout.changesShare()}
+ onSizeChangeEnd={(size) => {
+ const total = zone?.size() ?? 0;
+ if (total > 0) layout.setChangesShare((size / total) * 100);
+ }}
+ >
+ <div class="h-full min-w-0 overflow-hidden">
+ <ChangesPane />
+ </div>
+ </Resize.Panel>
+ </Show>
+ </Resize.Zone>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/views/ChangesPane.tsx b/apps/web/src/features/agent-changes/views/ChangesPane.tsx
new file mode 100644
index 0000000000..43acdaf8e3
--- /dev/null
+++ b/apps/web/src/features/agent-changes/views/ChangesPane.tsx
@@ -0,0 +1,287 @@
+/**
+ * The Changes pane: header, review bar, file tree, the stack of file cards,
+ * and their inline notes. Reads the controller and hands
+ * resolved values to the components.
+ */
+
+import CircleNotchIcon from '@phosphor/circle-notch.svg';
+import WarningCircleIcon from '@phosphor/warning-circle.svg';
+import { Button } from '@ui';
+import {
+ createEffect,
+ createSignal,
+ For,
+ Match,
+ on,
+ onCleanup,
+ Show,
+ Switch,
+} from 'solid-js';
+import { ChangesHeader } from '../components/ChangesHeader';
+import { CaptureBanner, ChangesNotice } from '../components/ChangesNotice';
+import { FileCard } from '../components/FileCard';
+import { FileTree } from '../components/FileTree';
+import { PierreFileDiff } from '../components/PierreFileDiff';
+import { ReviewBar } from '../components/ReviewBar';
+import { useAgentChanges } from '../context/agent-changes-controller';
+import { type ChangesState, describeRange } from '../core/changeset';
+import type { FileDiffEntry } from '../core/patch';
+import { notesForFile } from '../core/review-notes';
+import { createThemeType } from '../primitives/create-theme-type';
+
+const FLASH_MS = 900;
+
+function DiffStack(props: { entries: FileDiffEntry[] }) {
+ const { review, diffStyle, copyPath, context } = useAgentChanges();
+ const themeType = createThemeType();
+ const cards = new Map<string, HTMLElement>();
+ const [flashing, setFlashing] = createSignal<string>();
+
+ // Jumping from the tree is a DOM concern: scroll the card in and flash it.
+ createEffect(
+ on(
+ review.active,
+ (path) => {
+ if (!path) return;
+ cards.get(path)?.scrollIntoView({ block: 'start', behavior: 'smooth' });
+ setFlashing(path);
+ const timer = setTimeout(() => setFlashing(undefined), FLASH_MS);
+ onCleanup(() => clearTimeout(timer));
+ },
+ { defer: true }
+ )
+ );
+
+ return (
+ <div class="flex min-h-0 min-w-0 flex-1 flex-col gap-3 overflow-y-auto scroll-smooth px-3.5 pt-3 pb-24 motion-reduce:scroll-auto">
+ <For each={props.entries}>
+ {(entry) => {
+ const path = () => entry.file.path;
+ const composing = () => {
+ const anchor = review.composing();
+ return anchor?.path === path() ? anchor : undefined;
+ };
+ return (
+ <FileCard
+ entry={entry}
+ collapsed={review.isCollapsed(path())}
+ flash={flashing() === path()}
+ onToggleCollapsed={() => review.toggleCollapsed(path())}
+ onCopyPath={() => copyPath(path())}
+ ref={(element) => {
+ cards.set(path(), element);
+ onCleanup(() => cards.delete(path()));
+ }}
+ body={
+ <Show when={entry.diff}>
+ {(diff) => (
+ <PierreFileDiff
+ path={path()}
+ diff={diff()}
+ diffStyle={diffStyle()}
+ themeType={themeType()}
+ notes={notesForFile(review.notes(), path())}
+ composing={composing()}
+ onOpenNote={
+ context.host.agent ? review.openNote : undefined
+ }
+ onCancelNote={review.cancelNote}
+ onAddNote={review.addNote}
+ onRemoveNote={review.removeNote}
+ />
+ )}
+ </Show>
+ }
+ />
+ );
+ }}
+ </For>
+ </div>
+ );
+}
+
+export function ChangesPane() {
+ const controller = useAgentChanges();
+ const { layout, model, review, context, diffStyle, setDiffStyle } =
+ controller;
+ const state = model.state;
+ const changeset = model.changeset;
+ /** The state narrowed to one kind, for `<Match>` to hand its fields down. */
+ const stateOf = <K extends ChangesState['kind']>(kind: K) => {
+ const current = state();
+ return current.kind === kind
+ ? (current as Extract<ChangesState, { kind: K }>)
+ : undefined;
+ };
+ const range = () => {
+ const current = changeset();
+ return current ? describeRange(current) : undefined;
+ };
+ const hasFiles = () => model.files().length > 0;
+ const showsChangeset = () => changeset() !== undefined;
+
+ return (
+ <section
+ class="relative flex h-full min-w-0 flex-col bg-panel"
+ aria-label="Changes"
+ >
+ <ChangesHeader
+ spotlit={layout.layout() === 'changes-only'}
+ range={range()}
+ diffStyle={diffStyle()}
+ onDiffStyle={setDiffStyle}
+ pullRequestUrl={context.host.pullRequestUrl()}
+ onViewPullRequest={() => {
+ const url = context.host.pullRequestUrl();
+ if (url) context.host.openExternal(url);
+ }}
+ refreshing={model.refreshing() || state().kind === 'capturing'}
+ onRefresh={() => void model.refresh()}
+ onBack={layout.backToSplit}
+ onSpotlight={layout.spotlight}
+ onClose={layout.close}
+ />
+ <Show when={model.refreshError()}>
+ {(message) => (
+ <CaptureBanner
+ tone="failure"
+ text={message()}
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ )}
+ </Show>
+ <Switch>
+ <Match when={state().kind === 'loading'}>
+ <ChangesNotice
+ icon={<CircleNotchIcon class="animate-spin" />}
+ title="Loading changes"
+ />
+ </Match>
+ <Match when={state().kind === 'load_error'}>
+ <ChangesNotice
+ icon={<WarningCircleIcon />}
+ title="The changes could not be loaded"
+ detail="The changes service did not answer. Try again in a moment."
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ </Match>
+ <Match when={stateOf('not_ready')}>
+ {(current) => (
+ <ChangesNotice
+ title="Pull request changes unavailable"
+ detail={current().message}
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ )}
+ </Match>
+ <Match when={state().kind === 'none'}>
+ <ChangesNotice
+ title="No pull request changes loaded"
+ detail="Link a GitHub pull request, then refresh to review its changes."
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ </Match>
+ <Match when={showsChangeset() ? undefined : stateOf('failed')}>
+ {(current) => (
+ <ChangesNotice
+ icon={<WarningCircleIcon />}
+ title="The changes could not be captured"
+ detail={current().message}
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ )}
+ </Match>
+ <Match when={state().kind === 'capturing' && !showsChangeset()}>
+ <ChangesNotice
+ icon={<CircleNotchIcon class="animate-spin" />}
+ title="Capturing the changes"
+ detail="Reading the linked pull request from GitHub."
+ />
+ </Match>
+ <Match when={showsChangeset()}>
+ <Show when={state().kind === 'capturing'}>
+ <CaptureBanner
+ tone="progress"
+ text="Capturing the changes again…"
+ />
+ </Show>
+ <Show when={stateOf('failed')}>
+ {(current) => (
+ <CaptureBanner
+ tone="failure"
+ text={`The last capture failed: ${current().message}`}
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ )}
+ </Show>
+ <Show
+ when={hasFiles()}
+ fallback={
+ <ChangesNotice
+ title="No changes"
+ detail={
+ range()
+ ? `Nothing differs between ${range()}.`
+ : 'The pull request has no changed files.'
+ }
+ onRefresh={() => void model.refresh()}
+ refreshing={model.refreshing()}
+ />
+ }
+ >
+ <ReviewBar
+ anyExpanded={review.anyExpanded()}
+ onToggleCollapsed={review.toggleAllCollapsed}
+ />
+ <Show when={changeset()?.truncated}>
+ <CaptureBanner
+ tone="failure"
+ text="Some diffs were left out to fit the size budget; the file list is complete."
+ />
+ </Show>
+ <div class="flex min-h-0 flex-1">
+ <FileTree
+ nodes={model.tree()}
+ fileCount={model.files().length}
+ active={review.active()}
+ onSelect={review.activate}
+ />
+ <Switch>
+ <Match when={model.patchStatus() === 'error'}>
+ <div class="flex flex-1 flex-col items-center justify-center gap-2 text-center">
+ <WarningCircleIcon class="size-6 text-ink-placeholder" />
+ <p class="text-sm font-medium text-ink">
+ The diff could not be loaded
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={model.retryPatch}
+ >
+ Try again
+ </Button>
+ </div>
+ </Match>
+ <Match when={model.entries()}>
+ {(entries) => <DiffStack entries={entries()} />}
+ </Match>
+ <Match when={true}>
+ <div class="flex flex-1 items-center justify-center gap-2 text-xs text-ink-placeholder">
+ <CircleNotchIcon class="size-4 animate-spin" />
+ Loading the diff…
+ </div>
+ </Match>
+ </Switch>
+ </div>
+ </Show>
+ </Match>
+ </Switch>
+ </section>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx b/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx
new file mode 100644
index 0000000000..d98ef4ec83
--- /dev/null
+++ b/apps/web/src/features/agent-changes/views/SessionChangesControls.tsx
@@ -0,0 +1,72 @@
+/**
+ * The pieces the session pane itself shows: the header toggle, the
+ * "changes ready" hand-off card, and the queued-notes chip by the composer.
+ * Each renders nothing until a host has mounted the controller.
+ */
+
+import { Show } from 'solid-js';
+import { ChangesReadyCard } from '../components/ChangesReadyCard';
+import { ChangesToggleButton } from '../components/ChangesToggleButton';
+import { ReviewNotesChip } from '../components/ReviewNotesChip';
+import { useOptionalAgentChanges } from '../context/agent-changes-controller';
+
+export function ChangesToggle() {
+ const controller = useOptionalAgentChanges();
+ if (!controller) return null;
+ const { layout, model } = controller;
+ return (
+ <ChangesToggleButton
+ open={layout.changesVisible()}
+ additions={model.changeset()?.additions ?? 0}
+ deletions={model.changeset()?.deletions ?? 0}
+ capturing={model.state().kind === 'capturing'}
+ onToggle={layout.toggle}
+ />
+ );
+}
+
+/** Shown while the pane is closed and a changeset with files is waiting. */
+export function ChangesHandoff() {
+ const controller = useOptionalAgentChanges();
+ if (!controller) return null;
+ const { layout, model, review, context } = controller;
+ const visible = () =>
+ !layout.changesVisible() &&
+ model.files().length > 0 &&
+ !controller.handoffDismissed();
+ return (
+ <Show when={visible()}>
+ <ChangesReadyCard
+ fileCount={model.files().length}
+ additions={model.changeset()?.additions ?? 0}
+ deletions={model.changeset()?.deletions ?? 0}
+ linkedUrl={context.host.pullRequestUrl()}
+ onReview={() => {
+ const first = model.files()[0];
+ layout.open();
+ if (first) review.activate(first.path);
+ }}
+ onViewPullRequest={() => {
+ const url = context.host.pullRequestUrl();
+ if (url) context.host.openExternal(url);
+ }}
+ onDismiss={controller.dismissHandoff}
+ />
+ </Show>
+ );
+}
+
+export function ReviewNotesDock() {
+ const controller = useOptionalAgentChanges();
+ if (!controller) return null;
+ const { review, context } = controller;
+ return (
+ <Show when={context.host.agent && review.queued().length > 0}>
+ <ReviewNotesChip
+ count={review.queued().length}
+ disabled={!context.host.agent?.canSend()}
+ onSend={controller.sendQueuedNotes}
+ />
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/agent-changes/views/changes-pane.test.tsx b/apps/web/src/features/agent-changes/views/changes-pane.test.tsx
new file mode 100644
index 0000000000..d845bda43d
--- /dev/null
+++ b/apps/web/src/features/agent-changes/views/changes-pane.test.tsx
@@ -0,0 +1,271 @@
+import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import type { AgentChangesContext } from '../context/agent-changes-context';
+import { AgentChangesControllerProvider } from '../context/agent-changes-controller';
+import {
+ type AgentChangesController,
+ createAgentChanges,
+ type DiffStyle,
+} from '../primitives/create-agent-changes';
+import { createMemoryStorage } from '../tests/memory-storage';
+import {
+ createMockAgentChangesContext,
+ MOCK_PATCH,
+ mockChangeset,
+} from '../tests/mock-context';
+import { ChangesPane } from './ChangesPane';
+import {
+ ChangesHandoff,
+ ChangesToggle,
+ ReviewNotesDock,
+} from './SessionChangesControls';
+
+// Pierre mounts a custom element and highlights with shiki; the pane test
+// covers everything around it and leaves the diff body to the browser.
+vi.mock('../components/PierreFileDiff', () => ({
+ PierreFileDiff: (props: { path: string }) => (
+ <div data-testid="diff" data-path={props.path} />
+ ),
+}));
+
+// Module-load quarantine, not a dependency substitute: the connection-gateway
+// websocket connects when imported, which jsdom cannot do.
+vi.mock('@service-connection/websocket', () => ({
+ ws: { send() {}, addEventListener() {}, removeEventListener() {} },
+ state: () => 'closed',
+ createConnectionBlockWebsocketEffect() {},
+ createConnectionWebsocketEffect() {},
+ parseWebsocketPayload: () => undefined,
+}));
+
+// The block registry globs every block definition (and their heavy
+// dependencies) at import time; the pane never reads it.
+vi.mock('@core/constant/allBlocks', () => ({
+ blocks: {},
+ blockAcceptedMimetypeToFileExtension: {},
+ blockAcceptedFileExtensionToMimeType: {},
+}));
+
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { send() {}, addEventListener() {}, removeEventListener() {} },
+ createWebSocketJob: () => Promise.reject(new Error('no websocket in tests')),
+}));
+
+function mount(
+ context: AgentChangesContext,
+ ui: () => ReturnType<typeof ChangesPane>
+) {
+ const [diffStyle, setDiffStyle] = createSignal<DiffStyle>('unified');
+ const [dismissed, setDismissed] = createSignal<string>();
+ let controller!: AgentChangesController;
+ const result = render(() => {
+ controller = createAgentChanges({
+ context,
+ storage: createMemoryStorage(),
+ diffStyle: [diffStyle, setDiffStyle],
+ dismissed: [dismissed, setDismissed],
+ });
+ return (
+ <AgentChangesControllerProvider value={controller}>
+ {ui()}
+ </AgentChangesControllerProvider>
+ );
+ });
+ return { ...result, controller: () => controller };
+}
+
+function readyContext() {
+ return createMockAgentChangesContext({
+ summary: { capturing: false, changeset: mockChangeset() },
+ patch: MOCK_PATCH,
+ });
+}
+
+describe('ChangesPane', () => {
+ it('lists files and collapses individual or all diffs without viewed controls', async () => {
+ const context = readyContext();
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+
+ expect(
+ screen.getByText('agent/unread-archived-sessions → main')
+ ).toBeTruthy();
+ await waitFor(() => expect(screen.getAllByTestId('diff')).toHaveLength(2));
+ expect(screen.queryByRole('button', { name: /^Viewed$/ })).toBeNull();
+ expect(screen.queryByRole('progressbar')).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'Mark all viewed' })
+ ).toBeNull();
+
+ fireEvent.click(screen.getAllByRole('button', { name: /^Hide / })[0]!);
+ expect(screen.getAllByTestId('diff')).toHaveLength(1);
+ expect(screen.getByText('Show diff')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Collapse all' }));
+ expect(screen.queryAllByTestId('diff')).toHaveLength(0);
+ fireEvent.click(screen.getByRole('button', { name: 'Expand all' }));
+ expect(screen.getAllByTestId('diff')).toHaveLength(2);
+ });
+
+ it('supports a PR host with no agent capabilities', async () => {
+ const context = readyContext();
+ const { controller } = mount(
+ {
+ ...context,
+ host: {
+ ...context.host,
+ scopeKey: () => 'pr:macro-inc/macro/1482',
+ agent: undefined,
+ },
+ },
+ () => (
+ <>
+ <ChangesPane />
+ <ReviewNotesDock />
+ </>
+ )
+ );
+ controller().layout.open();
+ await waitFor(() => expect(screen.getAllByTestId('diff')).toHaveLength(2));
+ controller().sendQueuedNotes();
+ expect(context.sent).toEqual([]);
+ expect(screen.queryByRole('button', { name: 'Send to agent' })).toBeNull();
+ });
+
+ it('shows refresh failures without discarding the current diff and allows retry', async () => {
+ const context = readyContext();
+ const refresh = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('unavailable'))
+ .mockResolvedValueOnce(undefined);
+ context.source.refresh = refresh;
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+ fireEvent.click(
+ screen.getByRole('button', { name: /Refresh pull request changes/ })
+ );
+ await waitFor(() =>
+ expect(screen.getByRole('status').textContent).toContain(
+ 'could not be refreshed'
+ )
+ );
+ expect(screen.getAllByTestId('diff')).toHaveLength(2);
+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull());
+ expect(refresh).toHaveBeenCalledTimes(2);
+ });
+
+ it('explains that a linked GitHub PR is required', () => {
+ const context = createMockAgentChangesContext({
+ summary: {
+ capturing: false,
+ attempt: {
+ startedAt: 't',
+ finishedAt: 't',
+ outcome: 'not_ready',
+ error:
+ 'Link a GitHub pull request to this session to review its changes.',
+ },
+ },
+ });
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+ expect(screen.getByText('Pull request changes unavailable')).toBeTruthy();
+ expect(
+ screen.getByText(
+ 'Link a GitHub pull request to this session to review its changes.'
+ )
+ ).toBeTruthy();
+ });
+
+ it('offers to capture when nothing has been captured, and refreshes', async () => {
+ const context = createMockAgentChangesContext({
+ summary: { capturing: false },
+ });
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+ fireEvent.click(screen.getByRole('button', { name: /Refresh changes/ }));
+ await waitFor(() => expect(context.refreshes()).toBe(1));
+ });
+
+ it('opens the linked GitHub PR without creating another one', () => {
+ const context = readyContext();
+ const url = 'https://github.com/macro-inc/macro/pull/1482';
+ context.setPullRequestUrl(url);
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+ expect(
+ screen.queryByRole('button', { name: 'Create pull request' })
+ ).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'View pull request' }));
+ expect(context.opened).toEqual([url]);
+ expect(context.sent).toEqual([]);
+ });
+
+ it('closes and spotlights from its header', () => {
+ const context = readyContext();
+ const { controller } = mount(context, () => <ChangesPane />);
+ controller().layout.open();
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Expand changes to the full width' })
+ );
+ expect(controller().layout.layout()).toBe('changes-only');
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Bring the session back' })
+ );
+ expect(controller().layout.layout()).toBe('split');
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Close the changes pane' })
+ );
+ expect(controller().layout.layout()).toBe('agent-only');
+ });
+});
+
+describe('session controls', () => {
+ it('toggles the pane and shows addition/deletion totals', () => {
+ const context = readyContext();
+ const { controller } = mount(context, () => <ChangesToggle />);
+ const toggle = screen.getByRole('button', { name: /Changes/ });
+ expect(toggle.textContent).toContain('Changes+3−1');
+ expect(toggle.getAttribute('aria-pressed')).toBe('false');
+ fireEvent.click(toggle);
+ expect(controller().layout.layout()).toBe('split');
+ expect(toggle.getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('hands off to the pane while it is closed, and can be dismissed', () => {
+ const context = readyContext();
+ const { controller } = mount(context, () => <ChangesHandoff />);
+ expect(screen.getByText('Changes ready to review')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Review changes' }));
+ expect(controller().layout.layout()).toBe('split');
+ expect(controller().review.active()).toBe('apps/web/src/a.ts');
+ expect(screen.queryByText('Changes ready to review')).toBeNull();
+
+ controller().layout.close();
+ expect(screen.getByText('Changes ready to review')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
+ expect(screen.queryByText('Changes ready to review')).toBeNull();
+ });
+
+ it('sends queued notes to the agent from the dock', () => {
+ const context = readyContext();
+ const { controller } = mount(context, () => <ReviewNotesDock />);
+ expect(screen.queryByText(/review note/)).toBeNull();
+ controller().review.addNote(
+ {
+ path: 'apps/web/src/a.ts',
+ side: 'additions',
+ lineNumber: 2,
+ endLineNumber: 2,
+ },
+ 'Use a constant'
+ );
+ expect(screen.getByText(/review note/).textContent).toContain('1');
+ fireEvent.click(screen.getByRole('button', { name: 'Send to agent' }));
+ expect(context.sent[0]).toContain('`apps/web/src/a.ts`, line 2 (new)');
+ expect(context.sent[0]).toContain('Use a constant');
+ expect(screen.queryByText(/review note/)).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
index 061bcc8d58..390c56fc15 100644
--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx
@@ -1,3 +1,10 @@
+import {
+ AgentChangesProvider,
+ AgentChangesSplit,
+ ChangesHandoff,
+ ChangesToggle,
+ ReviewNotesDock,
+} from '@app/features/agent-changes/agent-changes';
import { AgentComposer } from '@app/features/block-agent/component/AgentComposer';
import { AgentPullRequestChip } from '@app/features/block-agent/component/AgentPullRequestChip';
import { agentSessionTitle } from '@app/features/block-agent/component/AgentSplitHeader';
@@ -190,6 +197,7 @@ function SessionContent(props: { onDeleted: () => void }) {
/>
)}
</Show>
+ <ChangesToggle />
<SidePanel.Toggle />
</Topbar>
<div class="relative min-h-0 min-w-0 flex-1">
@@ -213,7 +221,9 @@ function SessionContent(props: { onDeleted: () => void }) {
<Transcript />
</div>
<div class="dock">
- <div class="composer-anchor">
+ <div class="composer-anchor flex flex-col gap-2">
+ <ChangesHandoff />
+ <ReviewNotesDock />
<AgentComposer
autofocus
input={ChatSessionInput}
@@ -262,7 +272,11 @@ export function AgentSessionPane(props: {
return (
<AgentSessionProvider blockId={props.id} onSessionId={props.onSessionId}>
- <SessionContent onDeleted={props.onDeleted} />
+ <AgentChangesProvider>
+ <AgentChangesSplit>
+ <SessionContent onDeleted={props.onDeleted} />
+ </AgentChangesSplit>
+ </AgentChangesProvider>
</AgentSessionProvider>
);
}
diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx
index fd7649bb59..06d0cf1f07 100644
--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx
+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx
@@ -1,3 +1,4 @@
+import { ChangesToggle } from '@app/features/agent-changes/agent-changes';
import { useBlockEntityCommands } from '@app/features/next-soup/actions/use-block-entity-commands';
import {
type BlockTool,
@@ -162,6 +163,7 @@ export function AgentSplitHeader(props: {
{(url) => <AgentPullRequestChip url={url()} />}
</Show>
<Show when={!isMobile()}>
+ <ChangesToggle />
<For each={tools}>
{(tool) => (
<Show when={!tool.condition || tool.condition()}>
diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsx
index c9683ae25b..6a2afb4755 100644
--- a/apps/web/src/features/block-agent/component/Block.tsx
+++ b/apps/web/src/features/block-agent/component/Block.tsx
@@ -1,3 +1,9 @@
+import {
+ AgentChangesProvider,
+ AgentChangesSplit,
+ ChangesHandoff,
+ ReviewNotesDock,
+} from '@app/features/agent-changes/agent-changes';
import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';
import { SidePanel } from '@components/app/side-panel';
import { SplitPanelContext } from '@components/app/split-layout/context';
@@ -96,7 +102,9 @@ function AgentBlockContent() {
session={session()}
title={metadata()?.title ?? undefined}
/>
- <div class="size-full min-w-0 flex flex-col">
+ {/* The Changes pane opens beside the transcript; closed, the
+ transcript keeps the whole width. */}
+ <AgentChangesSplit>
<Transcript searchTarget={searchTarget()} />
{/* Full-frame mobile: composer + queue float in the bottom
accessory region above the dock; desktop stays inline. */}
@@ -104,7 +112,9 @@ function AgentBlockContent() {
{/* Home/chat: re-enable pointer events on the accessory
contribution — the float host is pointer-transparent. */}
<div class="flex w-full justify-center shrink-0 px-4 pb-4.5 pointer-events-auto touch:px-(--mobile-chrome-gutter) touch:pb-0">
- <div class="macro-message-width mx-auto">
+ <div class="macro-message-width mx-auto flex flex-col gap-2">
+ <ChangesHandoff />
+ <ReviewNotesDock />
<AgentComposer
autofocus={
canAutofocusSplitContent &&
@@ -115,7 +125,7 @@ function AgentBlockContent() {
</div>
</div>
</FloatRegionOrInline>
- </div>
+ </AgentChangesSplit>
<Show when={sessionOriginThread(session())}>
{(origin) => (
<LinkedConversationDrawer
@@ -151,7 +161,9 @@ export default function BlockAgent() {
<Show when={blockId}>
{(id) => (
<AgentSessionProvider blockId={id()} onSessionId={adoptSessionId}>
- <AgentBlockContent />
+ <AgentChangesProvider>
+ <AgentBlockContent />
+ </AgentChangesProvider>
</AgentSessionProvider>
)}
</Show>
diff --git a/apps/web/src/lib/queries/agent-session/changes-sync.ts b/apps/web/src/lib/queries/agent-session/changes-sync.ts
new file mode 100644
index 0000000000..c4cb8712c8
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/changes-sync.ts
@@ -0,0 +1,26 @@
+import { queryClient } from '@queries/client';
+import { agentSessionChangesKeys } from './keys';
+import type { AgentSessionChangesEvent } from './realtime-protocol';
+
+/**
+ * A session's changes moved on the server. The event carries no body, so
+ * the summary refetches; the patch query is keyed by changeset id and a new
+ * capture simply reads a new key.
+ */
+export async function handleAgentSessionChanges(
+ event: AgentSessionChangesEvent
+): Promise<void> {
+ await invalidateAgentSessionChanges(event.agentSessionId);
+}
+
+/** Drop and refetch one session's changes summary. */
+export async function invalidateAgentSessionChanges(
+ sessionId: string
+): Promise<void> {
+ const filters = {
+ queryKey: agentSessionChangesKeys.summary(sessionId).queryKey,
+ exact: true,
+ };
+ await queryClient.cancelQueries(filters);
+ await queryClient.invalidateQueries(filters);
+}
diff --git a/apps/web/src/lib/queries/agent-session/changes.ts b/apps/web/src/lib/queries/agent-session/changes.ts
new file mode 100644
index 0000000000..44b6630501
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/changes.ts
@@ -0,0 +1,83 @@
+/**
+ * Queries and mutations for an agent session's captured changes.
+ *
+ * The summary (changed files, counts, latest capture attempt) is small and
+ * refetched whenever the `agent_session_changes` realtime event names the
+ * session. The patch is fetched once per changeset id and cached for the
+ * life of the page: a newer capture has a new id, so an old body is never
+ * shown for a new summary.
+ */
+
+import { throwOnErr } from '@core/util/result';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { useMutation, useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { invalidateAgentSessionChanges } from './changes-sync';
+import { agentSessionChangesKeys } from './keys';
+
+/**
+ * While a capture is in flight the realtime event may race the HTTP answer
+ * or be missed on a flaky socket, so the summary re-reads on a short
+ * interval until the attempt settles.
+ */
+export const CAPTURE_POLL_INTERVAL_MS = 3_000;
+
+/** The session's latest changes summary. Disabled while `sessionId` is unset. */
+export function useAgentSessionChangesQuery(
+ sessionId: Accessor<string | undefined>
+) {
+ return useQuery(() => {
+ const id = sessionId();
+ return {
+ queryKey: agentSessionChangesKeys.summary(id ?? '').queryKey,
+ queryFn: () =>
+ throwOnErr(() => agentHarnessServiceClient.getChanges(id!)),
+ enabled: Boolean(id),
+ retry: false,
+ staleTime: 30_000,
+ refetchInterval: (query) =>
+ query.state.data?.capturing ? CAPTURE_POLL_INTERVAL_MS : false,
+ };
+ });
+}
+
+/**
+ * The unified diff behind one changeset. Callers pass the changeset id from
+ * the summary; `undefined` disables the query rather than fetching a body
+ * that has not been captured yet.
+ */
+export function useAgentSessionChangesPatchQuery(
+ sessionId: Accessor<string | undefined>,
+ changesetId: Accessor<string | undefined>
+) {
+ return useQuery(() => {
+ const id = sessionId();
+ const changeset = changesetId();
+ return {
+ queryKey: agentSessionChangesKeys.patch(id ?? '', changeset ?? '')
+ .queryKey,
+ queryFn: () =>
+ throwOnErr(() => agentHarnessServiceClient.getChangesPatch(id!)),
+ enabled: Boolean(id) && Boolean(changeset),
+ retry: 1,
+ // A changeset's body never changes once captured.
+ staleTime: Number.POSITIVE_INFINITY,
+ };
+ });
+}
+
+/**
+ * Ask the server to capture the session's changes again. The answer is the
+ * state as it stood when the capture started; the summary is invalidated so
+ * the pane shows "capturing" at once, and the realtime event lands the
+ * result.
+ */
+export function useRefreshAgentSessionChangesMutation() {
+ return useMutation(() => ({
+ retry: false,
+ mutationFn: (sessionId: string) =>
+ throwOnErr(() => agentHarnessServiceClient.refreshChanges(sessionId)),
+ onSettled: (_data, _error, sessionId) =>
+ invalidateAgentSessionChanges(sessionId),
+ }));
+}
diff --git a/apps/web/src/lib/queries/agent-session/keys.ts b/apps/web/src/lib/queries/agent-session/keys.ts
index afdce95d8c..f5cd0ad902 100644
--- a/apps/web/src/lib/queries/agent-session/keys.ts
+++ b/apps/web/src/lib/queries/agent-session/keys.ts
@@ -4,3 +4,15 @@ export const agentSessionKeys = createQueryKeys('agentSessionMentions', {
detail: (id: string) => ({ queryKey: [id] }),
preview: (id: string, graphql: boolean) => ({ queryKey: [id, graphql] }),
});
+
+/**
+ * A session's captured changes: the summary (invalidated by the
+ * `agent_session_changes` realtime event) and the patch behind one capture,
+ * keyed by changeset id so a newer capture never reads an older body.
+ */
+export const agentSessionChangesKeys = createQueryKeys('agentSessionChanges', {
+ summary: (sessionId: string) => ({ queryKey: [sessionId] }),
+ patch: (sessionId: string, changesetId: string) => ({
+ queryKey: [sessionId, changesetId],
+ }),
+});
diff --git a/apps/web/src/lib/queries/agent-session/realtime-protocol.ts b/apps/web/src/lib/queries/agent-session/realtime-protocol.ts
index 384b14999d..bd0bc98d7f 100644
--- a/apps/web/src/lib/queries/agent-session/realtime-protocol.ts
+++ b/apps/web/src/lib/queries/agent-session/realtime-protocol.ts
@@ -54,3 +54,12 @@ export function entryOf(event: AgentSessionLogEvent): AgentSessionLogEntryDto {
/** A persisted session changed; consumers reload its current metadata. */
export const AGENT_SESSION_UPDATED_EVENT = 'agent_session_updated';
export type AgentSessionUpdatedEvent = { agentSessionId: string };
+
+/**
+ * A session's captured changes moved: a capture started, landed, or failed.
+ * Carries only the session id; consumers refetch the changes summary.
+ * Mirrors `AGENT_SESSION_CHANGES` in
+ * `crates/agent_session/src/outbound/connection_gateway_realtime.rs`.
+ */
+export const AGENT_SESSION_CHANGES_EVENT = 'agent_session_changes';
+export type AgentSessionChangesEvent = { agentSessionId: string };
diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsx
index 8610f7a905..f4285f9bd2 100644
--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx
+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx
@@ -4,12 +4,15 @@ import {
isFeatureEnabled,
} from '@core/constant/featureFlags';
import { WebsocketEvent } from '@macro-inc/collaboration/websocket';
+import { handleAgentSessionChanges } from '@queries/agent-session/changes-sync';
import { handleAgentSessionQueue } from '@queries/agent-session/queue-sync';
import {
+ AGENT_SESSION_CHANGES_EVENT,
AGENT_SESSION_LOG_EVENT,
AGENT_SESSION_QUEUE_EVENT,
AGENT_SESSION_RENAMED_EVENT,
AGENT_SESSION_UPDATED_EVENT,
+ type AgentSessionChangesEvent,
type AgentSessionLogEvent,
type AgentSessionQueueEvent,
type AgentSessionRenamedEvent,
@@ -130,6 +133,17 @@ export function QuerySyncProvider(props: SyncProviderProps) {
handleAgentSessionRenamed
);
})
+ // A session's captured changes moved (capture started, landed, or
+ // failed). The event carries no body; the changes summary refetches.
+ .with({ type: AGENT_SESSION_CHANGES_EVENT }, () => {
+ withParsedWebsocketPayload<AgentSessionChangesEvent>(
+ data.type,
+ data.data,
+ (event) => {
+ void handleAgentSessionChanges(event);
+ }
+ );
+ })
// A session's whole action queue after a change. Full snapshot every
// time: once one has arrived on this socket, the socket is the queue's
// only writer and the last event wins unconditionally.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index e2bd75329e..8e8fe4bd31 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -3,6 +3,8 @@ import { fetchWithToken } from '@core/util/fetchWithToken';
import type { ErrorResponseHandler } from '@core/util/safeFetch';
import type {
AgentRepositoriesResponse,
+ AgentSessionChangesPatchResponse,
+ AgentSessionChangesResponse,
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
@@ -187,6 +189,37 @@ export const agentHarnessServiceClient = {
);
},
+ /**
+ * The session's latest captured changes: changed files with statuses and
+ * line counts, plus how the latest capture attempt went.
+ */
+ getChanges(sessionId: string) {
+ return fetchWithToken<AgentSessionChangesResponse>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/changes`,
+ { method: 'GET' }
+ );
+ },
+
+ /** The unified diff behind the session's latest changeset. 404 until one exists. */
+ getChangesPatch(sessionId: string) {
+ return fetchWithToken<AgentSessionChangesPatchResponse>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/changes/patch`,
+ { method: 'GET' }
+ );
+ },
+
+ /**
+ * Capture the session's changes again now. Answers at once with the state
+ * as it stands; the capture lands through the `agent_session_changes`
+ * realtime event.
+ */
+ refreshChanges(sessionId: string) {
+ return fetchWithToken<AgentSessionChangesResponse>(
+ `${agentHarnessHost}/agent-sessions/${sessionId}/changes/refresh`,
+ { method: 'POST' }
+ );
+ },
+
setSessionSandboxSize(sessionId: string, size: SandboxSize) {
return fetchWithToken<SandboxSizeBody>(
`${agentHarnessHost}/agent-sessions/${sessionId}/sandbox-size`,
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 81f4d98e96..20a8d7e7c6 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
@@ -6,6 +6,8 @@
*/
import type {
AgentRepositoriesResponse,
+ AgentSessionChangesPatchResponse,
+ AgentSessionChangesResponse,
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
@@ -558,6 +560,206 @@ export const deleteAgentSession = async (
} as deleteAgentSessionResponse;
};
+/**
+ * @summary The latest captured changes of an agent session: the changed files with
+statuses and line counts, and how the latest capture attempt went.
+ */
+export type getAgentSessionChangesResponse200 = {
+ data: AgentSessionChangesResponse;
+ status: 200;
+};
+
+export type getAgentSessionChangesResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getAgentSessionChangesResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type getAgentSessionChangesResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type getAgentSessionChangesResponseSuccess =
+ getAgentSessionChangesResponse200 & {
+ headers: Headers;
+ };
+export type getAgentSessionChangesResponseError = (
+ | getAgentSessionChangesResponse401
+ | getAgentSessionChangesResponse403
+ | getAgentSessionChangesResponse500
+) & {
+ headers: Headers;
+};
+
+export type getAgentSessionChangesResponse =
+ | getAgentSessionChangesResponseSuccess
+ | getAgentSessionChangesResponseError;
+
+export const getGetAgentSessionChangesUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/changes`;
+};
+
+export const getAgentSessionChanges = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<getAgentSessionChangesResponse> => {
+ const res = await fetch(getGetAgentSessionChangesUrl(sessionId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAgentSessionChangesResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAgentSessionChangesResponse;
+};
+
+/**
+ * @summary The unified diff behind the session's latest changeset.
+ */
+export type getAgentSessionChangesPatchResponse200 = {
+ data: AgentSessionChangesPatchResponse;
+ status: 200;
+};
+
+export type getAgentSessionChangesPatchResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getAgentSessionChangesPatchResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type getAgentSessionChangesPatchResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type getAgentSessionChangesPatchResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type getAgentSessionChangesPatchResponseSuccess =
+ getAgentSessionChangesPatchResponse200 & {
+ headers: Headers;
+ };
+export type getAgentSessionChangesPatchResponseError = (
+ | getAgentSessionChangesPatchResponse401
+ | getAgentSessionChangesPatchResponse403
+ | getAgentSessionChangesPatchResponse404
+ | getAgentSessionChangesPatchResponse500
+) & {
+ headers: Headers;
+};
+
+export type getAgentSessionChangesPatchResponse =
+ | getAgentSessionChangesPatchResponseSuccess
+ | getAgentSessionChangesPatchResponseError;
+
+export const getGetAgentSessionChangesPatchUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/changes/patch`;
+};
+
+export const getAgentSessionChangesPatch = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<getAgentSessionChangesPatchResponse> => {
+ const res = await fetch(getGetAgentSessionChangesPatchUrl(sessionId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAgentSessionChangesPatchResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAgentSessionChangesPatchResponse;
+};
+
+/**
+ * @summary Capture the session's changes again now. Answers at once with the state
+as it stands; the capture runs on and viewers are told when it lands.
+ */
+export type refreshAgentSessionChangesResponse202 = {
+ data: AgentSessionChangesResponse;
+ status: 202;
+};
+
+export type refreshAgentSessionChangesResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type refreshAgentSessionChangesResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type refreshAgentSessionChangesResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type refreshAgentSessionChangesResponseSuccess =
+ refreshAgentSessionChangesResponse202 & {
+ headers: Headers;
+ };
+export type refreshAgentSessionChangesResponseError = (
+ | refreshAgentSessionChangesResponse401
+ | refreshAgentSessionChangesResponse403
+ | refreshAgentSessionChangesResponse500
+) & {
+ headers: Headers;
+};
+
+export type refreshAgentSessionChangesResponse =
+ | refreshAgentSessionChangesResponseSuccess
+ | refreshAgentSessionChangesResponseError;
+
+export const getRefreshAgentSessionChangesUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/changes/refresh`;
+};
+
+export const refreshAgentSessionChanges = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<refreshAgentSessionChangesResponse> => {
+ const res = await fetch(getRefreshAgentSessionChangesUrl(sessionId), {
+ ...options,
+ method: 'POST',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: refreshAgentSessionChangesResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as refreshAgentSessionChangesResponse;
+};
+
/**
* Edit access suffices: whoever can prompt the bot through its thread can
prompt it here.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesPatchResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesPatchResponse.ts
new file mode 100644
index 0000000000..d4f0cb0be6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesPatchResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response body for `GET /agent-sessions/{session_id}/changes/patch`.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface AgentSessionChangesPatchResponse {
+ /** The git-style unified diff of the current changeset. */
+ patch: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponse.ts
new file mode 100644
index 0000000000..fcf1dadbf8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponse.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionChangesResponseAttempt } from './agentSessionChangesResponseAttempt';
+import type { AgentSessionChangesResponseChangeset } from './agentSessionChangesResponseChangeset';
+
+/**
+ * Response body for `GET /agent-sessions/{session_id}/changes`.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface AgentSessionChangesResponse {
+ attempt?: AgentSessionChangesResponseAttempt;
+ /** A capture is running right now. */
+ capturing: boolean;
+ changeset?: AgentSessionChangesResponseChangeset;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponseAttempt.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponseAttempt.ts
new file mode 100644
index 0000000000..d8e8333ca9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponseAttempt.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CaptureAttemptDto } from './captureAttemptDto';
+
+export type AgentSessionChangesResponseAttempt = null | CaptureAttemptDto;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponseChangeset.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponseChangeset.ts
new file mode 100644
index 0000000000..2bd385cf5c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionChangesResponseChangeset.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChangesetDto } from './changesetDto';
+
+export type AgentSessionChangesResponseChangeset = null | ChangesetDto;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDto.ts
new file mode 100644
index 0000000000..30f9004f5c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDto.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CaptureAttemptDtoError } from './captureAttemptDtoError';
+import type { CaptureAttemptDtoFinishedAt } from './captureAttemptDtoFinishedAt';
+import type { CaptureAttemptDtoOutcome } from './captureAttemptDtoOutcome';
+
+/**
+ * The latest capture attempt.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface CaptureAttemptDto {
+ /** Why it did not capture, in a sentence the user can read. */
+ error?: CaptureAttemptDtoError;
+ /** When it ended; absent while it runs. */
+ finishedAt?: CaptureAttemptDtoFinishedAt;
+ outcome?: CaptureAttemptDtoOutcome;
+ /** When it started. */
+ startedAt: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoError.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoError.ts
new file mode 100644
index 0000000000..b0caef7bed
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoError.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Why it did not capture, in a sentence the user can read.
+ */
+export type CaptureAttemptDtoError = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoFinishedAt.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoFinishedAt.ts
new file mode 100644
index 0000000000..07f81583e5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoFinishedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When it ended; absent while it runs.
+ */
+export type CaptureAttemptDtoFinishedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoOutcome.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoOutcome.ts
new file mode 100644
index 0000000000..f0f352ff17
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureAttemptDtoOutcome.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CaptureOutcomeDto } from './captureOutcomeDto';
+
+export type CaptureAttemptDtoOutcome = null | CaptureOutcomeDto;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureOutcomeDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureOutcomeDto.ts
new file mode 100644
index 0000000000..54cf111eff
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/captureOutcomeDto.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * How the latest capture attempt ended, on the wire.
+ */
+export type CaptureOutcomeDto =
+ (typeof CaptureOutcomeDto)[keyof typeof CaptureOutcomeDto];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const CaptureOutcomeDto = {
+ captured: 'captured',
+ not_ready: 'not_ready',
+ failed: 'failed',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changedFileDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changedFileDto.ts
new file mode 100644
index 0000000000..10dbdabf64
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changedFileDto.ts
@@ -0,0 +1,37 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { ChangedFileDtoPreviousPath } from './changedFileDtoPreviousPath';
+import type { FileChangeKindDto } from './fileChangeKindDto';
+
+/**
+ * One changed file.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface ChangedFileDto {
+ /**
+ * Lines added.
+ * @minimum 0
+ */
+ additions: number;
+ /** The diff carries no text for this file. */
+ binary: boolean;
+ /**
+ * Lines removed.
+ * @minimum 0
+ */
+ deletions: number;
+ /** What happened to the file. */
+ kind: FileChangeKindDto;
+ /** The file's hunks were left out of the patch to fit the size budget. */
+ patchOmitted: boolean;
+ /** The file's path after the change, or before it for a deletion. */
+ path: string;
+ /** Where a renamed file came from. */
+ previousPath?: ChangedFileDtoPreviousPath;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changedFileDtoPreviousPath.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changedFileDtoPreviousPath.ts
new file mode 100644
index 0000000000..75d843eddc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changedFileDtoPreviousPath.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Where a renamed file came from.
+ */
+export type ChangedFileDtoPreviousPath = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetDto.ts
new file mode 100644
index 0000000000..f3584b6fd0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetDto.ts
@@ -0,0 +1,51 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { ChangedFileDto } from './changedFileDto';
+import type { ChangesetDtoRepository } from './changesetDtoRepository';
+import type { ChangesetSourceDto } from './changesetSourceDto';
+import type { GitRefDto } from './gitRefDto';
+
+/**
+ * One capture of a session's changes.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface ChangesetDto {
+ /**
+ * Lines added across all files.
+ * @minimum 0
+ */
+ additions: number;
+ /** The side the work started from. */
+ base: GitRefDto;
+ /** When the diff was taken. */
+ capturedAt: string;
+ /**
+ * Lines removed across all files.
+ * @minimum 0
+ */
+ deletions: number;
+ /** Every changed file, in patch order. */
+ files: ChangedFileDto[];
+ /** The side carrying the work. */
+ head: GitRefDto;
+ /** The capture's id; changes with every capture. */
+ id: string;
+ /**
+ * Size of the patch `GET .../changes/patch` serves; zero when nothing
+changed.
+ * @minimum 0
+ */
+ patchBytes: number;
+ /** `https://github.com/owner/name`, when known. */
+ repository?: ChangesetDtoRepository;
+ /** Where the diff was read from. */
+ source: ChangesetSourceDto;
+ /** Some files' hunks were left out of the patch. */
+ truncated: boolean;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetDtoRepository.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetDtoRepository.ts
new file mode 100644
index 0000000000..9fbe7a6f5e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetDtoRepository.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * `https://github.com/owner/name`, when known.
+ */
+export type ChangesetDtoRepository = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetSourceDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetSourceDto.ts
new file mode 100644
index 0000000000..ba46ac932d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/changesetSourceDto.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The source of the captured diff, on the wire.
+ */
+export type ChangesetSourceDto =
+ (typeof ChangesetSourceDto)[keyof typeof ChangesetSourceDto];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ChangesetSourceDto = {
+ github_pull_request: 'github_pull_request',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/fileChangeKindDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/fileChangeKindDto.ts
new file mode 100644
index 0000000000..5524dad7e8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/fileChangeKindDto.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * What happened to a file, on the wire.
+ */
+export type FileChangeKindDto =
+ (typeof FileChangeKindDto)[keyof typeof FileChangeKindDto];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const FileChangeKindDto = {
+ added: 'added',
+ modified: 'modified',
+ deleted: 'deleted',
+ renamed: 'renamed',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDto.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDto.ts
new file mode 100644
index 0000000000..7d0b1be329
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDto.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GitRefDtoName } from './gitRefDtoName';
+import type { GitRefDtoSha } from './gitRefDtoSha';
+
+/**
+ * One end of the compared range.
+ */
+export interface GitRefDto {
+ /** The branch name, when known. */
+ name?: GitRefDtoName;
+ /** The commit, when known. */
+ sha?: GitRefDtoSha;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDtoName.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDtoName.ts
new file mode 100644
index 0000000000..2b2ac312f3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDtoName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The branch name, when known.
+ */
+export type GitRefDtoName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDtoSha.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDtoSha.ts
new file mode 100644
index 0000000000..a5974bc569
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/gitRefDtoSha.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The commit, when known.
+ */
+export type GitRefDtoSha = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 3f6f4dcb81..ed99e4909f 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -30,6 +30,10 @@ export * from './agentRepositoryDto';
export * from './agentRepositoryDtoDefaultBranch';
export * from './agentRespondElicitationAction';
export * from './agentRespondElicitationActionAllOf';
+export * from './agentSessionChangesPatchResponse';
+export * from './agentSessionChangesResponse';
+export * from './agentSessionChangesResponseAttempt';
+export * from './agentSessionChangesResponseChangeset';
export * from './agentSessionLogEntryDto';
export * from './agentSessionLogEntryDtoAllOf';
export * from './agentSessionLogEntryDtoAllOfUserId';
@@ -59,6 +63,16 @@ export * from './agentSessionResponseThreadId';
export * from './agentSessionResponseThreadParent';
export * from './agentSetModelAction';
export * from './botId';
+export * from './captureAttemptDto';
+export * from './captureAttemptDtoError';
+export * from './captureAttemptDtoFinishedAt';
+export * from './captureAttemptDtoOutcome';
+export * from './captureOutcomeDto';
+export * from './changedFileDto';
+export * from './changedFileDtoPreviousPath';
+export * from './changesetDto';
+export * from './changesetDtoRepository';
+export * from './changesetSourceDto';
export * from './completeRequest';
export * from './controlRequest';
export * from './controlRequestAllOf';
@@ -96,6 +110,10 @@ export * from './emptyRequest';
export * from './externalSessionResponse';
export * from './externalSessionResponseName';
export * from './externalSessionResponseUrl';
+export * from './fileChangeKindDto';
+export * from './gitRefDto';
+export * from './gitRefDtoName';
+export * from './gitRefDtoSha';
export * from './loadAgentModelsRequest';
export * from './loadAgentModelsRequestHarnessId';
export * from './loadAgentModelsResponse';
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 2b5ff0358f..136eda6e54 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
@@ -431,6 +431,199 @@
}
}
},
+ "/agent-sessions/{session_id}/changes": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "The latest captured changes of an agent session: the changed files with\nstatuses and line counts, and how the latest capture attempt went.",
+ "operationId": "get_agent_session_changes",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionChangesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-sessions/{session_id}/changes/patch": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "The unified diff behind the session's latest changeset.",
+ "operationId": "get_agent_session_changes_patch",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionChangesPatchResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-sessions/{session_id}/changes/refresh": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "Capture the session's changes again now. Answers at once with the state\nas it stands; the capture runs on and viewers are told when it lands.",
+ "operationId": "refresh_agent_session_changes",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "202": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionChangesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/control": {
"post": {
"tags": ["agent-sessions"],
@@ -1264,6 +1457,50 @@
],
"description": "Answer an elicitation the agent is waiting on."
},
+ "AgentSessionChangesPatchResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-sessions/{session_id}/changes/patch`.\n\nClients deserialize this, so both derives are used.",
+ "required": ["patch"],
+ "properties": {
+ "patch": {
+ "type": "string",
+ "description": "The git-style unified diff of the current changeset."
+ }
+ }
+ },
+ "AgentSessionChangesResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-sessions/{session_id}/changes`.\n\nClients deserialize this, so both derives are used.",
+ "required": ["capturing"],
+ "properties": {
+ "attempt": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CaptureAttemptDto",
+ "description": "The latest attempt, if any was made."
+ }
+ ]
+ },
+ "capturing": {
+ "type": "boolean",
+ "description": "A capture is running right now."
+ },
+ "changeset": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ChangesetDto",
+ "description": "The latest capture, if any succeeded."
+ }
+ ]
+ }
+ }
+ },
"AgentSessionLogEntryDto": {
"allOf": [
{
@@ -1584,6 +1821,167 @@
"BotId": {
"type": "string"
},
+ "CaptureAttemptDto": {
+ "type": "object",
+ "description": "The latest capture attempt.\n\nClients deserialize this, so both derives are used.",
+ "required": ["startedAt"],
+ "properties": {
+ "error": {
+ "type": ["string", "null"],
+ "description": "Why it did not capture, in a sentence the user can read."
+ },
+ "finishedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When it ended; absent while it runs."
+ },
+ "outcome": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CaptureOutcomeDto",
+ "description": "How it ended; absent while it runs."
+ }
+ ]
+ },
+ "startedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When it started."
+ }
+ }
+ },
+ "CaptureOutcomeDto": {
+ "type": "string",
+ "description": "How the latest capture attempt ended, on the wire.",
+ "enum": ["captured", "not_ready", "failed"]
+ },
+ "ChangedFileDto": {
+ "type": "object",
+ "description": "One changed file.\n\nClients deserialize this, so both derives are used.",
+ "required": [
+ "path",
+ "kind",
+ "additions",
+ "deletions",
+ "binary",
+ "patchOmitted"
+ ],
+ "properties": {
+ "additions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines added.",
+ "minimum": 0
+ },
+ "binary": {
+ "type": "boolean",
+ "description": "The diff carries no text for this file."
+ },
+ "deletions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines removed.",
+ "minimum": 0
+ },
+ "kind": {
+ "$ref": "#/components/schemas/FileChangeKindDto",
+ "description": "What happened to the file."
+ },
+ "patchOmitted": {
+ "type": "boolean",
+ "description": "The file's hunks were left out of the patch to fit the size budget."
+ },
+ "path": {
+ "type": "string",
+ "description": "The file's path after the change, or before it for a deletion."
+ },
+ "previousPath": {
+ "type": ["string", "null"],
+ "description": "Where a renamed file came from."
+ }
+ }
+ },
+ "ChangesetDto": {
+ "type": "object",
+ "description": "One capture of a session's changes.\n\nClients deserialize this, so both derives are used.",
+ "required": [
+ "id",
+ "source",
+ "base",
+ "head",
+ "files",
+ "additions",
+ "deletions",
+ "patchBytes",
+ "truncated",
+ "capturedAt"
+ ],
+ "properties": {
+ "additions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines added across all files.",
+ "minimum": 0
+ },
+ "base": {
+ "$ref": "#/components/schemas/GitRefDto",
+ "description": "The side the work started from."
+ },
+ "capturedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the diff was taken."
+ },
+ "deletions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines removed across all files.",
+ "minimum": 0
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ChangedFileDto"
+ },
+ "description": "Every changed file, in patch order."
+ },
+ "head": {
+ "$ref": "#/components/schemas/GitRefDto",
+ "description": "The side carrying the work."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The capture's id; changes with every capture."
+ },
+ "patchBytes": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Size of the patch `GET .../changes/patch` serves; zero when nothing\nchanged.",
+ "minimum": 0
+ },
+ "repository": {
+ "type": ["string", "null"],
+ "description": "`https://github.com/owner/name`, when known."
+ },
+ "source": {
+ "$ref": "#/components/schemas/ChangesetSourceDto",
+ "description": "Where the diff was read from."
+ },
+ "truncated": {
+ "type": "boolean",
+ "description": "Some files' hunks were left out of the patch."
+ }
+ }
+ },
+ "ChangesetSourceDto": {
+ "type": "string",
+ "description": "The source of the captured diff, on the wire.",
+ "enum": ["github_pull_request"]
+ },
"CompleteRequest": {
"type": "object",
"description": "One-time manual code. Deliberately does not implement Debug.",
@@ -1871,6 +2269,25 @@
}
}
},
+ "FileChangeKindDto": {
+ "type": "string",
+ "description": "What happened to a file, on the wire.",
+ "enum": ["added", "modified", "deleted", "renamed"]
+ },
+ "GitRefDto": {
+ "type": "object",
+ "description": "One end of the compared range.",
+ "properties": {
+ "name": {
+ "type": ["string", "null"],
+ "description": "The branch name, when known."
+ },
+ "sha": {
+ "type": ["string", "null"],
+ "description": "The commit, when known."
+ }
+ }
+ },
"LoadAgentModelsRequest": {
"type": "object",
"description": "HTTP request selecting one provider to probe.",
diff --git a/crates/agent_changes/Cargo.toml b/crates/agent_changes/Cargo.toml
new file mode 100644
index 0000000000..fb2abc7294
--- /dev/null
+++ b/crates/agent_changes/Cargo.toml
@@ -0,0 +1,68 @@
+[package]
+edition = "2024"
+name = "agent_changes"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["inbound", "outbound"]
+# The axum router serving a session's changes over HTTP.
+inbound = [
+ "dep:axum",
+ "dep:macro_authorization",
+ "entity_access/inbound",
+ "macro_authorization/axum",
+ "schema",
+]
+# Postgres, S3, the GitHub pull request client.
+outbound = [
+ "dep:aws-sdk-s3",
+ "dep:github",
+ "dep:reqwest",
+ "dep:sqlx",
+ "macro_user_id/sqlx",
+]
+# OpenAPI schemas for the router's DTOs.
+schema = ["dep:utoipa"]
+# In-memory port implementations, for crates that test against this one.
+test-utils = []
+
+[dependencies]
+agent_fold = { path = "../agent_fold", default-features = false }
+agent_session = { path = "../agent_session", default-features = false }
+anyhow = { workspace = true }
+aws-sdk-s3 = { workspace = true, optional = true }
+axum = { workspace = true, optional = true }
+chrono = { workspace = true }
+dashmap = { workspace = true }
+entity_access = { path = "../entity_access", default-features = false, features = [
+ "ports",
+] }
+# `sync` alone does not compile without `outbound` today; mirror agent_harness.
+github = { path = "../github", default-features = false, features = [
+ "outbound",
+ "ports",
+ "sync",
+], optional = true }
+macro_authorization = { path = "../macro_authorization", default-features = false, optional = true }
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+reqwest = { workspace = true, optional = true }
+rootcause = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true, features = ["json"], optional = true }
+strum = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, features = ["rt", "sync"] }
+tracing = { workspace = true }
+url = { workspace = true }
+utoipa = { workspace = true, optional = true }
+uuid = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+agent_session = { path = "../agent_session", default-features = false, features = ["test-utils"] }
+bot_id = { path = "../bot_id", features = ["test-utils"] }
+macro_db_migrator = { path = "../macro_db_migrator" }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
diff --git a/crates/agent_changes/src/domain/error.rs b/crates/agent_changes/src/domain/error.rs
new file mode 100644
index 0000000000..e29ebfc7c3
--- /dev/null
+++ b/crates/agent_changes/src/domain/error.rs
@@ -0,0 +1,54 @@
+//! Errors of the changes domain.
+
+use agent_session::domain::error::AgentSessionError;
+
+/// The domain's result type.
+pub type Result<T, E = ChangesError> = std::result::Result<T, E>;
+
+/// Why a changes operation could not be served.
+#[derive(Debug, thiserror::Error)]
+pub enum ChangesError {
+ /// The caller holds no grant that covers this operation.
+ #[error("the caller may not act on this session's changes")]
+ Forbidden,
+ /// Nothing has been captured for the session, so there is no patch.
+ #[error("no changes have been captured for this session yet")]
+ NoChangeset,
+ /// The summary row names a patch the blob store no longer has.
+ #[error("the stored patch for this changeset is missing")]
+ PatchMissing,
+ /// The session itself could not be read.
+ #[error(transparent)]
+ Session(#[from] AgentSessionError),
+ /// The summary store or the blob store failed.
+ #[error("changes storage failed: {0}")]
+ Storage(rootcause::Report),
+}
+
+/// Why an extractor could not hand back a changeset.
+#[derive(Debug, thiserror::Error)]
+pub enum ExtractError {
+ /// The linked pull request is missing or unavailable. Shown to the user.
+ #[error("{0}")]
+ NotReady(String),
+ /// The provider or the transport failed.
+ #[error("{0}")]
+ Failed(rootcause::Report),
+}
+
+/// Why a GitHub pull request diff could not be read.
+#[derive(Debug, thiserror::Error)]
+pub enum CompareError {
+ /// GitHub cannot find the linked pull request.
+ #[error("the linked pull request does not exist on GitHub")]
+ NotFound,
+ /// The provider refuses to render a diff this large.
+ #[error("the diff is too large for the repository provider to compare")]
+ TooLarge,
+ /// The caller may not reach the repository through the provider.
+ #[error("the repository is not reachable through the configured GitHub App")]
+ Unavailable,
+ /// Anything else.
+ #[error("{0}")]
+ Other(rootcause::Report),
+}
diff --git a/crates/agent_changes/src/domain/mod.rs b/crates/agent_changes/src/domain/mod.rs
new file mode 100644
index 0000000000..71997fa9e1
--- /dev/null
+++ b/crates/agent_changes/src/domain/mod.rs
@@ -0,0 +1,9 @@
+//! The changes domain: models, patch reading, ports, and the service.
+
+pub mod error;
+pub mod model;
+pub mod patch;
+pub mod ports;
+/// Linked pull request extraction.
+pub mod pull_request;
+pub mod service;
diff --git a/crates/agent_changes/src/domain/model.rs b/crates/agent_changes/src/domain/model.rs
new file mode 100644
index 0000000000..0cd145901d
--- /dev/null
+++ b/crates/agent_changes/src/domain/model.rs
@@ -0,0 +1,334 @@
+//! The vocabulary of a session's changes.
+//!
+//! A [`Changeset`] is one capture of everything a session has changed in its
+//! repository: the per-file facts a review needs at a glance (path, status,
+//! line counts) plus where the patch itself is stored. Only the latest capture
+//! is kept per session - the Changes pane shows the current state of the
+//! linked pull request, not a history of captures.
+
+use chrono::{DateTime, Utc};
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+
+pub use agent_session::domain::model::AgentSessionId;
+
+/// Identity of one capture. Minted per capture (UUIDv7), so the patch blob's
+/// key changes every time and a reader never sees half of a newer capture
+/// under an older summary.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct ChangesetId(Uuid);
+
+impl ChangesetId {
+ /// Mint a fresh id, backed by a UUIDv7.
+ #[expect(clippy::new_without_default, reason = "each call mints a distinct id")]
+ #[must_use]
+ pub fn new() -> Self {
+ Self(macro_uuid::generate_uuid_v7())
+ }
+
+ /// Wrap an existing UUID.
+ #[must_use]
+ pub fn from_uuid(id: Uuid) -> Self {
+ Self(id)
+ }
+
+ /// The underlying UUID.
+ #[must_use]
+ pub fn as_uuid(&self) -> Uuid {
+ self.0
+ }
+}
+
+impl std::fmt::Display for ChangesetId {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ self.0.fmt(formatter)
+ }
+}
+
+/// What happened to one file, as a diff reports it.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum FileChangeKind {
+ /// The file did not exist before.
+ Added,
+ /// The file exists on both sides with different contents.
+ Modified,
+ /// The file no longer exists.
+ Deleted,
+ /// The file moved; `previous_path` names where from. Contents may also
+ /// have changed.
+ Renamed,
+}
+
+/// One file in a changeset, as much as the pane's tree and headers need.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ChangedFile {
+ /// The file's path after the change - or before it, for a deletion.
+ pub path: String,
+ /// Where a renamed file came from.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub previous_path: Option<String>,
+ /// What happened to the file.
+ pub kind: FileChangeKind,
+ /// Lines added.
+ pub additions: u32,
+ /// Lines removed.
+ pub deletions: u32,
+ /// The diff carries no text for this file (an image, an archive, ...).
+ #[serde(default)]
+ pub binary: bool,
+ /// This file's hunks were left out of the stored patch because the
+ /// changeset exceeded the size budget; the summary is still complete.
+ #[serde(default)]
+ pub patch_omitted: bool,
+}
+
+/// One end of the compared range, as much of it as the provider told us.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GitRef {
+ /// The branch name, when the provider names one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// The commit the diff was taken at, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sha: Option<String>,
+}
+
+impl GitRef {
+ /// A ref known by name only.
+ #[must_use]
+ pub fn named(name: impl Into<String>) -> Self {
+ Self {
+ name: Some(name.into()),
+ sha: None,
+ }
+ }
+}
+
+/// What was compared with what.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ChangesetRange {
+ /// The linked pull request's repository, as `https://github.com/owner/name`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repository: Option<String>,
+ /// The side the work started from.
+ pub base: GitRef,
+ /// The side carrying the work.
+ pub head: GitRef,
+}
+
+/// The source of the captured diff.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum ChangesetSource {
+ /// The diff of the session's linked GitHub pull request.
+ GithubPullRequest,
+}
+
+/// What an extractor hands back: the raw patch plus the range it covers. The
+/// service derives every per-file fact from the patch, so no extractor has to
+/// count lines or classify files itself.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExtractedChangeset {
+ /// Where it came from.
+ pub source: ChangesetSource,
+ /// What was compared.
+ pub range: ChangesetRange,
+ /// A git-style unified diff, possibly empty when nothing changed.
+ pub patch: String,
+ /// The extractor already cut the patch down to a size budget of its
+ /// own, so files past its cut are missing from `patch` entirely.
+ pub truncated: bool,
+}
+
+/// One capture of a session's changes, as stored and served.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Changeset {
+ /// This capture's id.
+ pub id: ChangesetId,
+ /// The session whose changes these are.
+ pub session: AgentSessionId,
+ /// Where it came from.
+ pub source: ChangesetSource,
+ /// What was compared.
+ pub range: ChangesetRange,
+ /// Every changed file, in patch order.
+ pub files: Vec<ChangedFile>,
+ /// Lines added across all files.
+ pub additions: u32,
+ /// Lines removed across all files.
+ pub deletions: u32,
+ /// Size of the stored patch. Zero when nothing changed.
+ pub patch_bytes: u64,
+ /// Some files' hunks were dropped to fit the size budget.
+ pub truncated: bool,
+ /// When the extractor took the diff.
+ pub captured_at: DateTime<Utc>,
+}
+
+impl Changeset {
+ /// Whether there is a patch to fetch at all.
+ #[must_use]
+ pub fn has_patch(&self) -> bool {
+ self.patch_bytes > 0
+ }
+}
+
+/// How the latest capture attempt ended.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum AttemptOutcome {
+ /// A changeset was stored (possibly an empty one).
+ Captured,
+ /// The linked pull request is missing or unavailable.
+ NotReady,
+ /// The extractor or storage failed.
+ Failed,
+}
+
+/// The latest attempt to capture a session's changes.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CaptureAttempt {
+ /// When it started.
+ pub started_at: DateTime<Utc>,
+ /// When it ended, or `None` while it runs.
+ pub finished_at: Option<DateTime<Utc>>,
+ /// How it ended, or `None` while it runs.
+ pub outcome: Option<AttemptOutcome>,
+ /// A user-presentable reason for a non-captured outcome.
+ pub error: Option<String>,
+}
+
+impl CaptureAttempt {
+ /// Whether the attempt is still running.
+ #[must_use]
+ pub fn in_flight(&self) -> bool {
+ self.finished_at.is_none()
+ }
+}
+
+/// Everything the Changes pane asks for at once: the latest changeset, if one
+/// was ever captured, and how the latest attempt went.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SessionChanges {
+ /// The latest capture, if any succeeded.
+ pub changeset: Option<Changeset>,
+ /// The latest attempt, if any was made.
+ pub attempt: Option<CaptureAttempt>,
+}
+
+/// An `owner/name` GitHub repository, parsed from any of the spellings a
+/// provider uses (`https://github.com/o/n`, `github.com/o/n`, `o/n`, with or
+/// without a trailing `.git`).
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct RepositorySlug {
+ /// The account the repository lives under.
+ pub owner: String,
+ /// The repository's name.
+ pub name: String,
+}
+
+impl RepositorySlug {
+ /// Parse a repository reference. `None` when the text does not name a
+ /// GitHub repository.
+ #[must_use]
+ pub fn parse(text: &str) -> Option<Self> {
+ let trimmed = text.trim().trim_end_matches('/');
+ let without_scheme = trimmed
+ .strip_prefix("https://")
+ .or_else(|| trimmed.strip_prefix("http://"))
+ .or_else(|| trimmed.strip_prefix("git@"))
+ .unwrap_or(trimmed);
+ let path = without_scheme
+ .strip_prefix("github.com/")
+ .or_else(|| without_scheme.strip_prefix("github.com:"))
+ .unwrap_or(without_scheme);
+ let path = path.strip_suffix(".git").unwrap_or(path);
+ let mut parts = path.split('/');
+ let owner = parts.next()?;
+ let name = parts.next()?;
+ if parts.next().is_some() || owner.is_empty() || name.is_empty() {
+ return None;
+ }
+ let valid = |part: &str| {
+ part.chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
+ };
+ if !valid(owner) || !valid(name) {
+ return None;
+ }
+ Some(Self {
+ owner: owner.to_owned(),
+ name: name.to_owned(),
+ })
+ }
+
+ /// The canonical `https://github.com/{owner}/{name}` address.
+ #[must_use]
+ pub fn https_url(&self) -> String {
+ format!("https://github.com/{}/{}", self.owner, self.name)
+ }
+}
+
+impl std::fmt::Display for RepositorySlug {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(formatter, "{}/{}", self.owner, self.name)
+ }
+}
+
+#[cfg(test)]
+mod test;
+
+/// A validated GitHub pull request URL, used to build a fixed-origin API request.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PullRequestRef {
+ /// The repository containing the PR, including when its head is a fork.
+ pub repository: RepositorySlug,
+ /// The positive GitHub pull request number.
+ pub number: std::num::NonZeroU64,
+}
+
+impl PullRequestRef {
+ /// Accept GitHub PR links, optionally with a files/commits suffix or fragment.
+ pub fn parse(value: &str) -> Option<Self> {
+ let url = url::Url::parse(value).ok()?;
+ if url.scheme() != "https"
+ || url.host_str() != Some("github.com")
+ || !url.username().is_empty()
+ || url.password().is_some()
+ || url.port().is_some()
+ {
+ return None;
+ }
+ let mut segments = url.path_segments()?;
+ let owner = segments.next()?;
+ let repo = segments.next()?;
+ if segments.next()? != "pull" {
+ return None;
+ }
+ let number = segments.next()?.parse().ok()?;
+ match segments.next() {
+ None => {}
+ Some("") if segments.next().is_none() => {}
+ Some("files" | "commits" | "checks") if segments.next().is_none() => {}
+ _ => return None,
+ }
+ Some(Self {
+ repository: RepositorySlug::parse(&format!("{owner}/{repo}"))?,
+ number,
+ })
+ }
+}
diff --git a/crates/agent_changes/src/domain/model/test.rs b/crates/agent_changes/src/domain/model/test.rs
new file mode 100644
index 0000000000..6c68ddaada
--- /dev/null
+++ b/crates/agent_changes/src/domain/model/test.rs
@@ -0,0 +1,85 @@
+use super::*;
+
+#[test]
+fn repository_slugs_parse_every_provider_spelling() {
+ for text in [
+ "https://github.com/macro-inc/macro",
+ "https://github.com/macro-inc/macro.git",
+ "http://github.com/macro-inc/macro/",
+ "github.com/macro-inc/macro",
+ "[email protected]:macro-inc/macro.git",
+ "macro-inc/macro",
+ ] {
+ let slug = RepositorySlug::parse(text).unwrap_or_else(|| panic!("{text} should parse"));
+ assert_eq!(slug.owner, "macro-inc", "{text}");
+ assert_eq!(slug.name, "macro", "{text}");
+ assert_eq!(slug.https_url(), "https://github.com/macro-inc/macro");
+ }
+}
+
+#[test]
+fn repository_slugs_reject_anything_that_is_not_owner_and_name() {
+ for text in [
+ "",
+ "macro",
+ "https://github.com/macro-inc",
+ "https://github.com/macro-inc/macro/pull/1",
+ "https://gitlab.com/macro-inc/macro",
+ "owner/na me",
+ ] {
+ assert!(
+ RepositorySlug::parse(text).is_none(),
+ "{text:?} should not parse"
+ );
+ }
+}
+
+#[test]
+fn enums_round_trip_through_their_wire_strings() {
+ assert_eq!(FileChangeKind::Renamed.to_string(), "renamed");
+ assert_eq!(
+ "renamed".parse::<FileChangeKind>().unwrap(),
+ FileChangeKind::Renamed
+ );
+ assert_eq!(
+ ChangesetSource::GithubPullRequest.to_string(),
+ "github_pull_request"
+ );
+ assert_eq!(
+ "github_pull_request".parse::<ChangesetSource>().unwrap(),
+ ChangesetSource::GithubPullRequest
+ );
+ assert_eq!(AttemptOutcome::NotReady.to_string(), "not_ready");
+}
+
+#[test]
+fn pull_request_urls_accept_github_pr_links_only() {
+ for suffix in [
+ "",
+ "/",
+ "/files",
+ "/commits",
+ "/checks",
+ "#discussion_r1",
+ "?diff=split",
+ ] {
+ let pr = PullRequestRef::parse(&format!("https://github.com/owner/repo/pull/123{suffix}"))
+ .unwrap();
+ assert_eq!(pr.repository.to_string(), "owner/repo");
+ assert_eq!(pr.number.get(), 123);
+ }
+ for url in [
+ "https://github.com/owner/repo/tree/work",
+ "https://github.com/owner/repo/pull/0",
+ "https://github.com/owner/repo/pull/-1",
+ "https://github.com/owner/repo/pull/1/anything",
+ "https://github.com/owner/repo/pull/1//anything",
+ "https://github.com.evil.example/owner/repo/pull/1",
+ "https://evil.example/owner/repo/pull/1",
+ "https://user:[email protected]/owner/repo/pull/1",
+ "http://github.com/owner/repo/pull/1",
+ "https://github.com/owner/repo/pull/nope",
+ ] {
+ assert!(PullRequestRef::parse(url).is_none(), "accepted {url}");
+ }
+}
diff --git a/crates/agent_changes/src/domain/patch.rs b/crates/agent_changes/src/domain/patch.rs
new file mode 100644
index 0000000000..b23dd8c9f0
--- /dev/null
+++ b/crates/agent_changes/src/domain/patch.rs
@@ -0,0 +1,347 @@
+//! Reading a git-style unified diff into per-file facts.
+//!
+//! Every extractor hands the service a raw patch - `git diff` output, or the
+//! diff GitHub renders for a compare - and this is the one place that reads
+//! it: which files it touches, what happened to each, how many lines moved,
+//! and which files carry no text at all. Doing it here, once, is what keeps
+//! extractors trivial and the summary identical whichever harness produced it.
+//!
+//! The reader is deliberately forgiving. A patch is a stream of `diff --git`
+//! blocks; anything before the first block is ignored, an unknown extended
+//! header line is skipped, and a block with no hunks is a rename, a mode
+//! change, or a binary file rather than an error.
+
+use super::model::{ChangedFile, FileChangeKind};
+
+#[cfg(test)]
+mod test;
+
+/// The most patch text stored for one changeset. Past this, whole files are
+/// left out (largest last-in-order first) and the summary says so.
+pub const MAX_PATCH_BYTES: usize = 6 * 1024 * 1024;
+
+/// The most patch text stored for one file. A single file past this is a
+/// generated artifact or a vendored tree, not something anyone reviews line
+/// by line; its summary row stays, its hunks go.
+pub const MAX_FILE_PATCH_BYTES: usize = 1024 * 1024;
+
+/// One file's slice of a patch: the facts, and the text they were read from.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ParsedFile {
+ /// What the diff says about the file.
+ pub file: ChangedFile,
+ /// This file's complete block, `diff --git` header through its last
+ /// hunk line, without a trailing newline.
+ pub text: String,
+}
+
+/// Split `patch` into its files, in order.
+#[must_use]
+pub fn parse_git_patch(patch: &str) -> Vec<ParsedFile> {
+ let mut files = Vec::new();
+ let mut current: Option<BlockReader> = None;
+ for line in patch.split_inclusive('\n') {
+ let content = line.strip_suffix('\n').unwrap_or(line);
+ let content = content.strip_suffix('\r').unwrap_or(content);
+ if let Some(rest) = content.strip_prefix("diff --git ") {
+ if let Some(block) = current.take() {
+ files.push(block.finish());
+ }
+ current = Some(BlockReader::start(rest, line));
+ continue;
+ }
+ if let Some(block) = current.as_mut() {
+ block.push(content, line);
+ }
+ }
+ if let Some(block) = current.take() {
+ files.push(block.finish());
+ }
+ files
+}
+
+/// A patch cut down to the size budget: the text to store, the files with
+/// `patch_omitted` set where their hunks were dropped, and whether anything
+/// was.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct BudgetedPatch {
+ /// The concatenated blocks that fit.
+ pub patch: String,
+ /// Every file, in patch order.
+ pub files: Vec<ChangedFile>,
+ /// Whether any file's hunks were left out.
+ pub truncated: bool,
+}
+
+/// Keep as much of `files` as the budget allows.
+///
+/// A file larger than `max_file_bytes` is always omitted; the rest are kept
+/// in patch order while the running total stays within `max_total_bytes`.
+/// Order is preserved rather than packing by size so the stored patch reads
+/// like the diff it came from.
+#[must_use]
+pub fn budget_patch(
+ files: Vec<ParsedFile>,
+ max_total_bytes: usize,
+ max_file_bytes: usize,
+) -> BudgetedPatch {
+ let mut patch = String::new();
+ let mut kept = Vec::with_capacity(files.len());
+ let mut truncated = false;
+ for parsed in files {
+ let ParsedFile { mut file, text } = parsed;
+ let block_bytes = text.len() + 1;
+ let fits = text.len() <= max_file_bytes && patch.len() + block_bytes <= max_total_bytes;
+ if fits && !file.binary {
+ patch.push_str(&text);
+ patch.push('\n');
+ } else if !file.binary {
+ file.patch_omitted = true;
+ truncated = true;
+ }
+ kept.push(file);
+ }
+ BudgetedPatch {
+ patch,
+ files: kept,
+ truncated,
+ }
+}
+
+/// Totals across a changeset's files.
+#[must_use]
+pub fn totals(files: &[ChangedFile]) -> (u32, u32) {
+ files.iter().fold((0, 0), |(adds, dels), file| {
+ (
+ adds.saturating_add(file.additions),
+ dels.saturating_add(file.deletions),
+ )
+ })
+}
+
+/// Reads one `diff --git` block line by line.
+struct BlockReader {
+ header_old: String,
+ header_new: String,
+ old_path: Option<String>,
+ new_path: Option<String>,
+ rename_from: Option<String>,
+ rename_to: Option<String>,
+ added: bool,
+ deleted: bool,
+ binary: bool,
+ in_hunks: bool,
+ additions: u32,
+ deletions: u32,
+ text: String,
+}
+
+impl BlockReader {
+ fn start(header_rest: &str, raw_line: &str) -> Self {
+ let (header_old, header_new) = split_header_paths(header_rest);
+ Self {
+ header_old,
+ header_new,
+ old_path: None,
+ new_path: None,
+ rename_from: None,
+ rename_to: None,
+ added: false,
+ deleted: false,
+ binary: false,
+ in_hunks: false,
+ additions: 0,
+ deletions: 0,
+ text: raw_line.to_owned(),
+ }
+ }
+
+ fn push(&mut self, content: &str, raw_line: &str) {
+ self.text.push_str(raw_line);
+ if self.in_hunks {
+ self.count(content);
+ return;
+ }
+ if content.starts_with("@@") {
+ self.in_hunks = true;
+ return;
+ }
+ if let Some(path) = content.strip_prefix("--- ") {
+ self.old_path = Some(strip_side(path, "a/"));
+ } else if let Some(path) = content.strip_prefix("+++ ") {
+ self.new_path = Some(strip_side(path, "b/"));
+ } else if content.starts_with("new file mode") {
+ self.added = true;
+ } else if content.starts_with("deleted file mode") {
+ self.deleted = true;
+ } else if let Some(from) = content.strip_prefix("rename from ") {
+ self.rename_from = Some(unquote(from));
+ } else if let Some(to) = content.strip_prefix("rename to ") {
+ self.rename_to = Some(unquote(to));
+ } else if content.starts_with("Binary files ") || content.starts_with("GIT binary patch") {
+ self.binary = true;
+ }
+ }
+
+ fn count(&mut self, content: &str) {
+ // `--- `/`+++ ` cannot be headers here: a header only precedes the
+ // first hunk, and inside one a leading `-`/`+` is a changed line
+ // whatever follows it.
+ if content.starts_with('+') {
+ self.additions = self.additions.saturating_add(1);
+ } else if content.starts_with('-') {
+ self.deletions = self.deletions.saturating_add(1);
+ }
+ }
+
+ fn finish(mut self) -> ParsedFile {
+ while self.text.ends_with('\n') || self.text.ends_with('\r') {
+ self.text.pop();
+ }
+ let dev_null = |path: &Option<String>| path.as_deref() == Some("/dev/null");
+ let added = self.added || dev_null(&self.old_path);
+ let deleted = self.deleted || dev_null(&self.new_path);
+ let renamed = self.rename_from.is_some() || self.rename_to.is_some();
+
+ let new_name = self
+ .new_path
+ .clone()
+ .filter(|path| path != "/dev/null")
+ .or_else(|| self.rename_to.clone())
+ .unwrap_or_else(|| self.header_new.clone());
+ let old_name = self
+ .old_path
+ .clone()
+ .filter(|path| path != "/dev/null")
+ .or_else(|| self.rename_from.clone())
+ .unwrap_or_else(|| self.header_old.clone());
+
+ let (kind, path, previous_path) = if deleted && !added {
+ (FileChangeKind::Deleted, old_name, None)
+ } else if added && !deleted {
+ (FileChangeKind::Added, new_name, None)
+ } else if renamed || old_name != new_name {
+ (FileChangeKind::Renamed, new_name, Some(old_name))
+ } else {
+ (FileChangeKind::Modified, new_name, None)
+ };
+
+ ParsedFile {
+ file: ChangedFile {
+ path,
+ previous_path,
+ kind,
+ additions: self.additions,
+ deletions: self.deletions,
+ binary: self.binary,
+ patch_omitted: false,
+ },
+ text: self.text,
+ }
+ }
+}
+
+/// `a/OLD b/NEW` into `(OLD, NEW)`.
+///
+/// Paths can contain spaces, so the split point is the ` b/` after which
+/// the two sides read the same - the common case of an unrenamed file - and
+/// failing that the first ` b/`. Quoted paths are split on the closing quote.
+fn split_header_paths(rest: &str) -> (String, String) {
+ if rest.starts_with('"')
+ && let Some((old, new)) = split_quoted_pair(rest)
+ {
+ return (strip_side(&old, "a/"), strip_side(&new, "b/"));
+ }
+ let candidates: Vec<usize> = rest.match_indices(" b/").map(|(index, _)| index).collect();
+ for index in &candidates {
+ let old = &rest[..*index];
+ let new = &rest[index + 1..];
+ if old.strip_prefix("a/") == new.strip_prefix("b/") {
+ return (strip_side(old, "a/"), strip_side(new, "b/"));
+ }
+ }
+ match candidates.first() {
+ Some(index) => (
+ strip_side(&rest[..*index], "a/"),
+ strip_side(&rest[index + 1..], "b/"),
+ ),
+ None => (strip_side(rest, "a/"), strip_side(rest, "b/")),
+ }
+}
+
+/// Two C-quoted strings separated by a space.
+fn split_quoted_pair(rest: &str) -> Option<(String, String)> {
+ let mut escaped = false;
+ for (index, character) in rest.char_indices().skip(1) {
+ match character {
+ '\\' if !escaped => escaped = true,
+ '"' if !escaped => {
+ let first = &rest[..=index];
+ let second = rest.get(index + 1..)?.trim_start();
+ return Some((unquote(first), unquote(second)));
+ }
+ _ => escaped = false,
+ }
+ }
+ None
+}
+
+/// Drop git's `a/`/`b/` prefix and any `\t<timestamp>` suffix, unquoting a
+/// C-quoted path on the way.
+fn strip_side(path: &str, prefix: &str) -> String {
+ let path = path.split('\t').next().unwrap_or(path);
+ let unquoted = unquote(path);
+ if unquoted == "/dev/null" {
+ return unquoted;
+ }
+ unquoted
+ .strip_prefix(prefix)
+ .map(str::to_owned)
+ .unwrap_or(unquoted)
+}
+
+/// Undo git's C-style quoting of paths with unusual characters.
+fn unquote(path: &str) -> String {
+ let path = path.trim();
+ let Some(inner) = path
+ .strip_prefix('"')
+ .and_then(|rest| rest.strip_suffix('"'))
+ else {
+ return path.to_owned();
+ };
+ let mut bytes = Vec::with_capacity(inner.len());
+ let mut chars = inner.chars().peekable();
+ while let Some(character) = chars.next() {
+ if character != '\\' {
+ let mut buffer = [0u8; 4];
+ bytes.extend_from_slice(character.encode_utf8(&mut buffer).as_bytes());
+ continue;
+ }
+ match chars.next() {
+ Some('n') => bytes.push(b'\n'),
+ Some('t') => bytes.push(b'\t'),
+ Some('r') => bytes.push(b'\r'),
+ Some('\\') => bytes.push(b'\\'),
+ Some('"') => bytes.push(b'"'),
+ Some(digit @ '0'..='7') => {
+ let mut value = digit.to_digit(8).unwrap_or(0);
+ for _ in 0..2 {
+ match chars.peek().and_then(|next| next.to_digit(8)) {
+ Some(next) => {
+ value = value * 8 + next;
+ chars.next();
+ }
+ None => break,
+ }
+ }
+ bytes.push(value.min(255) as u8);
+ }
+ Some(other) => {
+ let mut buffer = [0u8; 4];
+ bytes.extend_from_slice(other.encode_utf8(&mut buffer).as_bytes());
+ }
+ None => bytes.push(b'\\'),
+ }
+ }
+ String::from_utf8_lossy(&bytes).into_owned()
+}
diff --git a/crates/agent_changes/src/domain/patch/test.rs b/crates/agent_changes/src/domain/patch/test.rs
new file mode 100644
index 0000000000..fa2008e444
--- /dev/null
+++ b/crates/agent_changes/src/domain/patch/test.rs
@@ -0,0 +1,197 @@
+use super::*;
+
+const MODIFIED: &str = "\
+diff --git a/src/lib.rs b/src/lib.rs
+index 1111111..2222222 100644
+--- a/src/lib.rs
++++ b/src/lib.rs
+@@ -1,4 +1,5 @@
+ fn main() {
+- println!(\"hi\");
++ println!(\"hello\");
++ println!(\"world\");
+ }
+";
+
+const ADDED: &str = "\
+diff --git a/docs/new.md b/docs/new.md
+new file mode 100644
+index 0000000..3333333
+--- /dev/null
++++ b/docs/new.md
+@@ -0,0 +1,2 @@
++# Title
++text
+";
+
+const DELETED: &str = "\
+diff --git a/old.txt b/old.txt
+deleted file mode 100644
+index 4444444..0000000
+--- a/old.txt
++++ /dev/null
+@@ -1,2 +0,0 @@
+-gone
+-forever
+";
+
+const RENAMED_PURE: &str = "\
+diff --git a/a/before.rs b/b/after.rs
+similarity index 100%
+rename from a/before.rs
+rename to b/after.rs
+";
+
+const RENAMED_CHANGED: &str = "\
+diff --git a/before.rs b/after.rs
+similarity index 90%
+rename from before.rs
+rename to after.rs
+index 5555555..6666666 100644
+--- a/before.rs
++++ b/after.rs
+@@ -1 +1 @@
+-old
++new
+";
+
+const BINARY: &str = "\
+diff --git a/logo.png b/logo.png
+new file mode 100644
+index 0000000..7777777
+Binary files /dev/null and b/logo.png differ
+";
+
+#[test]
+fn a_modified_file_counts_its_lines() {
+ let files = parse_git_patch(MODIFIED);
+ assert_eq!(files.len(), 1);
+ let file = &files[0].file;
+ assert_eq!(file.path, "src/lib.rs");
+ assert_eq!(file.kind, FileChangeKind::Modified);
+ assert_eq!((file.additions, file.deletions), (2, 1));
+ assert!(!file.binary);
+ assert_eq!(files[0].text, MODIFIED.trim_end());
+}
+
+#[test]
+fn added_and_deleted_files_are_told_apart_by_dev_null_and_modes() {
+ let files = parse_git_patch(&format!("{ADDED}{DELETED}"));
+ assert_eq!(files.len(), 2);
+ assert_eq!(files[0].file.path, "docs/new.md");
+ assert_eq!(files[0].file.kind, FileChangeKind::Added);
+ assert_eq!((files[0].file.additions, files[0].file.deletions), (2, 0));
+ assert_eq!(files[1].file.path, "old.txt");
+ assert_eq!(files[1].file.kind, FileChangeKind::Deleted);
+ assert_eq!((files[1].file.additions, files[1].file.deletions), (0, 2));
+}
+
+#[test]
+fn renames_keep_the_previous_path_with_or_without_hunks() {
+ let files = parse_git_patch(&format!("{RENAMED_PURE}{RENAMED_CHANGED}"));
+ assert_eq!(files.len(), 2);
+ assert_eq!(files[0].file.kind, FileChangeKind::Renamed);
+ assert_eq!(files[0].file.path, "b/after.rs");
+ assert_eq!(files[0].file.previous_path.as_deref(), Some("a/before.rs"));
+ assert_eq!((files[0].file.additions, files[0].file.deletions), (0, 0));
+ assert_eq!(files[1].file.kind, FileChangeKind::Renamed);
+ assert_eq!(files[1].file.path, "after.rs");
+ assert_eq!(files[1].file.previous_path.as_deref(), Some("before.rs"));
+ assert_eq!((files[1].file.additions, files[1].file.deletions), (1, 1));
+}
+
+#[test]
+fn binary_files_are_flagged_and_carry_no_counts() {
+ let files = parse_git_patch(BINARY);
+ assert_eq!(files.len(), 1);
+ assert!(files[0].file.binary);
+ assert_eq!(files[0].file.kind, FileChangeKind::Added);
+ assert_eq!(files[0].file.path, "logo.png");
+ assert_eq!((files[0].file.additions, files[0].file.deletions), (0, 0));
+}
+
+#[test]
+fn lines_that_look_like_headers_inside_a_hunk_are_changes() {
+ let patch = "\
+diff --git a/notes.md b/notes.md
+index 1..2 100644
+--- a/notes.md
++++ b/notes.md
+@@ -1,2 +1,2 @@
+---- removed rule
+++++ added rule
+ kept
+\\ No newline at end of file
+";
+ let files = parse_git_patch(patch);
+ assert_eq!(files[0].file.path, "notes.md");
+ assert_eq!((files[0].file.additions, files[0].file.deletions), (1, 1));
+}
+
+#[test]
+fn paths_with_spaces_and_quoting_survive() {
+ let patch = "\
+diff --git a/with space.txt b/with space.txt
+index 1..2 100644
+--- a/with space.txt
++++ b/with space.txt
+@@ -1 +1 @@
+-a
++b
+diff --git \"a/caf\\303\\251.txt\" \"b/caf\\303\\251.txt\"
+new file mode 100644
+--- /dev/null
++++ \"b/caf\\303\\251.txt\"
+@@ -0,0 +1 @@
++x
+";
+ let files = parse_git_patch(patch);
+ assert_eq!(files.len(), 2);
+ assert_eq!(files[0].file.path, "with space.txt");
+ assert_eq!(files[1].file.path, "café.txt");
+ assert_eq!(files[1].file.kind, FileChangeKind::Added);
+}
+
+#[test]
+fn text_before_the_first_block_and_an_empty_patch_are_ignored() {
+ assert!(parse_git_patch("").is_empty());
+ assert!(parse_git_patch("\n\n").is_empty());
+ let files = parse_git_patch(&format!("From abc Mon Sep 17\nSubject: x\n\n{MODIFIED}"));
+ assert_eq!(files.len(), 1);
+}
+
+#[test]
+fn the_budget_drops_whole_files_and_says_so() {
+ let files = parse_git_patch(&format!("{MODIFIED}{ADDED}{DELETED}"));
+ let small_first = files[0].text.len();
+ let budgeted = budget_patch(files.clone(), small_first + 1, usize::MAX);
+ assert!(budgeted.truncated);
+ assert!(!budgeted.files[0].patch_omitted);
+ assert!(budgeted.files[1].patch_omitted);
+ assert!(budgeted.files[2].patch_omitted);
+ assert_eq!(budgeted.patch.trim_end(), MODIFIED.trim_end());
+ assert_eq!(budgeted.files.len(), 3, "omitted files keep their summary");
+
+ let generous = budget_patch(files, usize::MAX, usize::MAX);
+ assert!(!generous.truncated);
+ assert_eq!(parse_git_patch(&generous.patch).len(), 3);
+}
+
+#[test]
+fn a_single_oversized_file_is_omitted_on_its_own() {
+ let files = parse_git_patch(&format!("{MODIFIED}{ADDED}"));
+ let budgeted = budget_patch(files, usize::MAX, 10);
+ assert!(budgeted.truncated);
+ assert!(budgeted.files.iter().all(|file| file.patch_omitted));
+ assert!(budgeted.patch.is_empty());
+}
+
+#[test]
+fn binary_files_never_enter_the_stored_patch() {
+ let files = parse_git_patch(&format!("{BINARY}{MODIFIED}"));
+ let budgeted = budget_patch(files, usize::MAX, usize::MAX);
+ assert!(!budgeted.truncated);
+ assert!(!budgeted.files[0].patch_omitted);
+ assert_eq!(parse_git_patch(&budgeted.patch).len(), 1);
+ assert_eq!(totals(&budgeted.files), (2, 1));
+}
diff --git a/crates/agent_changes/src/domain/ports.rs b/crates/agent_changes/src/domain/ports.rs
new file mode 100644
index 0000000000..7fd9111a69
--- /dev/null
+++ b/crates/agent_changes/src/domain/ports.rs
@@ -0,0 +1,139 @@
+//! Storage and GitHub capabilities required by the changes service.
+
+use std::future::Future;
+
+use agent_session::domain::model::AgentSession;
+
+use super::error::ExtractError;
+use super::model::{AgentSessionId, AttemptOutcome, Changeset, ExtractedChangeset, SessionChanges};
+use chrono::{DateTime, Utc};
+
+/// Reads the linked GitHub pull request for a session. The service derives
+/// per-file facts from the raw patch.
+pub trait ChangesetExtractor: Send + Sync + 'static {
+ /// The current diff for `session`, or why there is none.
+ fn extract(
+ &self,
+ session: &AgentSession,
+ ) -> impl Future<Output = Result<ExtractedChangeset, ExtractError>> + Send;
+}
+
+/// Where a stored patch lives in the blob store.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct PatchBlobKey(String);
+
+impl PatchBlobKey {
+ /// The key for a capture's patch: one object per capture, under the
+ /// session, so an older capture's readers are never handed a newer body.
+ #[must_use]
+ pub fn for_changeset(session: AgentSessionId, changeset: super::model::ChangesetId) -> Self {
+ Self(format!(
+ "agent-sessions/{session}/changes/{changeset}.patch"
+ ))
+ }
+
+ /// Wrap a key read back from storage.
+ #[must_use]
+ pub fn from_stored(key: String) -> Self {
+ Self(key)
+ }
+
+ /// The key as the blob store spells it.
+ #[must_use]
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::fmt::Display for PatchBlobKey {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(&self.0)
+ }
+}
+
+/// The summary row: one per session, replaced on every capture.
+pub trait ChangesetRepo: Send + Sync + 'static {
+ /// Note that a capture started at `started_at`. Creates the session's
+ /// row when this is its first attempt; an earlier changeset stays put.
+ fn begin_attempt(
+ &self,
+ session: AgentSessionId,
+ started_at: DateTime<Utc>,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+
+ /// Replace the session's changeset with `changeset`, whose patch (if any)
+ /// is stored under `patch_key`, and close the running attempt as
+ /// captured. Returns the key of the patch this one superseded, so the
+ /// caller can delete the orphaned blob.
+ fn record_changeset(
+ &self,
+ changeset: &Changeset,
+ patch_key: Option<&PatchBlobKey>,
+ finished_at: DateTime<Utc>,
+ ) -> impl Future<Output = Result<Option<PatchBlobKey>, rootcause::Report>> + Send;
+
+ /// Close the running attempt without a changeset: what went wrong, in a
+ /// word and in a sentence the user can read. An earlier changeset stays.
+ fn record_failure(
+ &self,
+ session: AgentSessionId,
+ outcome: AttemptOutcome,
+ error: Option<&str>,
+ finished_at: DateTime<Utc>,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+
+ /// The session's latest changeset and attempt, or an empty
+ /// [`SessionChanges`] for a session nothing was ever captured for.
+ fn get(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<SessionChanges, rootcause::Report>> + Send;
+
+ /// Where the session's current patch is stored, if it has one.
+ fn patch_key(
+ &self,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Result<Option<PatchBlobKey>, rootcause::Report>> + Send;
+}
+
+/// The patch bodies, kept out of the database because a patch can be
+/// megabytes and is read as a whole or not at all.
+pub trait ChangesetBlobStore: Send + Sync + 'static {
+ /// Store `patch` under `key`, replacing whatever was there.
+ fn put_patch(
+ &self,
+ key: &PatchBlobKey,
+ patch: &str,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+
+ /// The patch under `key`, or `None` when nothing is stored there.
+ fn get_patch(
+ &self,
+ key: &PatchBlobKey,
+ ) -> impl Future<Output = Result<Option<String>, rootcause::Report>> + Send;
+
+ /// Remove the patch under `key`. Removing a missing key succeeds.
+ fn delete_patch(
+ &self,
+ key: &PatchBlobKey,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send;
+}
+
+/// The patch and actual base/head refs of a GitHub pull request.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PullRequestDiff {
+ /// Git-style unified diff returned by GitHub.
+ pub patch: String,
+ /// The PR's target and source, including forks and non-default bases.
+ pub range: super::model::ChangesetRange,
+}
+
+/// Reads a pull request using the session owner's GitHub repository access.
+pub trait PullRequestDiffReader: Send + Sync + 'static {
+ /// Read the PR itself; never fall back to a branch or workspace diff.
+ fn read(
+ &self,
+ user: &macro_user_id::user_id::MacroUserIdStr<'static>,
+ pull_request: &super::model::PullRequestRef,
+ ) -> impl Future<Output = Result<PullRequestDiff, super::error::CompareError>> + Send;
+}
diff --git a/crates/agent_changes/src/domain/pull_request.rs b/crates/agent_changes/src/domain/pull_request.rs
new file mode 100644
index 0000000000..a1082aef77
--- /dev/null
+++ b/crates/agent_changes/src/domain/pull_request.rs
@@ -0,0 +1,47 @@
+//! Reading the linked pull request, independently of the session's harness.
+
+use agent_session::domain::model::AgentSession;
+
+use super::error::{CompareError, ExtractError};
+use super::model::{ChangesetSource, ExtractedChangeset, PullRequestRef};
+use super::ports::{ChangesetExtractor, PullRequestDiffReader};
+
+#[cfg(test)]
+mod test;
+
+/// Extracts only the diff of a session's linked GitHub pull request.
+pub struct PullRequestChanges<Reader> {
+ reader: Reader,
+}
+
+impl<Reader> PullRequestChanges<Reader> {
+ /// Read pull requests through `reader`.
+ pub fn new(reader: Reader) -> Self {
+ Self { reader }
+ }
+}
+
+impl<Reader: PullRequestDiffReader> ChangesetExtractor for PullRequestChanges<Reader> {
+ async fn extract(&self, session: &AgentSession) -> Result<ExtractedChangeset, ExtractError> {
+ let url = session.pull_request_url.as_deref().ok_or_else(|| {
+ ExtractError::NotReady(
+ "Link a GitHub pull request to this session to review its changes.".to_owned(),
+ )
+ })?;
+ let pull_request = PullRequestRef::parse(url).ok_or_else(|| {
+ ExtractError::NotReady("The linked URL is not a GitHub pull request.".to_owned())
+ })?;
+ let diff = self.reader.read(&session.owner_id, &pull_request).await.map_err(|error| match error {
+ CompareError::NotFound => ExtractError::NotReady("The linked pull request is not available on GitHub.".to_owned()),
+ CompareError::TooLarge => ExtractError::NotReady("This pull request is too large to load here. Review it on GitHub.".to_owned()),
+ CompareError::Unavailable => ExtractError::NotReady("Macro's GitHub App cannot read this pull request. Check its repository access.".to_owned()),
+ CompareError::Other(report) => ExtractError::Failed(report),
+ })?;
+ Ok(ExtractedChangeset {
+ source: ChangesetSource::GithubPullRequest,
+ range: diff.range,
+ patch: diff.patch,
+ truncated: false,
+ })
+ }
+}
diff --git a/crates/agent_changes/src/domain/pull_request/test.rs b/crates/agent_changes/src/domain/pull_request/test.rs
new file mode 100644
index 0000000000..3df2225cac
--- /dev/null
+++ b/crates/agent_changes/src/domain/pull_request/test.rs
@@ -0,0 +1,106 @@
+use super::*;
+use crate::domain::model::{ChangesetRange, GitRef};
+use crate::domain::ports::PullRequestDiff;
+use agent_session::domain::model::AgentSessionId;
+use agent_session::testing::test_agent_session;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct Reader {
+ calls: Mutex<Vec<(String, PullRequestRef)>>,
+ error: Option<fn() -> CompareError>,
+}
+
+impl PullRequestDiffReader for Reader {
+ async fn read(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ pr: &PullRequestRef,
+ ) -> Result<PullRequestDiff, CompareError> {
+ self.calls
+ .lock()
+ .unwrap()
+ .push((user.to_string(), pr.clone()));
+ if let Some(error) = self.error {
+ return Err(error());
+ }
+ Ok(PullRequestDiff {
+ patch: "PR diff".to_owned(),
+ range: ChangesetRange {
+ repository: Some(pr.repository.https_url()),
+ base: GitRef::named("release"),
+ head: GitRef::named("fork-fix"),
+ },
+ })
+ }
+}
+
+#[tokio::test]
+async fn every_harness_reads_the_linked_pr_with_the_session_owners_access() {
+ let extractor = PullRequestChanges::new(Reader::default());
+ for harness in [
+ "cursor",
+ "macrod",
+ "opencode",
+ "codex-cloud",
+ "claude-cloud",
+ "macro-inmem",
+ ] {
+ let mut session = test_agent_session(AgentSessionId::TEST_A);
+ session.harness = harness.to_owned();
+ session.pull_request_url = Some("https://github.com/upstream/repo/pull/42".to_owned());
+ session.repo_url = Some("https://github.com/other/repo".to_owned());
+ let changes = extractor.extract(&session).await.unwrap();
+ assert_eq!(changes.source, ChangesetSource::GithubPullRequest);
+ assert_eq!(changes.patch, "PR diff");
+ assert_eq!(
+ changes.range.repository.as_deref(),
+ Some("https://github.com/upstream/repo")
+ );
+ assert_eq!(changes.range.base.name.as_deref(), Some("release"));
+ let calls = extractor.reader.calls.lock().unwrap();
+ let (user, pr) = calls.last().unwrap();
+ assert_eq!(user, &session.owner_id.to_string());
+ assert_eq!(pr.number.get(), 42);
+ }
+}
+
+#[tokio::test]
+async fn missing_or_invalid_pr_never_falls_back_to_a_branch_or_runtime() {
+ let extractor = PullRequestChanges::new(Reader::default());
+ for url in [
+ None,
+ Some("https://github.com/o/r/tree/work"),
+ Some("https://evil.example/o/r/pull/1"),
+ ] {
+ let mut session = test_agent_session(AgentSessionId::TEST_A);
+ session.pull_request_url = url.map(str::to_owned);
+ assert!(matches!(
+ extractor.extract(&session).await,
+ Err(ExtractError::NotReady(_))
+ ));
+ }
+ assert!(extractor.reader.calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn inaccessible_and_oversized_prs_remain_unavailable_without_a_fallback() {
+ for error in [
+ || CompareError::NotFound,
+ || CompareError::Unavailable,
+ || CompareError::TooLarge,
+ ] {
+ let extractor = PullRequestChanges::new(Reader {
+ error: Some(error),
+ ..Reader::default()
+ });
+ let mut session = test_agent_session(AgentSessionId::TEST_A);
+ session.pull_request_url = Some("https://github.com/o/r/pull/1".to_owned());
+ assert!(matches!(
+ extractor.extract(&session).await,
+ Err(ExtractError::NotReady(_))
+ ));
+ assert_eq!(extractor.reader.calls.lock().unwrap().len(), 1);
+ }
+}
diff --git a/crates/agent_changes/src/domain/service.rs b/crates/agent_changes/src/domain/service.rs
new file mode 100644
index 0000000000..cbe75df72d
--- /dev/null
+++ b/crates/agent_changes/src/domain/service.rs
@@ -0,0 +1,443 @@
+//! Capturing, storing, and serving a session's changes.
+//!
+//! One capture is one round trip through the extractor: read the patch, read
+//! the facts out of it, store the patch, replace the summary, tell the
+//! viewers. Captures run after every turn - the moment a session has
+//! something new to show - and on demand from the pane. A session never has
+//! two captures running at once: a request that lands mid-capture is folded
+//! into a rerun, so the stored changeset always reflects a state at least as
+//! new as the request that asked for it.
+
+use std::collections::HashMap;
+use std::future::Future;
+use std::sync::{Arc, Mutex};
+
+use agent_session::domain::model::AgentSession;
+use agent_session::domain::ports::{AgentSessionRealtime, AgentSessionRepo, SessionTurnObserver};
+use agent_session::domain::session::StopReason;
+use chrono::Utc;
+use entity_access::domain::models::{
+ EditAccessLevel, EntityAccessReceipt, EntityType, RequiredPermission, ViewAccessLevel,
+};
+use macro_uuid::Uuid;
+use tracing::Instrument as _;
+
+use super::error::{ChangesError, ExtractError, Result};
+use super::model::{AgentSessionId, AttemptOutcome, Changeset, ChangesetId, SessionChanges};
+use super::patch::{self, MAX_FILE_PATCH_BYTES, MAX_PATCH_BYTES};
+use super::ports::{ChangesetBlobStore, ChangesetExtractor, ChangesetRepo, PatchBlobKey};
+
+#[cfg(test)]
+mod test;
+
+/// How one capture ended.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CaptureOutcome {
+ /// A changeset (possibly empty) was stored.
+ Captured(Box<Changeset>),
+ /// The pull request was not available; the reason was recorded.
+ NotReady,
+ /// The extractor or the storage failed; the reason was recorded.
+ Failed,
+ /// A capture was already running; it will run once more when it ends,
+ /// so the caller's request is not lost.
+ Queued,
+}
+
+/// What the inbound adapters ask of the service, so they can be generic over
+/// one type rather than the service's five.
+pub trait AgentChanges: Send + Sync + 'static {
+ /// The latest changeset and attempt for the session the receipt names.
+ fn changes(
+ &self,
+ access: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<SessionChanges>> + Send;
+
+ /// The stored patch for the session the receipt names.
+ fn patch(
+ &self,
+ access: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<String>> + Send;
+
+ /// Start a capture without waiting for it; answer with the state as it
+ /// stands.
+ fn request_capture(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ ) -> impl Future<Output = Result<SessionChanges>> + Send;
+}
+
+struct Inner<Sessions, Extractor, Repo, Blobs, Realtime> {
+ sessions: Sessions,
+ extractor: Extractor,
+ repo: Repo,
+ blobs: Blobs,
+ realtime: Realtime,
+ /// Sessions with a capture running, and whether another was asked for
+ /// while it ran.
+ in_flight: Mutex<HashMap<AgentSessionId, bool>>,
+}
+
+/// The changes service: one per process, cloned wherever a capture can start.
+pub struct AgentChangesService<Sessions, Extractor, Repo, Blobs, Realtime> {
+ inner: Arc<Inner<Sessions, Extractor, Repo, Blobs, Realtime>>,
+}
+
+// Manual Clone so the port types need not be Clone; a clone is another
+// handle on the same in-flight table, which is what makes "one capture per
+// session" hold across every handle.
+impl<Sessions, Extractor, Repo, Blobs, Realtime> Clone
+ for AgentChangesService<Sessions, Extractor, Repo, Blobs, Realtime>
+{
+ fn clone(&self) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ }
+ }
+}
+
+impl<Sessions, Extractor, Repo, Blobs, Realtime>
+ AgentChangesService<Sessions, Extractor, Repo, Blobs, Realtime>
+where
+ Sessions: AgentSessionRepo,
+ Extractor: ChangesetExtractor,
+ Repo: ChangesetRepo,
+ Blobs: ChangesetBlobStore,
+ Realtime: AgentSessionRealtime + Send + Sync + 'static,
+{
+ /// Build the service from its ports.
+ pub fn new(
+ sessions: Sessions,
+ extractor: Extractor,
+ repo: Repo,
+ blobs: Blobs,
+ realtime: Realtime,
+ ) -> Self {
+ Self {
+ inner: Arc::new(Inner {
+ sessions,
+ extractor,
+ repo,
+ blobs,
+ realtime,
+ in_flight: Mutex::new(HashMap::new()),
+ }),
+ }
+ }
+
+ /// The latest changeset and attempt for the session the receipt names.
+ async fn read_changes(
+ &self,
+ access: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<SessionChanges> {
+ let session = session_of(access)?;
+ self.inner
+ .repo
+ .get(session)
+ .await
+ .map_err(ChangesError::Storage)
+ }
+
+ /// The stored patch for the session the receipt names.
+ async fn read_patch(&self, access: &EntityAccessReceipt<ViewAccessLevel>) -> Result<String> {
+ let session = session_of(access)?;
+ let key = self
+ .inner
+ .repo
+ .patch_key(session)
+ .await
+ .map_err(ChangesError::Storage)?
+ .ok_or(ChangesError::NoChangeset)?;
+ self.inner
+ .blobs
+ .get_patch(&key)
+ .await
+ .map_err(ChangesError::Storage)?
+ .ok_or(ChangesError::PatchMissing)
+ }
+
+ /// Start a capture for the session the receipt names, without waiting
+ /// for it, and answer with the state as it stands - which includes the
+ /// attempt just started, once the repo has noted it.
+ async fn start_capture(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ ) -> Result<SessionChanges> {
+ let session = session_of(access)?;
+ self.capture_in_background(session);
+ // Give the spawned capture a chance to mark its attempt so the
+ // answer already says "running" - but never wait on the extractor.
+ tokio::task::yield_now().await;
+ self.inner
+ .repo
+ .get(session)
+ .await
+ .map_err(ChangesError::Storage)
+ }
+
+ /// Run a capture on a task of its own. Safe to call from anywhere on a
+ /// runtime - the session actor's task included - because it returns
+ /// before any work happens.
+ pub fn capture_in_background(&self, session: AgentSessionId) {
+ let service = self.clone();
+ let span = tracing::info_span!("agent.changes.capture", agent.session.id = %session);
+ tokio::spawn(
+ async move {
+ if let Err(error) = service.capture(session).await {
+ tracing::warn!(error = ?error, %session, "capturing session changes failed");
+ }
+ }
+ .instrument(span),
+ );
+ }
+
+ /// Capture the session's changes now, rerunning once if another capture
+ /// was requested while this one ran.
+ pub async fn capture(&self, session: AgentSessionId) -> Result<CaptureOutcome> {
+ if !self.claim(session) {
+ return Ok(CaptureOutcome::Queued);
+ }
+ let mut outcome = self.capture_once(session).await;
+ while self.release(session) {
+ // Somebody asked again mid-capture; their request is the newer
+ // state, so capture once more before letting go.
+ if !self.claim(session) {
+ break;
+ }
+ outcome = self.capture_once(session).await;
+ }
+ outcome
+ }
+
+ /// Take the session's capture slot, or note a rerun if it is taken.
+ fn claim(&self, session: AgentSessionId) -> bool {
+ let mut in_flight = self
+ .inner
+ .in_flight
+ .lock()
+ .expect("in-flight table poisoned");
+ match in_flight.get_mut(&session) {
+ Some(rerun) => {
+ *rerun = true;
+ false
+ }
+ None => {
+ in_flight.insert(session, false);
+ true
+ }
+ }
+ }
+
+ /// Give the slot back. Whether a rerun was asked for meanwhile.
+ fn release(&self, session: AgentSessionId) -> bool {
+ let mut in_flight = self
+ .inner
+ .in_flight
+ .lock()
+ .expect("in-flight table poisoned");
+ in_flight.remove(&session).unwrap_or(false)
+ }
+
+ async fn capture_once(&self, session: AgentSessionId) -> Result<CaptureOutcome> {
+ let started_at = Utc::now();
+ let row = self.inner.sessions.get(session).await?;
+ self.inner
+ .repo
+ .begin_attempt(session, started_at)
+ .await
+ .map_err(ChangesError::Storage)?;
+ // Viewers learn a capture is running the same way they learn it
+ // ended: by re-reading the summary.
+ self.notify(session).await;
+
+ let extracted = self.inner.extractor.extract(&row).await;
+ let outcome = match extracted {
+ Ok(extracted) => self.store(&row, extracted).await,
+ Err(ExtractError::NotReady(reason)) => {
+ tracing::info!(%session, reason, "changes are not ready to capture");
+ self.fail(session, AttemptOutcome::NotReady, reason)
+ .await
+ .map(|()| CaptureOutcome::NotReady)
+ }
+ Err(ExtractError::Failed(report)) => {
+ tracing::warn!(%session, error = ?report, "extracting session changes failed");
+ self.fail(
+ session,
+ AttemptOutcome::Failed,
+ "Collecting the changes failed. Try again after the agent's next turn."
+ .to_owned(),
+ )
+ .await
+ .map(|()| CaptureOutcome::Failed)
+ }
+ };
+ self.notify(session).await;
+ outcome
+ }
+
+ async fn store(
+ &self,
+ row: &AgentSession,
+ extracted: super::model::ExtractedChangeset,
+ ) -> Result<CaptureOutcome> {
+ let session = row.id;
+ let parsed = patch::parse_git_patch(&extracted.patch);
+ let budgeted = patch::budget_patch(parsed, MAX_PATCH_BYTES, MAX_FILE_PATCH_BYTES);
+ let (additions, deletions) = patch::totals(&budgeted.files);
+ let id = ChangesetId::new();
+ let key = (!budgeted.patch.is_empty()).then(|| PatchBlobKey::for_changeset(session, id));
+ if let Some(key) = &key
+ && let Err(error) = self.inner.blobs.put_patch(key, &budgeted.patch).await
+ {
+ let _ = self
+ .fail(
+ session,
+ AttemptOutcome::Failed,
+ "Storing the changes failed.".to_owned(),
+ )
+ .await;
+ return Err(ChangesError::Storage(error));
+ }
+ let changeset = Changeset {
+ id,
+ session,
+ source: extracted.source,
+ range: extracted.range,
+ patch_bytes: budgeted.patch.len() as u64,
+ files: budgeted.files,
+ additions,
+ deletions,
+ truncated: budgeted.truncated || extracted.truncated,
+ captured_at: Utc::now(),
+ };
+ let superseded = match self
+ .inner
+ .repo
+ .record_changeset(&changeset, key.as_ref(), Utc::now())
+ .await
+ {
+ Ok(superseded) => superseded,
+ Err(error) => {
+ let _ = self
+ .fail(
+ session,
+ AttemptOutcome::Failed,
+ "Storing the changes failed.".to_owned(),
+ )
+ .await;
+ return Err(ChangesError::Storage(error));
+ }
+ };
+ // The old patch is unreachable now that the row points elsewhere;
+ // deleting it is tidiness, not correctness, so a failure only logs.
+ if let Some(old) = superseded
+ && key.as_ref() != Some(&old)
+ && let Err(error) = self.inner.blobs.delete_patch(&old).await
+ {
+ tracing::warn!(error = ?error, %session, key = %old, "could not delete a superseded patch");
+ }
+ tracing::info!(
+ %session,
+ files = changeset.files.len(),
+ additions,
+ deletions,
+ truncated = changeset.truncated,
+ source = %changeset.source,
+ "captured session changes"
+ );
+ Ok(CaptureOutcome::Captured(Box::new(changeset)))
+ }
+
+ async fn fail(
+ &self,
+ session: AgentSessionId,
+ outcome: AttemptOutcome,
+ reason: String,
+ ) -> Result<()> {
+ self.inner
+ .repo
+ .record_failure(session, outcome, Some(&reason), Utc::now())
+ .await
+ .map_err(ChangesError::Storage)
+ }
+
+ async fn notify(&self, session: AgentSessionId) {
+ if let Err(error) = self.inner.realtime.publish_changes_updated(session).await {
+ tracing::warn!(error = ?error, %session, "could not publish a changes update");
+ }
+ }
+}
+
+impl<Sessions, Extractor, Repo, Blobs, Realtime> AgentChanges
+ for AgentChangesService<Sessions, Extractor, Repo, Blobs, Realtime>
+where
+ Sessions: AgentSessionRepo,
+ Extractor: ChangesetExtractor,
+ Repo: ChangesetRepo,
+ Blobs: ChangesetBlobStore,
+ Realtime: AgentSessionRealtime + Send + Sync + 'static,
+{
+ async fn changes(
+ &self,
+ access: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<SessionChanges> {
+ self.read_changes(access).await
+ }
+
+ async fn patch(&self, access: &EntityAccessReceipt<ViewAccessLevel>) -> Result<String> {
+ self.read_patch(access).await
+ }
+
+ async fn request_capture(
+ &self,
+ access: &EntityAccessReceipt<EditAccessLevel>,
+ ) -> Result<SessionChanges> {
+ self.start_capture(access).await
+ }
+}
+
+/// The session a receipt is for. Anything else is a wiring bug: every route
+/// here resolves access against an agent session.
+fn session_of<T: RequiredPermission>(access: &EntityAccessReceipt<T>) -> Result<AgentSessionId> {
+ if access.entity().entity_type != EntityType::AgentSession {
+ return Err(ChangesError::Forbidden);
+ }
+ let id = Uuid::parse_str(&access.entity().entity_id).map_err(|_| ChangesError::Forbidden)?;
+ Ok(AgentSessionId::new_from_uuid(id))
+}
+
+/// Captures a session's changes each time one of its turns ends.
+///
+/// The observer runs on the session actor's task, so it only spawns; the
+/// capture itself - a provider round trip and two writes - happens elsewhere.
+pub struct CaptureOnTurnEnd<Service> {
+ service: Service,
+}
+
+impl<Service> CaptureOnTurnEnd<Service> {
+ /// Capture through `service` whenever a turn ends.
+ pub fn new(service: Service) -> Self {
+ Self { service }
+ }
+}
+
+impl<Sessions, Extractor, Repo, Blobs, Realtime> SessionTurnObserver
+ for CaptureOnTurnEnd<AgentChangesService<Sessions, Extractor, Repo, Blobs, Realtime>>
+where
+ Sessions: AgentSessionRepo,
+ Extractor: ChangesetExtractor,
+ Repo: ChangesetRepo,
+ Blobs: ChangesetBlobStore,
+ Realtime: AgentSessionRealtime + Send + Sync + 'static,
+{
+ fn signal(&self, id: AgentSessionId, signal: agent_fold::domain::model::TurnSignal) {
+ if matches!(
+ signal,
+ agent_fold::domain::model::TurnSignal::TurnEnded { .. }
+ ) {
+ self.service.capture_in_background(id);
+ }
+ }
+
+ fn session_stopped(&self, _id: AgentSessionId, _reason: StopReason) {}
+}
diff --git a/crates/agent_changes/src/domain/service/test.rs b/crates/agent_changes/src/domain/service/test.rs
new file mode 100644
index 0000000000..ddd0d00372
--- /dev/null
+++ b/crates/agent_changes/src/domain/service/test.rs
@@ -0,0 +1,251 @@
+use super::*;
+use crate::domain::model::{ChangesetRange, ChangesetSource, ExtractedChangeset, GitRef};
+use crate::testing::{MemoryBlobStore, MemoryChangesetRepo, ScriptedExtractor};
+use agent_session::testing::{InMemoryAgentSessionRepo, RecordingRealtime, test_agent_session};
+
+const SESSION: AgentSessionId = AgentSessionId::TEST_A;
+
+const PATCH: &str = "\
+diff --git a/src/lib.rs b/src/lib.rs
+index 1111111..2222222 100644
+--- a/src/lib.rs
++++ b/src/lib.rs
+@@ -1,2 +1,3 @@
+ fn main() {
++ run();
+ }
+";
+
+type TestService = AgentChangesService<
+ InMemoryAgentSessionRepo,
+ ScriptedExtractor,
+ MemoryChangesetRepo,
+ MemoryBlobStore,
+ RecordingRealtime,
+>;
+
+fn extracted(patch: &str) -> ExtractedChangeset {
+ ExtractedChangeset {
+ source: ChangesetSource::GithubPullRequest,
+ range: ChangesetRange {
+ repository: Some("https://github.com/example/example".to_owned()),
+ base: GitRef::named("main"),
+ head: GitRef::named("agent/work"),
+ },
+ patch: patch.to_owned(),
+ truncated: false,
+ }
+}
+
+fn service(extractor: ScriptedExtractor) -> (TestService, MemoryChangesetRepo, MemoryBlobStore) {
+ let sessions = InMemoryAgentSessionRepo::new();
+ sessions.insert_session(test_agent_session(SESSION));
+ let repo = MemoryChangesetRepo::new();
+ let blobs = MemoryBlobStore::new();
+ let service = AgentChangesService::new(
+ sessions,
+ extractor,
+ repo.clone(),
+ blobs.clone(),
+ RecordingRealtime::new(),
+ );
+ (service, repo, blobs)
+}
+
+fn view_access() -> EntityAccessReceipt<ViewAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &SESSION.as_uuid().to_string(),
+ EntityType::AgentSession,
+ )
+}
+
+fn edit_access() -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &SESSION.as_uuid().to_string(),
+ EntityType::AgentSession,
+ )
+}
+
+#[tokio::test]
+async fn a_capture_stores_the_patch_and_a_summary_read_from_it() {
+ let (service, _repo, blobs) = service(ScriptedExtractor::returning(extracted(PATCH)));
+
+ let outcome = service.capture(SESSION).await.unwrap();
+ let CaptureOutcome::Captured(changeset) = outcome else {
+ panic!("expected a capture, got {outcome:?}");
+ };
+ assert_eq!(changeset.files.len(), 1);
+ assert_eq!(changeset.files[0].path, "src/lib.rs");
+ assert_eq!((changeset.additions, changeset.deletions), (1, 0));
+ assert_eq!(changeset.range.head.name.as_deref(), Some("agent/work"));
+ assert!(changeset.has_patch());
+
+ let changes = service.changes(&view_access()).await.unwrap();
+ assert_eq!(changes.changeset.as_ref(), Some(changeset.as_ref()));
+ let attempt = changes.attempt.expect("an attempt was recorded");
+ assert_eq!(attempt.outcome, Some(AttemptOutcome::Captured));
+ assert!(!attempt.in_flight());
+
+ assert_eq!(service.patch(&view_access()).await.unwrap(), PATCH);
+ assert_eq!(
+ blobs.keys(),
+ vec![
+ PatchBlobKey::for_changeset(SESSION, changeset.id)
+ .as_str()
+ .to_owned()
+ ]
+ );
+}
+
+#[tokio::test]
+async fn a_new_capture_replaces_the_summary_and_drops_the_old_patch() {
+ let extractor = ScriptedExtractor::returning(extracted(PATCH));
+ let (service, _repo, blobs) = service(extractor.clone());
+ service.capture(SESSION).await.unwrap();
+ let first_key = blobs.keys();
+
+ extractor.set(extracted(&PATCH.replace("run();", "run_again();")));
+ let outcome = service.capture(SESSION).await.unwrap();
+ assert!(matches!(outcome, CaptureOutcome::Captured(_)));
+
+ let keys = blobs.keys();
+ assert_eq!(keys.len(), 1, "exactly one patch is kept");
+ assert_ne!(
+ keys, first_key,
+ "the patch lives under the new capture's key"
+ );
+ assert!(
+ service
+ .patch(&view_access())
+ .await
+ .unwrap()
+ .contains("run_again")
+ );
+}
+
+#[tokio::test]
+async fn an_empty_patch_is_a_changeset_with_nothing_in_it() {
+ let (service, _repo, blobs) = service(ScriptedExtractor::returning(extracted("")));
+ let CaptureOutcome::Captured(changeset) = service.capture(SESSION).await.unwrap() else {
+ panic!("expected a capture");
+ };
+ assert!(changeset.files.is_empty());
+ assert!(!changeset.has_patch());
+ assert!(
+ blobs.keys().is_empty(),
+ "nothing is stored for an empty diff"
+ );
+ assert!(matches!(
+ service.patch(&view_access()).await,
+ Err(ChangesError::NoChangeset)
+ ));
+}
+
+#[tokio::test]
+async fn an_unavailable_pull_request_keeps_the_previous_changeset() {
+ let extractor = ScriptedExtractor::returning(extracted(PATCH));
+ let (service, _repo, _blobs) = service(extractor.clone());
+ service.capture(SESSION).await.unwrap();
+
+ let not_ready = ScriptedExtractor::not_ready("GitHub could not return the pull request.");
+ let sessions = InMemoryAgentSessionRepo::new();
+ sessions.insert_session(test_agent_session(SESSION));
+ // Same stores, different extractor: the second service sees the first
+ // capture and fails to replace it.
+ let repo = service.inner.repo.clone();
+ let blobs = service.inner.blobs.clone();
+ let second =
+ AgentChangesService::new(sessions, not_ready, repo, blobs, RecordingRealtime::new());
+ assert_eq!(
+ second.capture(SESSION).await.unwrap(),
+ CaptureOutcome::NotReady
+ );
+ let changes = second.changes(&view_access()).await.unwrap();
+ assert!(changes.changeset.is_some(), "the earlier capture stays");
+ let attempt = changes.attempt.unwrap();
+ assert_eq!(attempt.outcome, Some(AttemptOutcome::NotReady));
+ assert_eq!(
+ attempt.error.as_deref(),
+ Some("GitHub could not return the pull request.")
+ );
+}
+
+#[tokio::test]
+async fn an_extractor_failure_is_recorded_with_a_readable_reason() {
+ let (service, _repo, _blobs) = service(ScriptedExtractor::failing("boom"));
+ assert_eq!(
+ service.capture(SESSION).await.unwrap(),
+ CaptureOutcome::Failed
+ );
+ let attempt = service
+ .changes(&view_access())
+ .await
+ .unwrap()
+ .attempt
+ .unwrap();
+ assert_eq!(attempt.outcome, Some(AttemptOutcome::Failed));
+ assert!(
+ !attempt.error.unwrap().contains("boom"),
+ "internal detail stays out"
+ );
+}
+
+#[tokio::test]
+async fn a_request_during_a_capture_becomes_one_rerun() {
+ let extractor = ScriptedExtractor::returning(extracted(PATCH));
+ let (service, _repo, _blobs) = service(extractor.clone());
+ assert!(service.claim(SESSION), "the slot is free");
+ // Two requests while it runs collapse into a single rerun.
+ assert_eq!(
+ service.capture(SESSION).await.unwrap(),
+ CaptureOutcome::Queued
+ );
+ assert_eq!(
+ service.capture(SESSION).await.unwrap(),
+ CaptureOutcome::Queued
+ );
+ assert!(service.release(SESSION), "a rerun was asked for");
+ assert!(!service.release(SESSION), "and only one");
+ assert_eq!(
+ extractor.calls(),
+ 0,
+ "queued requests never call the extractor"
+ );
+
+ let outcome = service.capture(SESSION).await.unwrap();
+ assert!(matches!(outcome, CaptureOutcome::Captured(_)));
+ assert_eq!(extractor.calls(), 1);
+}
+
+#[tokio::test]
+async fn requesting_a_capture_answers_with_the_running_attempt() {
+ let (service, _repo, _blobs) = service(ScriptedExtractor::returning(extracted(PATCH)));
+ let changes = service.request_capture(&edit_access()).await.unwrap();
+ assert!(changes.attempt.is_some(), "the attempt is visible at once");
+ // Let the background capture finish before the runtime goes away.
+ tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ loop {
+ let changes = service.changes(&view_access()).await.unwrap();
+ if changes.changeset.is_some() {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the background capture completes");
+}
+
+#[tokio::test]
+async fn a_receipt_for_another_entity_type_is_refused() {
+ let (service, _repo, _blobs) = service(ScriptedExtractor::returning(extracted(PATCH)));
+ let access: EntityAccessReceipt<ViewAccessLevel> =
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &SESSION.as_uuid().to_string(),
+ EntityType::Document,
+ );
+ assert!(matches!(
+ service.changes(&access).await,
+ Err(ChangesError::Forbidden)
+ ));
+}
diff --git a/crates/agent_changes/src/inbound/axum_router.rs b/crates/agent_changes/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..96c8abeca4
--- /dev/null
+++ b/crates/agent_changes/src/inbound/axum_router.rs
@@ -0,0 +1,476 @@
+//! Axum routes serving a session's changes, mounted under `/agent-sessions`.
+//!
+//! Every route authenticates its caller and resolves their grant on the
+//! session with [`AgentSessionAccessLevelExtractor`] before the handler body
+//! runs: reading the summary or the patch needs `View`; asking for a fresh
+//! capture needs `Edit`, the same bar as prompting
+//! the agent. Handlers map DTOs to the domain and call one service method;
+//! the receipt travels into the domain so the service can prove the check
+//! happened.
+
+use std::sync::Arc;
+
+use axum::{
+ Json, Router,
+ extract::{FromRef, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::{get, post},
+};
+use chrono::{DateTime, Utc};
+use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;
+use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
+use macro_uuid::Uuid;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
+use crate::domain::error::ChangesError;
+use crate::domain::model::{
+ AttemptOutcome, CaptureAttempt, ChangedFile, Changeset, ChangesetSource, FileChangeKind,
+ GitRef, SessionChanges,
+};
+use crate::domain::service::AgentChanges;
+
+#[cfg(test)]
+mod test;
+
+/// Shared state for the changes router: the service plus what the access
+/// extractors resolve grants and identity through.
+pub struct AgentChangesRouterState<Changes, Access, Auth> {
+ service: Arc<Changes>,
+ entity_access: Arc<Access>,
+ authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<Changes, Access, Auth> AgentChangesRouterState<Changes, Access, Auth> {
+ /// Build the state from the service and the extractors' dependencies.
+ pub fn new(
+ service: Changes,
+ entity_access: Arc<Access>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
+ Self {
+ service: Arc::new(service),
+ entity_access,
+ authorization_state,
+ }
+ }
+}
+
+// Manual Clone so `Changes` need not be Clone (it is behind an Arc).
+impl<Changes, Access, Auth> Clone for AgentChangesRouterState<Changes, Access, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ service: Arc::clone(&self.service),
+ entity_access: Arc::clone(&self.entity_access),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<Changes, Access, Auth> FromRef<AgentChangesRouterState<Changes, Access, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &AgentChangesRouterState<Changes, Access, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+impl<Changes, Access, Auth> FromRef<AgentChangesRouterState<Changes, Access, Auth>>
+ for Arc<Access>
+{
+ fn from_ref(state: &AgentChangesRouterState<Changes, Access, Auth>) -> Self {
+ Arc::clone(&state.entity_access)
+ }
+}
+
+/// Build the changes router. Mount it under the session prefix the
+/// composition root chooses, e.g. `/agent-sessions`, beside the session
+/// routers.
+pub fn agent_changes_router<Changes, Access, Auth, S>(
+ state: AgentChangesRouterState<Changes, Access, Auth>,
+) -> Router<S>
+where
+ Changes: AgentChanges,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/{session_id}/changes",
+ get(get_agent_session_changes_handler::<Changes, Access, Auth>),
+ )
+ .route(
+ "/{session_id}/changes/patch",
+ get(get_agent_session_changes_patch_handler::<Changes, Access, Auth>),
+ )
+ .route(
+ "/{session_id}/changes/refresh",
+ post(refresh_agent_session_changes_handler::<Changes, Access, Auth>),
+ )
+ .with_state(state)
+}
+
+/// What happened to a file, on the wire.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum FileChangeKindDto {
+ /// The file did not exist before.
+ Added,
+ /// The file exists on both sides with different contents.
+ Modified,
+ /// The file no longer exists.
+ Deleted,
+ /// The file moved; `previousPath` says from where.
+ Renamed,
+}
+
+impl From<FileChangeKind> for FileChangeKindDto {
+ fn from(kind: FileChangeKind) -> Self {
+ match kind {
+ FileChangeKind::Added => Self::Added,
+ FileChangeKind::Modified => Self::Modified,
+ FileChangeKind::Deleted => Self::Deleted,
+ FileChangeKind::Renamed => Self::Renamed,
+ }
+ }
+}
+
+/// The source of the captured diff, on the wire.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ChangesetSourceDto {
+ /// The diff of the session's linked GitHub pull request.
+ GithubPullRequest,
+}
+
+impl From<ChangesetSource> for ChangesetSourceDto {
+ fn from(source: ChangesetSource) -> Self {
+ match source {
+ ChangesetSource::GithubPullRequest => Self::GithubPullRequest,
+ }
+ }
+}
+
+/// How the latest capture attempt ended, on the wire.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum CaptureOutcomeDto {
+ /// A changeset (possibly empty) was stored.
+ Captured,
+ /// The pull request was not available; `error` says why.
+ NotReady,
+ /// The extractor or storage failed; `error` says what a user can do.
+ Failed,
+}
+
+impl From<AttemptOutcome> for CaptureOutcomeDto {
+ fn from(outcome: AttemptOutcome) -> Self {
+ match outcome {
+ AttemptOutcome::Captured => Self::Captured,
+ AttemptOutcome::NotReady => Self::NotReady,
+ AttemptOutcome::Failed => Self::Failed,
+ }
+ }
+}
+
+/// One changed file.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ChangedFileDto {
+ /// The file's path after the change, or before it for a deletion.
+ pub path: String,
+ /// Where a renamed file came from.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub previous_path: Option<String>,
+ /// What happened to the file.
+ pub kind: FileChangeKindDto,
+ /// Lines added.
+ pub additions: u32,
+ /// Lines removed.
+ pub deletions: u32,
+ /// The diff carries no text for this file.
+ pub binary: bool,
+ /// The file's hunks were left out of the patch to fit the size budget.
+ pub patch_omitted: bool,
+}
+
+impl From<ChangedFile> for ChangedFileDto {
+ fn from(file: ChangedFile) -> Self {
+ Self {
+ path: file.path,
+ previous_path: file.previous_path,
+ kind: file.kind.into(),
+ additions: file.additions,
+ deletions: file.deletions,
+ binary: file.binary,
+ patch_omitted: file.patch_omitted,
+ }
+ }
+}
+
+/// One end of the compared range.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct GitRefDto {
+ /// The branch name, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ /// The commit, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub sha: Option<String>,
+}
+
+impl From<GitRef> for GitRefDto {
+ fn from(git_ref: GitRef) -> Self {
+ Self {
+ name: git_ref.name,
+ sha: git_ref.sha,
+ }
+ }
+}
+
+/// One capture of a session's changes.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ChangesetDto {
+ /// The capture's id; changes with every capture.
+ pub id: Uuid,
+ /// Where the diff was read from.
+ pub source: ChangesetSourceDto,
+ /// `https://github.com/owner/name`, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repository: Option<String>,
+ /// The side the work started from.
+ pub base: GitRefDto,
+ /// The side carrying the work.
+ pub head: GitRefDto,
+ /// Every changed file, in patch order.
+ pub files: Vec<ChangedFileDto>,
+ /// Lines added across all files.
+ pub additions: u32,
+ /// Lines removed across all files.
+ pub deletions: u32,
+ /// Size of the patch `GET .../changes/patch` serves; zero when nothing
+ /// changed.
+ pub patch_bytes: u64,
+ /// Some files' hunks were left out of the patch.
+ pub truncated: bool,
+ /// When the diff was taken.
+ pub captured_at: DateTime<Utc>,
+}
+
+impl From<Changeset> for ChangesetDto {
+ fn from(changeset: Changeset) -> Self {
+ Self {
+ id: changeset.id.as_uuid(),
+ source: changeset.source.into(),
+ repository: changeset.range.repository,
+ base: changeset.range.base.into(),
+ head: changeset.range.head.into(),
+ files: changeset.files.into_iter().map(Into::into).collect(),
+ additions: changeset.additions,
+ deletions: changeset.deletions,
+ patch_bytes: changeset.patch_bytes,
+ truncated: changeset.truncated,
+ captured_at: changeset.captured_at,
+ }
+ }
+}
+
+/// The latest capture attempt.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureAttemptDto {
+ /// When it started.
+ pub started_at: DateTime<Utc>,
+ /// When it ended; absent while it runs.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub finished_at: Option<DateTime<Utc>>,
+ /// How it ended; absent while it runs.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub outcome: Option<CaptureOutcomeDto>,
+ /// Why it did not capture, in a sentence the user can read.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+impl From<CaptureAttempt> for CaptureAttemptDto {
+ fn from(attempt: CaptureAttempt) -> Self {
+ Self {
+ started_at: attempt.started_at,
+ finished_at: attempt.finished_at,
+ outcome: attempt.outcome.map(Into::into),
+ error: attempt.error,
+ }
+ }
+}
+
+/// Response body for `GET /agent-sessions/{session_id}/changes`.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentSessionChangesResponse {
+ /// The latest capture, if any succeeded.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub changeset: Option<ChangesetDto>,
+ /// The latest attempt, if any was made.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub attempt: Option<CaptureAttemptDto>,
+ /// A capture is running right now.
+ pub capturing: bool,
+}
+
+impl From<SessionChanges> for AgentSessionChangesResponse {
+ fn from(changes: SessionChanges) -> Self {
+ let capturing = changes
+ .attempt
+ .as_ref()
+ .is_some_and(CaptureAttempt::in_flight);
+ Self {
+ changeset: changes.changeset.map(Into::into),
+ attempt: changes.attempt.map(Into::into),
+ capturing,
+ }
+ }
+}
+
+/// Response body for `GET /agent-sessions/{session_id}/changes/patch`.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentSessionChangesPatchResponse {
+ /// The git-style unified diff of the current changeset.
+ pub patch: String,
+}
+
+/// How the domain's refusals and failures answer on the wire.
+#[derive(Debug)]
+pub enum AgentChangesApiError {
+ /// The domain rejected or failed the operation.
+ Domain(ChangesError),
+}
+
+impl From<ChangesError> for AgentChangesApiError {
+ fn from(error: ChangesError) -> Self {
+ Self::Domain(error)
+ }
+}
+
+impl IntoResponse for AgentChangesApiError {
+ fn into_response(self) -> Response {
+ match self {
+ Self::Domain(ChangesError::Forbidden) => {
+ (StatusCode::FORBIDDEN, "forbidden").into_response()
+ }
+ Self::Domain(error @ (ChangesError::NoChangeset | ChangesError::PatchMissing)) => {
+ (StatusCode::NOT_FOUND, error.to_string()).into_response()
+ }
+ Self::Domain(ChangesError::Session(
+ agent_session::domain::error::AgentSessionError::Forbidden,
+ )) => (StatusCode::FORBIDDEN, "forbidden").into_response(),
+ Self::Domain(error) => {
+ tracing::error!(error = ?error, "agent session changes request failed");
+ (StatusCode::INTERNAL_SERVER_ERROR, "internal error").into_response()
+ }
+ }
+ }
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-sessions/{session_id}/changes",
+ tag = "agent-sessions",
+ operation_id = "get_agent_session_changes",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 200, body = AgentSessionChangesResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// The latest captured changes of an agent session: the changed files with
+/// statuses and line counts, and how the latest capture attempt went.
+#[tracing::instrument(skip_all, fields(agent.session.id = %access.entity_access_receipt.entity().entity_id), err(Debug))]
+pub async fn get_agent_session_changes_handler<
+ Changes: AgentChanges,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,
+ State(state): State<AgentChangesRouterState<Changes, Access, Auth>>,
+) -> Result<Json<AgentSessionChangesResponse>, AgentChangesApiError> {
+ let changes = state.service.changes(&access.entity_access_receipt).await?;
+ Ok(Json(changes.into()))
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-sessions/{session_id}/changes/patch",
+ tag = "agent-sessions",
+ operation_id = "get_agent_session_changes_patch",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 200, body = AgentSessionChangesPatchResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 404, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// The unified diff behind the session's latest changeset.
+#[tracing::instrument(skip_all, fields(agent.session.id = %access.entity_access_receipt.entity().entity_id), err(Debug))]
+pub async fn get_agent_session_changes_patch_handler<
+ Changes: AgentChanges,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,
+ State(state): State<AgentChangesRouterState<Changes, Access, Auth>>,
+) -> Result<Json<AgentSessionChangesPatchResponse>, AgentChangesApiError> {
+ let patch = state.service.patch(&access.entity_access_receipt).await?;
+ Ok(Json(AgentSessionChangesPatchResponse { patch }))
+}
+
+#[utoipa::path(
+ post,
+ path = "/agent-sessions/{session_id}/changes/refresh",
+ tag = "agent-sessions",
+ operation_id = "refresh_agent_session_changes",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 202, body = AgentSessionChangesResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Capture the session's changes again now. Answers at once with the state
+/// as it stands; the capture runs on and viewers are told when it lands.
+#[tracing::instrument(skip_all, fields(agent.session.id = %access.entity_access_receipt.entity().entity_id), err(Debug))]
+pub async fn refresh_agent_session_changes_handler<
+ Changes: AgentChanges,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: AgentSessionAccessLevelExtractor<EditAccessLevel, Access, Auth>,
+ State(state): State<AgentChangesRouterState<Changes, Access, Auth>>,
+) -> Result<(StatusCode, Json<AgentSessionChangesResponse>), AgentChangesApiError> {
+ let changes = state
+ .service
+ .request_capture(&access.entity_access_receipt)
+ .await?;
+ Ok((StatusCode::ACCEPTED, Json(changes.into())))
+}
diff --git a/crates/agent_changes/src/inbound/axum_router/test.rs b/crates/agent_changes/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..554cd9a724
--- /dev/null
+++ b/crates/agent_changes/src/inbound/axum_router/test.rs
@@ -0,0 +1,73 @@
+use super::*;
+use crate::domain::model::{ChangesetId, ChangesetRange};
+
+#[test]
+fn the_changes_response_says_when_a_capture_is_running() {
+ let started = Utc::now();
+ let running: AgentSessionChangesResponse = SessionChanges {
+ changeset: None,
+ attempt: Some(CaptureAttempt {
+ started_at: started,
+ finished_at: None,
+ outcome: None,
+ error: None,
+ }),
+ }
+ .into();
+ assert!(running.capturing);
+ assert!(running.changeset.is_none());
+
+ let done: AgentSessionChangesResponse = SessionChanges {
+ changeset: Some(Changeset {
+ id: ChangesetId::new(),
+ session: crate::domain::model::AgentSessionId::TEST_A,
+ source: ChangesetSource::GithubPullRequest,
+ range: ChangesetRange::default(),
+ files: vec![ChangedFile {
+ path: "a.rs".to_owned(),
+ previous_path: Some("b.rs".to_owned()),
+ kind: FileChangeKind::Renamed,
+ additions: 1,
+ deletions: 2,
+ binary: false,
+ patch_omitted: true,
+ }],
+ additions: 1,
+ deletions: 2,
+ patch_bytes: 10,
+ truncated: true,
+ captured_at: started,
+ }),
+ attempt: Some(CaptureAttempt {
+ started_at: started,
+ finished_at: Some(started),
+ outcome: Some(AttemptOutcome::Captured),
+ error: None,
+ }),
+ }
+ .into();
+ assert!(!done.capturing);
+ let changeset = done.changeset.unwrap();
+ assert_eq!(changeset.files[0].kind, FileChangeKindDto::Renamed);
+ assert!(changeset.files[0].patch_omitted);
+ assert_eq!(
+ done.attempt.unwrap().outcome,
+ Some(CaptureOutcomeDto::Captured)
+ );
+
+ let json = serde_json::to_value(&changeset).unwrap();
+ assert_eq!(json["files"][0]["previousPath"], "b.rs");
+ assert_eq!(json["source"], "github_pull_request");
+ assert_eq!(json["files"][0]["kind"], "renamed");
+}
+
+#[test]
+fn errors_answer_with_the_status_the_pane_branches_on() {
+ let forbidden = AgentChangesApiError::from(ChangesError::Forbidden).into_response();
+ assert_eq!(forbidden.status(), StatusCode::FORBIDDEN);
+ let missing = AgentChangesApiError::from(ChangesError::NoChangeset).into_response();
+ assert_eq!(missing.status(), StatusCode::NOT_FOUND);
+ let storage = AgentChangesApiError::from(ChangesError::Storage(rootcause::report!("down")))
+ .into_response();
+ assert_eq!(storage.status(), StatusCode::INTERNAL_SERVER_ERROR);
+}
diff --git a/crates/agent_changes/src/inbound/mod.rs b/crates/agent_changes/src/inbound/mod.rs
new file mode 100644
index 0000000000..c0c1b476e0
--- /dev/null
+++ b/crates/agent_changes/src/inbound/mod.rs
@@ -0,0 +1,5 @@
+//! Inbound transport adapters for the changes service.
+
+pub mod axum_router;
+
+pub use axum_router::{AgentChangesRouterState, agent_changes_router};
diff --git a/crates/agent_changes/src/lib.rs b/crates/agent_changes/src/lib.rs
new file mode 100644
index 0000000000..cbe3c13878
--- /dev/null
+++ b/crates/agent_changes/src/lib.rs
@@ -0,0 +1,20 @@
+#![deny(missing_docs)]
+//! Review changes from the GitHub pull request linked to an agent session.
+//!
+//! The domain service reads the PR through a port, derives per-file facts,
+//! stores the patch in S3 and the summary in Postgres, and notifies viewers.
+//! Capture runs after each turn and on demand, regardless of the runtime.
+//! HTTP handlers pass session access receipts to the domain service. GitHub
+//! repository access is checked by the owning GitHub token service.
+
+/// Domain models, the patch reader, ports, and the changes service.
+pub mod domain;
+/// Inbound HTTP adapter.
+#[cfg(feature = "inbound")]
+pub mod inbound;
+/// Adapters implementing the domain ports for external systems.
+#[cfg(feature = "outbound")]
+pub mod outbound;
+/// In-memory port implementations for tests.
+#[cfg(any(test, feature = "test-utils"))]
+pub mod testing;
diff --git a/crates/agent_changes/src/outbound/github_pull_request.rs b/crates/agent_changes/src/outbound/github_pull_request.rs
new file mode 100644
index 0000000000..ddaa004905
--- /dev/null
+++ b/crates/agent_changes/src/outbound/github_pull_request.rs
@@ -0,0 +1,150 @@
+//! Read GitHub pull request metadata and its diff with a repository-scoped App token.
+
+use std::time::Duration;
+
+use github::domain::models::GithubError;
+use github::domain::ports::{GithubSyncClient, GithubSyncRepo};
+use github::domain::service::InstallationTokenService;
+use macro_user_id::user_id::MacroUserIdStr;
+use reqwest::StatusCode;
+use serde::Deserialize;
+
+use crate::domain::error::CompareError;
+use crate::domain::model::{ChangesetRange, GitRef, PullRequestRef};
+use crate::domain::ports::{PullRequestDiff, PullRequestDiffReader};
+
+#[cfg(test)]
+mod test;
+
+const GITHUB_API_BASE_URL: &str = "https://api.github.com";
+const READ_PERMISSIONS: &[(&str, &str)] = &[("pull_requests", "read")];
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
+
+/// GitHub REST adapter for a linked pull request's diff.
+pub struct GithubPullRequestDiff<Installations, Client> {
+ tokens: InstallationTokenService<Installations, Client>,
+ http: reqwest::Client,
+ api_base_url: String,
+}
+
+impl<Installations: GithubSyncRepo, Client: GithubSyncClient>
+ GithubPullRequestDiff<Installations, Client>
+{
+ /// Mint repository-scoped tokens through the owning GitHub domain service.
+ pub fn new(tokens: InstallationTokenService<Installations, Client>) -> Self {
+ Self::with_api_base_url(tokens, GITHUB_API_BASE_URL.to_owned())
+ }
+
+ /// Use another API origin for adapter tests.
+ pub fn with_api_base_url(
+ tokens: InstallationTokenService<Installations, Client>,
+ api_base_url: String,
+ ) -> Self {
+ Self {
+ tokens,
+ http: reqwest::Client::builder()
+ .timeout(REQUEST_TIMEOUT)
+ .build()
+ .expect("GitHub HTTP client"),
+ api_base_url,
+ }
+ }
+
+ async fn get(&self, url: &str, token: &str, accept: &str) -> Result<String, CompareError> {
+ let response = self
+ .http
+ .get(url)
+ .bearer_auth(token)
+ .header("Accept", accept)
+ .header("User-Agent", "Macro-Agent-Changes")
+ .header("X-GitHub-Api-Version", "2022-11-28")
+ .send()
+ .await
+ .map_err(|error| CompareError::Other(rootcause::report!(error).into()))?;
+ let status = response.status();
+ let body = response
+ .text()
+ .await
+ .map_err(|error| CompareError::Other(rootcause::report!(error).into()))?;
+ if !status.is_success() {
+ return Err(status_error(status, &body));
+ }
+ Ok(body)
+ }
+}
+
+#[derive(Deserialize)]
+struct PullRequestMetadata {
+ base: PullRequestBranch,
+ head: PullRequestBranch,
+}
+
+#[derive(Deserialize)]
+struct PullRequestBranch {
+ #[serde(rename = "ref")]
+ name: String,
+ sha: String,
+}
+
+impl From<PullRequestBranch> for GitRef {
+ fn from(branch: PullRequestBranch) -> Self {
+ Self {
+ name: Some(branch.name),
+ sha: Some(branch.sha),
+ }
+ }
+}
+
+impl<Installations: GithubSyncRepo, Client: GithubSyncClient> PullRequestDiffReader
+ for GithubPullRequestDiff<Installations, Client>
+{
+ #[tracing::instrument(skip_all, err)]
+ async fn read(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ pull_request: &PullRequestRef,
+ ) -> Result<PullRequestDiff, CompareError> {
+ let repository = &pull_request.repository;
+ let token = self
+ .tokens
+ .for_repository(user, &repository.owner, &repository.name, READ_PERMISSIONS)
+ .await
+ .map_err(|error| match error {
+ GithubError::RepositoryUnavailable => CompareError::Unavailable,
+ other => CompareError::Other(rootcause::report!("github token: {other}")),
+ })?;
+ let url = format!(
+ "{}/repos/{}/{}/pulls/{}",
+ self.api_base_url, repository.owner, repository.name, pull_request.number
+ );
+ let metadata = self
+ .get(&url, &token.token, "application/vnd.github+json")
+ .await?;
+ let metadata: PullRequestMetadata = serde_json::from_str(&metadata).map_err(|error| {
+ CompareError::Other(rootcause::report!("pull request metadata: {error}"))
+ })?;
+ let patch = self
+ .get(&url, &token.token, "application/vnd.github.diff")
+ .await?;
+ Ok(PullRequestDiff {
+ patch,
+ range: ChangesetRange {
+ repository: Some(repository.https_url()),
+ base: metadata.base.into(),
+ head: metadata.head.into(),
+ },
+ })
+ }
+}
+
+fn status_error(status: StatusCode, body: &str) -> CompareError {
+ match status {
+ StatusCode::NOT_FOUND => CompareError::NotFound,
+ StatusCode::NOT_ACCEPTABLE => CompareError::TooLarge,
+ StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => CompareError::Unavailable,
+ other => CompareError::Other(rootcause::report!(
+ "github answered {other}: {}",
+ body.chars().take(300).collect::<String>()
+ )),
+ }
+}
diff --git a/crates/agent_changes/src/outbound/github_pull_request/test.rs b/crates/agent_changes/src/outbound/github_pull_request/test.rs
new file mode 100644
index 0000000000..cc3dc5a73e
--- /dev/null
+++ b/crates/agent_changes/src/outbound/github_pull_request/test.rs
@@ -0,0 +1,39 @@
+use super::*;
+
+#[test]
+fn metadata_uses_the_prs_actual_base_and_head_including_a_fork() {
+ let metadata: PullRequestMetadata = serde_json::from_value(serde_json::json!({
+ "base": { "ref": "release/v2", "sha": "base-sha", "repo": { "full_name": "upstream/repo" } },
+ "head": { "ref": "fix", "sha": "head-sha", "repo": { "full_name": "contributor/repo" } }
+ })).unwrap();
+ let base: GitRef = metadata.base.into();
+ let head: GitRef = metadata.head.into();
+ assert_eq!(base.name.as_deref(), Some("release/v2"));
+ assert_eq!(base.sha.as_deref(), Some("base-sha"));
+ assert_eq!(head.name.as_deref(), Some("fix"));
+ assert_eq!(head.sha.as_deref(), Some("head-sha"));
+}
+
+#[test]
+fn inaccessible_or_oversized_diffs_map_to_unavailable_states() {
+ assert!(matches!(
+ status_error(StatusCode::NOT_FOUND, ""),
+ CompareError::NotFound
+ ));
+ assert!(matches!(
+ status_error(StatusCode::FORBIDDEN, ""),
+ CompareError::Unavailable
+ ));
+ assert!(matches!(
+ status_error(StatusCode::UNAUTHORIZED, ""),
+ CompareError::Unavailable
+ ));
+ assert!(matches!(
+ status_error(StatusCode::NOT_ACCEPTABLE, ""),
+ CompareError::TooLarge
+ ));
+ assert!(matches!(
+ status_error(StatusCode::BAD_GATEWAY, ""),
+ CompareError::Other(_)
+ ));
+}
diff --git a/crates/agent_changes/src/outbound/mod.rs b/crates/agent_changes/src/outbound/mod.rs
new file mode 100644
index 0000000000..6a38f5b7a3
--- /dev/null
+++ b/crates/agent_changes/src/outbound/mod.rs
@@ -0,0 +1,8 @@
+//! Adapters implementing the changes ports for external systems.
+
+/// Reading a linked pull request on GitHub.
+pub mod github_pull_request;
+/// The summary row in Postgres.
+pub mod postgres;
+/// Patch blobs in S3.
+pub mod s3;
diff --git a/crates/agent_changes/src/outbound/postgres.rs b/crates/agent_changes/src/outbound/postgres.rs
new file mode 100644
index 0000000000..f5fbc1dada
--- /dev/null
+++ b/crates/agent_changes/src/outbound/postgres.rs
@@ -0,0 +1,271 @@
+//! The summary row in Postgres: `agent_session_changes`, one per session.
+
+use agent_session::domain::model::AgentSessionId;
+use chrono::{DateTime, Utc};
+use macro_uuid::Uuid;
+use sqlx::PgPool;
+
+use crate::domain::model::{
+ AttemptOutcome, CaptureAttempt, ChangedFile, Changeset, ChangesetId, ChangesetRange,
+ ChangesetSource, GitRef, SessionChanges,
+};
+use crate::domain::ports::{ChangesetRepo, PatchBlobKey};
+
+#[cfg(test)]
+mod test;
+
+/// Postgres-backed [`ChangesetRepo`].
+#[derive(Clone)]
+pub struct PgChangesetRepo {
+ pool: PgPool,
+}
+
+impl PgChangesetRepo {
+ /// Read and write summaries through `pool`.
+ #[must_use]
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+/// The row as stored. Kept apart from the domain types so a column rename
+/// touches one mapping.
+struct ChangesRow {
+ changeset_id: Option<Uuid>,
+ source: Option<String>,
+ repository: Option<String>,
+ base_ref: Option<String>,
+ base_sha: Option<String>,
+ head_ref: Option<String>,
+ head_sha: Option<String>,
+ files: serde_json::Value,
+ additions: i32,
+ deletions: i32,
+ patch_bytes: i64,
+ truncated: bool,
+ captured_at: Option<DateTime<Utc>>,
+ attempt_started_at: DateTime<Utc>,
+ attempt_finished_at: Option<DateTime<Utc>>,
+ attempt_outcome: Option<String>,
+ attempt_error: Option<String>,
+}
+
+impl ChangesRow {
+ fn into_changes(self, session: AgentSessionId) -> Result<SessionChanges, rootcause::Report> {
+ let attempt = Some(CaptureAttempt {
+ started_at: self.attempt_started_at,
+ finished_at: self.attempt_finished_at,
+ outcome: self
+ .attempt_outcome
+ .as_deref()
+ .map(str::parse::<AttemptOutcome>)
+ .transpose()
+ .map_err(|error| rootcause::report!("stored attempt outcome: {error}"))?,
+ error: self.attempt_error,
+ });
+ let changeset = match (self.changeset_id, self.source, self.captured_at) {
+ (Some(id), Some(source), Some(captured_at)) => {
+ let files: Vec<ChangedFile> = serde_json::from_value(self.files)
+ .map_err(|error| rootcause::report!("stored changed files: {error}"))?;
+ Some(Changeset {
+ id: ChangesetId::from_uuid(id),
+ session,
+ source: source
+ .parse::<ChangesetSource>()
+ .map_err(|error| rootcause::report!("stored changeset source: {error}"))?,
+ range: ChangesetRange {
+ repository: self.repository,
+ base: GitRef {
+ name: self.base_ref,
+ sha: self.base_sha,
+ },
+ head: GitRef {
+ name: self.head_ref,
+ sha: self.head_sha,
+ },
+ },
+ files,
+ additions: u32::try_from(self.additions).unwrap_or(u32::MAX),
+ deletions: u32::try_from(self.deletions).unwrap_or(u32::MAX),
+ patch_bytes: u64::try_from(self.patch_bytes).unwrap_or(0),
+ truncated: self.truncated,
+ captured_at,
+ })
+ }
+ _ => None,
+ };
+ Ok(SessionChanges { changeset, attempt })
+ }
+}
+
+impl ChangesetRepo for PgChangesetRepo {
+ #[tracing::instrument(skip(self), err, fields(agent.session.id = %session))]
+ async fn begin_attempt(
+ &self,
+ session: AgentSessionId,
+ started_at: DateTime<Utc>,
+ ) -> Result<(), rootcause::Report> {
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_changes (agent_session_id, attempt_started_at)
+ VALUES ($1, $2)
+ ON CONFLICT (agent_session_id) DO UPDATE SET
+ attempt_started_at = EXCLUDED.attempt_started_at,
+ attempt_finished_at = NULL,
+ attempt_outcome = NULL,
+ attempt_error = NULL,
+ updated_at = now()
+ "#,
+ session.as_uuid(),
+ started_at,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ Ok(())
+ }
+
+ #[tracing::instrument(
+ skip(self, changeset, patch_key),
+ err,
+ fields(agent.session.id = %changeset.session, changeset.id = %changeset.id)
+ )]
+ async fn record_changeset(
+ &self,
+ changeset: &Changeset,
+ patch_key: Option<&PatchBlobKey>,
+ finished_at: DateTime<Utc>,
+ ) -> Result<Option<PatchBlobKey>, rootcause::Report> {
+ let files = serde_json::to_value(&changeset.files)
+ .map_err(|error| rootcause::report!("serialize changed files: {error}"))?;
+ // The CTE reads the row as it was before this statement, which is
+ // what makes "the key this capture superseded" one round trip.
+ let superseded = sqlx::query_scalar!(
+ r#"
+ WITH previous AS (
+ SELECT patch_blob_key FROM agent_session_changes WHERE agent_session_id = $1
+ )
+ INSERT INTO agent_session_changes (
+ agent_session_id, changeset_id, source, repository,
+ base_ref, base_sha, head_ref, head_sha,
+ files, additions, deletions, patch_blob_key, patch_bytes, truncated,
+ captured_at, attempt_started_at, attempt_finished_at, attempt_outcome, attempt_error
+ )
+ VALUES (
+ $1, $2, $3, $4,
+ $5, $6, $7, $8,
+ $9, $10, $11, $12, $13, $14,
+ $15, $16, $16, 'captured', NULL
+ )
+ ON CONFLICT (agent_session_id) DO UPDATE SET
+ changeset_id = EXCLUDED.changeset_id,
+ source = EXCLUDED.source,
+ repository = EXCLUDED.repository,
+ base_ref = EXCLUDED.base_ref,
+ base_sha = EXCLUDED.base_sha,
+ head_ref = EXCLUDED.head_ref,
+ head_sha = EXCLUDED.head_sha,
+ files = EXCLUDED.files,
+ additions = EXCLUDED.additions,
+ deletions = EXCLUDED.deletions,
+ patch_blob_key = EXCLUDED.patch_blob_key,
+ patch_bytes = EXCLUDED.patch_bytes,
+ truncated = EXCLUDED.truncated,
+ captured_at = EXCLUDED.captured_at,
+ attempt_finished_at = EXCLUDED.attempt_finished_at,
+ attempt_outcome = 'captured',
+ attempt_error = NULL,
+ updated_at = now()
+ RETURNING (SELECT patch_blob_key FROM previous) AS "superseded?"
+ "#,
+ changeset.session.as_uuid(),
+ changeset.id.as_uuid(),
+ changeset.source.to_string(),
+ changeset.range.repository.as_deref(),
+ changeset.range.base.name.as_deref(),
+ changeset.range.base.sha.as_deref(),
+ changeset.range.head.name.as_deref(),
+ changeset.range.head.sha.as_deref(),
+ files,
+ i32::try_from(changeset.additions).unwrap_or(i32::MAX),
+ i32::try_from(changeset.deletions).unwrap_or(i32::MAX),
+ patch_key.map(PatchBlobKey::as_str),
+ i64::try_from(changeset.patch_bytes).unwrap_or(i64::MAX),
+ changeset.truncated,
+ changeset.captured_at,
+ finished_at,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ Ok(superseded.map(PatchBlobKey::from_stored))
+ }
+
+ #[tracing::instrument(skip(self, error), err, fields(agent.session.id = %session, %outcome))]
+ async fn record_failure(
+ &self,
+ session: AgentSessionId,
+ outcome: AttemptOutcome,
+ error: Option<&str>,
+ finished_at: DateTime<Utc>,
+ ) -> Result<(), rootcause::Report> {
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session_changes (
+ agent_session_id, attempt_started_at, attempt_finished_at, attempt_outcome, attempt_error
+ )
+ VALUES ($1, $4, $4, $2, $3)
+ ON CONFLICT (agent_session_id) DO UPDATE SET
+ attempt_finished_at = EXCLUDED.attempt_finished_at,
+ attempt_outcome = EXCLUDED.attempt_outcome,
+ attempt_error = EXCLUDED.attempt_error,
+ updated_at = now()
+ "#,
+ session.as_uuid(),
+ outcome.to_string(),
+ error,
+ finished_at,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err, fields(agent.session.id = %session))]
+ async fn get(&self, session: AgentSessionId) -> Result<SessionChanges, rootcause::Report> {
+ let row = sqlx::query_as!(
+ ChangesRow,
+ r#"
+ SELECT changeset_id, source, repository, base_ref, base_sha, head_ref, head_sha,
+ files, additions, deletions, patch_bytes, truncated, captured_at,
+ attempt_started_at, attempt_finished_at, attempt_outcome, attempt_error
+ FROM agent_session_changes
+ WHERE agent_session_id = $1
+ "#,
+ session.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ match row {
+ Some(row) => row.into_changes(session),
+ None => Ok(SessionChanges::default()),
+ }
+ }
+
+ #[tracing::instrument(skip(self), err, fields(agent.session.id = %session))]
+ async fn patch_key(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Option<PatchBlobKey>, rootcause::Report> {
+ let key = sqlx::query_scalar!(
+ r#"SELECT patch_blob_key FROM agent_session_changes WHERE agent_session_id = $1"#,
+ session.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ Ok(key.flatten().map(PatchBlobKey::from_stored))
+ }
+}
diff --git a/crates/agent_changes/src/outbound/postgres/test.rs b/crates/agent_changes/src/outbound/postgres/test.rs
new file mode 100644
index 0000000000..a8a9d8dc69
--- /dev/null
+++ b/crates/agent_changes/src/outbound/postgres/test.rs
@@ -0,0 +1,222 @@
+use super::*;
+use crate::domain::model::FileChangeKind;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+
+const OWNER: &str = "macro|[email protected]";
+
+/// A session row for the summary row's foreign key, with the user and bot
+/// rows it needs in turn.
+async fn seed_session(pool: &PgPool) -> AgentSessionId {
+ let email = OWNER.strip_prefix("macro|").unwrap_or(OWNER);
+ let macro_user_id = sqlx::query_scalar!(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (username) DO UPDATE SET username = EXCLUDED.username
+ RETURNING id
+ "#,
+ macro_uuid::generate_uuid_v7(),
+ email,
+ email,
+ format!("stripe_{email}"),
+ )
+ .fetch_one(pool)
+ .await
+ .expect("insert macro_user");
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING"#,
+ OWNER,
+ email,
+ macro_user_id,
+ )
+ .execute(pool)
+ .await
+ .expect("insert User");
+ let bot_id = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ r#"INSERT INTO bots (id, kind, name, handle, has_agent, owner_user_id) VALUES ($1, 'owned', 'Changes Bot', $2, true, $3)"#,
+ bot_id,
+ format!("changes-bot-{}", bot_id.simple()),
+ OWNER,
+ )
+ .execute(pool)
+ .await
+ .expect("insert bot");
+ let session = AgentSessionId::new();
+ sqlx::query!(
+ r#"
+ INSERT INTO agent_session (id, owner_id, bot_id, model, harness, repo_url, workspace, name)
+ VALUES ($1, $2, $3, 'claude', 'macrod', 'https://github.com/example/example', '/workspace', 'Changes')
+ "#,
+ session.as_uuid(),
+ OWNER,
+ bot_id,
+ )
+ .execute(pool)
+ .await
+ .expect("insert agent_session");
+ session
+}
+
+fn changeset(session: AgentSessionId) -> Changeset {
+ Changeset {
+ id: ChangesetId::new(),
+ session,
+ source: ChangesetSource::GithubPullRequest,
+ range: ChangesetRange {
+ repository: Some("https://github.com/example/example".to_owned()),
+ base: GitRef {
+ name: Some("main".to_owned()),
+ sha: Some("aaa".to_owned()),
+ },
+ head: GitRef {
+ name: Some("agent/work".to_owned()),
+ sha: None,
+ },
+ },
+ files: vec![ChangedFile {
+ path: "src/lib.rs".to_owned(),
+ previous_path: None,
+ kind: FileChangeKind::Modified,
+ additions: 3,
+ deletions: 1,
+ binary: false,
+ patch_omitted: false,
+ }],
+ additions: 3,
+ deletions: 1,
+ patch_bytes: 120,
+ truncated: false,
+ captured_at: Utc::now(),
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_session_without_captures_reads_as_empty(pool: PgPool) {
+ let repo = PgChangesetRepo::new(pool.clone());
+ let session = seed_session(&pool).await;
+ assert_eq!(repo.get(session).await.unwrap(), SessionChanges::default());
+ assert!(repo.patch_key(session).await.unwrap().is_none());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_attempt_is_visible_while_it_runs_and_when_it_ends(pool: PgPool) {
+ let repo = PgChangesetRepo::new(pool.clone());
+ let session = seed_session(&pool).await;
+ let started = Utc::now();
+ repo.begin_attempt(session, started).await.unwrap();
+
+ let running = repo.get(session).await.unwrap();
+ assert!(running.changeset.is_none());
+ let attempt = running.attempt.expect("the attempt is recorded");
+ assert!(attempt.in_flight());
+ assert_eq!(
+ attempt.started_at.timestamp_millis(),
+ started.timestamp_millis()
+ );
+
+ repo.record_failure(
+ session,
+ AttemptOutcome::NotReady,
+ Some("not yet"),
+ Utc::now(),
+ )
+ .await
+ .unwrap();
+ let attempt = repo.get(session).await.unwrap().attempt.unwrap();
+ assert!(!attempt.in_flight());
+ assert_eq!(attempt.outcome, Some(AttemptOutcome::NotReady));
+ assert_eq!(attempt.error.as_deref(), Some("not yet"));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_captured_changeset_round_trips_and_reports_what_it_superseded(pool: PgPool) {
+ let repo = PgChangesetRepo::new(pool.clone());
+ let session = seed_session(&pool).await;
+ repo.begin_attempt(session, Utc::now()).await.unwrap();
+
+ let first = changeset(session);
+ let first_key = PatchBlobKey::for_changeset(session, first.id);
+ let superseded = repo
+ .record_changeset(&first, Some(&first_key), Utc::now())
+ .await
+ .unwrap();
+ assert!(superseded.is_none(), "nothing came before");
+
+ let stored = repo.get(session).await.unwrap();
+ let stored_changeset = stored.changeset.expect("captured");
+ assert_eq!(stored_changeset.id, first.id);
+ assert_eq!(stored_changeset.files, first.files);
+ assert_eq!(stored_changeset.range, first.range);
+ assert_eq!(
+ (stored_changeset.additions, stored_changeset.deletions),
+ (3, 1)
+ );
+ assert_eq!(stored_changeset.patch_bytes, 120);
+ assert_eq!(
+ stored.attempt.unwrap().outcome,
+ Some(AttemptOutcome::Captured)
+ );
+ assert_eq!(
+ repo.patch_key(session).await.unwrap(),
+ Some(first_key.clone())
+ );
+
+ let mut second = changeset(session);
+ second.files.clear();
+ second.patch_bytes = 0;
+ let superseded = repo
+ .record_changeset(&second, None, Utc::now())
+ .await
+ .unwrap();
+ assert_eq!(
+ superseded,
+ Some(first_key),
+ "the old patch is reported for cleanup"
+ );
+ assert!(repo.patch_key(session).await.unwrap().is_none());
+ assert!(
+ repo.get(session)
+ .await
+ .unwrap()
+ .changeset
+ .unwrap()
+ .files
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_failed_attempt_keeps_the_previous_changeset(pool: PgPool) {
+ let repo = PgChangesetRepo::new(pool.clone());
+ let session = seed_session(&pool).await;
+ let first = changeset(session);
+ repo.record_changeset(&first, None, Utc::now())
+ .await
+ .unwrap();
+
+ repo.begin_attempt(session, Utc::now()).await.unwrap();
+ repo.record_failure(session, AttemptOutcome::Failed, Some("boom"), Utc::now())
+ .await
+ .unwrap();
+
+ let stored = repo.get(session).await.unwrap();
+ assert_eq!(stored.changeset.map(|c| c.id), Some(first.id));
+ let attempt = stored.attempt.unwrap();
+ assert_eq!(attempt.outcome, Some(AttemptOutcome::Failed));
+ assert_eq!(attempt.error.as_deref(), Some("boom"));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn deleting_the_session_takes_its_changes_with_it(pool: PgPool) {
+ let repo = PgChangesetRepo::new(pool.clone());
+ let session = seed_session(&pool).await;
+ repo.record_changeset(&changeset(session), None, Utc::now())
+ .await
+ .unwrap();
+ sqlx::query!("DELETE FROM agent_session WHERE id = $1", session.as_uuid())
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(repo.get(session).await.unwrap(), SessionChanges::default());
+}
diff --git a/crates/agent_changes/src/outbound/s3.rs b/crates/agent_changes/src/outbound/s3.rs
new file mode 100644
index 0000000000..532f96c710
--- /dev/null
+++ b/crates/agent_changes/src/outbound/s3.rs
@@ -0,0 +1,84 @@
+//! Patch blobs in S3.
+//!
+//! One object per capture under `agent-sessions/{session}/changes/`; the
+//! key is minted by the domain ([`PatchBlobKey`]), this adapter only moves
+//! bytes. Patches are UTF-8 text and rarely more than a few megabytes, so
+//! they are read whole - there is no streaming here to get right.
+
+use aws_sdk_s3::primitives::ByteStream;
+
+use crate::domain::ports::{ChangesetBlobStore, PatchBlobKey};
+
+/// S3-backed [`ChangesetBlobStore`].
+#[derive(Clone)]
+pub struct S3ChangesetBlobStore {
+ client: aws_sdk_s3::Client,
+ bucket: String,
+}
+
+impl S3ChangesetBlobStore {
+ /// Store patches in `bucket` through `client`.
+ #[must_use]
+ pub fn new(client: aws_sdk_s3::Client, bucket: String) -> Self {
+ Self { client, bucket }
+ }
+}
+
+impl ChangesetBlobStore for S3ChangesetBlobStore {
+ #[tracing::instrument(skip(self, patch), err, fields(key = %key, bytes = patch.len()))]
+ async fn put_patch(&self, key: &PatchBlobKey, patch: &str) -> Result<(), rootcause::Report> {
+ self.client
+ .put_object()
+ .bucket(&self.bucket)
+ .key(key.as_str())
+ .content_type("text/x-diff; charset=utf-8")
+ .body(ByteStream::from(patch.as_bytes().to_vec()))
+ .send()
+ .await
+ .map_err(|error| rootcause::report!("put patch {key}: {error:?}"))?;
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err, fields(key = %key))]
+ async fn get_patch(&self, key: &PatchBlobKey) -> Result<Option<String>, rootcause::Report> {
+ let response = match self
+ .client
+ .get_object()
+ .bucket(&self.bucket)
+ .key(key.as_str())
+ .send()
+ .await
+ {
+ Ok(response) => response,
+ Err(error)
+ if error
+ .as_service_error()
+ .is_some_and(|service_error| service_error.is_no_such_key()) =>
+ {
+ return Ok(None);
+ }
+ Err(error) => return Err(rootcause::report!("get patch {key}: {error:?}")),
+ };
+ let bytes = response
+ .body
+ .collect()
+ .await
+ .map_err(|error| rootcause::report!("read patch {key}: {error:?}"))?
+ .into_bytes();
+ String::from_utf8(bytes.to_vec())
+ .map(Some)
+ .map_err(|error| rootcause::report!("patch {key} is not UTF-8: {error}"))
+ }
+
+ #[tracing::instrument(skip(self), err, fields(key = %key))]
+ async fn delete_patch(&self, key: &PatchBlobKey) -> Result<(), rootcause::Report> {
+ self.client
+ .delete_object()
+ .bucket(&self.bucket)
+ .key(key.as_str())
+ .send()
+ .await
+ .map_err(|error| rootcause::report!("delete patch {key}: {error:?}"))?;
+ Ok(())
+ }
+}
diff --git a/crates/agent_changes/src/testing.rs b/crates/agent_changes/src/testing.rs
new file mode 100644
index 0000000000..611c762eb8
--- /dev/null
+++ b/crates/agent_changes/src/testing.rs
@@ -0,0 +1,217 @@
+//! In-memory implementations of the changes ports, for tests here and in the
+//! crates that plug extractors into this one.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use agent_session::domain::model::AgentSession;
+use chrono::{DateTime, Utc};
+
+use crate::domain::error::ExtractError;
+use crate::domain::model::{
+ AgentSessionId, AttemptOutcome, CaptureAttempt, Changeset, ExtractedChangeset, SessionChanges,
+};
+use crate::domain::ports::{ChangesetBlobStore, ChangesetExtractor, ChangesetRepo, PatchBlobKey};
+
+/// An extractor that answers with whatever it was last told to, and counts
+/// how often it was asked.
+#[derive(Clone, Default)]
+pub struct ScriptedExtractor {
+ state: Arc<Mutex<ScriptedState>>,
+}
+
+#[derive(Default)]
+struct ScriptedState {
+ answer: Option<Result<ExtractedChangeset, String>>,
+ not_ready: Option<String>,
+ calls: usize,
+}
+
+impl ScriptedExtractor {
+ /// Answer every extraction with `changeset`.
+ #[must_use]
+ pub fn returning(changeset: ExtractedChangeset) -> Self {
+ let this = Self::default();
+ this.set(changeset);
+ this
+ }
+
+ /// An extractor whose linked PR is unavailable.
+ #[must_use]
+ pub fn not_ready(reason: &str) -> Self {
+ let this = Self::default();
+ this.state.lock().expect("scripted state").not_ready = Some(reason.to_owned());
+ this
+ }
+
+ /// An extractor that fails with `message`.
+ #[must_use]
+ pub fn failing(message: &str) -> Self {
+ let this = Self::default();
+ this.state.lock().expect("scripted state").answer = Some(Err(message.to_owned()));
+ this
+ }
+
+ /// Change what later extractions answer.
+ pub fn set(&self, changeset: ExtractedChangeset) {
+ self.state.lock().expect("scripted state").answer = Some(Ok(changeset));
+ }
+
+ /// How many extractions were asked for.
+ #[must_use]
+ pub fn calls(&self) -> usize {
+ self.state.lock().expect("scripted state").calls
+ }
+}
+
+impl ChangesetExtractor for ScriptedExtractor {
+ async fn extract(&self, _session: &AgentSession) -> Result<ExtractedChangeset, ExtractError> {
+ let mut state = self.state.lock().expect("scripted state");
+ state.calls += 1;
+ if let Some(reason) = &state.not_ready {
+ return Err(ExtractError::NotReady(reason.clone()));
+ }
+ match state.answer.clone() {
+ Some(Ok(changeset)) => Ok(changeset),
+ Some(Err(message)) => Err(ExtractError::Failed(rootcause::report!("{message}"))),
+ None => Err(ExtractError::Failed(rootcause::report!(
+ "the scripted extractor was given no answer"
+ ))),
+ }
+ }
+}
+
+#[derive(Default)]
+struct MemoryRow {
+ changeset: Option<Changeset>,
+ patch_key: Option<PatchBlobKey>,
+ attempt: Option<CaptureAttempt>,
+}
+
+/// An in-memory [`ChangesetRepo`]. Cheap to clone - clones share one store.
+#[derive(Clone, Default)]
+pub struct MemoryChangesetRepo {
+ rows: Arc<Mutex<HashMap<AgentSessionId, MemoryRow>>>,
+}
+
+impl MemoryChangesetRepo {
+ /// An empty store.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+}
+
+impl ChangesetRepo for MemoryChangesetRepo {
+ async fn begin_attempt(
+ &self,
+ session: AgentSessionId,
+ started_at: DateTime<Utc>,
+ ) -> Result<(), rootcause::Report> {
+ let mut rows = self.rows.lock().expect("rows");
+ rows.entry(session).or_default().attempt = Some(CaptureAttempt {
+ started_at,
+ finished_at: None,
+ outcome: None,
+ error: None,
+ });
+ Ok(())
+ }
+
+ async fn record_changeset(
+ &self,
+ changeset: &Changeset,
+ patch_key: Option<&PatchBlobKey>,
+ finished_at: DateTime<Utc>,
+ ) -> Result<Option<PatchBlobKey>, rootcause::Report> {
+ let mut rows = self.rows.lock().expect("rows");
+ let row = rows.entry(changeset.session).or_default();
+ let superseded = row.patch_key.take();
+ row.changeset = Some(changeset.clone());
+ row.patch_key = patch_key.cloned();
+ if let Some(attempt) = row.attempt.as_mut() {
+ attempt.finished_at = Some(finished_at);
+ attempt.outcome = Some(AttemptOutcome::Captured);
+ attempt.error = None;
+ }
+ Ok(superseded)
+ }
+
+ async fn record_failure(
+ &self,
+ session: AgentSessionId,
+ outcome: AttemptOutcome,
+ error: Option<&str>,
+ finished_at: DateTime<Utc>,
+ ) -> Result<(), rootcause::Report> {
+ let mut rows = self.rows.lock().expect("rows");
+ let row = rows.entry(session).or_default();
+ if let Some(attempt) = row.attempt.as_mut() {
+ attempt.finished_at = Some(finished_at);
+ attempt.outcome = Some(outcome);
+ attempt.error = error.map(str::to_owned);
+ }
+ Ok(())
+ }
+
+ async fn get(&self, session: AgentSessionId) -> Result<SessionChanges, rootcause::Report> {
+ let rows = self.rows.lock().expect("rows");
+ Ok(rows
+ .get(&session)
+ .map(|row| SessionChanges {
+ changeset: row.changeset.clone(),
+ attempt: row.attempt.clone(),
+ })
+ .unwrap_or_default())
+ }
+
+ async fn patch_key(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<Option<PatchBlobKey>, rootcause::Report> {
+ let rows = self.rows.lock().expect("rows");
+ Ok(rows.get(&session).and_then(|row| row.patch_key.clone()))
+ }
+}
+
+/// An in-memory [`ChangesetBlobStore`]. Cheap to clone - clones share one
+/// store.
+#[derive(Clone, Default)]
+pub struct MemoryBlobStore {
+ blobs: Arc<Mutex<HashMap<String, String>>>,
+}
+
+impl MemoryBlobStore {
+ /// An empty store.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Every stored key, sorted.
+ #[must_use]
+ pub fn keys(&self) -> Vec<String> {
+ let mut keys: Vec<String> = self.blobs.lock().expect("blobs").keys().cloned().collect();
+ keys.sort();
+ keys
+ }
+}
+
+impl ChangesetBlobStore for MemoryBlobStore {
+ async fn put_patch(&self, key: &PatchBlobKey, patch: &str) -> Result<(), rootcause::Report> {
+ self.blobs
+ .lock()
+ .expect("blobs")
+ .insert(key.as_str().to_owned(), patch.to_owned());
+ Ok(())
+ }
+
+ async fn get_patch(&self, key: &PatchBlobKey) -> Result<Option<String>, rootcause::Report> {
+ Ok(self.blobs.lock().expect("blobs").get(key.as_str()).cloned())
+ }
+
+ async fn delete_patch(&self, key: &PatchBlobKey) -> Result<(), rootcause::Report> {
+ self.blobs.lock().expect("blobs").remove(key.as_str());
+ Ok(())
+ }
+}
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 3682155a8f..ecc5d2616e 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -691,6 +691,15 @@ pub trait AgentSessionRealtime {
) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
async { Ok(()) }
}
+
+ /// Tell viewers the session's captured changes moved: a capture started,
+ /// finished, or failed. Viewers refetch the changes summary.
+ fn publish_changes_updated(
+ &self,
+ _session: AgentSessionId,
+ ) -> impl Future<Output = Result<(), rootcause::Report>> + Send {
+ async { Ok(()) }
+ }
}
/// Publishing a session's lifecycle facts for anyone downstream: webhooks,
@@ -769,6 +778,21 @@ impl<T: SessionTurnObserver + ?Sized> SessionTurnObserver for std::sync::Arc<T>
}
}
+/// Two observers told the same facts, in order. How the composition root
+/// fans one session service's signals out to the harness (which drains its
+/// queue on them) and to anything else that wants to know a turn ended.
+impl<A: SessionTurnObserver, B: SessionTurnObserver> SessionTurnObserver for (A, B) {
+ fn signal(&self, id: AgentSessionId, signal: TurnSignal) {
+ self.0.signal(id, signal.clone());
+ self.1.signal(id, signal);
+ }
+
+ fn session_stopped(&self, id: AgentSessionId, reason: StopReason) {
+ self.0.session_stopped(id, reason.clone());
+ self.1.session_stopped(id, reason);
+ }
+}
+
/// A [`SessionTurnObserver`] for services with no queue above them: tests,
/// offline tooling, and replay.
#[derive(Debug, Clone, Copy, Default)]
diff --git a/crates/agent_session/src/outbound/connection_gateway_realtime.rs b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
index 2c1bc04b60..cb0c44aa37 100644
--- a/crates/agent_session/src/outbound/connection_gateway_realtime.rs
+++ b/crates/agent_session/src/outbound/connection_gateway_realtime.rs
@@ -63,6 +63,11 @@ pub const AGENT_SESSION_RENAMED: &str = "agent_session_renamed";
/// response can never carry information the socket will not deliver.
pub const AGENT_SESSION_QUEUE: &str = "agent_session_queue";
+/// The realtime message type telling viewers a session's captured changes
+/// moved: a capture started, finished, or failed. Carries only the session
+/// id; viewers refetch `GET /agent-sessions/{id}/changes`.
+pub const AGENT_SESSION_CHANGES: &str = "agent_session_changes";
+
/// The body of an [`AGENT_SESSION_LOG`] message - the module docs are the
/// contract.
#[derive(Debug, Serialize)]
@@ -292,6 +297,33 @@ where
Ok(())
}
+ #[tracing::instrument(skip(self), err, fields(agent.session.id = %session))]
+ async fn publish_changes_updated(
+ &self,
+ session: AgentSessionId,
+ ) -> Result<(), rootcause::Report> {
+ let recipients = self.participants.viewers(session).await?;
+ if recipients.is_empty() {
+ return Ok(());
+ }
+ let payload = serde_json::to_value(AgentSessionUpdatedEvent {
+ agent_session_id: session.as_uuid(),
+ })
+ .map_err(|error| rootcause::report!(error))?;
+ self.client
+ .batch_send_message(
+ AGENT_SESSION_CHANGES.to_owned(),
+ payload,
+ recipients
+ .iter()
+ .map(|user| GatewayEntityType::User.with_entity_str(user.as_ref()))
+ .collect(),
+ )
+ .await
+ .map_err(|error| rootcause::report!(error))?;
+ Ok(())
+ }
+
async fn publish_renamed(&self, event: AgentSessionRenamed) -> Result<(), rootcause::Report> {
let recipients = self.participants.viewers(event.agent_session_id).await?;
if recipients.is_empty() {
diff --git a/crates/macro_db_client/migrations/20260918195318_agent_session_changes.sql b/crates/macro_db_client/migrations/20260918195318_agent_session_changes.sql
new file mode 100644
index 0000000000..695c08e030
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260918195318_agent_session_changes.sql
@@ -0,0 +1,49 @@
+-- The latest captured changeset of an agent session, and how the latest
+-- capture attempt went (see agent_changes::domain::model).
+--
+-- One row per session, replaced on every capture: the Changes pane shows the
+-- current state of the linked pull request, not a history of captures. The patch
+-- itself is a blob under `patch_blob_key`; this row holds what the pane needs
+-- before the patch arrives - the file list with statuses and line counts - so
+-- the tree and headers render at once and the patch streams in behind them.
+--
+-- The summary columns are all NULL until a first capture succeeds, and a
+-- failed attempt leaves the previous summary in place: a branch the provider
+-- could not compare for a moment is still the branch it was. Cascade: a
+-- session's changes go with the session; the orphaned patch blob is reclaimed
+-- by the bucket's lifecycle rule rather than a delete here.
+CREATE TABLE agent_session_changes (
+ agent_session_id UUID PRIMARY KEY REFERENCES agent_session(id) ON DELETE CASCADE,
+ -- Identity of the capture the summary columns describe (UUIDv7, minted
+ -- in application code).
+ changeset_id UUID,
+ source TEXT CHECK (source IN ('github_pull_request')),
+ -- `https://github.com/owner/name` when the extractor knows it.
+ repository TEXT,
+ base_ref TEXT,
+ base_sha TEXT,
+ head_ref TEXT,
+ head_sha TEXT,
+ -- agent_changes::domain::model::ChangedFile, one per changed file, in
+ -- patch order.
+ files JSONB NOT NULL DEFAULT '[]'::jsonb,
+ additions INTEGER NOT NULL DEFAULT 0,
+ deletions INTEGER NOT NULL DEFAULT 0,
+ patch_blob_key TEXT,
+ patch_bytes BIGINT NOT NULL DEFAULT 0,
+ truncated BOOLEAN NOT NULL DEFAULT false,
+ captured_at TIMESTAMPTZ,
+ -- The latest attempt: running while attempt_finished_at is NULL.
+ attempt_started_at TIMESTAMPTZ NOT NULL,
+ attempt_finished_at TIMESTAMPTZ,
+ attempt_outcome TEXT CHECK (attempt_outcome IN ('captured', 'not_ready', 'failed')),
+ attempt_error TEXT,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT agent_session_changes_summary_complete CHECK (
+ (changeset_id IS NULL) = (source IS NULL)
+ AND (changeset_id IS NULL) = (captured_at IS NULL)
+ ),
+ CONSTRAINT agent_session_changes_attempt_complete CHECK (
+ (attempt_finished_at IS NULL) = (attempt_outcome IS NULL)
+ )
+);
diff --git a/crates/macro_db_migrator/src/bin/comment_import/test.rs b/crates/macro_db_migrator/src/bin/comment_import/test.rs
index 43a2e14943..a20de15d6a 100644
--- a/crates/macro_db_migrator/src/bin/comment_import/test.rs
+++ b/crates/macro_db_migrator/src/bin/comment_import/test.rs
@@ -504,6 +504,7 @@ async fn rejects_concurrent_runner_ambiguous_anchors_and_duplicate_marks(pool: P
.to_string()
.contains("Another comment import")
);
+ release_import_lock(&mut other).await;
other.close().await.unwrap();
sqlx::query!(r#"UPDATE "PdfHighlightAnchor" SET "threadId" = 3"#)
@@ -544,6 +545,7 @@ async fn rejects_concurrent_runner_ambiguous_anchors_and_duplicate_marks(pool: P
.await
.unwrap();
assert!(acquired);
+ release_import_lock(&mut probe).await;
probe.close().await.unwrap();
sqlx::query!(r#"UPDATE "Thread" SET metadata = '{"markId":"not-a-mark"}' WHERE id = 5"#)
@@ -563,6 +565,17 @@ async fn other_connection(pool: &PgPool) -> PgConnection {
pool.acquire().await.unwrap().detach()
}
+async fn release_import_lock(connection: &mut PgConnection) {
+ // Closing the client does not wait for PostgreSQL to release session locks.
+ // Await an explicit unlock before another connection tries to run the import.
+ assert!(
+ sqlx::query_scalar!(r#"SELECT pg_advisory_unlock($1) AS "released!""#, LOCK_ID)
+ .fetch_one(connection)
+ .await
+ .unwrap()
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn failed_batch_rolls_back_and_can_retry(pool: PgPool) {
let mut connection = legacy_database(&pool).await;
diff --git a/docker/docker-compose.local-e2e.yml b/docker/docker-compose.local-e2e.yml
index 55ad724950..4aa0638a77 100644
--- a/docker/docker-compose.local-e2e.yml
+++ b/docker/docker-compose.local-e2e.yml
@@ -21,6 +21,7 @@ x-local-e2e-env: &local-e2e-env
DOCX_DOCUMENT_UPLOAD_BUCKET: docx-upload
STATIC_STORAGE_BUCKET: static-file-storage
UPLOAD_STAGING_BUCKET: bulk-upload-staging
+ AGENT_SESSION_CHANGES_BUCKET: agent-session-changes
BULK_UPLOAD_REQUESTS_TABLE: bulk-upload
CONNECTION_GATEWAY_TABLE: connection-gateway-table
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index f3ebd303a8..d585c2d121 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -399,6 +399,45 @@ The display choice survives reload and copying; expansion still references the
same session and does not invoke a bot. Compact mentions do not load transcripts.
Existing announcement chips remain locked to the turn they announced.
+### Reviewing a linked GitHub pull request
+
+Sessions with a linked GitHub pull request capture that PR's diff when each
+turn ends, regardless of the agent runtime. Unpushed workspace changes and
+branches without a PR are not included. The session header gains a **Changes**
+toggle (`aria-pressed`) with green additions and red deletions (`+N −M`); it opens a resizable
+**Changes** pane beside the transcript (drag the 1px divider between them).
+The URL's `diff` query parameter stores each session's pane state and diff
+layout (`session-id:split:unified`, or `changes-only` / `agent-only` and
+`split` for side-by-side diffs). Copying the URL preserves that view; reload
+and Back/Forward restore it. A plain session URL starts with Changes closed.
+Divider width, collapsed files, and review notes stay local.
+The pane header shows a `head → base` branch pill, a **Unified / Split**
+segmented control (`aria-label="Diff layout"`), a refresh button, the
+**View pull request** button (opens GitHub), and **Expand changes to the full width**
+(spotlight; **Bring the session back** returns to the split) and **Close the
+changes pane**. Below it is a **Collapse all / Expand all** button.
+The body is a file tree (`nav[aria-label="Changed files"]`, directories
+compressed along single-child chains, status letters A/M/D/R and +/− counts)
+next to a scrollable stack of file cards. Expanded cards keep their full height;
+**Collapse all / Expand all** hides or restores their bodies. Each card's header has a disclosure
+caret, the path, `+adds −dels`, and **Copy path**. Diffs render with Pierre; hover a
+line and click the accent **+** in the gutter (drag for a range) to leave a
+review note for the agent (`aria-label="Review note"`; `Cmd/Ctrl+Enter` adds,
+`Escape` cancels). Notes hang under their line as "queued for the agent" and a
+**N review notes queued · Send to agent** chip appears above the composer;
+sending posts one prompt listing every note by file and line and marks them
+"sent to agent". Notes never go to GitHub. Collapsed files and unsent notes
+persist per session in localStorage; a new capture expands all files.
+
+While the pane is closed and a capture has files, a **Changes ready to
+review** card sits above the composer with **Review changes**, **Pull request
+#N** (opens GitHub), and **Dismiss**. With no linked PR, the pane explains
+that a GitHub PR is required. Ask the agent to open one and register its URL
+with `set_pull_request`, then use **Refresh changes**. An unavailable or
+oversized PR is explained in the pane; there is no branch or container fallback.
+Refresh request failures show a retry banner while keeping the last diff visible.
+The pane does not create PRs or generate their descriptions.
+
### Transcript navigation
Agent sessions reuse the channel's TanStack `ThreadList`. Opening a session lands
diff --git a/infra/stacks/agent-harness-service/index.ts b/infra/stacks/agent-harness-service/index.ts
index 9cef7be9a4..8a1cfb397e 100644
--- a/infra/stacks/agent-harness-service/index.ts
+++ b/infra/stacks/agent-harness-service/index.ts
@@ -1,5 +1,6 @@
import * as aws from '@pulumi/aws';
import * as pulumi from '@pulumi/pulumi';
+import { createBucket } from '../../packages/resources';
import {
config,
CODEX_OAUTH_KMS_ALIAS,
@@ -46,6 +47,30 @@ const macroApiTokenPrivateKeyArn = aws.secretsmanager
const MACRO_API_TOKENS = getMacroApiToken();
+// ── Session changes bucket ───────────────────────────────────────────────────
+// The patch behind each agent session's Changes pane, one object per capture
+// under `agent-sessions/{session}/changes/`. Only the latest capture is
+// reachable from the database; superseded patches are deleted on capture and
+// a session's last patch is orphaned when the session is deleted, so the
+// lifecycle rule is what reclaims those.
+
+const sessionChangesBucket = createBucket({
+ id: `macro-agent-session-changes-${stack}`,
+ bucketName: `macro-agent-session-changes-${stack}`,
+ transferAcceleration: false,
+ enableVersioning: false,
+ lifecycleRules: [
+ {
+ id: 'expire-orphaned-patches',
+ enabled: true,
+ expiration: { days: 90 },
+ },
+ ],
+ tags,
+});
+
+export const agentSessionChangesBucketArn = sessionChangesBucket.arn;
+
// ── AI tools infra ───────────────────────────────────────────────────────────
const aiTools = getAiToolsInfra();
@@ -85,7 +110,7 @@ const service = new AgentHarnessService(`agent-harness-service-${stack}`, {
...aiTools.secretArns,
],
queueArns: [...aiTools.queueArns],
- bucketArns: [...aiTools.bucketArns],
+ bucketArns: [...aiTools.bucketArns, sessionChangesBucket.arn],
containerEnvVars: [
{
name: 'CODEX_OAUTH_KMS_KEY_ID',
@@ -95,6 +120,10 @@ const service = new AgentHarnessService(`agent-harness-service-${stack}`, {
name: 'ENVIRONMENT',
value: stack,
},
+ {
+ name: 'AGENT_SESSION_CHANGES_BUCKET',
+ value: sessionChangesBucket.bucket,
+ },
// Datadog
{
name: 'DD_SERVICE',
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 5cfa1deab5..4f1ca98c21 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
+export type { AgentAction, AgentActionId, AgentModelDto, AgentModelsStatusDto, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index d150f40ac2..521b73a358 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses } from './types.gen';
+import type { CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -157,6 +157,29 @@ export class Sdk extends HeyApiClient {
return (options.client ?? this.client).get<GetAgentSessionResponses, GetAgentSessionErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}', ...options });
}
+ /**
+ * The latest captured changes of an agent session: the changed files with
+ * statuses and line counts, and how the latest capture attempt went.
+ */
+ public getAgentSessionChanges<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionChangesData, ThrowOnError>): RequestResult<GetAgentSessionChangesResponses, GetAgentSessionChangesErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetAgentSessionChangesResponses, GetAgentSessionChangesErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/changes', ...options });
+ }
+
+ /**
+ * The unified diff behind the session's latest changeset.
+ */
+ public getAgentSessionChangesPatch<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionChangesPatchData, ThrowOnError>): RequestResult<GetAgentSessionChangesPatchResponses, GetAgentSessionChangesPatchErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetAgentSessionChangesPatchResponses, GetAgentSessionChangesPatchErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/changes/patch', ...options });
+ }
+
+ /**
+ * Capture the session's changes again now. Answers at once with the state
+ * as it stands; the capture runs on and viewers are told when it lands.
+ */
+ public refreshAgentSessionChanges<ThrowOnError extends boolean = false>(options: Options<RefreshAgentSessionChangesData, ThrowOnError>): RequestResult<RefreshAgentSessionChangesResponses, RefreshAgentSessionChangesErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<RefreshAgentSessionChangesResponses, RefreshAgentSessionChangesErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/changes/refresh', ...options });
+ }
+
/**
* Perform a control operation on a live agent session.
*
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 559151e2de..fe1f6625dc 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -116,6 +116,32 @@ export type AgentRespondElicitationAction = ElicitationAnswer & {
requestId: ElicitationRequestId;
};
+/**
+ * Response body for `GET /agent-sessions/{session_id}/changes/patch`.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type AgentSessionChangesPatchResponse = {
+ /**
+ * The git-style unified diff of the current changeset.
+ */
+ patch: string;
+};
+
+/**
+ * Response body for `GET /agent-sessions/{session_id}/changes`.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type AgentSessionChangesResponse = {
+ attempt?: null | CaptureAttemptDto;
+ /**
+ * A capture is running right now.
+ */
+ capturing: boolean;
+ changeset?: null | ChangesetDto;
+};
+
/**
* One entry of a session's protocol log.
*
@@ -349,6 +375,126 @@ export type AgentSetModelAction = {
export type BotId = string;
+/**
+ * The latest capture attempt.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type CaptureAttemptDto = {
+ /**
+ * Why it did not capture, in a sentence the user can read.
+ */
+ error?: string | null;
+ /**
+ * When it ended; absent while it runs.
+ */
+ finishedAt?: string | null;
+ outcome?: null | CaptureOutcomeDto;
+ /**
+ * When it started.
+ */
+ startedAt: string;
+};
+
+/**
+ * How the latest capture attempt ended, on the wire.
+ */
+export type CaptureOutcomeDto = 'captured' | 'not_ready' | 'failed';
+
+/**
+ * One changed file.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type ChangedFileDto = {
+ /**
+ * Lines added.
+ */
+ additions: number;
+ /**
+ * The diff carries no text for this file.
+ */
+ binary: boolean;
+ /**
+ * Lines removed.
+ */
+ deletions: number;
+ /**
+ * What happened to the file.
+ */
+ kind: FileChangeKindDto;
+ /**
+ * The file's hunks were left out of the patch to fit the size budget.
+ */
+ patchOmitted: boolean;
+ /**
+ * The file's path after the change, or before it for a deletion.
+ */
+ path: string;
+ /**
+ * Where a renamed file came from.
+ */
+ previousPath?: string | null;
+};
+
+/**
+ * One capture of a session's changes.
+ *
+ * Clients deserialize this, so both derives are used.
+ */
+export type ChangesetDto = {
+ /**
+ * Lines added across all files.
+ */
+ additions: number;
+ /**
+ * The side the work started from.
+ */
+ base: GitRefDto;
+ /**
+ * When the diff was taken.
+ */
+ capturedAt: string;
+ /**
+ * Lines removed across all files.
+ */
+ deletions: number;
+ /**
+ * Every changed file, in patch order.
+ */
+ files: Array<ChangedFileDto>;
+ /**
+ * The side carrying the work.
+ */
+ head: GitRefDto;
+ /**
+ * The capture's id; changes with every capture.
+ */
+ id: string;
+ /**
+ * Size of the patch `GET .../changes/patch` serves; zero when nothing
+ * changed.
+ */
+ patchBytes: number;
+ /**
+ * `https://github.com/owner/name`, when known.
+ */
+ repository?: string | null;
+ /**
+ * Where the diff was read from.
+ */
+ source: ChangesetSourceDto;
+ /**
+ * Some files' hunks were left out of the patch.
+ */
+ truncated: boolean;
+};
+
+/**
+ * The source of the captured diff, on the wire.
+ */
+export type ChangesetSourceDto = 'github_pull_request';
+
/**
* One-time manual code. Deliberately does not implement Debug.
*/
@@ -591,6 +737,25 @@ export type ExternalSessionResponse = {
url?: string | null;
};
+/**
+ * What happened to a file, on the wire.
+ */
+export type FileChangeKindDto = 'added' | 'modified' | 'deleted' | 'renamed';
+
+/**
+ * One end of the compared range.
+ */
+export type GitRefDto = {
+ /**
+ * The branch name, when known.
+ */
+ name?: string | null;
+ /**
+ * The commit, when known.
+ */
+ sha?: string | null;
+};
+
/**
* HTTP request selecting one provider to probe.
*/
@@ -1085,6 +1250,85 @@ export type GetAgentSessionResponses = {
export type GetAgentSessionResponse = GetAgentSessionResponses[keyof GetAgentSessionResponses];
+export type GetAgentSessionChangesData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/changes';
+};
+
+export type GetAgentSessionChangesErrors = {
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type GetAgentSessionChangesError = GetAgentSessionChangesErrors[keyof GetAgentSessionChangesErrors];
+
+export type GetAgentSessionChangesResponses = {
+ 200: AgentSessionChangesResponse;
+};
+
+export type GetAgentSessionChangesResponse = GetAgentSessionChangesResponses[keyof GetAgentSessionChangesResponses];
+
+export type GetAgentSessionChangesPatchData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/changes/patch';
+};
+
+export type GetAgentSessionChangesPatchErrors = {
+ 401: string;
+ 403: string;
+ 404: string;
+ 500: string;
+};
+
+export type GetAgentSessionChangesPatchError = GetAgentSessionChangesPatchErrors[keyof GetAgentSessionChangesPatchErrors];
+
+export type GetAgentSessionChangesPatchResponses = {
+ 200: AgentSessionChangesPatchResponse;
+};
+
+export type GetAgentSessionChangesPatchResponse = GetAgentSessionChangesPatchResponses[keyof GetAgentSessionChangesPatchResponses];
+
+export type RefreshAgentSessionChangesData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/changes/refresh';
+};
+
+export type RefreshAgentSessionChangesErrors = {
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type RefreshAgentSessionChangesError = RefreshAgentSessionChangesErrors[keyof RefreshAgentSessionChangesErrors];
+
+export type RefreshAgentSessionChangesResponses = {
+ 202: AgentSessionChangesResponse;
+};
+
+export type RefreshAgentSessionChangesResponse = RefreshAgentSessionChangesResponses[keyof RefreshAgentSessionChangesResponses];
+
export type ControlAgentSessionData = {
body: ControlRequest;
path: {
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 2b5ff0358f..136eda6e54 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -431,6 +431,199 @@
}
}
},
+ "/agent-sessions/{session_id}/changes": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "The latest captured changes of an agent session: the changed files with\nstatuses and line counts, and how the latest capture attempt went.",
+ "operationId": "get_agent_session_changes",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionChangesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-sessions/{session_id}/changes/patch": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "The unified diff behind the session's latest changeset.",
+ "operationId": "get_agent_session_changes_patch",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionChangesPatchResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/agent-sessions/{session_id}/changes/refresh": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "Capture the session's changes again now. Answers at once with the state\nas it stands; the capture runs on and viewers are told when it lands.",
+ "operationId": "refresh_agent_session_changes",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "202": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionChangesResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/control": {
"post": {
"tags": ["agent-sessions"],
@@ -1264,6 +1457,50 @@
],
"description": "Answer an elicitation the agent is waiting on."
},
+ "AgentSessionChangesPatchResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-sessions/{session_id}/changes/patch`.\n\nClients deserialize this, so both derives are used.",
+ "required": ["patch"],
+ "properties": {
+ "patch": {
+ "type": "string",
+ "description": "The git-style unified diff of the current changeset."
+ }
+ }
+ },
+ "AgentSessionChangesResponse": {
+ "type": "object",
+ "description": "Response body for `GET /agent-sessions/{session_id}/changes`.\n\nClients deserialize this, so both derives are used.",
+ "required": ["capturing"],
+ "properties": {
+ "attempt": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CaptureAttemptDto",
+ "description": "The latest attempt, if any was made."
+ }
+ ]
+ },
+ "capturing": {
+ "type": "boolean",
+ "description": "A capture is running right now."
+ },
+ "changeset": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ChangesetDto",
+ "description": "The latest capture, if any succeeded."
+ }
+ ]
+ }
+ }
+ },
"AgentSessionLogEntryDto": {
"allOf": [
{
@@ -1584,6 +1821,167 @@
"BotId": {
"type": "string"
},
+ "CaptureAttemptDto": {
+ "type": "object",
+ "description": "The latest capture attempt.\n\nClients deserialize this, so both derives are used.",
+ "required": ["startedAt"],
+ "properties": {
+ "error": {
+ "type": ["string", "null"],
+ "description": "Why it did not capture, in a sentence the user can read."
+ },
+ "finishedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When it ended; absent while it runs."
+ },
+ "outcome": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CaptureOutcomeDto",
+ "description": "How it ended; absent while it runs."
+ }
+ ]
+ },
+ "startedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When it started."
+ }
+ }
+ },
+ "CaptureOutcomeDto": {
+ "type": "string",
+ "description": "How the latest capture attempt ended, on the wire.",
+ "enum": ["captured", "not_ready", "failed"]
+ },
+ "ChangedFileDto": {
+ "type": "object",
+ "description": "One changed file.\n\nClients deserialize this, so both derives are used.",
+ "required": [
+ "path",
+ "kind",
+ "additions",
+ "deletions",
+ "binary",
+ "patchOmitted"
+ ],
+ "properties": {
+ "additions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines added.",
+ "minimum": 0
+ },
+ "binary": {
+ "type": "boolean",
+ "description": "The diff carries no text for this file."
+ },
+ "deletions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines removed.",
+ "minimum": 0
+ },
+ "kind": {
+ "$ref": "#/components/schemas/FileChangeKindDto",
+ "description": "What happened to the file."
+ },
+ "patchOmitted": {
+ "type": "boolean",
+ "description": "The file's hunks were left out of the patch to fit the size budget."
+ },
+ "path": {
+ "type": "string",
+ "description": "The file's path after the change, or before it for a deletion."
+ },
+ "previousPath": {
+ "type": ["string", "null"],
+ "description": "Where a renamed file came from."
+ }
+ }
+ },
+ "ChangesetDto": {
+ "type": "object",
+ "description": "One capture of a session's changes.\n\nClients deserialize this, so both derives are used.",
+ "required": [
+ "id",
+ "source",
+ "base",
+ "head",
+ "files",
+ "additions",
+ "deletions",
+ "patchBytes",
+ "truncated",
+ "capturedAt"
+ ],
+ "properties": {
+ "additions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines added across all files.",
+ "minimum": 0
+ },
+ "base": {
+ "$ref": "#/components/schemas/GitRefDto",
+ "description": "The side the work started from."
+ },
+ "capturedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the diff was taken."
+ },
+ "deletions": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Lines removed across all files.",
+ "minimum": 0
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ChangedFileDto"
+ },
+ "description": "Every changed file, in patch order."
+ },
+ "head": {
+ "$ref": "#/components/schemas/GitRefDto",
+ "description": "The side carrying the work."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The capture's id; changes with every capture."
+ },
+ "patchBytes": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Size of the patch `GET .../changes/patch` serves; zero when nothing\nchanged.",
+ "minimum": 0
+ },
+ "repository": {
+ "type": ["string", "null"],
+ "description": "`https://github.com/owner/name`, when known."
+ },
+ "source": {
+ "$ref": "#/components/schemas/ChangesetSourceDto",
+ "description": "Where the diff was read from."
+ },
+ "truncated": {
+ "type": "boolean",
+ "description": "Some files' hunks were left out of the patch."
+ }
+ }
+ },
+ "ChangesetSourceDto": {
+ "type": "string",
+ "description": "The source of the captured diff, on the wire.",
+ "enum": ["github_pull_request"]
+ },
"CompleteRequest": {
"type": "object",
"description": "One-time manual code. Deliberately does not implement Debug.",
@@ -1871,6 +2269,25 @@
}
}
},
+ "FileChangeKindDto": {
+ "type": "string",
+ "description": "What happened to a file, on the wire.",
+ "enum": ["added", "modified", "deleted", "renamed"]
+ },
+ "GitRefDto": {
+ "type": "object",
+ "description": "One end of the compared range.",
+ "properties": {
+ "name": {
+ "type": ["string", "null"],
+ "description": "The branch name, when known."
+ },
+ "sha": {
+ "type": ["string", "null"],
+ "description": "The commit, when known."
+ }
+ }
+ },
"LoadAgentModelsRequest": {
"type": "object",
"description": "HTTP request selecting one provider to probe.",
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index ab924dbed0..f2235780f4 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -1,5 +1,6 @@
import type {
AgentAction,
+ AgentSessionChangesResponse,
AgentSessionLogResponse,
AgentSessionResponse,
ControlResponse,
@@ -213,6 +214,33 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
);
}
+ /** Read the latest captured GitHub pull request changes and capture status. */
+ async changes(): Promise<AgentSessionChangesResponse> {
+ return unwrap(
+ await this.client.agentHarness.getAgentSessionChanges({
+ path: { session_id: this.id },
+ }),
+ );
+ }
+
+ /** Read the unified diff of the latest captured changeset. */
+ async changesPatch(): Promise<string> {
+ return unwrap(
+ await this.client.agentHarness.getAgentSessionChangesPatch({
+ path: { session_id: this.id },
+ }),
+ ).patch;
+ }
+
+ /** Request a fresh capture and return the current state while it runs. */
+ async refreshChanges(): Promise<AgentSessionChangesResponse> {
+ return this.mutate((client) =>
+ client.agentHarness.refreshAgentSessionChanges({
+ path: { session_id: this.id },
+ }),
+ );
+ }
+
/** Read the complete raw protocol log for this session. */
async log(): Promise<AgentSessionLogResponse> {
return unwrap(
diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.ts
index 7ddfb2bf1d..99f9064632 100644
--- a/packages/sdk/tests/agent-sessions.test.ts
+++ b/packages/sdk/tests/agent-sessions.test.ts
@@ -1,5 +1,8 @@
import { afterEach, describe, expect, test } from 'bun:test';
-import type { AgentSessionResponse } from '../generated/agent-harness/types.gen';
+import type {
+ AgentSessionChangesResponse,
+ AgentSessionResponse,
+} from '../generated/agent-harness/types.gen';
import { Macro } from '../src/macro';
const originalFetch = globalThis.fetch;
@@ -24,6 +27,76 @@ afterEach(() => {
});
describe('AgentSession', () => {
+ test('reads fresh changes and patch data and requests asynchronous capture', async () => {
+ const requests: Request[] = [];
+ const snapshot: AgentSessionChangesResponse = {
+ capturing: false,
+ changeset: null,
+ attempt: null,
+ };
+ const patch = 'diff --git a/file.txt b/file.txt\n';
+ globalThis.fetch = (async (input) => {
+ const request = input instanceof Request ? input : new Request(input);
+ requests.push(request);
+ if (request.url.endsWith('/patch')) {
+ return Response.json({ patch });
+ }
+ if (request.url.endsWith('/refresh')) {
+ snapshot.capturing = true;
+ return Response.json(snapshot, { status: 202 });
+ }
+ return Response.json(snapshot);
+ }) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+ const agent = macro.agentSessions.byId(sessionId);
+
+ await expect(agent.changes()).resolves.toEqual(snapshot);
+ await expect(agent.changesPatch()).resolves.toBe(patch);
+ await expect(agent.refreshChanges()).resolves.toMatchObject({
+ capturing: true,
+ });
+ await expect(agent.changes()).resolves.toMatchObject({ capturing: true });
+
+ const base = `https://agent.example.test/agent-sessions/${sessionId}/changes`;
+ expect(requests.map((request) => [request.method, request.url])).toEqual([
+ ['GET', base],
+ ['GET', `${base}/patch`],
+ ['POST', `${base}/refresh`],
+ ['GET', base],
+ ]);
+ expect(
+ requests.every(
+ (request) =>
+ request.headers.get('authorization') === 'Bearer user-token',
+ ),
+ ).toBe(true);
+ });
+
+ test('preserves access errors from changes endpoints', async () => {
+ globalThis.fetch = (async (_input) =>
+ Response.json({ message: 'Forbidden' }, { status: 403 })) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+ const agent = macro.agentSessions.byId(sessionId);
+
+ for (const read of [
+ () => agent.changes(),
+ () => agent.changesPatch(),
+ () => agent.refreshChanges(),
+ ]) {
+ await expect(read()).rejects.toMatchObject({
+ name: 'MacroApiError',
+ status: 403,
+ data: { message: 'Forbidden' },
+ });
+ }
+ });
+
test('renames through the agent-harness service with user auth', async () => {
let request: Request | undefined;
globalThis.fetch = (async (input) => {
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index 3d13f16ca0..a2005291f8 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -20,6 +20,7 @@ files:
- apps/web/src/features/email-message/components/**
- apps/web/src/features/email-thread/components/**
- apps/web/src/features/email-compose/components/**
+ - apps/web/src/features/agent-changes/components/**
rule:
any:
- kind: string
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 73586f180a..2665eaafc7 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -22,6 +22,7 @@ files:
- apps/web/src/features/email-message/core/**
- apps/web/src/features/email-thread/core/**
- apps/web/src/features/email-compose/core/**
+ - apps/web/src/features/agent-changes/core/**
rule:
kind: string
regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views)/|(\.\./)+context/)
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index 1af8a679cb..c3e055b227 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -26,6 +26,8 @@ files:
- apps/web/src/features/email-thread/primitives/**
- apps/web/src/features/email-compose/queries/**
- apps/web/src/features/email-compose/primitives/**
+ - apps/web/src/features/agent-changes/queries/**
+ - apps/web/src/features/agent-changes/primitives/**
rule:
kind: string
regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views)/)
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index af75a93d63..c7c8483a93 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -44,6 +44,10 @@ files:
- apps/web/src/features/email-compose/queries/**
- apps/web/src/features/email-compose/primitives/**
- apps/web/src/features/email-compose/views/**
+ - apps/web/src/features/agent-changes/components/**
+ - apps/web/src/features/agent-changes/queries/**
+ - apps/web/src/features/agent-changes/primitives/**
+ - apps/web/src/features/agent-changes/views/**
rule:
kind: string
regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index 0136dc43de..e3e774e94c 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -20,6 +20,7 @@ files:
- apps/web/src/features/email-message/components/**
- apps/web/src/features/email-thread/components/**
- apps/web/src/features/email-compose/components/**
+ - apps/web/src/features/agent-changes/components/**
rule:
any:
- kind: string
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index f94a60ce3d..d95046be0c 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -22,6 +22,7 @@ files:
- apps/web/src/features/email-message/core/**
- apps/web/src/features/email-thread/core/**
- apps/web/src/features/email-compose/core/**
+ - apps/web/src/features/agent-changes/core/**
rule:
kind: string
regex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views)/|(\.\./)+context/)
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 669e9ad689..e68a80a10a 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -26,6 +26,8 @@ files:
- apps/web/src/features/email-thread/primitives/**
- apps/web/src/features/email-compose/queries/**
- apps/web/src/features/email-compose/primitives/**
+ - apps/web/src/features/agent-changes/queries/**
+ - apps/web/src/features/agent-changes/primitives/**
rule:
kind: string
regex: ^['"](solid-js/web|@ui|@components/|(\.\./)+(components|views)/)
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index b2fa1f4b88..b8ba8c6be4 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -44,6 +44,10 @@ files:
- apps/web/src/features/email-compose/queries/**
- apps/web/src/features/email-compose/primitives/**
- apps/web/src/features/email-compose/views/**
+ - apps/web/src/features/agent-changes/components/**
+ - apps/web/src/features/agent-changes/queries/**
+ - apps/web/src/features/agent-changes/primitives/**
+ - apps/web/src/features/agent-changes/views/**
rule:
kind: string
regex: ^['"](@service-storage/graphql-soup|@core/context/user|@core/user|@property/hooks|@property/editor/hooks|@core/component/LexicalMarkdown/component/core/BlockLink|@app/lib/analytics/posthog)
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index d6cdd05b18..44cc8d0e66 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -19,6 +19,7 @@ path = "src/doppler_config.rs"
[dependencies]
codex_cloud_agents = { path = "../../crates/codex_cloud_agents" }
codex_connection = { path = "../../crates/codex_connection" }
+agent_changes = { path = "../../crates/agent_changes" }
agent_egress = { path = "../../crates/agent_egress" }
agent_fold = { path = "../../crates/agent_fold" }
agent_harness = { path = "../../crates/agent_harness" }
@@ -51,7 +52,7 @@ github = { path = "../../crates/github", default-features = false, features = [
pipedream_mcp = { path = "../../crates/pipedream_mcp" }
url = { workspace = true }
contacts = { path = "../../crates/contacts" }
-macro_aws_config = { path = "../../crates/macro_aws_config" }
+macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }
macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }
macro_queues = { path = "../../crates/macro_queues" }
lexical_client = { path = "../../crates/lexical_client" }
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 45f7f3ecea..e3b7ffc1b1 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -5,6 +5,8 @@
use std::time::Duration;
+use agent_changes::domain::service::AgentChanges;
+use agent_changes::inbound::axum_router::{AgentChangesRouterState, agent_changes_router};
use agent_egress::domain::service::EgressService;
use agent_egress::inbound::axum_router::{EgressRouterState, egress_router};
use agent_harness::domain::model_load::AgentModelsService;
@@ -59,7 +61,7 @@ fn health_router(ready: tokio::sync::watch::Receiver<bool>) -> Router {
}
/// All route state served by the public agent-harness HTTP listener.
-pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models> {
+pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes> {
read: AgentSessionRouterState<T, Access, Auth>,
control: AgentSessionControlState<R, Access, Auth>,
create: CreateSessionState<Opener, Bots, Auth>,
@@ -67,9 +69,12 @@ pub struct ApiStates<T, R, Opener, Bots, Access, Auth, Models> {
models: AgentModelsRouterState<Models, Auth>,
repositories: AgentRepositoriesRouterState<Auth>,
claude_auth: Router,
+ changes: AgentChangesRouterState<Changes, Access, Auth>,
}
-impl<T, R, Opener, Bots, Access, Auth, Models> ApiStates<T, R, Opener, Bots, Access, Auth, Models> {
+impl<T, R, Opener, Bots, Access, Auth, Models, Changes>
+ ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes>
+{
/// Group the independently constructed route states for the HTTP server.
pub fn new(
read: AgentSessionRouterState<T, Access, Auth>,
@@ -78,6 +83,7 @@ impl<T, R, Opener, Bots, Access, Auth, Models> ApiStates<T, R, Opener, Bots, Acc
gateway: RuntimeGatewayState<Auth>,
models: AgentModelsRouterState<Models, Auth>,
repositories: AgentRepositoriesRouterState<Auth>,
+ changes: AgentChangesRouterState<Changes, Access, Auth>,
) -> Self {
Self {
read,
@@ -87,6 +93,7 @@ impl<T, R, Opener, Bots, Access, Auth, Models> ApiStates<T, R, Opener, Bots, Acc
models,
repositories,
claude_auth: Router::new(),
+ changes,
}
}
@@ -128,8 +135,8 @@ where
}
/// Build the router and serve it until the process is asked to stop.
-pub async fn setup_and_serve<T, R, Opener, Bots, Access, Auth, Models>(
- states: ApiStates<T, R, Opener, Bots, Access, Auth, Models>,
+pub async fn setup_and_serve<T, R, Opener, Bots, Access, Auth, Models, Changes>(
+ states: ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes>,
runtime_commands_ready: tokio::sync::watch::Receiver<bool>,
port: u16,
shutdown: impl Future<Output = ()> + Send + 'static,
@@ -142,6 +149,7 @@ where
Access: EntityAccessService,
Auth: MacroAuthorizationService,
Models: AgentModelsService,
+ Changes: AgentChanges,
{
let inner = api_router(states)
.layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())
@@ -166,8 +174,8 @@ where
.context("agent harness service http failed")
}
-fn api_router<T, R, Opener, Bots, Access, Auth, Models>(
- states: ApiStates<T, R, Opener, Bots, Access, Auth, Models>,
+fn api_router<T, R, Opener, Bots, Access, Auth, Models, Changes>(
+ states: ApiStates<T, R, Opener, Bots, Access, Auth, Models, Changes>,
) -> Router
where
T: AgentSessionService,
@@ -177,10 +185,12 @@ where
Access: EntityAccessService,
Auth: MacroAuthorizationService,
Models: AgentModelsService,
+ Changes: AgentChanges,
{
let agent_sessions = agent_session_read_router(states.read.clone())
.merge(agent_session_control_router(states.control))
- .merge(agent_session_create_router(states.create));
+ .merge(agent_session_create_router(states.create))
+ .merge(agent_changes_router(states.changes));
Router::new()
.nest("/agent-sessions", agent_sessions)
.merge(agent_sandbox_size_router(states.read))
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index e1d1641071..682e333b72 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -1,5 +1,10 @@
//! OpenAPI document for the agent harness service's session routes.
+use agent_changes::inbound::axum_router::{
+ self as changes_router, AgentSessionChangesPatchResponse, AgentSessionChangesResponse,
+ CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto,
+ FileChangeKindDto, GitRefDto,
+};
use agent_harness::inbound::model_load::{
self, AgentModelDto, AgentModelsStatusDto, LoadAgentModelsRequest, LoadAgentModelsResponse,
ModelHarnessDto,
@@ -58,6 +63,9 @@ impl Modify for SecurityAddon {
axum_router::put_agent_sandbox_size_handler,
model_load::load_agent_models_handler,
repositories::list_agent_repositories_handler,
+ changes_router::get_agent_session_changes_handler,
+ changes_router::get_agent_session_changes_patch_handler,
+ changes_router::refresh_agent_session_changes_handler,
),
components(schemas(
claude_auth::StatusResponse,
@@ -98,6 +106,15 @@ impl Modify for SecurityAddon {
ModelHarnessDto,
AgentRepositoriesResponse,
AgentRepositoryDto,
+ AgentSessionChangesResponse,
+ AgentSessionChangesPatchResponse,
+ ChangesetDto,
+ ChangedFileDto,
+ GitRefDto,
+ CaptureAttemptDto,
+ CaptureOutcomeDto,
+ ChangesetSourceDto,
+ FileChangeKindDto,
)),
tags(
(name = "agent-sessions", description = "Agent sessions"),
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index 722592d990..acae3709a4 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -175,6 +175,11 @@ pub struct Config {
pub macro_api_token_private_secret_key: LocalOrRemoteSecret<MacroApiTokenPrivateSecretKey>,
/// Issuer stamped into minted Macro API tokens.
pub macro_api_token_issuer: MacroApiTokenIssuer,
+ /// S3 bucket the Changes pane's patches are stored in, one object per
+ /// capture under `agent-sessions/{session}/changes/`. Required: a
+ /// harness that cannot store a patch cannot show a session's changes,
+ /// and that is worth failing at boot rather than on the first capture.
+ pub agent_session_changes_bucket: String,
/// Client id of the GitHub App installation tokens are minted for.
pub github_sync_app_client_id: String,
/// PEM private key of that App.
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 728b0005b5..54c2453337 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -23,6 +23,12 @@ mod test;
use std::{future::Future, pin::Pin, sync::Arc};
+use agent_changes::domain::pull_request::PullRequestChanges;
+use agent_changes::domain::service::{AgentChangesService, CaptureOnTurnEnd};
+use agent_changes::inbound::axum_router::AgentChangesRouterState;
+use agent_changes::outbound::github_pull_request::GithubPullRequestDiff;
+use agent_changes::outbound::postgres::PgChangesetRepo;
+use agent_changes::outbound::s3::S3ChangesetBlobStore;
use agent_egress::domain::service::EgressServiceImpl;
use agent_egress::outbound::forwarder::ReqwestForwarder;
use agent_egress::outbound::github_tokens::GithubAppTokens;
@@ -827,12 +833,37 @@ async fn run() -> anyhow::Result<()> {
)
.with_repositories(open_repositories),
);
- // Close the loop: turn ends observed by the session actors drain the
- // harness's prompt queue.
- turn_observer.bind(harness.clone());
let model_probe_timeout = std::time::Duration::from_secs(10);
let macrod_models =
MacrodModels::new(Arc::clone(&runtimes), redis.clone(), model_probe_timeout);
+
+ // Capture only the session's linked GitHub pull request, for every harness.
+ let changes_extractor =
+ PullRequestChanges::new(GithubPullRequestDiff::new(InstallationTokenService::new(
+ InstallationTokenConfig {
+ client_id: config.github_sync_app_client_id.clone(),
+ private_key_pem: config.github_sync_app_pem_secret_key.as_ref().to_owned(),
+ },
+ PgGithubSyncRepo::new(pool.clone()),
+ GithubSyncClientImpl::default(),
+ )));
+ let changes = AgentChangesService::new(
+ session_repo.clone(),
+ changes_extractor,
+ PgChangesetRepo::new(pool.clone()),
+ S3ChangesetBlobStore::new(
+ macro_aws_config::s3_client().await,
+ config.agent_session_changes_bucket.clone(),
+ ),
+ ConnectionGatewayAgentSessionRealtime::new(
+ connection_gateway.clone(),
+ session_repo.clone(),
+ ),
+ );
+
+ // Close the loop: turn ends observed by the session actors drain the
+ // harness's prompt queue, and capture what the turn changed.
+ turn_observer.bind((harness.clone(), CaptureOnTurnEnd::new(changes.clone())));
let runtime_command_models = macrod_models.clone();
let runtime_command_redis = redis.clone();
let runtime_command_harness = harness.clone();
@@ -923,6 +954,11 @@ async fn run() -> anyhow::Result<()> {
entity_access.clone(),
MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
);
+ let changes_state = AgentChangesRouterState::new(
+ changes,
+ entity_access.clone(),
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ );
let control_state = AgentSessionControlState::new(
harness.clone(),
entity_access,
@@ -964,6 +1000,7 @@ async fn run() -> anyhow::Result<()> {
gateway_state,
model_state,
repositories_state,
+ changes_state,
)
.with_claude_auth(claude_auth),
http_runtime_commands_readiness,
diff --git a/tooling/just/local_stack.just b/tooling/just/local_stack.just
index 448c85b049..ce6dd30c3a 100644
--- a/tooling/just/local_stack.just
+++ b/tooling/just/local_stack.just
@@ -164,8 +164,9 @@ create_local_buckets:
aws --endpoint-url=http://localhost:4566 s3 mb s3://static-file-storage || true
aws --endpoint-url=http://localhost:4566 s3 mb s3://bulk-upload-staging || true
aws --endpoint-url=http://localhost:4566 s3 mb s3://macro-call-recording-local || true
+ aws --endpoint-url=http://localhost:4566 s3 mb s3://agent-session-changes || true
# Apply CORS configuration to all buckets
- for bucket in macro-email-attachments doc-storage docx-upload static-file-storage bulk-upload-staging macro-call-recording-local; do \
+ for bucket in macro-email-attachments doc-storage docx-upload static-file-storage bulk-upload-staging macro-call-recording-local agent-session-changes; do \
aws --endpoint-url=http://localhost:4566 s3api put-bucket-cors --bucket $bucket --cors-configuration '{"CORSRules":[{"AllowedOrigins":["http://localhost:3000","http://localhost:3001","http://localhost:3002","http://localhost:3003","http://localhost:3004","http://localhost:3005","http://localhost:3006","http://localhost:3007","http://localhost:3008","http://localhost:3009"],"AllowedMethods":["GET","PUT","POST","DELETE","HEAD"],"AllowedHeaders":["*"],"ExposeHeaders":["ETag"],"MaxAgeSeconds":3600}]}' || true; \
done
@echo "S3 buckets created"
diff --git a/tooling/xtask/crates/xtask_local/src/local/resources.rs b/tooling/xtask/crates/xtask_local/src/local/resources.rs
index 69b14a50dd..67a3174aed 100644
--- a/tooling/xtask/crates/xtask_local/src/local/resources.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/resources.rs
@@ -253,6 +253,11 @@ pub const BUCKETS: &[Bucket] = &[
name: "macro-call-recording-local",
env_key: "CALL_RECORDING_BUCKET_NAME",
},
+ Bucket {
+ // The patch behind each agent session's Changes pane.
+ name: "agent-session-changes",
+ env_key: "AGENT_SESSION_CHANGES_BUCKET",
+ },
];
/// Every local DynamoDB table and the env var that references it.