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(routines): share routines from the standard Share menu and by mention (#9223)
Eric Hayes10e629ff8ec0
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex dcae8092fd..0ad81eaaca 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -785,7 +785,8 @@ call the reviewed workspace tools, and show separate task/project totals.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.+`blockName: "routine"`; the `@` menu offers routines only to their owner in+channel composers, where picking one shares it as a template.Direct local hosts use port 8101 with the existing feature prefixes; theinstance proxy retains `/cognition`, `/scheduled-action`, and `/preview`.diff --git a/apps/web/src/features/routines/core/template.test.ts b/apps/web/src/features/routines/core/template.test.tsindex 6d4214f832..51aa2f3cbe 100644--- a/apps/web/src/features/routines/core/template.test.ts+++ b/apps/web/src/features/routines/core/template.test.ts@@ -1,8 +1,10 @@import { describe, expect, it } from 'vitest';+import { createEmptyDraft } from './routine-draft';import {extractTemplateVariables,fillTemplatePrompt,fillTemplateTrigger,+ templateShareBody,} from './template';const AUTHOR =@@ -152,3 +154,80 @@ describe('fillTemplateTrigger', () => {).toEqual(CRON);});});++describe('templateShareBody', () => {+ it('keeps the shared template’s fills and description for references the routine still has', () => {+ const draft = {+ ...createEmptyDraft(''),+ target: { kind: 'agent' as const, agentId: 'agent-1' },+ };+ expect(+ templateShareBody({+ draft: { ...draft, prompt: PROMPT, timezone: CRON.timezone },+ authorId: 'macro|[email protected]',+ shared: {+ active_count: 2,+ author: 'macro|[email protected]',+ created_at: '2026-10-01T00:00:00Z',+ description: 'Weekly renewals digest',+ id: 'routine-1',+ name: 'Renewals',+ task: { user_prompt: PROMPT },+ trigger: CRON,+ updated_at: '2026-10-01T00:00:00Z',+ variables: [+ {+ kind: 'item',+ id: 'doc-1',+ block_name: 'md',+ label: 'Acme account',+ fill: 'choice',+ },+ {+ kind: 'item',+ id: 'doc-removed',+ block_name: 'md',+ label: 'Old notes',+ fill: 'choice',+ },+ ],+ },+ })+ ).toEqual({+ description: 'Weekly renewals digest',+ variables: [+ {+ kind: 'item',+ id: 'channel-1',+ block_name: 'channel',+ label: 'customer-success',+ fill: 'shared',+ },+ {+ kind: 'item',+ id: 'doc-1',+ block_name: 'md',+ label: 'Acme account',+ fill: 'choice',+ },+ {+ kind: 'user',+ id: 'macro|[email protected]',+ label: 'Priya Shah',+ fill: 'shared',+ },+ {+ kind: 'user',+ id: 'macro|[email protected]',+ label: 'Eric',+ fill: 'activator',+ },+ {+ kind: 'time_zone',+ timezone: CRON.timezone,+ fill: 'activator',+ },+ ],+ });+ });+});diff --git a/apps/web/src/features/routines/core/template.ts b/apps/web/src/features/routines/core/template.tsindex 9ca73aaf9b..533fef324d 100644--- a/apps/web/src/features/routines/core/template.ts+++ b/apps/web/src/features/routines/core/template.ts@@ -1,9 +1,12 @@import type {ActionTrigger,+ RoutineTemplate,+ ShareRoutineTemplate,TemplateVariable,VariableFill,} from '@service-scheduled-action/generated/schemas';import { match } from 'ts-pattern';+import type { ScheduleDraft } from './draft';const MENTION_PATTERN =/<m-(user|document)-mention>([\s\S]*?)<\/m-\1-mention>/g;@@ -103,6 +106,43 @@ export function extractTemplateVariables(args: {return [...variables.values()];}+/** The time zone a routine's schedules run in; absent for event-only routines. */+function routineTimezone(draft: ScheduleDraft | undefined) {+ const schedule = draft?.triggers?.find(+ (trigger) => trigger.kind === 'schedule'+ );+ if (schedule?.kind === 'schedule') return schedule.timezone;+ return draft?.triggers ? undefined : draft?.timezone;+}++/**+ * What sharing a routine publishes: its current references, each filled the+ * way the template already shared fills it, else by the defaults.+ */+export function templateShareBody(args: {+ draft: ScheduleDraft | undefined;+ authorId: string;+ shared: RoutineTemplate | null;+}): ShareRoutineTemplate {+ const previous = new Map(+ (args.shared?.variables ?? []).map((variable) => [+ variableKey(variable),+ variable.fill,+ ])+ );+ return {+ description: args.shared?.description ?? '',+ variables: extractTemplateVariables({+ prompt: args.draft?.prompt ?? '',+ timezone: routineTimezone(args.draft),+ authorId: args.authorId,+ }).map((variable) => ({+ ...variable,+ fill: previous.get(variableKey(variable)) ?? variable.fill,+ })),+ };+}+/** Keep the referenced item, or drop it and leave its name as plain text. */export type ReferenceChoice = 'keep' | 'leave_out';diff --git a/apps/web/src/features/routines/queries/routines.ts b/apps/web/src/features/routines/queries/routines.tsindex 3519115cc0..d9a33bb329 100644--- a/apps/web/src/features/routines/queries/routines.ts+++ b/apps/web/src/features/routines/queries/routines.ts@@ -4,7 +4,7 @@ import { queryOptions, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { scheduledActionKeys } from './keys';-function routineQueryOptions(id: string) {+export function routineQueryOptions(id: string) {return queryOptions({queryKey: scheduledActionKeys.detail({ scheduleId: id }).queryKey,queryFn: () => throwOnErr(() => scheduledActionClient.getRoutine(id)),diff --git a/apps/web/src/features/routines/queries/templates.ts b/apps/web/src/features/routines/queries/templates.tsindex 51dbec9f58..a69ed78da7 100644--- a/apps/web/src/features/routines/queries/templates.ts+++ b/apps/web/src/features/routines/queries/templates.ts@@ -12,7 +12,6 @@ import type {CreateScheduledAction,RoutineTemplate,ScheduledAction,- ShareRoutineTemplate,} from '@service-scheduled-action/generated/schemas';import { blockNameToItemType } from '@service-storage/itemType';import {@@ -22,7 +21,10 @@ import {useQuery,} from '@tanstack/solid-query';import type { Accessor } from 'solid-js';+import { templateShareBody } from '../core/template';import { scheduledActionKeys } from './keys';+import { draftFromSchedule } from './routine-draft';+import { routineQueryOptions } from './routines';import { invalidateSchedules } from './schedules';/** A routine that isn't shared has no template: `null`, not an error. */@@ -66,21 +68,27 @@ function setTemplate(scheduleId: string, template: RoutineTemplate | null) {);}-export function useShareTemplateMutation(- callbacks?: MutationCallbacks<- RoutineTemplate,- Error,- { scheduleId: string; body: ShareRoutineTemplate }- >-) {- return useMutation(() => ({- mutationFn: (args: { scheduleId: string; body: ShareRoutineTemplate }) =>- throwOnErr(() => scheduledActionClient.shareTemplate(args)),- ...withCallbacks(- { onSuccess: (template) => setTemplate(template.id, template) },- callbacks- ),- }));+/**+ * Shares a routine as a template, or brings its template up to date with the+ * routine's saved setup. Repeating it publishes the same snapshot again.+ */+export async function publishRoutineTemplate(+ scheduleId: string+): Promise<RoutineTemplate> {+ const [routine, shared] = await Promise.all([+ queryClient.fetchQuery(routineQueryOptions(scheduleId)),+ queryClient.fetchQuery(routineTemplateQueryOptions(scheduleId)),+ ]);+ const body = templateShareBody({+ draft: draftFromSchedule(routine),+ authorId: routine.owner,+ shared,+ });+ const template = await throwOnErr(() =>+ scheduledActionClient.shareTemplate({ scheduleId, body })+ );+ setTemplate(scheduleId, template);+ return template;}export function useUnshareTemplateMutation(diff --git a/apps/web/src/features/routines/routine-detail.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsxindex 6ba83612df..d4efe401d4 100644--- a/apps/web/src/features/routines/routine-detail.test.tsx+++ b/apps/web/src/features/routines/routine-detail.test.tsx@@ -78,7 +78,7 @@ vi.mock('./routine-template', () => ({RoutineTemplatePage: (props: { scheduleId: string }) => (<div>Template for {props.scheduleId}</div>),- openShareTemplateDialog: vi.fn(),+ openShareRoutineDialog: vi.fn(),}));vi.mock('@core/block', () => ({ useBlockId: () => 'routine-id' }));vi.mock('@core/component/AI/constant', () => ({diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsxindex d4a422d64a..2bb6d951e2 100644--- a/apps/web/src/features/routines/routine-detail.tsx+++ b/apps/web/src/features/routines/routine-detail.tsx@@ -11,7 +11,6 @@ import { enableRoutineSharing } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { writeClipboardData } from '@core/util/dataTransfer';import { getOwner, onMount, Show } from 'solid-js';-import type { ScheduleDraft } from './core/draft';import { getErrorMessage } from './core/routine-draft';import {createAgentHistoryMetadata,@@ -22,7 +21,7 @@ import { createRoutineConnectedApps, RoutineApps } from './routine-apps';import { RoutineExecutionPicker } from './routine-execution-picker';import { RoutinePromptEditor } from './routine-prompt-editor';import {- openShareTemplateDialog,+ openShareRoutineDialog,RoutineTemplatePage,} from './routine-template';import { RoutineTriggers } from './routine-triggers';@@ -83,16 +82,13 @@ export function RoutineDetail(props: {});};const owner = getOwner();- const shareTemplate = () => {+ const share = () => {const routine = source.routine();if (!routine) return;- openShareTemplateDialog(+ openShareRoutineDialog({routineId: routine.id,name: routine.name,- prompt: routine.draft?.prompt ?? '',- timezone: scheduleTimezone(routine.draft),- ownerId: routine.ownerId,},owner);@@ -130,7 +126,7 @@ export function RoutineDetail(props: {toast.success('Prompt copied');else toast.alert('Could not copy prompt');}}- onShareTemplate={sharing().enabled ? shareTemplate : undefined}+ onShare={sharing().enabled ? share : undefined}onOpenTemplate={sharing().enabled ? open : undefined}slots={{PromptEditor: RoutinePromptEditor,@@ -145,12 +141,3 @@ export function RoutineDetail(props: {</Show>);}--/** The time zone a routine's schedules run in, for sharing it as a template. */-function scheduleTimezone(draft: ScheduleDraft | undefined) {- const schedule = draft?.triggers?.find(- (trigger) => trigger.kind === 'schedule'- );- if (schedule?.kind === 'schedule') return schedule.timezone;- return draft?.triggers ? undefined : draft?.timezone;-}diff --git a/apps/web/src/features/routines/routine-mentions.ts b/apps/web/src/features/routines/routine-mentions.tsnew file mode 100644index 0000000000..ec7c1ef853--- /dev/null+++ b/apps/web/src/features/routines/routine-mentions.ts@@ -0,0 +1,39 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import type { RoutineMentionItem } from '@core/component/LexicalMarkdown/utils/mentionsUtils';+import { enableRoutineSharing } from '@core/constant/featureFlags';+import { useUserId } from '@core/context/user';+import { queryReadyGate } from '@queries/gate';+import { createLazyMemo } from '@solid-primitives/memo';+import type { Accessor } from 'solid-js';+import { useSchedulesQuery } from './queries/schedules';++/**+ * The viewer's own routines for a channel's mention menu. Only an owner can+ * share a routine, so nobody else's are offered.+ */+export function useRoutineMentionSource(+ searchTerm: Accessor<string>,+ enabled: Accessor<boolean>+): Accessor<RoutineMentionItem[]> {+ const sharing = useFeatureFlag(enableRoutineSharing);+ const userId = useUserId();+ const active = () => enabled() && sharing().enabled;+ const query = useSchedulesQuery(active);+ return createLazyMemo(() => {+ if (!active() || !queryReadyGate(query)) return [];+ const term = searchTerm().trim().toLocaleLowerCase();+ return query.data.flatMap((routine) =>+ routine.id &&+ routine.owner === userId() &&+ routine.name.toLocaleLowerCase().includes(term)+ ? [+ {+ kind: 'routine' as const,+ id: routine.id,+ data: { id: routine.id, name: routine.name },+ },+ ]+ : []+ );+ });+}diff --git a/apps/web/src/features/routines/routine-template.tsx b/apps/web/src/features/routines/routine-template.tsxindex 1707752ac4..e16edc4c54 100644--- a/apps/web/src/features/routines/routine-template.tsx+++ b/apps/web/src/features/routines/routine-template.tsx@@ -1,36 +1,30 @@import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useSplitLayout } from '@components/app/split-layout/layout';-import { RecipientSelector } from '@core/component/RecipientSelector';+import { ForwardToChannel } from '@core/component/ForwardToChannel';import { toast } from '@core/component/Toast/Toast';import {enableRoutineSharing,isFeatureEnabled,} from '@core/constant/featureFlags';import { useEmail, useUserId } from '@core/context/user';-import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';-import type { WithCustomUserInput } from '@core/user';import { getDisplayName } from '@core/user/displayName';import { tryMacroId } from '@core/user/macroId';-import { useSendMessageToPeople } from '@core/util/channels';import { getDefaultTimezone } from '@core/util/cron';import { writeClipboardData } from '@core/util/dataTransfer';-import { getDestinationFromOptions } from '@core/util/destination';import { fireAndForget } from '@core/util/fireAndForget';import { buildSimpleEntityUrl } from '@core/util/url';-import PaperPlaneIcon from '@icon/system/regular/paper-plane-tilt.svg';import { Telemetry } from '@macro-inc/observability';import type {ActionTrigger,RoutineTemplate,TemplateVariable,} from '@service-scheduled-action/generated/schemas';-import { Button, type ManagedDialogProps, openDialog } from '@ui';+import { type ManagedDialogProps, openDialog } from '@ui';import {type Accessor,type ComponentProps,createEffect,- createMemo,createSignal,getOwner,Match,@@ -40,27 +34,23 @@ import {} from 'solid-js';import { TemplateCard } from './components/template-card';import { describeTrigger } from './core/routine-triggers';-import {- type Activator,- extractTemplateVariables,- variableKey,-} from './core/template';+import type { Activator } from './core/template';import {createTemplateActivation,templatePrompt,} from './primitives/template-activation';import { parseRoutineTriggers } from './queries/routine-trigger-mapping';import {+ publishRoutineTemplate,useActivateTemplateMutation,useReferenceAccess,useRoutineTemplateQuery,- useShareTemplateMutation,useUnshareTemplateMutation,} from './queries/templates';import { RoutinePromptEditor } from './routine-prompt-editor';import { ActivateTemplateDialog } from './views/activate-template-dialog';import { RoutineTemplateView } from './views/routine-template-view';-import { ShareTemplateDialog } from './views/share-template-dialog';+import { ShareRoutineDialog } from './views/share-template-dialog';function triggerLines(trigger: ActionTrigger): string[] {return (parseRoutineTriggers(trigger) ?? []).map(describeTrigger);@@ -295,188 +285,112 @@ function EnabledRoutineTemplatePage(props: {);}-type Recipient = WithCustomUserInput<'user' | 'contact' | 'channel'>;--function mentionMarkup(routineId: string, name: string) {+/** A routine as a mention in a message, which renders its template card. */+function routineReference(routineId: string, name: string) {const data = JSON.stringify({documentId: routineId,documentName: name,blockName: 'routine',});- return `<m-document-mention>${data}</m-document-mention>`;+ return {+ markdown: `<m-document-mention>${data}</m-document-mention>`,+ mention: { entity_type: 'automation', entity_id: routineId },+ };}-/** Posts a template's link to a channel or people. */-function SendTemplate(props: { routineId: string; name: string }) {- const [recipients, setRecipients] = createSignal<Recipient[]>([]);- const [sending, setSending] = createSignal(false);- const { all } = useCombinedRecipients();- const { sendToChannel, sendToUsers } = useSendMessageToPeople();+/** The owner's Share menu for one of their routines. */+function ShareRoutine(+ props: ManagedDialogProps & { routineId: string; name: string }+) {+ const query = useRoutineTemplateQuery(() => props.routineId);+ const template = () => (query.isPending ? undefined : (query.data ?? null));+ const unshare = useUnshareTemplateMutation();+ const [publishing, setPublishing] = createSignal(false);+ const [sendForm, setSendForm] = createSignal<{+ canSubmit(): boolean;+ submit(): void;+ }>();- async function send() {- const destination = getDestinationFromOptions(recipients());- if (!destination || sending()) return;- setSending(true);- const message = {- content: `Here's a routine you can activate for yourself: ${mentionMarkup(props.routineId, props.name)}`,- mentions: [],- };+ // Every send and copy publishes the routine's current setup first.+ async function publish(source: 'send' | 'link') {+ setPublishing(true);try {- const result =- destination.type === 'channel'- ? await sendToChannel({ ...message, channelId: destination.id })- : await sendToUsers({ ...message, users: destination.users });- if (result) {- toast.success('Template sent');- setRecipients([]);- } else toast.failure('Message failed to send');+ await Telemetry.span('routine.template.share', async (span) => {+ span.setAttr('routine.id', props.routineId);+ span.setAttr('routine.template.source', source);+ try {+ await publishRoutineTemplate(props.routineId);+ } catch (cause) {+ span.error('Sharing the routine failed');+ throw cause;+ }+ });} finally {- setSending(false);+ setPublishing(false);}}- return (- <div class="flex items-start gap-2">- <RecipientSelector<'user' | 'contact' | 'channel'>- placeholder="Channel or people"- options={all}- selectedOptions={recipients()}- setSelectedOptions={setRecipients}- triggerMode="input"- portalScope="local"- class="min-w-0 flex-1"- />- <Button- variant="outline"- disabled={recipients().length === 0 || sending()}- onClick={() => fireAndForget(send(), 'routines')}- >- <PaperPlaneIcon class="size-4" />- Send- </Button>- </div>- );-}--/** The owner's share dialog for one of their routines. */-function ShareTemplate(- props: ManagedDialogProps & {- routineId: string;- name: string;- prompt: string;- timezone: string | undefined;- ownerId: string;- }-) {- const query = useRoutineTemplateQuery(() => props.routineId);- const shared = () => (query.isPending ? undefined : (query.data ?? null));- const share = useShareTemplateMutation();- const unshare = useUnshareTemplateMutation();- const [error, setError] = createSignal<string>();- const [description, setDescription] = createSignal<string>();- const [fills, setFills] = createSignal<- ReadonlyMap<string, TemplateVariable['fill']>- >(new Map());-- // Start from the shared template's choices for references it still has.- const variables = createMemo(() => {- const previous = new Map(- (shared()?.variables ?? []).map((variable) => [- variableKey(variable),- variable.fill,- ])- );- return extractTemplateVariables({- prompt: props.prompt,- timezone: props.timezone,- authorId: props.ownerId,- }).map((variable) => {- const key = variableKey(variable);- const fill = fills().get(key) ?? previous.get(key) ?? variable.fill;- return { ...variable, fill };- });- });-- const failed = (cause: unknown) =>- setError(- cause instanceof Error && cause.message- ? cause.message- : 'Something went wrong. Please try again.'- );-- async function shareTemplate() {- setError(undefined);- await Telemetry.span('routine.template.share', async (span) => {- span.setAttr('routine.id', props.routineId);- span.setAttr('routine.template.variables', variables().length);- try {- await share.mutateAsync({- scheduleId: props.routineId,- body: {- description: description() ?? shared()?.description ?? '',- variables: variables(),- },- });- toast.success(shared() ? 'Template updated' : 'Template shared');- } catch (cause) {- span.error('Sharing the template failed');- failed(cause);- }- });+ async function copyLink() {+ try {+ await publish('link');+ } catch {+ toast.failure('Could not share this routine');+ return;+ }+ const url = buildSimpleEntityUrl({ type: 'routine', id: props.routineId });+ if (await writeClipboardData({ 'text/plain': url }))+ toast.success('Link copied', {+ subtext: 'Anyone with the link can activate their own copy.',+ });+ else toast.alert('Could not copy the link');}async function stopSharing() {- setError(undefined);try {await unshare.mutateAsync({ scheduleId: props.routineId });toast.success('Stopped sharing');- } catch (cause) {- failed(cause);+ } catch {+ toast.failure('Could not stop sharing', { subtext: 'Please try again' });}}- async function copyLink() {- const url = buildSimpleEntityUrl({ type: 'routine', id: props.routineId });- if (await writeClipboardData({ 'text/plain': url }))- toast.success('Template link copied');- else toast.alert('Could not copy the link');- }-return (- <ShareTemplateDialog+ <ShareRoutineDialogopen={props.open}onOpenChange={props.onOpenChange}name={props.name}- template={shared()}- description={description() ?? shared()?.description ?? ''}- onDescription={setDescription}- variables={variables()}- onFill={(key, fill) =>- setFills((current) => new Map(current).set(key, fill))- }- pending={share.isPending || unshare.isPending}- error={error()}- onShare={() => fireAndForget(shareTemplate(), 'routines')}- onUnshare={() => fireAndForget(stopSharing(), 'routines')}+ template={template()}+ pending={publishing() || unshare.isPending}onCopyLink={() => fireAndForget(copyLink(), 'routines')}- send={<SendTemplate routineId={props.routineId} name={props.name} />}+ onStopSharing={() => fireAndForget(stopSharing(), 'routines')}+ sendAction={sendForm()}+ send={+ <ForwardToChannel+ name={props.name}+ entity={{ entity_type: 'automation', entity_id: props.routineId }}+ inlineReference={routineReference(props.routineId, props.name)}+ prepareChannel={() => publish('send')}+ onSubmit={() => props.onOpenChange(false)}+ onCancel={() => props.onOpenChange(false)}+ ref={(form) =>+ setSendForm({+ canSubmit: form.canSubmit,+ submit: form.handleSubmit,+ })+ }+ />+ }/>);}-/** Opens the share-as-template dialog for a routine the viewer owns. */-export function openShareTemplateDialog(- routine: {- routineId: string;- name: string;- prompt: string;- timezone: string | undefined;- ownerId: string;- },+/** Opens the Share menu for a routine the viewer owns. */+export function openShareRoutineDialog(+ routine: { routineId: string; name: string },owner: ReturnType<typeof getOwner>) {if (!isFeatureEnabled(enableRoutineSharing)) return;- return openDialog<ComponentProps<typeof ShareTemplate>>(+ return openDialog<ComponentProps<typeof ShareRoutine>>((props) => {const sharing = useFeatureFlag(enableRoutineSharing);createEffect(@@ -486,7 +400,7 @@ export function openShareTemplateDialog();return (<Show when={sharing().enabled}>- <ShareTemplate {...props} />+ <ShareRoutine {...props} /></Show>);},diff --git a/apps/web/src/features/routines/views/routine-detail.tsx b/apps/web/src/features/routines/views/routine-detail.tsxindex 50e779b508..c56a56d139 100644--- a/apps/web/src/features/routines/views/routine-detail.tsx+++ b/apps/web/src/features/routines/views/routine-detail.tsx@@ -28,7 +28,7 @@ export function RoutineDetailView(props: {onBack(): void;onDelete(): void;onCopyPrompt(prompt: string): Promise<void>;- onShareTemplate?(): void;+ onShare?(): void;onOpenTemplate?(templateId: string): void;onOpenRun(resource: HistoryResource, newSplit: boolean): void;}) {@@ -120,10 +120,10 @@ export function RoutineDetailView(props: {<CopyIcon class="size-4" />Duplicate</Dropdown.Item>- <Show when={props.onShareTemplate}>- <Dropdown.Item onSelect={props.onShareTemplate}>+ <Show when={props.onShare}>+ <Dropdown.Item onSelect={props.onShare}><ShareIcon class="size-4" />- Share as template+ Share</Dropdown.Item></Show><Show when={isOwned()}>diff --git a/apps/web/src/features/routines/views/share-template-dialog.tsx b/apps/web/src/features/routines/views/share-template-dialog.tsxindex ed2576338b..89471601fe 100644--- a/apps/web/src/features/routines/views/share-template-dialog.tsx+++ b/apps/web/src/features/routines/views/share-template-dialog.tsx@@ -1,212 +1,115 @@-import ArrowsClockwiseIcon from '@icon/system/regular/arrows-clockwise.svg';-import CheckIcon from '@icon/system/regular/check.svg';-import LinkIcon from '@icon/system/regular/link.svg';-import LockIcon from '@icon/system/regular/lock-simple.svg';-import type {- RoutineTemplate,- TemplateVariable,- VariableFill,-} from '@service-scheduled-action/generated/schemas';+import { EntityIcon } from '@core/component/EntityIcon';import {- ActionDialogShell,- Badge,- Button,- Card,- Dialog,- Input,- Tabs,-} from '@ui';-import { For, type JSX, Show } from 'solid-js';-import {- TemplateReferenceChip,- variableLabel,-} from '../components/template-reference';-import { variableKey } from '../core/template';--function fillOptions(variable: TemplateVariable) {- if (variable.kind === 'time_zone')- return [- { value: 'activator' as const, label: 'Their time zone' },- { value: 'shared' as const, label: `Keep ${variable.timezone}` },- ];- return [- ...(variable.kind === 'user'- ? [{ value: 'activator' as const, label: 'The person activating' }]- : []),- { value: 'shared' as const, label: 'Same for everyone' },- { value: 'choice' as const, label: 'They choose' },- ];-}--function VariableRow(props: {- variable: TemplateVariable;- disabled: boolean;- onFill(fill: VariableFill): void;-}) {- return (- <div class="flex flex-wrap items-center justify-between gap-2 py-1.5">- <TemplateReferenceChip- variable={props.variable}- state={props.variable.fill === 'activator' ? 'fills_in' : 'works'}- />- <Tabs- aria-label={`How ${variableLabel(props.variable)} fills in`}- size="sm"- wrap- disabled={props.disabled}- options={fillOptions(props.variable)}- value={props.variable.fill}- onChange={props.onFill}- />- </div>- );-}--function ShareNote(props: { icon: JSX.Element; children: JSX.Element }) {- return (- <li class="flex gap-2 text-sm text-ink-muted">- <span class="mt-0.5 shrink-0">{props.icon}</span>- <span>{props.children}</span>- </li>- );-}+ ShareCard,+ ShareDialogFrame,+ ShareDialogTitle,+} from '@core/component/TopBar/ShareDialogFrame';+import { isMobile } from '@core/mobile/isMobile';+import CopyIcon from '@icon/system/regular/copy.svg';+import type { RoutineTemplate } from '@service-scheduled-action/generated/schemas';+import { Button, cn } from '@ui';+import { type JSX, Show } from 'solid-js';/**- * Sharing a routine as a template: the owner generalizes its references,- * publishes the snapshot, and passes the link on. Their routine itself is- * never shared.+ * A routine's Share menu. Sending it or copying its link shares the routine's+ * current setup; each person who opens it can activate their own copy.*/-export function ShareTemplateDialog(props: {+export function ShareRoutineDialog(props: {open: boolean;onOpenChange(open: boolean): void;name: string;/** `undefined` while loading, `null` when not shared yet. */template: RoutineTemplate | null | undefined;- description: string;- onDescription(description: string): void;- variables: readonly TemplateVariable[];- onFill(key: string, fill: VariableFill): void;pending: boolean;- error?: string;- onShare(): void;- onUnshare(): void;onCopyLink(): void;- /** Posts the template to a channel or person; shown once it's shared. */+ onStopSharing(): void;+ /** The standard send form: recipients, optional message, Share. */send: JSX.Element;+ /** The send form's submit, which phones show beside the title. */+ sendAction?: { canSubmit(): boolean; submit(): void };}) {+ const shared = () => Boolean(props.template);return (- <Dialog- open={props.open}- onOpenChange={props.onOpenChange}- position="center"- class="w-[min(40rem,calc(100vw-2rem))]"- visibleScrim- >- <div class="contents">- <ActionDialogShell hideBorder class="max-h-[85dvh] bg-transparent">- <ActionDialogShell.Body class="flex flex-col gap-5 space-y-0">- <ActionDialogShell.Header class="flex flex-wrap items-center gap-2 space-y-0">- <ActionDialogShell.Title class="text-base">- Share: {props.name}- </ActionDialogShell.Title>- <Badge variant="outline" size="xs">- As a template- </Badge>- </ActionDialogShell.Header>- <Card>- <Card.Body>- <p class="font-medium">- People get a template, not your routine- </p>- <ul class="mt-2 flex flex-col gap-1.5">- <ShareNote icon={<CheckIcon class="size-4 text-success" />}>- They see your instructions and triggers, and can activate- their own copy that runs as them.- </ShareNote>- <ShareNote icon={<LockIcon class="size-4" />}>- Your routine, its runs and its results stay private to you.- </ShareNote>- <ShareNote icon={<ArrowsClockwiseIcon class="size-4" />}>- Sharing again updates the template with your routine's- current setup.- </ShareNote>- </ul>- </Card.Body>- </Card>- <label class="flex flex-col gap-1.5 text-sm">- <span class="font-medium">Description</span>- <Input- value={props.description}- placeholder="What does this routine do for someone?"- maxLength={1000}- disabled={props.pending}- onInput={(event) =>- props.onDescription(event.currentTarget.value)- }- />- </label>- <Show when={props.variables.length > 0}>- <section class="flex flex-col gap-1">- <h3 class="text-sm font-medium">- What changes for each person- </h3>- <div class="divide-y divide-edge-divider">- <For each={props.variables}>- {(variable) => (- <VariableRow- variable={variable}- disabled={props.pending}- onFill={(fill) =>- props.onFill(variableKey(variable), fill)- }- />- )}- </For>- </div>- </section>- </Show>- <Show when={props.template}>- {(template) => (- <section class="flex flex-col gap-2">- <h3 class="text-sm font-medium">- Shared · active for {template().active_count}- </h3>- {props.send}- </section>+ <ShareDialogFrame open={props.open} onOpenChange={props.onOpenChange}>+ <ShareCard+ header={+ <div class="flex w-full min-w-0 items-center justify-between gap-2">+ <ShareDialogTitle+ icon={+ <EntityIcon targetType="routine" size="sm" class="shrink-0" />+ }+ name={props.name}+ />+ <Show when={isMobile() && props.sendAction}>+ {(action) => (+ <Button+ variant="primary"+ size="sm"+ class="shrink-0"+ disabled={!action().canSubmit()}+ onClick={() => action().submit()}+ >+ Share+ </Button>)}</Show>- <Show when={props.error}>- <p class="text-sm text-failure" role="alert">- {props.error}- </p>- </Show>- </ActionDialogShell.Body>- <ActionDialogShell.Footer class="justify-between">- <Show when={props.template} fallback={<span />}>- <div class="flex flex-wrap gap-2">- <Button variant="secondary" onClick={() => props.onCopyLink()}>- <LinkIcon class="size-4" />- Copy template link- </Button>+ </div>+ }+ >+ {props.send}+ </ShareCard>+ <ShareCard>+ <div class="flex flex-col gap-3 p-4 text-sm text-ink">+ <div class="flex flex-wrap items-center justify-between gap-3">+ <div class="flex items-center gap-2">+ <span class="font-medium">Anyone with the link</span>+ <div+ class={cn(+ 'flex items-center justify-center rounded-xl border px-2 py-0.5',+ shared()+ ? 'border-accent/30 bg-accent/10 text-accent'+ : 'border-edge-muted bg-edge-muted text-ink-extra-muted'+ )}+ >+ <span class="text-xs font-medium whitespace-nowrap">+ {shared() ? 'Shared' : 'Just me'}+ </span>+ </div>+ </div>+ <div class="flex items-center gap-2">+ <Show when={shared()}><Button- variant="danger"+ variant="ghost"disabled={props.pending}- onClick={() => props.onUnshare()}+ onClick={() => props.onStopSharing()}>Stop sharing</Button>- </div>- </Show>- <Button- variant="primary"- disabled={props.pending || props.template === undefined}- onClick={() => props.onShare()}+ </Show>+ <Button+ variant="secondary"+ disabled={props.pending || props.template === undefined}+ onClick={() => props.onCopyLink()}+ >+ <CopyIcon class="size-4" />+ <span>Copy Link</span>+ </Button>+ </div>+ </div>+ <p class="text-ink-muted">+ <Show+ when={props.template}+ fallback="People you share with can activate their own copy. Your runs stay private.">- {props.template ? 'Update template' : 'Share template'}- </Button>- </ActionDialogShell.Footer>- </ActionDialogShell>- </div>- </Dialog>+ {(template) =>+ template().active_count === 1+ ? 'Active for 1 person. Your runs stay private.'+ : `Active for ${template().active_count} people. Your runs stay private.`+ }+ </Show>+ </p>+ </div>+ </ShareCard>+ </ShareDialogFrame>);}diff --git a/apps/web/src/lib/core/component/ForwardToChannel.test.tsx b/apps/web/src/lib/core/component/ForwardToChannel.test.tsxindex 9012e8c82d..8f3a302d2f 100644--- a/apps/web/src/lib/core/component/ForwardToChannel.test.tsx+++ b/apps/web/src/lib/core/component/ForwardToChannel.test.tsx@@ -625,3 +625,44 @@ describe('forwarding image attachments', () => {});});++describe('forwarding an inline reference', () => {+ it('prepares each destination and sends the reference in the text, not as an attachment', async () => {+ const prepare = vi.fn().mockResolvedValue(undefined);+ const onSubmit = vi.fn();+ mocks.sendToChannel.mockImplementation(async ({ beforeSend }) => {+ await beforeSend('channel-1');+ return { channelId: 'channel-1', navigateToChannel: vi.fn() };+ });+ let submit: (() => void) | undefined;+ render(() => (+ <ForwardToChannel+ name="Weekly digest"+ entity={{ entity_type: 'automation', entity_id: 'routine-1' }}+ inlineReference={{+ markdown: '<m-document-mention>routine-1</m-document-mention>',+ mention: { entity_type: 'automation', entity_id: 'routine-1' },+ }}+ prepareChannel={prepare}+ onSubmit={onSubmit}+ ref={(controls) => {+ submit = controls.handleSubmit;+ }}+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Select recipients' }));++ await submit?.();++ expect(prepare).toHaveBeenCalledWith('channel-1', 'view');+ expect(mocks.sendToChannel).toHaveBeenCalledWith(+ expect.objectContaining({+ channelId: 'channel-1',+ content: '<m-document-mention>routine-1</m-document-mention>',+ mentions: [{ entity_type: 'automation', entity_id: 'routine-1' }],+ attachments: [],+ })+ );+ expect(onSubmit).toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/core/component/ForwardToChannel.tsx b/apps/web/src/lib/core/component/ForwardToChannel.tsxindex f4b402181f..9fdaa57e43 100644--- a/apps/web/src/lib/core/component/ForwardToChannel.tsx+++ b/apps/web/src/lib/core/component/ForwardToChannel.tsx@@ -29,6 +29,7 @@ import {import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';import type { NewAttachment } from '@service-storage/generated/schemas/newAttachment';import type { SharePermissionV2ChannelSharePermissions } from '@service-storage/generated/schemas/sharePermissionV2ChannelSharePermissions';+import type { SimpleMention } from '@service-storage/generated/schemas/simpleMention';import { Button, cn, Hotkey } from '@ui';import {type Accessor,@@ -190,6 +191,11 @@ interface ForwardToChannelProps {allowedAccessLevels?: readonly AccessLevel[];/** Attach an entity that has no block, instead of `blockId`/`blockName`. */entity?: NewAttachment;+ /**+ * Reference `entity` in the message text instead of attaching it, for+ * entities messages show only as mentions (routines).+ */+ inlineReference?: { markdown: string; mention: SimpleMention };/*** Grant the destination before the message is sent, for entities that* sending does not grant. Rejecting cancels that delivery.@@ -364,9 +370,20 @@ export function ForwardToChannel(props: ForwardToChannelProps) {) {const prepare = props.prepareChannel;const composed = composer.message();+ const inline = props.inlineReference;const message = {...composed,- attachments: [asAttachment(), ...(composed.attachments ?? [])],+ ...(inline+ ? {+ content: [composed.content.trim(), inline.markdown]+ .filter(Boolean)+ .join('\n\n'),+ mentions: [...composed.mentions, inline.mention],+ attachments: composed.attachments ?? [],+ }+ : {+ attachments: [asAttachment(), ...(composed.attachments ?? [])],+ }),beforeSend:prepare &&((id: string) =>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsxindex 05d0bfdc8e..1a095bd9b4 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx@@ -35,6 +35,20 @@ vi.mock('@app/features/crm/record-adapter', () => ({},}));+vi.mock('@app/features/routines/routine-mentions', () => ({+ useRoutineMentionSource:+ (_searchTerm: () => string, enabled: () => boolean) => () =>+ enabled()+ ? [+ {+ kind: 'routine',+ id: 'routine-1',+ data: { id: 'routine-1', name: 'Weekly digest' },+ },+ ]+ : [],+}));+vi.mock('@app/lib/analytics/analytics-context', () => ({useAnalytics: () => ({ track: vi.fn() }),}));@@ -516,3 +530,38 @@ it("offers the viewer's own WhatsApp chats to share by mention, only in channelexpect(screen.queryByText('WhatsApp chats')).toBeNull();expect(mocks.whatsappUserIds.every((id) => id === '')).toBe(true);});++it("offers the viewer's routines to share by mention, only in channel composers", () => {+ Element.prototype.scrollIntoView = vi.fn();+ vi.mocked(useEmailSearchMention).mockReturnValue({+ emails: () => [],+ totalCount: () => 0,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ } as unknown as ReturnType<typeof useEmailSearchMention>);+ const menu = createMenuOperations();+ menu.openMenu();+ render(() => (+ <MentionsMenu+ menu={menu}+ users={() => []}+ block="channel"+ anchor={document.createElement('div')}+ onPick={vi.fn()}+ />+ ));+ expect(screen.getByText('Routines')).toBeTruthy();+ expect(screen.getByText('Weekly digest')).toBeTruthy();+ cleanup();++ render(() => (+ <MentionsMenu+ menu={menu}+ users={() => []}+ anchor={document.createElement('div')}+ onPick={vi.fn()}+ />+ ));+ expect(screen.queryByText('Routines')).toBeNull();+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex a0050b8ef3..14700d40f5 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -1,5 +1,6 @@import { useCrmContactMentionSource } from '@app/features/crm/record-adapter';import { externalChatApi } from '@app/features/external-chat/queries/production-api';+import { useRoutineMentionSource } from '@app/features/routines/routine-mentions';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { globalSplitManager } from '@app/signal/splitLayout';import type { BlockName } from '@core/block';@@ -293,6 +294,16 @@ function MentionsMenuInner(props: MentionsMenuProps) {}));});+ // Mentioning a routine in a channel shares it with the channel's members.+ const routines = useRoutineMentionSource(+ searchTerm,+ () =>+ !hasCustomEntities() &&+ props.block === 'channel' &&+ props.menu.isOpen() &&+ (!props.sources || props.sources.includes('routines'))+ );+const dateOptions = useDateSearch({ query: searchTerm });const dates = createLazyMemo((): DateMentionItem[] => {return dateOptions().map(@@ -382,6 +393,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {...(sourceEnabled('documents') ? (docs() ?? []) : []),...(sourceEnabled('channels') ? (channels() ?? []) : []),...externalChats(),+ ...routines(),...(sourceEnabled('agentSessions') ? agentSessions() : []),...(sourceEnabled('companies') ? (companies() ?? []) : []),...(sourceEnabled('emails') ? (emails() ?? []) : []),@@ -409,6 +421,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {(sourceEnabled('agentSessions') ? agentSessions().length : 0) +(sourceEnabled('channels') ? channelsMention.totalCount() : 0) +externalChats().length ++ routines().length +(sourceEnabled('companies')? (companyMention?.totalCount() ?? 0): 0) +@@ -495,6 +508,12 @@ function MentionsMenuInner(props: MentionsMenuProps) {getData: externalChats,getFullCount: () => externalChats().length,},+ {+ id: 'routines',+ label: 'Routines',+ getData: routines,+ getFullCount: () => routines().length,+ },{id: 'agentSessions',label: 'Recent agent sessions',diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.tsindex 6b3ea9ebf6..554bc0eb85 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts@@ -8,6 +8,7 @@ export type MentionBucketId =| 'users'| 'documents'| 'externalChats'+ | 'routines'| 'agentSessions'| 'channels'| 'companies'diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsxindex 98b5085ff0..ccb78d9f97 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/MentionsMenuItem.tsx@@ -95,6 +95,8 @@ export function MentionsMenuItem(props: {case 'calendarEvent':return <EntityIcon targetType="calendar" size="xs" />;+ case 'routine':+ return <EntityIcon targetType="routine" size="xs" />;case 'entity':if (props.item.bucket === 'email') {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.tsindex ba40663fa8..fb47fef2b8 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts@@ -62,6 +62,7 @@ export function getMentionItemName(item: MentionItem): string {case 'entity':return item.data.name ?? (item.bucket === 'email' ? 'No Subject' : '');case 'externalChat':+ case 'routine':return item.data.name;}}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.tsindex dc58bb5499..6d52e8797e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts@@ -53,7 +53,8 @@ function getMentionName(item: MentionItem): string {if (item.kind === 'group') return item.data.groupAlias;if (item.kind === 'bookingLink' || item.kind === 'calendarEvent')return item.data.title;- if (item.kind === 'externalChat') return item.data.name;+ if (item.kind === 'externalChat' || item.kind === 'routine')+ return item.data.name;return item.searchText;}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.tsindex cca4a41dd0..292931a735 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts@@ -1,7 +1,9 @@+import { toast } from '@core/component/Toast/Toast';import type { EntityItem } from '@core/context/quickAccess';import { trackMention } from '@core/signal/mention';import type { DateOption } from '@core/util/dateSearch/useDateSearch';import type { ChannelEntity, CrmCompanyEntity, EmailEntity } from '@entity';+import { Telemetry } from '@macro-inc/observability';import { match } from 'ts-pattern';import { REMOVE_INLINE_SEARCH_COMMAND } from '../../../../plugins';import {@@ -230,6 +232,45 @@ async function handleExternalChatMention(});}+/**+ * Mentioning your routine shares it as a template: everyone who can read the+ * message can activate their own copy from its card. The chip goes in only+ * once the template reflects the routine's current setup.+ */+async function handleRoutineMention(+ routine: { id: string; name: string },+ dependencies: HandlerDependencies+): Promise<void> {+ const shared = await Telemetry.span(+ 'routine.template.share',+ async (span) => {+ span.setAttr('routine.id', routine.id);+ span.setAttr('routine.template.source', 'mention');+ try {+ const { publishRoutineTemplate } = await import(+ '@app/features/routines/queries/templates'+ );+ await publishRoutineTemplate(routine.id);+ return true;+ } catch {+ span.error('Sharing the routine failed');+ return false;+ }+ }+ );+ if (!shared) {+ toast.failure('Could not share this routine', {+ subtext: 'Please try again',+ });+ return;+ }+ dependencies.editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {+ documentId: routine.id,+ documentName: routine.name,+ blockName: 'routine',+ });+}+/*** Creates a handler for MentionItem selection.*/@@ -260,6 +301,8 @@ export function createItemHandler(dependencies: HandlerDependencies) {return await handleEntityMention(item, dependencies);case 'externalChat':return await handleExternalChatMention(item.data, dependencies);+ case 'routine':+ return await handleRoutineMention(item.data, dependencies);}};}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.tsindex b8e198c17e..45b406529a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils/mentionsUtils.ts@@ -426,6 +426,13 @@ export type ExternalChatMentionItem = {data: { id: string; name: string; provider: ExternalChatProvider };};+/** One of the viewer's routines; mentioning it in a channel shares it. */+export type RoutineMentionItem = {+ kind: 'routine';+ id: string;+ data: { id: string; name: string };+};+export type MentionItem =| QuickAccessItem| DateMentionItem@@ -433,7 +440,8 @@ export type MentionItem =| AgentSessionMentionItem| BookingLinkMentionItem| CalendarEventMentionItem- | ExternalChatMentionItem;+ | ExternalChatMentionItem+ | RoutineMentionItem;/*** Type guard for DateMentionItem.diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex 03c097b859..8a4f6be2d3 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -76,7 +76,6 @@ import IconEdit from '@icon/system/regular/pencil.svg';import UserCircle from '@icon/system/regular/user-circle.svg';import UsersIcon from '@icon/system/regular/users.svg';import IconX from '@icon/system/regular/x.svg';-import { Dialog } from '@kobalte/core/dialog';import { updateAgentSessionSharePermissions } from '@queries/agent-session/share-permissions';import {setCallRecordTeamShareCache,@@ -165,6 +164,7 @@ import {type TeamShareScope,teamShareScopeOptionsForItem,} from './linkShare';+import { ShareDialogFrame, ShareDialogTitle } from './ShareDialogFrame';false && clickOutside;@@ -1853,355 +1853,334 @@ export function ShareModal(props: ShareModalProps) {/>}>- <Dialog onOpenChange={props.onOpenChange} open={props.open}>- <Dialog.Portal>- <Dialog.Overlay class="z-modal fixed inset-0 scrim-glass" />- <div class="z-modal fixed inset-0">- <Dialog.Content- class="max-w-[calc(100vw-16px)] mt-20 sm:mt-40 mx-auto overflow-y-auto scrollbar-hidden portal-scope isolate flex flex-col gap-2 *:max-h-[75vh]"- style={{ width: '800px' }}- >- {/* Card 1: Share form — gradient border */}- <Panel- depth={2}- hideBorder- class="elevated-surface rounded-[24px] bg-dialog"- >- <Panel.Header class="px-4">- <Dialog.Title class="flex items-center gap-1.5 min-w-0 overflow-hidden whitespace-nowrap w-full text-sm font-medium">- <span class="shrink-0">Share:</span>- <EntityIcon- targetType={props.blockAlias}- size="sm"- class="shrink-0"+ <ShareDialogFrame open={props.open} onOpenChange={props.onOpenChange}>+ {/* Card 1: Share form — gradient border */}+ <Panel+ depth={2}+ hideBorder+ class="elevated-surface rounded-[24px] bg-dialog"+ >+ <Panel.Header class="px-4">+ <ShareDialogTitle+ icon={+ <EntityIcon+ targetType={props.blockAlias}+ size="sm"+ class="shrink-0"+ />+ }+ name={props.name}+ />+ </Panel.Header>+ <Panel.Body>+ <Show when={!canForward() && !directSharingOwner()}>+ <p class="px-4 py-3 text-sm text-ink-muted">+ {RESTRICTED_SHARE_DESCRIPTIONS[props.itemType]}+ </p>+ </Show>+ <Show when={directSharingOwner()}>+ <DirectAccessInvite+ source={requests}+ description="Invite someone to read this conversation. Sending requires their own connected account."+ />+ </Show>+ <Show when={canForward()}>+ <AfterFirstPaint fallback={<ShareFormSkeleton />}>+ <ForwardToChannel+ {...forwardTarget(+ props.blockAlias,+ props.id,+ setChannelPermissions+ )}+ editPermissionEnabled={editPermissionEnabled()}+ submitPermissionInfo={{+ setChannelPermissions: (id, accessLevel) =>+ setChannelPermissions(id, accessLevel, true),+ userPermissions: recipientPermissions(),+ channelSharePermissions: recipients(),+ }}+ onSubmit={() => props.onOpenChange(false)}+ onCancel={() => props.onOpenChange(false)}+ refetch={refetch}+ name={props.name}+ hideAccessLevelSelector={props.itemType === 'email'}+ initialAccessLevel={+ props.itemType === 'email' ? 'view' : null+ }+ allowedAccessLevels={shareLevelsFor(+ props.itemType,+ props.blockAlias+ )}+ />+ </AfterFirstPaint>+ </Show>+ <Show when={!canForward()}>+ <div class="flex justify-end px-4 py-3">+ <Button variant="secondary" onClick={copyLink}>+ <CopyIcon class="size-4" />+ <span>Copy Link</span>+ </Button>+ </div>+ </Show>+ </Panel.Body>+ </Panel>++ <AccessRequestError source={requests} />+ <Show+ when={+ requests.state()?.canReview &&+ (requests.state()?.pendingCount ?? 0) > 0+ }+ >+ <Panel+ depth={2}+ hideBorder+ class="elevated-surface rounded-[24px] bg-dialog"+ >+ <Panel.Body>+ <PermissionRequestsView source={requests} />+ </Panel.Body>+ </Panel>+ </Show>++ {/* Card 2: Recipients — plain border */}+ <Show+ when={+ (recipients()?.length ?? 0) > 0 ||+ !!(props.owner ?? requests.state()?.owner) ||+ permissionsLoading()+ }+ >+ <Panel+ depth={2}+ hideBorder+ class="elevated-surface rounded-[24px] bg-dialog"+ >+ <Panel.Header class="px-4">+ <span class="text-sm font-medium">+ <Show when={!ownerOnlyRoster()} fallback="Owner">+ People with access to this {getShareItemNoun(props.itemType)}+ </Show>+ </span>+ </Panel.Header>+ <Panel.Body class="text-ink">+ <div class="relative">+ <ScrollIndicators+ scrollRef={recipientScrollRef}+ noBorderStart+ noBorderEnd+ />+ <CustomScrollbar scrollContainer={recipientScrollRef} />+ <div+ class="overflow-y-auto scrollbar-hidden max-h-[calc(27vh-40px)]"+ ref={setRecipientScrollRef}+ >+ <div class="grid gap-3 text-ink text-sm select-none p-4">+ <Show when={props.owner ?? requests.state()?.owner}>+ <div class="flex justify-between">+ <div class="flex items-center gap-2 overflow-hidden font-medium">+ <OwnerLabel+ ownerId={+ props.owner ??+ requests.state()?.owner ??+ undefined+ }+ viewerLabel="Me"+ />+ </div>+ <div class="flex items-center">+ <div class="font-medium text-ink-muted text-xs">+ Owner+ </div>+ </div>+ </div>+ </Show>+ <RequestAccessView+ source={requests}+ allowedLevels={requestLevels()}/>- <span class="truncate">{props.name}</span>- </Dialog.Title>- </Panel.Header>- <Panel.Body>- <Show when={!canForward() && !directSharingOwner()}>- <p class="px-4 py-3 text-sm text-ink-muted">- {RESTRICTED_SHARE_DESCRIPTIONS[props.itemType]}- </p>- </Show>- <Show when={directSharingOwner()}>- <DirectAccessInvite+ <DirectAccessViewsource={requests}- description="Invite someone to read this conversation. Sending requires their own connected account."+ exclude={props.directPeopleIds}/>- </Show>- <Show when={canForward()}>- <AfterFirstPaint fallback={<ShareFormSkeleton />}>- <ForwardToChannel- {...forwardTarget(- props.blockAlias,- props.id,- setChannelPermissions- )}- editPermissionEnabled={editPermissionEnabled()}- submitPermissionInfo={{- setChannelPermissions: (id, accessLevel) =>- setChannelPermissions(id, accessLevel, true),- userPermissions: recipientPermissions(),- channelSharePermissions: recipients(),- }}- onSubmit={() => props.onOpenChange(false)}- onCancel={() => props.onOpenChange(false)}- refetch={refetch}- name={props.name}- hideAccessLevelSelector={props.itemType === 'email'}- initialAccessLevel={- props.itemType === 'email' ? 'view' : null- }- allowedAccessLevels={shareLevelsFor(- props.itemType,- props.blockAlias- )}- />- </AfterFirstPaint>- </Show>- <Show when={!canForward()}>- <div class="flex justify-end px-4 py-3">- <Button variant="secondary" onClick={copyLink}>- <CopyIcon class="size-4" />- <span>Copy Link</span>- </Button>- </div>- </Show>- </Panel.Body>- </Panel>-- <AccessRequestError source={requests} />- <Show- when={- requests.state()?.canReview &&- (requests.state()?.pendingCount ?? 0) > 0- }- >- <Panel- depth={2}- hideBorder- class="elevated-surface rounded-[24px] bg-dialog"- >- <Panel.Body>- <PermissionRequestsView source={requests} />- </Panel.Body>- </Panel>- </Show>-- {/* Card 2: Recipients — plain border */}- <Show- when={- (recipients()?.length ?? 0) > 0 ||- !!(props.owner ?? requests.state()?.owner) ||- permissionsLoading()- }- >- <Panel- depth={2}- hideBorder- class="elevated-surface rounded-[24px] bg-dialog"- >- <Panel.Header class="px-4">- <span class="text-sm font-medium">- <Show when={!ownerOnlyRoster()} fallback="Owner">- People with access to this{' '}- {getShareItemNoun(props.itemType)}- </Show>- </span>- </Panel.Header>- <Panel.Body class="text-ink">- <div class="relative">- <ScrollIndicators- scrollRef={recipientScrollRef}- noBorderStart- noBorderEnd- />- <CustomScrollbar scrollContainer={recipientScrollRef} />- <div- class="overflow-y-auto scrollbar-hidden max-h-[calc(27vh-40px)]"- ref={setRecipientScrollRef}- >- <div class="grid gap-3 text-ink text-sm select-none p-4">- <Show when={props.owner ?? requests.state()?.owner}>- <div class="flex justify-between">- <div class="flex items-center gap-2 overflow-hidden font-medium">- <OwnerLabel- ownerId={- props.owner ??- requests.state()?.owner ??- undefined+ <Dynamic component={props.people} />+ <Show when={permissionsLoading()}>+ <RecipientsSkeleton />+ </Show>+ <For each={recipients() || []}>+ {(recipient) => (+ <div class="flex justify-between">+ <div+ class="flex items-center gap-2 overflow-hidden"+ onClick={() =>+ navigateToChannel(recipient.channel_id)+ }+ >+ <Switch+ fallback={<UsersIcon class="shrink-0 size-4" />}+ >+ <Match+ when={+ channelNameMap().get(recipient.channel_id)+ ?.type === 'direct_message'+ }+ >+ <DmRecipientIcon+ channelId={recipient.channel_id}+ />+ </Match>+ <Match+ when={channelNameMap().get(+ recipient.channel_id+ )}+ >+ <UsersIcon class="shrink-0 size-4" />+ </Match>+ </Switch>+ <div class="font-medium truncate">+ <Show+ when={+ channelNameMap().get(recipient.channel_id)+ ?.type !== 'direct_message'+ }+ fallback={+ channelNameMap().get(recipient.channel_id)+ ?.name || 'Conversation'+ }+ >+ <GroupChannelLabel+ channelId={recipient.channel_id}+ fallbackName={+ channelNameMap().get(recipient.channel_id)+ ?.name || 'Conversation'}- viewerLabel="Me"/>- </div>- <div class="flex items-center">- <div class="font-medium text-ink-muted text-xs">- Owner- </div>- </div>+ </Show></div>- </Show>- <RequestAccessView- source={requests}- allowedLevels={requestLevels()}- />- <DirectAccessView- source={requests}- exclude={props.directPeopleIds}- />- <Dynamic component={props.people} />- <Show when={permissionsLoading()}>- <RecipientsSkeleton />- </Show>- <For each={recipients() || []}>- {(recipient) => (- <div class="flex justify-between">- <div- class="flex items-center gap-2 overflow-hidden"- onClick={() =>- navigateToChannel(recipient.channel_id)- }- >- <Switch- fallback={- <UsersIcon class="shrink-0 size-4" />- }- >- <Match- when={- channelNameMap().get(- recipient.channel_id- )?.type === 'direct_message'- }- >- <DmRecipientIcon- channelId={recipient.channel_id}- />- </Match>- <Match- when={channelNameMap().get(- recipient.channel_id- )}- >- <UsersIcon class="shrink-0 size-4" />- </Match>- </Switch>- <div class="font-medium truncate">- <Show- when={- channelNameMap().get(- recipient.channel_id- )?.type !== 'direct_message'- }- fallback={- channelNameMap().get(- recipient.channel_id- )?.name || 'Conversation'- }- >- <GroupChannelLabel- channelId={recipient.channel_id}- fallbackName={- channelNameMap().get(- recipient.channel_id- )?.name || 'Conversation'- }- />- </Show>- </div>- <Show when={props.itemType === 'form'}>- <span class="shrink-0 text-xs text-ink-muted">- Can respond (channel)- </span>- </Show>- </div>- <div class="flex items-center">- <ShareOptions- editPermissionEnabled={editPermissionEnabled()}- allowedAccessLevels={shareLevelsFor(- props.itemType,- props.blockAlias- )}- disabled={- recipientPermissions() !==- Permissions.OWNER- }- permissions={recipient.access_level}- setPermissions={(accessLevel) => {- if (accessLevel === null) {- fireAndForget(- removeChannelAccess(- recipient.channel_id- ),- 'share-modal'- );- } else if (- accessLevel !== recipient.access_level- ) {- fireAndForget(- setChannelPermissions(- recipient.channel_id,- accessLevel- ),- 'share-modal'- );- }- }}- />- </div>- </div>- )}- </For>+ <Show when={props.itemType === 'form'}>+ <span class="shrink-0 text-xs text-ink-muted">+ Can respond (channel)+ </span>+ </Show>+ </div>+ <div class="flex items-center">+ <ShareOptions+ editPermissionEnabled={editPermissionEnabled()}+ allowedAccessLevels={shareLevelsFor(+ props.itemType,+ props.blockAlias+ )}+ disabled={+ recipientPermissions() !== Permissions.OWNER+ }+ permissions={recipient.access_level}+ setPermissions={(accessLevel) => {+ if (accessLevel === null) {+ fireAndForget(+ removeChannelAccess(recipient.channel_id),+ 'share-modal'+ );+ } else if (+ accessLevel !== recipient.access_level+ ) {+ fireAndForget(+ setChannelPermissions(+ recipient.channel_id,+ accessLevel+ ),+ 'share-modal'+ );+ }+ }}+ />+ </div></div>- </div>- </div>- </Panel.Body>- </Panel>- </Show>+ )}+ </For>+ </div>+ </div>+ </div>+ </Panel.Body>+ </Panel>+ </Show>- {/* Card 3: Link sharing — plain border */}- <Show- when={- props.open &&- meetingNotesFlag().enabled &&- props.blockAlias === 'md' &&- props.itemType === 'document' &&- !!userId() &&- (props.owner ?? requests.state()?.owner) === userId()- }- >- <DocumentMeetingNotes- documentId={props.id}- onAccessState={setMeetingAccess}- />- </Show>+ {/* Card 3: Link sharing — plain border */}+ <Show+ when={+ props.open &&+ meetingNotesFlag().enabled &&+ props.blockAlias === 'md' &&+ props.itemType === 'document' &&+ !!userId() &&+ (props.owner ?? requests.state()?.owner) === userId()+ }+ >+ <DocumentMeetingNotes+ documentId={props.id}+ onAccessState={setMeetingAccess}+ />+ </Show>+ <Show+ when={+ props.linkSharing ||+ (userPermissions() === Permissions.OWNER &&+ !isLinkSharingDisabledForItem(props.itemType))+ }+ >+ <Panel+ depth={2}+ hideBorder+ class="elevated-surface rounded-[24px] bg-dialog"+ >+ <Panel.Body><Show- when={- props.linkSharing ||- (userPermissions() === Permissions.OWNER &&- !isLinkSharingDisabledForItem(props.itemType))+ when={props.linkSharing}+ fallback={+ <LinkSharingControls+ allowedAccessLevels={shareLevelsFor(+ props.itemType,+ props.blockAlias+ )}+ loading={permissionsLoading()}+ meetingAccess={meetingAccessForSharing()}+ editPermissionEnabled={editPermissionEnabled()}+ linkShare={linkShare()}+ linkShareAccessLevel={linkShareAccessLevel()}+ hasExplicitShares={+ (recipients()?.length ?? 0) > 0 ||+ !!props.hasDirectShares ||+ requests.grants().length > 0+ }+ setLinkShareScope={setLinkShareScope}+ setLinkShareAccessLevel={setLinkShareAccessLevel}+ copyLink={copyLink}+ teamShare={teamShareControls()}+ />}>- <Panel- depth={2}- hideBorder- class="elevated-surface rounded-[24px] bg-dialog"- >- <Panel.Body>- <Show- when={props.linkSharing}- fallback={- <LinkSharingControls- allowedAccessLevels={shareLevelsFor(- props.itemType,- props.blockAlias- )}- loading={permissionsLoading()}- meetingAccess={meetingAccessForSharing()}- editPermissionEnabled={editPermissionEnabled()}- linkShare={linkShare()}- linkShareAccessLevel={linkShareAccessLevel()}- hasExplicitShares={- (recipients()?.length ?? 0) > 0 ||- !!props.hasDirectShares ||- requests.grants().length > 0- }- setLinkShareScope={setLinkShareScope}- setLinkShareAccessLevel={setLinkShareAccessLevel}- copyLink={copyLink}- teamShare={teamShareControls()}- />- }- >- <div class="p-4">- <Dynamic component={props.linkSharing} />- </div>- </Show>- </Panel.Body>- </Panel>- </Show>- <Show- when={teamShareOnOwnCard(props.itemType, teamShareControls())}- >- {(teamShare) => (- <Panel- depth={2}- hideBorder- class="elevated-surface rounded-[24px] bg-dialog"- >- <Panel.Body>- <div class="p-4 text-sm text-ink">- <TeamAccessSection teamShare={teamShare()} />- </div>- </Panel.Body>- </Panel>- )}+ <div class="p-4">+ <Dynamic component={props.linkSharing} />+ </div></Show>- </Dialog.Content>- </div>- </Dialog.Portal>- </Dialog>+ </Panel.Body>+ </Panel>+ </Show>+ <Show when={teamShareOnOwnCard(props.itemType, teamShareControls())}>+ {(teamShare) => (+ <Panel+ depth={2}+ hideBorder+ class="elevated-surface rounded-[24px] bg-dialog"+ >+ <Panel.Body>+ <div class="p-4 text-sm text-ink">+ <TeamAccessSection teamShare={teamShare()} />+ </div>+ </Panel.Body>+ </Panel>+ )}+ </Show>+ </ShareDialogFrame></Show>);}diff --git a/apps/web/src/lib/core/component/TopBar/ShareDialogFrame.tsx b/apps/web/src/lib/core/component/TopBar/ShareDialogFrame.tsxnew file mode 100644index 0000000000..a9c35b4771--- /dev/null+++ b/apps/web/src/lib/core/component/TopBar/ShareDialogFrame.tsx@@ -0,0 +1,71 @@+import { isMobile } from '@core/mobile/isMobile';+import { Dialog as KobalteDialog } from '@kobalte/core/dialog';+import { cn, Panel } from '@ui';+import { Dialog } from '@ui/components/Dialog';+import type { JSX, ParentProps } from 'solid-js';+import { Show } from 'solid-js';++/**+ * The Share dialog's frame: a column of cards below the top of the window on+ * desktop, one drawer on phones.+ */+export function ShareDialogFrame(+ props: ParentProps<{ open: boolean; onOpenChange(open: boolean): void }>+) {+ return (+ <Show+ when={!isMobile()}+ fallback={+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>+ <div class="flex flex-col">{props.children}</div>+ </Dialog>+ }+ >+ <KobalteDialog onOpenChange={props.onOpenChange} open={props.open}>+ <KobalteDialog.Portal>+ <KobalteDialog.Overlay class="z-modal fixed inset-0 scrim-glass" />+ <div class="z-modal fixed inset-0">+ <KobalteDialog.Content+ class="max-w-[calc(100vw-16px)] mt-20 sm:mt-40 mx-auto overflow-y-auto scrollbar-hidden portal-scope isolate flex flex-col gap-2 *:max-h-[75vh]"+ style={{ width: '800px' }}+ >+ {props.children}+ </KobalteDialog.Content>+ </div>+ </KobalteDialog.Portal>+ </KobalteDialog>+ </Show>+ );+}++/** One card of the Share dialog; on phones, a section of its drawer. */+export function ShareCard(+ props: ParentProps<{ header?: JSX.Element; bodyClass?: string }>+) {+ return (+ <Panel+ depth={2}+ hideBorder+ class={cn(+ 'rounded-[24px] bg-dialog',+ isMobile() ? 'rounded-none bg-transparent' : 'elevated-surface'+ )}+ >+ <Show when={props.header}>+ <Panel.Header class="px-4">{props.header}</Panel.Header>+ </Show>+ <Panel.Body class={props.bodyClass}>{props.children}</Panel.Body>+ </Panel>+ );+}++/** The Share dialog's title: what is being shared. */+export function ShareDialogTitle(props: { icon: JSX.Element; name: string }) {+ return (+ <Dialog.Title class="flex items-center gap-1.5 min-w-0 overflow-hidden whitespace-nowrap w-full text-sm font-medium">+ <span class="shrink-0">Share:</span>+ {props.icon}+ <span class="truncate">{props.name}</span>+ </Dialog.Title>+ );+}diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex fe273d34ec..4f57594dd1 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -1155,7 +1155,8 @@ their history and do not repeat.An `m-document-mention` with `blockName: "routine"`, the returned routine ID,and the saved name renders as a clickable mention in an agent reply. Once theroutine is deleted the mention reads `Deleted` and clicking it shows a card-instead of opening the routine. Routines do not appear in the mention menu.+instead of opening the routine. Owners can mention their routines in channels+(see Routine templates).Only the owner sees a routine's editor and can edit, enable, run, duplicate,delete, or view run history. Anyone else who opens a routine link sees itstemplate when the owner shared one and routine sharing is enabled, and otherwise@@ -1176,18 +1177,20 @@ already activated copies keep working. `VITE_ENABLE_ROUTINE_SHARING` overridesonly the web gate; exercising templates needs the backend flag enabled too.A routine runs as its owner, so it is shared as a template, never directly.-The three-dot menu's **Share as template** opens **Share: name**. It explains-what people get, takes a **Description**, and lists **What changes for each-person**: every mention in the instructions plus the schedules' time zone, each-with tabs. People can be **The person activating** (the owner's own mention-starts here), **Same for everyone**, or **They choose**; items are **Same for-everyone** or **They choose**; the time zone is **Their time zone** or **Keep** the owner's-zone. **Share template** publishes a snapshot of the saved routine;-**Update template** re-snapshots it. Once shared, the dialog shows how many-routines were activated from it, a channel-or-people picker with **Send** that-posts the routine mention, **Copy template link** (the routine's own URL), and-**Stop sharing**, which hides the template while activated routines keep-running.+The three-dot menu's **Share** opens the standard Share dialog, **Share:+name**: a channel-or-people picker, an optional message, and **Share**, which+posts the routine mention; below it, **Anyone with the link** shows **Just me**+or **Shared** with the activation count, **Copy Link** (the routine's own URL),+and, once shared, **Stop sharing**, which hides the template while activated+routines keep running. Every Share and Copy Link first publishes a snapshot of+the saved routine. The owner's own mention and the schedules' time zone fill in+as whoever activates it; other references stay the same for everyone, and+re-sharing keeps the fills an earlier template set.++In a channel composer (including thread replies), the owner's routines appear+under **Routines** in the `@` menu. Picking one publishes its template the same+way, then inserts the mention, so everyone in the channel gets a card they can+activate from. If publishing fails, the mention is not inserted.Opening a shared routine someone else owns shows the template laid out like aroutine's Overview: **Activate for me** at the right of the top bar, then the