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(routines): link created routines in agent replies (#8568)

Eric Hayesa72ebc461863
diff --git a/apps/docs/AI/mcp/tools/create-routine.mdx b/apps/docs/AI/mcp/tools/create-routine.mdx
index 11b44c8d4c..62457dc889 100644
--- a/apps/docs/AI/mcp/tools/create-routine.mdx
+++ b/apps/docs/AI/mcp/tools/create-routine.mdx
@@ -6,7 +6,7 @@ description: >-
# CreateRoutine
-Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.
+Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.
## Parameters
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 551ad78140..4fee015c56 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -428,6 +428,8 @@ Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` when using the Nix Chrome binary.
### Agent backend hosting
Cognition, routines, preview control, and MCP share `agent_harness_service`.
+Agent replies can use the existing `m-document-mention` format with
+`blockName: "routine"`; routines do not appear in the mention menu.
Direct local hosts use port 8101 with the existing feature prefixes; the
instance proxy retains `/cognition`, `/scheduled-action`, and `/preview`.
diff --git a/apps/web/src/features/routines/components/routine-editor.tsx b/apps/web/src/features/routines/components/routine-editor.tsx
index f84655d133..0ac2ddf8f8 100644
--- a/apps/web/src/features/routines/components/routine-editor.tsx
+++ b/apps/web/src/features/routines/components/routine-editor.tsx
@@ -23,6 +23,7 @@ export function RoutineEditor(props: {
triggerContent?: JSX.Element;
nextRun: string;
history: JSX.Element;
+ showHistory?: boolean;
actions?: JSX.Element;
feedback?: JSX.Element;
}) {
@@ -82,10 +83,14 @@ export function RoutineEditor(props: {
<TabSelector class="w-fit">
<TabSelector.List aria-label="Routine details">
<For
- each={[
- { value: 'settings', label: 'Overview' },
- { value: 'history', label: 'Run History' },
- ]}
+ each={
+ props.showHistory === false
+ ? [{ value: 'settings', label: 'Overview' }]
+ : [
+ { value: 'settings', label: 'Overview' },
+ { value: 'history', label: 'Run History' },
+ ]
+ }
>
{(tab) => (
<TabSelector.Tab value={tab.value}>
diff --git a/apps/web/src/features/routines/context/routine-slots.ts b/apps/web/src/features/routines/context/routine-slots.ts
index f5b105cbbb..69289857aa 100644
--- a/apps/web/src/features/routines/context/routine-slots.ts
+++ b/apps/web/src/features/routines/context/routine-slots.ts
@@ -6,6 +6,7 @@ import type { HistoryMetadata } from './history';
export type RoutineEditorSlots = {
PromptEditor: Component<{
initialValue: string;
+ disabled?: boolean;
onChange(value: string): void;
}>;
ExecutionPicker: Component<{
diff --git a/apps/web/src/features/routines/queries/routine-sources.ts b/apps/web/src/features/routines/queries/routine-sources.ts
index b131563114..9a8c80492f 100644
--- a/apps/web/src/features/routines/queries/routine-sources.ts
+++ b/apps/web/src/features/routines/queries/routine-sources.ts
@@ -56,6 +56,7 @@ type DetailCallbacks = {
export function createRoutineDetailSource(
id: Accessor<string>,
+ userId: Accessor<string | undefined>,
callbacks: DetailCallbacks
): RoutineDetailSource {
const list = useSchedulesQuery(() => true);
@@ -84,7 +85,9 @@ export function createRoutineDetailSource(
},
onError: (error) => callbacks.onError('Failed to duplicate routine', error),
});
- const history = useScheduleHistoryQuery(id, () => Boolean(raw()));
+ const history = useScheduleHistoryQuery(id, () =>
+ Boolean(raw() && raw()?.owner === userId())
+ );
onMount(() => {
fireAndForget(invalidateSchedules(), 'routines');
});
diff --git a/apps/web/src/features/routines/routine-detail.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsx
index b48a7c5995..2af24f8d1c 100644
--- a/apps/web/src/features/routines/routine-detail.test.tsx
+++ b/apps/web/src/features/routines/routine-detail.test.tsx
@@ -143,12 +143,14 @@ vi.mock('@components/app/split-layout/components/SplitFileMenu', () => ({
vi.mock('./routine-prompt-editor', () => ({
RoutinePromptEditor: (props: {
initialValue: string;
+ disabled?: boolean;
onChange: (value: string) => void;
}) => {
mocks.changePrompt = props.onChange;
return (
<textarea
aria-label="Instructions"
+ disabled={props.disabled}
value={props.initialValue}
onInput={(event) => props.onChange(event.currentTarget.value)}
/>
@@ -364,6 +366,22 @@ function deferredSave(): {
}
describe('routine execution target autosave', () => {
+ it('shows another owner’s routine without edit, run, or history controls', () => {
+ setSchedules([{ ...cron, owner: 'macro|[email protected]' }]);
+ render(() => <Routine />);
+ expect(screen.getByLabelText('Instructions')).toHaveProperty(
+ 'disabled',
+ true
+ );
+ expect(screen.queryByRole('button', { name: 'Run now' })).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'Routine actions' })
+ ).toBeNull();
+ expect(screen.queryByRole('tab', { name: 'Run History' })).toBeNull();
+ mocks.changePrompt('Changed');
+ expect(mocks.update).not.toHaveBeenCalled();
+ });
+
it('copies the current prompt, including unsaved edits, from the run menu', async () => {
render(() => <Routine />);
mocks.changePrompt('Use my latest instructions');
diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsx
index c3accce693..26206c2a11 100644
--- a/apps/web/src/features/routines/routine-detail.tsx
+++ b/apps/web/src/features/routines/routine-detail.tsx
@@ -52,7 +52,7 @@ export function RoutineDetail(props: {
props.onOpen
? props.onOpen(id)
: openAgentsPage(layout, 'routines', { routineId: id });
- const source = createRoutineDetailSource(() => props.scheduleId, {
+ const source = createRoutineDetailSource(() => props.scheduleId, userId, {
onError: (title, error) =>
toast.alert(title, { subtext: getErrorMessage(error) }),
onDuplicated: (id) => {
diff --git a/apps/web/src/features/routines/routine-prompt-editor.tsx b/apps/web/src/features/routines/routine-prompt-editor.tsx
index 0f04ceb243..819ddbee1b 100644
--- a/apps/web/src/features/routines/routine-prompt-editor.tsx
+++ b/apps/web/src/features/routines/routine-prompt-editor.tsx
@@ -4,6 +4,7 @@ import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownS
export function RoutinePromptEditor(props: {
initialValue: string;
+ disabled?: boolean;
onChange: (markdown: string) => void;
}) {
const editor = new EditorConfigBuilder()
@@ -19,6 +20,7 @@ export function RoutinePromptEditor(props: {
<MarkdownShell
config={editor}
initialValue={props.initialValue}
+ disabled={props.disabled}
placeholder="What should this routine do? Type @ to add context…"
portalScope="local"
class="min-h-28"
diff --git a/apps/web/src/features/routines/views/routine-detail.tsx b/apps/web/src/features/routines/views/routine-detail.tsx
index 732ca37d86..038a48d59b 100644
--- a/apps/web/src/features/routines/views/routine-detail.tsx
+++ b/apps/web/src/features/routines/views/routine-detail.tsx
@@ -74,46 +74,51 @@ export function RoutineDetailView(props: {
}
onChange={setState}
disabled={!isOwned() || isRunning() || !state()}
- tab={tab()}
+ tab={isOwned() ? tab() : 'settings'}
+ showHistory={isOwned()}
onTab={setTab}
onBack={back}
enabled={isActive()}
runActions={
- <RoutineRunButton
- enabled={isActive()}
- runDisabled={runDisabled()}
- activationDisabled={activationDisabled()}
- copyDisabled={!state()?.prompt}
- onRun={runNow}
- onEnabled={(enabled) => props.source.setEnabled(enabled)}
- onCopyPrompt={() => fireAndForget(copyPrompt(), 'routines')}
- />
+ isOwned() && (
+ <RoutineRunButton
+ enabled={isActive()}
+ runDisabled={runDisabled()}
+ activationDisabled={activationDisabled()}
+ copyDisabled={!state()?.prompt}
+ onRun={runNow}
+ onEnabled={(enabled) => props.source.setEnabled(enabled)}
+ onCopyPrompt={() => fireAndForget(copyPrompt(), 'routines')}
+ />
+ )
}
actions={
- <Dropdown placement="bottom-start">
- <Dropdown.Trigger
- variant="ghost"
- size="icon-sm"
- aria-label="Routine actions"
- >
- <DotsIcon class="size-5" />
- </Dropdown.Trigger>
- <Dropdown.Content portalScope="local">
- <Dropdown.Item
- disabled={!state() || props.source.duplicationPending()}
- onSelect={() => props.source.duplicate()}
+ isOwned() && (
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Routine actions"
>
- <CopyIcon class="size-4" />
- Duplicate
- </Dropdown.Item>
- <Show when={isOwned()}>
- <Dropdown.Item onSelect={props.onDelete}>
- <TrashIcon class="size-4" />
- Delete
+ <DotsIcon class="size-5" />
+ </Dropdown.Trigger>
+ <Dropdown.Content portalScope="local">
+ <Dropdown.Item
+ disabled={!state() || props.source.duplicationPending()}
+ onSelect={() => props.source.duplicate()}
+ >
+ <CopyIcon class="size-4" />
+ Duplicate
</Dropdown.Item>
- </Show>
- </Dropdown.Content>
- </Dropdown>
+ <Show when={isOwned()}>
+ <Dropdown.Item onSelect={props.onDelete}>
+ <TrashIcon class="size-4" />
+ Delete
+ </Dropdown.Item>
+ </Show>
+ </Dropdown.Content>
+ </Dropdown>
+ )
}
nextRun={nextRun()}
instructions={
@@ -121,6 +126,7 @@ export function RoutineDetailView(props: {
<Show when={{ version: editorVersion() }} keyed>
<props.slots.PromptEditor
initialValue={state()?.prompt ?? ''}
+ disabled={!isOwned() || isRunning()}
onChange={(prompt) =>
setState((draft) =>
draft.prompt === prompt ? draft : { ...draft, prompt }
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
index d4999709af..ba66f59ead 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/DocumentMention.tsx
@@ -57,7 +57,7 @@ import { useFormDetailQuery } from '@queries/storage/forms';
import { useSystemSkillsQuery } from '@queries/storage/system-skills';
import { blockNameToItemType } from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
-import { Button } from '@ui';
+import { Button, Tooltip } from '@ui';
import {
$getNodeByKey,
COMMAND_PRIORITY_NORMAL,
@@ -389,6 +389,9 @@ function InlinePreview(props: {
}
export function DocumentMention(props: DocumentMentionDecoratorProps) {
+ if (props.blockName === 'routine' || props.blockName === 'automation') {
+ return <RoutineMention {...props} />;
+ }
const lexicalWrapper = useContext(LexicalWrapperContext);
if (lexicalWrapper?.skipPreviewFetch) {
return <DocumentMentionStatic {...props} />;
@@ -416,6 +419,39 @@ export function DocumentMention(props: DocumentMentionDecoratorProps) {
);
}
+/** Routine references use their saved label; routines have no shared item preview. */
+function RoutineMention(props: DocumentMentionDecoratorProps) {
+ const name = () =>
+ props.documentName?.replaceAll('\n', ' ').trim() || 'Routine';
+ const open = (event: MouseEvent | KeyboardEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openDocument(
+ 'routine',
+ props.documentId,
+ undefined,
+ openInNewSplitForMention(event.shiftKey, true)
+ );
+ };
+ return (
+ <Tooltip label={name()} as="span" disabled={!props.collapsed}>
+ <span
+ class="rounded-xs hover:bg-hover focus-visible:outline-2 focus-visible:outline-ink/30"
+ role="link"
+ aria-label={name()}
+ tabIndex={0}
+ on:mousedown={(event) => event.preventDefault()}
+ on:click={open}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') open(event);
+ }}
+ >
+ <DocumentMentionStatic {...props} />
+ </span>
+ </Tooltip>
+ );
+}
+
/** Databases have their own permission-checked metadata, not a document preview. */
function DatabaseMention(props: DocumentMentionDecoratorProps) {
const wrapper = useContext(LexicalWrapperContext);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/playwright.config.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..c887b6f9e9
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/playwright.config.ts
@@ -0,0 +1,28 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from '@playwright/test';
+
+const webDirectory = fileURLToPath(
+ new URL('../../../../../../../../', import.meta.url)
+);
+const port = process.env.ROUTINE_MENTION_TEST_PORT ?? '3049';
+
+export default defineConfig({
+ testDir: '.',
+ testMatch: 'routine-mention.browser.e2e.ts',
+ workers: 1,
+ timeout: 60_000,
+ use: {
+ baseURL: `http://localhost:${port}`,
+ headless: true,
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ webServer: {
+ command: `MACRO_DEV_HTTPS=false bunx vite --port ${port} --strictPort`,
+ cwd: webDirectory,
+ url: `http://localhost:${port}/app/`,
+ reuseExistingServer: false,
+ timeout: 60_000,
+ },
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.browser.e2e.ts
new file mode 100644
index 0000000000..9b98a67fc0
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.browser.e2e.ts
@@ -0,0 +1,26 @@
+import { expect, test } from '@playwright/test';
+
+test('an agent m-document routine mention is clickable', async ({ page }) => {
+ await page.goto(
+ '/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.html'
+ );
+ const mention = page.getByRole('link', { name: 'Daily review' });
+ await expect(mention).toBeVisible();
+ await expect(mention.locator('[data-block-name="routine"]')).toHaveAttribute(
+ 'data-document-id',
+ '0195ceb6-ec2e-7023-80e4-6e084fa6cccd'
+ );
+ await mention.click();
+ await expect(page.getByLabel('Opened split')).toContainText(
+ '"type":"routine"'
+ );
+ await expect(page.getByLabel('Opened split')).toContainText(
+ '"id":"0195ceb6-ec2e-7023-80e4-6e084fa6cccd"'
+ );
+
+ const collapsed = page.getByRole('link', { name: 'Collapsed review' });
+ await expect(collapsed).toBeVisible();
+ await expect(collapsed.locator('[data-block-name="routine"]')).toBeHidden();
+ await collapsed.hover();
+ await expect(page.getByText('Collapsed review')).toBeVisible();
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.html b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.html
new file mode 100644
index 0000000000..db5be25619
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8"><title>Routine mention fixture</title></head>
+ <body><div id="root"></div><script type="module" src="./routine-mention.tsx"></script></body>
+</html>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.tsx
new file mode 100644
index 0000000000..60c1e6e8e4
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/routine-mention.tsx
@@ -0,0 +1,59 @@
+import '@app/index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { setGlobalSplitManager } from '@app/signal/splitLayout';
+import type {
+ SplitContent,
+ SplitManager,
+} from '@components/app/split-layout/layoutManager';
+import { render } from 'solid-js/web';
+import { channelTheme } from '../../../theme';
+import {
+ StaticMarkdown,
+ StaticMarkdownContext,
+} from '../../core/StaticMarkdown';
+import { DocumentMention } from '../DocumentMention';
+
+const id = '0195ceb6-ec2e-7023-80e4-6e084fa6cccd';
+const mention = `<m-document-mention>${JSON.stringify({
+ documentId: id,
+ documentName: 'Daily review',
+ blockName: 'routine',
+})}</m-document-mention>`;
+
+// Only navigation is used by this isolated decorator fixture.
+setGlobalSplitManager({
+ openWithSplit(content: SplitContent) {
+ document.getElementById('opened')!.textContent = JSON.stringify(content);
+ return { status: 'unavailable' };
+ },
+} as SplitManager);
+
+render(
+ () => (
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <StaticMarkdownContext theme={channelTheme}>
+ <main class="p-4 text-ink bg-page">
+ <StaticMarkdown
+ markdown={`Created ${mention}.`}
+ target="internal"
+ />
+ <p>
+ <DocumentMention
+ key="collapsed-routine"
+ theme={channelTheme}
+ documentId={id}
+ documentName="Collapsed review"
+ blockName="routine"
+ collapsed
+ />
+ </p>
+ <output id="opened" aria-label="Opened split" />
+ </main>
+ </StaticMarkdownContext>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ ),
+ document.getElementById('root')!
+);
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 48cc2909cb..1443ca63f9 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -7919,7 +7919,7 @@ export interface CreateProjectResponse {
projectName: string;
}
/**
- * Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.
+ * Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.
*/
export interface CreateRoutine {
configuration: RoutineConfiguration;
diff --git a/crates/prompt/AGENTS.md b/crates/prompt/AGENTS.md
index 2f2d06044a..0a3f95aa0d 100644
--- a/crates/prompt/AGENTS.md
+++ b/crates/prompt/AGENTS.md
@@ -40,6 +40,8 @@ AI system prompts: one module per prompt section, each exporting a
The agent-session prompt distinguishes typed `<m-notifications>` system facts
from user requests and defines the notification-only `<noop/>` contract.
+In-app replies use `m-document-mention` with `blockName: "routine"` for routines;
+external MCP replies use `/app/routines/<id>` URLs.
## Checks
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index 4cf81d2225..2acedcae75 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -152,6 +152,7 @@ mod tests {
// worked example for a document.
assert!(instructions.contains("https://macro.com/app/<type>/<id>"));
assert!(instructions.contains("[Name](https://macro.com/app/md/<id>)"));
+ assert!(instructions.contains("[Name](https://macro.com/app/routines/<id>)"));
}
#[test]
@@ -356,6 +357,7 @@ mod tests {
assert!(instructions.contains("\"blockName\":\"skill\""));
assert!(instructions.contains("\"blockName\":\"initiative\""));
assert!(instructions.contains("\"blockName\":\"pipeline\""));
+ assert!(instructions.contains("\"blockName\":\"routine\""));
}
#[test]
diff --git a/crates/prompt/src/mcp_item_links.rs b/crates/prompt/src/mcp_item_links.rs
index e689591dc6..6520973a5e 100644
--- a/crates/prompt/src/mcp_item_links.rs
+++ b/crates/prompt/src/mcp_item_links.rs
@@ -27,11 +27,12 @@ pub fn render(base_url: &str) -> String {
format!(
"# {TITLE}\n\
When referring the user to a Macro item (document, channel, chat, \
- project, task, email thread, or database) in your responses, write a plain URL of \
+ project, task, email thread, database, or routine) in your responses, write a plain URL of \
the form `{base_url}/app/<type>/<id>`, where `<type>` is the item's type \
— `md` for a document, `channel`, `chat`, `project`, `task`, `email` \
for an email thread, or `database` — and `<id>` is the item id. Render it as a normal \
Markdown link, e.g. `[Name]({base_url}/app/md/<id>)`.\n\
+ For a routine, use `[Name]({base_url}/app/routines/<id>)`.\n\
\n\
Do NOT emit `<m-document-mention>` XML tags or any other Macro internal \
mention/markup format in these responses. Those only render inside the \
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index 57bc4c9584..f4297dd89b 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -39,6 +39,7 @@ Use `<m-document-mention>` with the right `blockName` (and `blockParams` when ne
- Skill mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"skill","blockParams":{}}</m-document-mention>`
- Call mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"call","blockParams":{}}</m-document-mention>`
- Automation mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"automation","blockParams":{}}</m-document-mention>`
+- Routine mention: `<m-document-mention>{"documentId":"{id}","documentName":"{name}","blockName":"routine"}</m-document-mention>`
- Snippet mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"snippet","blockParams":{}}</m-document-mention>`
- CRM company mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"company","blockParams":{}}</m-document-mention>`
- CRM pipeline mention: `<m-document-mention>{"documentId":"{pipeline_id}","documentName":"","blockName":"pipeline","blockParams":{}}</m-document-mention>`
diff --git a/crates/routines/AGENTS.md b/crates/routines/AGENTS.md
index 31dd2cf737..d5e777e22e 100644
--- a/crates/routines/AGENTS.md
+++ b/crates/routines/AGENTS.md
@@ -11,6 +11,8 @@ persona/model to run later.
- `src/domain.rs`: `RoutineTarget` (model vs. agent persona) and
`RoutineSchedule` (`Once` / `Cron`) — the validated command shapes.
- `src/inbound.rs`: the AI toolset exposed to MCP and embedded agents.
+- `CreateRoutine` tells agents to use `m-document-mention` with the routine ID,
+ name, and `blockName: "routine"` in replies.
- `src/outbound.rs`: the HTTP client to the owning scheduled-action service.
## Scope
diff --git a/crates/routines/src/inbound.rs b/crates/routines/src/inbound.rs
index a6688f3e2d..1bb07cac59 100644
--- a/crates/routines/src/inbound.rs
+++ b/crates/routines/src/inbound.rs
@@ -48,7 +48,7 @@ pub fn routine_toolset() -> AsyncToolCollection<RoutineToolContext> {
#[derive(Deserialize, JsonSchema)]
#[schemars(
title = "CreateRoutine",
- description = "Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine."
+ description = r#"Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. In Macro app replies, mention the created routine as `<m-document-mention>{"documentId":"ID","documentName":"NAME","blockName":"routine"}</m-document-mention>`, replacing ID with the returned ID and NAME with the saved routine name. In external MCP replies, follow the MCP item-linking instructions. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine."#
)]
pub struct CreateRoutine {
/// Name, instructions, target, and schedule.
diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.md
index c1380019ad..9df409d732 100644
--- a/crates/scheduled_action/AGENTS.md
+++ b/crates/scheduled_action/AGENTS.md
@@ -24,6 +24,8 @@ each run.
- Owns: scheduled-action and event-trigger CRUD, dispatch (in-process or
tokio), run history, and live-update notifications over the connection
gateway.
+- An authenticated caller with a routine ID can read its detail; listing,
+ run history, and mutations stay owner-scoped.
- Not here: the target being run (an agent turn, a routine's tool logic) →
`crates/agent_session`, `ai_tools`; Jev condition evaluation → `crates/jev`.
diff --git a/crates/scheduled_action/src/domain/ports.rs b/crates/scheduled_action/src/domain/ports.rs
index c2eb03ae90..142c35e495 100644
--- a/crates/scheduled_action/src/domain/ports.rs
+++ b/crates/scheduled_action/src/domain/ports.rs
@@ -121,11 +121,8 @@ pub trait ScheduledActionReadService: Send + Sync + 'static {
}
pub trait ScheduledActionService: Send + Sync + 'static {
- /// Read a routine only when the caller is its owner.
- fn get_action(
- &self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- ) -> impl Future<Output = Result<ScheduledAction>> + Send;
+ /// Read a routine by its unguessable ID for an authenticated viewer.
+ fn get_action(&self, id: Uuid) -> impl Future<Output = Result<ScheduledAction>> + Send;
/// Delete all of a user's actions before account deletion, including disabled
/// and claimed actions. Repeating a completed cleanup succeeds.
diff --git a/crates/scheduled_action/src/domain/service.rs b/crates/scheduled_action/src/domain/service.rs
index f246ddd31c..7c974ec2ce 100644
--- a/crates/scheduled_action/src/domain/service.rs
+++ b/crates/scheduled_action/src/domain/service.rs
@@ -252,11 +252,11 @@ where
Targets: TaskTargetValidator,
Exe: ScheduledActionExecutor + Send + Sync + 'static,
{
- async fn get_action(
- &self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- ) -> Result<ScheduledAction> {
- self.load_granted(&receipt).await
+ async fn get_action(&self, id: Uuid) -> Result<ScheduledAction> {
+ self.repo
+ .get_action(&id)
+ .await?
+ .ok_or_else(|| ActionPolicyError::NotFound.into())
}
async fn delete_user_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<()> {
diff --git a/crates/scheduled_action/src/domain/service/test.rs b/crates/scheduled_action/src/domain/service/test.rs
index 5571b43297..1b6a6ea3e8 100644
--- a/crates/scheduled_action/src/domain/service/test.rs
+++ b/crates/scheduled_action/src/domain/service/test.rs
@@ -696,7 +696,7 @@ async fn list_is_cron_only_by_default_but_id_operations_reach_events() {
}
#[tokio::test]
-async fn grants_do_not_allow_access_to_another_owners_routine() {
+async fn nonowners_can_read_but_not_manage_routines() {
let svc = service(true);
for owner in [
Owner::from_principal_str(FOREIGN_USER).unwrap(),
@@ -711,12 +711,9 @@ async fn grants_do_not_allow_access_to_another_owners_routine() {
.await
.unwrap();
let id = created.id.unwrap();
- assert_eq!(svc.get_action(view_receipt(id)).await.unwrap().id, Some(id));
+ assert_eq!(svc.get_action(id).await.unwrap().id, Some(id));
svc.repo.actions.lock().unwrap().last_mut().unwrap().owner = owner;
- assert_policy(
- svc.get_action(view_receipt(id)).await,
- ActionPolicyError::NotFound,
- );
+ assert_eq!(svc.get_action(id).await.unwrap().id, Some(id));
assert_policy(
svc.update_action(edit_receipt(id), update(configuration(true)))
.await,
diff --git a/crates/scheduled_action/src/inbound/axum_router.rs b/crates/scheduled_action/src/inbound/axum_router.rs
index d67d6360eb..a3f2a99746 100644
--- a/crates/scheduled_action/src/inbound/axum_router.rs
+++ b/crates/scheduled_action/src/inbound/axum_router.rs
@@ -302,17 +302,15 @@ where
)]
pub async fn get_action<S, Svc, Auth>(
State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,
- ScheduledActionAccessExtractor {
- entity_access_receipt,
- ..
- }: ScheduledActionAccessExtractor<ViewAccessLevel, Svc, Auth>,
+ _user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Path(id): Path<Uuid>,
) -> Result<Json<ScheduledActionResponse>, ScheduledActionApiError>
where
S: ScheduledActionService,
Svc: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let action = state.service.get_action(entity_access_receipt).await?;
+ let action = state.service.get_action(id).await?;
Ok(Json(action.into()))
}
diff --git a/crates/scheduled_action/src/inbound/axum_router/test.rs b/crates/scheduled_action/src/inbound/axum_router/test.rs
index 98bc0a999e..d30d2326a5 100644
--- a/crates/scheduled_action/src/inbound/axum_router/test.rs
+++ b/crates/scheduled_action/src/inbound/axum_router/test.rs
@@ -514,7 +514,7 @@ async fn owner_can_read_cron_and_event_routines_but_missing_ids_return_not_found
}
#[tokio::test]
-async fn foreign_owner_operations_return_not_found_and_list_is_empty() {
+async fn foreign_owner_can_read_but_not_manage_and_list_is_empty() {
let app = router(true);
let (_, action) = request(
&app,
@@ -525,8 +525,11 @@ async fn foreign_owner_operations_return_not_found_and_list_is_empty() {
)
.await;
let url = format!("/scheduled-actions/{}", action["id"].as_str().unwrap());
+ assert_eq!(
+ request(&app, "GET", &url, "other", Value::Null).await.0,
+ StatusCode::OK
+ );
for (method, path, body) in [
- ("GET", url.clone(), Value::Null),
("PUT", url.clone(), legacy()),
("PUT", format!("{url}/enabled"), json!({"enabled": false})),
("DELETE", url.clone(), Value::Null),
@@ -895,7 +898,11 @@ async fn grants_do_not_allow_nonowners_to_manage_routines() {
);
assert_eq!(
request(&app, "GET", &url, "viewer", Value::Null).await.0,
- StatusCode::NOT_FOUND
+ StatusCode::OK
+ );
+ assert_eq!(
+ request(&app, "GET", &url, "stranger", Value::Null).await.0,
+ StatusCode::OK
);
assert_eq!(
request(
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 81a678a45f..7f3f179f99 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -836,9 +836,12 @@ loads those settings before further edits. While running, configuration is locke
but cannot resume until the run ends. Completed one-offs remain visible with
their history and do not repeat.
-Routines are private to their owner. Other users cannot list or open the routine
-or its history, even if they belong to the same team. Run conversations keep
-their own permissions.
+An `m-document-mention` with `blockName: "routine"`, the returned routine ID,
+and the saved name renders as a clickable mention in an agent reply. Routines
+do not appear in the mention menu. Anyone signed in with the link can view its
+settings, instructions, and triggers. Only the owner can edit, enable, run,
+duplicate, delete, or view run history; other users do not see those controls.
+Run conversations keep their own permissions.
**Run History** shows outcome, duration, and firing time. History loads fifty
rows at a time; **Load more runs** reveals older records. Accessible run rows
diff --git a/packages/lexical-core/tests/routine-mention.test.ts b/packages/lexical-core/tests/routine-mention.test.ts
new file mode 100644
index 0000000000..80f12e9753
--- /dev/null
+++ b/packages/lexical-core/tests/routine-mention.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import { extractChannelMentionsFromMarkdown } from '../utils/markdown-mentions';
+import {
+ markdownToSerializedEditorStateWithIds,
+ serializedEditorStateToMarkdown,
+} from '../utils/markdown-state';
+
+describe('routine mentions in agent replies', () => {
+ it('imports an m-document mention with the routine block type', () => {
+ const id = '0195ceb6-ec2e-7023-80e4-6e084fa6cccd';
+ const markdown = `Created <m-document-mention>${JSON.stringify({
+ documentId: id,
+ documentName: 'Daily review',
+ blockName: 'routine',
+ })}</m-document-mention>.`;
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+ expect(state.root.children[0]).toMatchObject({
+ children: [
+ { type: 'text', text: 'Created ' },
+ {
+ type: 'document-mention',
+ documentId: id,
+ documentName: 'Daily review',
+ blockName: 'routine',
+ },
+ { type: 'text', text: '.' },
+ ],
+ });
+ expect(serializedEditorStateToMarkdown(state)).toContain(
+ '"blockName":"routine"'
+ );
+ expect(extractChannelMentionsFromMarkdown(markdown)).toEqual([
+ { entityType: 'automation', entityId: id },
+ ]);
+ });
+});
diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.ts
index df338471f8..b6cdf9b0ff 100644
--- a/packages/lexical-core/transformers/mentions.ts
+++ b/packages/lexical-core/transformers/mentions.ts
@@ -300,7 +300,11 @@ export const E_DOCUMENT_MENTION: ElementTransformer = {
}
const hostname = cleanHostname(window.location.hostname);
- const documentUrl = `https://${hostname}/app/${blockType}/${documentId}`;
+ const path =
+ blockType === 'routine' || blockType === 'automation'
+ ? 'routines'
+ : blockType;
+ const documentUrl = `https://${hostname}/app/${path}/${documentId}`;
return `[${documentName}](${documentUrl})`;
},
replace: (