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): gate template sharing with PostHog (#9141)
Eric Hayes50ba9e4dd675
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex b2de458403..e570373760 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -4082,6 +4082,7 @@"crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry","crates/favorites",+ "crates/feature_flags","crates/fig_engine","crates/filter_ast","crates/folds/agent_fold",@@ -5212,6 +5213,7 @@"crates/entity_registry/shared_entity_registry","crates/external_chat","crates/favorites",+ "crates/feature_flags","crates/fig_engine","crates/filter_ast","crates/folds/agent_fold",@@ -8379,6 +8381,7 @@"crates/entity_registry/entity_registry","crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry",+ "crates/feature_flags","crates/fig_engine","crates/filter_ast","crates/folds/agent_fold",@@ -11690,6 +11693,7 @@"crates/entity_registry/entity_registry","crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry",+ "crates/feature_flags","crates/fig_engine","crates/filter_ast","crates/folds/agent_fold",diff --git a/Cargo.lock b/Cargo.lockindex 1d46fa56ca..cfd11d826a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -17298,6 +17298,7 @@ dependencies = ["entity_access_management","entity_registry","entity_registry_db_utils",+ "feature_flags","frecency","futures","jev",diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 1a1f767416..0af37fa370 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -490,6 +490,7 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription toThe resolved interface language is reported to PostHog as the personproperty `interface_language` when the account language loads.- When adding or changing a feature flag, follow the `feature-flags` skill.+- Gate routine template actions, pages, dialogs, and message cards on `enable-routine-sharing`; keep ordinary routines usable while it is off.- When adding or changing a view's feature tour, follow the `add-tour` skill.## Rulesdiff --git a/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsx b/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsxindex 7c7be40e0b..9c265971db 100644--- a/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsx+++ b/apps/web/src/features/channel/Message/MentionedRoutineTemplates.tsx@@ -1,3 +1,5 @@+import { ShowFeatureFlag } from '@app/lib/analytics/posthog';+import { enableRoutineSharing } from '@core/constant/featureFlags';import { getDocumentMentions } from '@core/util/documentMentions';import { lazyNamed } from '@core/util/lazyNamed';import { createMemo, For, Show, Suspense } from 'solid-js';@@ -22,11 +24,13 @@ export function MentionedRoutineTemplates(props: { content: string }) {);return (<Show when={routineIds().length > 0}>- <Suspense>- <For each={routineIds()}>- {(routineId) => <RoutineTemplateCard routineId={routineId} />}- </For>- </Suspense>+ <ShowFeatureFlag flag={enableRoutineSharing}>+ <Suspense>+ <For each={routineIds()}>+ {(routineId) => <RoutineTemplateCard routineId={routineId} />}+ </For>+ </Suspense>+ </ShowFeatureFlag></Show>);}diff --git a/apps/web/src/features/routines/routine-detail.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsxindex 6cd3e28c42..6ba83612df 100644--- a/apps/web/src/features/routines/routine-detail.test.tsx+++ b/apps/web/src/features/routines/routine-detail.test.tsx@@ -7,6 +7,10 @@ import type { RoutineTarget } from './core/routine-target';import { Routine } from './routine-detail';import type { HistoryRecord } from './views/routine-history';+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: false, loading: false }),+}));+vi.mock('@app/lib/split-router', () => ({createSearchParamsCodec: () => ({}),createSearchParams: () => {diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsxindex a47e0da375..d4a422d64a 100644--- a/apps/web/src/features/routines/routine-detail.tsx+++ b/apps/web/src/features/routines/routine-detail.tsx@@ -1,11 +1,13 @@import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { useHasPaidAccess } from '@core/auth/license';import { useBlockId } from '@core/block';import { defaultModelForPlan } from '@core/component/AI/constant';import { toast } from '@core/component/Toast/Toast';+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';@@ -52,6 +54,7 @@ export function RoutineDetail(props: {const panel = useSplitPanelOrThrow();const userId = useUserId();const hasPaidAccess = useHasPaidAccess();+ const sharing = useFeatureFlag(enableRoutineSharing);const back = () =>props.onBack ? props.onBack() : openAgentsPage(layout, 'routines');const open = (id: string) =>@@ -127,8 +130,8 @@ export function RoutineDetail(props: {toast.success('Prompt copied');else toast.alert('Could not copy prompt');}}- onShareTemplate={shareTemplate}- onOpenTemplate={open}+ onShareTemplate={sharing().enabled ? shareTemplate : undefined}+ onOpenTemplate={sharing().enabled ? open : undefined}slots={{PromptEditor: RoutinePromptEditor,ExecutionPicker: RoutineExecutionPicker,diff --git a/apps/web/src/features/routines/routine-template.tsx b/apps/web/src/features/routines/routine-template.tsxindex 6c2738a38b..1707752ac4 100644--- a/apps/web/src/features/routines/routine-template.tsx+++ b/apps/web/src/features/routines/routine-template.tsx@@ -1,7 +1,12 @@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 { 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';@@ -23,10 +28,13 @@ import type {import { Button, type ManagedDialogProps, openDialog } from '@ui';import {type Accessor,+ type ComponentProps,+ createEffect,createMemo,createSignal,getOwner,Match,+ on,Show,Switch,} from 'solid-js';@@ -172,8 +180,21 @@ export function openActivateTemplateDialog(owner: ReturnType<typeof getOwner>,onActivated: (routineId: string) => void) {- return openDialog(- ActivateTemplate,+ if (!isFeatureEnabled(enableRoutineSharing)) return;+ return openDialog<ComponentProps<typeof ActivateTemplate>>(+ (props) => {+ const sharing = useFeatureFlag(enableRoutineSharing);+ createEffect(+ on(sharing, (flag) => {+ if (!flag.loading && !flag.enabled) props.onOpenChange(false);+ })+ );+ return (+ <Show when={sharing().enabled}>+ <ActivateTemplate {...props} />+ </Show>+ );+ },{template,onActivated: (routineId) => {@@ -192,6 +213,25 @@ export function openActivateTemplateDialog(export function RoutineTemplatePage(props: {scheduleId: string;onBack(): void;+}) {+ const sharing = useFeatureFlag(enableRoutineSharing);+ return (+ <Show+ when={sharing().enabled}+ fallback={+ <div class="flex size-full items-center justify-center p-3 text-center text-sm text-ink-muted">+ {sharing().loading ? 'Loading…' : 'Routine sharing is unavailable.'}+ </div>+ }+ >+ <EnabledRoutineTemplatePage {...props} />+ </Show>+ );+}++function EnabledRoutineTemplatePage(props: {+ scheduleId: string;+ onBack(): void;}) {const owner = getOwner();const layout = useSplitLayout();@@ -435,10 +475,27 @@ export function openShareTemplateDialog(},owner: ReturnType<typeof getOwner>) {- return openDialog(ShareTemplate, routine, {- owner,- key: `share-template-${routine.routineId}`,- });+ if (!isFeatureEnabled(enableRoutineSharing)) return;+ return openDialog<ComponentProps<typeof ShareTemplate>>(+ (props) => {+ const sharing = useFeatureFlag(enableRoutineSharing);+ createEffect(+ on(sharing, (flag) => {+ if (!flag.loading && !flag.enabled) props.onOpenChange(false);+ })+ );+ return (+ <Show when={sharing().enabled}>+ <ShareTemplate {...props} />+ </Show>+ );+ },+ routine,+ {+ owner,+ key: `share-template-${routine.routineId}`,+ }+ );}/**diff --git a/apps/web/src/features/routines/views/routine-detail.tsx b/apps/web/src/features/routines/views/routine-detail.tsxindex c9b196255c..50e779b508 100644--- a/apps/web/src/features/routines/views/routine-detail.tsx+++ b/apps/web/src/features/routines/views/routine-detail.tsx@@ -28,8 +28,8 @@ export function RoutineDetailView(props: {onBack(): void;onDelete(): void;onCopyPrompt(prompt: string): Promise<void>;- onShareTemplate(): void;- onOpenTemplate(templateId: string): void;+ onShareTemplate?(): void;+ onOpenTemplate?(templateId: string): void;onOpenRun(resource: HistoryResource, newSplit: boolean): void;}) {const {@@ -120,10 +120,12 @@ export function RoutineDetailView(props: {<CopyIcon class="size-4" />Duplicate</Dropdown.Item>- <Dropdown.Item onSelect={props.onShareTemplate}>- <ShareIcon class="size-4" />- Share as template- </Dropdown.Item>+ <Show when={props.onShareTemplate}>+ <Dropdown.Item onSelect={props.onShareTemplate}>+ <ShareIcon class="size-4" />+ Share as template+ </Dropdown.Item>+ </Show><Show when={isOwned()}><Dropdown.Item onSelect={props.onDelete}><TrashIcon class="size-4" />@@ -136,12 +138,12 @@ export function RoutineDetailView(props: {)}properties={- <Show when={routine().templateId}>+ <Show when={props.onOpenTemplate && routine().templateId}>{(templateId) => (<Buttonvariant="ghost"size="sm"- onClick={() => props.onOpenTemplate(templateId())}+ onClick={() => props.onOpenTemplate?.(templateId())}>Created from template<ArrowUpRightIcon class="size-3.5" />diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex a78b083729..484da879ca 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -842,6 +842,13 @@ export const enableRoutineConditions = defineFlag({default: onInDev,});+// Templates are not ready for general use. Follow PostHog even in development+// so the UI and the server's per-user rollout agree.+export const enableRoutineSharing = defineFlag({+ key: 'enable-routine-sharing',+ env: 'ENABLE_ROUTINE_SHARING',+});+// The Recent view: the touched-by-me feed (everything the viewer mutated,// newest own-touch first). Gates the view (the route redirects to the inbox// when off) and its sidebar entry. PostHog-gated with a dev-mode default;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.tsindex d6ddf07aab..a5c26d868c 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTemplate.ts@@ -11,7 +11,7 @@ import type { RoutineTemplateTask } from './routineTemplateTask';import type { TemplateVariable } from './templateVariable';/**- * A shared routine's snapshot, readable by any signed-in user with its ID.+ * A shared routine's snapshot, readable by signed-in users with sharing enabled.*/export interface RoutineTemplate {/**diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.jsonindex afb4d7882b..0838f601a3 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json@@ -1328,7 +1328,7 @@},"RoutineTemplate": {"type": "object",- "description": "A shared routine's snapshot, readable by any signed-in user with its ID.",+ "description": "A shared routine's snapshot, readable by signed-in users with sharing enabled.","required": ["id","author",diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex 90d59777c0..43bb37506f 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -14,6 +14,7 @@ interface ImportMetaEnv {/** `true` logs each `perfMark` as a `[perf]` console line. */readonly VITE_PERF_LOG?: string;readonly VITE_ENABLE_REMINDERS?: string;+ readonly VITE_ENABLE_ROUTINE_SHARING?: string;readonly VITE_ENABLE_CALENDAR_MEETING_NOTES?: string;readonly VITE_DISABLE_BROWSER_TURSO_CACHE?: string;readonly VITE_ENABLE_WHATSAPP_LINKED?: string;diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex 9bd6f2ddb6..b615f3ca5e 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -441,7 +441,7 @@"EventFilter": "# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: `EventName`[]; `ids?`: `string`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | `EventName`[] | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |","EventFilters": "# Type Alias: EventFilters\n\n> **EventFilters** = `EventFilter`[]\n\nBounded nonempty OR of filters, canonicalized to remove duplicates.","EventName": "# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.",- "scheduled-action.RoutineTemplate": "# Type Alias: RoutineTemplate\n\n> **RoutineTemplate** = \\{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: `ActionTrigger`; `updated_at`: `string`; `variables`: `TemplateVariable`[]; \\}\n\nA shared routine's snapshot, readable by any signed-in user with its ID.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-active_count\"></a> `active_count` | `number` | Routines activated from this template, including stopped ones. |\n| <a id=\"property-author\"></a> `author` | `string` | Who shared it: the source routine's owner. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-description\"></a> `description` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | The routine it was shared from. |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n| <a id=\"property-variables\"></a> `variables` | `TemplateVariable`[] | - |",+ "scheduled-action.RoutineTemplate": "# Type Alias: RoutineTemplate\n\n> **RoutineTemplate** = \\{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: `ActionTrigger`; `updated_at`: `string`; `variables`: `TemplateVariable`[]; \\}\n\nA shared routine's snapshot, readable by signed-in users with sharing enabled.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-active_count\"></a> `active_count` | `number` | Routines activated from this template, including stopped ones. |\n| <a id=\"property-author\"></a> `author` | `string` | Who shared it: the source routine's owner. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-description\"></a> `description` | `string` | - |\n| <a id=\"property-id\"></a> `id` | `string` | The routine it was shared from. |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | `ActionTrigger` | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n| <a id=\"property-variables\"></a> `variables` | `TemplateVariable`[] | - |","RoutineTrigger": "# Type Alias: RoutineTrigger\n\n> **RoutineTrigger** = \\{ `schedule`: `Schedule`; `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: `EventFilters`; `type`: `\"events\"`; \\}\n\nAn individual trigger in a routine's trigger list.","RoutineTriggers": "# Type Alias: RoutineTriggers\n\n> **RoutineTriggers** = `RoutineTrigger`[]\n\nBounded schedules and one combined set of event filters.","RunVisibility": "# Type Alias: RunVisibility\n\n> **RunVisibility** = `\"listed\"` \\| `\"unlisted\"`\n\nWhether a routine's runs are listed in Home and the Agents list. Routines\nthat run often would bury the owner's own work, so runs start unlisted;\neither way they stay in the routine's history. The string form is the\n`scheduled_action.run_visibility` column's.",diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.mdindex 7203778fb6..efa8140e28 100644--- a/crates/scheduled_action/AGENTS.md+++ b/crates/scheduled_action/AGENTS.md@@ -29,8 +29,10 @@ each run.- An authenticated caller with a routine ID can read its detail; listing,run history, and mutations stay owner-scoped.- Templates: the owner shares a snapshot of a routine (keyed by the routine's- ID) with its references marked as variables; any authenticated caller reads- it, and activating creates the caller's own routine with `template_id`+ ID) with its references marked as variables; publishing, reading, and activation+ require the caller's `enable-routine-sharing` PostHog flag. Missing flags,+ missing configuration, and failed evaluations return 404. Owner unsharing+ stays available. Activating creates the caller's own routine with `template_id`pointing back. Filling variables happens in the client.- 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/Cargo.toml b/crates/scheduled_action/Cargo.tomlindex dd47c94a81..3d2a4eca56 100644--- a/crates/scheduled_action/Cargo.toml+++ b/crates/scheduled_action/Cargo.toml@@ -27,6 +27,7 @@ document_sub_type = { path = "../document_sub_type" }email = { path = "../email", default-features = false, features = ["outbound"] }entity_access_management = { path = "../entity_access_management" }frecency = { path = "../frecency", features = ["postgres"] }+feature_flags = { path = "../feature_flags" }jev = { path = "../jev", features = ["outbound"] }lexical_client = { path = "../lexical_client" }mention_utils = { path = "../mention_utils" }diff --git a/crates/scheduled_action/src/domain/ports.rs b/crates/scheduled_action/src/domain/ports.rsindex 75386279de..c342e45bd4 100644--- a/crates/scheduled_action/src/domain/ports.rs+++ b/crates/scheduled_action/src/domain/ports.rs@@ -230,8 +230,12 @@ pub trait RoutineTemplateService: Send + Sync + 'static {receipt: EntityAccessReceipt<OwnerAccessLevel>,) -> impl Future<Output = Result<()>> + Send;- /// Read a template by its unguessable ID for any authenticated viewer.- fn get_template(&self, id: Uuid) -> impl Future<Output = Result<RoutineTemplate>> + Send;+ /// Read a template by its unguessable ID for a viewer with sharing enabled.+ fn get_template(+ &self,+ user: &MacroUserIdStr<'_>,+ id: Uuid,+ ) -> impl Future<Output = Result<RoutineTemplate>> + Send;/// Create the principal's own routine from a shared template. The input/// is the activator's filled-in configuration, validated like any create.diff --git a/crates/scheduled_action/src/domain/service/test.rs b/crates/scheduled_action/src/domain/service/test.rsindex 34327ebefa..91c2a29f08 100644--- a/crates/scheduled_action/src/domain/service/test.rs+++ b/crates/scheduled_action/src/domain/service/test.rs@@ -209,6 +209,10 @@ pub(crate) fn stored_owner(service: &TestService, id: Uuid) -> Option<Owner> {.map(|action| action.owner.clone())}+pub(crate) fn stored_actions(service: &TestService) -> Vec<ScheduledAction> {+ service.repo.actions.lock().unwrap().clone()+}+/// The same store behind a dispatcher that has stopped.pub(crate) fn with_stopped_dispatcher(service: &TestService) -> Arc<TestService> {let (tx, _) = tokio::sync::mpsc::channel(1);diff --git a/crates/scheduled_action/src/domain/templates.rs b/crates/scheduled_action/src/domain/templates.rsindex 420521e1e1..0c055b9474 100644--- a/crates/scheduled_action/src/domain/templates.rs+++ b/crates/scheduled_action/src/domain/templates.rs@@ -10,6 +10,8 @@ use anyhow::Result;use chrono::{DateTime, Utc};use chrono_tz::Tz;use entity_access::domain::models::{EntityAccessReceipt, EntityType, OwnerAccessLevel};+use feature_flags::FeatureFlags;+use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use model_owner::{CreationPrincipal, Owner};use serde::{Deserialize, Serialize};@@ -27,6 +29,8 @@ mod test;pub const MAX_DESCRIPTION_CHARS: usize = 1_000;/// Most variables a template can mark.pub const MAX_VARIABLES: usize = 100;+/// PostHog rollout shared with the web app; missing or failed evaluations stay off.+pub const ROUTINE_SHARING_FLAG: &str = "enable-routine-sharing";/// How a variable is filled when someone activates the template.#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]@@ -75,7 +79,7 @@ pub struct ShareRoutineTemplate {pub variables: Vec<TemplateVariable>,}-/// A shared routine's snapshot, readable by any signed-in user with its ID.+/// A shared routine's snapshot, readable by signed-in users with sharing enabled.#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]pub struct RoutineTemplate {/// The routine it was shared from.@@ -135,18 +139,48 @@ impl ShareRoutineTemplate {}}-pub struct RoutineTemplateServiceImpl<Actions, Templates> {+pub struct RoutineTemplateServiceImpl<Actions, Templates, Flags> {actions: Arc<Actions>,templates: Arc<Templates>,+ flags: Option<Flags>,}-impl<Actions, Templates> RoutineTemplateServiceImpl<Actions, Templates> {- pub fn new(actions: Arc<Actions>, templates: Arc<Templates>) -> Self {- Self { actions, templates }+impl<Actions, Templates, Flags: FeatureFlags>+ RoutineTemplateServiceImpl<Actions, Templates, Flags>+{+ pub fn new(actions: Arc<Actions>, templates: Arc<Templates>, flags: Option<Flags>) -> Self {+ Self {+ actions,+ templates,+ flags,+ }+ }++ #[tracing::instrument(name = "routine.sharing_flag", err, skip_all)]+ async fn require_sharing(&self, user: Option<&MacroUserIdStr<'_>>) -> Result<()> {+ let (Some(flags), Some(user)) = (&self.flags, user) else {+ anyhow::bail!(ActionPolicyError::NotFound);+ };+ let enabled = flags+ .load(user)+ .await+ .inspect_err(|error| {+ tracing::warn!(+ ?error,+ "feature flags unavailable; routine sharing stays off"+ );+ })+ .is_ok_and(|snapshot| snapshot.is_enabled(ROUTINE_SHARING_FLAG));+ if !enabled {+ anyhow::bail!(ActionPolicyError::NotFound);+ }+ Ok(())}}-impl<Actions: ScheduledActionService, Templates> RoutineTemplateServiceImpl<Actions, Templates> {+impl<Actions: ScheduledActionService, Templates, Flags>+ RoutineTemplateServiceImpl<Actions, Templates, Flags>+{/// The routine behind an owner receipt, while the receipt's user still owns it.async fn owned_action(&self,@@ -171,10 +205,12 @@ impl<Actions: ScheduledActionService, Templates> RoutineTemplateServiceImpl<Acti}}-impl<Actions, Templates> RoutineTemplateService for RoutineTemplateServiceImpl<Actions, Templates>+impl<Actions, Templates, Flags> RoutineTemplateService+ for RoutineTemplateServiceImpl<Actions, Templates, Flags>whereActions: ScheduledActionService,Templates: RoutineTemplateRepo,+ Flags: FeatureFlags + 'static,{#[tracing::instrument(err, skip_all, fields(action_id = %receipt.entity().entity_id, variables = input.variables.len()))]async fn share_template(@@ -182,6 +218,7 @@ wherereceipt: EntityAccessReceipt<OwnerAccessLevel>,input: ShareRoutineTemplate,) -> Result<RoutineTemplate> {+ self.require_sharing(receipt.acting_user_id()).await?;let (id, action) = self.owned_action(&receipt).await?;action.owner_user()?;let snapshot = input.into_snapshot(&action, id)?;@@ -194,7 +231,9 @@ whereself.templates.delete_template(&id).await}- async fn get_template(&self, id: Uuid) -> Result<RoutineTemplate> {+ #[tracing::instrument(err, skip_all, fields(template_id = %id))]+ async fn get_template(&self, user: &MacroUserIdStr<'_>, id: Uuid) -> Result<RoutineTemplate> {+ self.require_sharing(Some(user)).await?;self.templates.get_template(&id).await?@@ -208,6 +247,7 @@ wheretemplate_id: Uuid,input: CreateScheduledAction,) -> Result<ScheduledAction> {+ self.require_sharing(principal.user()).await?;if self.templates.get_template(&template_id).await?.is_none() {return Err(ActionPolicyError::NotFound.into());}diff --git a/crates/scheduled_action/src/domain/templates/test.rs b/crates/scheduled_action/src/domain/templates/test.rsindex 0926ed327c..f37b907aca 100644--- a/crates/scheduled_action/src/domain/templates/test.rs+++ b/crates/scheduled_action/src/domain/templates/test.rs@@ -1,5 +1,8 @@use super::*;-use crate::domain::service::test::{TestService, USER, configuration, service, user};+use crate::domain::service::test::{+ TestService, USER, configuration, service, stored_actions, user,+};+use feature_flags::{FlagSnapshot, FlagValue, outbound::fake::FakeFeatureFlags};use macro_user_id::user_id::MacroUserIdStr;use std::collections::HashMap;use std::sync::Mutex;@@ -41,10 +44,24 @@ impl RoutineTemplateRepo for FakeTemplates {}}-type Templates = RoutineTemplateServiceImpl<TestService, FakeTemplates>;+type Templates = RoutineTemplateServiceImpl<TestService, FakeTemplates, FakeFeatureFlags>;fn templates(actions: &Arc<TestService>) -> Templates {- RoutineTemplateServiceImpl::new(Arc::clone(actions), Arc::new(FakeTemplates::default()))+ let mut flags = FakeFeatureFlags::default();+ for viewer in [user(), other_user()] {+ flags.set(+ viewer,+ Ok(FlagSnapshot::new([(+ ROUTINE_SHARING_FLAG.to_owned(),+ FlagValue::Boolean(true),+ )])),+ );+ }+ RoutineTemplateServiceImpl::new(+ Arc::clone(actions),+ Arc::new(FakeTemplates::default()),+ Some(flags),+ )}fn owner_receipt(user: MacroUserIdStr<'static>, id: Uuid) -> EntityAccessReceipt<OwnerAccessLevel> {@@ -96,6 +113,10 @@ async fn sharing_snapshots_the_routine_and_activation_points_back_at_it() {assert_eq!(shared.name, "routine");assert_eq!(shared.description, "Summarizes the week");assert_eq!(shared.task, configuration(false).task);+ assert_eq!(+ templates.get_template(&other_user(), id).await.unwrap().id,+ id+ );let activated = templates.activate_template(@@ -136,7 +157,7 @@ async fn only_the_owner_can_share_or_stop_sharing() {error.downcast_ref::<ActionPolicyError>(),Some(ActionPolicyError::NotFound)));- assert!(templates.get_template(id).await.is_ok());+ assert!(templates.get_template(&user(), id).await.is_ok());}#[tokio::test]@@ -187,5 +208,131 @@ async fn rejects_an_oversized_description() {error.downcast_ref::<TemplateInputError>(),Some(&TemplateInputError::DescriptionTooLong));- assert!(templates.get_template(id).await.is_err());+ assert!(templates.get_template(&user(), id).await.is_err());+}++#[tokio::test]+async fn disabled_missing_or_failed_flags_block_templates_but_preserve_routines_and_unsharing() {+ for evaluation in [+ None,+ Some(Ok(FlagSnapshot::default())),+ Some(Ok(FlagSnapshot::new([(+ ROUTINE_SHARING_FLAG.to_owned(),+ FlagValue::Boolean(false),+ )]))),+ Some(Err("PostHog unavailable".to_owned())),+ ] {+ let actions = service(false);+ let mut templates = templates(&actions);+ let id = create_routine(&actions).await;+ let shared = templates+ .share_template(owner_receipt(user(), id), share_input())+ .await+ .unwrap();+ let activated = templates+ .activate_template(+ &CreationPrincipal::User(other_user()),+ id,+ CreateScheduledAction::Canonical(configuration(false)),+ )+ .await+ .unwrap();++ templates.flags = evaluation.map(|result| {+ let mut flags = FakeFeatureFlags::default();+ flags.set(user(), result.clone());+ flags.set(other_user(), result);+ flags+ });+ let mut replacement = share_input();+ replacement.description = "Must not publish".to_owned();+ let errors = [+ templates+ .share_template(owner_receipt(user(), id), replacement)+ .await+ .unwrap_err(),+ templates.get_template(&other_user(), id).await.unwrap_err(),+ templates+ .activate_template(+ &CreationPrincipal::User(other_user()),+ id,+ CreateScheduledAction::Canonical(configuration(false)),+ )+ .await+ .unwrap_err(),+ ];+ for error in errors {+ assert!(matches!(+ error.downcast_ref::<ActionPolicyError>(),+ Some(ActionPolicyError::NotFound)+ ));+ }+ assert_eq!(+ templates+ .templates+ .get_template(&id)+ .await+ .unwrap()+ .unwrap()+ .description,+ shared.description+ );+ let copies: Vec<_> = stored_actions(&actions)+ .into_iter()+ .filter(|action| action.owner.is_user(&other_user()))+ .collect();+ assert_eq!(copies.len(), 1);+ assert_eq!(copies[0].id, activated.id);+ assert_eq!(copies[0].enabled, activated.enabled);+ assert!(actions.get_action(id).await.is_ok());++ templates+ .unshare_template(owner_receipt(user(), id))+ .await+ .unwrap();+ assert!(+ templates+ .templates+ .get_template(&id)+ .await+ .unwrap()+ .is_none()+ );+ assert!(actions.get_action(activated.id.unwrap()).await.is_ok());+ }+}++#[tokio::test]+async fn templates_use_the_viewer_and_activating_users_rollout() {+ let actions = service(false);+ let mut templates = templates(&actions);+ let id = create_routine(&actions).await;+ templates+ .share_template(owner_receipt(user(), id), share_input())+ .await+ .unwrap();+ templates+ .flags+ .as_mut()+ .unwrap()+ .set(other_user(), Ok(FlagSnapshot::default()));++ assert!(templates.get_template(&user(), id).await.is_ok());+ assert!(templates.get_template(&other_user(), id).await.is_err());+ assert!(+ templates+ .activate_template(+ &CreationPrincipal::BotForUser {+ bot: bot_id::BotId::TEST_A,+ user: other_user()+ },+ id,+ CreateScheduledAction::Canonical(configuration(false)),+ )+ .await+ .is_err()+ );+ let stored = stored_actions(&actions);+ assert_eq!(stored.len(), 1);+ assert_eq!(stored[0].id, Some(id));}diff --git a/crates/scheduled_action/src/inbound/template_router.rs b/crates/scheduled_action/src/inbound/template_router.rsindex 05ed91dd97..22331c602d 100644--- a/crates/scheduled_action/src/inbound/template_router.rs+++ b/crates/scheduled_action/src/inbound/template_router.rs@@ -49,8 +49,8 @@ impl<T, Svc, Auth> FromRef<RoutineTemplateRouterState<T, Svc, Auth>>}}-/// Like routine creation, a team bot reaches the domain so its non-user owner-/// gets the explicit `OwnerNotUserError` instead of a generic 403.+/// Let the domain apply the rollout to the creation principal; a team bot+/// without an acting user has no enabled user rollout.impl<T, Svc, Auth> FromRef<RoutineTemplateRouterState<T, Svc, Auth>> for NonUserOwners {fn from_ref(_state: &RoutineTemplateRouterState<T, Svc, Auth>) -> Self {NonUserOwners::Enabled@@ -163,14 +163,19 @@ where)]pub async fn get_template<T, Svc, Auth>(State(state): State<RoutineTemplateRouterState<T, Svc, Auth>>,- _user: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ user: MacroAuthorizationExtractor<Auth, UserOrInternal>,Path(id): Path<Uuid>,) -> Result<Json<RoutineTemplate>, ScheduledActionApiError>whereT: RoutineTemplateService,Auth: MacroAuthorizationService,{- Ok(Json(state.service.get_template(id).await?))+ Ok(Json(+ state+ .service+ .get_template(&user.authorization.user.macro_user_id, id)+ .await?,+ ))}#[utoipa::path(diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex cd1baa6153..bec45d3d60 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -1128,11 +1128,23 @@ routine is deleted the mention reads `Deleted` and clicking it shows a cardinstead of opening the routine. Routines do not appear in the mention menu.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 its-template when the owner shared one, and otherwise "isn't shared as a template".+template when the owner shared one and routine sharing is enabled, and otherwise+an unavailable message.Run conversations keep their own permissions.### Routine templates+Templates require the per-user PostHog flag `enable-routine-sharing`, which is+off unless explicitly enabled, including in development. Configure it for both+client and server evaluation. While off, sharing actions, message cards, and+**Created from template** links are hidden; someone else's routine link shows+**Routine sharing is unavailable.** after flags finish loading. Template queries+and activation dialogs do not mount. The API also rejects publishing, reading,+and activation with 404 when the flag is off, missing, or cannot be evaluated.+Owners can still stop sharing through the API; their existing routines and+already activated copies keep working. `VITE_ENABLE_ROUTINE_SHARING` overrides+only 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 explainswhat people get, takes a **Description**, and lists **What changes for eachdiff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.mdindex b7cfe535d5..ff196998c0 100644--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/RoutineTemplate.md@@ -2,7 +2,7 @@> **RoutineTemplate** = \{ `active_count`: `number`; `author`: `string`; `created_at`: `string`; `description`: `string`; `id`: `string`; `name`: `string`; `task`: \{\[`key`: `string`\]: `unknown`; \}; `trigger`: [`ActionTrigger`](ActionTrigger.md); `updated_at`: `string`; `variables`: [`TemplateVariable`](TemplateVariable.md)[]; \}-A shared routine's snapshot, readable by any signed-in user with its ID.+A shared routine's snapshot, readable by signed-in users with sharing enabled.## Propertiesdiff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex b1800292b7..0d433d5789 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -380,6 +380,10 @@ Routines run as their owner, so share one as a template instead:`routine.template()` reads it (undefined when not shared), and`routine.activateTemplate(options)` creates the caller's own routine from it.`routine.sourceTemplate()` returns the routine a template came from.+Publishing, reading, and activating templates require the caller's+`enable-routine-sharing` PostHog flag. Disabled or unavailable evaluations return+404 (`template()` returns `undefined`). `stopSharingTemplate()` stays available+to owners, and previously activated routines continue working.### Agents, conversations and hostsdiff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.tsindex 37cbd1caf1..50fb3f03fa 100644--- a/packages/sdk/generated/scheduled-action/types.gen.ts+++ b/packages/sdk/generated/scheduled-action/types.gen.ts@@ -227,7 +227,7 @@ export type LegacyActionConfiguration = {export type RoutineModelId = string;/**- * A shared routine's snapshot, readable by any signed-in user with its ID.+ * A shared routine's snapshot, readable by signed-in users with sharing enabled.*/export type RoutineTemplate = {/**diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.jsonindex afb4d7882b..0838f601a3 100644--- a/packages/sdk/specs/scheduled-action.json+++ b/packages/sdk/specs/scheduled-action.json@@ -1328,7 +1328,7 @@},"RoutineTemplate": {"type": "object",- "description": "A shared routine's snapshot, readable by any signed-in user with its ID.",+ "description": "A shared routine's snapshot, readable by signed-in users with sharing enabled.","required": ["id","author",diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex 41e04c548f..e14ac41288 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -117,7 +117,9 @@ hostnames and internally rewrites cognition paths. `PREVIEW_DOMAIN` and`PREVIEW_CONTROL_HOSTS` values are retained only for old-image rollback; newcode does not read them. `POSTHOG_API_KEY` and `POSTHOG_HOST` drivefeature flags and the MCP and integration analytics; when the key is unset,-analytics are off.+analytics are off and routine template publishing, reads, and activation are+disabled. Scheduling wires the per-user `enable-routine-sharing` PostHog gate;+owner unsharing and already activated routines remain available.In deployed configs, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY`is cognition's Secrets Manager reference; AI tools resolve the separate`DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME` reference.diff --git a/services/agent_harness_service/src/scheduling.rs b/services/agent_harness_service/src/scheduling.rsindex d3e70450ae..35435d880c 100644--- a/services/agent_harness_service/src/scheduling.rs+++ b/services/agent_harness_service/src/scheduling.rs@@ -265,10 +265,26 @@ pub async fn build(config.routine_agents_enabled,)),);+ let template_flags = config+ .posthog_api_key+ .value()+ .map(|key| {+ feature_flags::outbound::posthog::PostHogFeatureFlags::new(+ config+ .posthog_host+ .value()+ .unwrap_or("https://us.i.posthog.com"),+ key.to_owned(),+ Duration::from_secs(3),+ )+ })+ .transpose()+ .map_err(|error| anyhow::anyhow!("invalid routine feature flag configuration: {error}"))?;let template_state = RoutineTemplateRouterState {service: Arc::new(RoutineTemplateServiceImpl::new(Arc::clone(&service),Arc::new(PgRoutineTemplateRepo::new(db.clone())),+ template_flags,)),access_service: Arc::clone(&access),authorization_state: authorization_state.clone(),