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(forms): show inaccessible poll cards and share agent-posted polls with the channel (#9325)
Wolf Mermelstein2627122bef90
diff --git a/.sqlx/query-887a7fa028bd086a426d53040995846cb162a53df4a6053cf105869e3d15f0e6.json b/.sqlx/query-887a7fa028bd086a426d53040995846cb162a53df4a6053cf105869e3d15f0e6.jsonnew file mode 100644index 0000000000..f6b2ff6281--- /dev/null+++ b/.sqlx/query-887a7fa028bd086a426d53040995846cb162a53df4a6053cf105869e3d15f0e6.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT max(created_at) AS \"sent_at\"\n FROM comms_messages\n WHERE parent_entity_type = 'channel' AND parent_entity_id = $1\n AND sender_id = $2 AND created_at < $3 AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "sent_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Timestamptz"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "887a7fa028bd086a426d53040995846cb162a53df4a6053cf105869e3d15f0e6"+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.test.tsxindex 0f577c6a21..3587327f44 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.test.tsx@@ -45,6 +45,7 @@ const mocks = vi.hoisted(() => {disposed: 0,created: [] as string[],read: undefined as (() => void) | undefined,+ access: 'access' as 'access' | 'no_access' | 'does_not_exist',};});@@ -52,22 +53,25 @@ vi.mock('@core/component/ItemPreview', () => ({useItemPreviewData: () => ({item: () => {mocks.read?.();+ if (mocks.access !== 'access')+ return {+ id: 'form-1',+ type: 'form',+ loading: false,+ access: mocks.access,+ };return {id: 'form-1',name: 'Lunch?',type: 'form',loading: false,- access: 'view',+ access: 'access',};},ItemEntityIcon: () => null,documentProperties: () => undefined,}),}));-vi.mock('@queries/preview', async (importOriginal) => ({- ...(await importOriginal<typeof import('@queries/preview')>()),- isAccessiblePreviewItem: () => true,-}));vi.mock('@core/orchestrator', async (importOriginal) => ({...(await importOriginal<typeof import('@core/orchestrator')>()),createBlockInstance: (blockName: string, id: string) => {@@ -111,6 +115,46 @@ vi.mock('@ui', async (importOriginal) => {afterEach(() => {cleanup();mocks.read = undefined;+ mocks.access = 'access';+});++it('tells a channel member without access to a posted poll that they have no access, instead of an empty card', async () => {+ mocks.access = 'no_access';+ render(() => (+ <MarkdownHostContext.Provider value="channel">+ <DocumentCard+ key="node-1"+ documentId="form-1"+ documentName="Lunch?"+ blockName="form"+ blockParams={{}}+ previewData={{ poll: { optionCount: 2 } }}+ theme={{}}+ />+ </MarkdownHostContext.Provider>+ ));+ expect(+ await screen.findByText('You don’t have access to this poll')+ ).toBeTruthy();+ expect(mocks.created).not.toContain('form form-1');+});++it('says a deleted poll was deleted, instead of an empty card', async () => {+ mocks.access = 'does_not_exist';+ render(() => (+ <MarkdownHostContext.Provider value="channel">+ <DocumentCard+ key="node-1"+ documentId="form-1"+ documentName="Lunch?"+ blockName="form"+ blockParams={{}}+ previewData={{ poll: { optionCount: 2 } }}+ theme={{}}+ />+ </MarkdownHostContext.Provider>+ ));+ expect(await screen.findByText('This poll was deleted')).toBeTruthy();});it('mounts a form card’s body in a channel message, with no block and no editor around it, and disposes it with the card', async () => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsxindex d3c96e34ba..771c88d08c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx@@ -36,6 +36,7 @@ import {import {type AccessiblePreviewItem,isAccessiblePreviewItem,+ isPreviewItemNoAccess,} from '@queries/preview';import { blockNameToItemType } from '@service-storage/client';import { createCallback } from '@solid-primitives/rootless';@@ -434,6 +435,8 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {const pollHeight = () =>props.blockName === 'form' ? pollCardHeight(props.previewData) : undefined;const boundedPreview = () => resizable() || Boolean(pollHeight());+ const cardNoun = () =>+ pollHeight() ? 'poll' : props.blockName === 'form' ? 'form' : 'item';const [previewBoxHeight, setPreviewBoxHeight] = createSignal(stringifyPreviewBox(props.previewBox || DEFAULT_PREVIEW_BOX)[1]@@ -698,6 +701,18 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {</TaskPropertiesPreviewProvider>)}</Match>+ <Match when={matches(item(), isPreviewItemNoAccess)}>+ {(item) => (+ <div+ role="status"+ class="flex flex-1 items-center justify-center p-4 text-sm text-ink-muted"+ >+ {item().access === 'no_access'+ ? `You don’t have access to this ${cardNoun()}`+ : `This ${cardNoun()} was deleted`}+ </div>+ )}+ </Match></Switch></Card>);diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.mdindex 4effc609c8..72efde2fa5 100644--- a/crates/channels/AGENTS.md+++ b/crates/channels/AGENTS.md@@ -62,7 +62,9 @@ DMs, and the shared message store other domains discuss things on.person (`triggered_by`) shares, as that person, only the linked items thesending bot created for them while answering: `created` rows in`activity_events` by that bot on the person's behalf since the person's- latest message in the thread before the reply (`PgAgentCreations`). The same+ latest message in the thread before the reply, falling back to their+ latest message in the channel only when the bot message starts its own+ thread; a reply never falls back (`PgAgentCreations`). The samebound covers classic `@Macro` and agent session turns. Activity lands asynchronously, so misses arere-checked after 5 s and 30 s in a spawned task. Creations recorded underanother bot (`MACRO_AI_BOT_ID` for Claude/Codex/Cursor MCP tools) or thediff --git a/crates/channels/src/domain/message_delivery.rs b/crates/channels/src/domain/message_delivery.rsindex 98d8e1efed..51692fc3ad 100644--- a/crates/channels/src/domain/message_delivery.rs+++ b/crates/channels/src/domain/message_delivery.rs@@ -143,6 +143,21 @@ async fn recheck_agent_creations<C, P>();}+/// Where a bot message sits: the thread it starts, or the one it replies in.+#[derive(Clone, Copy, Debug)]+enum BotMessageThread {+ Starts(Uuid),+ RepliesIn(Uuid),+}++impl BotMessageThread {+ fn root(self) -> Uuid {+ match self {+ Self::Starts(root) | Self::RepliesIn(root) => root,+ }+ }+}+fn repo_error(error: impl Into<anyhow::Error>) -> rootcause::Report {rootcause::report!("channel message delivery failed: {}", error.into())}@@ -157,14 +172,16 @@ where{/// Share, as `person`, the linked items that `bot` created for them since/// their latest message in this thread before `replied_at`, the request- /// the reply answers. One bound covers classic bot replies and agent- /// session turns alike. Items without a creation record yet are+ /// the reply answers; a bot message that starts its own thread answers+ /// their latest message in the channel. One bound covers classic bot+ /// replies and agent session turns alike. Items without a creation record yet are/// re-checked in the background; the rest, including anything that/// existed before the request, stay unshared.#[tracing::instrument(skip(self, person, items),fields(items = items.len(),+ request = tracing::field::Empty,created = tracing::field::Empty,shared = tracing::field::Empty,not_permitted = tracing::field::Empty,@@ -176,18 +193,30 @@ wherebot: BotId,person: MacroUserIdStr<'static>,channel_id: Uuid,- thread_root: Uuid,+ thread: BotMessageThread,replied_at: DateTime<Utc>,items: Vec<ReferencedShareItem>,) -> anyhow::Result<()> {- let Some(requested_at) = self+ let in_thread = self.creations- .request_sent_at(thread_root, &person, replied_at)+ .request_sent_at(thread.root(), &person, replied_at).await- .map_err(Into::into)?- else {+ .map_err(Into::into)?;+ let request = match (in_thread, thread) {+ (Some(at), _) => Some((at, "thread")),+ (None, BotMessageThread::Starts(_)) => self+ .creations+ .channel_request_sent_at(channel_id, &person, replied_at)+ .await+ .map_err(Into::into)?+ .map(|at| (at, "channel")),+ (None, BotMessageThread::RepliesIn(_)) => None,+ };+ let Some((requested_at, source)) = request else {+ tracing::Span::current().record("request", "none");return Ok(());};+ tracing::Span::current().record("request", source);let created = self.creations.created_since(bot, &person, requested_at, items.clone())@@ -214,7 +243,7 @@ where"channels.recheck_agent_creations",%channel_id,%bot,- %thread_root,+ thread_root = %thread.root(),pending = pending_count,shared = tracing::field::Empty,not_permitted = tracing::field::Empty,@@ -322,7 +351,10 @@ wherebot.bot_id(),person,channel_id,- message.thread_id.unwrap_or(message.id),+ match message.thread_id {+ Some(root) => BotMessageThread::RepliesIn(root),+ None => BotMessageThread::Starts(message.id),+ },message.created_at,items,)diff --git a/crates/channels/src/domain/message_delivery/test.rs b/crates/channels/src/domain/message_delivery/test.rsindex 1e1b495e53..5d72ddcfe7 100644--- a/crates/channels/src/domain/message_delivery/test.rs+++ b/crates/channels/src/domain/message_delivery/test.rs@@ -73,10 +73,13 @@ impl ChannelReferenceSharePermissions for Log {}}-/// What bots created for MEMBER, who asked in the thread when `asked` is set.+/// What bots created for MEMBER, who asked in the thread when `asked` is set+/// and elsewhere in the channel when `asked_in_channel` is.#[derive(Clone, Default)]struct Creations {asked: bool,+ asked_in_channel: bool,+ channel_lookups: Arc<Mutex<usize>>,created: Arc<Mutex<Vec<(BotId, ReferencedShareItem)>>>,lookups: Arc<Mutex<usize>>,}@@ -89,14 +92,24 @@ impl AgentCreations for Creations {person: &MacroUserIdStr<'static>,_: DateTime<Utc>,) -> Result<Option<DateTime<Utc>>, Self::Err> {- assert_eq!(- thread_root,- Uuid::from_u128(1),+ assert!(+ [Uuid::from_u128(1), REPLIED_THREAD].contains(&thread_root),"the root message is the thread");assert_eq!(person.as_ref(), MEMBER);Ok(self.asked.then(Utc::now))}+ async fn channel_request_sent_at(+ &self,+ channel_id: Uuid,+ person: &MacroUserIdStr<'static>,+ _: DateTime<Utc>,+ ) -> Result<Option<DateTime<Utc>>, Self::Err> {+ assert_eq!(channel_id, CHANNEL);+ assert_eq!(person.as_ref(), MEMBER);+ *self.channel_lookups.lock().unwrap() += 1;+ Ok(self.asked_in_channel.then(Utc::now))+ }async fn created_since(&self,bot: BotId,@@ -114,6 +127,7 @@ impl AgentCreations for Creations {}const CHANNEL: Uuid = Uuid::from_u128(2);+const REPLIED_THREAD: Uuid = Uuid::from_u128(9);const MEMBER: &str = "macro|[email protected]";const SENDER: &str = "macro|[email protected]";const BOT: &str = "bot|00000000-0000-0000-0000-00000000b07a";@@ -594,6 +608,57 @@ async fn a_reply_to_no_request_from_the_person_shares_nothing() {assert_eq!(*creations.lookups.lock().unwrap(), 0);}+#[tokio::test(start_paused = true)]+async fn a_top_level_agent_post_answers_the_persons_latest_channel_message() {+ let log = Log::default();+ let creations = Creations {+ asked: false,+ asked_in_channel: true,+ ..asked_and(BotId::TEST_A, vec![document(DOCUMENT)])+ };+ let delivery = ChannelMessageDelivery::new(+ repo(),+ log.clone(),+ log.clone(),+ log.clone(),+ creations.clone(),+ );++ let _ = delivery.publish(agent_post(Some(MEMBER))).await;++ assert_eq!(+ *log.shares.lock().unwrap(),+ [(MEMBER.to_owned(), vec![DOCUMENT.to_string()])]+ );+}++#[tokio::test(start_paused = true)]+async fn an_agent_reply_in_a_thread_the_person_never_wrote_in_shares_nothing() {+ let log = Log::default();+ let creations = Creations {+ asked: false,+ asked_in_channel: true,+ ..asked_and(BotId::TEST_A, vec![document(DOCUMENT)])+ };+ let delivery = ChannelMessageDelivery::new(+ repo(),+ log.clone(),+ log.clone(),+ log.clone(),+ creations.clone(),+ );+ let mut reply = agent_post(Some(MEMBER));+ if let MessageChange::Posted { message, .. } = &mut reply.change {+ message.thread_id = Some(REPLIED_THREAD);+ }++ delivery.publish(reply).await.unwrap();+ tokio::time::sleep(Duration::from_secs(60)).await;++ assert!(log.shares.lock().unwrap().is_empty());+ assert_eq!(*creations.channel_lookups.lock().unwrap(), 0);+}+#[tokio::test(start_paused = true)]async fn an_agent_post_for_nobody_shares_nothing() {let log = Log::default();diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rsindex c533de0ff8..bda1c4445d 100644--- a/crates/channels/src/domain/ports.rs+++ b/crates/channels/src/domain/ports.rs@@ -979,6 +979,15 @@ pub trait AgentCreations: Clone + Send + Sync + 'static {before: DateTime<Utc>,) -> impl Future<Output = Result<Option<DateTime<Utc>>, Self::Err>> + Send;+ /// When `person` last wrote anywhere in `channel_id` before `before`: the+ /// request a bot message that starts its own thread is answering.+ fn channel_request_sent_at(+ &self,+ channel_id: Uuid,+ person: &MacroUserIdStr<'static>,+ before: DateTime<Utc>,+ ) -> impl Future<Output = Result<Option<DateTime<Utc>>, Self::Err>> + Send;+/// The `items` that `bot` recorded creating on `person`'s behalf at or after `since`.fn created_since(&self,diff --git a/crates/channels/src/outbound/pg_agent_creations.rs b/crates/channels/src/outbound/pg_agent_creations.rsindex b2c3af4f3f..5641da3dc1 100644--- a/crates/channels/src/outbound/pg_agent_creations.rs+++ b/crates/channels/src/outbound/pg_agent_creations.rs@@ -57,6 +57,29 @@ impl AgentCreations for PgAgentCreations {.await}+ #[tracing::instrument(skip(self, person), err)]+ async fn channel_request_sent_at(+ &self,+ channel_id: Uuid,+ person: &MacroUserIdStr<'static>,+ before: DateTime<Utc>,+ ) -> Result<Option<DateTime<Utc>>, Self::Err> {+ // The parent timeline index, filtered to the person.+ sqlx::query_scalar!(+ r#"+ SELECT max(created_at) AS "sent_at"+ FROM comms_messages+ WHERE parent_entity_type = 'channel' AND parent_entity_id = $1+ AND sender_id = $2 AND created_at < $3 AND deleted_at IS NULL+ "#,+ channel_id.to_string(),+ person.as_ref(),+ before,+ )+ .fetch_one(&self.pool)+ .await+ }+#[tracing::instrument(skip(self, person, items), fields(items = items.len()), err)]async fn created_since(&self,diff --git a/crates/channels/src/outbound/pg_agent_creations/test.rs b/crates/channels/src/outbound/pg_agent_creations/test.rsindex bfd390b87a..bef1fc4f27 100644--- a/crates/channels/src/outbound/pg_agent_creations/test.rs+++ b/crates/channels/src/outbound/pg_agent_creations/test.rs@@ -3,6 +3,7 @@ use crate::domain::models::ReferencedShareItemType;use chrono::{Duration, SubsecRound};use macro_db_migrator::MACRO_DB_MIGRATIONS;+const CHANNEL: Uuid = Uuid::from_u128(100);const THREAD_ROOT: Uuid = Uuid::from_u128(1);const REPLYING_BOT: BotId = BotId::TEST_A;const OTHER_BOT: BotId = BotId::TEST_B;@@ -14,16 +15,29 @@ fn person() -> MacroUserIdStr<'static> {}async fn post(pool: &PgPool, id: Uuid, thread_id: Option<Uuid>, sender: &str, at: DateTime<Utc>) {+ sqlx::query!(+ r#"+ INSERT INTO comms_channels (id, channel_type, owner_id)+ VALUES ($1, 'private', $2)+ ON CONFLICT DO NOTHING+ "#,+ CHANNEL,+ PERSON,+ )+ .execute(pool)+ .await+ .unwrap();sqlx::query!(r#"INSERT INTO comms_messages(id, thread_id, sender_id, content, parent_entity_type, parent_entity_id, created_at)- VALUES ($1, $2, $3, 'message', 'document', 'parent', $4)+ VALUES ($1, $2, $3, 'message', 'channel', $5, $4)"#,id,thread_id,sender,at,+ CHANNEL.to_string(),).execute(pool).await@@ -115,6 +129,46 @@ async fn the_request_is_the_persons_latest_message_in_the_thread_before_the_repl);}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_channel_request_is_the_persons_latest_message_anywhere_in_the_channel(pool: PgPool) {+ let asked_at = Utc::now() - Duration::minutes(5);+ let posted_at = asked_at + Duration::minutes(2);+ post(+ &pool,+ THREAD_ROOT,+ None,+ PERSON,+ asked_at - Duration::hours(1),+ )+ .await;+ post(&pool, Uuid::from_u128(2), None, PERSON, asked_at).await;+ post(+ &pool,+ Uuid::from_u128(3),+ None,+ SOMEONE_ELSE,+ asked_at + Duration::minutes(1),+ )+ .await;+ let bot_post = Uuid::from_u128(4);+ post(+ &pool,+ bot_post,+ None,+ "bot|00000000-0000-0000-0000-00000000a2a2",+ posted_at,+ )+ .await;++ assert_eq!(+ PgAgentCreations::new(pool)+ .channel_request_sent_at(CHANNEL, &person(), posted_at)+ .await+ .unwrap(),+ Some(asked_at.trunc_subsecs(6))+ );+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn only_what_the_replying_bot_created_for_the_person_since_the_request_counts(pool: PgPool) {let requested_at = Utc::now() - Duration::minutes(5);diff --git a/crates/forms/AGENTS.md b/crates/forms/AGENTS.mdindex b288141f03..3279e9afe9 100644--- a/crates/forms/AGENTS.md+++ b/crates/forms/AGENTS.md@@ -46,6 +46,12 @@ service.- `cargo test -p forms --all-features` (`SQLX_OFFLINE` unset).+## Gotchas++- `POST /forms` attributes the creation to the SDK token's `agent_id` (code+ mode), like the native tool, so channel delivery shares a poll an agent+ posts; access checks still run as the plain user.+## Related- Skills: `collab-surface-core`, `database-core` · Rules: `.agents/rules/rust/architecture.md`diff --git a/crates/forms/Cargo.toml b/crates/forms/Cargo.tomlindex 9f3548f584..2fb631f2f0 100644--- a/crates/forms/Cargo.toml+++ b/crates/forms/Cargo.toml@@ -74,6 +74,7 @@ uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+bot_id = { path = "../bot_id", features = ["test-utils"] }entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }macro_db_migrator = { path = "../macro_db_migrator" }models_properties = { path = "../models_properties" }diff --git a/crates/forms/src/inbound/axum_router/forms.rs b/crates/forms/src/inbound/axum_router/forms.rsindex de8c8c054f..b04c4e56ad 100644--- a/crates/forms/src/inbound/axum_router/forms.rs+++ b/crates/forms/src/inbound/axum_router/forms.rs@@ -3,6 +3,7 @@use axum::Json;use axum::extract::{Query, State};use axum::http::StatusCode;+use databases::domain::models::Viewer;use databases::domain::receipt::database_receipt;use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};use entity_access::domain::ports::EntityAccessService;@@ -37,7 +38,7 @@ pub struct ListFormsQuery {responses((status = 201, body = FormDetail), (status = 400, body = FormErrorResponse),(status = 401, body = FormErrorResponse), (status = 403, body = FormErrorResponse),(status = 404, body = FormErrorResponse), (status = 500, body = FormErrorResponse)))]-#[tracing::instrument(err, skip_all)]+#[tracing::instrument(err, skip_all, fields(acting_bot = tracing::field::Empty))]pub async fn create_form_handler<Service, EntityAccess, Authorization>(State(state): State<FormsRouterState<Service, EntityAccess, Authorization>>,user: SignedIn<Authorization>,@@ -49,6 +50,20 @@ whereAuthorization: MacroAuthorizationService,{let creator = viewer_of(&user);+ // An agent's SDK token (code mode) creates as its user, attributed to the+ // agent like the native tool's creations, so channel delivery can share+ // what it made for the request.+ let acting_bot = user.user.authorization.user.agent_id;+ tracing::Span::current().record(+ "acting_bot",+ tracing::field::display(+ acting_bot.map_or_else(|| "none".to_owned(), |bot| bot.to_string()),+ ),+ );+ let attributed_creator = Viewer {+ acting_bot,+ ..creator.clone()+ };let source = match request.source {FormSource::New { is_hidden_in_drive } => CreateSource::NewDatabase { is_hidden_in_drive },FormSource::Table {@@ -67,7 +82,7 @@ wherelet detail = state.service.create_form(- creator,+ attributed_creator,CreateFormCommand {name: request.name,source,diff --git a/crates/forms/src/inbound/axum_router/test.rs b/crates/forms/src/inbound/axum_router/test.rsindex 77625482aa..951781d226 100644--- a/crates/forms/src/inbound/axum_router/test.rs+++ b/crates/forms/src/inbound/axum_router/test.rs@@ -306,6 +306,20 @@ async fn an_owner_reaches_every_route_with_their_own_receipt() {));}+#[tokio::test]+async fn a_form_an_agent_creates_with_its_sdk_token_is_attributed_to_the_agent() {+ let body = json!({ "name": "Lunch?", "source": { "kind": "new" } });+ for (token, bot) in [("agent", Some(AGENT)), ("owner", None)] {+ let (router, service) = router(Grants::default());+ let created = router+ .oneshot(request(Method::POST, "/", Some(token), Some(body.clone())))+ .await+ .unwrap();+ assert_eq!(created.status(), StatusCode::CREATED, "{token}");+ assert_eq!(*service.creating_bots.lock().unwrap(), vec![bot], "{token}");+ }+}+#[tokio::test]async fn creating_over_a_table_needs_owner_on_its_database() {let body = json!({diff --git a/crates/forms/src/inbound/axum_router/test/fakes.rs b/crates/forms/src/inbound/axum_router/test/fakes.rsindex dddd82c11f..c928c6bd6a 100644--- a/crates/forms/src/inbound/axum_router/test/fakes.rs+++ b/crates/forms/src/inbound/axum_router/test/fakes.rs@@ -33,10 +33,12 @@ use crate::inbound::axum_router::{FormsRouterState, forms_router};pub(super) const OWNER: &str = "macro|[email protected]";pub(super) const RESPONDENT: &str = "macro|[email protected]";+pub(super) const AGENT: bot_id::BotId = bot_id::BotId::TEST_A;pub(super) const FORM: FormId = FormId::from_uuid(Uuid::from_u128(0xf0));pub(super) const ROW: RowId = RowId::from_uuid(Uuid::from_u128(0x40));-/// Accepts the bearer tokens `owner` and `respondent`.+/// Accepts the bearer tokens `owner` and `respondent`, and `agent`: the+/// owner's SDK token carrying [`AGENT`]'s attribution, as code mode mints.#[derive(Clone, Copy)]pub(super) struct Tokens;@@ -45,15 +47,16 @@ impl JwtValidator for Tokens {&self,jwt: &str,) -> Result<macro_authorization::ValidatedCredential, Report<MacroAuthorizationError>> {- let user_id = match jwt {- "owner" => OWNER,- "respondent" => RESPONDENT,+ let (user_id, agent_id) = match jwt {+ "owner" => (OWNER, None),+ "respondent" => (RESPONDENT, None),+ "agent" => (OWNER, Some(AGENT)),_ => return Err(Report::new(MacroAuthorizationError::InvalidCredentials)),};Ok(macro_authorization::ValidatedCredential {- origin: macro_authorization::CredentialOrigin::Session,+ origin: macro_authorization::CredentialOrigin::MacroApiJwt,identity: ValidatedIdentity {- agent_id: None,+ agent_id,user_id: user_id.to_string(),fusion_user_id: format!("fusion-{jwt}"),organization_id: None,@@ -232,6 +235,7 @@ fn handed<Level: RequiredPermission>(pub(super) struct RecordingForms {pub(super) handed: Mutex<Vec<Handed>>,pub(super) refusal: Mutex<Option<FormError>>,+ pub(super) creating_bots: Mutex<Vec<Option<bot_id::BotId>>>,}pub(super) fn form() -> Form {@@ -296,6 +300,7 @@ impl FormsService for RecordingForms {creator: databases::domain::models::Viewer,command: CreateFormCommand,) -> Result<FormDetail, FormError> {+ self.creating_bots.lock().unwrap().push(creator.acting_bot);let entity_id = match &command.source {crate::domain::ports::CreateSource::NewDatabase { .. } => String::new(),crate::domain::ports::CreateSource::Table { receipt, .. } => {diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex d6f7cf3cc9..8ace6c91d1 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -485,7 +485,9 @@ event is created — no invitation goes out from the initial request. It cannotemail at all. A bot or agent reply posted for a person shares, as that person, the linked items(chips or attachments) that the replying bot created for them while answering: those with a`created` activity row by that bot on the person's behalf since the person's latest message in-the thread before the reply. Activity arrives asynchronously, so missing rows are re-checked+the thread before the reply, or, for a bot message that starts its own thread (a poll card+posted top-level), their latest message in the channel. Forms an agent creates through code+mode (its SDK token) are attributed to its bot like native tool creations. Activity arrives asynchronously, so missing rows are re-checkedafter 5 and 30 seconds. Existing items it links, plain URLs, and bot posts with no personbehind them share nothing. The bot never asks whether to share; it calls `ShareWithChannel` when asked toshare an existing item. Private and confidential calendar events stay unshared, and adiff --git a/docs/agent-guide/forms.md b/docs/agent-guide/forms.mdindex 28058cc59c..2d5c9399fc 100644--- a/docs/agent-guide/forms.md+++ b/docs/agent-guide/forms.md@@ -222,7 +222,9 @@ once, in the card header. Newly posted poll cardsstore their option count in Lexical preview metadata to reserve their heightbefore loading. Choices have fixed-height rows; large polls and expandedresults scroll inside the card. Older cards without that metadata keep their-content-sized layout.+content-sized layout. A viewer without access to the card's item sees "You+don’t have access to this poll" (or form/item), and a deleted item reads "This+poll was deleted", never an empty card.## Reading responses as an agent