Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): track coding sessions with Macro tasks (#7786)
Wolf Mermelsteinc41413a77a69
diff --git a/.sqlx/query-1b2b28550601cb03ea0b84b42fb18d07e1ea512c3fb7c481ada844ad08f6e240.json b/.sqlx/query-1b2b28550601cb03ea0b84b42fb18d07e1ea512c3fb7c481ada844ad08f6e240.jsonnew file mode 100644index 0000000000..d0773e3718--- /dev/null+++ b/.sqlx/query-1b2b28550601cb03ea0b84b42fb18d07e1ea512c3fb7c481ada844ad08f6e240.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO user_agent_coding_preferences\n (user_id, create_tasks, open_pull_requests, modified_at)\n VALUES ($1, $2, $3, NOW())\n ON CONFLICT (user_id) DO UPDATE\n SET create_tasks = EXCLUDED.create_tasks,\n open_pull_requests = EXCLUDED.open_pull_requests,\n modified_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Bool",+ "Bool"+ ]+ },+ "nullable": []+ },+ "hash": "1b2b28550601cb03ea0b84b42fb18d07e1ea512c3fb7c481ada844ad08f6e240"+}diff --git a/.sqlx/query-8dc30429ce9c14dfb2514d42b3c7aec759513d74a84cef29a63bf5e9950c126f.json b/.sqlx/query-3431359bc44b69d54fd87185424df866071761d35a7c45637cb5f2d4eb14cc9b.jsonsimilarity index 75%rename from .sqlx/query-8dc30429ce9c14dfb2514d42b3c7aec759513d74a84cef29a63bf5e9950c126f.jsonrename to .sqlx/query-3431359bc44b69d54fd87185424df866071761d35a7c45637cb5f2d4eb14cc9b.jsonindex 987b2baffd..f3251d7fe7 100644--- a/.sqlx/query-8dc30429ce9c14dfb2514d42b3c7aec759513d74a84cef29a63bf5e9950c126f.json+++ b/.sqlx/query-3431359bc44b69d54fd87185424df866071761d35a7c45637cb5f2d4eb14cc9b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",+ "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -65,87 +65,93 @@},{"ordinal": 12,- "name": "workspace",+ "name": "task_id","type_info": "Text"},{"ordinal": 13,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 14,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 15,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 16,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 17,+ "ordinal": 18,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "status","type_info": "Text"},{- "ordinal": 19,+ "ordinal": 20,"name": "status_event_name","type_info": "Text"},{- "ordinal": 20,+ "ordinal": 21,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 21,+ "ordinal": 22,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 22,+ "ordinal": 23,"name": "thread_parent?: Json<MessageParent>","type_info": "Jsonb"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_provider?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_id?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_name?","type_info": "Text"},{- "ordinal": 26,+ "ordinal": 27,"name": "external_url?","type_info": "Text"},{- "ordinal": 27,+ "ordinal": 28,"name": "external_last_run_id?","type_info": "Text"}],"parameters": {"Left": [+ "Uuid","Uuid"]},@@ -162,6 +168,7 @@true,true,true,+ true,false,false,true,@@ -180,5 +187,5 @@true]},- "hash": "8dc30429ce9c14dfb2514d42b3c7aec759513d74a84cef29a63bf5e9950c126f"+ "hash": "3431359bc44b69d54fd87185424df866071761d35a7c45637cb5f2d4eb14cc9b"}diff --git a/.sqlx/query-481b55ce6c07d52cc7735412db49e576d605ac3ca2e7d2c381c0f73071677bed.json b/.sqlx/query-481b55ce6c07d52cc7735412db49e576d605ac3ca2e7d2c381c0f73071677bed.jsonnew file mode 100644index 0000000000..968dfa713a--- /dev/null+++ b/.sqlx/query-481b55ce6c07d52cc7735412db49e576d605ac3ca2e7d2c381c0f73071677bed.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT task_id FROM agent_session WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "481b55ce6c07d52cc7735412db49e576d605ac3ca2e7d2c381c0f73071677bed"+}diff --git a/.sqlx/query-54e898a564f27deb66caca710182ee38ba1033dc9a075d707fa187dde5a7477a.json b/.sqlx/query-54e898a564f27deb66caca710182ee38ba1033dc9a075d707fa187dde5a7477a.jsonnew file mode 100644index 0000000000..44e4adeb17--- /dev/null+++ b/.sqlx/query-54e898a564f27deb66caca710182ee38ba1033dc9a075d707fa187dde5a7477a.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT create_tasks, open_pull_requests\n FROM user_agent_coding_preferences\n WHERE user_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "create_tasks",+ "type_info": "Bool"+ },+ {+ "ordinal": 1,+ "name": "open_pull_requests",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "54e898a564f27deb66caca710182ee38ba1033dc9a075d707fa187dde5a7477a"+}diff --git a/.sqlx/query-4646f5f31d84223038f11e0277fc6816eab6d32e25d0c3e6997538f48ddd0cab.json b/.sqlx/query-553a02988454f56c4e8d6ceea4002406a5492a8fb26972d090e838f72a67b9c8.jsonsimilarity index 77%rename from .sqlx/query-4646f5f31d84223038f11e0277fc6816eab6d32e25d0c3e6997538f48ddd0cab.jsonrename to .sqlx/query-553a02988454f56c4e8d6ceea4002406a5492a8fb26972d090e838f72a67b9c8.jsonindex 38f28efa7b..6354d30361 100644--- a/.sqlx/query-4646f5f31d84223038f11e0277fc6816eab6d32e25d0c3e6997538f48ddd0cab.json+++ b/.sqlx/query-553a02988454f56c4e8d6ceea4002406a5492a8fb26972d090e838f72a67b9c8.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",+ "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ","describe": {"columns": [{@@ -65,81 +65,86 @@},{"ordinal": 12,- "name": "workspace",+ "name": "task_id","type_info": "Text"},{"ordinal": 13,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 14,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 15,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 16,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 17,+ "ordinal": 18,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "status","type_info": "Text"},{- "ordinal": 19,+ "ordinal": 20,"name": "status_event_name","type_info": "Text"},{- "ordinal": 20,+ "ordinal": 21,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 21,+ "ordinal": 22,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 22,+ "ordinal": 23,"name": "thread_parent?: Json<MessageParent>","type_info": "Jsonb"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_provider?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_id?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_name?","type_info": "Text"},{- "ordinal": 26,+ "ordinal": 27,"name": "external_url?","type_info": "Text"},{- "ordinal": 27,+ "ordinal": 28,"name": "external_last_run_id?","type_info": "Text"}@@ -162,6 +167,7 @@true,true,true,+ true,false,false,true,@@ -180,5 +186,5 @@true]},- "hash": "4646f5f31d84223038f11e0277fc6816eab6d32e25d0c3e6997538f48ddd0cab"+ "hash": "553a02988454f56c4e8d6ceea4002406a5492a8fb26972d090e838f72a67b9c8"}diff --git a/.sqlx/query-c796786824c01c944b84a2afc7204b7e87b307499db387ed3796cc74b41dc4cf.json b/.sqlx/query-557aa6c3589bd3743acacf09681b3da5ecf2d6ebfb4442ce1941a60913d22026.jsonsimilarity index 75%rename from .sqlx/query-c796786824c01c944b84a2afc7204b7e87b307499db387ed3796cc74b41dc4cf.jsonrename to .sqlx/query-557aa6c3589bd3743acacf09681b3da5ecf2d6ebfb4442ce1941a60913d22026.jsonindex 0a2efb3b1c..3384bf4044 100644--- a/.sqlx/query-c796786824c01c944b84a2afc7204b7e87b307499db387ed3796cc74b41dc4cf.json+++ b/.sqlx/query-557aa6c3589bd3743acacf09681b3da5ecf2d6ebfb4442ce1941a60913d22026.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1 AND NOT list_hidden\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ",+ "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1 AND NOT list_hidden\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ","describe": {"columns": [{@@ -65,81 +65,86 @@},{"ordinal": 12,- "name": "workspace",+ "name": "task_id","type_info": "Text"},{"ordinal": 13,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 14,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 15,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 16,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 17,+ "ordinal": 18,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "status","type_info": "Text"},{- "ordinal": 19,+ "ordinal": 20,"name": "status_event_name","type_info": "Text"},{- "ordinal": 20,+ "ordinal": 21,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 21,+ "ordinal": 22,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 22,+ "ordinal": 23,"name": "thread_parent?: Json<MessageParent>","type_info": "Jsonb"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_provider?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_id?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_name?","type_info": "Text"},{- "ordinal": 26,+ "ordinal": 27,"name": "external_url?","type_info": "Text"},{- "ordinal": 27,+ "ordinal": 28,"name": "external_last_run_id?","type_info": "Text"}@@ -163,6 +168,7 @@true,true,true,+ true,false,false,true,@@ -181,5 +187,5 @@true]},- "hash": "c796786824c01c944b84a2afc7204b7e87b307499db387ed3796cc74b41dc4cf"+ "hash": "557aa6c3589bd3743acacf09681b3da5ecf2d6ebfb4442ce1941a60913d22026"}diff --git a/.sqlx/query-c9eb98ee4c4b8a8b651fb2fa1554b2f43009a14236863883043b240a9b8f6da3.json b/.sqlx/query-6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8.jsonsimilarity index 81%rename from .sqlx/query-c9eb98ee4c4b8a8b651fb2fa1554b2f43009a14236863883043b240a9b8f6da3.jsonrename to .sqlx/query-6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8.jsonindex 587919c163..2f998c76e8 100644--- a/.sqlx/query-c9eb98ee4c4b8a8b651fb2fa1554b2f43009a14236863883043b240a9b8f6da3.json+++ b/.sqlx/query-6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch, list_hidden\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)\n RETURNING\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers, repo_branch, list_hidden\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)\n RETURNING\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ","describe": {"columns": [{@@ -65,81 +65,86 @@},{"ordinal": 12,- "name": "workspace",+ "name": "task_id","type_info": "Text"},{"ordinal": 13,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 14,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 15,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 16,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 17,+ "ordinal": 18,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "status","type_info": "Text"},{- "ordinal": 19,+ "ordinal": 20,"name": "status_event_name","type_info": "Text"},{- "ordinal": 20,+ "ordinal": 21,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 21,+ "ordinal": 22,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 22,+ "ordinal": 23,"name": "thread_parent?: Json<MessageParent>","type_info": "Jsonb"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_provider?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_id?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_name?","type_info": "Text"},{- "ordinal": 26,+ "ordinal": 27,"name": "external_url?","type_info": "Text"},{- "ordinal": 27,+ "ordinal": 28,"name": "external_last_run_id?","type_info": "Text"}@@ -180,6 +185,7 @@true,true,true,+ true,false,false,true,@@ -198,5 +204,5 @@null]},- "hash": "c9eb98ee4c4b8a8b651fb2fa1554b2f43009a14236863883043b240a9b8f6da3"+ "hash": "6a52abe1389d8efde828f53d38e951e03722c8b77c20830d4fd33ede1f9ca8b8"}diff --git a/.sqlx/query-a6f12d99ef18281686a45ec4afe1615ca96202ee4707c88bb36a9c5c8cc3adac.json b/.sqlx/query-a6f12d99ef18281686a45ec4afe1615ca96202ee4707c88bb36a9c5c8cc3adac.jsonnew file mode 100644index 0000000000..aa84aba46f--- /dev/null+++ b/.sqlx/query-a6f12d99ef18281686a45ec4afe1615ca96202ee4707c88bb36a9c5c8cc3adac.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE agent_session AS session SET task_id = $3\n FROM (\n SELECT id, task_id FROM agent_session WHERE id = $1 AND owner_id = $2 FOR UPDATE\n ) AS previous\n WHERE session.id = previous.id\n RETURNING\n session.pull_request_url,\n previous.task_id IS DISTINCT FROM $3 AS \"changed!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "pull_request_url",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "changed!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ true,+ null+ ]+ },+ "hash": "a6f12d99ef18281686a45ec4afe1615ca96202ee4707c88bb36a9c5c8cc3adac"+}diff --git a/.sqlx/query-0d28246f8f16ef4940690afa9d053c7afd5c83b3ed94d642858849470beb8648.json b/.sqlx/query-a8b7f8732340ab7b5cbeda5d87bd4aaa3eb1449480c2b86c7593096b47488ced.jsonsimilarity index 76%rename from .sqlx/query-0d28246f8f16ef4940690afa9d053c7afd5c83b3ed94d642858849470beb8648.jsonrename to .sqlx/query-a8b7f8732340ab7b5cbeda5d87bd4aaa3eb1449480c2b86c7593096b47488ced.jsonindex 51a3b158c9..b5ae26c4b0 100644--- a/.sqlx/query-0d28246f8f16ef4940690afa9d053c7afd5c83b3ed94d642858849470beb8648.json+++ b/.sqlx/query-a8b7f8732340ab7b5cbeda5d87bd4aaa3eb1449480c2b86c7593096b47488ced.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",+ "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ","describe": {"columns": [{@@ -65,81 +65,86 @@},{"ordinal": 12,- "name": "workspace",+ "name": "task_id","type_info": "Text"},{"ordinal": 13,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 14,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 15,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 16,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 17,+ "ordinal": 18,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "status","type_info": "Text"},{- "ordinal": 19,+ "ordinal": 20,"name": "status_event_name","type_info": "Text"},{- "ordinal": 20,+ "ordinal": 21,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 21,+ "ordinal": 22,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 22,+ "ordinal": 23,"name": "thread_parent?: Json<MessageParent>","type_info": "Jsonb"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_provider?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_id?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_name?","type_info": "Text"},{- "ordinal": 26,+ "ordinal": 27,"name": "external_url?","type_info": "Text"},{- "ordinal": 27,+ "ordinal": 28,"name": "external_last_run_id?","type_info": "Text"}@@ -162,6 +167,7 @@true,true,true,+ true,false,false,true,@@ -180,5 +186,5 @@true]},- "hash": "0d28246f8f16ef4940690afa9d053c7afd5c83b3ed94d642858849470beb8648"+ "hash": "a8b7f8732340ab7b5cbeda5d87bd4aaa3eb1449480c2b86c7593096b47488ced"}diff --git a/.sqlx/query-e4983e95ae23b4db4e9048ff194dfda1280339ca295d60cb5d585cd4f57e028b.json b/.sqlx/query-aad9a171729640b7d27b4c1ce9c93a66d31fddb966efcc7519b1885f4add7151.jsonsimilarity index 76%rename from .sqlx/query-e4983e95ae23b4db4e9048ff194dfda1280339ca295d60cb5d585cd4f57e028b.jsonrename to .sqlx/query-aad9a171729640b7d27b4c1ce9c93a66d31fddb966efcc7519b1885f4add7151.jsonindex fc3745049f..535baef49b 100644--- a/.sqlx/query-e4983e95ae23b4db4e9048ff194dfda1280339ca295d60cb5d585cd4f57e028b.json+++ b/.sqlx/query-aad9a171729640b7d27b4c1ce9c93a66d31fddb966efcc7519b1885f4add7151.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",+ "query": "\n SELECT\n id, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,\n mcp_scope, mcp_servers, acp_session_id, status,\n status_event_name, agent_session.created_at, modified_at,\n (SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)\n FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_parent?: Json<MessageParent>\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ","describe": {"columns": [{@@ -65,88 +65,92 @@},{"ordinal": 12,- "name": "workspace",+ "name": "task_id","type_info": "Text"},{"ordinal": 13,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 14,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 15,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 16,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 17,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 17,+ "ordinal": 18,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "status","type_info": "Text"},{- "ordinal": 19,+ "ordinal": 20,"name": "status_event_name","type_info": "Text"},{- "ordinal": 20,+ "ordinal": 21,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 21,+ "ordinal": 22,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 22,+ "ordinal": 23,"name": "thread_parent?: Json<MessageParent>","type_info": "Jsonb"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_provider?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_id?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_name?","type_info": "Text"},{- "ordinal": 26,+ "ordinal": 27,"name": "external_url?","type_info": "Text"},{- "ordinal": 27,+ "ordinal": 28,"name": "external_last_run_id?","type_info": "Text"}],"parameters": {"Left": [- "Uuid","Uuid"]},@@ -163,6 +167,7 @@true,true,true,+ true,false,false,true,@@ -181,5 +186,5 @@true]},- "hash": "e4983e95ae23b4db4e9048ff194dfda1280339ca295d60cb5d585cd4f57e028b"+ "hash": "aad9a171729640b7d27b4c1ce9c93a66d31fddb966efcc7519b1885f4add7151"}diff --git a/.sqlx/query-b6e125ba0b0f93c18df1b062840b3fd1d35bafd547fc67e264b5f4f0517d5da7.json b/.sqlx/query-b6e125ba0b0f93c18df1b062840b3fd1d35bafd547fc67e264b5f4f0517d5da7.jsonnew file mode 100644index 0000000000..7fc5095361--- /dev/null+++ b/.sqlx/query-b6e125ba0b0f93c18df1b062840b3fd1d35bafd547fc67e264b5f4f0517d5da7.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT t.slug AS \"team_slug!\", tt.task_num\n FROM team_task tt\n JOIN team t ON t.id = tt.team_id\n WHERE tt.document_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_slug!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 1,+ "name": "task_num",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "b6e125ba0b0f93c18df1b062840b3fd1d35bafd547fc67e264b5f4f0517d5da7"+}diff --git a/Cargo.lock b/Cargo.lockindex c75f273101..dbba84568b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -351,6 +351,7 @@ dependencies = ["cursor_api_key","cursor_cloud_agents","dashmap",+ "documents","entity_access","entity_access_db_utils","futures",@@ -367,6 +368,7 @@ dependencies = ["mcp_client","messages","mockall",+ "model","model-entity","model_notifications","model_owner",diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsxindex 9b18130995..6841d80352 100644--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx@@ -7,6 +7,7 @@ import {agentSessionFileOperations,agentSessionTitle,} from '@app/features/block-agent/component/AgentSplitHeader';+import { AgentTaskChip } from '@app/features/block-agent/component/AgentTaskChip';import { ArchivedSessionFooter } from '@app/features/block-agent/component/ArchivedSessionFooter';import { AgentSidePanelSections } from '@app/features/block-agent/component/sidepanel/AgentSidePanelSections';import { Transcript } from '@app/features/block-agent/component/Transcript';@@ -208,6 +209,9 @@ function SessionContent(props: {</>}>+ <Show when={session()?.taskId}>+ {(taskId) => <AgentTaskChip taskId={taskId()} />}+ </Show><Show when={session()?.pullRequestUrl}>{(url) => <AgentPullRequestChip url={url()} />}</Show>diff --git a/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsx b/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsxindex b837edc48e..fb41d67b1a 100644--- a/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsx+++ b/apps/web/src/features/block-agent/component/AgentPullRequestChip.tsx@@ -18,14 +18,9 @@ import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler'import { usePullRequestByGithubKeyQuery } from '@queries/storage/pr-mention';import type { ForeignEntity } from '@service-storage/generated/schemas';import { cn, Layer } from '@ui';-import {- type Accessor,- createMemo,- type JSX,- type ParentProps,- Show,-} from 'solid-js';+import { type Accessor, createMemo, type JSX, Show } from 'solid-js';import { match } from 'ts-pattern';+import { ChipShell } from './AgentSessionChipShell';function metadataRecord(metadata: unknown): Record<string, unknown> {if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {@@ -92,15 +87,6 @@ function ChipFace(props: {);}-/** Shared pill chrome for the GitHub fallback and the entity button. */-function ChipShell(props: ParentProps): JSX.Element {- return (- <span class="inline-flex h-7 max-w-44 min-w-0 items-center gap-1 rounded-full border border-edge-muted bg-surface px-2 text-xs leading-none text-ink-muted hover:bg-hover hover:text-ink">- {props.children}- </span>- );-}-function GithubFallback(props: { url: string; number?: number }): JSX.Element {return (<adiff --git a/apps/web/src/features/block-agent/component/AgentSessionChipShell.tsx b/apps/web/src/features/block-agent/component/AgentSessionChipShell.tsxnew file mode 100644index 0000000000..819f0190ec--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentSessionChipShell.tsx@@ -0,0 +1,10 @@+import type { JSX, ParentProps } from 'solid-js';++/** Pill chrome shared by the session header chips. */+export function ChipShell(props: ParentProps): JSX.Element {+ return (+ <span class="inline-flex h-7 max-w-44 min-w-0 items-center gap-1 rounded-full border border-edge-muted bg-surface px-2 text-xs leading-none text-ink-muted hover:bg-hover hover:text-ink">+ {props.children}+ </span>+ );+}diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex 5392fb5efe..48361c4ef9 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -27,6 +27,7 @@ import { For, Show } from 'solid-js';import { useAgentSession } from '../context/AgentSessionContext';import { changeSessionArchiveState } from '../queries/change-session-archive-state';import { AgentPullRequestChip } from './AgentPullRequestChip';+import { AgentTaskChip } from './AgentTaskChip';import {harnessTitle,sessionHarnessTitle,@@ -189,6 +190,9 @@ export function AgentSplitHeader(props: {into the title menu via `menuTools` below instead. */}<SplitHeaderRight><div class="order-[1000] flex items-center gap-1.5">+ <Show when={props.session?.taskId}>+ {(taskId) => <AgentTaskChip taskId={taskId()} />}+ </Show><Show when={props.session?.pullRequestUrl}>{(url) => <AgentPullRequestChip url={url()} />}</Show>diff --git a/apps/web/src/features/block-agent/component/AgentTaskChip.test.tsx b/apps/web/src/features/block-agent/component/AgentTaskChip.test.tsxnew file mode 100644index 0000000000..2901b7c186--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentTaskChip.test.tsx@@ -0,0 +1,93 @@+/** @vitest-environment jsdom */+import type { PreviewItem } from '@queries/preview';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, expect, it, vi } from 'vitest';+import { AgentTaskChip } from './AgentTaskChip';++const { openWithSplit, preview } = vi.hoisted(() => {+ // Imports reach the connection gateway, which dials on load.+ class FakeWebSocket {+ url: string;+ readyState = 1;+ constructor(url: string) {+ this.url = url;+ }+ close() {}+ addEventListener() {}+ removeEventListener() {}+ send() {}+ }+ vi.stubGlobal('WebSocket', FakeWebSocket);+ return {+ openWithSplit: vi.fn(),+ preview: { current: undefined as PreviewItem | undefined },+ };+});++vi.mock('@queries/preview', () => ({+ useItemPreview: () => [() => preview.current],+ isAccessiblePreviewItem: (item: PreviewItem) =>+ !item.loading && item.access === 'access',+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit }),+}));+vi.mock('@core/util/useSplitNavigationHandler', () => ({+ useSplitNavigationHandler: (onClick: (event: MouseEvent) => void) => ({+ onClick,+ }),+}));+vi.mock('@core/component/HoverCard', () => ({+ HoverCard: (props: { trigger: import('solid-js').JSX.Element }) =>+ props.trigger,+}));+vi.mock('@core/component/DocumentPreview', () => ({+ PopupPreview: () => null,+}));++const taskId = '0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e6f';++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++it('shows the task title and opens the task in a new split', () => {+ preview.current = {+ access: 'access',+ loading: false,+ id: taskId,+ type: 'document',+ rawName: 'Show the linked task in the session header',+ name: 'Show the linked task in the session header',+ fileType: 'md',+ subType: { type: 'task', is_completed: false },+ };+ render(() => <AgentTaskChip taskId={taskId} />);++ const chip = screen.getByRole('button');+ expect(chip.textContent).toBe('Show the linked task in the session header');+ fireEvent.click(chip);+ expect(openWithSplit).toHaveBeenCalledWith(+ { type: 'task', id: taskId },+ { preferNewSplit: true }+ );+});++it('reads "Task" for a task the viewer cannot see and still opens it', () => {+ preview.current = {+ access: 'no_access',+ loading: false,+ id: taskId,+ type: 'document',+ };+ render(() => <AgentTaskChip taskId={taskId} />);++ const chip = screen.getByRole('button');+ expect(chip.textContent).toBe('Task');+ fireEvent.click(chip);+ expect(openWithSplit).toHaveBeenCalledWith(+ { type: 'task', id: taskId },+ { preferNewSplit: true }+ );+});diff --git a/apps/web/src/features/block-agent/component/AgentTaskChip.tsx b/apps/web/src/features/block-agent/component/AgentTaskChip.tsxnew file mode 100644index 0000000000..e959b34c64--- /dev/null+++ b/apps/web/src/features/block-agent/component/AgentTaskChip.tsx@@ -0,0 +1,86 @@+/**+ * Compact header chip for the session's linked Macro task: its title, opening+ * the task in a split. While the preview loads, or when the viewer cannot see+ * the task, it reads "Task" and still opens it.+ */++import { useSplitLayout } from '@components/app/split-layout/layout';+import { PopupPreview } from '@core/component/DocumentPreview';+import { EntityIcon } from '@core/component/EntityIcon';+import { HoverCard } from '@core/component/HoverCard';+import { openInNewSplitForMention } from '@core/util/openInNewSplit';+import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';+import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';+import { Layer } from '@ui';+import { type JSX, Suspense } from 'solid-js';+import { ChipShell } from './AgentSessionChipShell';++function TaskChipButton(props: {+ taskId: string;+ title?: string;+}): JSX.Element {+ const { openWithSplit } = useSplitLayout();+ const navHandlers = useSplitNavigationHandler<HTMLButtonElement>((event) => {+ event.stopPropagation();+ openWithSplit(+ { type: 'task', id: props.taskId },+ { preferNewSplit: openInNewSplitForMention(event.shiftKey, true) }+ );+ });+ const label = () => props.title?.replaceAll('\n', ' ').trim() || 'Task';++ return (+ <button+ type="button"+ data-agent-task={props.taskId}+ title={props.title ?? 'Open task'}+ {...navHandlers}+ >+ <ChipShell>+ <EntityIcon targetType="task" size="xs" />+ <span class="min-w-0 truncate">{label()}</span>+ </ChipShell>+ </button>+ );+}++function PreviewedTaskChip(props: { taskId: string }): JSX.Element {+ const [preview] = useItemPreview(() => ({+ id: props.taskId,+ type: 'document',+ }));+ const title = () => {+ const item = preview();+ return isAccessiblePreviewItem(item) ? item.name : undefined;+ };++ return (+ <HoverCard+ triggerClass="min-w-0 max-w-full"+ disabled={title() === undefined}+ trigger={<TaskChipButton taskId={props.taskId} title={title()} />}+ content={+ <PopupPreview+ mouseEnter={() => {}}+ mouseLeave={() => {}}+ documentInfo={{+ id: props.taskId,+ type: 'task',+ params: {},+ isOpenable: true,+ }}+ />+ }+ />+ );+}++export function AgentTaskChip(props: { taskId: string }): JSX.Element {+ return (+ <Layer depth={2}>+ <Suspense fallback={<TaskChipButton taskId={props.taskId} />}>+ <PreviewedTaskChip taskId={props.taskId} />+ </Suspense>+ </Layer>+ );+}diff --git a/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx b/apps/web/src/features/block-agent/component/session-read-hosts.test.tsxindex 256b62aa1f..082de8e9fd 100644--- a/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx+++ b/apps/web/src/features/block-agent/component/session-read-hosts.test.tsx@@ -137,6 +137,7 @@ vi.mock('@components/app/split-layout/components/SplitLabel', () => ({}));vi.mock('./AgentComposer', () => ({ AgentComposer: () => null }));vi.mock('./AgentPullRequestChip', () => ({ AgentPullRequestChip: () => null }));+vi.mock('./AgentTaskChip', () => ({ AgentTaskChip: () => null }));vi.mock('./AgentSplitHeader', () => ({AgentSplitHeader: () => null,agentSessionTitle: () => 'Agent session',diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsxindex f0602dc100..8bb09dc4b0 100644--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx@@ -24,6 +24,7 @@ import { sessionStatus } from '../../state/session-status';import { activityCounts, latestPlan } from '../../state/session-summary';import { CountSummary, SessionStatusPill, TodoList } from '../../ui';import { AgentPullRequestChip } from '../AgentPullRequestChip';+import { AgentTaskChip } from '../AgentTaskChip';import {modelDisplayName,sessionHarnessTitle,@@ -101,6 +102,13 @@ export function AgentSidePanelSections() {</SidePanel.Row>)}</Show>+ <Show when={session()?.taskId}>+ {(taskId) => (+ <SidePanel.Row label="Task">+ <AgentTaskChip taskId={taskId()} />+ </SidePanel.Row>+ )}+ </Show><Show when={session()?.pullRequestUrl}>{(url) => (<SidePanel.Row label="Pull request">diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsxindex 704a3f3296..6f3e9162e3 100644--- a/apps/web/src/features/settings/Agents.test.tsx+++ b/apps/web/src/features/settings/Agents.test.tsx@@ -41,6 +41,11 @@ vi.mock('./components/instructions-editor', () => ({),}));+// Covered by its own suite; it owns a live query.+vi.mock('./components/coding-preferences-setting', () => ({+ CodingPreferencesSetting: () => null,+}));+const claudeFlag = vi.hoisted(() => ({ enabled: true }));vi.mock('@app/lib/analytics/posthog', () => ({useFeatureFlag: (flag: { key: string }) => {diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsxindex 4c916b7847..ffcc2a8c8d 100644--- a/apps/web/src/features/settings/Agents.tsx+++ b/apps/web/src/features/settings/Agents.tsx@@ -46,6 +46,7 @@ import { botAssignableChannelOptions } from '../channel/Bots/botChannelOptions';import { canDeleteBot, canManageAgent } from '../channel/Bots/botPermissions';import { ChannelMultiSelect } from '../channel/Bots/ChannelMultiSelect';import { AgentSettingsDescription } from './components/agent-settings-description';+import { CodingPreferencesSetting } from './components/coding-preferences-setting';import { AgentInstructionsEditor } from './components/instructions-editor';import { SettingsSelect } from './components/settings-select';import { PipedreamAppPicker } from './PipedreamAppPicker';@@ -331,6 +332,8 @@ export function Agents(props: { navigation?: JSX.Element } = {}) {</Show></SettingsCard></SettingsSection>++ <CodingPreferencesSetting /></SettingsPage></Show>diff --git a/apps/web/src/features/settings/components/coding-preferences-setting.test.tsx b/apps/web/src/features/settings/components/coding-preferences-setting.test.tsxnew file mode 100644index 0000000000..dde3fad9e1--- /dev/null+++ b/apps/web/src/features/settings/components/coding-preferences-setting.test.tsx@@ -0,0 +1,122 @@+/**+ * @vitest-environment jsdom+ */++import { queryClient } from '@queries/client';+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import { fireEvent, render, screen, waitFor } from '@solidjs/testing-library';+import { QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { CodingPreferencesSetting } from './coding-preferences-setting';++vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: {+ getCodingPreferences: vi.fn(),+ setCodingPreferences: vi.fn(),+ },+}));++const toastFailure = vi.hoisted(() => vi.fn());+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: toastFailure },+}));++afterEach(() => {+ vi.clearAllMocks();+ queryClient.clear();+});++function renderSetting() {+ render(() => (+ <QueryClientProvider client={queryClient}>+ <CodingPreferencesSetting />+ </QueryClientProvider>+ ));+}++/** The switch's accessible input is sr-only; users click the control drawn beside it. */+function visibleControl(toggle: HTMLElement): HTMLElement {+ const control = toggle.nextElementSibling;+ if (!(control instanceof HTMLElement)) {+ throw new Error('the switch has no visible control');+ }+ return control;+}++describe('CodingPreferencesSetting', () => {+ it('saves one toggled preference alongside the other', async () => {+ vi.mocked(agentHarnessServiceClient.getCodingPreferences).mockResolvedValue(+ ok({ createTasks: false, openPullRequests: true })+ );+ vi.mocked(agentHarnessServiceClient.setCodingPreferences).mockResolvedValue(+ ok({ createTasks: true, openPullRequests: true })+ );+ renderSetting();++ const createTasks = await screen.findByRole('switch', {+ name: 'Create tasks',+ });+ const openPullRequests = screen.getByRole('switch', {+ name: 'Open pull requests',+ });+ await waitFor(() => expect(createTasks).toHaveProperty('disabled', false));+ expect(createTasks).toHaveProperty('checked', false);+ expect(openPullRequests).toHaveProperty('checked', true);++ vi.mocked(agentHarnessServiceClient.getCodingPreferences).mockResolvedValue(+ ok({ createTasks: true, openPullRequests: true })+ );+ fireEvent.click(visibleControl(createTasks));++ await waitFor(() => expect(createTasks).toHaveProperty('checked', true));+ expect(openPullRequests).toHaveProperty('checked', true);+ expect(agentHarnessServiceClient.setCodingPreferences).toHaveBeenCalledWith(+ { createTasks: true, openPullRequests: true }+ );+ expect(toastFailure).not.toHaveBeenCalled();+ });++ it('rolls back and reports a failed save', async () => {+ vi.mocked(agentHarnessServiceClient.getCodingPreferences).mockResolvedValue(+ ok({ createTasks: false, openPullRequests: false })+ );+ vi.mocked(agentHarnessServiceClient.setCodingPreferences).mockResolvedValue(+ err([{ code: 'HTTP_ERROR', message: 'boom' }])+ );+ renderSetting();++ const openPullRequests = await screen.findByRole('switch', {+ name: 'Open pull requests',+ });+ await waitFor(() =>+ expect(openPullRequests).toHaveProperty('disabled', false)+ );+ fireEvent.click(visibleControl(openPullRequests));++ await waitFor(() =>+ expect(toastFailure).toHaveBeenCalledWith(+ 'Could not update coding preferences'+ )+ );+ expect(openPullRequests).toHaveProperty('checked', false);+ });++ it('disables both switches when the preferences fail to load', async () => {+ vi.mocked(agentHarnessServiceClient.getCodingPreferences).mockResolvedValue(+ err([{ code: 'HTTP_ERROR', message: 'boom' }])+ );+ renderSetting();++ const createTasks = await screen.findByRole('switch', {+ name: 'Create tasks',+ });+ await waitFor(() =>+ expect(agentHarnessServiceClient.getCodingPreferences).toHaveBeenCalled()+ );+ expect(createTasks).toHaveProperty('disabled', true);+ expect(+ screen.getByRole('switch', { name: 'Open pull requests' })+ ).toHaveProperty('disabled', true);+ });+});diff --git a/apps/web/src/features/settings/components/coding-preferences-setting.tsx b/apps/web/src/features/settings/components/coding-preferences-setting.tsxnew file mode 100644index 0000000000..7d01645fcb--- /dev/null+++ b/apps/web/src/features/settings/components/coding-preferences-setting.tsx@@ -0,0 +1,63 @@+import { toast } from '@core/component/Toast/Toast';+import {+ useCodingPreferencesQuery,+ useSetCodingPreferencesMutation,+} from '@queries/agents/coding-preferences';+import type { CodingPreferencesBody } from '@service-agent-harness/client';+import { ToggleSwitch } from '@ui';+import { SettingsCard, SettingsRow, SettingsSection } from '../primitives';++/** What the user's new coding sessions do beyond their assignment. */+export function CodingPreferencesSetting() {+ const preferences = useCodingPreferencesQuery();+ const setPreferences = useSetCodingPreferencesMutation();++ const toggle = async (+ current: CodingPreferencesBody,+ preference: keyof CodingPreferencesBody,+ enabled: boolean+ ) => {+ try {+ await setPreferences.mutateAsync({ ...current, [preference]: enabled });+ } catch {+ toast.failure('Could not update coding preferences');+ }+ };++ const PreferenceRow = (props: {+ preference: keyof CodingPreferencesBody;+ label: string;+ description: string;+ }) => (+ <SettingsRow label={props.label} description={props.description}>+ <ToggleSwitch+ size="md"+ label={props.label}+ labelClass="sr-only"+ checked={preferences.isSuccess && preferences.data[props.preference]}+ disabled={!preferences.isSuccess}+ onChange={(enabled) => {+ if (!preferences.isSuccess) return;+ void toggle(preferences.data, props.preference, enabled);+ }}+ />+ </SettingsRow>+ );++ return (+ <SettingsSection title="Coding sessions">+ <SettingsCard>+ <PreferenceRow+ preference="createTasks"+ label="Create tasks"+ description="Link each coding session to a Macro task"+ />+ <PreferenceRow+ preference="openPullRequests"+ label="Open pull requests"+ description="Deliver coding work as a pull request"+ />+ </SettingsCard>+ </SettingsSection>+ );+}diff --git a/apps/web/src/lib/queries/agents/coding-preferences.ts b/apps/web/src/lib/queries/agents/coding-preferences.tsnew file mode 100644index 0000000000..7124d0c096--- /dev/null+++ b/apps/web/src/lib/queries/agents/coding-preferences.ts@@ -0,0 +1,55 @@+import { throwOnErr } from '@core/util/result';+import { queryClient } from '@queries/client';+import {+ agentHarnessServiceClient,+ type CodingPreferencesBody,+} from '@service-agent-harness/client';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { agentKeys } from './keys';++/** What the user's new coding sessions are told to do beyond their assignment. */+export function useCodingPreferencesQuery() {+ return useQuery(() => ({+ queryKey: agentKeys.codingPreferences.queryKey,+ queryFn: async () =>+ throwOnErr(+ async () => await agentHarnessServiceClient.getCodingPreferences()+ ),+ }));+}++/** Replaces the preferences optimistically and rolls back if the save fails. */+export function useSetCodingPreferencesMutation() {+ return useMutation(() => ({+ mutationFn: async (preferences: CodingPreferencesBody) =>+ throwOnErr(+ async () =>+ await agentHarnessServiceClient.setCodingPreferences(preferences)+ ),+ onMutate: async (preferences: CodingPreferencesBody) => {+ await queryClient.cancelQueries({+ queryKey: agentKeys.codingPreferences.queryKey,+ });+ const previous = queryClient.getQueryData<CodingPreferencesBody>(+ agentKeys.codingPreferences.queryKey+ );+ queryClient.setQueryData<CodingPreferencesBody>(+ agentKeys.codingPreferences.queryKey,+ preferences+ );+ return { previous };+ },+ onError: (_error, _preferences, context) => {+ if (context?.previous === undefined) return;+ queryClient.setQueryData(+ agentKeys.codingPreferences.queryKey,+ context.previous+ );+ },+ onSettled: () => {+ void queryClient.invalidateQueries({+ queryKey: agentKeys.codingPreferences.queryKey,+ });+ },+ }));+}diff --git a/apps/web/src/lib/queries/agents/keys.ts b/apps/web/src/lib/queries/agents/keys.tsindex cdbb754da5..d113d77a49 100644--- a/apps/web/src/lib/queries/agents/keys.ts+++ b/apps/web/src/lib/queries/agents/keys.ts@@ -2,4 +2,5 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';export const agentKeys = createQueryKeys('agents', {list: null,+ codingPreferences: null,});diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.tsindex 744fc66006..6e70397844 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@@ -14,6 +14,7 @@ import type {AgentSessionQueueResponse,AgentSessionResponse,AnswerToolApprovalResponse,+ CodingPreferencesBody,ControlRequest,ControlResponse,CreateAgentSessionRequest,@@ -34,7 +35,7 @@ import type {WarmAgentSessionResponse,} from './generated/schemas';-export type { SandboxSize, SandboxSizeBody };+export type { CodingPreferencesBody, SandboxSize, SandboxSizeBody };const agentHarnessHost = SERVER_HOSTS['agent-harness'];@@ -296,6 +297,26 @@ export const agentHarnessServiceClient = {);},+ getCodingPreferences() {+ return fetchWithToken<CodingPreferencesBody>(+ `${agentHarnessHost}/agent-coding-preferences`,+ {+ method: 'GET',+ }+ );+ },++ setCodingPreferences(preferences: CodingPreferencesBody) {+ return fetchWithToken<CodingPreferencesBody>(+ `${agentHarnessHost}/agent-coding-preferences`,+ {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(preferences),+ }+ );+ },+/*** The session's latest captured changes: changed files with statuses and* line counts, plus how the latest capture attempt went.diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.tsindex 87ece67629..26082a4b6c 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@@ -15,6 +15,7 @@ import type {AiAdmissionErrorBody,AnswerToolApprovalRequest,AnswerToolApprovalResponse,+ CodingPreferencesBody,CompleteRequest,ControlRequest,ControlResponse,@@ -130,6 +131,123 @@ export const discoverAgentCapabilitiesHandler = async (} as discoverAgentCapabilitiesHandlerResponse;};+/**+ * @summary Read what the caller's new coding sessions are told to do beyond their assignment.+ */+export type getAgentCodingPreferencesResponse200 = {+ data: CodingPreferencesBody;+ status: 200;+};++export type getAgentCodingPreferencesResponse401 = {+ data: string;+ status: 401;+};++export type getAgentCodingPreferencesResponse500 = {+ data: string;+ status: 500;+};++export type getAgentCodingPreferencesResponseSuccess =+ getAgentCodingPreferencesResponse200 & {+ headers: Headers;+ };+export type getAgentCodingPreferencesResponseError = (+ | getAgentCodingPreferencesResponse401+ | getAgentCodingPreferencesResponse500+) & {+ headers: Headers;+};++export type getAgentCodingPreferencesResponse =+ | getAgentCodingPreferencesResponseSuccess+ | getAgentCodingPreferencesResponseError;++export const getGetAgentCodingPreferencesUrl = () => {+ return `/agent-coding-preferences`;+};++export const getAgentCodingPreferences = async (+ options?: RequestInit+): Promise<getAgentCodingPreferencesResponse> => {+ const res = await fetch(getGetAgentCodingPreferencesUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getAgentCodingPreferencesResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getAgentCodingPreferencesResponse;+};++/**+ * @summary Replace the caller's coding preferences.+ */+export type putAgentCodingPreferencesResponse200 = {+ data: CodingPreferencesBody;+ status: 200;+};++export type putAgentCodingPreferencesResponse401 = {+ data: string;+ status: 401;+};++export type putAgentCodingPreferencesResponse500 = {+ data: string;+ status: 500;+};++export type putAgentCodingPreferencesResponseSuccess =+ putAgentCodingPreferencesResponse200 & {+ headers: Headers;+ };+export type putAgentCodingPreferencesResponseError = (+ | putAgentCodingPreferencesResponse401+ | putAgentCodingPreferencesResponse500+) & {+ headers: Headers;+};++export type putAgentCodingPreferencesResponse =+ | putAgentCodingPreferencesResponseSuccess+ | putAgentCodingPreferencesResponseError;++export const getPutAgentCodingPreferencesUrl = () => {+ return `/agent-coding-preferences`;+};++export const putAgentCodingPreferences = async (+ codingPreferencesBody: CodingPreferencesBody,+ options?: RequestInit+): Promise<putAgentCodingPreferencesResponse> => {+ const res = await fetch(getPutAgentCodingPreferencesUrl(), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(codingPreferencesBody),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: putAgentCodingPreferencesResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as putAgentCodingPreferencesResponse;+};+/*** @summary Probe one provider's model catalog without creating an agent session.*/diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.tsindex 8b0f872fcb..7a00379830 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts@@ -10,6 +10,7 @@ import type { AgentSessionResponseInstructions } from './agentSessionResponseInsimport type { AgentSessionResponseOriginatingMessageId } from './agentSessionResponseOriginatingMessageId';import type { AgentSessionResponsePullRequestUrl } from './agentSessionResponsePullRequestUrl';import type { AgentSessionResponseRepoUrl } from './agentSessionResponseRepoUrl';+import type { AgentSessionResponseTaskId } from './agentSessionResponseTaskId';import type { AgentSessionResponseThreadChannelId } from './agentSessionResponseThreadChannelId';import type { AgentSessionResponseThreadId } from './agentSessionResponseThreadId';import type { AgentSessionResponseThreadParent } from './agentSessionResponseThreadParent';@@ -60,6 +61,8 @@ at creation. Absent otherwise, so existing payloads are unchanged. */sandboxSize: SandboxSize;/** The session's status. */status: SessionStatusDto;+ /** The Macro task the session was linked to. */+ taskId?: AgentSessionResponseTaskId;/** The channel `thread_id` lives in, when the session was spawned from achannel thread. Derived from `thread_parent`. */threadChannelId?: AgentSessionResponseThreadChannelId;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseTaskId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseTaskId.tsnew file mode 100644index 0000000000..fb558d4d7a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseTaskId.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 Macro task the session was linked to.+ */+export type AgentSessionResponseTaskId = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/codingPreferencesBody.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/codingPreferencesBody.tsnew file mode 100644index 0000000000..985409e760--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/codingPreferencesBody.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Request or response body for the caller's coding preferences.+ */+export interface CodingPreferencesBody {+ /** Whether new coding sessions research prior work and link a Macro task. */+ createTasks: boolean;+ /** Whether new coding sessions deliver their work as a pull request. */+ openPullRequests: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex c53228cb37..e9d99616be 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@@ -79,6 +79,7 @@ export * from './agentSessionResponseInstructions';export * from './agentSessionResponseOriginatingMessageId';export * from './agentSessionResponsePullRequestUrl';export * from './agentSessionResponseRepoUrl';+export * from './agentSessionResponseTaskId';export * from './agentSessionResponseThreadChannelId';export * from './agentSessionResponseThreadId';export * from './agentSessionResponseThreadParent';@@ -100,6 +101,7 @@ export * from './changesetDto';export * from './changesetDtoRepository';export * from './changesetSourceDto';export * from './channelSharePermission';+export * from './codingPreferencesBody';export * from './completeRequest';export * from './controlRequest';export * from './controlRequestAllOf';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex 735b9993b3..452b92b16e 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@@ -62,6 +62,92 @@]}},+ "/agent-coding-preferences": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Read what the caller's new coding sessions are told to do beyond their assignment.",+ "operationId": "get_agent_coding_preferences",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodingPreferencesBody"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["agent-sessions"],+ "summary": "Replace the caller's coding preferences.",+ "operationId": "put_agent_coding_preferences",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodingPreferencesBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodingPreferencesBody"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/agent-models/load": {"post": {"tags": ["agent-models"],@@ -2847,6 +2933,10 @@"$ref": "#/components/schemas/SessionStatusDto","description": "The session's status."},+ "taskId": {+ "type": ["string", "null"],+ "description": "The Macro task the session was linked to."+ },"threadChannelId": {"type": ["string", "null"],"format": "uuid",@@ -3121,6 +3211,21 @@}}},+ "CodingPreferencesBody": {+ "type": "object",+ "description": "Request or response body for the caller's coding preferences.",+ "required": ["createTasks", "openPullRequests"],+ "properties": {+ "createTasks": {+ "type": "boolean",+ "description": "Whether new coding sessions research prior work and link a Macro task."+ },+ "openPullRequests": {+ "type": "boolean",+ "description": "Whether new coding sessions deliver their work as a pull request."+ }+ }+ },"CompleteRequest": {"type": "object","description": "One-time manual code. Deliberately does not implement Debug.",diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.tomlindex 8cd1213c4e..ed467936d3 100644--- a/crates/agent_harness/Cargo.toml+++ b/crates/agent_harness/Cargo.toml@@ -22,6 +22,10 @@ agent_trigger = { path = "../agent_trigger" }ai_usage = { path = "../ai_usage" }cursor_api_key = { path = "../cursor_api_key" }cursor_cloud_agents = { path = "../cursor_cloud_agents" }+# Task documents a session links to, read as the session owner.+documents = { path = "../documents", default-features = false, features = [+ "ports",+] }entity_access = { path = "../entity_access" }entity_access_db_utils = { path = "../entity_access_db_utils" }anyhow = { workspace = true }@@ -51,6 +55,7 @@ macro_authorization = { path = "../macro_authorization", features = ["axum"] }macro_tower_layers = { path = "../macro_tower_layers" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }+model = { path = "../model" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }model_owner = { path = "../model_owner" }diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 0af7c46a35..06afd9908b 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -18,6 +18,10 @@ use macro_uuid::Uuid;use messages::domain::events::MessageEventAttachment;mod session_origin;pub use session_origin::{MentionOrigin, SessionOrigin, TaskAssignmentOrigin};+mod coding_preferences;+pub use coding_preferences::{+ CREATE_TASKS_INSTRUCTIONS, OPEN_PULL_REQUESTS_INSTRUCTIONS, with_coding_preferences,+};/// How a channel message's attached files are named to an agent.///diff --git a/crates/agent_harness/src/domain/model/coding_preferences.rs b/crates/agent_harness/src/domain/model/coding_preferences.rsnew file mode 100644index 0000000000..b94730445e--- /dev/null+++ b/crates/agent_harness/src/domain/model/coding_preferences.rs@@ -0,0 +1,39 @@+//! The workflows a user's coding preferences add to new coding sessions.++use agent_session::domain::coding_preferences::CodingPreferences;++#[cfg(test)]+mod test;++/// Research prior work, then link the session to a Macro task.+pub const CREATE_TASKS_INSTRUCTIONS: &str = include_str!("coding_preferences/create_tasks.md");++/// Deliver the work as a pull request registered with the session.+pub const OPEN_PULL_REQUESTS_INSTRUCTIONS: &str =+ include_str!("coding_preferences/open_pull_requests.md");++/// `instructions` followed by each enabled preference's workflow: tasks+/// first, then pull requests.+#[must_use]+pub fn with_coding_preferences(+ instructions: Option<String>,+ preferences: CodingPreferences,+) -> Option<String> {+ let CodingPreferences {+ create_tasks,+ open_pull_requests,+ } = preferences;+ let workflows = [+ (create_tasks, CREATE_TASKS_INSTRUCTIONS),+ (open_pull_requests, OPEN_PULL_REQUESTS_INSTRUCTIONS),+ ]+ .into_iter()+ .filter(|(enabled, _)| *enabled)+ .map(|(_, workflow)| workflow.trim());+ let sections: Vec<&str> = instructions+ .as_deref()+ .into_iter()+ .chain(workflows)+ .collect();+ (!sections.is_empty()).then(|| sections.join("\n\n"))+}diff --git a/crates/agent_harness/src/domain/model/coding_preferences/create_tasks.md b/crates/agent_harness/src/domain/model/coding_preferences/create_tasks.mdnew file mode 100644index 0000000000..090c686e4f--- /dev/null+++ b/crates/agent_harness/src/domain/model/coding_preferences/create_tasks.md@@ -0,0 +1,10 @@+## Tasks++The user tracks coding work with Macro tasks. Before changing code:++1. If this session was started from a Macro task, it is already linked: skip to step 4.+2. Search the user's Macro workspace (macro.NameSearch, macro.ContentSearch) for related tasks, documents and discussions. For each related task, call macro_internal.task_pull_requests to see its pull requests and whether they merged.+3. If related work exists or already shipped, stop and ask the user how to proceed before writing code.+4. Link the session with macro_internal.link_task, creating the task with macro.CreateDocument (isTask true) when none fits. Tell the user which task you are working from.++When you open a pull request, put the task reference link_task returns in its description.diff --git a/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.md b/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.mdnew file mode 100644index 0000000000..fd69b5a871--- /dev/null+++ b/crates/agent_harness/src/domain/model/coding_preferences/open_pull_requests.md@@ -0,0 +1,3 @@+## Pull requests++Deliver the work as a pull request, and register it with macro_internal.set_pull_request.diff --git a/crates/agent_harness/src/domain/model/coding_preferences/test.rs b/crates/agent_harness/src/domain/model/coding_preferences/test.rsnew file mode 100644index 0000000000..1fa85ba8ba--- /dev/null+++ b/crates/agent_harness/src/domain/model/coding_preferences/test.rs@@ -0,0 +1,83 @@+use super::*;++const TASKS: CodingPreferences = CodingPreferences {+ create_tasks: true,+ open_pull_requests: false,+};+const PULL_REQUESTS: CodingPreferences = CodingPreferences {+ create_tasks: false,+ open_pull_requests: true,+};+const BOTH: CodingPreferences = CodingPreferences {+ create_tasks: true,+ open_pull_requests: true,+};++fn tasks() -> &'static str {+ CREATE_TASKS_INSTRUCTIONS.trim()+}++fn pull_requests() -> &'static str {+ OPEN_PULL_REQUESTS_INSTRUCTIONS.trim()+}++#[test]+fn no_preferences_leave_instructions_unchanged() {+ assert_eq!(+ with_coding_preferences(Some("Persona.".to_owned()), CodingPreferences::default()),+ Some("Persona.".to_owned())+ );+ assert_eq!(+ with_coding_preferences(None, CodingPreferences::default()),+ None+ );+}++#[test]+fn tasks_alone_follow_existing_instructions() {+ assert_eq!(+ with_coding_preferences(Some("Persona.\n\nAssignment.".to_owned()), TASKS),+ Some(format!("Persona.\n\nAssignment.\n\n{}", tasks()))+ );+}++#[test]+fn pull_requests_alone_stand_without_other_instructions() {+ assert_eq!(+ with_coding_preferences(None, PULL_REQUESTS),+ Some(pull_requests().to_owned())+ );+}++#[test]+fn both_put_tasks_before_pull_requests() {+ assert_eq!(+ with_coding_preferences(Some("Persona.".to_owned()), BOTH),+ Some(format!("Persona.\n\n{}\n\n{}", tasks(), pull_requests()))+ );+}++#[test]+fn tasks_name_the_tools_they_rely_on() {+ for tool in [+ "macro.NameSearch",+ "macro.ContentSearch",+ "macro.CreateDocument",+ "macro_internal.task_pull_requests",+ "macro_internal.link_task",+ ] {+ assert!(CREATE_TASKS_INSTRUCTIONS.contains(tool), "{tool}");+ }+}++#[test]+fn tasks_put_their_reference_in_any_pull_request() {+ assert!(CREATE_TASKS_INSTRUCTIONS.contains(+ "When you open a pull request, put the task reference link_task returns in its description."+ ));+}++#[test]+fn pull_requests_are_registered_with_the_session() {+ assert!(OPEN_PULL_REQUESTS_INSTRUCTIONS.contains("macro_internal.set_pull_request"));+}diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex 00054d9a95..32c0586dad 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -2,6 +2,7 @@//! external runtime that dials in. Each creates the row, provisions egress//! where there is a sandbox to give it to, and attaches the runtime.+use crate::domain::model::{is_coding_agent, with_coding_preferences};use agent_session::domain::model::session_owner_user;use agent_session::domain::repository_branch::RepositoryBranch;use model_owner::Owner;@@ -89,6 +90,15 @@ where),None => (defaults.model.clone(), defaults.harness.clone(), None),};+ let instructions = self+ .inner+ .with_owner_coding_preferences(+ &owner_user,+ request.bot_id,+ AgentKind::for_session(request.bot_id, &harness),+ request.instructions.or(profile_instructions),+ )+ .await?;let session = self.inner.sessions@@ -105,7 +115,7 @@ whererepo_url: request.repo_url,workspace: request.workspace,sandbox_size: SandboxSize::Default,- instructions: request.instructions.or(profile_instructions),+ instructions,// No egress, so no MCP servers of ours to select from.mcp_servers: AgentMcpServers::OwnerConnections,// Mint the internal-tool credential when an authenticated@@ -224,6 +234,30 @@ whereMentions: PromptMentions,Notifier: AgentSessionNotifier,{+ /// A new session's instructions, ending with the workflows its owner's+ /// coding preferences add when the session is a coding agent's.+ ///+ /// Warm sessions are only ever the in-memory chat agent's, which never+ /// gets the workflows, so the warm claim's instructions match still holds.+ pub(super) async fn with_owner_coding_preferences(+ &self,+ owner: &MacroUserIdStr<'static>,+ bot_id: BotId,+ kind: AgentKind,+ instructions: Option<String>,+ ) -> agent_session::domain::error::Result<Option<String>> {+ let choice = self+ .coding_agents+ .coding_agent_choice(bot_id)+ .await+ .map_err(AgentSessionError::Unknown)?;+ if !is_coding_agent(choice, kind) {+ return Ok(instructions);+ }+ let preferences = self.sessions.user_coding_preferences(owner).await?;+ Ok(with_coding_preferences(instructions, preferences))+ }+#[tracing::instrument(err, skip(self, command), fields(%session_id,bot_id = %command.bot_id,@@ -292,7 +326,14 @@ wherelet sandbox_size = self.sessions.user_sandbox_size(&actor).await?;// Assignments retain the original task and update policy alongside the// profile instructions, including across later turns and reattachments.- let instructions = origin.session_instructions(&runtime.instructions);+ let instructions = self+ .with_owner_coding_preferences(+ &actor,+ bot_id,+ runtime.kind,+ origin.session_instructions(&runtime.instructions),+ )+ .await?;// Provisioned before the session exists, because the row is what makes// the token mean anything: it carries the hash the proxy recognises.diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex 15ed19c79e..3163be5b35 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -3,6 +3,7 @@//! recording announcer. Only the edges are doubles.mod chat_reply;+mod coding_preferences;mod owned_purge;mod quota;mod user_cleanup;diff --git a/crates/agent_harness/src/domain/service/test/coding_preferences.rs b/crates/agent_harness/src/domain/service/test/coding_preferences.rsnew file mode 100644index 0000000000..2e105fa844--- /dev/null+++ b/crates/agent_harness/src/domain/service/test/coding_preferences.rs@@ -0,0 +1,224 @@+//! A user's coding preferences append their workflows to new coding sessions'+//! instructions, after the persona's and any task assignment's.++use super::*;+use crate::domain::model::{+ CREATE_TASKS_INSTRUCTIONS, OPEN_PULL_REQUESTS_INSTRUCTIONS, TaskAssignmentOrigin,+};+use agent_session::domain::coding_preferences::CodingPreferences;++const TASKS: CodingPreferences = CodingPreferences {+ create_tasks: true,+ open_pull_requests: false,+};+const PULL_REQUESTS: CodingPreferences = CodingPreferences {+ create_tasks: false,+ open_pull_requests: true,+};+const BOTH: CodingPreferences = CodingPreferences {+ create_tasks: true,+ open_pull_requests: true,+};++fn tasks() -> &'static str {+ CREATE_TASKS_INSTRUCTIONS.trim()+}++fn pull_requests() -> &'static str {+ OPEN_PULL_REQUESTS_INSTRUCTIONS.trim()+}++fn assignment_command(kind: AgentKind, harness: &str) -> OpenSession {+ let mut command = open_command();+ command.runtime.kind = kind;+ command.runtime.harness = harness.to_owned();+ command.runtime.instructions = "Persona.".to_owned();+ command.origin = SessionOrigin::TaskAssignment(TaskAssignmentOrigin {+ parent: MessageParent::parse("document", "task-1").unwrap(),+ discussion_id: macro_uuid::generate_uuid_v7(),+ actor: sender(),+ prompt: "Private assignment instructions".to_owned(),+ });+ command+}++fn assignment() -> String {+ agent_trigger::domain::task_assignment::assignment_instructions(+ &MessageParent::parse("document", "task-1").unwrap(),+ )+}++/// Opens until the row exists; the sandbox then fails so nothing waits on a+/// runtime handshake.+async fn opened_instructions(+ (service, repo, containers, _, _): &TestBench,+ command: OpenSession,+) -> Option<String> {+ let id = AgentSessionId::new();+ containers.fail_next_spawn("no sandbox in this test");+ service+ .execute(id, HarnessCommand::Open(command))+ .await+ .expect_err("the sandbox never comes up");+ repo.get(id).await.expect("the row exists").instructions+}++#[tokio::test]+async fn a_coding_assignment_with_tasks_ends_with_the_tasks_workflow() {+ let bench = harness();+ bench+ .1+ .set_user_coding_preferences(&sender(), TASKS)+ .await+ .unwrap();++ let instructions = opened_instructions(+ &bench,+ assignment_command(AgentKind::SandboxedCoder, "opencode"),+ )+ .await;++ assert_eq!(+ instructions,+ Some(format!("Persona.\n\n{}\n\n{}", assignment(), tasks()))+ );+}++#[tokio::test]+async fn a_coding_mention_with_pull_requests_and_no_instructions_gets_only_that_workflow() {+ let bench = harness();+ bench+ .1+ .set_user_coding_preferences(&sender(), PULL_REQUESTS)+ .await+ .unwrap();++ let instructions = opened_instructions(&bench, open_command()).await;++ assert_eq!(instructions.as_deref(), Some(pull_requests()));+}++#[tokio::test]+async fn a_coding_assignment_with_both_puts_tasks_before_pull_requests() {+ let bench = harness();+ bench+ .1+ .set_user_coding_preferences(&sender(), BOTH)+ .await+ .unwrap();++ let instructions = opened_instructions(+ &bench,+ assignment_command(AgentKind::SandboxedCoder, "opencode"),+ )+ .await;++ assert_eq!(+ instructions,+ Some(format!(+ "Persona.\n\n{}\n\n{}\n\n{}",+ assignment(),+ tasks(),+ pull_requests()+ ))+ );+}++#[tokio::test]+async fn coding_sessions_of_users_without_preferences_are_unchanged() {+ let bench = harness();++ let instructions = opened_instructions(+ &bench,+ assignment_command(AgentKind::SandboxedCoder, "opencode"),+ )+ .await;++ assert_eq!(instructions, Some(format!("Persona.\n\n{}", assignment())));+}++#[tokio::test]+async fn chat_sessions_never_get_the_workflows() {+ let bench = harness();+ bench+ .1+ .set_user_coding_preferences(&sender(), BOTH)+ .await+ .unwrap();++ let instructions = opened_instructions(+ &bench,+ assignment_command(AgentKind::InMemory, "macro-inmem"),+ )+ .await;++ assert_eq!(instructions, Some(format!("Persona.\n\n{}", assignment())));+}++#[tokio::test]+async fn a_persona_that_chose_chat_never_gets_the_workflows() {+ let (bench, _signals) = harness_with_coding_choice(false);+ bench+ .1+ .set_user_coding_preferences(&sender(), BOTH)+ .await+ .unwrap();++ let instructions = opened_instructions(+ &bench,+ assignment_command(AgentKind::SandboxedCoder, "opencode"),+ )+ .await;++ assert_eq!(instructions, Some(format!("Persona.\n\n{}", assignment())));+}++#[tokio::test]+async fn a_managed_open_ends_with_both_workflows() {+ let (service, repo, containers, _, _) = harness();+ repo.set_user_coding_preferences(&sender(), BOTH)+ .await+ .unwrap();+ containers.fail_next_spawn("no sandbox in this test");+ let id = AgentSessionId::new();++ service+ .open_managed_session(OpenManagedSession {+ id: Some(id),+ repo_url: None,+ repo_branch: None,+ instructions: Some("Ad hoc.".to_owned()),+ model: None,+ owner: model_owner::Owner::User(sender()),+ prompt: None,+ profile: None,+ })+ .await+ .expect_err("the sandbox never comes up");++ assert_eq!(+ repo.get(id).await.unwrap().instructions,+ Some(format!("Ad hoc.\n\n{}\n\n{}", tasks(), pull_requests()))+ );+}++#[tokio::test]+async fn an_external_open_ends_with_the_tasks_workflow() {+ let (service, repo, _, _, _) = harness();+ repo.set_user_coding_preferences(&sender(), TASKS)+ .await+ .unwrap();++ let session = service+ .open_external_session(OpenExternalAgentSession {+ instructions: Some("Ad hoc.".to_owned()),+ ..open_external_request("/srv/agent")+ })+ .await+ .expect("open external");++ assert_eq!(+ session.instructions,+ Some(format!("Ad hoc.\n\n{}", tasks()))+ );+}diff --git a/crates/agent_harness/src/domain/service/warm.rs b/crates/agent_harness/src/domain/service/warm.rsindex 8b2c4cb1e4..a1bdf12217 100644--- a/crates/agent_harness/src/domain/service/warm.rs+++ b/crates/agent_harness/src/domain/service/warm.rs@@ -205,6 +205,10 @@ where}return Ok(session);}+ let instructions = self+ .inner+ .with_owner_coding_preferences(&owner_user, bot_id, kind, instructions)+ .await?;let defaults = self.inner.defaults.for_bot(bot_id);let sandbox_size = self.innerdiff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rsindex 2bb6412e86..c3cdb03807 100644--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs@@ -7,6 +7,7 @@ use agent_runtime_protocol::domain::ports::{Transport as _, TransportSender as _use agent_runtime_protocol::domain::schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,};+use agent_session::domain::coding_preferences::CodingPreferences;use agent_session::domain::error::Result as SessionResult;use agent_session::domain::model::{AgentSession, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot,@@ -99,6 +100,7 @@ impl AgentSessionRepo for StubSessions {.as_ref().map(|_| "https://github.com/macro-inc/macro".into()),pull_request_url: None,+ task_id: None,workspace: "/workspace".to_owned(),name: DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,@@ -223,6 +225,21 @@ impl AgentSessionRepo for StubSessions {unimplemented!("resizing is the harness service's job")}+ async fn user_coding_preferences(+ &self,+ _owner: &MacroUserIdStr<'static>,+ ) -> SessionResult<CodingPreferences> {+ unimplemented!("coding preferences are read when a session opens")+ }++ async fn set_user_coding_preferences(+ &self,+ _owner: &MacroUserIdStr<'static>,+ _preferences: CodingPreferences,+ ) -> SessionResult<()> {+ unimplemented!("coding preferences are read when a session opens")+ }+async fn list_queued_actions(&self,_id: AgentSessionId,diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rsindex 173e837509..2f608f692b 100644--- a/crates/agent_harness/src/outbound/mod.rs+++ b/crates/agent_harness/src/outbound/mod.rs@@ -19,6 +19,7 @@ pub mod prompt_mentions;pub(crate) mod provision;pub mod routing;pub mod runtime_registry;+pub mod session_tasks;pub mod sidecar;pub mod tool_approvals;diff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex 0f5b6aecd8..0c6d69c47e 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -2,6 +2,7 @@ use super::*;use crate::domain::sandbox::SandboxResizeEffect;use crate::testing::helpers::egress::test_egress;use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};+use agent_session::domain::coding_preferences::CodingPreferences;use agent_session::domain::error::Result as SessionResult;use agent_session::domain::model::{AgentSession, CreateAgentSessionParams, DEFAULT_AGENT_SESSION_NAME, SandboxSize, SessionBot,@@ -143,6 +144,7 @@ impl AgentSessionRepo for FixedBotSessions {Ok(AgentSession {repo_branch: None,pull_request_url: None,+ task_id: None,id,owner_id: model_owner::Owner::User(MacroUserIdStr::try_from("macro|[email protected]".to_owned())@@ -275,6 +277,21 @@ impl AgentSessionRepo for FixedBotSessions {unimplemented!("resizing is the harness service's job")}+ async fn user_coding_preferences(+ &self,+ _owner: &MacroUserIdStr<'static>,+ ) -> SessionResult<CodingPreferences> {+ unimplemented!("coding preferences are read when a session opens")+ }++ async fn set_user_coding_preferences(+ &self,+ _owner: &MacroUserIdStr<'static>,+ _preferences: CodingPreferences,+ ) -> SessionResult<()> {+ unimplemented!("coding preferences are read when a session opens")+ }+async fn list_queued_actions(&self,_id: AgentSessionId,diff --git a/crates/agent_harness/src/outbound/session_tasks.rs b/crates/agent_harness/src/outbound/session_tasks.rsnew file mode 100644index 0000000000..cac50615a2--- /dev/null+++ b/crates/agent_harness/src/outbound/session_tasks.rs@@ -0,0 +1,211 @@+//! A session's task, as the `documents` and `github` crates know it.+//!+//! Whether the owner may view a task, whether a document is a task, and which pull requests+//! a task has belong to the `documents` crate; how a pull request is linked to a task, and+//! which reference the webhook recognizes, belong to the `github` crate. These adapters only+//! translate between those services and the session's ports.++use std::sync::Arc;++use documents::domain::models::{DocumentError, GithubPullRequest};+use documents::domain::ports::DocumentService;+use entity_access::domain::models::{AccessError, EntityType, ViewAccessLevel};+use entity_access::domain::ports::EntityAccessService;+use github::domain::models::{+ GithubKey, MacroTaskId, TeamTaskReference, pull_request_task_reference,+};+use github::domain::ports::GithubSyncRepo;+use github::domain::service::PullRequestTaskLinkService;+use macro_user_id::user_id::MacroUserIdStr;++use agent_session::domain::session_task::{+ PullRequestState, SessionTaskError, TaskDirectory, TaskDocumentId, TaskFacts, TaskPullRequest,+ TaskPullRequestLinker,+};++#[cfg(test)]+mod test;++/// [`TaskDirectory`] over the documents service, checked with entity access.+pub struct DocumentTaskDirectory<Documents, Access> {+ documents: Arc<Documents>,+ access: Arc<Access>,+}++impl<Documents, Access> DocumentTaskDirectory<Documents, Access> {+ /// Read tasks through `documents` after `access` grants the viewer a view receipt.+ pub fn new(documents: Arc<Documents>, access: Arc<Access>) -> Self {+ Self { documents, access }+ }+}++impl<Documents, Access> DocumentTaskDirectory<Documents, Access>+where+ Documents: DocumentService,+ Access: EntityAccessService,+{+ async fn view(+ &self,+ viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<+ (+ entity_access::domain::models::EntityAccessReceipt<ViewAccessLevel>,+ model::document::DocumentBasic,+ ),+ SessionTaskError,+ > {+ let receipt = self+ .access+ .generate_entity_access_receipt::<ViewAccessLevel>(+ viewer,+ None,+ task.as_str(),+ EntityType::Document,+ )+ .await+ .map_err(access_error)?;+ let document = self+ .documents+ .internal_get_basic_document(task.as_str())+ .await+ .map_err(document_error)?;+ Ok((receipt, document))+ }+}++impl<Documents, Access> TaskDirectory for DocumentTaskDirectory<Documents, Access>+where+ Documents: DocumentService,+ Access: EntityAccessService,+{+ async fn task(+ &self,+ viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<TaskFacts, SessionTaskError> {+ let (receipt, document) = self.view(viewer, task).await?;+ let identity = self+ .documents+ .get_task_identity(receipt, &document)+ .await+ .map_err(document_error)?;+ let short = MacroTaskId::from_short_uuid(&identity.short_id).ok_or_else(|| {+ SessionTaskError::Unavailable(rootcause::report!(+ "task short id {} is not a short uuid",+ identity.short_id+ ))+ })?;+ let team = identity+ .team_task+ .and_then(|team| TeamTaskReference::new(&team.team_slug, team.task_num));+ Ok(TaskFacts {+ id: task.clone(),+ title: identity.title,+ reference: pull_request_task_reference(&short, team.as_ref()),+ short_id: identity.short_id,+ })+ }++ async fn pull_requests(+ &self,+ viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<Vec<TaskPullRequest>, SessionTaskError> {+ let (receipt, document) = self.view(viewer, task).await?;+ let response = self+ .documents+ .get_task_github_pull_requests(receipt, &document)+ .await+ .map_err(document_error)?;+ Ok(response+ .pull_requests+ .into_iter()+ .map(task_pull_request)+ .collect())+ }+}++/// A task's pull request as the session tools show it.+fn task_pull_request(pull_request: GithubPullRequest) -> TaskPullRequest {+ let state = pull_request+ .status+ .as_deref()+ .and_then(|status| match status {+ "open" => Some(PullRequestState::Open),+ "closed" => Some(PullRequestState::Closed),+ "merged" => Some(PullRequestState::Merged),+ unknown => {+ tracing::warn!(status = unknown, github_key = %pull_request.github_key, "unknown pull request status");+ None+ }+ });+ TaskPullRequest {+ url: pull_request.url,+ title: pull_request.name,+ state,+ }+}++/// A hidden task and a missing one are the same answer.+fn access_error(error: AccessError) -> SessionTaskError {+ match error {+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_) => SessionTaskError::TaskNotFound,+ AccessError::BadRequest(_) => SessionTaskError::InvalidTaskReference,+ AccessError::Unavailable(report) | AccessError::Internal(report) => {+ SessionTaskError::Unavailable(report)+ }+ }+}++fn document_error(error: DocumentError) -> SessionTaskError {+ match error {+ DocumentError::NotFound(_) | DocumentError::Unauthorized | DocumentError::Gone => {+ SessionTaskError::TaskNotFound+ }+ // The documents service refuses task operations on other documents as a bad request.+ DocumentError::BadRequest(_) => SessionTaskError::NotATask,+ other => SessionTaskError::Unavailable(rootcause::report!("{other}")),+ }+}++/// [`TaskPullRequestLinker`] over the `github` crate's link service.+pub struct GithubTaskPullRequestLinker<Repo> {+ links: PullRequestTaskLinkService<Repo>,+}++impl<Repo: GithubSyncRepo> GithubTaskPullRequestLinker<Repo> {+ /// Wrap the `github` crate's link service.+ pub fn new(links: PullRequestTaskLinkService<Repo>) -> Self {+ Self { links }+ }+}++impl<Repo: GithubSyncRepo> TaskPullRequestLinker for GithubTaskPullRequestLinker<Repo> {+ async fn link(&self, github_key: &str, task: &TaskFacts) -> Result<(), SessionTaskError> {+ let malformed = || {+ SessionTaskError::Unavailable(rootcause::report!(+ "not an owner/repo/pull/number key: {github_key}"+ ))+ };+ let Some((owner, repo, number)) = github_key.split_once('/').and_then(|(owner, rest)| {+ rest.split_once("/pull/")+ .map(|(repo, number)| (owner, repo, number))+ }) else {+ return Err(malformed());+ };+ let number: u64 = number.parse().map_err(|_| malformed())?;+ let short = MacroTaskId::from_short_uuid(&task.short_id).ok_or_else(|| {+ SessionTaskError::Unavailable(rootcause::report!(+ "task short id {} is not a short uuid",+ task.short_id+ ))+ })?;+ self.links+ .link(GithubKey::new(owner, repo, number), short)+ .await+ .map_err(|error| SessionTaskError::Unavailable(rootcause::report!("{error}")))+ }+}diff --git a/crates/agent_harness/src/outbound/session_tasks/test.rs b/crates/agent_harness/src/outbound/session_tasks/test.rsnew file mode 100644index 0000000000..22ebaccd4b--- /dev/null+++ b/crates/agent_harness/src/outbound/session_tasks/test.rs@@ -0,0 +1,63 @@+use super::*;++fn pull_request(status: Option<&str>, name: Option<&str>) -> GithubPullRequest {+ let mut pull_request = GithubPullRequest::from_github_key("org/repo/pull/7").unwrap();+ pull_request.status = status.map(str::to_owned);+ pull_request.name = name.map(str::to_owned);+ pull_request+}++#[test]+fn maps_indexed_and_unindexed_pull_requests() {+ assert_eq!(+ task_pull_request(pull_request(Some("merged"), Some("Fix the thing"))),+ TaskPullRequest {+ url: "https://github.com/org/repo/pull/7".to_owned(),+ title: Some("Fix the thing".to_owned()),+ state: Some(PullRequestState::Merged),+ }+ );+ for (status, state) in [+ ("open", PullRequestState::Open),+ ("closed", PullRequestState::Closed),+ ] {+ assert_eq!(+ task_pull_request(pull_request(Some(status), None)).state,+ Some(state)+ );+ }+ assert_eq!(+ task_pull_request(pull_request(None, None)),+ TaskPullRequest {+ url: "https://github.com/org/repo/pull/7".to_owned(),+ title: None,+ state: None,+ }+ );+}++#[test]+fn hidden_and_missing_tasks_look_alike_and_other_documents_are_not_tasks() {+ assert!(matches!(+ access_error(AccessError::Unauthorized),+ SessionTaskError::TaskNotFound+ ));+ assert!(matches!(+ access_error(AccessError::NotFound("document")),+ SessionTaskError::TaskNotFound+ ));+ assert!(matches!(+ document_error(DocumentError::NotFound("task".to_owned())),+ SessionTaskError::TaskNotFound+ ));+ assert!(matches!(+ document_error(DocumentError::BadRequest(+ "document is not a task".to_owned()+ )),+ SessionTaskError::NotATask+ ));+ assert!(matches!(+ document_error(DocumentError::Internal(anyhow::anyhow!("database down"))),+ SessionTaskError::Unavailable(_)+ ));+}diff --git a/crates/agent_session/src/domain/coding_preferences.rs b/crates/agent_session/src/domain/coding_preferences.rsnew file mode 100644index 0000000000..85939a2d96--- /dev/null+++ b/crates/agent_session/src/domain/coding_preferences.rs@@ -0,0 +1,12 @@+//! What a user's new coding sessions are told to do beyond their assignment.++/// A user's choices for how new coding sessions deliver their work.+///+/// Every choice defaults to off.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct CodingPreferences {+ /// Research prior work and link each session to a Macro task.+ pub create_tasks: bool,+ /// Deliver the work as a pull request registered with the session.+ pub open_pull_requests: bool,+}diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rsindex 12e32f15b9..6a108abcee 100644--- a/crates/agent_session/src/domain/mod.rs+++ b/crates/agent_session/src/domain/mod.rs@@ -1,6 +1,7 @@/// Current authorization for agent session streams.pub mod audience;pub mod coding_agents;+pub mod coding_preferences;pub mod connection;/// Authorization of user and runtime session controls.pub mod control;@@ -17,6 +18,8 @@ mod sandbox_size;pub mod search;pub mod service;pub mod session;+/// The task a session works on, and linking its pull request to it.+pub mod session_task;/// Session link, channel, and team sharing.pub mod sharing;diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 3505fabe9c..9dbcb31da0 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -260,6 +260,8 @@ pub struct AgentSession {pub repo_branch: Option<super::repository_branch::RepositoryBranch>,/// The pull request associated with this session, independent of conversation history.pub pull_request_url: Option<String>,+ /// The Macro task the session was explicitly linked to.+ pub task_id: Option<String>,/// Directory the harness runs in, snapshotted at creation. The session/// actor sends it as the working directory of `session/new`, and resume/// and load re-enter it - the directory the session actually ran in,diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 8861d5bafc..fb67d46d19 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -1,5 +1,6 @@use std::pin::Pin;+use super::coding_preferences::CodingPreferences;use super::error::{AgentSessionError, Result};use super::model::*;use super::session::StopReason;@@ -541,6 +542,21 @@ pub trait AgentSessionRepo: Send + Sync + 'static {size: SandboxSize,) -> impl Future<Output = Result<()>> + Send;+ /// The user's coding preferences.+ ///+ /// A missing row is every preference off, not an error.+ fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<CodingPreferences>> + Send;++ /// Upsert the user's coding preferences, replacing every field.+ fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> impl Future<Output = Result<()>> + Send;+/// Delete an agent session by id.fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;diff --git a/crates/agent_session/src/domain/pull_request.rs b/crates/agent_session/src/domain/pull_request.rsindex b909b33a61..4b186131fd 100644--- a/crates/agent_session/src/domain/pull_request.rs+++ b/crates/agent_session/src/domain/pull_request.rs@@ -1,12 +1,14 @@//! Associating a pull request with a session, regardless of its harness.use std::pin::Pin;+use std::sync::Arc;use macro_user_id::user_id::MacroUserIdStr;use super::error::{AgentSessionError, Result};use super::model::{AgentSessionId, SessionClaim};use super::ports::{AgentSessionRealtime, AgentSessionRepo};+use super::session_task::SessionTasks;use tracing::Instrument;#[cfg(test)]@@ -41,12 +43,18 @@ pub trait SessionPullRequestRepo: Send + Sync {pub struct SessionPullRequestService<R, Rt> {repo: R,realtime: Rt,+ tasks: Arc<dyn SessionTasks>,}impl<R, Rt> SessionPullRequestService<R, Rt> {- /// Build the service using the same store and publisher as session logs.- pub fn new(repo: R, realtime: Rt) -> Self {- Self { repo, realtime }+ /// Build the service using the same store and publisher as session logs, linking each+ /// recorded pull request to the session's task.+ pub fn new(repo: R, realtime: Rt, tasks: Arc<dyn SessionTasks>) -> Self {+ Self {+ repo,+ realtime,+ tasks,+ }}}@@ -66,6 +74,7 @@ where"agent.session.set_pull_request",agent.session.id = %session,outcome = tracing::field::Empty,+ task_link = tracing::field::Empty,);Box::pin(async move {@@ -87,6 +96,17 @@ wheretracing::warn!(?error, "could not publish session metadata update");}}+ // The recorded PR stands even when its task link fails: the link is+ // idempotent and retried by the next set_pull_request or link_task.+ let task_link = self+ .tasks+ .link_session_pull_request(session, owner)+ .await+ .inspect_err(|error| {+ tracing::error!(error = ?error, "could not link session pull request to its task");+ });+ tracing::Span::current()+ .record("task_link", if task_link.is_ok() { "ok" } else { "failed" });Ok(url)}.await;diff --git a/crates/agent_session/src/domain/pull_request/test.rs b/crates/agent_session/src/domain/pull_request/test.rsindex e9a932e691..fe46e99841 100644--- a/crates/agent_session/src/domain/pull_request/test.rs+++ b/crates/agent_session/src/domain/pull_request/test.rs@@ -1,7 +1,38 @@use super::*;use crate::domain::ports::AgentSessionLogRepo;+use crate::domain::session_task::{LinkedTask, SessionTaskError, SessionTasks, TaskPullRequests};use crate::testing::{InMemoryAgentSessionRepo, RecordingRealtime, test_agent_session};+/// Sessions without tasks; linking a pull request to one has nothing to do.+struct NoTasks;++impl SessionTasks for NoTasks {+ fn link_task<'a>(+ &'a self,+ _session: AgentSessionId,+ _owner: &'a MacroUserIdStr<'static>,+ _task: &'a str,+ ) -> Pin<Box<dyn Future<Output = Result<LinkedTask, SessionTaskError>> + Send + 'a>> {+ unimplemented!("pull request tests link no tasks")+ }++ fn task_pull_requests<'a>(+ &'a self,+ _owner: &'a MacroUserIdStr<'static>,+ _task: &'a str,+ ) -> Pin<Box<dyn Future<Output = Result<TaskPullRequests, SessionTaskError>> + Send + 'a>> {+ unimplemented!("pull request tests list no tasks")+ }++ fn link_session_pull_request<'a>(+ &'a self,+ _session: AgentSessionId,+ _owner: &'a MacroUserIdStr<'static>,+ ) -> Pin<Box<dyn Future<Output = Result<(), SessionTaskError>> + Send + 'a>> {+ Box::pin(async { Ok(()) })+ }+}+#[test]fn normalizes_pr_urls_and_rejects_non_pr_destinations() {assert_eq!(@@ -35,7 +66,7 @@ async fn persists_and_publishes_once_and_rejects_another_owner() {let session = test_agent_session(AgentSessionId::new());repo.insert_session(session.clone());let realtime = RecordingRealtime::new();- let service = SessionPullRequestService::new(repo.clone(), realtime.clone());+ let service = SessionPullRequestService::new(repo.clone(), realtime.clone(), Arc::new(NoTasks));let url = "https://github.com/org/repo/pull/123";let other = MacroUserIdStr::try_from_email("[email protected]").unwrap();assert!(matches!(@@ -89,7 +120,8 @@ async fn gateway_failure_does_not_undo_the_persisted_link() {let repo = InMemoryAgentSessionRepo::new();let session = test_agent_session(AgentSessionId::new());repo.insert_session(session.clone());- let service = SessionPullRequestService::new(repo.clone(), RecordingRealtime::down());+ let service =+ SessionPullRequestService::new(repo.clone(), RecordingRealtime::down(), Arc::new(NoTasks));let url = "https://github.com/org/repo/pull/123";service.set_pull_request(session.id, session.owner_user().unwrap(), url, None)@@ -121,7 +153,7 @@ async fn superseded_claim_cannot_publish_even_an_unchanged_url() {panic!("reclaim")};let realtime = RecordingRealtime::new();- let service = SessionPullRequestService::new(repo.clone(), realtime.clone());+ let service = SessionPullRequestService::new(repo.clone(), realtime.clone(), Arc::new(NoTasks));let current_url = "https://github.com/org/repo/pull/2";service.set_pull_request(diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rsindex 242fcca82f..511df2ff37 100644--- a/crates/agent_session/src/domain/service.rs+++ b/crates/agent_session/src/domain/service.rs@@ -55,6 +55,7 @@ use tracing::instrument::WithSubscriber as _;use bots::domain::models::BotId;+use super::coding_preferences::CodingPreferences;use super::connection::RuntimeAttachment;use super::error::{AgentSessionError, Result};use super::lifecycle::session_identity;@@ -348,6 +349,19 @@ pub trait AgentSessionService: Send + Sync + 'static {user_id: &MacroUserIdStr<'static>,size: SandboxSize,) -> impl Future<Output = Result<()>> + Send;++ /// The user's coding preferences; every preference is off until set.+ fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> impl Future<Output = Result<CodingPreferences>> + Send;++ /// Upsert the user's coding preferences, replacing every field.+ fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> impl Future<Output = Result<()>> + Send;}/// Agent session service backed by one durable repository and local actors.@@ -1070,6 +1084,23 @@ where) -> Result<()> {self.repo.set_user_sandbox_size(user_id, size).await}++ async fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> Result<CodingPreferences> {+ self.repo.user_coding_preferences(user_id).await+ }++ async fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> Result<()> {+ self.repo+ .set_user_coding_preferences(user_id, preferences)+ .await+ }}async fn initial_prompt_for_rename<Folds>(@@ -1776,6 +1807,23 @@ whereself.repo.set_user_sandbox_size(user_id, size).await}+ async fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> Result<CodingPreferences> {+ self.repo.user_coding_preferences(user_id).await+ }++ async fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> Result<()> {+ self.repo+ .set_user_coding_preferences(user_id, preferences)+ .await+ }+async fn delete(&self, id: AgentSessionId) -> Result<()> {self.repo.delete(id).await}diff --git a/crates/agent_session/src/domain/service/test.rs b/crates/agent_session/src/domain/service/test.rsindex c5443593f1..50996a4729 100644--- a/crates/agent_session/src/domain/service/test.rs+++ b/crates/agent_session/src/domain/service/test.rs@@ -676,6 +676,23 @@ impl AgentSessionRepo for BlockingPromptLogs {self.repo.set_user_sandbox_size(user_id, size).await}+ async fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> Result<CodingPreferences> {+ self.repo.user_coding_preferences(user_id).await+ }++ async fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> Result<()> {+ self.repo+ .set_user_coding_preferences(user_id, preferences)+ .await+ }+async fn delete(&self, id: AgentSessionId) -> Result<()> {self.repo.delete(id).await}diff --git a/crates/agent_session/src/domain/session_task.rs b/crates/agent_session/src/domain/session_task.rsnew file mode 100644index 0000000000..22926f5ee4--- /dev/null+++ b/crates/agent_session/src/domain/session_task.rs@@ -0,0 +1,379 @@+//! The Macro task a coding session works on, and keeping the session's pull request linked to it.+//!+//! A session has at most one task: the one its agent linked, else the task whose thread+//! started it. Whenever a session has both a task and a pull request, the pull request is+//! linked to the task the same way the GitHub webhook links pull requests that reference one.++use std::pin::Pin;++use macro_user_id::user_id::MacroUserIdStr;+use messages::domain::models::MessageParent;+use tracing::Instrument;++use super::error::AgentSessionError;+use super::model::AgentSessionId;+use super::ports::{AgentSessionRealtime, AgentSessionRepo};++#[cfg(test)]+mod test;++/// Why a session's task could not be linked or read.+#[derive(Debug, thiserror::Error)]+pub enum SessionTaskError {+ /// The input names no task in a form this accepts.+ #[error(+ "expected a Macro task id, a MACRO-<id> reference, or a task link like https://macro.com/app/task/<id>"+ )]+ InvalidTaskReference,+ /// The task does not exist, or the session owner cannot view it.+ #[error("no task found that the session owner can view")]+ TaskNotFound,+ /// The document exists but is not a task.+ #[error("this document is not a task")]+ NotATask,+ /// The session could not be read or written.+ #[error(transparent)]+ Session(#[from] AgentSessionError),+ /// A task or pull request service failed.+ #[error("{0}")]+ Unavailable(rootcause::Report),+}++type Result<T, E = SessionTaskError> = std::result::Result<T, E>;++/// A task document id, parsed from what an agent was given.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct TaskDocumentId(String);++impl TaskDocumentId {+ /// Accept a task document id, a `MACRO-{short id}` reference, or a link whose path is+ /// `/app/task/{id}`.+ pub fn parse(input: &str) -> Result<Self> {+ let input = input.trim();+ if let Some((_, id)) = lazy_regex::regex_captures!(+ r"\A(?i:https?)://[^/\s?#]+/app/task/([^/\s?#]+)/*(?:[?#]\S*)?\z",+ input+ ) {+ return Self::from_uuid(id);+ }+ if let Some((_, short)) =+ lazy_regex::regex_captures!(r"\A(?i:macro)-([1-9A-HJ-NP-Za-km-z]+)\z", input)+ {+ return macro_uuid::ShortUuidConverter::default()+ .to_uuid(short)+ .map(|uuid| Self(uuid.to_string()))+ .map_err(|_| SessionTaskError::InvalidTaskReference);+ }+ Self::from_uuid(input)+ }++ fn from_uuid(input: &str) -> Result<Self> {+ uuid::Uuid::parse_str(input)+ .map(|uuid| Self(uuid.to_string()))+ .map_err(|_| SessionTaskError::InvalidTaskReference)+ }++ /// Wrap an id already stored as a task document id.+ pub fn from_stored(id: String) -> Self {+ Self(id)+ }++ /// The document id.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++/// A task as its viewer sees it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TaskFacts {+ /// The task document id.+ pub id: TaskDocumentId,+ /// The task title.+ pub title: String,+ /// The short id GitHub links key the task by.+ pub short_id: String,+ /// The text that links a pull request to the task when its description contains it.+ pub reference: String,+}++/// The task a session was linked to.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+pub struct LinkedTask {+ /// The task document id.+ pub task_id: String,+ /// The task title.+ pub title: String,+ /// Link to the task in Macro.+ pub url: String,+ /// Put this in the pull request description so GitHub activity reaches the task.+ pub reference: String,+ /// The session's pull request, now linked to the task, if it has one.+ pub pull_request: Option<String>,+}++/// Where a pull request is in its lifecycle.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+#[serde(rename_all = "snake_case")]+pub enum PullRequestState {+ /// Open.+ Open,+ /// Closed without merging.+ Closed,+ /// Merged.+ Merged,+}++/// A pull request linked to a task.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+pub struct TaskPullRequest {+ /// The pull request's GitHub URL.+ pub url: String,+ /// The pull request title, once Macro has indexed it.+ pub title: Option<String>,+ /// The pull request state, once Macro has indexed it.+ pub state: Option<PullRequestState>,+}++/// The pull requests linked to a task.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[cfg_attr(feature = "ai_tools", derive(schemars::JsonSchema))]+pub struct TaskPullRequests {+ /// The task document id.+ pub task_id: String,+ /// Linked pull requests, oldest link first.+ pub pull_requests: Vec<TaskPullRequest>,+}++/// Tasks as a user sees them.+pub trait TaskDirectory: Send + Sync {+ /// The task, if `viewer` can view it. Fails with [`SessionTaskError::TaskNotFound`] when+ /// it does not exist or is hidden, and [`SessionTaskError::NotATask`] for other documents.+ fn task(+ &self,+ viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> impl Future<Output = Result<TaskFacts>> + Send;++ /// The pull requests linked to a task `viewer` can view.+ fn pull_requests(+ &self,+ viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> impl Future<Output = Result<Vec<TaskPullRequest>>> + Send;+}++/// Links pull requests to tasks where the GitHub integration keeps those links.+pub trait TaskPullRequestLinker: Send + Sync {+ /// Link the pull request `owner/repo/pull/number` to the task. Additive and idempotent.+ fn link(&self, github_key: &str, task: &TaskFacts) -> impl Future<Output = Result<()>> + Send;+}++/// What replacing a session's task wrote.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct SessionTaskWrite {+ /// Whether the session was linked to a different task before.+ pub changed: bool,+ /// The session's pull request URL as of the write, so a pull request recorded+ /// concurrently is never missed.+ pub pull_request_url: Option<String>,+}++/// Persist a session's task.+pub trait SessionTaskRepo: Send + Sync {+ /// Replace the owner's session task.+ fn set_task(+ &self,+ session: AgentSessionId,+ owner: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> impl Future<Output = Result<SessionTaskWrite, AgentSessionError>> + Send;++ /// The task the session was explicitly linked to.+ fn task(+ &self,+ session: AgentSessionId,+ ) -> impl Future<Output = Result<Option<TaskDocumentId>, AgentSessionError>> + Send;+}++type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;++/// Session task operations used by the session MCP tools and by pull request recording.+pub trait SessionTasks: Send + Sync {+ /// Link the owner's session to a task, replacing any earlier one, and link the session's+ /// pull request to it.+ fn link_task<'a>(+ &'a self,+ session: AgentSessionId,+ owner: &'a MacroUserIdStr<'static>,+ task: &'a str,+ ) -> BoxFuture<'a, Result<LinkedTask>>;++ /// The pull requests linked to a task the owner can view.+ fn task_pull_requests<'a>(+ &'a self,+ owner: &'a MacroUserIdStr<'static>,+ task: &'a str,+ ) -> BoxFuture<'a, Result<TaskPullRequests>>;++ /// Link the session's pull request to the session's task, when it has both.+ fn link_session_pull_request<'a>(+ &'a self,+ session: AgentSessionId,+ owner: &'a MacroUserIdStr<'static>,+ ) -> BoxFuture<'a, Result<()>>;+}++/// [`SessionTasks`] over the session store, its realtime publisher, and the task and+/// GitHub domains.+pub struct SessionTaskService<Sessions, Links, Directory, Linker, Realtime> {+ sessions: Sessions,+ links: Links,+ directory: Directory,+ linker: Linker,+ realtime: Realtime,+ task_url_base: String,+}++impl<Sessions, Links, Directory, Linker, Realtime>+ SessionTaskService<Sessions, Links, Directory, Linker, Realtime>+{+ /// Build the service. Task links are `{app_url}/app/task/{id}`.+ pub fn new(+ sessions: Sessions,+ links: Links,+ directory: Directory,+ linker: Linker,+ realtime: Realtime,+ app_url: &str,+ ) -> Self {+ Self {+ sessions,+ links,+ directory,+ linker,+ realtime,+ task_url_base: format!("{}/app/task", app_url.trim_end_matches('/')),+ }+ }+}++impl<Sessions, Links, Directory, Linker, Realtime>+ SessionTaskService<Sessions, Links, Directory, Linker, Realtime>+where+ Sessions: AgentSessionRepo,+ Linker: TaskPullRequestLinker,+{+ async fn owned_session(+ &self,+ session: AgentSessionId,+ owner: &MacroUserIdStr<'static>,+ ) -> Result<super::model::AgentSession> {+ let stored = self.sessions.get(session).await?;+ if !stored.owner_id.is_user(owner) {+ return Err(AgentSessionError::Forbidden.into());+ }+ Ok(stored)+ }++ async fn link_pull_request(&self, pull_request_url: &str, task: &TaskFacts) -> Result<()> {+ let github_key = pull_request_url+ .strip_prefix("https://github.com/")+ .ok_or(AgentSessionError::InvalidPullRequestUrl)?;+ self.linker.link(github_key, task).await+ }+}++impl<Sessions, Links, Directory, Linker, Realtime> SessionTasks+ for SessionTaskService<Sessions, Links, Directory, Linker, Realtime>+where+ Sessions: AgentSessionRepo,+ Links: SessionTaskRepo,+ Directory: TaskDirectory,+ Linker: TaskPullRequestLinker,+ Realtime: AgentSessionRealtime + Send + Sync,+{+ fn link_task<'a>(+ &'a self,+ session: AgentSessionId,+ owner: &'a MacroUserIdStr<'static>,+ task: &'a str,+ ) -> BoxFuture<'a, Result<LinkedTask>> {+ let span = tracing::info_span!("agent.session.link_task", agent.session.id = %session);+ Box::pin(+ async move {+ self.owned_session(session, owner).await?;+ let task = TaskDocumentId::parse(task)?;+ let facts = self.directory.task(owner, &task).await?;+ let SessionTaskWrite {+ changed,+ pull_request_url: pull_request,+ } = self.links.set_task(session, owner, &facts.id).await?;+ if changed {+ // Persistence is authoritative; viewers refetch on reconnect.+ if let Err(error) = self.realtime.publish_updated(session).await {+ tracing::warn!(?error, "could not publish session metadata update");+ }+ }+ if let Some(url) = &pull_request {+ self.link_pull_request(url, &facts).await?;+ }+ Ok(LinkedTask {+ url: format!("{}/{}", self.task_url_base, facts.id.as_str()),+ task_id: facts.id.0,+ title: facts.title,+ reference: facts.reference,+ pull_request,+ })+ }+ .instrument(span),+ )+ }++ fn task_pull_requests<'a>(+ &'a self,+ owner: &'a MacroUserIdStr<'static>,+ task: &'a str,+ ) -> BoxFuture<'a, Result<TaskPullRequests>> {+ Box::pin(async move {+ let task = TaskDocumentId::parse(task)?;+ let pull_requests = self.directory.pull_requests(owner, &task).await?;+ Ok(TaskPullRequests {+ task_id: task.0,+ pull_requests,+ })+ })+ }++ fn link_session_pull_request<'a>(+ &'a self,+ session: AgentSessionId,+ owner: &'a MacroUserIdStr<'static>,+ ) -> BoxFuture<'a, Result<()>> {+ Box::pin(async move {+ let stored = self.owned_session(session, owner).await?;+ let Some(url) = stored.pull_request_url else {+ return Ok(());+ };+ if let Some(task) = self.links.task(session).await? {+ let facts = self.directory.task(owner, &task).await?;+ return self.link_pull_request(&url, &facts).await;+ }+ // A session started from a task's thread works on that task unless linked elsewhere.+ let Some(MessageParent::Document(document)) = stored.thread_parent else {+ return Ok(());+ };+ let Ok(task) = TaskDocumentId::from_uuid(&String::from(document)) else {+ return Ok(());+ };+ match self.directory.task(owner, &task).await {+ Ok(facts) => self.link_pull_request(&url, &facts).await,+ Err(SessionTaskError::NotATask | SessionTaskError::TaskNotFound) => Ok(()),+ Err(error) => Err(error),+ }+ })+ }+}diff --git a/crates/agent_session/src/domain/session_task/test.rs b/crates/agent_session/src/domain/session_task/test.rsnew file mode 100644index 0000000000..283c48baa5--- /dev/null+++ b/crates/agent_session/src/domain/session_task/test.rs@@ -0,0 +1,550 @@+use std::sync::{Arc, Mutex};++use super::*;+use crate::domain::pull_request::{SessionPullRequestService, SessionPullRequests};+use crate::testing::{InMemoryAgentSessionRepo, RecordingRealtime, test_agent_session};++const TASK: &str = "0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e6f";+const OTHER_TASK: &str = "0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e70";+const NOTE: &str = "0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e71";+const HIDDEN: &str = "0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e72";+const PULL_REQUEST: &str = "https://github.com/org/repo/pull/7";++/// Task documents keyed by id; `NOTE` is a document but not a task, `HIDDEN` a task the+/// owner cannot view.+#[derive(Clone, Default)]+struct FakeDirectory {+ pull_requests: Vec<TaskPullRequest>,+}++impl TaskDirectory for FakeDirectory {+ async fn task(+ &self,+ _viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<TaskFacts> {+ match task.as_str() {+ NOTE => Err(SessionTaskError::NotATask),+ TASK | OTHER_TASK => Ok(TaskFacts {+ id: task.clone(),+ title: format!("Task {}", &task.as_str()[34..]),+ short_id: format!("short-{}", &task.as_str()[34..]),+ reference: format!("ENG-{}", &task.as_str()[34..]),+ }),+ _ => Err(SessionTaskError::TaskNotFound),+ }+ }++ async fn pull_requests(+ &self,+ viewer: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<Vec<TaskPullRequest>> {+ self.task(viewer, task).await?;+ Ok(self.pull_requests.clone())+ }+}++/// Records `(github_key, task short id)` links; can be told to fail.+#[derive(Clone, Default)]+struct RecordingLinker {+ links: Arc<Mutex<Vec<(String, String)>>>,+ down: bool,+}++impl RecordingLinker {+ fn links(&self) -> Vec<(String, String)> {+ self.links.lock().unwrap().clone()+ }+}++impl TaskPullRequestLinker for RecordingLinker {+ async fn link(&self, github_key: &str, task: &TaskFacts) -> Result<()> {+ if self.down {+ return Err(SessionTaskError::Unavailable(rootcause::report!(+ "github links unavailable"+ )));+ }+ self.links+ .lock()+ .unwrap()+ .push((github_key.to_owned(), task.short_id.clone()));+ Ok(())+ }+}++/// Session tasks stored on the in-memory session store's sessions.+#[derive(Clone, Default)]+struct InMemorySessionTasks {+ sessions: InMemoryAgentSessionRepo,+}++impl SessionTaskRepo for InMemorySessionTasks {+ async fn set_task(+ &self,+ session: AgentSessionId,+ owner: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<SessionTaskWrite, AgentSessionError> {+ let mut stored = self.sessions.get(session).await?;+ if !stored.owner_id.is_user(owner) {+ return Err(AgentSessionError::Forbidden);+ }+ let changed = stored.task_id.as_deref() != Some(task.as_str());+ stored.task_id = Some(task.as_str().to_owned());+ let pull_request_url = stored.pull_request_url.clone();+ self.sessions.insert_session(stored);+ Ok(SessionTaskWrite {+ changed,+ pull_request_url,+ })+ }++ async fn task(+ &self,+ session: AgentSessionId,+ ) -> Result<Option<TaskDocumentId>, AgentSessionError> {+ Ok(self+ .sessions+ .get(session)+ .await?+ .task_id+ .map(TaskDocumentId::from_stored))+ }+}++struct Harness {+ sessions: InMemoryAgentSessionRepo,+ links: InMemorySessionTasks,+ linker: RecordingLinker,+ realtime: RecordingRealtime,+ tasks: Arc<dyn SessionTasks>,+ pull_requests: SessionPullRequestService<InMemoryAgentSessionRepo, RecordingRealtime>,+}++fn harness(linker: RecordingLinker, directory: FakeDirectory) -> Harness {+ harness_publishing_to(linker, directory, RecordingRealtime::new())+}++fn harness_publishing_to(+ linker: RecordingLinker,+ directory: FakeDirectory,+ realtime: RecordingRealtime,+) -> Harness {+ let sessions = InMemoryAgentSessionRepo::new();+ let links = InMemorySessionTasks {+ sessions: sessions.clone(),+ };+ let tasks: Arc<dyn SessionTasks> = Arc::new(SessionTaskService::new(+ sessions.clone(),+ links.clone(),+ directory,+ linker.clone(),+ realtime.clone(),+ "https://macro.com/",+ ));+ let pull_requests =+ SessionPullRequestService::new(sessions.clone(), RecordingRealtime::new(), tasks.clone());+ Harness {+ sessions,+ links,+ linker,+ realtime,+ tasks,+ pull_requests,+ }+}++fn seeded(harness: &Harness) -> crate::domain::model::AgentSession {+ let session = test_agent_session(AgentSessionId::new());+ harness.sessions.insert_session(session.clone());+ session+}++#[test]+fn parses_task_ids_links_and_macro_references() {+ let expected = TaskDocumentId(TASK.to_owned());+ let short =+ macro_uuid::ShortUuidConverter::default().from_uuid(&uuid::Uuid::parse_str(TASK).unwrap());+ for input in [+ TASK.to_owned(),+ format!(" {} ", TASK.to_uppercase()),+ format!("https://macro.com/app/task/{TASK}"),+ format!("https://dev.macro.com/app/task/{TASK}/?tab=activity#top"),+ format!("http://localhost:3000/app/task/{TASK}"),+ format!("MACRO-{short}"),+ format!("macro-{short}"),+ ] {+ assert_eq!(TaskDocumentId::parse(&input).unwrap(), expected, "{input}");+ }+ for invalid in [+ "",+ "ENG-42",+ "MACRO-0OIl",+ "not-a-task",+ &format!("https://macro.com/app/md/{TASK}"),+ &format!("https://macro.com/app/task/{TASK}/comments"),+ &format!("{TASK}x"),+ ] {+ assert!(+ matches!(+ TaskDocumentId::parse(invalid),+ Err(SessionTaskError::InvalidTaskReference)+ ),+ "{invalid}"+ );+ }+}++#[tokio::test]+async fn links_a_task_and_answers_its_link_and_reference() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let session = seeded(&harness);++ let linked = harness+ .tasks+ .link_task(+ session.id,+ session.owner_user().unwrap(),+ &format!("https://macro.com/app/task/{TASK}"),+ )+ .await+ .unwrap();++ assert_eq!(+ linked,+ LinkedTask {+ task_id: TASK.to_owned(),+ title: "Task 6f".to_owned(),+ url: format!("https://macro.com/app/task/{TASK}"),+ reference: "ENG-6f".to_owned(),+ pull_request: None,+ }+ );+ assert_eq!(+ harness.links.task(session.id).await.unwrap(),+ Some(TaskDocumentId(TASK.to_owned()))+ );+ assert!(harness.linker.links().is_empty());+}++#[tokio::test]+async fn relinking_replaces_the_session_task() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let session = seeded(&harness);+ let owner = session.owner_user().unwrap();++ harness+ .tasks+ .link_task(session.id, owner, TASK)+ .await+ .unwrap();+ harness+ .tasks+ .link_task(session.id, owner, OTHER_TASK)+ .await+ .unwrap();++ assert_eq!(+ harness.links.task(session.id).await.unwrap(),+ Some(TaskDocumentId(OTHER_TASK.to_owned()))+ );+}++#[tokio::test]+async fn publishes_a_session_update_only_when_the_task_changes() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let session = seeded(&harness);+ let owner = session.owner_user().unwrap();++ harness+ .tasks+ .link_task(session.id, owner, TASK)+ .await+ .unwrap();+ assert_eq!(harness.realtime.updated(), [session.id]);+ assert_eq!(+ harness+ .sessions+ .get(session.id)+ .await+ .unwrap()+ .task_id+ .as_deref(),+ Some(TASK)+ );++ harness+ .tasks+ .link_task(+ session.id,+ owner,+ &format!("https://macro.com/app/task/{TASK}"),+ )+ .await+ .unwrap();+ assert_eq!(harness.realtime.updated(), [session.id]);++ harness+ .tasks+ .link_task(session.id, owner, OTHER_TASK)+ .await+ .unwrap();+ assert_eq!(harness.realtime.updated(), [session.id, session.id]);+}++#[tokio::test]+async fn links_the_task_when_the_session_update_cannot_be_published() {+ let harness = harness_publishing_to(+ RecordingLinker::default(),+ FakeDirectory::default(),+ RecordingRealtime::down(),+ );+ let session = seeded(&harness);++ let linked = harness+ .tasks+ .link_task(session.id, session.owner_user().unwrap(), TASK)+ .await+ .unwrap();++ assert_eq!(linked.task_id, TASK);+ assert_eq!(+ harness.links.task(session.id).await.unwrap(),+ Some(TaskDocumentId(TASK.to_owned()))+ );+}++#[tokio::test]+async fn refuses_another_owner_a_document_that_is_not_a_task_and_a_hidden_task() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let session = seeded(&harness);+ let owner = session.owner_user().unwrap();+ let other = MacroUserIdStr::try_from_email("[email protected]").unwrap();++ assert!(matches!(+ harness.tasks.link_task(session.id, &other, TASK).await,+ Err(SessionTaskError::Session(AgentSessionError::Forbidden))+ ));+ assert!(matches!(+ harness.tasks.link_task(session.id, owner, NOTE).await,+ Err(SessionTaskError::NotATask)+ ));+ assert!(matches!(+ harness.tasks.link_task(session.id, owner, HIDDEN).await,+ Err(SessionTaskError::TaskNotFound)+ ));+ assert!(matches!(+ harness.tasks.link_task(session.id, owner, "ENG-42").await,+ Err(SessionTaskError::InvalidTaskReference)+ ));+ assert_eq!(harness.links.task(session.id).await.unwrap(), None);+ assert!(harness.realtime.updated().is_empty());+}++#[tokio::test]+async fn links_the_pull_request_when_the_task_comes_second() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let session = seeded(&harness);+ let owner = session.owner_user().unwrap();++ harness+ .pull_requests+ .set_pull_request(session.id, owner, PULL_REQUEST, None)+ .await+ .unwrap();+ assert!(harness.linker.links().is_empty());+ let linked = harness+ .tasks+ .link_task(session.id, owner, TASK)+ .await+ .unwrap();++ assert_eq!(linked.pull_request.as_deref(), Some(PULL_REQUEST));+ assert_eq!(+ harness.linker.links(),+ [("org/repo/pull/7".to_owned(), "short-6f".to_owned())]+ );+}++#[tokio::test]+async fn links_the_pull_request_when_the_task_comes_first() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let session = seeded(&harness);+ let owner = session.owner_user().unwrap();++ harness+ .tasks+ .link_task(session.id, owner, TASK)+ .await+ .unwrap();+ harness+ .pull_requests+ .set_pull_request(session.id, owner, PULL_REQUEST, None)+ .await+ .unwrap();++ assert_eq!(+ harness.linker.links(),+ [("org/repo/pull/7".to_owned(), "short-6f".to_owned())]+ );+}++#[tokio::test]+async fn a_session_started_from_a_task_thread_links_its_pull_request_to_that_task() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let mut session = test_agent_session(AgentSessionId::new());+ session.thread_parent = Some(MessageParent::Document(TASK.to_owned().try_into().unwrap()));+ harness.sessions.insert_session(session.clone());++ harness+ .pull_requests+ .set_pull_request(+ session.id,+ session.owner_user().unwrap(),+ PULL_REQUEST,+ None,+ )+ .await+ .unwrap();++ assert_eq!(+ harness.linker.links(),+ [("org/repo/pull/7".to_owned(), "short-6f".to_owned())]+ );+}++#[tokio::test]+async fn an_explicit_task_outranks_the_thread_task() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let mut session = test_agent_session(AgentSessionId::new());+ session.thread_parent = Some(MessageParent::Document(TASK.to_owned().try_into().unwrap()));+ harness.sessions.insert_session(session.clone());+ let owner = session.owner_user().unwrap();++ harness+ .tasks+ .link_task(session.id, owner, OTHER_TASK)+ .await+ .unwrap();+ harness+ .pull_requests+ .set_pull_request(session.id, owner, PULL_REQUEST, None)+ .await+ .unwrap();++ assert_eq!(+ harness.linker.links(),+ [("org/repo/pull/7".to_owned(), "short-70".to_owned())]+ );+}++#[tokio::test]+async fn a_thread_on_a_document_that_is_not_a_task_links_nothing() {+ let harness = harness(RecordingLinker::default(), FakeDirectory::default());+ let mut session = test_agent_session(AgentSessionId::new());+ session.thread_parent = Some(MessageParent::Document(NOTE.to_owned().try_into().unwrap()));+ harness.sessions.insert_session(session.clone());++ harness+ .pull_requests+ .set_pull_request(+ session.id,+ session.owner_user().unwrap(),+ PULL_REQUEST,+ None,+ )+ .await+ .unwrap();++ assert!(harness.linker.links().is_empty());+}++#[tokio::test]+async fn a_failed_task_link_keeps_the_recorded_pull_request() {+ let harness = harness(+ RecordingLinker {+ down: true,+ ..RecordingLinker::default()+ },+ FakeDirectory::default(),+ );+ let session = seeded(&harness);+ let owner = session.owner_user().unwrap();+ harness+ .tasks+ .link_task(session.id, owner, TASK)+ .await+ .unwrap();++ harness+ .pull_requests+ .set_pull_request(session.id, owner, PULL_REQUEST, None)+ .await+ .unwrap();++ assert_eq!(+ harness+ .sessions+ .get(session.id)+ .await+ .unwrap()+ .pull_request_url+ .as_deref(),+ Some(PULL_REQUEST)+ );+ // Linking the task again reports the failure, so the agent can retry.+ assert!(matches!(+ harness.tasks.link_task(session.id, owner, TASK).await,+ Err(SessionTaskError::Unavailable(_))+ ));+}++#[tokio::test]+async fn lists_a_tasks_pull_requests() {+ let pull_requests = vec![+ TaskPullRequest {+ url: PULL_REQUEST.to_owned(),+ title: Some("Fix the thing".to_owned()),+ state: Some(PullRequestState::Merged),+ },+ TaskPullRequest {+ url: "https://github.com/org/repo/pull/8".to_owned(),+ title: None,+ state: None,+ },+ ];+ let harness = harness(+ RecordingLinker::default(),+ FakeDirectory {+ pull_requests: pull_requests.clone(),+ },+ );+ let owner = MacroUserIdStr::try_from_email("[email protected]").unwrap();++ let listed = harness+ .tasks+ .task_pull_requests(&owner, &format!("https://macro.com/app/task/{TASK}"))+ .await+ .unwrap();++ assert_eq!(+ listed,+ TaskPullRequests {+ task_id: TASK.to_owned(),+ pull_requests,+ }+ );+ assert_eq!(+ serde_json::to_value(&listed.pull_requests[0]).unwrap(),+ serde_json::json!({+ "url": PULL_REQUEST,+ "title": "Fix the thing",+ "state": "merged",+ })+ );+ assert!(matches!(+ harness.tasks.task_pull_requests(&owner, HIDDEN).await,+ Err(SessionTaskError::TaskNotFound)+ ));+}diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 3eff1d158a..0c2c28d390 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -47,6 +47,7 @@ use model_owner::Owner;use serde::{Deserialize, Serialize};use utoipa::ToSchema;+use crate::domain::coding_preferences::CodingPreferences;use crate::domain::error::AgentSessionError;use crate::domain::model::{AgentSession, AgentSessionId, AgentSessionPreview, ExternalSession, Message, SandboxSize,@@ -292,6 +293,25 @@ where.with_state(state)}+/// Build the caller's coding preferences router. Mount at `/agent-coding-preferences`.+pub fn agent_coding_preferences_router<T, Access, Auth, S>(+ state: AgentSessionRouterState<T, Access, Auth>,+) -> Router<S>+where+ T: AgentSessionService,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+ S: Clone + Send + Sync + 'static,+{+ Router::new()+ .route(+ "/agent-coding-preferences",+ get(get_agent_coding_preferences_handler::<T, Access, Auth>)+ .put(put_agent_coding_preferences_handler::<T, Access, Auth>),+ )+ .with_state(state)+}+/// Transport error for agent session handlers.#[derive(Debug)]pub enum AgentSessionApiError {@@ -595,6 +615,8 @@ pub struct AgentSessionResponse {pub repo_url: Option<String>,/// The session's linked pull request.pub pull_request_url: Option<String>,+ /// The Macro task the session was linked to.+ pub task_id: Option<String>,/// The directory the session's harness runs in on its runtime.pub workspace: String,/// Compute tier of the managed sandbox.@@ -671,6 +693,7 @@ impl AgentSessionResponse {harness: session.harness,repo_url: session.repo_url,pull_request_url: session.pull_request_url,+ task_id: session.task_id,workspace: session.workspace,sandbox_size: session.sandbox_size,instructions: session.instructions,@@ -1388,6 +1411,100 @@ pub async fn put_agent_sandbox_size_handler<Ok(Json(req))}+/// Request or response body for the caller's coding preferences.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CodingPreferencesBody {+ /// Whether new coding sessions research prior work and link a Macro task.+ pub create_tasks: bool,+ /// Whether new coding sessions deliver their work as a pull request.+ pub open_pull_requests: bool,+}++impl From<CodingPreferences> for CodingPreferencesBody {+ fn from(preferences: CodingPreferences) -> Self {+ Self {+ create_tasks: preferences.create_tasks,+ open_pull_requests: preferences.open_pull_requests,+ }+ }+}++impl From<CodingPreferencesBody> for CodingPreferences {+ fn from(body: CodingPreferencesBody) -> Self {+ Self {+ create_tasks: body.create_tasks,+ open_pull_requests: body.open_pull_requests,+ }+ }+}++#[utoipa::path(+ get,+ path = "/agent-coding-preferences",+ tag = "agent-sessions",+ operation_id = "get_agent_coding_preferences",+ responses(+ (status = 200, body = CodingPreferencesBody),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Read what the caller's new coding sessions are told to do beyond their assignment.+#[tracing::instrument(skip_all, fields(actor = %caller.acting_entity()), err(Debug))]+pub async fn get_agent_coding_preferences_handler<+ T: AgentSessionService,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+) -> Result<Json<CodingPreferencesBody>, AgentSessionApiError> {+ let preferences = state+ .service+ .user_coding_preferences(&caller.authorization.user.macro_user_id)+ .await?;+ Ok(Json(preferences.into()))+}++#[utoipa::path(+ put,+ path = "/agent-coding-preferences",+ tag = "agent-sessions",+ operation_id = "put_agent_coding_preferences",+ request_body = CodingPreferencesBody,+ responses(+ (status = 200, body = CodingPreferencesBody),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Replace the caller's coding preferences.+#[tracing::instrument(+ skip_all,+ fields(+ actor = %caller.acting_entity(),+ create_tasks = req.create_tasks,+ open_pull_requests = req.open_pull_requests,+ ),+ err(Debug)+)]+pub async fn put_agent_coding_preferences_handler<+ T: AgentSessionService,+ Access: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,+ caller: MacroAuthorizationExtractor<Auth, ActingUser>,+ Json(req): Json<CodingPreferencesBody>,+) -> Result<Json<CodingPreferencesBody>, AgentSessionApiError> {+ state+ .service+ .set_user_coding_preferences(&caller.authorization.user.macro_user_id, req.into())+ .await?;+ Ok(Json(req))+}+/// One entry of a session's protocol log.////// Serializes as `{"userId": ..., "direction": ..., "content": ...}` - thediff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 8ffd7c0630..78e292ba58 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -209,6 +209,7 @@ impl SessionOpener for RecordingOpener {let session = AgentSession {repo_branch: None,pull_request_url: None,+ task_id: None,id: AgentSessionId::TEST_A,name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,@@ -246,6 +247,7 @@ impl SessionOpener for RecordingOpener {let session = AgentSession {repo_branch: None,pull_request_url: None,+ task_id: None,id: AgentSessionId::TEST_A,name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,@@ -462,6 +464,7 @@ impl ExternalSessionRequester for RecordingRequester {let session = AgentSession {repo_branch: None,pull_request_url: None,+ task_id: None,id: request.session_id,name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,@@ -1324,6 +1327,7 @@ async fn an_external_open_carries_its_instructions() {);}+mod coding_preferences;mod owned_purge;mod read;mod user_cleanup;diff --git a/crates/agent_session/src/inbound/axum_router/test/coding_preferences.rs b/crates/agent_session/src/inbound/axum_router/test/coding_preferences.rsnew file mode 100644index 0000000000..783b00e110--- /dev/null+++ b/crates/agent_session/src/inbound/axum_router/test/coding_preferences.rs@@ -0,0 +1,141 @@+use super::*;+use crate::domain::model::ReplicaId;+use crate::domain::ports::{+ NoOpAgentSessionNameGenerator, NoOpRealtime, NoOpTurnObserver, NoopLifecyclePublisher,+};+use crate::domain::service::AgentSessionServiceImpl;+use crate::testing::InMemoryAgentSessionRepo;++fn coding_preferences_router() -> Router {+ let repo = InMemoryAgentSessionRepo::new();+ let auth = MacroAuthorizationServiceImpl::new(+ FakeJwtValidator,+ InternalAuthConfig {+ api_key: "test-internal-key".into(),+ default_user_id: None,+ },+ SelfBotAuthorizer,+ NoUserApiKeyAuthorizer,+ );+ agent_coding_preferences_router(AgentSessionRouterState::new(+ AgentSessionServiceImpl::new(+ repo.clone(),+ agent_fold::domain::service::FoldedMessageService::new(repo),+ NoOpRealtime,+ NoOpAgentSessionNameGenerator,+ Arc::new(NoOpTurnObserver),+ Arc::new(NoopLifecyclePublisher),+ ReplicaId::mint(),+ ),+ Arc::new(entity_access::domain::ports::NoOpEntityAccessService),+ MacroAuthorizationState::new(Arc::new(auth)),+ ))+}++async fn json_body(response: Response) -> serde_json::Value {+ let body = axum::body::to_bytes(response.into_body(), 8192)+ .await+ .unwrap();+ serde_json::from_slice(&body).unwrap()+}++async fn read(router: &Router, caller: &str) -> serde_json::Value {+ let response = router+ .clone()+ .oneshot(+ Request::get("/agent-coding-preferences")+ .header(header::AUTHORIZATION, format!("Bearer {caller}"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ json_body(response).await+}++#[tokio::test]+async fn coding_preferences_are_off_until_the_caller_sets_them() {+ let router = coding_preferences_router();++ assert_eq!(+ read(&router, OWNER).await,+ serde_json::json!({ "createTasks": false, "openPullRequests": false })+ );++ let write = router+ .clone()+ .oneshot(+ Request::put("/agent-coding-preferences")+ .header(header::CONTENT_TYPE, "application/json")+ .header(header::AUTHORIZATION, format!("Bearer {OWNER}"))+ .body(Body::from(+ r#"{"createTasks":true,"openPullRequests":false}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(write.status(), StatusCode::OK);+ assert_eq!(+ json_body(write).await,+ serde_json::json!({ "createTasks": true, "openPullRequests": false })+ );+ assert_eq!(+ read(&router, OWNER).await,+ serde_json::json!({ "createTasks": true, "openPullRequests": false })+ );++ let replace = router+ .clone()+ .oneshot(+ Request::put("/agent-coding-preferences")+ .header(header::CONTENT_TYPE, "application/json")+ .header(header::AUTHORIZATION, format!("Bearer {OWNER}"))+ .body(Body::from(+ r#"{"createTasks":false,"openPullRequests":true}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(replace.status(), StatusCode::OK);+ assert_eq!(+ read(&router, OWNER).await,+ serde_json::json!({ "createTasks": false, "openPullRequests": true })+ );++ assert_eq!(+ read(&router, "macro|[email protected]").await,+ serde_json::json!({ "createTasks": false, "openPullRequests": false })+ );+}++#[tokio::test]+async fn coding_preferences_require_a_user() {+ let router = coding_preferences_router();++ let read = router+ .clone()+ .oneshot(+ Request::get("/agent-coding-preferences")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(read.status(), StatusCode::UNAUTHORIZED);++ let write = router+ .oneshot(+ Request::put("/agent-coding-preferences")+ .header(header::CONTENT_TYPE, "application/json")+ .body(Body::from(+ r#"{"createTasks":true,"openPullRequests":true}"#,+ ))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(write.status(), StatusCode::UNAUTHORIZED);+}diff --git a/crates/agent_session/src/inbound/mod.rs b/crates/agent_session/src/inbound/mod.rsindex 9135555bf1..1440b58fa7 100644--- a/crates/agent_session/src/inbound/mod.rs+++ b/crates/agent_session/src/inbound/mod.rs@@ -5,8 +5,8 @@ pub mod coding_agents;pub mod routine_sessions;pub use axum_router::{- AgentSessionControlState, AgentSessionRouterState, agent_sandbox_size_router,- agent_session_control_router, agent_session_read_router,+ AgentSessionControlState, AgentSessionRouterState, agent_coding_preferences_router,+ agent_sandbox_size_router, agent_session_control_router, agent_session_read_router,};#[cfg(feature = "ai_tools")]diff --git a/crates/agent_session/src/inbound/toolset/context.rs b/crates/agent_session/src/inbound/toolset/context.rsindex 0c655a4975..cd6ef8caa1 100644--- a/crates/agent_session/src/inbound/toolset/context.rs+++ b/crates/agent_session/src/inbound/toolset/context.rs@@ -2,13 +2,17 @@use std::sync::Arc;-use crate::domain::{model::AgentSessionId, pull_request::SessionPullRequests};+use crate::domain::{+ model::AgentSessionId, pull_request::SessionPullRequests, session_task::SessionTasks,+};-/// A session-bound tool context. The caller supplies only a URL.+/// A session-bound tool context. The caller supplies only the tool arguments.#[derive(Clone)]pub struct SessionToolContext {/// Shared session operation.pub service: Arc<dyn SessionPullRequests>,+ /// The session's task.+ pub tasks: Arc<dyn SessionTasks>,/// Session resolved from the request credential.pub session: AgentSessionId,}diff --git a/crates/agent_session/src/inbound/toolset/link_task.rs b/crates/agent_session/src/inbound/toolset/link_task.rsnew file mode 100644index 0000000000..8eef6b6057--- /dev/null+++ b/crates/agent_session/src/inbound/toolset/link_task.rs@@ -0,0 +1,53 @@+//! Link the calling session to the Macro task it works on.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::Deserialize;++use super::SessionToolContext;+use crate::domain::session_task::LinkedTask;++/// Link the calling session to a task.+#[derive(Debug, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+#[schemars(+ title = "link_task",+ description = "Link this coding session to the Macro task it works on, replacing any earlier link. The session's pull request, now or later, is linked to the task. Returns the task's id, title, link, and the reference to put in the pull request description."+)]+pub struct LinkTask {+ /// The task to link.+ #[schemars(+ description = "Macro task id, MACRO-<id> reference, or task link, e.g. https://macro.com/app/task/<id>"+ )]+ pub task: String,+}++impl ToolAnnotated for LinkTask {+ const ANNOTATIONS: ToolAnnotations =+ ToolAnnotations::destructive("Link task").with_idempotent();+}++#[async_trait]+impl AsyncTool<SessionToolContext> for LinkTask {+ type Output = LinkedTask;++ #[tracing::instrument(skip_all, err)]+ async fn call(+ &self,+ context: ServiceContext<SessionToolContext>,+ request: RequestContext,+ ) -> ToolResult<LinkedTask> {+ context+ .tasks+ .link_task(context.session, &request.user_id, &self.task)+ .await+ .map_err(|error| ToolCallError {+ description: error.to_string(),+ internal_error: error.into(),+ })+ }+}diff --git a/crates/agent_session/src/inbound/toolset/mod.rs b/crates/agent_session/src/inbound/toolset/mod.rsindex 6c55e29253..820ea5533e 100644--- a/crates/agent_session/src/inbound/toolset/mod.rs+++ b/crates/agent_session/src/inbound/toolset/mod.rs@@ -2,11 +2,15 @@mod coding_agents;mod context;+mod link_task;mod set_pull_request;+mod task_pull_requests;pub use coding_agents::{CodingAgentToolContext, DispatchCodingAgent, ListCodingAgents, ListCodingAgentsResponse,coding_agent_toolset,};pub use context::SessionToolContext;+pub use link_task::LinkTask;pub use set_pull_request::SetPullRequest;+pub use task_pull_requests::TaskPullRequestsTool;diff --git a/crates/agent_session/src/inbound/toolset/task_pull_requests.rs b/crates/agent_session/src/inbound/toolset/task_pull_requests.rsnew file mode 100644index 0000000000..663c92f8ef--- /dev/null+++ b/crates/agent_session/src/inbound/toolset/task_pull_requests.rs@@ -0,0 +1,52 @@+//! The pull requests linked to a Macro task.++use ai_toolset::{+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,+ ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::Deserialize;++use super::SessionToolContext;+use crate::domain::session_task::TaskPullRequests;++/// List a task's pull requests.+#[derive(Debug, Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+#[schemars(+ title = "task_pull_requests",+ description = "List the GitHub pull requests linked to a Macro task, with each one's URL, title and state (open, closed or merged; null until Macro has indexed it)."+)]+pub struct TaskPullRequestsTool {+ /// The task to look up.+ #[schemars(+ description = "Macro task id, MACRO-<id> reference, or task link, e.g. https://macro.com/app/task/<id>"+ )]+ pub task: String,+}++impl ToolAnnotated for TaskPullRequestsTool {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Task pull requests");+}++#[async_trait]+impl AsyncTool<SessionToolContext> for TaskPullRequestsTool {+ type Output = TaskPullRequests;++ #[tracing::instrument(skip_all, err)]+ async fn call(+ &self,+ context: ServiceContext<SessionToolContext>,+ request: RequestContext,+ ) -> ToolResult<TaskPullRequests> {+ context+ .tasks+ .task_pull_requests(&request.user_id, &self.task)+ .await+ .map_err(|error| ToolCallError {+ description: error.to_string(),+ internal_error: error.into(),+ })+ }+}diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex 4616806b6c..04c31c752a 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -12,10 +12,12 @@ mod test;mod pull_request;mod queue;mod recovery;+mod session_task;mod sharing;mod turn_state;mod working_branch;+use crate::domain::coding_preferences::CodingPreferences;use crate::domain::error::{AgentSessionError, Result};use crate::domain::model::{AgentMcpServers, AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreviewData,@@ -226,6 +228,7 @@ struct AgentSessionRow {repo_url: Option<String>,repo_branch: Option<String>,pull_request_url: Option<String>,+ task_id: Option<String>,workspace: String,sandbox_size: String,instructions: Option<String>,@@ -267,6 +270,7 @@ impl TryFrom<AgentSessionRow> for AgentSession {.transpose().map_err(anyhow::Error::msg)?,pull_request_url: row.pull_request_url,+ task_id: row.task_id,workspace: row.workspace,sandbox_size: parse_sandbox_size(&row.sandbox_size)?,instructions: row.instructions,@@ -356,7 +360,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)RETURNINGid, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, created_at, modified_at,(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)@@ -486,7 +490,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {r#"SELECTid, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)@@ -593,7 +597,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {r#"SELECTid, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)@@ -634,7 +638,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {r#"SELECTid, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)@@ -668,7 +672,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {r#"SELECTid, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)@@ -704,7 +708,7 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {r#"SELECTid, name, is_archived, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, task_id, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT jsonb_build_object('type', parent_entity_type, 'id', parent_entity_id)@@ -1050,6 +1054,54 @@ impl<B: BotFacts + 'static> AgentSessionRepo for PgAgentSessionRepo<B> {Ok(())}+ async fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> Result<CodingPreferences> {+ let preferences = sqlx::query!(+ r#"+ SELECT create_tasks, open_pull_requests+ FROM user_agent_coding_preferences+ WHERE user_id = $1+ "#,+ user_id.as_ref(),+ )+ .fetch_optional(&self.pool)+ .await+ .context("failed to read user coding preferences")?;+ Ok(preferences+ .map(|row| CodingPreferences {+ create_tasks: row.create_tasks,+ open_pull_requests: row.open_pull_requests,+ })+ .unwrap_or_default())+ }++ async fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO user_agent_coding_preferences+ (user_id, create_tasks, open_pull_requests, modified_at)+ VALUES ($1, $2, $3, NOW())+ ON CONFLICT (user_id) DO UPDATE+ SET create_tasks = EXCLUDED.create_tasks,+ open_pull_requests = EXCLUDED.open_pull_requests,+ modified_at = NOW()+ "#,+ user_id.as_ref(),+ preferences.create_tasks,+ preferences.open_pull_requests,+ )+ .execute(&self.pool)+ .await+ .context("failed to persist user coding preferences")?;+ Ok(())+ }+async fn list_queued_actions(&self, id: AgentSessionId) -> Result<Vec<StoredQueuedAction>> {self.load_queued_actions(id).await}diff --git a/crates/agent_session/src/outbound/postgres/session_task.rs b/crates/agent_session/src/outbound/postgres/session_task.rsnew file mode 100644index 0000000000..e2c9e4529a--- /dev/null+++ b/crates/agent_session/src/outbound/postgres/session_task.rs@@ -0,0 +1,51 @@+//! Persist the task a session works on.++use super::*;+use crate::domain::session_task::{SessionTaskRepo, SessionTaskWrite, TaskDocumentId};++impl<B: BotFacts + 'static> SessionTaskRepo for PgAgentSessionRepo<B> {+ async fn set_task(+ &self,+ session: AgentSessionId,+ owner: &MacroUserIdStr<'static>,+ task: &TaskDocumentId,+ ) -> Result<SessionTaskWrite> {+ // The subquery locks the row before reading the previous task, and RETURNING reads+ // under this write's lock, so a pull request recorded concurrently is either returned+ // here or recorded after this commits.+ let row = sqlx::query!(+ r#"+ UPDATE agent_session AS session SET task_id = $3+ FROM (+ SELECT id, task_id FROM agent_session WHERE id = $1 AND owner_id = $2 FOR UPDATE+ ) AS previous+ WHERE session.id = previous.id+ RETURNING+ session.pull_request_url,+ previous.task_id IS DISTINCT FROM $3 AS "changed!"+ "#,+ session.as_uuid(),+ owner.as_ref(),+ task.as_str(),+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(AgentSessionError::Forbidden)?;+ Ok(SessionTaskWrite {+ changed: row.changed,+ pull_request_url: row.pull_request_url,+ })+ }++ async fn task(&self, session: AgentSessionId) -> Result<Option<TaskDocumentId>> {+ let task = sqlx::query_scalar!(+ "SELECT task_id FROM agent_session WHERE id = $1",+ session.as_uuid(),+ )+ .fetch_one(&self.pool)+ .await+ .map_err(anyhow::Error::from)?;+ Ok(task.map(TaskDocumentId::from_stored))+ }+}diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 6c38be1445..5131670216 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -2,6 +2,7 @@ use super::*;mod queue;mod recovery;mod search;+mod session_task;mod user_cleanup;mod working_branch;use crate::domain::model::{AgentMcpServer, DEFAULT_AGENT_SESSION_NAME};@@ -787,6 +788,61 @@ async fn sandbox_size_round_trips_and_user_default_falls_back(pool: PgPool) {);}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn user_coding_preferences_default_off_and_upsert_both_fields(pool: PgPool) {+ let repo = test_repo(&pool);+ insert_user(&pool, OWNER).await;+ let owner = user_id(OWNER);++ assert_eq!(+ repo.user_coding_preferences(&owner)+ .await+ .expect("missing row"),+ CodingPreferences {+ create_tasks: false,+ open_pull_requests: false,+ }+ );++ repo.set_user_coding_preferences(+ &owner,+ CodingPreferences {+ create_tasks: true,+ open_pull_requests: false,+ },+ )+ .await+ .expect("insert");+ assert_eq!(+ repo.user_coding_preferences(&owner)+ .await+ .expect("inserted"),+ CodingPreferences {+ create_tasks: true,+ open_pull_requests: false,+ }+ );++ repo.set_user_coding_preferences(+ &owner,+ CodingPreferences {+ create_tasks: false,+ open_pull_requests: true,+ },+ )+ .await+ .expect("replace");+ assert_eq!(+ repo.user_coding_preferences(&owner)+ .await+ .expect("replaced"),+ CodingPreferences {+ create_tasks: false,+ open_pull_requests: true,+ }+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn get_missing_session_errors(pool: PgPool) {let repo = test_repo(&pool);diff --git a/crates/agent_session/src/outbound/postgres/test/session_task.rs b/crates/agent_session/src/outbound/postgres/test/session_task.rsnew file mode 100644index 0000000000..199b9c3404--- /dev/null+++ b/crates/agent_session/src/outbound/postgres/test/session_task.rs@@ -0,0 +1,83 @@+use super::*;+use crate::domain::pull_request::SessionPullRequestRepo;+use crate::domain::session_task::{SessionTaskRepo, SessionTaskWrite, TaskDocumentId};++async fn insert_task(pool: &PgPool, id: &str) {+ sqlx::query!(+ r#"INSERT INTO "Document" (id, name, owner, "fileType") VALUES ($1, 'Task', $2, 'md')"#,+ id,+ OWNER+ )+ .execute(pool)+ .await+ .expect("insert task document");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn stores_one_task_per_session_and_returns_the_pull_request(pool: PgPool) {+ let repo = test_repo(&pool);+ let bot = create_test_bot(&pool).await;+ let session = create_session(&repo, new_session(bot, None, None)).await;+ let owner = session.owner_user().unwrap();+ let first = TaskDocumentId::parse("0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e6f").unwrap();+ let second = TaskDocumentId::parse("0199c0a8-7d3e-7c1a-9b5e-3f2a1c4d5e70").unwrap();+ insert_task(&pool, first.as_str()).await;+ insert_task(&pool, second.as_str()).await;++ assert_eq!(repo.task(session.id).await.unwrap(), None);+ assert_eq!(+ repo.set_task(session.id, owner, &first).await.unwrap(),+ SessionTaskWrite {+ changed: true,+ pull_request_url: None,+ }+ );+ assert_eq!(+ repo.set_task(session.id, owner, &first).await.unwrap(),+ SessionTaskWrite {+ changed: false,+ pull_request_url: None,+ }+ );+ let url = "https://github.com/org/repo/pull/7";+ repo.record_pull_request(session.id, owner, url, None)+ .await+ .unwrap();+ assert_eq!(+ repo.set_task(session.id, owner, &second).await.unwrap(),+ SessionTaskWrite {+ changed: true,+ pull_request_url: Some(url.to_owned()),+ }+ );+ assert_eq!(repo.task(session.id).await.unwrap(), Some(second.clone()));+ assert_eq!(+ AgentSessionRepo::get(&repo, session.id)+ .await+ .unwrap()+ .task_id+ .as_deref(),+ Some(second.as_str())+ );++ let other = user_id("macro|[email protected]");+ assert!(matches!(+ repo.set_task(session.id, &other, &first).await,+ Err(AgentSessionError::Forbidden)+ ));+ assert_eq!(repo.task(session.id).await.unwrap(), Some(second.clone()));++ // Deleting the task unlinks it and keeps the session.+ sqlx::query!(r#"DELETE FROM "Document" WHERE id = $1"#, second.as_str())+ .execute(&pool)+ .await+ .unwrap();+ assert_eq!(repo.task(session.id).await.unwrap(), None);+ assert_eq!(+ AgentSessionRepo::get(&repo, session.id)+ .await+ .unwrap()+ .task_id,+ None+ );+}diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex ba01162c6f..cf8633c94f 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -4,6 +4,7 @@//! exercise their own logic against a real [`AgentSessionRepo`] ///! [`AgentSessionLogRepo`] contract without a database.+use crate::domain::coding_preferences::CodingPreferences;use crate::domain::error::{AgentSessionError, Result};use crate::domain::events::AgentSessionLifecycleEvent;use crate::domain::model::{@@ -74,6 +75,7 @@ pub struct InMemoryAgentSessionRepo {turn_states: Arc<Mutex<HashMap<AgentSessionId, agent_fold::domain::model::TurnState>>>,working_branches: Arc<Mutex<HashMap<AgentSessionId, String>>>,user_sizes: Arc<Mutex<HashMap<String, SandboxSize>>>,+ user_coding_preferences: Arc<Mutex<HashMap<String, CodingPreferences>>>,log_reads: Arc<AtomicUsize>,session_reads: Arc<AtomicUsize>,/// Replica heartbeats and published addresses, mirroring `harness_replica`.@@ -176,6 +178,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {let session = AgentSession {repo_branch: params.repo_branch,pull_request_url: None,+ task_id: None,id: params.id,name: DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,@@ -496,6 +499,31 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {Ok(())}+ async fn user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> Result<CodingPreferences> {+ Ok(self+ .user_coding_preferences+ .lock()+ .expect("in-memory session store is not poisoned")+ .get(user_id.as_ref())+ .copied()+ .unwrap_or_default())+ }++ async fn set_user_coding_preferences(+ &self,+ user_id: &MacroUserIdStr<'static>,+ preferences: CodingPreferences,+ ) -> Result<()> {+ self.user_coding_preferences+ .lock()+ .expect("in-memory session store is not poisoned")+ .insert(user_id.as_ref().to_owned(), preferences);+ Ok(())+ }+async fn delete(&self, id: AgentSessionId) -> Result<()> {let _transaction = self.log_transaction.lock().unwrap();self.history_boundaries.lock().unwrap().remove(&id);@@ -930,6 +958,7 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {AgentSession {repo_branch: None,pull_request_url: None,+ task_id: None,id,name: DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex f3d696994d..c21b8e569f 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -109,6 +109,7 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {AgentSession {repo_branch: None,pull_request_url: None,+ task_id: None,id,name: agent_session::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),is_archived: false,diff --git a/crates/documents/src/domain/models.rs b/crates/documents/src/domain/models.rsindex 02211c514d..376139b404 100644--- a/crates/documents/src/domain/models.rs+++ b/crates/documents/src/domain/models.rs@@ -93,6 +93,28 @@ pub struct TeamTaskMetadata {pub task_num: i32,}+/// A task's number within its team, with the team's slug: `{team_slug}-{task_num}`.+#[derive(Eq, PartialEq, Debug, Clone)]+pub struct TeamTaskNumber {+ /// The slug of the team the task is numbered in.+ pub team_slug: String,+ /// Monotonic task number within the team.+ pub task_num: i32,+}++/// What names a task outside Macro: its title, short id, and team number.+#[derive(Eq, PartialEq, Debug, Clone)]+pub struct TaskIdentity {+ /// The task document id.+ pub document_id: String,+ /// The task title.+ pub title: String,+ /// The short id of the task document.+ pub short_id: String,+ /// The task's team number, when it belongs to a team.+ pub team_task: Option<TeamTaskNumber>,+}+/// User/team information needed to build a task branch name.#[derive(Eq, PartialEq, Debug, Clone)]pub struct BranchNameContext {diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rsindex 2cd33fb470..220014d76b 100644--- a/crates/documents/src/domain/ports.rs+++ b/crates/documents/src/domain/ports.rs@@ -39,7 +39,7 @@ use super::models::{DocumentError, DocumentTeamShare, DocumentTeamShareResponse, EditDocumentRepoArgs,EditDocumentServiceArgs, EmailImportRepoOutcome, GithubPullRequestTasksResponse,GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs, LocationQueryParams, NewDocument,- OwnerTeam, TaskBranchName, TeamTaskMetadata,+ OwnerTeam, TaskBranchName, TaskIdentity, TeamTaskMetadata, TeamTaskNumber,};/// Repository for accessing document data from the database.@@ -217,6 +217,12 @@ pub trait DocumentRepo: Send + Sync + 'static {document_id: &str,) -> impl Future<Output = Result<Option<TeamTaskMetadata>, Self::Err>> + Send;+ /// Get a task's team number and team slug, when it is a team task.+ fn get_team_task_number(+ &self,+ document_id: &str,+ ) -> impl Future<Output = Result<Option<TeamTaskNumber>, Self::Err>> + Send;+/// Get the document ID assigned to a task number within a team.fn get_document_id_by_team_task_number(&self,@@ -530,6 +536,14 @@ pub trait DocumentService: Send + Sync + 'static {document_name: String,) -> impl Future<Output = Result<TaskBranchName, DocumentError>> + Send;+ /// Identify a task document: its title, short id and team number.+ /// Returns a bad request if the document is not a task.+ fn get_task_identity(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ document_context: &DocumentBasic,+ ) -> impl Future<Output = Result<TaskIdentity, DocumentError>> + Send;+/// Get GitHub pull requests associated with a task document.fn get_task_github_pull_requests(&self,diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex c980e0d8b3..de27ea82ed 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -66,7 +66,7 @@ use super::models::{EmailImportRepoOutcome, FileTypeUpdate, GithubPullRequest, GithubPullRequestTasks,GithubPullRequestTasksResponse, GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs,LocationQueryParams, MAX_GITHUB_PULL_REQUEST_TASK_LOOKUP, NewDocument, TaskBranchName,- TeamTaskMetadata,+ TaskIdentity, TeamTaskMetadata,};#[cfg(feature = "document_create")]use super::ports::create::DocumentCreationService;@@ -1248,6 +1248,34 @@ impl<})}+ #[tracing::instrument(err, skip(self, document_context))]+ async fn get_task_identity(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ document_context: &DocumentBasic,+ ) -> Result<TaskIdentity, DocumentError> {+ if document_context.sub_type != Some(DocumentSubType::Task) {+ return Err(DocumentError::BadRequest(+ "document is not a task".to_string(),+ ));+ }+ let document_id = &entity_access_receipt.entity().entity_id;+ if document_context.deleted_at.is_some() {+ return Err(DocumentError::NotFound(document_id.clone()));+ }+ let team_task = self+ .repo+ .get_team_task_number(document_id)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))?;+ Ok(TaskIdentity {+ document_id: document_id.clone(),+ title: document_context.document_name.clone(),+ short_id: short_id_for_entity_id(document_id)?,+ team_task,+ })+ }+#[tracing::instrument(err, skip(self, document_context))]async fn get_task_github_pull_requests(&self,diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex b016328d84..252a572fba 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -10,6 +10,7 @@ use std::sync::{Arc, Mutex};use crate::domain::models::{EmailImportRepoOutcome, GithubPullRequest, ImportEmailAttachmentRepoArgs, OwnerTeam,+ TeamTaskNumber,};use crate::domain::ports::{DocumentContentEventService, MockDocumentRepo};@@ -3430,3 +3431,67 @@ async fn github_pull_request_tasks_reject_oversized_lookups() {assert!(matches!(result, Err(DocumentError::BadRequest(_))));}++#[tokio::test]+async fn task_identity_names_a_team_task_by_its_team_number() {+ let document_id = "00000000-0000-0000-0000-000000000301";+ let mut repo = make_mock_repo();+ repo.expect_get_team_task_number()+ .withf(move |id| id == document_id)+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(Some(TeamTaskNumber {+ team_slug: "ENG".to_string(),+ task_num: 42,+ }))))+ });+ let service = make_test_service(repo);++ let identity = service+ .get_task_identity(+ authenticated_receipt(document_id),+ &task_document_context(document_id),+ )+ .await+ .unwrap();++ assert_eq!(+ identity,+ TaskIdentity {+ document_id: document_id.to_string(),+ title: "Test task".to_string(),+ short_id: short_id_for_entity_id(document_id).unwrap(),+ team_task: Some(TeamTaskNumber {+ team_slug: "ENG".to_string(),+ task_num: 42,+ }),+ }+ );+}++#[tokio::test]+async fn task_identity_rejects_a_document_that_is_not_a_task() {+ let document_id = "00000000-0000-0000-0000-000000000302";+ let service = make_test_service(make_mock_repo());+ let mut document = task_document_context(document_id);+ document.sub_type = None;++ let result = service+ .get_task_identity(authenticated_receipt(document_id), &document)+ .await;++ assert!(matches!(result, Err(DocumentError::BadRequest(_))));+}++#[tokio::test]+async fn task_identity_treats_a_deleted_task_as_missing() {+ let document_id = "00000000-0000-0000-0000-000000000303";+ let service = make_test_service(make_mock_repo());+ let mut document = task_document_context(document_id);+ document.deleted_at = Some(chrono::Utc::now());++ let result = service+ .get_task_identity(authenticated_receipt(document_id), &document)+ .await;++ assert!(matches!(result, Err(DocumentError::NotFound(_))));+}diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rsindex fea03e9d30..12c9a1b30b 100644--- a/crates/documents/src/inbound/axum_router/tests.rs+++ b/crates/documents/src/inbound/axum_router/tests.rs@@ -366,6 +366,14 @@ impl DocumentService for FakeDocumentService {panic!("unexpected get_task_branch_name call")}+ async fn get_task_identity(+ &self,+ _entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::ViewAccessLevel>,+ _document_context: &DocumentBasic,+ ) -> Result<crate::domain::models::TaskIdentity, DocumentError> {+ panic!("unexpected get_task_identity call")+ }+async fn get_task_github_pull_requests(&self,_entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::ViewAccessLevel>,diff --git a/crates/documents/src/inbound/toolset/edit_document/test.rs b/crates/documents/src/inbound/toolset/edit_document/test.rsindex c62a527717..c097425154 100644--- a/crates/documents/src/inbound/toolset/edit_document/test.rs+++ b/crates/documents/src/inbound/toolset/edit_document/test.rs@@ -226,6 +226,14 @@ impl DocumentService for FakeDocumentService {panic!("unexpected get_task_branch_name call")}+ async fn get_task_identity(+ &self,+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ _document_context: &DocumentBasic,+ ) -> Result<crate::domain::models::TaskIdentity, DocumentError> {+ panic!("unexpected get_task_identity call")+ }+async fn get_task_github_pull_requests(&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rsindex b169121af5..4df66a12b7 100644--- a/crates/documents/src/outbound/pg_document_repo.rs+++ b/crates/documents/src/outbound/pg_document_repo.rs@@ -28,7 +28,7 @@ use crate::domain::content::{DocumentContent, DocumentContentState};use crate::domain::models::{BranchNameContext, CopyDocumentRepoArgs, CreateDocumentRepoArgs, DocumentError,DocumentTeamShare, EditDocumentRepoArgs, EmailImportRepoOutcome, ImportEmailAttachmentRepoArgs,- OwnerTeam, TeamTaskMetadata,+ OwnerTeam, TeamTaskMetadata, TeamTaskNumber,};use crate::domain::ports::DocumentRepo;@@ -860,6 +860,25 @@ impl<B: BotFacts + 'static> DocumentRepo for PgDocumentRepo<B> {}))}+ #[tracing::instrument(err, skip(self))]+ async fn get_team_task_number(+ &self,+ document_id: &str,+ ) -> Result<Option<TeamTaskNumber>, Self::Err> {+ sqlx::query_as!(+ TeamTaskNumber,+ r#"+ SELECT t.slug AS "team_slug!", tt.task_num+ FROM team_task tt+ JOIN team t ON t.id = tt.team_id+ WHERE tt.document_id = $1+ "#,+ document_id,+ )+ .fetch_optional(&self.pool)+ .await+ }+#[tracing::instrument(err, skip(self))]async fn get_document_id_by_team_task_number(&self,diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rsindex 67bb856e2f..ed31f0ef02 100644--- a/crates/documents/src/outbound/pg_document_repo/tests.rs+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs@@ -16,7 +16,7 @@ use sqlx::{Pool, Postgres, Row};use crate::domain::models::{CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs, EmailImportRepoOutcome,FileTypeUpdate, GithubPullRequest, GithubPullRequestsResponse, ImportEmailAttachmentRepoArgs,- InitialLinkShare, NewDocument,+ InitialLinkShare, NewDocument, TeamTaskNumber,};use crate::domain::ports::DocumentRepo;use crate::outbound::pg_document_repo::PgDocumentRepo;@@ -1865,6 +1865,31 @@ async fn test_create_first_task_assigns_team_task_id_one(pool: Pool<Postgres>) {assert_eq!(task_metadata.task_num, 1);}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_get_team_task_number_names_the_team_slug(pool: Pool<Postgres>) {+ sqlx::query!("UPDATE team SET slug = 'ENG' WHERE id = $1", TEST_TEAM_ID)+ .execute(&pool)+ .await+ .unwrap();+ let repo = test_repo(pool);+ let task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;++ assert_eq!(+ repo.get_team_task_number(&task.document_id).await.unwrap(),+ Some(TeamTaskNumber {+ team_slug: "ENG".to_string(),+ task_num: 1,+ })+ );+ assert_eq!(+ repo.get_team_task_number(TEST_DOCUMENT_ID).await.unwrap(),+ None+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rsindex c074babadc..8978228f96 100644--- a/crates/github/src/domain/models.rs+++ b/crates/github/src/domain/models.rs@@ -33,7 +33,8 @@ pub use sync::{GithubAppInstallationSource, GithubAuthenticatedUser, GithubInstallationAccessToken,GithubInstallationSetupAction, GithubSetupAccessToken, GithubUserInstallation,GithubUserInstallationsPage, GithubWebhookEventType, MacroTaskId, ResolvedTeamTaskReference,- TeamTaskReference, ValidatedGithubWebhookEvent, extract_github_mentions, strip_markdown_code,+ TeamTaskReference, ValidatedGithubWebhookEvent, extract_github_mentions,+ pull_request_task_reference, strip_markdown_code,};/// Errors that can occur during github operations.#[derive(Debug, thiserror::Error)]diff --git a/crates/github/src/domain/models/sync.rs b/crates/github/src/domain/models/sync.rsindex c561822be9..0a9b7520b5 100644--- a/crates/github/src/domain/models/sync.rs+++ b/crates/github/src/domain/models/sync.rs@@ -631,6 +631,21 @@ impl TeamTaskReference {}}+/// The text to put in a pull request so the webhook links it to `task`: the team reference+/// when the webhook's parser reads it back, else `MACRO-{short_uuid}`.+pub fn pull_request_task_reference(task: &MacroTaskId, team: Option<&TeamTaskReference>) -> String {+ team.and_then(|team| {+ let reference = format!(+ "{}-{}",+ team.team_slug.to_ascii_uppercase(),+ team.team_task_id+ );+ (TeamTaskReference::extract_from_text(&reference).as_slice() == std::slice::from_ref(team))+ .then_some(reference)+ })+ .unwrap_or_else(|| task.to_task_id_string())+}+/// A [`TeamTaskReference`] resolved against a concrete team.////// Because team slugs are not unique, one reference can resolve in more thandiff --git a/crates/github/src/domain/models/test.rs b/crates/github/src/domain/models/test.rsindex b7cd65022f..0d11c2a7b6 100644--- a/crates/github/src/domain/models/test.rs+++ b/crates/github/src/domain/models/test.rs@@ -567,3 +567,27 @@ fn github_mentions_does_not_capture_trailing_hyphen() {let mentions = extract_github_mentions("ping @user- and @-nobody");assert_eq!(mentions, vec!["user"]);}++// ---------------------------------------------------------------------------+// pull_request_task_reference+// ---------------------------------------------------------------------------++#[test]+fn pull_request_task_reference_prefers_the_team_reference() {+ let task = MacroTaskId::from_short_uuid("2BuyvtY3ae").unwrap();+ let team = TeamTaskReference::new("ENG_CORE", 42).unwrap();+ let reference = pull_request_task_reference(&task, Some(&team));+ assert_eq!(reference, "ENG_CORE-42");+ assert_eq!(TeamTaskReference::extract_from_text(&reference), [team]);+}++#[test]+fn pull_request_task_reference_falls_back_to_the_macro_id() {+ let task = MacroTaskId::from_short_uuid("2BuyvtY3ae").unwrap();+ assert_eq!(pull_request_task_reference(&task, None), "MACRO-2BuyvtY3ae");+ // A slug the webhook's parser would not read back cannot be the reference.+ let unreadable = TeamTaskReference::new("A_VERY_LONG_TEAM_SLUG_NAME", 7).unwrap();+ let reference = pull_request_task_reference(&task, Some(&unreadable));+ assert_eq!(reference, "MACRO-2BuyvtY3ae");+ assert_eq!(MacroTaskId::extract_from_text(&reference), [task]);+}diff --git a/crates/github/src/domain/ports/mod.rs b/crates/github/src/domain/ports/mod.rsindex 4746fd5347..7dcc6fa7d7 100644--- a/crates/github/src/domain/ports/mod.rs+++ b/crates/github/src/domain/ports/mod.rs@@ -9,6 +9,8 @@ mod sync;#[cfg(feature = "link")]pub use link::{Auth, GithubLinkService, GithubOauth, GithubRepo};+#[cfg(all(test, feature = "sync"))]+pub use sync::MockGithubSyncRepo;#[cfg(feature = "sync")]pub use sync::{GithubInstallationLister, GithubPullRequestIndex, GithubRepositoryClient, GithubSyncClient,diff --git a/crates/github/src/domain/service/mod.rs b/crates/github/src/domain/service/mod.rsindex f8bda7f691..debb49b4d3 100644--- a/crates/github/src/domain/service/mod.rs+++ b/crates/github/src/domain/service/mod.rs@@ -5,6 +5,8 @@ mod installation_tokens;#[cfg(feature = "sync")]mod pull_request_index;#[cfg(feature = "sync")]+mod pull_request_tasks;+#[cfg(feature = "sync")]mod reachable_repositories;#[cfg(feature = "sync")]mod sync;@@ -14,6 +16,8 @@ pub use installation_tokens::{InstallationTokenConfig, InstallationTokenService}#[cfg(feature = "sync")]pub use pull_request_index::PullRequestIndexService;#[cfg(feature = "sync")]+pub use pull_request_tasks::PullRequestTaskLinkService;+#[cfg(feature = "sync")]pub use reachable_repositories::ReachableRepositoriesService;#[cfg(feature = "sync")]pub use sync::{GithubSyncConfig, GithubSyncServiceImpl};diff --git a/crates/github/src/domain/service/pull_request_tasks.rs b/crates/github/src/domain/service/pull_request_tasks.rsnew file mode 100644index 0000000000..74f8a07342--- /dev/null+++ b/crates/github/src/domain/service/pull_request_tasks.rs@@ -0,0 +1,38 @@+//! Linking a pull request to a Macro task from outside the webhook.+//!+//! The webhook links a pull request to the tasks its text references; a coding+//! session that knows both its task and its pull request links them directly.+//! Both write the same additive `github_pr_tasks` record, so later webhook+//! events (merge, close) reach the task either way.++use crate::domain::models::{GithubError, GithubKey, MacroTaskId};+use crate::domain::ports::GithubSyncRepo;++#[cfg(test)]+mod test;++/// Records pull request to task links.+pub struct PullRequestTaskLinkService<Repo> {+ repo: Repo,+}++impl<Repo: GithubSyncRepo> PullRequestTaskLinkService<Repo> {+ /// Build the service over the store the webhook links through.+ pub fn new(repo: Repo) -> Self {+ Self { repo }+ }++ /// Link `pull_request` to `task`. Linking an existing pair changes nothing,+ /// and other tasks linked to the pull request stay linked.+ #[tracing::instrument(skip(self), err)]+ pub async fn link(+ &self,+ pull_request: GithubKey,+ task: MacroTaskId,+ ) -> Result<(), GithubError> {+ self.repo+ .upsert_task_ids(pull_request, &[task])+ .await+ .map_err(|error| GithubError::Internal(error.into()))+ }+}diff --git a/crates/github/src/domain/service/pull_request_tasks/test.rs b/crates/github/src/domain/service/pull_request_tasks/test.rsnew file mode 100644index 0000000000..1a167ff713--- /dev/null+++ b/crates/github/src/domain/service/pull_request_tasks/test.rs@@ -0,0 +1,36 @@+use super::*;+use crate::domain::ports::MockGithubSyncRepo;++#[tokio::test]+async fn links_one_task_to_the_pull_request() {+ let task = MacroTaskId::from_short_uuid("2BuyvtY3ae").unwrap();+ let mut repo = MockGithubSyncRepo::new();+ let expected = task.clone();+ repo.expect_upsert_task_ids()+ .withf(move |key, tasks| {+ key.as_ref() == "macro-inc/macro/pull/7" && tasks == std::slice::from_ref(&expected)+ })+ .times(1)+ .returning(|_, _| Box::pin(std::future::ready(Ok(()))));+ PullRequestTaskLinkService::new(repo)+ .link(GithubKey::new("macro-inc", "macro", 7), task)+ .await+ .unwrap();+}++#[tokio::test]+async fn reports_a_failed_write() {+ let mut repo = MockGithubSyncRepo::new();+ repo.expect_upsert_task_ids().returning(|_, _| {+ Box::pin(std::future::ready(Err(anyhow::anyhow!(+ "database unavailable"+ ))))+ });+ let result = PullRequestTaskLinkService::new(repo)+ .link(+ GithubKey::new("macro-inc", "macro", 7),+ MacroTaskId::from_short_uuid("2BuyvtY3ae").unwrap(),+ )+ .await;+ assert!(matches!(result, Err(GithubError::Internal(_))));+}diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rsindex c65adef483..eaa2cdf5b3 100644--- a/crates/github/src/domain/service/sync/test.rs+++ b/crates/github/src/domain/service/sync/test.rs@@ -165,6 +165,13 @@ impl DocumentService for StubDocumentService {) -> Result<documents::domain::models::TaskBranchName, DocumentError> {unimplemented!()}+ async fn get_task_identity(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _document_context: &DocumentBasic,+ ) -> Result<documents::domain::models::TaskIdentity, DocumentError> {+ unimplemented!()+ }async fn get_task_github_pull_requests(&self,_receipt: EntityAccessReceipt<ViewAccessLevel>,diff --git a/crates/macro_db_client/migrations/20261009161059_user_agent_coding_preferences.down.sql b/crates/macro_db_client/migrations/20261009161059_user_agent_coding_preferences.down.sqlnew file mode 100644index 0000000000..5375e28bf4--- /dev/null+++ b/crates/macro_db_client/migrations/20261009161059_user_agent_coding_preferences.down.sql@@ -0,0 +1 @@+DROP TABLE user_agent_coding_preferences;diff --git a/crates/macro_db_client/migrations/20261009161059_user_agent_coding_preferences.up.sql b/crates/macro_db_client/migrations/20261009161059_user_agent_coding_preferences.up.sqlnew file mode 100644index 0000000000..e9e2fd7519--- /dev/null+++ b/crates/macro_db_client/migrations/20261009161059_user_agent_coding_preferences.up.sql@@ -0,0 +1,8 @@+-- What new coding-agent sessions for this user are told to do beyond their+-- assignment. A missing row is every preference off.+CREATE TABLE user_agent_coding_preferences (+ user_id TEXT PRIMARY KEY REFERENCES "User"("id") ON DELETE CASCADE,+ create_tasks BOOLEAN NOT NULL DEFAULT false,+ open_pull_requests BOOLEAN NOT NULL DEFAULT false,+ modified_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/crates/macro_db_client/migrations/20261009161100_agent_session_task_id.down.sql b/crates/macro_db_client/migrations/20261009161100_agent_session_task_id.down.sqlnew file mode 100644index 0000000000..467eb17e63--- /dev/null+++ b/crates/macro_db_client/migrations/20261009161100_agent_session_task_id.down.sql@@ -0,0 +1,2 @@+DROP INDEX idx_agent_session_task_id;+ALTER TABLE agent_session DROP COLUMN task_id;diff --git a/crates/macro_db_client/migrations/20261009161100_agent_session_task_id.up.sql b/crates/macro_db_client/migrations/20261009161100_agent_session_task_id.up.sqlnew file mode 100644index 0000000000..1bcf5cbd7e--- /dev/null+++ b/crates/macro_db_client/migrations/20261009161100_agent_session_task_id.up.sql@@ -0,0 +1,6 @@+-- The task a coding-agent session works on, at most one. Relinking replaces it;+-- deleting the task document unlinks it rather than deleting the session.+ALTER TABLE agent_session+ ADD COLUMN task_id TEXT REFERENCES "Document" (id) ON DELETE SET NULL;++CREATE INDEX idx_agent_session_task_id ON agent_session (task_id) WHERE task_id IS NOT NULL;diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 093f133c77..2d92ee2291 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -310,6 +310,12 @@ in Chromium with mocked session snapshots and realtime invalidation. This UI chedoes not prove live provider discovery; backend tests separately cover delayedprovider metadata.+When an agent links its session to a task with `macro_internal.link_task`, the+session header (and the side panel's **Task** row) shows a task chip before the+PR chip: the task title, or `Task` while loading or without access. Clicking it+opens the task in a new split (in place on touch devices). Linking a different+task sends the same session-update notification, so mounted headers refresh.+When the agent stops to ask a question the question takes the area in the passage'splace, cropped and expandable the same way: the prompt, then what is asked - a form'sfields (choice rows with an accent box, an `Other` row when the agent allows a free-textdiff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex f105aed2e4..db19013a4c 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -782,6 +782,9 @@ restart rules still apply.Settings → Agents → Agents / Runtimes render while their requests are pending.A pending Cursor model catalog shows `Loading models…` beside a disabled modelpicker; a failed catalog shows an inline error. The rest of settings stays usable.+Settings → Agents → Agents ends with **Coding sessions**: per-user **Create+tasks** and **Open pull requests** switches, both off by default. Each saves on+toggle and reverts with a toast if the save fails.With the `claude-cloud` feature flag enabled, Claude Cloud connection setup is inSettings → Agents → Runtimes, above Cursor, with thediff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.tsindex c515710766..036477d220 100644--- a/packages/sdk/generated/agent-harness/index.ts+++ b/packages/sdk/generated/agent-harness/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex f1b310ba71..afcdde9ab8 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';+import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -72,6 +72,27 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Read what the caller's new coding sessions are told to do beyond their assignment.+ */+ public getAgentCodingPreferences<ThrowOnError extends boolean = false>(options?: Options<GetAgentCodingPreferencesData, ThrowOnError>): RequestResult<GetAgentCodingPreferencesResponses, GetAgentCodingPreferencesErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<GetAgentCodingPreferencesResponses, GetAgentCodingPreferencesErrors, ThrowOnError>({ url: '/agent-coding-preferences', ...options });+ }++ /**+ * Replace the caller's coding preferences.+ */+ public putAgentCodingPreferences<ThrowOnError extends boolean = false>(options: Options<PutAgentCodingPreferencesData, ThrowOnError>): RequestResult<PutAgentCodingPreferencesResponses, PutAgentCodingPreferencesErrors, ThrowOnError> {+ return (options.client ?? this.client).put<PutAgentCodingPreferencesResponses, PutAgentCodingPreferencesErrors, ThrowOnError>({+ url: '/agent-coding-preferences',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Probe one provider's model catalog without creating an agent session.*/diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex b2430ad756..d7a01493f1 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -456,6 +456,10 @@ export type AgentSessionResponse = {* The session's status.*/status: SessionStatusDto;+ /**+ * The Macro task the session was linked to.+ */+ taskId?: string | null;/*** The channel `thread_id` lives in, when the session was spawned from a* channel thread. Derived from `thread_parent`.@@ -672,6 +676,20 @@ export type ChannelSharePermission = {channel_id: string;};+/**+ * Request or response body for the caller's coding preferences.+ */+export type CodingPreferencesBody = {+ /**+ * Whether new coding sessions research prior work and link a Macro task.+ */+ createTasks: boolean;+ /**+ * Whether new coding sessions deliver their work as a pull request.+ */+ openPullRequests: boolean;+};+/*** One-time manual code. Deliberately does not implement Debug.*/@@ -1550,6 +1568,46 @@ export type DiscoverAgentCapabilitiesHandlerResponses = {export type DiscoverAgentCapabilitiesHandlerResponse = DiscoverAgentCapabilitiesHandlerResponses[keyof DiscoverAgentCapabilitiesHandlerResponses];+export type GetAgentCodingPreferencesData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/agent-coding-preferences';+};++export type GetAgentCodingPreferencesErrors = {+ 401: string;+ 500: string;+};++export type GetAgentCodingPreferencesError = GetAgentCodingPreferencesErrors[keyof GetAgentCodingPreferencesErrors];++export type GetAgentCodingPreferencesResponses = {+ 200: CodingPreferencesBody;+};++export type GetAgentCodingPreferencesResponse = GetAgentCodingPreferencesResponses[keyof GetAgentCodingPreferencesResponses];++export type PutAgentCodingPreferencesData = {+ body: CodingPreferencesBody;+ path?: never;+ query?: never;+ url: '/agent-coding-preferences';+};++export type PutAgentCodingPreferencesErrors = {+ 401: string;+ 500: string;+};++export type PutAgentCodingPreferencesError = PutAgentCodingPreferencesErrors[keyof PutAgentCodingPreferencesErrors];++export type PutAgentCodingPreferencesResponses = {+ 200: CodingPreferencesBody;+};++export type PutAgentCodingPreferencesResponse = PutAgentCodingPreferencesResponses[keyof PutAgentCodingPreferencesResponses];+export type LoadAgentModelsHandlerData = {body: LoadAgentModelsRequest;path?: never;diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 735b9993b3..452b92b16e 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -62,6 +62,92 @@]}},+ "/agent-coding-preferences": {+ "get": {+ "tags": ["agent-sessions"],+ "summary": "Read what the caller's new coding sessions are told to do beyond their assignment.",+ "operationId": "get_agent_coding_preferences",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodingPreferencesBody"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["agent-sessions"],+ "summary": "Replace the caller's coding preferences.",+ "operationId": "put_agent_coding_preferences",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodingPreferencesBody"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CodingPreferencesBody"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/agent-models/load": {"post": {"tags": ["agent-models"],@@ -2847,6 +2933,10 @@"$ref": "#/components/schemas/SessionStatusDto","description": "The session's status."},+ "taskId": {+ "type": ["string", "null"],+ "description": "The Macro task the session was linked to."+ },"threadChannelId": {"type": ["string", "null"],"format": "uuid",@@ -3121,6 +3211,21 @@}}},+ "CodingPreferencesBody": {+ "type": "object",+ "description": "Request or response body for the caller's coding preferences.",+ "required": ["createTasks", "openPullRequests"],+ "properties": {+ "createTasks": {+ "type": "boolean",+ "description": "Whether new coding sessions research prior work and link a Macro task."+ },+ "openPullRequests": {+ "type": "boolean",+ "description": "Whether new coding sessions deliver their work as a pull request."+ }+ }+ },"CompleteRequest": {"type": "object","description": "One-time manual code. Deliberately does not implement Debug.",diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.tsindex bc80392328..9142113d93 100644--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts@@ -3,6 +3,7 @@ import type {AgentSessionChangesResponse,AgentSessionLogResponse,AgentSessionResponse,+ CodingPreferencesBody,ControlResponse,PromptAttachment,PullRequestLinkSource,@@ -287,6 +288,25 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {).size;}+ /** What the caller's new coding sessions are told to do beyond their assignment. */+ static async codingPreferences(+ client: MacroClient+ ): Promise<CodingPreferencesBody> {+ return unwrap(await client.agentHarness.getAgentCodingPreferences());+ }++ /** Replace the caller's coding preferences. */+ static async setCodingPreferences(+ client: MacroClient,+ preferences: CodingPreferencesBody+ ): Promise<CodingPreferencesBody> {+ return unwrap(+ await client.agentHarness.putAgentCodingPreferences({+ body: preferences,+ })+ );+ }+/*** Send a prompt or lifecycle operation to the live agent session.*diff --git a/packages/sdk/src/entities/agent-sessions/namespace.ts b/packages/sdk/src/entities/agent-sessions/namespace.tsindex a6f1899fb3..d4b8005743 100644--- a/packages/sdk/src/entities/agent-sessions/namespace.ts+++ b/packages/sdk/src/entities/agent-sessions/namespace.ts@@ -1,4 +1,7 @@-import type { SandboxSize } from '../../../generated/agent-harness/types.gen';+import type {+ CodingPreferencesBody,+ SandboxSize,+} from '../../../generated/agent-harness/types.gen';import type { MacroClient } from '../../utils/client';import {AgentSession,@@ -54,4 +57,16 @@ export class AgentSessionNamespace {setDefaultSandboxSize(size: SandboxSize): Promise<SandboxSize> {return AgentSession.setDefaultSandboxSize(this.client, size);}++ /** What the caller's new coding sessions are told to do beyond their assignment. */+ codingPreferences(): Promise<CodingPreferencesBody> {+ return AgentSession.codingPreferences(this.client);+ }++ /** Replace the caller's coding preferences. */+ setCodingPreferences(+ preferences: CodingPreferencesBody+ ): Promise<CodingPreferencesBody> {+ return AgentSession.setCodingPreferences(this.client, preferences);+ }}diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.tsindex 143ec9b4e0..8edbd6a30a 100644--- a/packages/sdk/tests/agent-sessions.test.ts+++ b/packages/sdk/tests/agent-sessions.test.ts@@ -191,6 +191,43 @@ describe('AgentSession', () => {]);});+ test('reads and replaces the caller coding preferences', async () => {+ const requests: Request[] = [];+ globalThis.fetch = (async (input) => {+ const request = input instanceof Request ? input : new Request(input);+ requests.push(request.clone());+ return Response.json(+ { createTasks: true, openPullRequests: false },+ { status: 200 }+ );+ }) as typeof fetch;+ const macro = new Macro({+ token: 'user-token',+ hosts: { 'agent-harness': 'https://agent.example.test' },+ });++ await expect(macro.agentSessions.codingPreferences()).resolves.toEqual({+ createTasks: true,+ openPullRequests: false,+ });+ await expect(+ macro.agentSessions.setCodingPreferences({+ createTasks: true,+ openPullRequests: false,+ })+ ).resolves.toEqual({ createTasks: true, openPullRequests: false });++ expect(requests.map((request) => request.method)).toEqual(['GET', 'PUT']);+ expect(requests.map((request) => request.url)).toEqual([+ 'https://agent.example.test/agent-coding-preferences',+ 'https://agent.example.test/agent-coding-preferences',+ ]);+ await expect(requests[1]?.json()).resolves.toEqual({+ createTasks: true,+ openPullRequests: false,+ });+ });+test('lists one repository branches through the agent-harness service', async () => {let request: Request | undefined;globalThis.fetch = (async (input) => {diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rsindex 7157a9ae6f..c8771a8bad 100644--- a/services/agent_harness_service/src/api.rs+++ b/services/agent_harness_service/src/api.rs@@ -21,8 +21,8 @@ use agent_session::domain::ports::{use agent_session::domain::service::AgentSessionService;use agent_session::inbound::axum_router::{AgentSessionControlState, AgentSessionRouterState, CreateSessionState,- agent_sandbox_size_router, agent_session_control_router, agent_session_create_router,- agent_session_read_router,+ agent_coding_preferences_router, agent_sandbox_size_router, agent_session_control_router,+ agent_session_create_router, agent_session_read_router,};use anyhow::Context;use axum::Router;@@ -256,7 +256,8 @@ where.merge(agent_changes_router(states.changes));Router::new().nest("/agent-sessions", agent_sessions)- .merge(agent_sandbox_size_router(states.read))+ .merge(agent_sandbox_size_router(states.read.clone()))+ .merge(agent_coding_preferences_router(states.read)).merge(agent_models_router(states.models)).merge(agent_repositories_router(states.repositories)).merge(states.claude_auth)diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rsindex f540c97623..7bba8e97cc 100644--- a/services/agent_harness_service/src/api/swagger.rs+++ b/services/agent_harness_service/src/api/swagger.rs@@ -28,10 +28,10 @@ use agent_session::inbound::axum_router::pull_requests::{};use agent_session::inbound::axum_router::{self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData,- AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, ControlRequest,- ControlResponse, ControlStatusDto, CreateAgentSessionRequest, CreateAgentSessionResponse,- CreateSessionThread, EditQueuedActionRequest, LogDirectionDto, LogFrameDto,- PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, QueuedActionDto,+ AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, CodingPreferencesBody,+ ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionRequest,+ CreateAgentSessionResponse, CreateSessionThread, EditQueuedActionRequest, LogDirectionDto,+ LogFrameDto, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, QueuedActionDto,RenameAgentSessionRequest, SandboxSizeBody, SessionStatusDto, SetAgentSessionArchivedRequest,WithAgentSessionId,};@@ -86,6 +86,8 @@ impl Modify for SecurityAddon {axum_router::put_agent_session_sandbox_size_handler,axum_router::get_agent_sandbox_size_handler,axum_router::put_agent_sandbox_size_handler,+ axum_router::get_agent_coding_preferences_handler,+ axum_router::put_agent_coding_preferences_handler,model_load::load_agent_models_handler,capability_discovery::discover_agent_capabilities_handler,repositories::list_agent_repositories_handler,@@ -137,6 +139,7 @@ impl Modify for SecurityAddon {LogDirectionDto,SandboxSize,SandboxSizeBody,+ CodingPreferencesBody,LoadAgentModelsRequest,LoadAgentModelsResponse,AgentModelDto,diff --git a/services/agent_harness_service/src/internal_mcp.rs b/services/agent_harness_service/src/internal_mcp.rsindex d83c074ca8..e6163e15b5 100644--- a/services/agent_harness_service/src/internal_mcp.rs+++ b/services/agent_harness_service/src/internal_mcp.rs@@ -4,8 +4,8 @@ use std::sync::Arc;use agent_session::domain::ports::AgentSessionRepo;use agent_session::{- domain::pull_request::SessionPullRequests,- inbound::toolset::{SessionToolContext, SetPullRequest},+ domain::{pull_request::SessionPullRequests, session_task::SessionTasks},+ inbound::toolset::{LinkTask, SessionToolContext, SetPullRequest, TaskPullRequestsTool},};use ai_toolset::{AsyncToolCollection, RequestContext, ToolSet};use axum::{@@ -32,13 +32,17 @@ use authenticated_session::AuthenticatedSession;mod test;fn toolset() -> AsyncToolCollection<SessionToolContext> {- AsyncToolCollection::new().add_tool::<SetPullRequest, SessionToolContext>()+ AsyncToolCollection::new()+ .add_tool::<SetPullRequest, SessionToolContext>()+ .add_tool::<LinkTask, SessionToolContext>()+ .add_tool::<TaskPullRequestsTool, SessionToolContext>()}/// Build the internal endpoint with per-request session authentication.pub fn router<A: AgentSessionRepo + 'static>(authority: Arc<A>,service: Arc<dyn SessionPullRequests>,+ tasks: Arc<dyn SessionTasks>,host: String,) -> Router {let mut config = StreamableHttpServerConfig::default().with_allowed_hosts([@@ -54,6 +58,7 @@ pub fn router<A: AgentSessionRepo + 'static>(move || {Ok(InternalTools {service: service.clone(),+ tasks: tasks.clone(),})},Arc::new(LocalSessionManager::default()),@@ -71,6 +76,7 @@ async fn authenticate(session: AuthenticatedSession, mut request: Request, next:struct InternalTools {service: Arc<dyn SessionPullRequests>,+ tasks: Arc<dyn SessionTasks>,}impl ServerHandler for InternalTools {@@ -138,6 +144,7 @@ impl ServerHandler for InternalTools {.try_tool_call(SessionToolContext {service: self.service.clone(),+ tasks: self.tasks.clone(),session: grant.id,},RequestContext::new(owner.clone()),diff --git a/services/agent_harness_service/src/internal_mcp/test.rs b/services/agent_harness_service/src/internal_mcp/test.rsindex 43634b21d2..b8d8a1a9e7 100644--- a/services/agent_harness_service/src/internal_mcp/test.rs+++ b/services/agent_harness_service/src/internal_mcp/test.rs@@ -2,6 +2,26 @@ use super::*;use agent_egress::domain::model::SessionToken;use axum::http::StatusCode;+#[test]+fn task_tools_accept_only_a_task() {+ let tools = toolset();+ for name in ["link_task", "task_pull_requests"] {+ let tool = tools.tools.get(name).unwrap();+ assert_eq!(tool.input_schema["additionalProperties"], false, "{name}");+ assert_eq!(+ tool.input_schema["required"],+ serde_json::json!(["task"]),+ "{name}"+ );+ }+ assert!(+ tools.tools["task_pull_requests"]+ .annotations+ .kind+ .read_only_hint()+ );+}+#[test]fn tool_schema_accepts_only_a_url() {let tools = toolset();@@ -19,6 +39,10 @@ use agent_session::{model::{AgentSessionId, SessionStatus},ports::{AgentSessionLogRepo, AgentSessionRepo},pull_request::SessionPullRequestService,+ session_task::{+ LinkedTask, PullRequestState, SessionTaskError, SessionTasks, TaskPullRequest,+ TaskPullRequests,+ },},testing::{InMemoryAgentSessionRepo, RecordingRealtime, test_agent_session},};@@ -28,6 +52,59 @@ use axum::{};use tower::ServiceExt;+type BoxFuture<'a, T> = std::pin::Pin<Box<dyn Future<Output = T> + Send + 'a>>;++/// Answers task tools with fixed values and records which session linked what.+#[derive(Clone, Default)]+struct FixedTasks {+ linked: Arc<std::sync::Mutex<Vec<(AgentSessionId, String)>>>,+}++impl SessionTasks for FixedTasks {+ fn link_task<'a>(+ &'a self,+ session: AgentSessionId,+ _owner: &'a macro_user_id::user_id::MacroUserIdStr<'static>,+ task: &'a str,+ ) -> BoxFuture<'a, Result<LinkedTask, SessionTaskError>> {+ self.linked.lock().unwrap().push((session, task.to_owned()));+ Box::pin(async move {+ Ok(LinkedTask {+ task_id: task.to_owned(),+ title: "Fix the thing".into(),+ url: format!("https://macro.com/app/task/{task}"),+ reference: "ENG-42".into(),+ pull_request: None,+ })+ })+ }++ fn task_pull_requests<'a>(+ &'a self,+ _owner: &'a macro_user_id::user_id::MacroUserIdStr<'static>,+ task: &'a str,+ ) -> BoxFuture<'a, Result<TaskPullRequests, SessionTaskError>> {+ Box::pin(async move {+ Ok(TaskPullRequests {+ task_id: task.to_owned(),+ pull_requests: vec![TaskPullRequest {+ url: "https://github.com/org/repo/pull/1".into(),+ title: Some("Fix the thing".into()),+ state: Some(PullRequestState::Open),+ }],+ })+ })+ }++ fn link_session_pull_request<'a>(+ &'a self,+ _session: AgentSessionId,+ _owner: &'a macro_user_id::user_id::MacroUserIdStr<'static>,+ ) -> BoxFuture<'a, Result<(), SessionTaskError>> {+ Box::pin(async { Ok(()) })+ }+}+async fn rpc(app: Router,token: Option<&str>,@@ -74,12 +151,15 @@ async fn each_harness_gets_only_internal_tools_and_writes_only_its_session() {repo.set_egress_token_hash(session.id, &SessionToken::new("secret").hash()).await.unwrap();+ let tasks = FixedTasks::default();let app = router(Arc::new(repo.clone()),Arc::new(SessionPullRequestService::new(repo.clone(),RecordingRealtime::new(),+ Arc::new(tasks.clone()),)),+ Arc::new(tasks.clone()),"localhost".into(),);assert_eq!(@@ -122,8 +202,69 @@ async fn each_harness_gets_only_internal_tools_and_writes_only_its_session() {).await;assert_eq!(status, StatusCode::OK, "{listed}");- assert_eq!(listed["result"]["tools"].as_array().unwrap().len(), 1);- assert_eq!(listed["result"]["tools"][0]["name"], "set_pull_request");+ let mut names: Vec<&str> = listed["result"]["tools"]+ .as_array()+ .unwrap()+ .iter()+ .map(|tool| tool["name"].as_str().unwrap())+ .collect();+ names.sort_unstable();+ assert_eq!(+ names,+ ["link_task", "set_pull_request", "task_pull_requests"]+ );+ let (_, linked) = rpc(+ app.clone(),+ Some("secret"),+ "tools/call",+ serde_json::json!({+ "name": "link_task", "arguments": {"task": "MACRO-abc"},+ }),+ )+ .await;+ assert_ne!(linked["result"]["isError"], true, "{linked}");+ let linked: serde_json::Value =+ serde_json::from_str(linked["result"]["content"][0]["text"].as_str().unwrap()).unwrap();+ assert_eq!(+ linked,+ serde_json::json!({+ "task_id": "MACRO-abc",+ "title": "Fix the thing",+ "url": "https://macro.com/app/task/MACRO-abc",+ "reference": "ENG-42",+ "pull_request": null,+ })+ );+ assert_eq!(+ *tasks.linked.lock().unwrap(),+ [(session.id, "MACRO-abc".to_owned())]+ );+ let (_, pull_requests) = rpc(+ app.clone(),+ Some("secret"),+ "tools/call",+ serde_json::json!({+ "name": "task_pull_requests", "arguments": {"task": "MACRO-abc"},+ }),+ )+ .await;+ let pull_requests: serde_json::Value = serde_json::from_str(+ pull_requests["result"]["content"][0]["text"]+ .as_str()+ .unwrap(),+ )+ .unwrap();+ assert_eq!(+ pull_requests,+ serde_json::json!({+ "task_id": "MACRO-abc",+ "pull_requests": [{+ "url": "https://github.com/org/repo/pull/1",+ "title": "Fix the thing",+ "state": "open",+ }],+ })+ );let (_, bad) = rpc(app.clone(), Some("secret"), "tools/call", serde_json::json!({"name": "set_pull_request", "arguments": {"url": "https://github.com/org/repo/pull/1", "session": other.id.as_uuid()},})).await;diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 824d7d0327..5379bcf72f 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -536,6 +536,14 @@ async fn run() -> anyhow::Result<()> {).await.context("failed to build the in-memory agent tool context")?;+ // Session tasks are read as the owner through the same services Macro's own tools use.+ let task_directory = agent_harness::outbound::session_tasks::DocumentTaskDirectory::new(+ tool_context.document_tool_context.service.clone(),+ tool_context+ .document_tool_context+ .entity_access_service+ .clone(),+ );// Macro's own tools run in-process here rather than through the egress// proxy, so they are held for the owner by the same approvals.let inmem_model_engine: Arc<dyn TurnEngine> = Arc::new(@@ -637,14 +645,30 @@ async fn run() -> anyhow::Result<()> {GithubSyncClientImpl::default(),),));+ let session_metadata_realtime = ConnectionGatewayAgentSessionRealtime::new(+ connection_gateway.clone(),+ session_audience.clone(),+ );+ let session_tasks: Arc<dyn agent_session::domain::session_task::SessionTasks> = Arc::new(+ agent_session::domain::session_task::SessionTaskService::new(+ session_repo.clone(),+ session_repo.clone(),+ task_directory,+ agent_harness::outbound::session_tasks::GithubTaskPullRequestLinker::new(+ github::domain::service::PullRequestTaskLinkService::new(PgGithubSyncRepo::new(+ pool.clone(),+ )),+ ),+ session_metadata_realtime.clone(),+ macro_service_urls::AppServiceUrl::new()?.as_ref(),+ ),+ );let session_pull_requests: Arc<dyn agent_session::domain::pull_request::SessionPullRequests> =Arc::new(agent_session::domain::pull_request::SessionPullRequestService::new(session_repo.clone(),- ConnectionGatewayAgentSessionRealtime::new(- connection_gateway.clone(),- session_audience.clone(),- ),+ session_metadata_realtime,+ session_tasks.clone(),),);let session_working_branches: Arc<@@ -661,6 +685,7 @@ async fn run() -> anyhow::Result<()> {let internal_mcp = internal_mcp::router(Arc::new(session_repo.clone()),session_pull_requests.clone(),+ session_tasks,url::Url::parse(&egress_base_url)?.host_str().context("egress URL needs a host")?