Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat: agents can @ mention (#6114)

Wolf Mermelstein2bdb1e351cbc
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index ab361eb012..d0894108cd 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -42,7 +42,7 @@ export function AgentComposer() {
onRemove={composer.remove}
/>
<AgentInput
- placeholder="Message the agent"
+ placeholder="Message the agent, @mention anything"
autofocus={autofocus}
busy={composer.busy()}
disabled={loadFailed()}
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 31b9c530da..10a38ebe23 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -28,7 +28,9 @@ function AgentMessagePart(props: {
inFlight: boolean;
}): JSX.Element {
return match(props.part)
- .with({ kind: 'text' }, (part) => <TextPart text={part.text} />)
+ .with({ kind: 'text' }, (part) => (
+ <TextPart text={part.text} inFlight={props.inFlight} />
+ ))
.with({ kind: 'thought' }, (part) => (
<Thought text={part.text} active={props.inFlight} />
))
diff --git a/apps/web/src/features/block-agent/component/parts/TextPart.tsx b/apps/web/src/features/block-agent/component/parts/TextPart.tsx
index 80ba92af23..219197f6ab 100644
--- a/apps/web/src/features/block-agent/component/parts/TextPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/TextPart.tsx
@@ -2,12 +2,16 @@
import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { channelTheme } from '@core/component/LexicalMarkdown/theme';
+import { hideIncompleteMacroXml } from './hideIncompleteMacroXml';
+
+export function TextPart(props: { text: string; inFlight?: boolean }) {
+ const markdown = () =>
+ props.inFlight ? hideIncompleteMacroXml(props.text) : props.text;
-export function TextPart(props: { text: string }) {
return (
<div class="whitespace-pre-wrap wrap-break-word max-w-full text-sm">
<StaticMarkdown
- markdown={props.text}
+ markdown={markdown()}
theme={channelTheme}
target="internal"
/>
diff --git a/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts
new file mode 100644
index 0000000000..c00755e5fb
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { hideIncompleteMacroXml } from './hideIncompleteMacroXml';
+
+describe('hideIncompleteMacroXml', () => {
+ const complete =
+ '<m-document-mention>{"documentId":"abc","documentName":"","blockName":"md","blockParams":{}}</m-document-mention>';
+
+ it('leaves complete mention tags intact', () => {
+ expect(hideIncompleteMacroXml(`See ${complete}.`)).toBe(`See ${complete}.`);
+ });
+
+ it('strips a trailing unclosed mention tag', () => {
+ expect(
+ hideIncompleteMacroXml(`See ${complete.slice(0, complete.indexOf('{'))}`)
+ ).toBe('See ');
+ });
+
+ it('strips a trailing bare open prefix', () => {
+ expect(hideIncompleteMacroXml('See <m-document-ment')).toBe('See ');
+ });
+
+ it('leaves text with no mention markup alone', () => {
+ expect(hideIncompleteMacroXml('plain reply')).toBe('plain reply');
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts
new file mode 100644
index 0000000000..7073b27160
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/hideIncompleteMacroXml.ts
@@ -0,0 +1,13 @@
+/**
+ * Hide a trailing unclosed Macro mention tag so streaming text does not
+ * flash raw `<m-document-mention>` XML. Complete tags stay intact.
+ */
+export function hideIncompleteMacroXml(text: string): string {
+ const open = text.lastIndexOf('<m-');
+ if (open === -1) return text;
+ const after = text.slice(open);
+ if (/^<m-[a-zA-Z0-9_-]+>[\s\S]*<\/m-[a-zA-Z0-9_-]+>/.test(after)) {
+ return text;
+ }
+ return text.slice(0, open);
+}
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index d49a7869b3..081dc0ed94 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -1,9 +1,10 @@
/**
* The agent block's composer: the chat input's look and its markdown editing
- * surface (`MarkdownShell` over a lean `EditorConfigBuilder`), without the
- * rest of `ChatInput`'s machinery — no mentions, attachments, upload queue,
- * or contexts; model plumbing arrives through the `modelControl` slot. Visual
- * chrome mirrors `@core/component/AI/component/input/ChatInput.tsx`.
+ * surface (`MarkdownShell` over a lean `EditorConfigBuilder`), including `@`
+ * mentions so users can attach Macro items the same way they do in chat.
+ * Attachments, upload queue, and chat contexts stay out; model plumbing
+ * arrives through the `modelControl` slot. Visual chrome mirrors
+ * `@core/component/AI/component/input/ChatInput.tsx`.
*/
import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
@@ -27,7 +28,7 @@ export interface AgentInputProps {
* typing `/` opens a typeahead over them. `/` stays plain text while empty.
*/
commands?: () => AgentCommandItem[];
- /** Receives the composed markdown. */
+ /** Receives the composed markdown, including any `<m-document-mention>` tags. */
onSend: (markdown: string) => void;
onStop?: () => void;
/** Sits as a pill above the input box, e.g. the session's model selector. */
@@ -68,6 +69,10 @@ export function AgentInput(props: AgentInputProps) {
const editor = buildConfig('chat')
.namespace('agent-input')
+ .withMentions({
+ showOpenTabs: true,
+ block: 'agent',
+ })
.withEmojis()
.withLinks({ floatingMenu: true, autoLinkMatchMode: 'common-tlds' })
.withHistory({ timeGap: 400 })
@@ -118,7 +123,9 @@ export function AgentInput(props: AgentInputProps) {
>
<MarkdownShell
config={editor}
- placeholder={props.placeholder ?? 'Message the agent'}
+ placeholder={
+ props.placeholder ?? 'Message the agent, @mention anything'
+ }
autofocus={props.autofocus}
/>
</div>
diff --git a/crates/agent_inmem/src/outbound/rig_engine.rs b/crates/agent_inmem/src/outbound/rig_engine.rs
index 53b4fff7a2..acceae2acc 100644
--- a/crates/agent_inmem/src/outbound/rig_engine.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine.rs
@@ -3,9 +3,9 @@
//!
//! Consumption mirrors the scheduled-action executor
//! (`services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs`):
-//! the full static toolset, the tool-use system prompt plus the agent-session
-//! preamble and the owner's memory, and usage recorded per turn against the
-//! session owner.
+//! the full static toolset, the agent-session preamble, the static Macro
+//! prompt (immediately before any session instructions), and the owner's
+//! memory, with usage recorded per turn against the session owner.
//!
//! This is also where a session's own instructions become a system prompt.
//! Nothing has to be transported for it - the loop runs in this process - which
@@ -126,20 +126,21 @@ async fn drive_turn(
result
}
-/// The turn's system prompt: the toolset's, the agent-session preamble, then
-/// the session's own instructions and the owner's memory when there are any.
+/// The turn's system prompt: the agent-session preamble, the static Macro
+/// prompt (how to use the product: mentions, tools, terminology), then the
+/// session's own instructions and the owner's memory when there are any.
///
-/// Instructions land after the preamble and before the memory block for the
-/// same reason DCS puts `additional_instructions` there - they are the
-/// caller's word on how this session works, so they qualify the standing
-/// prompt rather than being qualified by it, and memory stays last so a
-/// remembered fact is never read as an instruction.
+/// The static Macro prompt sits immediately before `<session_instructions>`
+/// so it is the preamble the model reads as it takes in the caller's word —
+/// the same reason DCS puts `additional_instructions` after the standing
+/// prompt. Memory stays last so a remembered fact is never read as an
+/// instruction.
fn system_prompt(
tools_prompt: &impl std::fmt::Display,
instructions: Option<&str>,
user_memory: Option<&str>,
) -> String {
- let mut prompt = format!("{}\n{}", tools_prompt, prompt::agent_session::PROMPT);
+ let mut prompt = format!("{}\n{}", prompt::agent_session::PROMPT, tools_prompt);
// Blank instructions are "none" stated clumsily. A delimited section with
// nothing in it is worse than no section: the model has to decide what an
// empty instruction means.
diff --git a/crates/agent_inmem/src/outbound/rig_engine/test.rs b/crates/agent_inmem/src/outbound/rig_engine/test.rs
index 38f03c07da..d32d525d7f 100644
--- a/crates/agent_inmem/src/outbound/rig_engine/test.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine/test.rs
@@ -8,8 +8,14 @@ fn instructions_are_a_delimited_section_after_the_standing_prompt() {
let prompt = system_prompt(&TOOLS, Some("be terse"), None);
assert!(
- prompt.starts_with(&format!("{TOOLS}\n{}", prompt::agent_session::PROMPT)),
- "the standing prompt comes first, unchanged"
+ prompt.starts_with(&prompt::agent_session::PROMPT.to_string()),
+ "the session preamble comes first"
+ );
+ assert!(
+ prompt.contains(&format!(
+ "{TOOLS}\n<session_instructions>\nbe terse\n</session_instructions>"
+ )),
+ "the static Macro prompt sits immediately before session instructions"
);
assert!(prompt.ends_with("\n<session_instructions>\nbe terse\n</session_instructions>"));
}
diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rs
index 993a606cb3..619d080453 100644
--- a/crates/prompt/src/agent_session.rs
+++ b/crates/prompt/src/agent_session.rs
@@ -4,17 +4,19 @@ use crate::types::StaticPrompt;
static TITLE: &str = "Agent Sessions";
-static INSTRUCTIONS: &str = r##"You are Macro's agent, working inside an agent session that was opened from a channel mention. Your replies stream back into that channel thread.
+static INSTRUCTIONS: &str = r##"You are Macro's agent, working inside an agent session that was opened from a channel mention. Your replies stream back into that channel thread and also render in the session itself.
- Each prompt is a message from a user in the thread. Answer it directly; use your tools to look things up or act in the workspace when that is what the request needs.
- Be concise and directly useful. Respond in Markdown.
+- When you reference a Macro document, channel, chat, project, task, email thread, or calendar event, emit an XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.
- You have no shell and no filesystem. Everything you can do, you do through the tools you are given.
- Work autonomously: nobody can approve intermediate questions mid-turn, so make reasonable assumptions, state them briefly, and proceed.
"##;
static INTENT: &str = "The model behaves as a fast product assistant inside an agent session: \
-answers the prompt directly, uses Macro tools rather than expecting a shell, and does not \
-stall on questions nobody can answer mid-turn.";
+answers the prompt directly, cites Macro items with mention tags so they render as chips, \
+uses Macro tools rather than expecting a shell, and does not stall on questions nobody \
+can answer mid-turn.";
/// The agent-session preamble for the in-process Macro agent.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index a3f075d67f..9a394ab3f5 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -160,13 +160,25 @@ mod tests {
assert!(document_content_links::PROMPT.instructions.contains(TAG));
}
+ #[test]
+ fn agent_session_preamble_tells_the_model_to_emit_mention_tags() {
+ let preamble = agent_session::PROMPT.to_string();
+ assert!(preamble.contains("XML mention tag"));
+ assert!(preamble.contains("clickable chips"));
+ }
+
#[test]
fn markdown_surface_scope_names_every_surface_but_the_reply_tone_exception() {
// The mention rule must name every Markdown-authoring surface and the
// non-Markdown-document exception, and the tool-use tone rule must not
// silently bleed into tool-authored content.
let in_app = TOOL_USE_PROMPT.to_string();
- for surface in ["SendChannelMessage", "SendEmail", "CreateDocument"] {
+ for surface in [
+ "SendChannelMessage",
+ "SendEmail",
+ "CreateDocument",
+ "agent session",
+ ] {
assert!(
in_app.contains(surface),
"markdown surface scope should name {surface}"
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index 9f5f464a26..a101241676 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -2,8 +2,9 @@
//! Macro's shared Markdown rendering.
//!
//! These rules apply everywhere the model authors Markdown in Macro: its own
-//! conversational replies, `SendChannelMessage` content, `SendEmail` bodies,
-//! and `CreateDocument`/`EditDocument` content for Markdown (`.md`) documents.
+//! conversational replies (AI chat and agent session transcripts),
+//! `SendChannelMessage` content, `SendEmail` bodies, and
+//! `CreateDocument`/`EditDocument` content for Markdown (`.md`) documents.
//! The one exclusion is non-Markdown documents created via `CreateDocument`
//! (e.g. PDF, CSV, PNG, XLSX, DOCX) — those are stored as raw file bytes and
//! never parsed as Markdown, so they take no Markdown syntax or mention tags.
@@ -17,7 +18,7 @@ use crate::types::StaticPrompt;
static TITLE: &str = "Mentioning documents, channels, channel messages, chats, projects, email threads, and calendar events";
-static INSTRUCTIONS: &str = r##"These rules apply everywhere you author Markdown in Macro: your own conversational replies, `SendChannelMessage` content, `SendEmail` bodies, and `CreateDocument`/`EditDocument` content for Markdown (`.md`) documents. They do NOT apply to non-Markdown documents created via `CreateDocument` (e.g. PDF, CSV, PNG, XLSX, DOCX) — those are raw file bytes, never parsed as Markdown, and must never contain mention tags or Markdown syntax.
+static INSTRUCTIONS: &str = r##"These rules apply everywhere you author Markdown in Macro: your own conversational replies (AI chat and agent session transcripts), `SendChannelMessage` content, `SendEmail` bodies, and `CreateDocument`/`EditDocument` content for Markdown (`.md`) documents. They do NOT apply to non-Markdown documents created via `CreateDocument` (e.g. PDF, CSV, PNG, XLSX, DOCX) — those are raw file bytes, never parsed as Markdown, and must never contain mention tags or Markdown syntax.
When referencing a document, channel, chat, project, email thread, or calendar event, use XML mention tags with a JSON payload.
The AI does not need to know the name — an empty string is fine and the frontend will resolve it.
@@ -46,8 +47,8 @@ static INTENT: &str = "Entities and channel messages are referenced with correct
<m-document-mention> XML tags using the right blockName and blockParams for each entity type, \
including exactly \"email\" for email threads, exactly \"calendar\" for calendar events, and \
channel_message_id for specific channel messages, \
-across every Markdown surface (replies, channel messages, email bodies, and Markdown documents) — \
-never inside non-Markdown documents.";
+across every Markdown surface (AI chat replies, agent session replies, channel messages, \
+email bodies, and Markdown documents) — never inside non-Markdown documents.";
/// The entity-mention prompt.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 26193210ee..65239d61fa 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -41,4 +41,14 @@ stream over the app's websocket, not the HTTP response.
## In channels
-Mention `@Macro` in any channel message to invoke the agent there.
+Mention `@Macro` in any channel message for the classic in-channel reply. Mention
+`@macro-new` (or `@coder` / `@cursor`) to open an **agent session** — a dedicated
+transcript at `/app/agent/<uuid>` whose replies also stream back into the thread.
+
+## Agent sessions
+
+An agent session is `/app/agent/<uuid>`. The composer placeholder is
+**`Message the agent, @mention anything`**. Type `@` to insert the same mention chips
+used in chat and channels; they serialize as `<m-document-mention>` tags in the prompt
+the agent sees. Agent replies that emit those tags render as clickable chips in the
+transcript (and in the originating channel thread).
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 31ca177d9e..7bc98c6bfa 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -31,6 +31,11 @@ message; ordinary Markdown blockquotes remain presentation-only and do not count
The composer always keeps an editable empty line after a block reference, including after
the user deletes that line, so clicking below the reference can restore the text caret.
+`@Macro` answers in the thread (classic bot). `@macro-new` / `@coder` / `@cursor` open
+an agent session; follow-up `@` mentions of that bot in the same thread route to it.
+Agent replies may contain mention chips (`<m-document-mention>`) that render like any
+other channel mention.
+
## Channel tabs
Radio group at the top of the channel pane: `Messages` / `Attachments` / `Participants`,
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.md
index 35dbaeb8a4..47c4d6f9a6 100644
--- a/docs/AGENT_GUIDE/navigation.md
+++ b/docs/AGENT_GUIDE/navigation.md
@@ -19,6 +19,7 @@
| `/app/calendar/view` | Calendar |
| `/app/md/<uuid>` | A document |
| `/app/chat/<uuid>` | A standalone AI chat |
+| `/app/agent/<uuid>` | An agent session (opened from `@macro-new` / `@coder` / `@cursor`) |
| `/app/md/<doc>/chat/<chat>` | Doc + doc-scoped chat in a split |
| `/app/md/<doc>/channel/<channel>` | Doc + channel in a split |
| `/app/settings/account` | Settings (also `/app/settings/api-keys`, `/mcp-server`, `/shortcuts`, etc.) |