Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agents): share Home composer and honor repository selections (#6562)
Eric Hayes271fe45aef68
diff --git a/.sqlx/query-2cbb1c7ff427dccccb10a8a69655aa74bd2c8bc10ea5be567119f2934f35dd91.json b/.sqlx/query-205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba.jsonsimilarity index 76%rename from .sqlx/query-2cbb1c7ff427dccccb10a8a69655aa74bd2c8bc10ea5be567119f2934f35dd91.jsonrename to .sqlx/query-205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba.jsonindex 3131148510..8526744dea 100644--- a/.sqlx/query-2cbb1c7ff427dccccb10a8a69655aa74bd2c8bc10ea5be567119f2934f35dd91.json+++ b/.sqlx/query-205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ",+ "query": "\n SELECT\n id, name, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE egress_token_hash = $1\n ","describe": {"columns": [{@@ -50,86 +50,91 @@},{"ordinal": 9,- "name": "pull_request_url",+ "name": "repo_branch","type_info": "Text"},{"ordinal": 10,- "name": "workspace",+ "name": "pull_request_url","type_info": "Text"},{"ordinal": 11,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 12,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 13,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 14,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 15,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 15,+ "ordinal": 16,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "status","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "status_event_name","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 19,+ "ordinal": 20,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 20,+ "ordinal": 21,"name": "thread_channel_id?","type_info": "Uuid"},{- "ordinal": 21,+ "ordinal": 22,"name": "external_provider?","type_info": "Text"},{- "ordinal": 22,+ "ordinal": 23,"name": "external_id?","type_info": "Text"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_name?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_url?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_last_run_id?","type_info": "Text"}@@ -150,6 +155,7 @@false,true,true,+ true,false,false,true,@@ -168,5 +174,5 @@true]},- "hash": "2cbb1c7ff427dccccb10a8a69655aa74bd2c8bc10ea5be567119f2934f35dd91"+ "hash": "205a1accf8b5e0a08a8e46c7eb2911cdbd3ccc849309f9c2db63b6e6502d3dba"}diff --git a/.sqlx/query-af5efa2c953ccaf163da2f3aedeb5b4b6421888e28fbde42fab5ba9341576951.json b/.sqlx/query-23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a.jsonsimilarity index 74%rename from .sqlx/query-af5efa2c953ccaf163da2f3aedeb5b4b6421888e28fbde42fab5ba9341576951.jsonrename to .sqlx/query-23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a.jsonindex 7dc16ab3b9..35eece51ae 100644--- a/.sqlx/query-af5efa2c953ccaf163da2f3aedeb5b4b6421888e28fbde42fab5ba9341576951.json+++ b/.sqlx/query-23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ",+ "query": "\n SELECT\n id, name, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY agent_session.created_at DESC\n LIMIT 1\n ","describe": {"columns": [{@@ -50,86 +50,91 @@},{"ordinal": 9,- "name": "pull_request_url",+ "name": "repo_branch","type_info": "Text"},{"ordinal": 10,- "name": "workspace",+ "name": "pull_request_url","type_info": "Text"},{"ordinal": 11,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 12,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 13,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 14,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 15,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 15,+ "ordinal": 16,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "status","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "status_event_name","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 19,+ "ordinal": 20,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 20,+ "ordinal": 21,"name": "thread_channel_id?","type_info": "Uuid"},{- "ordinal": 21,+ "ordinal": 22,"name": "external_provider?","type_info": "Text"},{- "ordinal": 22,+ "ordinal": 23,"name": "external_id?","type_info": "Text"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_name?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_url?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_last_run_id?","type_info": "Text"}@@ -151,6 +156,7 @@false,true,true,+ true,false,false,true,@@ -169,5 +175,5 @@true]},- "hash": "af5efa2c953ccaf163da2f3aedeb5b4b6421888e28fbde42fab5ba9341576951"+ "hash": "23628bbbc5c35de5511a1473dceaa2f6f3ac861a56a9292f8b728ea544d46a2a"}diff --git a/.sqlx/query-be9f5e8e09e15c6d2fdabced0cafc13771ce7f78888368ae09ca74346ea349e1.json b/.sqlx/query-25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4.jsonsimilarity index 75%rename from .sqlx/query-be9f5e8e09e15c6d2fdabced0cafc13771ce7f78888368ae09ca74346ea349e1.jsonrename to .sqlx/query-25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4.jsonindex ab22c92a2f..a859cfcccd 100644--- a/.sqlx/query-be9f5e8e09e15c6d2fdabced0cafc13771ce7f78888368ae09ca74346ea349e1.json+++ b/.sqlx/query-25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ",+ "query": "\n SELECT\n id, name, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ","describe": {"columns": [{@@ -50,86 +50,91 @@},{"ordinal": 9,- "name": "pull_request_url",+ "name": "repo_branch","type_info": "Text"},{"ordinal": 10,- "name": "workspace",+ "name": "pull_request_url","type_info": "Text"},{"ordinal": 11,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 12,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 13,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 14,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 15,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 15,+ "ordinal": 16,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "status","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "status_event_name","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 19,+ "ordinal": 20,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 20,+ "ordinal": 21,"name": "thread_channel_id?","type_info": "Uuid"},{- "ordinal": 21,+ "ordinal": 22,"name": "external_provider?","type_info": "Text"},{- "ordinal": 22,+ "ordinal": 23,"name": "external_id?","type_info": "Text"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_name?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_url?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_last_run_id?","type_info": "Text"}@@ -150,6 +155,7 @@false,true,true,+ true,false,false,true,@@ -168,5 +174,5 @@true]},- "hash": "be9f5e8e09e15c6d2fdabced0cafc13771ce7f78888368ae09ca74346ea349e1"+ "hash": "25a11c79c03cc2c700b6ffbeb460daa7ce462e3b28cd04e0ab90018239051df4"}diff --git a/.sqlx/query-fe12b72ea6b29ba12c55fe64823261dfb43bf5a44ccb54f42c3e9eed226362ad.json b/.sqlx/query-97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132.jsonsimilarity index 76%rename from .sqlx/query-fe12b72ea6b29ba12c55fe64823261dfb43bf5a44ccb54f42c3e9eed226362ad.jsonrename to .sqlx/query-97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132.jsonindex 6f4e0a9195..84af580196 100644--- a/.sqlx/query-fe12b72ea6b29ba12c55fe64823261dfb43bf5a44ccb54f42c3e9eed226362ad.json+++ b/.sqlx/query-97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE thread_id = $1\n ORDER BY agent_session.created_at DESC\n ",+ "query": "\n SELECT\n id, name, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE id = $1\n ","describe": {"columns": [{@@ -50,86 +50,91 @@},{"ordinal": 9,- "name": "pull_request_url",+ "name": "repo_branch","type_info": "Text"},{"ordinal": 10,- "name": "workspace",+ "name": "pull_request_url","type_info": "Text"},{"ordinal": 11,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 12,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 13,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 14,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 15,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 15,+ "ordinal": 16,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "status","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "status_event_name","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 19,+ "ordinal": 20,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 20,+ "ordinal": 21,"name": "thread_channel_id?","type_info": "Uuid"},{- "ordinal": 21,+ "ordinal": 22,"name": "external_provider?","type_info": "Text"},{- "ordinal": 22,+ "ordinal": 23,"name": "external_id?","type_info": "Text"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_name?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_url?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_last_run_id?","type_info": "Text"}@@ -150,6 +155,7 @@false,true,true,+ true,false,false,true,@@ -168,5 +174,5 @@true]},- "hash": "fe12b72ea6b29ba12c55fe64823261dfb43bf5a44ccb54f42c3e9eed226362ad"+ "hash": "97ef237eb6866b33fe847279d4751ade9631b5b1c1e87a059dccbe72cdc57132"}diff --git a/.sqlx/query-96a95fcf9297f63118798a7ec8c36fdfdb9c81466f30cbe4da25acb3a51f0d68.json b/.sqlx/query-9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836.jsonsimilarity index 75%rename from .sqlx/query-96a95fcf9297f63118798a7ec8c36fdfdb9c81466f30cbe4da25acb3a51f0d68.jsonrename to .sqlx/query-9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836.jsonindex d1a448b678..cd816ecd69 100644--- a/.sqlx/query-96a95fcf9297f63118798a7ec8c36fdfdb9c81466f30cbe4da25acb3a51f0d68.json+++ b/.sqlx/query-9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, sandbox_size, instructions,\n acp_session_id, status, status_event_name, egress_token_hash,\n mcp_scope, mcp_servers\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)\n RETURNING\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ",+ "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\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)\n RETURNING\n id, name, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n -- A row being created cannot have an external identity yet.\n NULL::TEXT AS \"external_provider?\", NULL::TEXT AS \"external_id?\",\n NULL::TEXT AS \"external_name?\", NULL::TEXT AS \"external_url?\",\n NULL::TEXT AS \"external_last_run_id?\"\n ","describe": {"columns": [{@@ -50,86 +50,91 @@},{"ordinal": 9,- "name": "pull_request_url",+ "name": "repo_branch","type_info": "Text"},{"ordinal": 10,- "name": "workspace",+ "name": "pull_request_url","type_info": "Text"},{"ordinal": 11,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 12,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 13,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 14,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 15,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 15,+ "ordinal": 16,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "status","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "status_event_name","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 19,+ "ordinal": 20,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 20,+ "ordinal": 21,"name": "thread_channel_id?","type_info": "Uuid"},{- "ordinal": 21,+ "ordinal": 22,"name": "external_provider?","type_info": "Text"},{- "ordinal": 22,+ "ordinal": 23,"name": "external_id?","type_info": "Text"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_name?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_url?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_last_run_id?","type_info": "Text"}@@ -152,7 +157,8 @@"Text","Text","Text",- "Jsonb"+ "Jsonb",+ "Text"]},"nullable": [@@ -166,6 +172,7 @@false,true,true,+ true,false,false,true,@@ -184,5 +191,5 @@null]},- "hash": "96a95fcf9297f63118798a7ec8c36fdfdb9c81466f30cbe4da25acb3a51f0d68"+ "hash": "9c81dc959ddc96e6d9bcd928bb4827184e90f2ece1838299f3d67dda72485836"}diff --git a/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json b/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.jsonnew file mode 100644index 0000000000..ac476c9a0b--- /dev/null+++ b/.sqlx/query-b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT history_start_log_id FROM agent_session WHERE id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "history_start_log_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "b16931ecba057b16bf4028b613bf9f85761fe643ceb64b3185db814f1ea1a5d7"+}diff --git a/.sqlx/query-a6aa77d4a9a024f7446bd25c1b167d0959d829b815df02b5f7092d1c59e3987f.json b/.sqlx/query-dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657.jsonsimilarity index 74%rename from .sqlx/query-a6aa77d4a9a024f7446bd25c1b167d0959d829b815df02b5f7092d1c59e3987f.jsonrename to .sqlx/query-dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657.jsonindex 60538cc8dc..cd8a82b181 100644--- a/.sqlx/query-a6aa77d4a9a024f7446bd25c1b167d0959d829b815df02b5f7092d1c59e3987f.json+++ b/.sqlx/query-dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n id, name, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ",+ "query": "\n SELECT\n id, name, 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 channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\",\n ext.provider AS \"external_provider?\", ext.external_id AS \"external_id?\",\n ext.external_name AS \"external_name?\", ext.external_url AS \"external_url?\",\n ext.last_run_id AS \"external_last_run_id?\"\n FROM agent_session\n LEFT JOIN external_agent_session AS ext ON ext.agent_session_id = agent_session.id\n WHERE owner_id = $1\n ORDER BY agent_session.created_at DESC, id DESC\n LIMIT $2\n ","describe": {"columns": [{@@ -50,86 +50,91 @@},{"ordinal": 9,- "name": "pull_request_url",+ "name": "repo_branch","type_info": "Text"},{"ordinal": 10,- "name": "workspace",+ "name": "pull_request_url","type_info": "Text"},{"ordinal": 11,- "name": "sandbox_size",+ "name": "workspace","type_info": "Text"},{"ordinal": 12,- "name": "instructions",+ "name": "sandbox_size","type_info": "Text"},{"ordinal": 13,- "name": "mcp_scope",+ "name": "instructions","type_info": "Text"},{"ordinal": 14,+ "name": "mcp_scope",+ "type_info": "Text"+ },+ {+ "ordinal": 15,"name": "mcp_servers","type_info": "Jsonb"},{- "ordinal": 15,+ "ordinal": 16,"name": "acp_session_id","type_info": "Text"},{- "ordinal": 16,+ "ordinal": 17,"name": "status","type_info": "Text"},{- "ordinal": 17,+ "ordinal": 18,"name": "status_event_name","type_info": "Text"},{- "ordinal": 18,+ "ordinal": 19,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 19,+ "ordinal": 20,"name": "modified_at","type_info": "Timestamptz"},{- "ordinal": 20,+ "ordinal": 21,"name": "thread_channel_id?","type_info": "Uuid"},{- "ordinal": 21,+ "ordinal": 22,"name": "external_provider?","type_info": "Text"},{- "ordinal": 22,+ "ordinal": 23,"name": "external_id?","type_info": "Text"},{- "ordinal": 23,+ "ordinal": 24,"name": "external_name?","type_info": "Text"},{- "ordinal": 24,+ "ordinal": 25,"name": "external_url?","type_info": "Text"},{- "ordinal": 25,+ "ordinal": 26,"name": "external_last_run_id?","type_info": "Text"}@@ -151,6 +156,7 @@false,true,true,+ true,false,false,true,@@ -169,5 +175,5 @@true]},- "hash": "a6aa77d4a9a024f7446bd25c1b167d0959d829b815df02b5f7092d1c59e3987f"+ "hash": "dacaf399371a115436903c7a02db483923b64b662f6d6671f8775ee737aca657"}diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsxindex e137aa144e..c3d8aa0766 100644--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx@@ -1,5 +1,6 @@import { AgentComposer } from '@app/features/block-agent/component/AgentComposer';import { AgentPullRequestChip } from '@app/features/block-agent/component/AgentPullRequestChip';+import { agentSessionTitle } from '@app/features/block-agent/component/AgentSplitHeader';import { Transcript } from '@app/features/block-agent/component/Transcript';import {AgentSessionProvider,@@ -10,19 +11,25 @@ import {forgetPendingSession,pendingSession,} from '@app/features/block-agent/context/pending-session';-import { makeCopyLinkAction } from '@app/features/next-soup/actions';+import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';+import {+ SplitTitleFileMenu,+ StaticSplitLabel,+} from '@components/app/split-layout/components/SplitLabel';import { useSplitLayout } from '@components/app/split-layout/layout';+import { ProviderIcon } from '@core/component/AI/component/ProviderIcon';import { LoadErrorPanel } from '@core/component/EntityLoadGate';import { Permissions } from '@core/component/SharePermissions';-import { toast } from '@core/component/Toast/Toast';import {ShareDialogContext,ShareModal,} from '@core/component/TopBar/ShareButton';-import {- deleteAgentSession,- renameAgentSession,-} from '@queries/agent-session/entity-mutations';+import { useUserId } from '@core/context/user';+import { openExternalUrl } from '@core/util/url';+import type { AgentSessionEntity } from '@entity';+import ArrowSquareOut from '@phosphor/arrow-square-out.svg';+import GitBranch from '@phosphor/git-branch.svg';+import ShareIcon from '@phosphor/share.svg';import {type FavoritesFilter,useAddFavoriteMutation,@@ -36,7 +43,6 @@ import { type RosterAgent, runtimeLabel } from '../core/roster';import { ChatSessionInput } from './ChatComposer';import { SessionModelSelector } from './ModelSelector';import { modelLabel } from './model-label';-import { ConfirmDialog, RenameDialog } from './SimpleDialogs';import { Topbar } from './Topbar';const FAVORITES_FILTER: FavoritesFilter = { entityType: ['agent_session'] };@@ -63,11 +69,31 @@ function SessionContent(props: {const addFavorite = useAddFavoriteMutation();const removeFavorite = useRemoveFavoriteMutation();const [shareOpen, setShareOpen] = createSignal(false);- const [renaming, setRenaming] = createSignal(false);- const [deleting, setDeleting] = createSignal(false);- const [busy, setBusy] = createSignal(false);+ const userId = useUserId();- const title = () => metadata()?.title ?? session()?.name ?? 'New chat';+ const title = () => agentSessionTitle(session(), metadata()?.title);+ const permissions = () =>+ session()?.ownerId === userId()+ ? Permissions.OWNER+ : session()?.canEdit+ ? Permissions.CAN_EDIT+ : Permissions.CAN_VIEW;+ const entity = (): AgentSessionEntity | undefined => {+ const current = session();+ const id = sessionId();+ if (!current || !id) return;+ return {+ type: 'agent_session',+ id,+ name: title(),+ ownerId: current.ownerId,+ botId: current.botId,+ status:+ current.status.kind === 'event'+ ? current.status.event+ : current.status.kind,+ };+ };const isFavorite = () => {const id = sessionId();return (@@ -95,45 +121,10 @@ function SessionContent(props: {if (isFavorite()) removeFavorite.mutate(args);else addFavorite.mutate(args);};- const copyLink = () => {- const id = sessionId();- if (id)- void makeCopyLinkAction().executeByBlock(- id,- props.mode === 'code' ? 'coders' : 'agents'- );- };const openInSplit = () => {const id = sessionId();if (id) openWithSplit({ type: 'agent', id }, { referredFrom: 'launcher' });};- const rename = async (name: string) => {- const id = sessionId();- if (!id) return;- setBusy(true);- try {- await renameAgentSession(id, name);- setRenaming(false);- } catch {- toast.failure('Could not rename the session');- } finally {- setBusy(false);- }- };- const remove = async () => {- const id = sessionId();- if (!id) return;- setBusy(true);- try {- await deleteAgentSession(id);- setDeleting(false);- props.onDeleted();- } catch {- toast.failure('Could not delete the session');- } finally {- setBusy(false);- }- };return (<ShareDialogContext.Provider@@ -145,14 +136,74 @@ function SessionContent(props: {><Topbartitle={title()}+ titleContent={+ <>+ <StaticSplitLabel+ label={title()}+ icon={+ <ProviderIcon+ model={metadata()?.model ?? session()?.model}+ class="size-4 shrink-0"+ />+ }+ />+ <Show when={entity()}>+ {(current) => (+ <SplitTitleFileMenu>+ <SplitFileMenu+ id={current().id}+ itemType="agent_session"+ entityKind="agent"+ name={title()}+ entity={current()}+ permissions={permissions()}+ onDelete={props.onDeleted}+ ops={[+ { op: 'rename' },+ { op: 'delete' },+ {+ label: 'Open repository',+ icon: GitBranch,+ action: () => {+ const url = session()?.repoUrl;+ if (url) openExternalUrl(url);+ },+ },+ ]}+ tools={[+ {+ label: () => {+ const provider = session()?.external?.provider;+ if (provider === 'claude-cloud')+ return 'Open in Claude';+ return provider+ ? `Open in ${provider.charAt(0).toUpperCase()}${provider.slice(1)}`+ : 'Open externally';+ },+ icon: ArrowSquareOut,+ condition: () => Boolean(session()?.external?.url),+ action: () => {+ const url = session()?.external?.url;+ if (url) openExternalUrl(url);+ },+ },+ {+ label: 'Share',+ icon: ShareIcon,+ action: () => setShareOpen(true),+ },+ ]}+ />+ </SplitTitleFileMenu>+ )}+ </Show>+ </>+ }session={{favorite: isFavorite(),onToggleFavorite: toggleFavorite,onShare: () => setShareOpen(true),onSidePanel: openInSplit,- onRename: () => setRenaming(true),- onCopyLink: copyLink,- onDelete: () => setDeleting(true),}}><Show when={session()?.pullRequestUrl}>@@ -234,33 +285,13 @@ function SessionContent(props: {owner={session()?.ownerId ?? ''}itemType="agent_session"blockAlias="agent"- userPermissions={Permissions.OWNER}+ userPermissions={permissions()}isSharePermOpen={shareOpen()}setIsSharePermOpen={setShareOpen}/></Suspense>)}</Show>- <Show when={renaming()}>- <RenameDialog- value={title()}- pending={busy()}- onRename={(name) => void rename(name)}- onClose={() => setRenaming(false)}- />- </Show>- <Show when={deleting()}>- <ConfirmDialog- title="Delete session?"- body="This removes the session and its transcript for everyone it was shared with. This cannot be undone."- confirmLabel="Delete session"- pendingLabel="Deleting…"- danger- pending={busy()}- onConfirm={() => void remove()}- onClose={() => setDeleting(false)}- />- </Show></ShareDialogContext.Provider>);}diff --git a/apps/web/src/features/agents-view/components/ChatComposer.tsx b/apps/web/src/features/agents-view/components/ChatComposer.tsxindex fffb1ad587..b994c35907 100644--- a/apps/web/src/features/agents-view/components/ChatComposer.tsx+++ b/apps/web/src/features/agents-view/components/ChatComposer.tsx@@ -5,11 +5,20 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import { useTouchOutsideToDismissKeyboard } from '@core/mobile/useTouchOutsideToDismissKeyboard';import { $insertReferencedPaste } from '@macro-inc/lexical-core';import { Button, ComposerSurface, SendButton } from '@ui';-import { createSignal, type JSX, onCleanup, onMount, Show } from 'solid-js';+import {+ createEffect,+ createSignal,+ type JSX,+ onCleanup,+ onMount,+ Show,+} from 'solid-js';import { createChatComposerTip } from '../primitives/chat-composer-tip';/** Shared input that starts on one line and grows with the draft. */export function ChatComposer(props: {+ autoFocus?: boolean;+ registerFocus?: (focus: () => void) => void;draft: string;onDraftChange: (draft: string) => void;blockedReason?: string;@@ -64,7 +73,14 @@ export function ChatComposer(props: {editor.withSkills();}+ // Apply host-supplied drafts (Home suggestions) to the existing editor.+ createEffect(() => {+ if (props.draft !== editor.controls.getMarkdown())+ editor.controls.setMarkdown(props.draft);+ });+onMount(() => {+ props.registerFocus?.(() => editor.controls.focus());props.session?.registerFocus?.(() => editor.controls.focus());props.session?.registerQuoteInsert?.((text) => {editor.lexical.update(() => $insertReferencedPaste(text), {@@ -116,7 +132,10 @@ export function ChatComposer(props: {refFn={(element) =>element.setAttribute('aria-label', 'Message the agent')}- autofocus={!isTouchDevice() && (props.session?.autofocus ?? true)}+ autofocus={+ !isTouchDevice() &&+ (props.autoFocus ?? props.session?.autofocus ?? true)+ }/></div><divdiff --git a/apps/web/src/features/agents-view/components/Topbar.test.tsx b/apps/web/src/features/agents-view/components/Topbar.test.tsxnew file mode 100644index 0000000000..4892d95b8e--- /dev/null+++ b/apps/web/src/features/agents-view/components/Topbar.test.tsx@@ -0,0 +1,41 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import type { ParentProps } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import { Topbar } from './Topbar';++vi.mock('@app/components/view-shell/ViewShell', () => ({+ ViewShell: {+ TopBar: (props: ParentProps) => <div>{props.children}</div>,+ },+}));+afterEach(cleanup);++it('uses the block title control without duplicating its title or session menu', () => {+ const share = vi.fn();+ render(() => (+ <Topbar+ title="Session"+ titleContent={<button>Session title menu</button>}+ session={{+ favorite: false,+ onToggleFavorite: vi.fn(),+ onShare: share,+ onSidePanel: vi.fn(),+ }}+ />+ ));+ expect(+ screen.getByRole('button', { name: 'Session title menu' })+ ).toBeTruthy();+ expect(screen.queryByRole('heading')).toBeNull();+ expect(screen.queryByRole('button', { name: 'Session menu' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));+ expect(share).toHaveBeenCalledOnce();+});++it('keeps the plain heading for the new conversation page', () => {+ render(() => <Topbar title="New conversation" />);+ expect(+ screen.getByRole('heading', { name: 'New conversation' })+ ).toBeTruthy();+});diff --git a/apps/web/src/features/agents-view/components/Topbar.tsx b/apps/web/src/features/agents-view/components/Topbar.tsxindex 20dc897093..232418b046 100644--- a/apps/web/src/features/agents-view/components/Topbar.tsx+++ b/apps/web/src/features/agents-view/components/Topbar.tsx@@ -1,14 +1,9 @@import { ViewShell } from '@app/components/view-shell/ViewShell';-import CopyIcon from '@phosphor/copy.svg';-import DotsIcon from '@phosphor/dots-three.svg';-import PencilIcon from '@phosphor/pencil-simple.svg';import ShareIcon from '@phosphor/share.svg';import SidebarIcon from '@phosphor/sidebar.svg';import SparkleIcon from '@phosphor/sparkle.svg';-import TrashIcon from '@phosphor/trash.svg';import SparkleFillIcon from '@phosphor-fill/sparkle-fill.svg';import { type JSX, Show } from 'solid-js';-import { MenuAnchor } from './Menu';/** What the toolbar can do to the open session. */export type SessionActions = {@@ -16,9 +11,6 @@ export type SessionActions = {onToggleFavorite: () => void;onShare: () => void;onSidePanel: () => void;- onRename: () => void;- onCopyLink: () => void;- onDelete: () => void;};/**@@ -27,14 +19,19 @@ export type SessionActions = {*/export function Topbar(props: {title: string;+ titleContent?: JSX.Element;session?: SessionActions;children?: JSX.Element;}) {return (<ViewShell.TopBar class="touch:flex">- <h1 class="min-w-0 flex-1 truncate text-sm font-semibold text-ink">- {props.title}- </h1>+ <div class="flex min-w-0 flex-1 items-center">+ {props.titleContent ?? (+ <h1 class="min-w-0 truncate text-sm font-semibold text-ink">+ {props.title}+ </h1>+ )}+ </div><div class="flex shrink-0 items-center gap-2">{props.children}<div class="bbar" role="toolbar" aria-label="Session actions">@@ -76,88 +73,6 @@ export function Topbar(props: {><SidebarIcon class="ph" /></button>- <span class="sep session-only" />- <MenuAnchor- class="session-only"- menuLabel="Session actions"- menuClass="below"- role="menu"- style={{ width: '220px' }}- trigger={(menu) => (- <button- type="button"- class="icon-btn"- aria-label="More"- aria-haspopup="menu"- aria-expanded={menu.open()}- onClick={(event) => {- event.stopPropagation();- menu.toggle();- }}- >- <DotsIcon class="ph" />- </button>- )}- >- {(close) => (- <>- <button- type="button"- class="opt"- role="menuitem"- onClick={() => {- close();- props.session?.onRename();- }}- >- <PencilIcon class="ph" />- <span class="nm">Rename</span>- </button>- <button- type="button"- class="opt"- role="menuitem"- onClick={() => {- close();- props.session?.onCopyLink();- }}- >- <CopyIcon class="ph" />- <span class="nm">Copy link</span>- </button>- <button- type="button"- class="opt"- role="menuitem"- onClick={() => {- close();- props.session?.onToggleFavorite();- }}- >- <SparkleIcon class="ph" />- <span class="nm">- {props.session?.favorite- ? 'Remove from favorites'- : 'Add to favorites'}- </span>- </button>- <div class="grp" style={{ padding: '4px 0 0' }} />- <button- type="button"- class="opt"- role="menuitem"- style={{ color: 'var(--red)' }}- onClick={() => {- close();- props.session?.onDelete();- }}- >- <TrashIcon class="ph" />- <span class="nm">Delete session</span>- </button>- </>- )}- </MenuAnchor></div></div></ViewShell.TopBar>diff --git a/apps/web/src/features/agents-view/core/repository.ts b/apps/web/src/features/agents-view/core/repository.tsindex 09c809da2b..0cbd851ace 100644--- a/apps/web/src/features/agents-view/core/repository.ts+++ b/apps/web/src/features/agents-view/core/repository.ts@@ -49,3 +49,25 @@ export function repositoryLabel(url: string): string {export function repositoryShortName(url: string): string {return repositoryLabel(url).split('/').at(-1) ?? url;}++/** Git branch names, excluding revision expressions and ref shorthand. */+export function validRepositoryBranch(branch: string): boolean {+ return (+ !!branch &&+ branch !== '@' &&+ !branch.startsWith('-') &&+ !branch.endsWith('.') &&+ !branch.includes('..') &&+ !branch.includes('@{') &&+ !/[\s~^:?*\[\\]/.test(branch) &&+ !Array.from(branch).some(+ (character) =>+ character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127+ ) &&+ branch+ .split('/')+ .every(+ (part) => !!part && !part.startsWith('.') && !part.endsWith('.lock')+ )+ );+}diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsxindex 33c596e9dc..9ca4046e71 100644--- a/apps/web/src/features/agents-view/views/AgentsView.tsx+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx@@ -195,6 +195,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {prompt: start.prompt,modelOverride: start.modelOverride,repoUrl: start.repoUrl,+ repoBranch: start.repoBranch,});openConversation({ id, type: 'agent_session' },diff --git a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx b/apps/web/src/features/agents-view/views/NewChatPage.test.tsxindex 6247faad82..5b7f45fdd5 100644--- a/apps/web/src/features/agents-view/views/NewChatPage.test.tsx+++ b/apps/web/src/features/agents-view/views/NewChatPage.test.tsx@@ -184,13 +184,16 @@ describe('agent-led new conversation', () => {screen.getByRole('heading', { name: 'What should we build?' })).toBeTruthy();expect(screen.getByTestId('drawer').hasAttribute('hidden')).toBe(false);- fireEvent.click(screen.getByRole('button', { name: /Add repository/ }));+ fireEvent.click(screen.getByRole('button', { name: 'Repository' }));fireEvent.input(screen.getByRole('textbox', { name: 'Add repository' }), {target: { value: 'macro-inc/macro' },});- fireEvent.keyDown(screen.getByRole('textbox', { name: 'Add repository' }), {- key: 'Enter',+ fireEvent.click(screen.getByRole('button', { name: 'Use repository' }));+ fireEvent.click(screen.getByRole('button', { name: 'Branch' }));+ fireEvent.input(screen.getByRole('textbox', { name: 'Starting branch' }), {+ target: { value: 'feature/home' },});+ fireEvent.click(screen.getByRole('button', { name: 'Use branch' }));await selectAgent(/^Chat default$/);expect(screen.getByTestId('drawer').hasAttribute('hidden')).toBe(true);expect(@@ -204,14 +207,13 @@ describe('agent-led new conversation', () => {modelOverride: 'chat-default',});await selectAgent(/Cursor/);- expect(- screen.getByRole('button', { name: /macro-inc\/macro/ })- ).toBeTruthy();+ expect(screen.getByRole('button', { name: 'Repository' })).toBeTruthy();fireEvent.click(screen.getByRole('button', { name: 'Send' }));expect(send).toHaveBeenLastCalledWith({botId: CURSOR_BOT_ID,prompt: 'Shared draft',repoUrl: 'https://github.com/macro-inc/macro',+ repoBranch: 'feature/home',});});it('uses a saved agent without sending a per-session model override', async () => {diff --git a/apps/web/src/features/agents-view/views/NewChatPage.tsx b/apps/web/src/features/agents-view/views/NewChatPage.tsxindex 90056fbcd9..0fc2b6eb01 100644--- a/apps/web/src/features/agents-view/views/NewChatPage.tsx+++ b/apps/web/src/features/agents-view/views/NewChatPage.tsx@@ -1,15 +1,9 @@import { createRecentAgentSelections } from '@app/features/block-agent/context/recent-agent-selections';import { useSettingsState } from '@core/constant/SettingsState';import { useUserId } from '@core/context/user';-import CaretDownIcon from '@phosphor/caret-down.svg';-import GithubIcon from '@phosphor/github-logo.svg';-import PlusIcon from '@phosphor/plus.svg';-import XIcon from '@phosphor/x.svg';-import { createMemo, createSignal, For, Show } from 'solid-js';+import { createMemo, createSignal } from 'solid-js';import { ChatComposer } from '../components/ChatComposer';-import { MenuAnchor, MenuGroup, MenuOption } from '../components/Menu';import type { AgentKind } from '../core/agent-kind';-import { parseRepositoryInput, repositoryLabel } from '../core/repository';import {MACRO_PERSONA_ID,type RosterAgent,@@ -17,6 +11,7 @@ import {} from '../core/roster';import { createRecentRepositories } from '../primitives/recent-repositories';import { AgentPicker } from './AgentPicker';+import { RepositoryPicker } from './RepositoryPicker';/** What the composer hands the workspace to start a session with. */export type StartConversation = {@@ -24,11 +19,16 @@ export type StartConversation = {/** Persisted or first-party bot to run; omitted for Macro's default. */botId?: string;repoUrl?: string;+ repoBranch?: string;modelOverride?: string;};/** One agent choice determines the session kind, default model, and repository context. */export function NewChatPage(props: {+ draft?: string;+ onDraftChange?: (draft: string) => void;+ autoFocus?: boolean;+ registerFocus?: (focus: () => void) => void;roster: RosterAgent[];rosterLoading: boolean;onStart: (start: StartConversation) => void;@@ -45,8 +45,11 @@ export function NewChatPage(props: {const [repoUrl, setRepoUrl] = createSignal<string | undefined>(repositories.urls()[0]);- const [draft, setDraft] = createSignal('');- const [repoInput, setRepoInput] = createSignal('');+ const [localDraft, setLocalDraft] = createSignal('');+ const draft = () => props.draft ?? localDraft();+ const setDraft = (text: string) =>+ props.onDraftChange ? props.onDraftChange(text) : setLocalDraft(text);+ const [repoBranch, setRepoBranch] = createSignal('main');const selected = createMemo(() => {const wanted =agentId() ??@@ -78,19 +81,12 @@ export function NewChatPage(props: {prompt,botId: persona.botId,repoUrl: repo,+ ...(repo ? { repoBranch: repoBranch() } : {}),...(modelOverride() ? { modelOverride: modelOverride() } : {}),});setModelOverride(undefined);};- const addRepository = () => {- const url = parseRepositoryInput(repoInput());- if (!url) return;- repositories.remember(url);- setRepoUrl(url);- setRepoInput('');- };-const agentSelector = () => (<AgentPickeragents={options()}@@ -106,91 +102,6 @@ export function NewChatPage(props: {/>);- const repositorySelector = () => (- <MenuAnchor- menuLabel="Repository"- trigger={(menu) => (- <button- type="button"- class={repoUrl() ? 'pill' : 'pill empty'}- aria-haspopup="listbox"- aria-expanded={menu.open()}- title="Repository (optional)"- onClick={(event) => {- event.stopPropagation();- menu.toggle();- }}- >- <span class="logo">- <GithubIcon class="ph" style={{ width: '16px', height: '16px' }} />- </span>- <span class="lbl truncate">- <Show when={repoUrl()} fallback="Add repository">- {(url) => (- <span class="mono" style={{ 'font-size': '12px' }}>- {repositoryLabel(url())}- </span>- )}- </Show>- </span>- <CaretDownIcon class="ph caret" />- </button>- )}- >- {(close) => (- <>- <div class="filter">- <PlusIcon class="ph" />- <input- placeholder="Add owner/repo or a URL"- aria-label="Add repository"- value={repoInput()}- onInput={(event) => setRepoInput(event.currentTarget.value)}- onKeyDown={(event) => {- if (event.key !== 'Enter') return;- event.preventDefault();- addRepository();- close();- }}- />- </div>- <MenuOption- checked={!repoUrl()}- onSelect={() => {- setRepoUrl(undefined);- close();- }}- >- <XIcon class="ph" />- <span class="nm">No repository</span>- <span class="sub">workspace only</span>- </MenuOption>- <Show when={repositories.urls().length > 0}>- <MenuGroup>Recent</MenuGroup>- <For each={repositories.urls()}>- {(url) => (- <MenuOption- checked={repoUrl() === url}- onSelect={() => {- setRepoUrl(url);- close();- }}- >- <GithubIcon class="ph" />- <span class="nm">{repositoryLabel(url)}</span>- </MenuOption>- )}- </For>- </Show>- <div class="foot">- <span>Optional · repository for this session</span>- <span>{repositories.urls().length} repos</span>- </div>- </>- )}- </MenuAnchor>- );-return (<section class="page newchat" data-active aria-label="New conversation"><div class="col">@@ -200,11 +111,24 @@ export function NewChatPage(props: {</h2></div><ChatComposer+ autoFocus={props.autoFocus}+ registerFocus={props.registerFocus}draft={draft()}onDraftChange={setDraft}blockedReason={blocked()}selector={agentSelector()}- drawer={repositorySelector()}+ drawer={+ <RepositoryPicker+ repoUrl={repoUrl()}+ branch={repoBranch()}+ recentRepositories={repositories.urls()}+ onSelect={(url, branch) => {+ setRepoUrl(url);+ setRepoBranch(branch);+ if (url) repositories.remember(url);+ }}+ />+ }drawerOpen={coding()}placeholder={coding() ? 'Describe what you want to build' : undefined}onSend={send}diff --git a/apps/web/src/features/agents-view/views/RepositoryPicker.tsx b/apps/web/src/features/agents-view/views/RepositoryPicker.tsxnew file mode 100644index 0000000000..a6eeb8bdd9--- /dev/null+++ b/apps/web/src/features/agents-view/views/RepositoryPicker.tsx@@ -0,0 +1,180 @@+import { Popover } from '@kobalte/core/popover';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import GitBranchIcon from '@phosphor/git-branch.svg';+import GithubIcon from '@phosphor/github-logo.svg';+import { Button } from '@ui';+import { createSignal, For, Show } from 'solid-js';+import {+ parseRepositoryInput,+ repositoryLabel,+ validRepositoryBranch,+} from '../core/repository';++/** Explicit, portaled repository/branch controls shared by Home and Agents. */+export function RepositoryPicker(props: {+ repoUrl?: string;+ branch: string;+ recentRepositories: string[];+ onSelect: (url: string | undefined, branch: string) => void;+}) {+ const [repoOpen, setRepoOpen] = createSignal(false);+ const [branchOpen, setBranchOpen] = createSignal(false);+ const [repoInput, setRepoInput] = createSignal('');+ const [branchInput, setBranchInput] = createSignal('');+ const [error, setError] = createSignal('');+ const selectRepo = (url: string | undefined) => {+ props.onSelect(url, url === props.repoUrl ? props.branch : 'main');+ setRepoOpen(false);+ };+ const applyRepo = () => {+ const url = parseRepositoryInput(repoInput());+ if (!url || !url.startsWith('https://github.com/')) {+ setError('Enter a GitHub repository as owner/repo or a repository URL.');+ return;+ }+ selectRepo(url);+ };+ const applyBranch = () => {+ const branch = branchInput().trim();+ if (!validRepositoryBranch(branch)) {+ setError(+ 'Enter a valid branch name, for example main or feature/my-change.'+ );+ return;+ }+ props.onSelect(props.repoUrl, branch);+ setBranchOpen(false);+ };+ return (+ <div class="flex min-w-0 flex-wrap items-center gap-2">+ <Popover+ open={repoOpen()}+ onOpenChange={(open) => {+ setRepoOpen(open);+ setError('');+ if (open) setRepoInput(props.repoUrl ?? '');+ }}+ placement="top-start"+ gutter={8}+ >+ <Popover.Trigger class="pill max-w-full" aria-label="Repository">+ <GithubIcon class="size-4 shrink-0" />+ <span class="truncate">+ {props.repoUrl ? repositoryLabel(props.repoUrl) : 'Add repository'}+ </span>+ <CaretDownIcon class="size-3 shrink-0" />+ </Popover.Trigger>+ <Popover.Portal>+ <Popover.Content class="z-action-menu w-80 max-w-[calc(100vw-1rem)] rounded-xl border border-edge-muted bg-menu p-3 text-sm text-ink shadow-menu">+ <Popover.Title class="mb-2 font-medium">Repository</Popover.Title>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ applyRepo();+ }}+ class="flex flex-col gap-2"+ >+ <input+ aria-label="Add repository"+ placeholder="owner/repo or GitHub URL"+ value={repoInput()}+ onInput={(event) => {+ setRepoInput(event.currentTarget.value);+ setError('');+ }}+ class="w-full rounded-lg border border-edge-muted bg-input px-3 py-2 outline-none focus:border-accent"+ />+ <Show when={error()}>+ <p role="alert" class="text-xs text-failure">+ {error()}+ </p>+ </Show>+ <Button type="submit" variant="strong">+ Use repository+ </Button>+ </form>+ <div class="mt-2 max-h-48 overflow-y-auto">+ <button+ type="button"+ class="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover"+ onClick={() => selectRepo(undefined)}+ >+ Choose automatically+ <Show when={!props.repoUrl}>+ <CheckIcon class="ml-auto size-4" />+ </Show>+ </button>+ <For each={props.recentRepositories}>+ {(url) => (+ <button+ type="button"+ class="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left hover:bg-hover"+ onClick={() => selectRepo(url)}+ >+ <GithubIcon class="size-4 shrink-0" />+ <span class="truncate">{repositoryLabel(url)}</span>+ <Show when={url === props.repoUrl}>+ <CheckIcon class="ml-auto size-4 shrink-0" />+ </Show>+ </button>+ )}+ </For>+ </div>+ </Popover.Content>+ </Popover.Portal>+ </Popover>+ <Show when={props.repoUrl}>+ <Popover+ open={branchOpen()}+ onOpenChange={(open) => {+ setBranchOpen(open);+ setError('');+ if (open) setBranchInput(props.branch);+ }}+ placement="top-start"+ gutter={8}+ >+ <Popover.Trigger class="pill max-w-full" aria-label="Branch">+ <GitBranchIcon class="size-4 shrink-0" />+ <span class="truncate">{props.branch}</span>+ <CaretDownIcon class="size-3 shrink-0" />+ </Popover.Trigger>+ <Popover.Portal>+ <Popover.Content class="z-action-menu w-80 max-w-[calc(100vw-1rem)] rounded-xl border border-edge-muted bg-menu p-3 text-sm text-ink shadow-menu">+ <Popover.Title class="mb-2 font-medium">+ Starting branch+ </Popover.Title>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ applyBranch();+ }}+ class="flex flex-col gap-2"+ >+ <input+ aria-label="Starting branch"+ placeholder="main or feature/my-change"+ value={branchInput()}+ onInput={(event) => {+ setBranchInput(event.currentTarget.value);+ setError('');+ }}+ class="w-full rounded-lg border border-edge-muted bg-input px-3 py-2 outline-none focus:border-accent"+ />+ <Show when={error()}>+ <p role="alert" class="text-xs text-failure">+ {error()}+ </p>+ </Show>+ <Button type="submit" variant="strong">+ Use branch+ </Button>+ </form>+ </Popover.Content>+ </Popover.Portal>+ </Popover>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex 5863dc7fce..06746f5f46 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -31,6 +31,16 @@ import { harnessTitle } from './compose-agent-session-options';export { harnessTitle };+/** Shared title precedence for standalone and workspace agent sessions. */+export function agentSessionTitle(+ session: AgentSessionResponse | undefined,+ transcriptTitle?: string | null+): string {+ const name = session?.name;+ if (name && name !== 'Agent Session') return name;+ return transcriptTitle ?? name ?? harnessTitle(session?.harness);+}+/*** Agent-session identity in the split header chrome plus the standard split* toolbar: static label, shared entity actions, the session's pull request@@ -49,12 +59,7 @@ export function AgentSplitHeader(props: {// against a placeholder and keeps reporting it (see `Block.tsx`), so the// block id is the one thing here that is not a shareable session id.const { sessionId, metadata } = useAgentSession();- const title = () => {- const persistedName = props.session?.name;- if (persistedName && persistedName !== 'Agent Session')- return persistedName;- return props.title ?? persistedName ?? harnessTitle(props.session?.harness);- };+ const title = () => agentSessionTitle(props.session, props.title);const entity = (): AgentSessionEntity | undefined => {const session = props.session;diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.tsindex 1473c4cc8b..9bc2577f3a 100644--- a/apps/web/src/features/block-agent/context/pending-session.ts+++ b/apps/web/src/features/block-agent/context/pending-session.ts@@ -52,10 +52,11 @@ export type StartPendingSessionOptions = {/** Optional model switch applied before the first prompt. */modelOverride?: string;/**- * Repository the session should work in. Informational for the runtime:- * having it cloned there is the runtime operator's job.+ * Explicit GitHub repository for the managed Cursor session.*/repoUrl?: string;+ /** Starting branch for the selected repository. */+ repoBranch?: string;};/**@@ -73,7 +74,9 @@ export function startPendingSession(void agentHarnessServiceClient.create({...(options.botId ? { botId: options.botId } : {}),- ...(options.repoUrl ? { repoUrl: options.repoUrl } : {}),+ ...(options.repoUrl+ ? { repoUrl: options.repoUrl, repoBranch: options.repoBranch }+ : {}),} satisfies CreateAgentSessionRequest).then(async (result) => {if (result.isErr()) {diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts b/apps/web/src/features/block-agent/context/resolve-session-id.test.tsindex a21e196109..3642424569 100644--- a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts@@ -29,6 +29,9 @@ vi.mock('@service-agent-harness/client', () => ({}));const { startPendingSession } = await import('./pending-session');+const { agentHarnessServiceClient } = await import(+ '@service-agent-harness/client'+);const { resolveSessionId } = await import('./resolve-session-id');/** Let the mocked create's `.then` run. */@@ -86,6 +89,13 @@ describe('a placeholder', () => {botId: 'persona-1',modelOverride: 'model-2',prompt: 'Fix the tests',+ repoUrl: 'https://github.com/macro-inc/macro',+ repoBranch: 'feature/home',+ });+ expect(agentHarnessServiceClient.create).toHaveBeenLastCalledWith({+ botId: 'persona-1',+ repoUrl: 'https://github.com/macro-inc/macro',+ repoBranch: 'feature/home',});await createRoot(async (dispose) => {const resolved = resolveSessionId(() => placeholder);diff --git a/apps/web/src/features/home/components/home-start-layout.tsx b/apps/web/src/features/home/components/home-start-layout.tsxindex 88fc7fcf98..3a8e66fe74 100644--- a/apps/web/src/features/home/components/home-start-layout.tsx+++ b/apps/web/src/features/home/components/home-start-layout.tsx@@ -1,19 +1,24 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableChatV3Agents } from '@core/constant/featureFlags';import MacroLogo from '@icon/macro-logo.svg';-import type { JSX } from 'solid-js';+import { type JSX, Show } from 'solid-js';export function HomeStartLayout(props: {composer: JSX.Element;suggestions: JSX.Element;}) {+ const agents = useFeatureFlag(enableChatV3Agents);return (<div class="size-full overflow-y-auto font-sans"><main class="mx-auto flex min-h-full w-full max-w-[816px] flex-col justify-center gap-0 px-6 py-16">- <header class="mb-8 flex flex-wrap items-center justify-center gap-3 text-center">- <MacroLogo class="size-9 shrink-0 text-accent" aria-hidden="true" />- <h1 class="text-[clamp(24px,2.5vw,32px)] font-medium leading-tight tracking-tight text-ink">- What should we work on?- </h1>- </header>+ <Show when={!agents().enabled}>+ <header class="mb-8 flex flex-wrap items-center justify-center gap-3 text-center">+ <MacroLogo class="size-9 shrink-0 text-accent" aria-hidden="true" />+ <h1 class="text-[clamp(24px,2.5vw,32px)] font-medium leading-tight tracking-tight text-ink">+ What should we work on?+ </h1>+ </header>+ </Show>{props.composer}{props.suggestions}</main>diff --git a/apps/web/src/features/home/home-agent-composer.test.tsx b/apps/web/src/features/home/home-agent-composer.test.tsxnew file mode 100644index 0000000000..aae5f7254c--- /dev/null+++ b/apps/web/src/features/home/home-agent-composer.test.tsx@@ -0,0 +1,118 @@+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { StartConversation } from '../agents-view/views/NewChatPage';+import { HomeAgentComposer } from './home-agent-composer';++const mocks = vi.hoisted(() => ({+ start: vi.fn(() => 'pending-session'),+ replace: vi.fn(),+ buildPrompt: vi.fn(),+ failure: vi.fn(),+ pendingDraft: () => null as string | null,+ setPendingDraft: (_: string | null) => {},+ onStart: undefined as ((start: StartConversation) => void) | undefined,+}));+vi.mock('@app/features/block-agent/context/pending-session', () => ({+ startPendingSession: mocks.start,+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({ handle: { replace: mocks.replace } }),+}));+vi.mock('@core/component/AI/context', () => ({+ useChatInputContext: () => ({+ pendingDraft: () => mocks.pendingDraft(),+ setPendingDraft: (value: string | null) => mocks.setPendingDraft(value),+ attachments: { attached: () => [], setAttached: vi.fn() },+ }),+}));+vi.mock('@core/constant/SettingsState', () => ({+ useSettingsState: () => ({ openSettings: vi.fn() }),+}));+vi.mock('@core/hotkey/hotkeys', () => ({ registerHotkey: vi.fn() }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { failure: mocks.failure },+}));+vi.mock('../agents-view/queries/agent-roster-source', () => ({+ createAgentRosterSource: () => ({ roster: () => [], loading: () => false }),+}));+vi.mock('./queries/home-agent-prompt', () => ({+ buildHomeAgentPrompt: mocks.buildPrompt,+}));+vi.mock('../agents-view/views/NewChatPage', () => ({+ NewChatPage: (props: {+ draft: string;+ onDraftChange: (value: string) => void;+ onStart: (start: StartConversation) => void;+ }) => {+ mocks.onStart = props.onStart;+ return (+ <input+ aria-label="Shared draft"+ value={props.draft}+ onInput={(e) => props.onDraftChange(e.currentTarget.value)}+ />+ );+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ const [pendingDraft, setPendingDraft] = createSignal<string | null>(null);+ mocks.pendingDraft = pendingDraft;+ mocks.setPendingDraft = setPendingDraft;+});+afterEach(cleanup);++it('forwards the shared composer selection into the common session flow', () => {+ render(() => <HomeAgentComposer />);+ const start = {+ prompt: 'Build it',+ botId: 'selected-agent',+ modelOverride: 'model',+ repoUrl: 'https://github.com/macro-inc/macro',+ repoBranch: 'feature/home',+ };+ mocks.onStart?.(start);+ expect(mocks.start).toHaveBeenCalledWith(start);+ expect(mocks.replace).toHaveBeenCalledWith({+ next: { type: 'component', id: 'agents-session~agents~pending-session' },+ });+});++it('puts suggested context into the shared draft', async () => {+ mocks.buildPrompt.mockResolvedValue('Suggested task with context');+ render(() => <HomeAgentComposer />);+ mocks.setPendingDraft('Suggested task');+ await waitFor(() =>+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(+ 'Suggested task with context'+ )+ );+ expect(mocks.pendingDraft()).toBeNull();+});++it('does not replace a newer typed draft when suggested context resolves late', async () => {+ let resolve!: (value: string) => void;+ mocks.buildPrompt.mockReturnValue(+ new Promise<string>((done) => {+ resolve = done;+ })+ );+ render(() => <HomeAgentComposer />);+ mocks.setPendingDraft('Suggested task');+ fireEvent.input(screen.getByRole('textbox'), {+ target: { value: 'My new task' },+ });+ resolve('Late suggestion');+ await Promise.resolve();+ expect((screen.getByRole('textbox') as HTMLInputElement).value).toBe(+ 'My new task'+ );+});diff --git a/apps/web/src/features/home/home-agent-composer.tsx b/apps/web/src/features/home/home-agent-composer.tsxnew file mode 100644index 0000000000..3191ec4402--- /dev/null+++ b/apps/web/src/features/home/home-agent-composer.tsx@@ -0,0 +1,98 @@+import { startPendingSession } from '@app/features/block-agent/context/pending-session';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { useChatInputContext } from '@core/component/AI/context';+import { toast } from '@core/component/Toast/Toast';+import { useSettingsState } from '@core/constant/SettingsState';+import { registerHotkey } from '@core/hotkey/hotkeys';+import { TOKENS } from '@core/hotkey/tokens';+import { createEffect, createSignal } from 'solid-js';+import '../agents-view/agents-view.css';+import { modeForKind } from '../agents-view/core/agent-kind';+import { kindForBot } from '../agents-view/core/roster';+import { agentsRouteId } from '../agents-view/core/route';+import { createAgentRosterSource } from '../agents-view/queries/agent-roster-source';+import {+ NewChatPage,+ type StartConversation,+} from '../agents-view/views/NewChatPage';+import { buildHomeAgentPrompt } from './queries/home-agent-prompt';++/** Home supplies suggestions and navigation to the same composer used by Agents. */+export function HomeAgentComposer(props: { autoFocus?: boolean }) {+ const panel = useSplitPanelOrThrow();+ const input = useChatInputContext();+ const roster = createAgentRosterSource();+ const settings = useSettingsState();+ const [draft, setDraft] = createSignal('');+ let focus: (() => void) | undefined;+ let draftVersion = 0;+ const applySuggestion = async (content: string) => {+ const version = ++draftVersion;+ try {+ const prompt = await buildHomeAgentPrompt({+ content,+ attachments: input.attachments.attached(),+ });+ if (version !== draftVersion) return;+ setDraft(prompt);+ input.attachments.setAttached([]);+ focus?.();+ } catch (error) {+ if (version !== draftVersion) return;+ setDraft(content);+ toast.failure(+ error instanceof Error+ ? error.message+ : 'Could not load the suggested context.'+ );+ }+ };+ createEffect(() => {+ const requested = input.pendingDraft();+ if (requested == null) return;+ input.setPendingDraft(null);+ void applySuggestion(requested);+ });+ registerHotkey({+ hotkey: 'enter',+ scopeId: panel.splitHotkeyScope,+ description: 'Focus Chat Input',+ hotkeyToken: TOKENS.block.focus,+ hide: true,+ keyDownHandler: () => {+ focus?.();+ return true;+ },+ });+ const start = (conversation: StartConversation) => {+ const id = startPendingSession(conversation);+ panel.handle.replace({+ next: {+ type: 'component',+ id: agentsRouteId({+ mode: modeForKind(kindForBot(conversation.botId, roster.roster())),+ conversation: { type: 'agent_session', id },+ }),+ },+ });+ };+ return (+ <div class="agents-view-portal min-w-0 [&_.newchat]:p-0">+ <NewChatPage+ roster={roster.roster()}+ rosterLoading={roster.loading()}+ draft={draft()}+ onDraftChange={(value) => {+ draftVersion++;+ setDraft(value);+ }}+ autoFocus={props.autoFocus}+ registerFocus={(callback) => {+ focus = callback;+ }}+ onStart={start}+ onOpenRoster={() => settings.openSettings('Agents')}+ />+ </div>+ );+}diff --git a/apps/web/src/features/home/home-chat-input.test.tsx b/apps/web/src/features/home/home-chat-input.test.tsxindex 68106599f4..ef6652007c 100644--- a/apps/web/src/features/home/home-chat-input.test.tsx+++ b/apps/web/src/features/home/home-chat-input.test.tsx@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { HomeChatInput } from './home-chat-input';const mocks = vi.hoisted(() => ({+ agentsEnabled: false,onSend: undefined as ((request: ChatSendInput) => Promise<void>) | undefined,draft: '',attached: [] as ChatSendInput['attachments'],@@ -20,6 +21,13 @@ const mocks = vi.hoisted(() => ({invalidateSoup: vi.fn(),}));+vi.mock('./home-agent-composer', () => ({+ HomeAgentComposer: () => <div data-testid="agent-composer" />,+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: mocks.agentsEnabled }),+}));+vi.mock('@core/constant/featureFlags', () => ({ enableChatV3Agents: {} }));vi.mock('@components/app/split-layout/layoutUtils', () => ({useSplitPanelOrThrow: () => ({ handle: { replace: mocks.replace } }),}));@@ -79,6 +87,7 @@ const request: ChatSendInput = {beforeEach(() => {vi.resetAllMocks();+ mocks.agentsEnabled = false;// ChatInput clears the editor and attachments before invoking onSend.mocks.draft = '';mocks.attached = [];@@ -178,3 +187,19 @@ describe('Home chat creation', () => {});});++describe('Home Agent V3 mounting', () => {+ it('mounts the shared agent composer instead of the legacy input when enabled', () => {+ cleanup();+ mocks.agentsEnabled = true;+ mocks.onSend = undefined;+ const view = render(() => <HomeChatInput />);+ expect(view.getByTestId('agent-composer')).toBeTruthy();+ expect(mocks.onSend).toBeUndefined();+ expect(mocks.createChat).not.toHaveBeenCalled();+ });+ it('keeps the legacy input when disabled', () => {+ expect(mocks.onSend).toBeDefined();+ expect(document.querySelector('[data-testid="agent-composer"]')).toBeNull();+ });+});diff --git a/apps/web/src/features/home/home-chat-input.tsx b/apps/web/src/features/home/home-chat-input.tsxindex a66d8b5fa2..27a418de2a 100644--- a/apps/web/src/features/home/home-chat-input.tsx+++ b/apps/web/src/features/home/home-chat-input.tsx@@ -1,3 +1,4 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';@@ -7,6 +8,7 @@ import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';import { createMentionAttachmentCallbacks } from '@core/component/AI/signal/mention-attachment-callbacks';import { setPendingSendData } from '@core/component/AI/signal/pendingSend';import { deriveChatName } from '@core/component/AI/util/deriveName';+import { enableChatV3Agents } from '@core/constant/featureFlags';import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';import { registerHotkey } from '@core/hotkey/hotkeys';import { TOKENS } from '@core/hotkey/tokens';@@ -15,10 +17,11 @@ import { createRenameDssEntityMutation } from '@entity';import { invalidateAllSoup } from '@queries/soup/normalized-cache';import { cognitionApiServiceClient } from '@service-cognition/client';import { $getRoot } from 'lexical';-import { createEffect } from 'solid-js';+import { createEffect, Show, Suspense } from 'solid-js';+import { HomeAgentComposer } from './home-agent-composer';import { replaceHomeComposerDraft } from './home-composer-selection';-export const HomeChatInput = (props: {+export type HomeChatInputProps = {variant?: 'default' | 'tall';class?: string;placeholder?: string;@@ -29,10 +32,22 @@ export const HomeChatInput = (props: {* the conversation (the Agents view and its sidebar) opens it in place.*/openChat?: (chatId: string) => void;-}) => {+};++export const HomeChatInput = (props: HomeChatInputProps) => {+ const flag = useFeatureFlag(enableChatV3Agents);+ return (+ <Show when={flag().enabled} fallback={<LegacyHomeChatInput {...props} />}>+ <Suspense fallback={<div class="min-h-24" />}>+ <HomeAgentComposer autoFocus={props.autoFocusOnMount} />+ </Suspense>+ </Show>+ );+};++export const LegacyHomeChatInput = (props: HomeChatInputProps) => {const splitPanelContext = useSplitPanelOrThrow();const input = useChatInputContext();-const { getAttachmentFromMention } = useGetChatAttachmentInfo();const attachmentMentionCallbacks = createMentionAttachmentCallbacks(input.attachments,@@ -79,14 +94,18 @@ export const HomeChatInput = (props: {const renameMutation = createRenameDssEntityMutation();+ const restoreDraft = (request: ChatSendInput) => {+ input.attachments.setAttached(request.attachments);+ replaceHomeComposerDraft(editor.controls, request.content);+ };+const handleSend = async (request: ChatSendInput) => {const backgroundSend = request.metaKey;// Create a new persistent chatconst response = await cognitionApiServiceClient.createChat({});if (response.isErr()) {- input.attachments.setAttached(request.attachments);- replaceHomeComposerDraft(editor.controls, request.content);+ restoreDraft(request);if (isPaymentError(response)) {const { showPaywall } = usePaywallState();showPaywall(PaywallKey.CHAT_LIMIT);diff --git a/apps/web/src/features/home/home.tsx b/apps/web/src/features/home/home.tsxindex e3cf6a3953..6e67c9795f 100644--- a/apps/web/src/features/home/home.tsx+++ b/apps/web/src/features/home/home.tsx@@ -1,35 +1,15 @@import { ShowFeatureFlag } from '@app/lib/analytics/posthog';import { FloatRegionOrInline } from '@components/app/mobile/float-regions/FloatRegion';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';-import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';-import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';-import { ChatInput } from '@core/component/AI/component/input/ChatInput';-import {- ChatInputProvider,- useChatInputContext,-} from '@core/component/AI/context';-import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';-import { createMentionAttachmentCallbacks } from '@core/component/AI/signal/mention-attachment-callbacks';-import { setPendingSendData } from '@core/component/AI/signal/pendingSend';-import { deriveChatName } from '@core/component/AI/util/deriveName';+import { ChatInputProvider } from '@core/component/AI/context';import {enableHomeRecommendations,enableHomeView,} from '@core/constant/featureFlags';-import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';import { useUserContext } from '@core/context/user';-import { registerHotkey } from '@core/hotkey/hotkeys';-import { TOKENS } from '@core/hotkey/tokens';-import { isPaymentError } from '@core/util/handlePaymentError';-import { createRenameDssEntityMutation } from '@entity';-import { invalidateAllSoup } from '@queries/soup/normalized-cache';-import { cognitionApiServiceClient } from '@service-cognition/client';import { Navigate } from '@solidjs/router';-import { $getRoot } from 'lexical';-import { createEffect } from 'solid-js';import { HomeBackfillProgress } from './home-backfill-progress';-import { replaceHomeComposerDraft } from './home-composer-selection';+import { HomeChatInput } from './home-chat-input';import { HomeExamples } from './home-examples';import { GettingStartedSection, RecommendedSection } from './home-hub';import { createHomePreferences } from './home-prefs';@@ -158,117 +138,3 @@ function HomeContent() {</main>);}--export const HomeChatInput = () => {- const splitPanelContext = useSplitPanelOrThrow();- const input = useChatInputContext();-- const { getAttachmentFromMention } = useGetChatAttachmentInfo();- const attachmentMentionCallbacks = createMentionAttachmentCallbacks(- input.attachments,- getAttachmentFromMention- );- const editor = buildChatEditor().withMentions({- ...attachmentMentionCallbacks,- block: 'chat',- showOpenTabs: true,- });-- const applyDraft = (text: string) => {- replaceHomeComposerDraft(editor.controls, text);- requestAnimationFrame(() => {- editor.controls.focus();- // Focus lands at the start of the document; drafts are prompt prefixes,- // so the caret belongs at the end, ready to complete the sentence.- editor.controls.getLexical().update(() => {- $getRoot().selectEnd();- });- });- };-- // Drafts requested from elsewhere on the home (e.g. a suggested action row).- createEffect(() => {- const draft = input.pendingDraft();- if (draft != null) {- applyDraft(draft);- input.setPendingDraft(null);- }- });-- registerHotkey({- hotkey: 'enter',- scopeId: splitPanelContext.splitHotkeyScope,- description: 'Focus Chat Input',- keyDownHandler: () => {- editor.controls.focus();- return true;- },- hotkeyToken: TOKENS.block.focus,- hide: true,- });-- const renameMutation = createRenameDssEntityMutation();-- const handleSend = async (request: ChatSendInput) => {- const backgroundSend = request.metaKey;-- // Create a new persistent chat- const response = await cognitionApiServiceClient.createChat({});- if (response.isErr()) {- if (isPaymentError(response)) {- const { showPaywall } = usePaywallState();- showPaywall(PaywallKey.CHAT_LIMIT);- }- return;- }- const { id: chatId } = response.value;-- // Rename via mutation for optimistic cache updates (history, preview, soup)- const name = deriveChatName(request.content);- if (name) {- renameMutation.mutate({- entity: { type: 'chat', id: chatId, name: '', ownerId: '' },- newName: name,- });- }-- if (backgroundSend) {- // Send the message in the background without navigating- cognitionApiServiceClient.sendStreamChatMessage({- content: request.content,- model: request.model,- chat_id: chatId,- attachments:- request.attachments.length > 0 ? request.attachments : undefined,- toolset: { type: 'all' },- });- invalidateAllSoup();- } else {- // Store the pending send data for the chat to pick up- setPendingSendData({- content: request.content,- attachments: request.attachments,- model: request.model,- });-- // Replace the soup split with the chat split- splitPanelContext.handle.replace({- next: { type: 'chat', id: chatId },- });- }- };-- return (- <ChatInput- variant="default"- editor={editor}- onSend={handleSend}- onEscape={() => {- splitPanelContext.panelRef()?.focus();- return true;- }}- isPersistent={true}- autoFocusOnMount={true}- />- );-};diff --git a/apps/web/src/features/home/queries/home-agent-prompt.test.ts b/apps/web/src/features/home/queries/home-agent-prompt.test.tsnew file mode 100644index 0000000000..9efb979e1d--- /dev/null+++ b/apps/web/src/features/home/queries/home-agent-prompt.test.ts@@ -0,0 +1,92 @@+import { buildMentionMarkdownString } from '@macro-inc/lexical-core/utils/mentions';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { buildHomeAgentPrompt } from './home-agent-prompt';++const mocks = vi.hoisted(() => ({ preview: vi.fn() }));+vi.mock('@core/constant/allBlocks', () => ({+ itemToBlockName: (item: { type: string; fileType?: string }) =>+ item.fileType ?? item.type,+}));+vi.mock('@queries/preview', () => ({+ getItemPreview: mocks.preview,+ isAccessiblePreviewItem: (item: { access?: string }) =>+ item?.access === 'access',+}));++beforeEach(() => {+ vi.resetAllMocks();+ mocks.preview.mockImplementation(async ({ id, type }) => ({+ id,+ type,+ name: 'Attached item',+ access: 'access',+ ...(type === 'document' ? { fileType: 'pdf' } : {}),+ }));+});++it('preserves prompts with existing mentions without another lookup or duplicate chip', async () => {+ const content = `Read ${buildMentionMarkdownString({ type: 'document', blockParams: {}, documentId: 'doc', documentName: 'Plan', blockName: 'md' })}`;+ expect(+ await buildHomeAgentPrompt({+ content,+ attachments: [{ entity_id: 'doc', entity_type: 'document' }],+ })+ ).toBe(content);+ expect(mocks.preview).not.toHaveBeenCalled();+});++it('adds context chips for attachment-only submissions and preserves file types', async () => {+ const prompt = await buildHomeAgentPrompt({+ content: '',+ attachments: [+ { entity_id: 'doc', entity_type: 'document' },+ { entity_id: 'project', entity_type: 'project' },+ { entity_id: 'thread', entity_type: 'email_thread' },+ ],+ });+ expect(prompt).toBe(+ [+ buildMentionMarkdownString({+ type: 'document',+ blockParams: {},+ documentId: 'doc',+ documentName: 'Attached item',+ blockName: 'pdf',+ }),+ buildMentionMarkdownString({+ type: 'document',+ blockParams: {},+ documentId: 'project',+ documentName: 'Attached item',+ blockName: 'project',+ }),+ buildMentionMarkdownString({+ type: 'document',+ blockParams: {},+ documentId: 'thread',+ documentName: 'Attached item',+ blockName: 'email',+ }),+ ].join('\n\n')+ );+});++describe('attachment failures', () => {+ it('does not silently drop image uploads', async () => {+ await expect(+ buildHomeAgentPrompt({+ content: 'Describe this',+ attachments: [{ entity_id: 'image', entity_type: 'static_file' }],+ })+ ).rejects.toThrow('Image attachments');+ });+ it('rejects unavailable context', async () => {+ mocks.preview.mockResolvedValue({ access: 'no_access' });+ await expect(+ buildHomeAgentPrompt({+ content: 'Read this',+ attachments: [{ entity_id: 'doc', entity_type: 'document' }],+ })+ ).rejects.toThrow('Could not load an attachment');+ });+});diff --git a/apps/web/src/features/home/queries/home-agent-prompt.ts b/apps/web/src/features/home/queries/home-agent-prompt.tsnew file mode 100644index 0000000000..f054fedd96--- /dev/null+++ b/apps/web/src/features/home/queries/home-agent-prompt.ts@@ -0,0 +1,40 @@+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import { getVisibleUserMessageAttachments } from '@core/component/AI/component/message/userMessageAttachments';+import { itemToBlockName } from '@core/constant/allBlocks';+import { buildMentionMarkdownString } from '@macro-inc/lexical-core/utils/mentions';+import { getItemPreview, isAccessiblePreviewItem } from '@queries/preview';+import { stringToItemType } from '@service-storage/itemType';++/** Agent prompts carry context as markdown mentions instead of a separate attachment list. */+export async function buildHomeAgentPrompt(+ request: Pick<ChatSendInput, 'content' | 'attachments'>+): Promise<string> {+ const { images, items } = getVisibleUserMessageAttachments(+ request.content,+ request.attachments+ );+ if (images.length) {+ throw new Error(+ 'Image attachments are not supported in agent sessions yet.'+ );+ }+ const mentions = await Promise.all(+ items.map(async (attachment) => {+ const type = stringToItemType(attachment.entity_type);+ if (!type)+ throw new Error('Could not attach this item to the agent session.');+ const preview = await getItemPreview({ id: attachment.entity_id, type });+ if (!isAccessiblePreviewItem(preview)) {+ throw new Error('Could not load an attachment. Please try again.');+ }+ return buildMentionMarkdownString({+ type: 'document',+ blockParams: {},+ documentId: attachment.entity_id,+ documentName: preview.name,+ blockName: itemToBlockName(preview),+ });+ })+ );+ return [request.content, ...mentions].filter(Boolean).join('\n\n');+}diff --git a/apps/web/src/features/inbox-view/components/HomeChatStart.tsx b/apps/web/src/features/inbox-view/components/HomeChatStart.tsxindex af4df3e2a4..fdc44844af 100644--- a/apps/web/src/features/inbox-view/components/HomeChatStart.tsx+++ b/apps/web/src/features/inbox-view/components/HomeChatStart.tsx@@ -1,6 +1,8 @@import { useViewShell, ViewShell } from '@app/components/view-shell';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';import { ChatInputProvider } from '@core/component/AI/context';+import { enableChatV3Agents } from '@core/constant/featureFlags';import { Show } from 'solid-js';import { HomeRecommendedActions } from '../../home/components/home-recommended-actions';import { HomeChatInput } from '../../home/home-chat-input';@@ -8,6 +10,7 @@ import { HomeChatInput } from '../../home/home-chat-input';/** Desktop Home's idle pane uses the single-line chat composer and send flow. */export function HomeChatStart() {const shell = useViewShell();+ const agents = useFeatureFlag(enableChatV3Agents);return (<ChatInputProvider><Show when={shell.aside.isCollapsed()}>@@ -17,9 +20,13 @@ export function HomeChatStart() {</Show><DragDropWrapper class="relative size-full min-h-0 min-w-0 overflow-y-auto px-6"><div class="mx-auto grid h-full min-h-64 min-w-0 w-full max-w-180 grid-cols-1 grid-rows-[1fr_auto_1fr] pb-16">- <h1 class="mb-6 min-h-0 min-w-0 self-end text-center text-2xl font-normal leading-[42px] text-ink">- What should we get done in Macro?- </h1>+ <div class="self-end">+ <Show when={!agents().enabled}>+ <h1 class="mb-6 min-h-0 min-w-0 self-end text-center text-2xl font-normal leading-[42px] text-ink">+ What should we get done in Macro?+ </h1>+ </Show>+ </div><HomeChatInputvariant="default"placeholder="Type @ to reference / for skills"diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.tsindex a712fbd463..e9a8487b0b 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts@@ -8,6 +8,7 @@ import type { CreateAgentSessionRequestBotId } from './createAgentSessionRequestimport type { CreateAgentSessionRequestInstructions } from './createAgentSessionRequestInstructions';import type { CreateAgentSessionRequestOwner } from './createAgentSessionRequestOwner';import type { CreateAgentSessionRequestPrompt } from './createAgentSessionRequestPrompt';+import type { CreateAgentSessionRequestRepoBranch } from './createAgentSessionRequestRepoBranch';import type { CreateAgentSessionRequestRepoUrl } from './createAgentSessionRequestRepoUrl';import type { CreateAgentSessionRequestThread } from './createAgentSessionRequestThread';import type { CreateAgentSessionRequestWorkspace } from './createAgentSessionRequestWorkspace';@@ -53,8 +54,11 @@ bot's say-so. */only - an external runtime sends its own first prompt through thecontrol endpoint. Omitted, the session opens idle. */prompt?: CreateAgentSessionRequestPrompt;- /** Repository nominally checked out at `workspace`. Informational and-optional: having it cloned there is the runtime operator's job. */+ /** Starting branch for a managed coding session's selected repository. */+ repoBranch?: CreateAgentSessionRequestRepoBranch;+ /** Explicit GitHub repository for a managed Cursor session. Access is+checked for the session owner. For external sessions this is+informational: cloning it is the runtime operator's job. */repoUrl?: CreateAgentSessionRequestRepoUrl;thread?: CreateAgentSessionRequestThread;/** Absolute directory the bot's harness runs in on its runtime. Presentdiff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.tsnew file mode 100644index 0000000000..ef0e9f0b6f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoBranch.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Starting branch for a managed coding session's selected repository.+ */+export type CreateAgentSessionRequestRepoBranch = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.tsindex fbbb32ae7b..0e82985115 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts@@ -6,7 +6,8 @@*//**- * Repository nominally checked out at `workspace`. Informational and-optional: having it cloned there is the runtime operator's job.+ * Explicit GitHub repository for a managed Cursor session. Access is+checked for the session owner. For external sessions this is+informational: cloning it is the runtime operator's job.*/export type CreateAgentSessionRequestRepoUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex d609474767..f6e3cd8f57 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@@ -64,6 +64,7 @@ export * from './createAgentSessionRequestBotId';export * from './createAgentSessionRequestInstructions';export * from './createAgentSessionRequestOwner';export * from './createAgentSessionRequestPrompt';+export * from './createAgentSessionRequestRepoBranch';export * from './createAgentSessionRequestRepoUrl';export * from './createAgentSessionRequestThread';export * from './createAgentSessionRequestWorkspace';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 f362574a52..87e7d3e5ed 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@@ -1573,9 +1573,13 @@"type": ["string", "null"],"description": "First prompt to deliver once the session is running. Managed sessions\nonly - an external runtime sends its own first prompt through the\ncontrol endpoint. Omitted, the session opens idle."},+ "repoBranch": {+ "type": ["string", "null"],+ "description": "Starting branch for a managed coding session's selected repository."+ },"repoUrl": {"type": ["string", "null"],- "description": "Repository nominally checked out at `workspace`. Informational and\noptional: having it cloned there is the runtime operator's job."+ "description": "Explicit GitHub repository for a managed Cursor session. Access is\nchecked for the session owner. For external sessions this is\ninformational: cloning it is the runtime operator's job."},"thread": {"oneOf": [diff --git a/crates/agent_harness/src/domain/claude/test.rs b/crates/agent_harness/src/domain/claude/test.rsindex fbe1fdf079..1fae9ad0e3 100644--- a/crates/agent_harness/src/domain/claude/test.rs+++ b/crates/agent_harness/src/domain/claude/test.rs@@ -137,6 +137,7 @@ async fn seed() -> AgentSessionId {let id = AgentSessionId::new();repo.create(CreateAgentSessionParams {+ repo_branch: None,id,bot_id: bot,owner_id: macro_user_id::user_id::MacroUserIdStr::try_from(owner.to_owned()).unwrap(),diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rsindex d144f5860c..9358f407c7 100644--- a/crates/agent_harness/src/domain/ports.rs+++ b/crates/agent_harness/src/domain/ports.rs@@ -35,12 +35,10 @@ pub enum CommandTarget {/// states what it needs - a list of repository urls for one user - without the/// installation records, App credentials and HTTP client that answering it/// takes. Reaching nothing is an empty list, not an error.+#[async_trait::async_trait]pub trait ReachableRepositories: Send + Sync + 'static {/// Every repository `user` reaches, as `https://github.com/owner/name`.- fn for_user(- &self,- user: &MacroUserIdStr<'_>,- ) -> impl Future<Output = Result<Vec<String>>> + Send;+ async fn for_user(&self, user: &MacroUserIdStr<'_>) -> Result<Vec<String>>;}/// Forwards commands to the replica currently responsible for execution.diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rsindex da73247a24..1a69ea9160 100644--- a/crates/agent_harness/src/domain/ports/test.rs+++ b/crates/agent_harness/src/domain/ports/test.rs@@ -30,6 +30,7 @@ fn owner() -> MacroUserIdStr<'static> {fn params(id: AgentSessionId) -> CreateAgentSessionParams {CreateAgentSessionParams {+ repo_branch: None,id,owner_id: owner(),bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rsindex 5b36de039a..0f52e5e31f 100644--- a/crates/agent_harness/src/domain/service.rs+++ b/crates/agent_harness/src/domain/service.rs@@ -159,6 +159,7 @@ pub struct AgentHarnessService<Notifier,>,workers: Arc<SessionWorkers>,+ repositories: Option<Arc<dyn crate::domain::ports::ReachableRepositories>>,}// Manual Clone impl so the port types don't need to be Clone (both fields@@ -194,6 +195,7 @@ impl<Self {inner: Arc::clone(&self.inner),workers: Arc::clone(&self.workers),+ repositories: self.repositories.clone(),}}}@@ -272,9 +274,19 @@ wherenotifier,}),workers: Arc::new(DashMap::new()),+ repositories: None,}}+ /// Enable explicit repository choices, authorized against the owner's reachable repositories.+ pub fn with_repositories(+ mut self,+ repositories: Arc<dyn crate::domain::ports::ReachableRepositories>,+ ) -> Self {+ self.repositories = Some(repositories);+ self+ }+/// Queue one command behind any work already running for its session.////// Queue admission happens synchronously so callers can spawn the returneddiff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rsindex 45653c6c81..df06c7b760 100644--- a/crates/agent_harness/src/domain/service/open.rs+++ b/crates/agent_harness/src/domain/service/open.rs@@ -5,6 +5,7 @@use agent_session::domain::ports::SelectedManagedPersona;use super::*;+use crate::domain::model::SessionRepository;/// External sessions create the row and announce - the magic-chip message/// the session's bot posts into the mention's thread, which is where the@@ -58,6 +59,7 @@ where.inner.sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id: AgentSessionId::new(),owner_id: request.owner.clone(),bot_id: request.bot_id,@@ -156,6 +158,45 @@ whereservers: Vec::new(),};}+ // Explicit source choices are a domain decision, before any session or egress grant exists.+ let selected_repo = if let Some(url) = request.repo_url.as_deref() {+ if kind != AgentKind::Cursor {+ return Err(+ agent_session::domain::error::AgentSessionError::InvalidRepositorySelection(+ "repository selection is supported for Cursor coding agents",+ ),+ );+ }+ let repo = SessionRepository::parse(url).ok_or(+ agent_session::domain::error::AgentSessionError::InvalidRepositorySelection(+ "select a valid GitHub repository",+ ),+ )?;+ let repositories = self+ .repositories+ .as_ref()+ .ok_or(agent_session::domain::error::AgentSessionError::Forbidden)?;+ let reachable = repositories+ .for_user(&request.owner)+ .await+ .map_err(into_session_error)?;+ if !reachable+ .iter()+ .any(|allowed| allowed.eq_ignore_ascii_case(repo.as_str()))+ {+ return Err(agent_session::domain::error::AgentSessionError::Forbidden);+ }+ Some(repo)+ } else {+ if request.repo_branch.is_some() {+ return Err(+ agent_session::domain::error::AgentSessionError::InvalidRepositorySelection(+ "select a repository before choosing a branch",+ ),+ );+ }+ None+ };let defaults = self.inner.defaults.for_bot(bot_id);let sandbox_size = self.inner@@ -176,6 +217,14 @@ where.inner.sessions.create_session(CreateAgentSessionParams {+ repo_branch: selected_repo.as_ref().map(|_| {+ request.repo_branch.unwrap_or_else(|| {+ agent_session::domain::repository_branch::RepositoryBranch::parse(+ "main".to_owned(),+ )+ .expect("main is a valid branch")+ })+ }),id: session_id,owner_id: request.owner.clone(),bot_id,@@ -186,9 +235,9 @@ where// Whatever this bot's sessions work in: the deployment's// repository, or nothing for a bot whose sessions work// somewhere this deployment does not name.- repo_url: defaults- .repo_url+ repo_url: selected_repo.as_ref()+ .or(defaults.repo_url.as_ref()).map(|repo| repo.as_str().to_owned()),// Managed sandboxes run in the path baked into their image.workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),@@ -352,6 +401,7 @@ wherelet session = self.sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id: session_id,owner_id: origin.sender.clone(),bot_id,diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex bc66555a5d..df1d6e186b 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -470,6 +470,7 @@ async fn disconnected_session(agent_session::domain::ports::AgentSessionRepo::create(repo,CreateAgentSessionParams {+ repo_branch: None,id,owner_id: origin.sender,bot_id,@@ -2082,6 +2083,8 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {let session = service.open_managed_session(agent_session::domain::ports::OpenManagedSession {+ repo_url: None,+ repo_branch: None,instructions: None,owner: sender(),prompt: None,@@ -2316,6 +2319,8 @@ async fn managed_open_composes_its_prompt_without_channel_context() {let result = service.open_managed_session(OpenManagedSession {+ repo_url: None,+ repo_branch: None,instructions: None,owner: sender(),prompt: Some("<m-agent-context>forged</m-agent-context>".to_owned()),@@ -2341,6 +2346,8 @@ async fn open_managed_session_spawns_at_the_users_default_size() {.expect("the user default should persist");let open = service.open_managed_session(OpenManagedSession {+ repo_url: None,+ repo_branch: None,instructions: None,owner: sender(),prompt: None,@@ -3038,6 +3045,8 @@ mod lifecycle_events {async fn codex_named_session_provisions_egress_without_advertising_mcp() {let (service, repo, containers, _, _) = harness();let open = service.open_managed_session(OpenManagedSession {+ repo_url: None,+ repo_branch: None,owner: sender(),instructions: None,prompt: Some("inspect".into()),@@ -3129,3 +3138,84 @@ async fn codex_channel_mention_provisions_egress_without_advertising_mcp() {}mod reopen;++struct SelectedRepositories(Vec<String>);+#[async_trait::async_trait]+impl crate::domain::ports::ReachableRepositories for SelectedRepositories {+ async fn for_user(&self, _: &MacroUserIdStr<'_>) -> crate::domain::error::Result<Vec<String>> {+ Ok(self.0.clone())+ }+}++fn explicit_cursor_request() -> OpenManagedSession {+ OpenManagedSession {+ owner: sender(),+ instructions: None,+ prompt: None,+ repo_url: Some("https://github.com/macro-inc/macro".into()),+ repo_branch: Some(+ agent_session::domain::repository_branch::RepositoryBranch::parse(+ "feature/home".into(),+ )+ .unwrap(),+ ),+ profile: Some(agent_session::domain::ports::SelectedManagedPersona {+ bot_id: bot_id::CURSOR_BOT_ID,+ profile: None,+ }),+ }+}++#[tokio::test]+async fn selected_repository_requires_owner_access_before_provisioning() {+ let (service, _, containers, _, _) = harness();+ let service = service.with_repositories(Arc::new(SelectedRepositories(vec![])));+ let result = service+ .open_managed_session(explicit_cursor_request())+ .await;+ assert!(matches!(+ result,+ Err(agent_session::domain::error::AgentSessionError::Forbidden)+ ));+ assert!(service.inner.egress.provisioned().is_empty());+ assert_eq!(containers.spawned(), 0);+}++#[tokio::test]+async fn selected_repository_and_branch_are_persisted_for_cursor() {+ let (service, repo, containers, _, _) = harness();+ let service = service.with_repositories(Arc::new(SelectedRepositories(vec![+ "https://github.com/macro-inc/macro".into(),+ ])));+ let open = service.open_managed_session(explicit_cursor_request());+ let drive = async {+ while containers.spawned() == 0 {+ tokio::task::yield_now().await;+ }+ let container = containers.container(session_of(&containers)).unwrap();+ complete_session_handshake(&container).await;+ };+ let (opened, _) = tokio::join!(open, drive);+ let session = repo.get(opened.unwrap().id).await.unwrap();+ assert_eq!(+ session.repo_url.as_deref(),+ Some("https://github.com/macro-inc/macro")+ );+ assert_eq!(+ session.repo_branch.as_ref().map(|branch| branch.as_str()),+ Some("feature/home")+ );+}++#[tokio::test]+async fn branch_without_repository_is_rejected_before_provisioning() {+ let (service, _, containers, _, _) = harness();+ let mut request = explicit_cursor_request();+ request.repo_url = None;+ assert!(matches!(+ service.open_managed_session(request).await,+ Err(agent_session::domain::error::AgentSessionError::InvalidRepositorySelection(_))+ ));+ assert!(service.inner.egress.provisioned().is_empty());+ assert_eq!(containers.spawned(), 0);+}diff --git a/crates/agent_harness/src/domain/service/test/reopen.rs b/crates/agent_harness/src/domain/service/test/reopen.rsindex 5237aff407..c0559b5654 100644--- a/crates/agent_harness/src/domain/service/test/reopen.rs+++ b/crates/agent_harness/src/domain/service/test/reopen.rs@@ -8,6 +8,7 @@ async fn codex_session(agent_session::domain::ports::AgentSessionRepo::create(repo,CreateAgentSessionParams {+ repo_branch: None,id,owner_id: sender(),bot_id: bot_id::CODEX_BOT_ID,diff --git a/crates/agent_harness/src/outbound/cursor/manager.rs b/crates/agent_harness/src/outbound/cursor/manager.rsindex e79f466d72..f9f2c34401 100644--- a/crates/agent_harness/src/outbound/cursor/manager.rs+++ b/crates/agent_harness/src/outbound/cursor/manager.rs@@ -291,7 +291,12 @@ where// model now (the user's default, seeded below via// `with_default_model`, or a per-session pick), applied per run.model: None,- starting_ref: DEFAULT_STARTING_REF.to_owned(),+ starting_ref: session+ .repo_branch+ .as_ref()+ .map(|branch| branch.as_str())+ .unwrap_or(DEFAULT_STARTING_REF)+ .to_owned(),record_dir: None,}).map_err(|error| {diff --git a/crates/agent_harness/src/outbound/cursor/manager/test.rs b/crates/agent_harness/src/outbound/cursor/manager/test.rsindex afe5e3bbf7..e27c98cad4 100644--- a/crates/agent_harness/src/outbound/cursor/manager/test.rs+++ b/crates/agent_harness/src/outbound/cursor/manager/test.rs@@ -25,6 +25,7 @@ use std::sync::{Arc, Mutex};/// the manager has no business calling.#[derive(Clone, Default)]struct StubSessions {+ repo_branch: Option<agent_session::domain::repository_branch::RepositoryBranch>,external: Arc<Mutex<HashMap<AgentSessionId, ExternalSession>>>,acp_session_id: Arc<Mutex<Option<String>>>,/// What the repository chooser wrote back, per session.@@ -77,6 +78,7 @@ impl AgentSessionRepo for StubSessions {async fn get(&self, id: AgentSessionId) -> SessionResult<AgentSession> {Ok(AgentSession {+ repo_branch: self.repo_branch.clone(),id,owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_owned()).expect("valid user id"),@@ -86,7 +88,10 @@ impl AgentSessionRepo for StubSessions {bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),model: "auto".to_owned(),harness: "cursor".to_owned(),- repo_url: None,+ repo_url: self+ .repo_branch+ .as_ref()+ .map(|_| "https://github.com/macro-inc/macro".into()),pull_request_url: None,workspace: "/workspace".to_owned(),name: DEFAULT_AGENT_SESSION_NAME.to_owned(),@@ -405,6 +410,7 @@ impl CursorApiKeys for StubKeys {/// path without a model call.struct NoRepositories;+#[async_trait::async_trait]impl ReachableRepositories for NoRepositories {async fn for_user(&self, _user: &MacroUserIdStr<'_>) -> Result<Vec<String>> {Ok(Vec::new())@@ -602,7 +608,15 @@ async fn spawn_uses_the_owners_default_model() {#[tokio::test]async fn session_new_mcp_servers_reach_the_created_agent() {let (base_url, _, created) = fake_cursor_api().await;- let sessions = StubSessions::default();+ let sessions = StubSessions {+ repo_branch: Some(+ agent_session::domain::repository_branch::RepositoryBranch::parse(+ "feature/home".into(),+ )+ .unwrap(),+ ),+ ..StubSessions::default()+ };let session_id = AgentSessionId::new();let manager = manager(base_url, sessions);@@ -665,6 +679,7 @@ async fn session_new_mcp_servers_reach_the_created_agent() {}let body = created.lock().expect("create log poisoned")[0].clone();+ assert_eq!(body["repos"][0]["startingRef"], "feature/home");assert_eq!(body["mcpServers"],serde_json::json!([diff --git a/crates/agent_harness/src/outbound/cursor/repository_chooser.rs b/crates/agent_harness/src/outbound/cursor/repository_chooser.rsindex 0bae23db71..945fe5b95c 100644--- a/crates/agent_harness/src/outbound/cursor/repository_chooser.rs+++ b/crates/agent_harness/src/outbound/cursor/repository_chooser.rs@@ -194,6 +194,22 @@ whereprompt: &str,_cwd: &std::path::Path,) -> Result<SessionIntent, rootcause::Report> {+ // A caller-selected repository was authorized by the opening service.+ // Keep that choice on retries and resumes instead of asking a model to replace it.+ let session =+ self.sessions.get(self.session_id).await.map_err(|error| {+ rootcause::report!("could not read selected repository: {error}")+ })?;+ if session.repo_branch.is_some()+ && let Some(url) = session.repo_url.as_deref()+ {+ let repository = RepoUrl::parse(url)+ .ok_or_else(|| rootcause::report!("invalid selected repository"))?;+ return Ok(SessionIntent {+ repository: Some(repository),+ open_pull_request: true,+ });+ }let mut had_candidates = false;let result = async {let candidates = self.reachable_repositories().await?;diff --git a/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs b/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rsindex fbd29480c8..479dc202d9 100644--- a/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs+++ b/crates/agent_harness/src/outbound/cursor/repository_chooser/test.rs@@ -17,6 +17,7 @@ impl StubRepositories {}}+#[async_trait::async_trait]impl ReachableRepositories for StubRepositories {async fn for_user(&self,@@ -47,6 +48,9 @@ fn candidates() -> Vec<String> {async fn no_reachable_repository_chooses_none_without_asking_the_model() {let session_id = AgentSessionId::new();let mut sessions = MockAgentSessionRepo::new();+ sessions.expect_get().returning(|id| {+ Box::pin(async move { Ok(agent_session::testing::test_agent_session(id)) })+ });sessions.expect_recent_for_owner().never();sessions.expect_set_repo_url()@@ -152,6 +156,7 @@ async fn history_excludes_the_current_session_without_crowding_out_prior_work()Ok(std::iter::once(current).chain(prior).map(|id| AgentSession {+ repo_branch: None,id,name: "session".into(),harness: "cursor".into(),@@ -174,3 +179,41 @@ async fn history_excludes_the_current_session_without_crowding_out_prior_work()expected);}++#[tokio::test]+async fn explicit_repository_bypasses_automatic_selection() {+ let session_id = AgentSessionId::new();+ let mut sessions = MockAgentSessionRepo::new();+ sessions.expect_get().returning(|id| {+ Box::pin(async move {+ let mut session = agent_session::testing::test_agent_session(id);+ session.repo_url = Some("https://github.com/macro-inc/infra".into());+ session.repo_branch = Some(+ agent_session::domain::repository_branch::RepositoryBranch::parse(+ "feature/home".into(),+ )+ .unwrap(),+ );+ Ok(session)+ })+ });+ sessions.expect_set_repo_url().never();+ sessions.expect_recent_for_owner().never();+ let repositories = StubRepositories::with(&[]);+ let chooser = HaikuRepositoryChooser::new(+ Arc::clone(&repositories),+ sessions,+ Arc::new(ai_usage::NoOpUsageRecorder),+ owner(),+ session_id,+ );+ let result = chooser+ .choose("fix home", std::path::Path::new(""))+ .await+ .unwrap();+ assert_eq!(+ result.repository.as_ref().map(RepoUrl::as_str),+ Some("https://github.com/macro-inc/infra")+ );+ assert!(repositories.asked_for.lock().unwrap().is_empty());+}diff --git a/crates/agent_harness/src/outbound/github_repositories.rs b/crates/agent_harness/src/outbound/github_repositories.rsindex 5062eafdda..29850e7355 100644--- a/crates/agent_harness/src/outbound/github_repositories.rs+++ b/crates/agent_harness/src/outbound/github_repositories.rs@@ -28,6 +28,7 @@ where}}+#[async_trait::async_trait]impl<Installations, Client> ReachableRepositoriesfor GithubReachableRepositories<Installations, Client>wherediff --git a/crates/agent_harness/src/outbound/routing/test.rs b/crates/agent_harness/src/outbound/routing/test.rsindex 47a6687ba5..52cd0d82d3 100644--- a/crates/agent_harness/src/outbound/routing/test.rs+++ b/crates/agent_harness/src/outbound/routing/test.rs@@ -123,6 +123,7 @@ impl AgentSessionRepo for FixedBotSessions {async fn get(&self, id: AgentSessionId) -> SessionResult<AgentSession> {Ok(AgentSession {+ repo_branch: None,pull_request_url: None,id,owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_owned())diff --git a/crates/agent_inmem/src/outbound/manager/test.rs b/crates/agent_inmem/src/outbound/manager/test.rsindex c333fcee54..54e0cf7be0 100644--- a/crates/agent_inmem/src/outbound/manager/test.rs+++ b/crates/agent_inmem/src/outbound/manager/test.rs@@ -167,6 +167,7 @@ async fn a_prompt_runs_end_to_end_through_the_real_session_machine() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id,owner_id: owner(),bot_id: BotId::TEST_A,@@ -306,6 +307,7 @@ async fn a_restarted_manager_rebuilds_the_conversation_from_the_log() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id,owner_id: owner(),bot_id: BotId::TEST_A,@@ -452,6 +454,7 @@ async fn instructions_reach_every_turn_including_after_a_reattach() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id,owner_id: owner(),bot_id: BotId::TEST_A,@@ -526,6 +529,7 @@ async fn a_session_without_instructions_hands_the_engine_none() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id,owner_id: owner(),bot_id: BotId::TEST_A,@@ -585,6 +589,7 @@ async fn identity_reaches_every_turn_including_after_a_reattach() {let id = AgentSessionId::new();sessions.create_session(CreateAgentSessionParams {+ repo_branch: None,id,owner_id: owner(),bot_id: BotId::TEST_A,diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rsindex c70d689a1c..c11535e389 100644--- a/crates/agent_session/src/bin/seed_jsonl.rs+++ b/crates/agent_session/src/bin/seed_jsonl.rs@@ -239,6 +239,7 @@ async fn seed(args: &Args) -> Result<(), SeedError> {let session = AgentSessionRepo::create(&repo,CreateAgentSessionParams {+ repo_branch: None,id: session_id,owner_id: owner,bot_id: BotId::new_from_uuid(args.bot_id),diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rsindex 793bb867b4..51c9174c3c 100644--- a/crates/agent_session/src/domain/error.rs+++ b/crates/agent_session/src/domain/error.rs@@ -6,6 +6,9 @@ pub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;#[derive(Error, Debug)]pub enum AgentSessionError {+ /// A repository or branch cannot be used by this session.+ #[error("{0}")]+ InvalidRepositorySelection(&'static str),#[error("agent session {0} already has an active transport")]AlreadyConnected(AgentSessionId),#[error("agent session {0} is managed by another live replica")]diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rsindex 08faba6566..48c59f8429 100644--- a/crates/agent_session/src/domain/mod.rs+++ b/crates/agent_session/src/domain/mod.rs@@ -11,3 +11,5 @@ pub mod service;pub mod session;pub mod credentials;++pub mod repository_branch;diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex 537ab1e3bb..a8ef9ba959 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -176,6 +176,8 @@ pub struct CreateAgentSessionParams {pub harness: String,/// Repository the agent works with, when one was stated.pub repo_url: Option<String>,+ /// Starting branch explicitly selected for this session.+ pub repo_branch: Option<super::repository_branch::RepositoryBranch>,/// Absolute directory the harness runs in on its runtime.pub workspace: String,/// Compute tier the managed sandbox was spawned with.@@ -224,6 +226,8 @@ pub struct AgentSession {pub harness: String,/// repo we are working with, when one was statedpub repo_url: Option<String>,+ /// Starting branch explicitly selected for this session.+ 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>,/// Directory the harness runs in, snapshotted at creation. The sessiondiff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 2a1970e9d1..455dec0555 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -208,12 +208,15 @@ pub struct OpenExternalAgentSession {/// Everything needed to open a session the server hosts itself.///-/// Deliberately thin: a managed session runs in a sandbox this deployment-/// provisions from its own configuration, so the bot, the repository and the-/// workspace are not the caller's to choose. There is no originating mention-/// and nothing to announce.+/// The deployment provisions the selected persona's runtime. Cursor sessions+/// may select an owner-accessible repository and starting branch; workspace+/// paths remain runtime-owned. There is no originating mention to announce.#[derive(Debug, Clone)]pub struct OpenManagedSession {+ /// Repository explicitly selected by the caller for a supported runtime.+ pub repo_url: Option<String>,+ /// Starting branch for the selected repository.+ pub repo_branch: Option<super::repository_branch::RepositoryBranch>,/// The user who owns the session and is credited for its messages.pub owner: MacroUserIdStr<'static>,/// First prompt to deliver once the sandbox is attached. `None` opens andiff --git a/crates/agent_session/src/domain/repository_branch.rs b/crates/agent_session/src/domain/repository_branch.rsnew file mode 100644index 0000000000..ade02709f9--- /dev/null+++ b/crates/agent_session/src/domain/repository_branch.rs@@ -0,0 +1,35 @@+//! Validated names of repository branches selected when a session starts.++/// A branch name, without the `refs/heads/` prefix.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RepositoryBranch(String);++impl RepositoryBranch {+ /// Parse a Git branch name, rejecting ref syntax and revision expressions.+ pub fn parse(value: String) -> Result<Self, &'static str> {+ let valid = !value.is_empty()+ && value != "@"+ && !value.starts_with('-')+ && !value.ends_with('.')+ && !value.contains("..")+ && !value.contains("@{")+ && !value+ .chars()+ .any(|c| c.is_control() || c.is_whitespace() || "~^:?*[\\".contains(c))+ && value+ .split('/')+ .all(|part| !part.is_empty() && !part.starts_with('.') && !part.ends_with(".lock"));+ if !valid {+ return Err("invalid repository branch");+ }+ Ok(Self(value))+ }++ /// The validated branch name passed to the runtime.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++#[cfg(test)]+mod test;diff --git a/crates/agent_session/src/domain/repository_branch/test.rs b/crates/agent_session/src/domain/repository_branch/test.rsnew file mode 100644index 0000000000..ba37df7e6e--- /dev/null+++ b/crates/agent_session/src/domain/repository_branch/test.rs@@ -0,0 +1,13 @@+use super::*;++#[test]+fn accepts_named_branches_and_rejects_revision_expressions() {+ for name in ["main", "develop", "eric/fix-home"] {+ assert_eq!(RepositoryBranch::parse(name.into()).unwrap().as_str(), name);+ }+ for name in [+ "", "@", "-main", "main~1", "a..b", "a//b", "a.lock", ".hidden", "a b", "a@{1}", "a.",+ ] {+ assert!(RepositoryBranch::parse(name.into()).is_err(), "{name}");+ }+}diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 1e5ddeb052..1e64ad2ea2 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -1383,9 +1383,12 @@ pub struct CreateAgentSessionRequest {/// only - an external runtime sends its own first prompt through the/// control endpoint. Omitted, the session opens idle.pub prompt: Option<String>,- /// Repository nominally checked out at `workspace`. Informational and- /// optional: having it cloned there is the runtime operator's job.+ /// Explicit GitHub repository for a managed Cursor session. Access is+ /// checked for the session owner. For external sessions this is+ /// informational: cloning it is the runtime operator's job.pub repo_url: Option<String>,+ /// Starting branch for a managed coding session's selected repository.+ pub repo_branch: Option<String>,/// The user who owns the session. Ignored for user callers, who always/// own their own sessions, and for harness callers, whose verified acting/// user (owner or confirmed team member) owns the session instead;@@ -1528,7 +1531,7 @@ impl IntoResponse for CreateSessionApiError {Self::MixedSessionShape => (StatusCode::UNPROCESSABLE_ENTITY,"a managed session may take a prompt, persona and instructions; naming a \- workspace, repo, owner or thread asks for an external one"+ workspace, owner or thread asks for an external one".to_owned(),),Self::ThreadSessionExists { session_id } => {@@ -1542,6 +1545,13 @@ impl IntoResponse for CreateSessionApiError {StatusCode::CONFLICT,"this bot already has a session for this thread".to_owned(),),+ Self::Domain(AgentSessionError::InvalidRepositorySelection(reason)) => {+ (StatusCode::UNPROCESSABLE_ENTITY, reason.to_owned())+ }+ Self::Domain(AgentSessionError::Forbidden) => (+ StatusCode::FORBIDDEN,+ "repository is not available to this user".to_owned(),+ ),Self::Domain(AgentSessionError::UnknownOwner) => (StatusCode::UNPROCESSABLE_ENTITY,"owner is not a known user".to_owned(),@@ -1669,7 +1679,7 @@ pub async fn create_agent_session_handler<// persona; the domain resolver owns its user/team/channel authorization// policy. External-only fields remain invalid on this shape.let Some(workspace) = request.workspace else {- if request.repo_url.is_some() || request.thread.is_some() || request.owner.is_some() {+ if request.thread.is_some() || request.owner.is_some() {return Err(CreateSessionApiError::MixedSessionShape);}let owner = resolve_owner(&caller.authorization, None)?;@@ -1691,6 +1701,16 @@ pub async fn create_agent_session_handler<let session = state.opener.open_managed_session(OpenManagedSession {+ repo_url: request.repo_url,+ repo_branch: request+ .repo_branch+ .map(crate::domain::repository_branch::RepositoryBranch::parse)+ .transpose()+ .map_err(|reason| {+ CreateSessionApiError::Domain(+ AgentSessionError::InvalidRepositorySelection(reason),+ )+ })?,owner,prompt: request.prompt,profile,@@ -1707,7 +1727,7 @@ pub async fn create_agent_session_handler<// An external runtime sends its own first prompt through the control// endpoint, so accepting one here would silently drop it.- if request.prompt.is_some() {+ if request.prompt.is_some() || request.repo_branch.is_some() {return Err(CreateSessionApiError::MixedSessionShape);}let bot_id = resolve_bot(&caller.authorization, request.bot_id)?;diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex ad5fb382ab..73b3d87a04 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -107,6 +107,7 @@ impl SessionOpener for RecordingOpener {request: OpenExternalAgentSession,) -> crate::domain::error::Result<AgentSession> {let session = AgentSession {+ repo_branch: None,pull_request_url: None,id: AgentSessionId::TEST_A,name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),@@ -141,6 +142,7 @@ impl SessionOpener for RecordingOpener {.as_ref().map_or(BotId::TEST_B, |selected| selected.bot_id);let session = AgentSession {+ repo_branch: None,pull_request_url: None,id: AgentSessionId::TEST_A,name: crate::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),@@ -791,3 +793,52 @@ async fn an_external_open_carries_its_instructions() {}mod read;++#[tokio::test]+async fn managed_repository_and_branch_reach_the_domain() {+ let opener = Arc::new(RecordingOpener::default());+ let response = router_for(opener.clone(), OneBotDirectory::system_coder())+ .oneshot(as_user(+ OWNER,+ serde_json::json!({+ "botId": BotId::TEST_A.as_uuid(),+ "repoUrl": "https://github.com/macro-inc/macro",+ "repoBranch": "feature/home"+ })+ .to_string(),+ ))+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::CREATED);+ let managed = opener.managed.lock().unwrap();+ assert_eq!(+ managed[0].repo_url.as_deref(),+ Some("https://github.com/macro-inc/macro")+ );+ assert_eq!(+ managed[0]+ .repo_branch+ .as_ref()+ .map(|branch| branch.as_str()),+ Some("feature/home")+ );+}++#[tokio::test]+async fn invalid_repository_branch_is_rejected_before_opening() {+ let opener = Arc::new(RecordingOpener::default());+ let response = router_for(opener.clone(), OneBotDirectory::system_coder())+ .oneshot(as_user(+ OWNER,+ serde_json::json!({+ "botId": BotId::TEST_A.as_uuid(),+ "repoUrl": "https://github.com/macro-inc/macro",+ "repoBranch": "../invalid"+ })+ .to_string(),+ ))+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);+ assert!(opener.managed.lock().unwrap().is_empty());+}diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rsindex e5e116b25c..0bd7c4e207 100644--- a/crates/agent_session/src/inbound/axum_router/test/read.rs+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs@@ -9,6 +9,7 @@ use crate::testing::InMemoryAgentSessionRepo;async fn view_router() -> Router {let repo = InMemoryAgentSessionRepo::new();repo.create(CreateAgentSessionParams {+ repo_branch: None,id: AgentSessionId::TEST_A,owner_id: MacroUserIdStr::try_from(OWNER.to_owned()).unwrap(),bot_id: BotId::TEST_A,diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex bf77a6ac29..89791d4988 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -193,6 +193,7 @@ struct AgentSessionRow {model: String,harness: String,repo_url: Option<String>,+ repo_branch: Option<String>,pull_request_url: Option<String>,workspace: String,sandbox_size: String,@@ -228,6 +229,11 @@ impl TryFrom<AgentSessionRow> for AgentSession {model: row.model,harness: row.harness,repo_url: row.repo_url,+ repo_branch: row+ .repo_branch+ .map(crate::domain::repository_branch::RepositoryBranch::parse)+ .transpose()+ .map_err(anyhow::Error::msg)?,pull_request_url: row.pull_request_url,workspace: row.workspace,sandbox_size: parse_sandbox_size(&row.sandbox_size)?,@@ -266,6 +272,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {model,harness,repo_url,+ repo_branch,workspace,sandbox_size,instructions,@@ -292,12 +299,12 @@ impl AgentSessionRepo for PgAgentSessionRepo {id, owner_id, thread_id, originating_message_id, bot_id, model,harness, repo_url, workspace, sandbox_size, instructions,acp_session_id, status, status_event_name, egress_token_hash,- mcp_scope, mcp_servers+ mcp_scope, mcp_servers, repo_branch)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)RETURNINGid, name, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, created_at, modified_at,(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)@@ -324,6 +331,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {egress_token_hash,mcp_servers.scope_str(),mcp_servers_json,+ repo_branch.as_ref().map(|branch| branch.as_str()),).fetch_one(&mut *transaction).await@@ -411,7 +419,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {r#"SELECTid, name, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)@@ -521,7 +529,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {r#"SELECTid, name, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)@@ -561,7 +569,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {r#"SELECTid, name, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)@@ -594,7 +602,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {r#"SELECTid, name, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)@@ -629,7 +637,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {r#"SELECTid, name, owner_id, thread_id, originating_message_id, bot_id,- model, harness, repo_url, pull_request_url, workspace, sandbox_size, instructions,+ model, harness, repo_url, repo_branch, pull_request_url, workspace, sandbox_size, instructions,mcp_scope, mcp_servers, acp_session_id, status,status_event_name, agent_session.created_at, modified_at,(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex 8e2d17d5bd..93a78df424 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -84,6 +84,7 @@ fn new_session(originating_message_id: Option<Uuid>,) -> CreateAgentSessionParams {CreateAgentSessionParams {+ repo_branch: None,id: AgentSessionId::new(),owner_id: user_id(OWNER),bot_id,@@ -217,7 +218,10 @@ fn acp_notification() -> AcpMessage {async fn create_and_get_round_trips(pool: PgPool) {let repo = PgAgentSessionRepo::new(pool.clone());let bot_id = create_test_bot(&pool).await;- let params = new_session(bot_id, None, None);+ let mut params = new_session(bot_id, None, None);+ params.repo_branch = Some(+ crate::domain::repository_branch::RepositoryBranch::parse("feature/home".into()).unwrap(),+ );let id = params.id;let created = create_session(&repo, params).await;@@ -229,6 +233,10 @@ async fn create_and_get_round_trips(pool: PgPool) {assert_eq!(created.created_at, session.created_at);assert_eq!(created.modified_at, session.modified_at);assert_eq!(session.id, id);+ assert_eq!(+ session.repo_branch.as_ref().map(|branch| branch.as_str()),+ Some("feature/home")+ );assert_eq!(session.name, DEFAULT_AGENT_SESSION_NAME);assert_eq!(session.bot_id, bot_id);assert_eq!(diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rsindex 02ecb5fda0..af7d3888ac 100644--- a/crates/agent_session/src/testing.rs+++ b/crates/agent_session/src/testing.rs@@ -129,6 +129,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {async fn create(&self, params: CreateAgentSessionParams) -> Result<AgentSession> {let now = chrono::Utc::now();let session = AgentSession {+ repo_branch: params.repo_branch,pull_request_url: None,id: params.id,name: DEFAULT_AGENT_SESSION_NAME.to_owned(),@@ -690,6 +691,7 @@ impl agent_fold::domain::ports::LogRepo for InMemoryAgentSessionRepo {pub fn test_agent_session(id: AgentSessionId) -> AgentSession {let now = chrono::Utc::now();AgentSession {+ repo_branch: None,pull_request_url: None,id,name: DEFAULT_AGENT_SESSION_NAME.to_owned(),diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rsindex 04fbecdd90..92cd48e805 100644--- a/crates/agent_trigger/src/domain/service/test.rs+++ b/crates/agent_trigger/src/domain/service/test.rs@@ -104,6 +104,7 @@ fn message(mentions: Vec<SimpleMention>) -> ChannelMessagePostedMetadata {fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {AgentSession {+ repo_branch: None,pull_request_url: None,id,name: agent_session::domain::model::DEFAULT_AGENT_SESSION_NAME.to_owned(),diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rsindex 0122698108..c55ce7f9fc 100644--- a/crates/coding_agent_worker/src/dispatch.rs+++ b/crates/coding_agent_worker/src/dispatch.rs@@ -59,6 +59,7 @@ impl WorkExecutor for Dispatcher {// the control endpoint. Sending one here is refused.prompt: None,repo_url: self.workspace.repo_url.clone(),+ repo_branch: None,owner: Some(sender.as_ref().to_owned()),thread: Some(CreateSessionThread {channel_id,diff --git a/crates/macro_db_client/migrations/20260917192903_agent_session_repo_branch.sql b/crates/macro_db_client/migrations/20260917192903_agent_session_repo_branch.sqlnew file mode 100644index 0000000000..cf4e2157b3--- /dev/null+++ b/crates/macro_db_client/migrations/20260917192903_agent_session_repo_branch.sql@@ -0,0 +1 @@+ALTER TABLE agent_session ADD COLUMN repo_branch TEXT;diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex f70152df39..9a19c0353a 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -39,8 +39,13 @@- Selecting a coding agent reveals a repository drawer directly under the inputwith a short slide and fade; selecting a chat agent retracts it. Reduced-motionpreferences disable the animation. The hidden drawer is inert. **Repository**- offers **No repository**, recent repositories, or `owner/repo` / URL entry.- The chosen repository survives agent changes and is sent only to coding agents.+ offers **Choose automatically**, recent repositories, or GitHub `owner/repo` /+ URL entry confirmed with **Use repository**. Once selected, **Branch** opens+ a starting-branch field confirmed with **Use branch** (initially `main`).+ Both controls open above the drawer without clipping. The selections survive+ agent changes and are sent only to coding agents. Cursor honors the explicit+ repository and branch instead of choosing a repository from the prompt;+ the owner must have access through the connected GitHub App.- Sending starts a session with the chosen agent's configured default model;a model selected from its submenu overrides that default for the next sendonly. Sending or choosing another agent clears the override. This does not@@ -64,7 +69,10 @@tab includes runtime setup. The create/edit dialog has sharing, name,`@tag`, runtime, default model, connections, channels, and instructions.- **Session**: the header has the sidebar reopen control, a linked PR status chip,- favorite, Share, Side panel, and a More menu+ favorite, Share, and Side panel. The top-left title uses the same provider icon,+ saved-title precedence, and title menu as `/app/agent/<id>`; click the caret+ beside the title for shared block actions such as Rename, Copy link, Favorite,+ and Delete(Rename, Copy link, Delete). A metadata strip lists the agent, runtime,model, repository, and status. Chat and Code session inputsuse the same growing, initially single-line input with the model selector on@@ -210,6 +218,16 @@ Leaving Macro selected uses the backend's in-memory default in everyenvironment, including production; it does not provision a Daytona container.Explicit coding-agent selections still use their configured runtimes.+## Starting from Home++Home's composer follows the existing `enable-chat-v3-agents` flag: disabled keeps+legacy chat; enabled mounts the same new-conversation composer as the Agents page.+The greeting, agent/model selector, coding repository/branch drawer, and send flow+are shared. Sending opens the new session inside Agents with the matching URL.+Home suggestions and document/project context populate this same draft as markdown+mentions. A failed suggestion conversion preserves the text and shows an error.+Session creation and prompt delivery use the shared pending-session flow.+## Sharing a chatA standalone chat (`/app/chat/<uuid>`) has **Share** and **Copy Share Link** in@@ -233,8 +251,7 @@ documents:Open a doc → side panel `Actions` → `Ask Macro`. Opens a chat pane with the document alreadyattached as context (it appears as a link chip in the composer). New-chat pane shows tips:`@mention anything` to attach entities, `Ctrl+Enter` to send in the background (you get-notified when the AI responds). Background sends from Home preserve the submitted-tool selection.+notified when the AI responds). Legacy Home background sends preserve the submitted tool selection.## Composer anatomy (a11y)diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex 02753a1f7d..7b34ff64e1 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -404,8 +404,13 @@ export type CreateAgentSessionRequest = {*/prompt?: string | null;/**- * Repository nominally checked out at `workspace`. Informational and- * optional: having it cloned there is the runtime operator's job.+ * Starting branch for a managed coding session's selected repository.+ */+ repoBranch?: string | null;+ /**+ * Explicit GitHub repository for a managed Cursor session. Access is+ * checked for the session owner. For external sessions this is+ * informational: cloning it is the runtime operator's job.*/repoUrl?: string | null;thread?: null | CreateSessionThread;diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex f362574a52..87e7d3e5ed 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -1573,9 +1573,13 @@"type": ["string", "null"],"description": "First prompt to deliver once the session is running. Managed sessions\nonly - an external runtime sends its own first prompt through the\ncontrol endpoint. Omitted, the session opens idle."},+ "repoBranch": {+ "type": ["string", "null"],+ "description": "Starting branch for a managed coding session's selected repository."+ },"repoUrl": {"type": ["string", "null"],- "description": "Repository nominally checked out at `workspace`. Informational and\noptional: having it cloned there is the runtime operator's job."+ "description": "Explicit GitHub repository for a managed Cursor session. Access is\nchecked for the session owner. For external sessions this is\ninformational: cloning it is the runtime operator's job."},"thread": {"oneOf": [diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 540df5d614..a95d101505 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -478,7 +478,7 @@ async fn run() -> anyhow::Result<()> {cursor_keys.clone(),cursor_api_base_url(),session_repo.clone(),- reachable_repositories,+ Arc::clone(&reachable_repositories),ai_usage::pg_recorder(pool.clone()),PostgresJournal {pool: pool.clone(),@@ -717,23 +717,29 @@ async fn run() -> anyhow::Result<()> {// explicitly selected coding agents keep their configured runtimes..with_managed_bot(inmem_bot);- let harness = Arc::new(AgentHarnessService::new(- sessions,- containers,- announcer,- HarnessKeyedConnections::new(PgHarnessBindings::new(pool.clone()), Arc::clone(&runtimes)),- prompt_context,- prompt_composer,- EgressProvisioner::new(Arc::clone(&mcp_connections), egress_base_url),- RedisCommandForwarder::new(redis.clone()),- defaults,- Arc::clone(&lifecycle_publisher),- pending_commands,- prompt_mentions,- // Finished / asking / mentioned reach people through the same- // notification ingress channel messages use.- IngressAgentSessionNotifier::new(Arc::clone(¬ifications)),- ));+ let harness = Arc::new(+ AgentHarnessService::new(+ sessions,+ containers,+ announcer,+ HarnessKeyedConnections::new(+ PgHarnessBindings::new(pool.clone()),+ Arc::clone(&runtimes),+ ),+ prompt_context,+ prompt_composer,+ EgressProvisioner::new(Arc::clone(&mcp_connections), egress_base_url),+ RedisCommandForwarder::new(redis.clone()),+ defaults,+ Arc::clone(&lifecycle_publisher),+ pending_commands,+ prompt_mentions,+ // Finished / asking / mentioned reach people through the same+ // notification ingress channel messages use.+ IngressAgentSessionNotifier::new(Arc::clone(¬ifications)),+ )+ .with_repositories(reachable_repositories),+ );// Close the loop: turn ends observed by the session actors drain the// harness's prompt queue.turn_observer.bind(harness.clone());