Skip to content

armgit / macro

Public Imported from GitHub
0

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

Show mentionable shared personas in the agent composer (#6384)

Eric Hayes9a0233d06f73
diff --git a/.sqlx/query-797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98.json b/.sqlx/query-53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7.json
similarity index 85%
rename from .sqlx/query-797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98.json
rename to .sqlx/query-53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7.json
index 359dfc92bc..7dd8b340bd 100644
--- a/.sqlx/query-797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98.json
+++ b/.sqlx/query-53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
+ "query": "\n SELECT\n b.id,\n b.kind,\n b.owner_user_id,\n b.team_id,\n b.name,\n b.handle,\n b.description,\n b.avatar_url,\n b.created_by,\n b.created_at,\n b.updated_at,\n b.deleted_at,\n b.has_agent,\n a.instructions,\n a.harness,\n a.harness_id,\n a.default_model,\n a.channel_scope,\n ARRAY(\n SELECT p.channel_id\n FROM comms_channel_participants p\n WHERE p.user_id = 'bot|' || b.id::text\n AND p.left_at IS NULL\n ORDER BY p.channel_id\n ) AS \"channel_ids!\",\n a.mcp_scope,\n ARRAY(\n SELECT m.app_slug\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_app_slugs!\",\n ARRAY(\n SELECT m.server_name\n FROM agent_mcp_servers m\n WHERE m.bot_id = b.id\n ORDER BY m.app_slug\n ) AS \"mcp_server_names!\"\n FROM bots b\n INNER JOIN agent_configs a ON a.bot_id = b.id\n WHERE b.kind = 'owned'\n AND b.deleted_at IS NULL\n AND (\n b.owner_user_id = $1\n OR b.team_id IN (\n SELECT team_id FROM team_user WHERE user_id = $1\n )\n OR (\n a.channel_scope = 'selected'\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $1\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = 'bot|' || b.id::text\n AND bot_p.left_at IS NULL\n )\n )\n )\n ORDER BY b.created_at ASC, b.id ASC\n ",
"describe": {
"columns": [
{
@@ -144,5 +144,5 @@
null
]
},
- "hash": "797e496988921e2f577b148abb390ab5bd246eea93626be6103ccd5849ec6c98"
+ "hash": "53568ca36df771ed291dad0d1edf013b45e322d08e5bb0c3c37b3084f459cdb7"
}
diff --git a/.sqlx/query-8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70.json b/.sqlx/query-8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70.json
new file mode 100644
index 0000000000..8a4d64bd44
--- /dev/null
+++ b/.sqlx/query-8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM comms_channel_participants bot_p\n INNER JOIN comms_channel_participants user_p\n ON user_p.channel_id = bot_p.channel_id\n AND user_p.user_id = $2\n AND user_p.left_at IS NULL\n WHERE bot_p.user_id = $1\n AND bot_p.left_at IS NULL\n ) AS \"shares!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "shares!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "8a18ae7fd3e128f4310259d0b98b649ed1fdbc54cad49ca8fe0c32db08afaa70"
+}
diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx
index 4164c55b6c..f4ce8c3b12 100644
--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx
+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.test.tsx
@@ -95,6 +95,33 @@ vi.mock('@queries/agents/agents', () => ({
harness: 'in-memory',
default_model: 'anthropic/claude-opus-5',
},
+ {
+ bot: {
+ id: 'shared-reviewer',
+ name: 'Shared Reviewer',
+ handle: 'shared-reviewer',
+ has_agent: true,
+ owner: { type: 'user', user_id: 'macro|[email protected]' },
+ },
+ harness: 'in-memory',
+ default_model: 'anthropic/claude-sonnet-5',
+ },
+ {
+ bot: {
+ id: 'team-helper',
+ name: 'Team Helper',
+ handle: 'team-helper',
+ has_agent: true,
+ owner: { type: 'team', team_id: 'team-1' },
+ },
+ harness: 'in-memory',
+ default_model: 'anthropic/claude-sonnet-5',
+ },
+ {
+ bot: { id: 'local', name: 'Local', handle: 'local', has_agent: true },
+ harness: 'macrod',
+ default_model: 'anthropic/claude-sonnet-5',
+ },
],
}),
}));
@@ -377,12 +404,23 @@ describe('agent session creation', () => {
expect(macro.queryByText('coding')).toBeNull();
expect(cursor.getByText('@cursor')).toBeTruthy();
expect(cursor.queryByText('coding')).toBeNull();
- const reviewer = within(screen.getByRole('radio', { name: /Reviewer/ }));
+ const reviewer = within(screen.getByRole('radio', { name: /^Reviewer/ }));
const coder = within(screen.getByRole('radio', { name: /Coder/ }));
expect(reviewer.getByText('@reviewer')).toBeTruthy();
expect(reviewer.queryByText('coding')).toBeNull();
expect(coder.getByText('@coder')).toBeTruthy();
expect(coder.queryByText('coding')).toBeNull();
+ expect(
+ within(screen.getByRole('radio', { name: /Shared Reviewer/ })).getByText(
+ '@shared-reviewer'
+ )
+ ).toBeTruthy();
+ expect(
+ within(screen.getByRole('radio', { name: /Team Helper/ })).getByText(
+ '@team-helper'
+ )
+ ).toBeTruthy();
+ expect(screen.queryByRole('radio', { name: /Local/ })).toBeNull();
expect(
screen.getByText(
'Starts quickly and runs in-memory. Great for workspace tasks'
diff --git a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
index 7df8b5c20c..b72edfde99 100644
--- a/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
+++ b/apps/web/src/features/block-agent/component/ComposeAgentSession.tsx
@@ -132,7 +132,8 @@ function ComposeAgentSessionContent(props: ComposeAgentSessionProps) {
const shouldAutofocusPrompt = () =>
canAutofocusSplitContent && !isTouchDevice();
- // The two first-party agents lead, then the user's own personas.
+ // First-party agents lead, then saved personas the caller can start —
+ // their own, team-shared, and selected-channel personas they can `@`.
const personas = createMemo<PersonaOption[]>(() => [
{
id: MACRO_PERSONA_ID,
diff --git a/apps/web/src/features/channel/Bots/botPermissions.ts b/apps/web/src/features/channel/Bots/botPermissions.ts
index 81ba8f2533..1e7047b3d5 100644
--- a/apps/web/src/features/channel/Bots/botPermissions.ts
+++ b/apps/web/src/features/channel/Bots/botPermissions.ts
@@ -18,3 +18,14 @@ export function canDeleteBot(
(bot.owner.team_id === currentTeamId && isCurrentTeamOwner)
);
}
+
+/** Whether Settings should treat this agent as one the caller can configure. */
+export function canManageAgent(
+ bot: BotOwnership,
+ currentUserId: string | undefined,
+ currentTeamId: string | undefined
+): boolean {
+ if (!currentUserId || !bot.owner) return false;
+ if (bot.owner.type === 'user') return bot.owner.user_id === currentUserId;
+ return bot.owner.team_id === currentTeamId;
+}
diff --git a/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts b/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts
index de6f054a54..c72f18f469 100644
--- a/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts
+++ b/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { canDeleteBot } from '../botPermissions';
+import { canDeleteBot, canManageAgent } from '../botPermissions';
const CURRENT_USER = 'macro|[email protected]';
const CREATOR = 'macro|[email protected]';
@@ -40,3 +40,45 @@ describe('canDeleteBot', () => {
expect(canDeleteBot(bot, CURRENT_USER, 'team-2', true)).toBe(false);
});
});
+
+describe('canManageAgent', () => {
+ it('allows the owner of a private agent', () => {
+ expect(
+ canManageAgent(
+ { owner: { type: 'user', user_id: CURRENT_USER } },
+ CURRENT_USER,
+ TEAM_ID
+ )
+ ).toBe(true);
+ });
+
+ it('rejects a coworker private agent that is only mentionable', () => {
+ expect(
+ canManageAgent(
+ { owner: { type: 'user', user_id: CREATOR } },
+ CURRENT_USER,
+ TEAM_ID
+ )
+ ).toBe(false);
+ });
+
+ it("allows team-owned agents for the caller's current team", () => {
+ expect(
+ canManageAgent(
+ { owner: { type: 'team', team_id: TEAM_ID } },
+ CURRENT_USER,
+ TEAM_ID
+ )
+ ).toBe(true);
+ });
+
+ it('rejects a team-owned agent from another team', () => {
+ expect(
+ canManageAgent(
+ { owner: { type: 'team', team_id: 'team-2' } },
+ CURRENT_USER,
+ TEAM_ID
+ )
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsx
index 3201413ff4..aba8609caa 100644
--- a/apps/web/src/features/settings/Agents.test.tsx
+++ b/apps/web/src/features/settings/Agents.test.tsx
@@ -484,6 +484,59 @@ describe('Agents', () => {
).toBeTruthy();
});
+ it('does not list a coworker private agent in Settings', () => {
+ agentMocks.query.data = [
+ {
+ bot: {
+ id: 'agent-shared',
+ kind: 'owned',
+ owner: { type: 'user', user_id: 'macro|[email protected]' },
+ name: 'Shared Reviewer',
+ handle: 'shared-reviewer',
+ has_agent: true,
+ created_at: '2026-08-27T12:00:00Z',
+ updated_at: '2026-08-27T12:00:00Z',
+ },
+ instructions: 'Review pull requests.',
+ harness: 'in-memory',
+ default_model: Model.sonnet5,
+ channel_scope: 'selected',
+ channel_ids: ['channel-engineering'],
+ },
+ ];
+
+ render(() => <Agents />);
+
+ expect(screen.queryByText('Shared Reviewer')).toBeNull();
+ expect(screen.getByText('No private agents yet.')).toBeTruthy();
+ });
+
+ it("does not list another team's mentionable agent in Settings", () => {
+ agentMocks.query.data = [
+ {
+ bot: {
+ id: 'agent-other-team',
+ kind: 'owned',
+ owner: { type: 'team', team_id: 'team-other' },
+ name: 'Other Team Helper',
+ handle: 'other-team-helper',
+ has_agent: true,
+ created_at: '2026-08-27T12:00:00Z',
+ updated_at: '2026-08-27T12:00:00Z',
+ },
+ instructions: 'Help the other team.',
+ harness: 'in-memory',
+ default_model: Model.sonnet5,
+ channel_scope: 'selected',
+ channel_ids: ['channel-engineering'],
+ },
+ ];
+
+ render(() => <Agents />);
+
+ expect(screen.queryByText('Other Team Helper')).toBeNull();
+ });
+
it('edits and persists an existing agent through the agents API', async () => {
agentMocks.query.data = [
{
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index 3ba6317f20..03b03c849b 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -36,7 +36,7 @@ import { useSearchParams } from '@solidjs/router';
import { Avatar, Button, Dialog, Panel } from '@ui';
import { createMemo, createSignal, For, Show } from 'solid-js';
import { botAssignableChannelOptions } from '../channel/Bots/botChannelOptions';
-import { canDeleteBot } from '../channel/Bots/botPermissions';
+import { canDeleteBot, canManageAgent } from '../channel/Bots/botPermissions';
import { ChannelMultiSelect } from '../channel/Bots/ChannelMultiSelect';
import { PipedreamAppPicker } from './PipedreamAppPicker';
import {
@@ -159,9 +159,13 @@ export function Agents() {
const canDeleteAgent = (agent: AgentWithHarnessId) =>
canDeleteBot(agent.bot, currentUserId(), currentTeamId(), isTeamOwner());
const agents = createMemo(() =>
- (agentsQuery.isSuccess ? agentsQuery.data : []).map((agent) =>
- summarizeAgent(agent, connectedHarnesses(), channelOptions())
- )
+ (agentsQuery.isSuccess ? agentsQuery.data : [])
+ .filter((agent) =>
+ canManageAgent(agent.bot, currentUserId(), currentTeamId())
+ )
+ .map((agent) =>
+ summarizeAgent(agent, connectedHarnesses(), channelOptions())
+ )
);
const teamAgents = createMemo(() => [
MACRO_AGENT,
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.ts
index f8a063f1f3..a712fbd463 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
@@ -28,10 +28,11 @@ Clients serialize this, so both derives are used.
*/
export interface CreateAgentSessionRequest {
/** Bot the session runs for. On a managed request this optionally selects
-a persisted persona the user owns or may use through team membership;
-omitting it uses the deployment's default coding persona. On an
-external request, bot callers may omit it (their own identity is used)
-and must not name another bot; user callers must supply a bot they own. */
+a persisted persona the user owns, may use through team membership, or
+can `@` mention in a shared channel; omitting it uses the deployment's
+default coding persona. On an external request, bot callers may omit it
+(their own identity is used) and must not name another bot; user callers
+must supply a bot they own. */
botId?: CreateAgentSessionRequestBotId;
/** Instructions the session's runtime works under, for its whole life.
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
index 1456e0d568..80e95f722a 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
@@ -7,9 +7,10 @@
/**
* Bot the session runs for. On a managed request this optionally selects
-a persisted persona the user owns or may use through team membership;
-omitting it uses the deployment's default coding persona. On an
-external request, bot callers may omit it (their own identity is used)
-and must not name another bot; user callers must supply a bot they own.
+a persisted persona the user owns, may use through team membership, or
+can `@` mention in a shared channel; omitting it uses the deployment's
+default coding persona. On an external request, bot callers may omit it
+(their own identity is used) and must not name another bot; user callers
+must supply a bot they own.
*/
export type CreateAgentSessionRequestBotId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index ce354856a0..737595ee52 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
@@ -1408,7 +1408,7 @@
"botId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns or may use through team membership;\nomitting it uses the deployment's default coding persona. On an\nexternal request, bot callers may omit it (their own identity is used)\nand must not name another bot; user callers must supply a bot they own."
+ "description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns, may use through team membership, or\ncan `@` mention in a shared channel; omitting it uses the deployment's\ndefault coding persona. On an external request, bot callers may omit it\n(their own identity is used) and must not name another bot; user callers\nmust supply a bot they own."
},
"instructions": {
"type": ["string", "null"],
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 1a4027d75b..5306b5f06f 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -45,6 +45,9 @@ pub struct BotFacts {
/// Runtime profile for a persisted agent. Fixed system bots have no
/// persisted profile and use deployment defaults instead.
pub managed_profile: Option<ManagedAgentProfile>,
+ /// Whether the persona is limited to selected channels. Channel co-members
+ /// may start a session as it, matching `@` mentions in those channels.
+ pub selected_channels: bool,
}
/// Runtime settings snapshotted when a managed persona opens a session.
@@ -81,6 +84,13 @@ pub trait BotDirectory: Send + Sync + 'static {
user: MacroUserIdStr<'static>,
team_id: Uuid,
) -> impl Future<Output = Result<bool>> + Send;
+
+ /// Whether the user and bot share at least one active channel.
+ fn user_shares_channel_with_bot(
+ &self,
+ user: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<bool>> + Send;
}
/// Why a user cannot select a bot as a managed session persona.
@@ -101,9 +111,10 @@ pub enum ManagedPersonaError {
/// Resolve and authorize a managed persona for a user.
///
/// Ownership policy lives in the domain: private personas belong to their
-/// owner, team personas are available to team members, and managed system
-/// bots (the deployment's own coders) are available to everyone, exactly as
-/// they are when mentioned in a channel.
+/// owner, team personas are available to team members, selected-channel
+/// personas are available to anyone who can `@` them in a shared channel,
+/// and managed system bots (the deployment's own coders) are available to
+/// everyone, exactly as they are when mentioned in a channel.
pub async fn managed_persona_for_user<Bots: BotDirectory>(
bots: &Bots,
bot_id: BotId,
@@ -126,12 +137,22 @@ pub async fn managed_persona_for_user<Bots: BotDirectory>(
profile: None,
});
}
- let authorized = if let Some(owner) = facts.owner_user_id {
+ let authorized = if let Some(owner) = &facts.owner_user_id {
owner.as_ref() == user.as_ref()
+ || (facts.selected_channels
+ && bots
+ .user_shares_channel_with_bot(user.clone(), bot_id)
+ .await
+ .map_err(ManagedPersonaError::Lookup)?)
} else if let Some(team_id) = facts.owner_team_id {
bots.user_has_team(user.clone(), team_id)
.await
.map_err(ManagedPersonaError::Lookup)?
+ || (facts.selected_channels
+ && bots
+ .user_shares_channel_with_bot(user.clone(), bot_id)
+ .await
+ .map_err(ManagedPersonaError::Lookup)?)
} else {
false
};
@@ -917,3 +938,6 @@ pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {
id: AgentSessionId,
) -> impl Future<Output = Result<Option<harness_id::HarnessId>>> + Send;
}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/agent_session/src/domain/ports/test.rs b/crates/agent_session/src/domain/ports/test.rs
new file mode 100644
index 0000000000..fd636e0281
--- /dev/null
+++ b/crates/agent_session/src/domain/ports/test.rs
@@ -0,0 +1,173 @@
+use super::{BotDirectory, BotFacts, ManagedPersonaError, managed_persona_for_user};
+use bots::domain::models::BotId;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+
+const OWNER: &str = "macro|[email protected]";
+const TEAMMATE: &str = "macro|[email protected]";
+const STRANGER: &str = "macro|[email protected]";
+
+struct Directory {
+ facts: BotFacts,
+ team_members: Vec<&'static str>,
+ channel_members: Vec<&'static str>,
+}
+
+impl Directory {
+ fn managed_private() -> Self {
+ Self {
+ facts: managed_facts(false),
+ team_members: Vec::new(),
+ channel_members: Vec::new(),
+ }
+ }
+
+ fn managed_selected_channel() -> Self {
+ Self {
+ facts: managed_facts(true),
+ team_members: Vec::new(),
+ channel_members: vec![OWNER, TEAMMATE],
+ }
+ }
+
+ fn managed_team() -> Self {
+ let mut facts = managed_facts(false);
+ facts.owner_user_id = None;
+ facts.owner_team_id = Some(Uuid::nil());
+ Self {
+ facts,
+ team_members: vec![OWNER, TEAMMATE],
+ channel_members: Vec::new(),
+ }
+ }
+
+ fn managed_team_selected_channel() -> Self {
+ let mut facts = managed_facts(true);
+ facts.owner_user_id = None;
+ facts.owner_team_id = Some(Uuid::nil());
+ Self {
+ facts,
+ team_members: vec![OWNER],
+ channel_members: vec![OWNER, TEAMMATE],
+ }
+ }
+}
+
+fn managed_facts(selected_channels: bool) -> BotFacts {
+ BotFacts {
+ has_agent: true,
+ is_managed: true,
+ is_system: false,
+ owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ owner_team_id: None,
+ harness_id: None,
+ managed_profile: Some(super::ManagedAgentProfile {
+ model: "persona-model".to_owned(),
+ harness: "in-memory".to_owned(),
+ instructions: "persona instructions".to_owned(),
+ mcp_servers: Default::default(),
+ }),
+ selected_channels,
+ }
+}
+
+fn user(id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(id.to_owned()).unwrap()
+}
+
+impl BotDirectory for Directory {
+ async fn bot_facts(&self, bot: BotId) -> super::Result<Option<BotFacts>> {
+ Ok((bot == BotId::TEST_A).then(|| self.facts.clone()))
+ }
+
+ async fn user_has_team(
+ &self,
+ user: MacroUserIdStr<'static>,
+ _team_id: Uuid,
+ ) -> super::Result<bool> {
+ Ok(self.team_members.contains(&user.as_ref()))
+ }
+
+ async fn user_shares_channel_with_bot(
+ &self,
+ user: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> super::Result<bool> {
+ Ok(self.channel_members.contains(&user.as_ref()))
+ }
+}
+
+#[tokio::test]
+async fn owner_can_select_a_private_persona() {
+ let selected =
+ managed_persona_for_user(&Directory::managed_private(), BotId::TEST_A, &user(OWNER))
+ .await
+ .expect("owner");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+}
+
+#[tokio::test]
+async fn stranger_cannot_select_a_private_all_channel_persona() {
+ let error = managed_persona_for_user(
+ &Directory::managed_private(),
+ BotId::TEST_A,
+ &user(STRANGER),
+ )
+ .await
+ .expect_err("private all-channel personas stay with their owner");
+ assert!(matches!(error, ManagedPersonaError::Forbidden));
+}
+
+#[tokio::test]
+async fn channel_co_member_can_select_a_selected_channel_persona() {
+ let selected = managed_persona_for_user(
+ &Directory::managed_selected_channel(),
+ BotId::TEST_A,
+ &user(TEAMMATE),
+ )
+ .await
+ .expect("channel co-member");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+}
+
+#[tokio::test]
+async fn stranger_cannot_select_a_selected_channel_persona_without_membership() {
+ let error = managed_persona_for_user(
+ &Directory::managed_selected_channel(),
+ BotId::TEST_A,
+ &user(STRANGER),
+ )
+ .await
+ .expect_err("no shared channel");
+ assert!(matches!(error, ManagedPersonaError::Forbidden));
+}
+
+#[tokio::test]
+async fn team_member_can_select_a_team_persona() {
+ let selected =
+ managed_persona_for_user(&Directory::managed_team(), BotId::TEST_A, &user(TEAMMATE))
+ .await
+ .expect("team member");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+}
+
+#[tokio::test]
+async fn stranger_cannot_select_a_team_all_channel_persona() {
+ let error =
+ managed_persona_for_user(&Directory::managed_team(), BotId::TEST_A, &user(STRANGER))
+ .await
+ .expect_err("all-channel team personas stay with the team");
+ assert!(matches!(error, ManagedPersonaError::Forbidden));
+}
+
+#[tokio::test]
+async fn channel_co_member_can_select_a_team_selected_channel_persona() {
+ let selected = managed_persona_for_user(
+ &Directory::managed_team_selected_channel(),
+ BotId::TEST_A,
+ &user(TEAMMATE),
+ )
+ .await
+ .expect("channel co-member");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 62a3a616c8..1166ed4df3 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -1365,10 +1365,11 @@ where
#[serde(rename_all = "camelCase")]
pub struct CreateAgentSessionRequest {
/// Bot the session runs for. On a managed request this optionally selects
- /// a persisted persona the user owns or may use through team membership;
- /// omitting it uses the deployment's default coding persona. On an
- /// external request, bot callers may omit it (their own identity is used)
- /// and must not name another bot; user callers must supply a bot they own.
+ /// a persisted persona the user owns, may use through team membership, or
+ /// can `@` mention in a shared channel; omitting it uses the deployment's
+ /// default coding persona. On an external request, bot callers may omit it
+ /// (their own identity is used) and must not name another bot; user callers
+ /// must supply a bot they own.
pub bot_id: Option<Uuid>,
/// Absolute directory the bot's harness runs in on its runtime. Present
/// for an external session, absent for a managed one, which runs in the
@@ -1661,8 +1662,8 @@ pub async fn create_agent_session_handler<
let instructions = request.instructions.filter(|text| !text.trim().is_empty());
// No workspace means the managed shape. A bot id selects a managed
- // persona; the domain resolver owns its user/team authorization policy.
- // External-only fields remain invalid on this shape.
+ // 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() {
return Err(CreateSessionApiError::MixedSessionShape);
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index c061dbca3a..fc920bbd0b 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -177,11 +177,13 @@ impl SessionOpener for RecordingOpener {
/// [`OWNER`]. Every other id is unknown.
struct OneBotDirectory {
facts: BotFacts,
+ shares_channel_with: Vec<&'static str>,
}
impl OneBotDirectory {
fn external_agent() -> Self {
Self {
+ shares_channel_with: Vec::new(),
facts: BotFacts {
has_agent: true,
is_managed: false,
@@ -190,12 +192,14 @@ impl OneBotDirectory {
owner_team_id: None,
harness_id: Some(harness_id::HarnessId::TEST_A),
managed_profile: None,
+ selected_channels: false,
},
}
}
fn managed_agent() -> Self {
Self {
+ shares_channel_with: Vec::new(),
facts: BotFacts {
has_agent: true,
is_managed: true,
@@ -209,12 +213,35 @@ impl OneBotDirectory {
instructions: "persona instructions".to_owned(),
mcp_servers: Default::default(),
}),
+ selected_channels: false,
+ },
+ }
+ }
+
+ fn managed_selected_channel_agent() -> Self {
+ Self {
+ shares_channel_with: vec![STRANGER],
+ facts: BotFacts {
+ has_agent: true,
+ is_managed: true,
+ is_system: false,
+ owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ owner_team_id: None,
+ harness_id: None,
+ managed_profile: Some(crate::domain::ports::ManagedAgentProfile {
+ model: "persona-model".to_owned(),
+ harness: "in-memory".to_owned(),
+ instructions: "persona instructions".to_owned(),
+ mcp_servers: Default::default(),
+ }),
+ selected_channels: true,
},
}
}
fn plain_bot() -> Self {
Self {
+ shares_channel_with: Vec::new(),
facts: BotFacts {
has_agent: false,
is_managed: false,
@@ -223,6 +250,7 @@ impl OneBotDirectory {
owner_team_id: None,
harness_id: None,
managed_profile: None,
+ selected_channels: false,
},
}
}
@@ -231,6 +259,7 @@ impl OneBotDirectory {
/// nobody, and with no persisted profile of its own.
fn system_coder() -> Self {
Self {
+ shares_channel_with: Vec::new(),
facts: BotFacts {
has_agent: true,
is_managed: true,
@@ -239,6 +268,7 @@ impl OneBotDirectory {
owner_team_id: None,
harness_id: None,
managed_profile: None,
+ selected_channels: false,
},
}
}
@@ -256,6 +286,14 @@ impl BotDirectory for OneBotDirectory {
) -> crate::domain::error::Result<bool> {
Ok(false)
}
+
+ async fn user_shares_channel_with_bot(
+ &self,
+ user: MacroUserIdStr<'static>,
+ _bot_id: BotId,
+ ) -> crate::domain::error::Result<bool> {
+ Ok(self.shares_channel_with.contains(&user.as_ref()))
+ }
}
fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {
@@ -686,6 +724,31 @@ async fn a_stranger_cannot_select_someone_elses_managed_persona() {
assert!(opener.managed.lock().unwrap().is_empty());
}
+/// A selected-channel persona is mentionable in the channels it is installed
+/// in. A co-member who could `@` it there can start a managed session as it
+/// from the composer too.
+#[tokio::test]
+async fn a_channel_co_member_can_select_a_shared_managed_persona() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ STRANGER,
+ serde_json::json!({ "botId": BotId::TEST_A.as_uuid() }).to_string(),
+ );
+
+ let response = router_for(
+ opener.clone(),
+ OneBotDirectory::managed_selected_channel_agent(),
+ )
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let managed = opener.managed.lock().unwrap();
+ let selected = managed[0].profile.as_ref().expect("selected persona");
+ assert_eq!(selected.bot_id, BotId::TEST_A);
+}
+
/// Whitespace-only instructions are absence stated clumsily, and are
/// normalized away rather than stored as a section a runtime would splice in
/// empty.
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index 20d20e21a3..a23faec48d 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -34,7 +34,11 @@ pub trait BotRepo: Send + Sync + 'static {
req: UpdateAgentRequest,
) -> impl Future<Output = Result<Option<Agent>, Self::Err>> + Send;
- /// List active agents manageable by a caller.
+ /// List active agents the caller can manage or start a managed session as.
+ ///
+ /// Own and team-owned agents are included, plus selected-channel agents
+ /// installed in a channel the caller belongs to — the same personas they
+ /// can `@` mention there.
fn list_manageable_agents(
&self,
caller: MacroUserIdStr<'static>,
@@ -109,6 +113,13 @@ pub trait BotRepo: Send + Sync + 'static {
bot_id: BotId,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+ /// Whether the user and bot share at least one active channel.
+ fn user_shares_channel_with_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
/// Check whether a user is an administrator or owner of a team.
fn user_can_administer_team(
&self,
@@ -216,7 +227,7 @@ pub trait BotService: Send + Sync + 'static {
req: UpdateAgentRequest,
) -> impl Future<Output = Result<Agent, BotError>> + Send;
- /// List agents manageable by the caller.
+ /// List agents the caller can manage or start a managed session as.
fn list_agents(
&self,
caller: MacroUserIdStr<'static>,
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index faeeaf4ff2..b6ec9cdd20 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -603,6 +603,19 @@ impl BotRepo for PgBotsRepo {
OR b.team_id IN (
SELECT team_id FROM team_user WHERE user_id = $1
)
+ OR (
+ a.channel_scope = 'selected'
+ AND EXISTS (
+ SELECT 1
+ FROM comms_channel_participants bot_p
+ INNER JOIN comms_channel_participants user_p
+ ON user_p.channel_id = bot_p.channel_id
+ AND user_p.user_id = $1
+ AND user_p.left_at IS NULL
+ WHERE bot_p.user_id = 'bot|' || b.id::text
+ AND bot_p.left_at IS NULL
+ )
+ )
)
ORDER BY b.created_at ASC, b.id ASC
"#,
@@ -1044,6 +1057,34 @@ impl BotRepo for PgBotsRepo {
Ok(is_active)
}
+ async fn user_shares_channel_with_bot(
+ &self,
+ caller: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<bool, Self::Err> {
+ let shares = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1
+ FROM comms_channel_participants bot_p
+ INNER JOIN comms_channel_participants user_p
+ ON user_p.channel_id = bot_p.channel_id
+ AND user_p.user_id = $2
+ AND user_p.left_at IS NULL
+ WHERE bot_p.user_id = $1
+ AND bot_p.left_at IS NULL
+ ) AS "shares!"
+ "#,
+ principal_id(bot_id),
+ caller.as_ref(),
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check whether the user shares a channel with the bot")?;
+
+ Ok(shares)
+ }
+
async fn user_can_administer_team(
&self,
caller: MacroUserIdStr<'static>,
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index 4cd4e75924..0a4023ea83 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -508,6 +508,91 @@ async fn create_team_agent_requires_membership_not_admin(pool: PgPool) -> anyhow
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_member_can_list_a_team_agent_created_by_someone_else(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::new_v4();
+ insert_team_user(&pool, team_id, TEAM_ADMIN, "admin").await?;
+ insert_team_user(&pool, team_id, TEAM_MEMBER, "member").await?;
+ let service = service(&pool);
+ let mut create = create_agent_req("team-shared", AgentChannelScope::All);
+ create.team_id = Some(team_id);
+ let created = service.create_agent(user_id(TEAM_ADMIN), create).await?;
+
+ let listed = service.list_agents(user_id(TEAM_MEMBER)).await?;
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].bot.id, created.bot.id);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn channel_co_member_can_list_a_selected_agent_they_can_mention(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ insert_channel_member(&pool, channel_id, USER_OWNER).await?;
+ insert_user(&pool, USER_OTHER).await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)
+ VALUES ($1, $2, 'member'::comms_participant_role, NULL)
+ "#,
+ channel_id,
+ USER_OTHER,
+ )
+ .execute(&pool)
+ .await?;
+
+ let service = service(&pool);
+ let mut request = create_agent_req("shared-reviewer", AgentChannelScope::Selected);
+ request.channel_ids = vec![channel_id];
+ let created = service.create_agent(user_id(USER_OWNER), request).await?;
+
+ let listed = service.list_agents(user_id(USER_OTHER)).await?;
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0].bot.id, created.bot.id);
+ assert_eq!(listed[0].bot.handle, "shared-reviewer");
+
+ assert!(service.list_agents(user_id(TEAM_OTHER)).await?.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn all_channel_private_agent_is_not_listed_for_a_channel_co_member(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let channel_id = Uuid::new_v4();
+ insert_channel_member(&pool, channel_id, USER_OWNER).await?;
+ insert_user(&pool, USER_OTHER).await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role, left_at)
+ VALUES ($1, $2, 'member'::comms_participant_role, NULL)
+ "#,
+ channel_id,
+ USER_OTHER,
+ )
+ .execute(&pool)
+ .await?;
+
+ let service = service(&pool);
+ let created = service
+ .create_agent(
+ user_id(USER_OWNER),
+ create_agent_req("private-global", AgentChannelScope::All),
+ )
+ .await?;
+ // All-channel agents are not channel participants unless selected, so a
+ // co-member of some other channel still cannot list them.
+ assert!(service.list_agents(user_id(USER_OTHER)).await?.is_empty());
+ assert_eq!(
+ service.list_agents(user_id(USER_OWNER)).await?[0].bot.id,
+ created.bot.id
+ );
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn updated_agent_replaces_every_field_and_selected_channel(
pool: PgPool,
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index db93e1e849..2db7803922 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -49,7 +49,9 @@ An accent **Create agent** button stays fixed to the right of the strip.
It closes the session composer and opens the new-agent form at
`/app/settings/agents?createAgent=true`; it does not create a session.
Recents are remembered per user on this device. With no history, **Macro**
-`@macro` (the default) and **Cursor** `@cursor` lead, followed by saved agents.
+`@macro` (the default) and **Cursor** `@cursor` lead, followed by saved agents
+the caller can start: their own, team-shared personas, and selected-channel
+personas they can `@` mention.
Without a connected Cursor API key, Cursor is a **Connect Cursor** button:
clicking it closes the composer and opens Settings → Harness without creating
a session. It is keyboard-accessible; arrow navigation focuses it without
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index b965dca9f8..76c52cf1c9 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -353,10 +353,11 @@ export type ControlStatusDto = 'sent' | 'queued';
export type CreateAgentSessionRequest = {
/**
* Bot the session runs for. On a managed request this optionally selects
- * a persisted persona the user owns or may use through team membership;
- * omitting it uses the deployment's default coding persona. On an
- * external request, bot callers may omit it (their own identity is used)
- * and must not name another bot; user callers must supply a bot they own.
+ * a persisted persona the user owns, may use through team membership, or
+ * can `@` mention in a shared channel; omitting it uses the deployment's
+ * default coding persona. On an external request, bot callers may omit it
+ * (their own identity is used) and must not name another bot; user callers
+ * must supply a bot they own.
*/
botId?: string | null;
/**
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index ce354856a0..737595ee52 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -1408,7 +1408,7 @@
"botId": {
"type": ["string", "null"],
"format": "uuid",
- "description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns or may use through team membership;\nomitting it uses the deployment's default coding persona. On an\nexternal request, bot callers may omit it (their own identity is used)\nand must not name another bot; user callers must supply a bot they own."
+ "description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns, may use through team membership, or\ncan `@` mention in a shared channel; omitting it uses the deployment's\ndefault coding persona. On an external request, bot callers may omit it\n(their own identity is used) and must not name another bot; user callers\nmust supply a bot they own."
},
"instructions": {
"type": ["string", "null"],
diff --git a/services/agent_harness_service/src/bots_directory.rs b/services/agent_harness_service/src/bots_directory.rs
index 6de57b771c..aa7e6f570e 100644
--- a/services/agent_harness_service/src/bots_directory.rs
+++ b/services/agent_harness_service/src/bots_directory.rs
@@ -8,7 +8,7 @@ use agent_harness::domain::model::AgentKind;
use agent_session::domain::error::{AgentSessionError, Result};
use agent_session::domain::ports::{BotDirectory, BotFacts, ManagedAgentProfile};
use bot_id::BotId;
-use bots::domain::models::{BotKind, BotOwner};
+use bots::domain::models::{AgentChannelScope, BotKind, BotOwner};
use bots::domain::ports::BotRepo;
use bots::outbound::pg_bots_repo::PgBotsRepo;
use macro_user_id::user_id::MacroUserIdStr;
@@ -48,7 +48,7 @@ impl BotDirectory for PgBotDirectory {
Some(BotOwner::Team { team_id }) => (None, Some(team_id)),
None => (None, None),
};
- let (is_managed, harness_id, managed_profile) = if row.has_agent {
+ let (is_managed, harness_id, managed_profile, selected_channels) = if row.has_agent {
let agent = self
.repo
.get_agent(bot)
@@ -62,6 +62,9 @@ impl BotDirectory for PgBotDirectory {
|agent| AgentKind::from_harness(&agent.harness),
)
.is_managed();
+ let selected_channels = agent
+ .as_ref()
+ .is_some_and(|agent| agent.channel_scope == AgentChannelScope::Selected);
let managed_profile = agent
.filter(|_| is_managed)
.map(|agent| ManagedAgentProfile {
@@ -70,9 +73,9 @@ impl BotDirectory for PgBotDirectory {
instructions: agent.instructions,
mcp_servers: agent.mcp,
});
- (is_managed, harness_id, managed_profile)
+ (is_managed, harness_id, managed_profile, selected_channels)
} else {
- (false, None, None)
+ (false, None, None, false)
};
Ok(Some(BotFacts {
has_agent: row.has_agent,
@@ -82,6 +85,7 @@ impl BotDirectory for PgBotDirectory {
owner_team_id,
harness_id,
managed_profile,
+ selected_channels,
}))
}
@@ -95,4 +99,15 @@ impl BotDirectory for PgBotDirectory {
.await
.map_err(AgentSessionError::Unknown)
}
+
+ async fn user_shares_channel_with_bot(
+ &self,
+ user: MacroUserIdStr<'static>,
+ bot_id: BotId,
+ ) -> Result<bool> {
+ self.repo
+ .user_shares_channel_with_bot(user, bot_id)
+ .await
+ .map_err(AgentSessionError::Unknown)
+ }
}