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
feat(routines): add routine management and agent scheduling tools (#7465)
teo5db5c540c916
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 483154bc01..749d0a9d6e 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -555,6 +555,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -713,6 +714,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -1305,6 +1307,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -1549,6 +1552,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -2545,6 +2549,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -3226,11 +3231,9 @@"crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",- "crates/ai_tools","crates/ai_toolset","crates/ai_usage","crates/analytics_client",- "crates/anthropic","crates/attachment","crates/authentication_service_client","crates/bot_id",@@ -3242,7 +3245,6 @@"crates/channel_sender","crates/channels","crates/chat",- "crates/collab_surface","crates/comms_db_client","crates/complete_graph","crates/connection",@@ -3252,14 +3254,10 @@"crates/cowlike","crates/crm","crates/database_env_vars",- "crates/database_sql",- "crates/databases",- "crates/databases_sql","crates/document_sub_type","crates/documents","crates/dynamodb_client","crates/email",- "crates/email_service_client","crates/email_utils","crates/embedding","crates/entity_access",@@ -3293,10 +3291,7 @@"crates/graphql_soup_filter_input","crates/harness_id","crates/harness_token",- "crates/image_generation",- "crates/import","crates/initiative",- "crates/initiative_description","crates/invite_email","crates/ip_extractor","crates/item_filter_index",@@ -3304,7 +3299,6 @@"crates/kafka_util","crates/last_online_tracker","crates/lexical_client",- "crates/lexical_mention_extractor","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config",@@ -3317,18 +3311,12 @@"crates/macro_env_var","crates/macro_event_broker","crates/macro_event_topics",- "crates/macro_queues","crates/macro_service_urls","crates/macro_sha_count_client","crates/macro_sync_service_jwt","crates/macro_tower_layers","crates/macro_user_id","crates/macro_uuid",- "crates/maybe_send",- "crates/mcp_client",- "crates/mcp_select",- "crates/mcp_toolset",- "crates/memory","crates/mention_utils","crates/messages","crates/model",@@ -3340,7 +3328,6 @@"crates/model_user","crates/models_ai_projection","crates/models_bulk_upload",- "crates/models_databases","crates/models_dcs","crates/models_email","crates/models_entity_access_management",@@ -3349,17 +3336,12 @@"crates/models_pagination","crates/models_permissions","crates/models_properties",- "crates/models_search",- "crates/models_search_cursor","crates/models_sfs","crates/models_soup","crates/models_team","crates/non_empty","crates/notification","crates/notification_state",- "crates/opensearch_client",- "crates/opensearch_query_builder",- "crates/pipedream_mcp","crates/pptx_engine","crates/predicate_index","crates/projects",@@ -3371,16 +3353,13 @@"crates/remote_env_var","crates/roles_and_permissions","crates/s3_key",- "crates/search_service_client","crates/secretsmanager_client","crates/share_permission_db_utils",- "crates/skills","crates/soup","crates/soup_filter_projection","crates/soup_realtime","crates/sqs_client","crates/sqs_worker",- "crates/static_file","crates/static_file_service_client","crates/sync_service","crates/sync_service_client",@@ -4370,6 +4349,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -4516,7 +4496,6 @@"crates/mcp_client","crates/mcp_select","crates/mcp_toolset",- "crates/memory","crates/mention_utils","crates/messages","crates/model",@@ -4560,6 +4539,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/saved_views","crates/search_service",@@ -6947,16 +6927,13 @@"graphql_scheduled_action": ["crates/activity","crates/agent",- "crates/agent_changes","crates/agent_fold","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",- "crates/ai_tools","crates/ai_toolset","crates/ai_usage","crates/analytics_client",- "crates/anthropic","crates/attachment","crates/authentication_service_client","crates/bot_id",@@ -6967,8 +6944,6 @@"crates/call","crates/channel_sender","crates/channels",- "crates/chat",- "crates/collab_surface","crates/comms_db_client","crates/connection","crates/connection_gateway_client",@@ -6977,14 +6952,9 @@"crates/cowlike","crates/crm","crates/database_env_vars",- "crates/database_sql",- "crates/databases",- "crates/databases_sql","crates/document_sub_type","crates/documents",- "crates/dynamodb_client","crates/email",- "crates/email_service_client","crates/email_utils","crates/embedding","crates/entity_access",@@ -6994,7 +6964,6 @@"crates/entity_registry/entity_registry","crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry",- "crates/favorites","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -7006,17 +6975,13 @@"crates/graphql_scheduled_action","crates/harness_id","crates/harness_token",- "crates/image_generation",- "crates/import","crates/initiative",- "crates/initiative_description","crates/invite_email","crates/ip_extractor","crates/item_filters","crates/kafka_util","crates/last_online_tracker","crates/lexical_client",- "crates/lexical_mention_extractor","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config",@@ -7029,18 +6994,11 @@"crates/macro_env_var","crates/macro_event_broker","crates/macro_event_topics",- "crates/macro_queues","crates/macro_service_urls",- "crates/macro_sha_count_client","crates/macro_sync_service_jwt","crates/macro_tower_layers","crates/macro_user_id","crates/macro_uuid",- "crates/maybe_send",- "crates/mcp_client",- "crates/mcp_select",- "crates/mcp_toolset",- "crates/memory","crates/mention_utils","crates/messages","crates/model",@@ -7052,44 +7010,29 @@"crates/model_user","crates/models_ai_projection","crates/models_bulk_upload",- "crates/models_databases","crates/models_dcs","crates/models_email","crates/models_entity_access_management",- "crates/models_grouping","crates/models_opensearch","crates/models_pagination","crates/models_permissions","crates/models_properties",- "crates/models_search",- "crates/models_search_cursor","crates/models_sfs",- "crates/models_soup","crates/models_team","crates/non_empty","crates/notification","crates/notification_state",- "crates/opensearch_client",- "crates/opensearch_query_builder",- "crates/pipedream_mcp","crates/pptx_engine",- "crates/projects","crates/prompt","crates/properties","crates/rate_limit",- "crates/readonly_pool",- "crates/reminders","crates/remote_env_var","crates/roles_and_permissions","crates/s3_key",- "crates/search_service_client","crates/secretsmanager_client","crates/share_permission_db_utils",- "crates/skills",- "crates/soup","crates/sqs_client","crates/sqs_worker",- "crates/static_file","crates/static_file_service_client","crates/sync_service","crates/sync_service_client",@@ -8417,6 +8360,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -8581,6 +8525,7 @@"crates/reminders","crates/remote_env_var","crates/roles_and_permissions",+ "crates/routines","crates/s3_key","crates/search_service_client","crates/secretsmanager_client",@@ -10101,6 +10046,25 @@"crates/roles_and_permissions","crates/workspace-hack"],+ "routines": [+ "crates/ai_toolset",+ "crates/bot_id",+ "crates/bot_token",+ "crates/cowlike",+ "crates/genai_telemetry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/model-error-response",+ "crates/model_user",+ "crates/remote_env_var",+ "crates/routines",+ "crates/workspace-hack"+ ],"s3_client": ["crates/s3_client","crates/workspace-hack"@@ -10121,16 +10085,13 @@"scheduled_action": ["crates/activity","crates/agent",- "crates/agent_changes","crates/agent_fold","crates/agent_runtime_protocol","crates/agent_session","crates/ai_billing",- "crates/ai_tools","crates/ai_toolset","crates/ai_usage","crates/analytics_client",- "crates/anthropic","crates/attachment","crates/authentication_service_client","crates/bot_id",@@ -10141,8 +10102,6 @@"crates/call","crates/channel_sender","crates/channels",- "crates/chat",- "crates/collab_surface","crates/comms_db_client","crates/connection","crates/connection_gateway_client",@@ -10151,14 +10110,9 @@"crates/cowlike","crates/crm","crates/database_env_vars",- "crates/database_sql",- "crates/databases",- "crates/databases_sql","crates/document_sub_type","crates/documents",- "crates/dynamodb_client","crates/email",- "crates/email_service_client","crates/email_utils","crates/embedding","crates/entity_access",@@ -10168,7 +10122,6 @@"crates/entity_registry/entity_registry","crates/entity_registry/entity_registry_db_utils","crates/entity_registry/shared_entity_registry",- "crates/favorites","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -10179,17 +10132,13 @@"crates/google_token","crates/harness_id","crates/harness_token",- "crates/image_generation",- "crates/import","crates/initiative",- "crates/initiative_description","crates/invite_email","crates/ip_extractor","crates/item_filters","crates/kafka_util","crates/last_online_tracker","crates/lexical_client",- "crates/lexical_mention_extractor","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config",@@ -10202,18 +10151,11 @@"crates/macro_env_var","crates/macro_event_broker","crates/macro_event_topics",- "crates/macro_queues","crates/macro_service_urls",- "crates/macro_sha_count_client","crates/macro_sync_service_jwt","crates/macro_tower_layers","crates/macro_user_id","crates/macro_uuid",- "crates/maybe_send",- "crates/mcp_client",- "crates/mcp_select",- "crates/mcp_toolset",- "crates/memory","crates/mention_utils","crates/messages","crates/model",@@ -10225,44 +10167,29 @@"crates/model_user","crates/models_ai_projection","crates/models_bulk_upload",- "crates/models_databases","crates/models_dcs","crates/models_email","crates/models_entity_access_management",- "crates/models_grouping","crates/models_opensearch","crates/models_pagination","crates/models_permissions","crates/models_properties",- "crates/models_search",- "crates/models_search_cursor","crates/models_sfs",- "crates/models_soup","crates/models_team","crates/non_empty","crates/notification","crates/notification_state",- "crates/opensearch_client",- "crates/opensearch_query_builder",- "crates/pipedream_mcp","crates/pptx_engine",- "crates/projects","crates/prompt","crates/properties","crates/rate_limit",- "crates/readonly_pool",- "crates/reminders","crates/remote_env_var","crates/roles_and_permissions","crates/s3_key",- "crates/search_service_client","crates/secretsmanager_client","crates/share_permission_db_utils",- "crates/skills",- "crates/soup","crates/sqs_client","crates/sqs_worker",- "crates/static_file","crates/static_file_service_client","crates/sync_service","crates/sync_service_client",diff --git a/.sqlx/query-650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b.json b/.sqlx/query-2e666a4c038095bda24d32d646c3d71ef4a12dc8f358e465125a799e9b7d80eb.jsonsimilarity index 83%rename from .sqlx/query-650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b.jsonrename to .sqlx/query-2e666a4c038095bda24d32d646c3d71ef4a12dc8f358e465125a799e9b7d80eb.jsonindex be74de2a43..c7e902224e 100644--- a/.sqlx/query-650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b.json+++ b/.sqlx/query-2e666a4c038095bda24d32d646c3d71ef4a12dc8f358e465125a799e9b7d80eb.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE id = ANY($1)\n ",+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters, trigger_config,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE id = ANY($1)\n ","describe": {"columns": [{@@ -75,11 +75,16 @@},{"ordinal": 14,+ "name": "trigger_config",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 15,"name": "configuration_revision","type_info": "Int8"},{- "ordinal": 15,+ "ordinal": 16,"name": "event_activated_at","type_info": "Timestamptz"}@@ -104,9 +109,10 @@false,false,true,+ true,false,true]},- "hash": "650b4cd0147a1ccb52430eb4879f77ff76e035e74e9b958745c3baefac59415b"+ "hash": "2e666a4c038095bda24d32d646c3d71ef4a12dc8f358e465125a799e9b7d80eb"}diff --git a/.sqlx/query-11aaeb83da5085bcd5e67566537f1d780a08b7a15856b2d50226b7e024211aa2.json b/.sqlx/query-3b0f0fbf2f27255501b55a260e4ea809395a577aa1bb7e363e91ababda683cc0.jsonsimilarity index 73%rename from .sqlx/query-11aaeb83da5085bcd5e67566537f1d780a08b7a15856b2d50226b7e024211aa2.jsonrename to .sqlx/query-3b0f0fbf2f27255501b55a260e4ea809395a577aa1bb7e363e91ababda683cc0.jsonindex 4b131d811b..f1dd4f6ea6 100644--- a/.sqlx/query-11aaeb83da5085bcd5e67566537f1d780a08b7a15856b2d50226b7e024211aa2.json+++ b/.sqlx/query-3b0f0fbf2f27255501b55a260e4ea809395a577aa1bb7e363e91ababda683cc0.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT r.action_id, r.event_id, r.configuration_revision, r.event_context, r.admitted_at\n FROM scheduled_action a\n CROSS JOIN LATERAL (\n SELECT action_id, event_id, configuration_revision, event_context, admitted_at, admission_order\n FROM scheduled_action_event_run\n WHERE action_id = a.id AND state = 'pending'\n ORDER BY admission_order LIMIT 1\n ) r\n WHERE a.enabled AND a.trigger_type = 'events'\n AND a.configuration_revision = r.configuration_revision\n AND (a.claimed IS NULL OR a.claimed < $1)\n AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run s WHERE s.action_id = a.id AND s.state = 'started')\n ORDER BY r.admission_order\n LIMIT $2 FOR UPDATE OF a SKIP LOCKED\n ",+ "query": "\n SELECT r.action_id, r.event_id, r.configuration_revision, r.event_context, r.admitted_at\n FROM scheduled_action a\n CROSS JOIN LATERAL (\n SELECT action_id, event_id, configuration_revision, event_context, admitted_at, admission_order\n FROM scheduled_action_event_run\n WHERE action_id = a.id AND state = 'pending'\n ORDER BY admission_order LIMIT 1\n ) r\n WHERE a.enabled AND a.event_filters IS NOT NULL\n AND a.configuration_revision = r.configuration_revision\n AND (a.claimed IS NULL OR a.claimed < $1)\n AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run s WHERE s.action_id = a.id AND s.state = 'started')\n ORDER BY r.admission_order\n LIMIT $2 FOR UPDATE OF a SKIP LOCKED\n ","describe": {"columns": [{@@ -43,5 +43,5 @@false]},- "hash": "11aaeb83da5085bcd5e67566537f1d780a08b7a15856b2d50226b7e024211aa2"+ "hash": "3b0f0fbf2f27255501b55a260e4ea809395a577aa1bb7e363e91ababda683cc0"}diff --git a/.sqlx/query-dac4a76e5ffb0692966932c8e3a711b42af43bc937b89145d0046e1f508ba209.json b/.sqlx/query-3b8229ca848b33e5086675daf04646b155cd5078be1ad2d7ba4db470e41dc27c.jsonsimilarity index 80%rename from .sqlx/query-dac4a76e5ffb0692966932c8e3a711b42af43bc937b89145d0046e1f508ba209.jsonrename to .sqlx/query-3b8229ca848b33e5086675daf04646b155cd5078be1ad2d7ba4db470e41dc27c.jsonindex 259a1df871..bc7c6c9b10 100644--- a/.sqlx/query-dac4a76e5ffb0692966932c8e3a711b42af43bc937b89145d0046e1f508ba209.json+++ b/.sqlx/query-3b8229ca848b33e5086675daf04646b155cd5078be1ad2d7ba4db470e41dc27c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE enabled AND trigger_type = 'cron'\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ",+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config\n FROM scheduled_action\n WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULL\n AND (claimed IS NULL OR claimed < $1)\n ORDER BY next_run_at ASC, id ASC\n LIMIT $2\n ","describe": {"columns": [{@@ -82,6 +82,11 @@"ordinal": 15,"name": "event_activated_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "trigger_config",+ "type_info": "Jsonb"}],"parameters": {@@ -106,8 +111,9 @@false,true,false,+ true,true]},- "hash": "dac4a76e5ffb0692966932c8e3a711b42af43bc937b89145d0046e1f508ba209"+ "hash": "3b8229ca848b33e5086675daf04646b155cd5078be1ad2d7ba4db470e41dc27c"}diff --git a/.sqlx/query-40ecb68cdcd633aefd35d32bcdb7349efe4ffcc5cac507df1afd7481a344708a.json b/.sqlx/query-40ecb68cdcd633aefd35d32bcdb7349efe4ffcc5cac507df1afd7481a344708a.jsondeleted file mode 100644index 2e3bb4d8ae..0000000000--- a/.sqlx/query-40ecb68cdcd633aefd35d32bcdb7349efe4ffcc5cac507df1afd7481a344708a.json+++ /dev/null@@ -1,26 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id FROM scheduled_action\n WHERE id = $1 AND enabled AND trigger_type = 'events'\n AND configuration_revision = $2 AND event_activated_at <= $3\n AND jsonb_path_exists(event_filters,\n '$[*] ? (@.events[*] == $event && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $4::text, 'id', $5::text))\n FOR UPDATE\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Uuid",- "Int8",- "Timestamptz",- "Text",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "40ecb68cdcd633aefd35d32bcdb7349efe4ffcc5cac507df1afd7481a344708a"-}diff --git a/.sqlx/query-230e59f6b2343c770363b67cacf66af58498dac9cb8c4fe63df1a78d38680b76.json b/.sqlx/query-4650ea6bd8a3e2deebda031e3d950c11a89020eae46a2e9eb65a68891e4990f4.jsonsimilarity index 82%rename from .sqlx/query-230e59f6b2343c770363b67cacf66af58498dac9cb8c4fe63df1a78d38680b76.jsonrename to .sqlx/query-4650ea6bd8a3e2deebda031e3d950c11a89020eae46a2e9eb65a68891e4990f4.jsonindex ca02a83551..80ee3439c9 100644--- a/.sqlx/query-230e59f6b2343c770363b67cacf66af58498dac9cb8c4fe63df1a78d38680b76.json+++ b/.sqlx/query-4650ea6bd8a3e2deebda031e3d950c11a89020eae46a2e9eb65a68891e4990f4.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, owner, name, kind, task, created_at, updated_at, enabled,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE id = $1 AND enabled AND trigger_type = 'events' AND configuration_revision = $2\n AND (claimed IS NULL OR claimed < $3)\n AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run WHERE action_id = $1 AND state = 'started')\n ",+ "query": "\n SELECT id, owner, name, kind, task, created_at, updated_at, enabled,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE id = $1 AND enabled AND event_filters IS NOT NULL AND configuration_revision = $2\n AND (claimed IS NULL OR claimed < $3)\n AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run WHERE action_id = $1 AND state = 'started')\n ","describe": {"columns": [{@@ -74,5 +74,5 @@true]},- "hash": "230e59f6b2343c770363b67cacf66af58498dac9cb8c4fe63df1a78d38680b76"+ "hash": "4650ea6bd8a3e2deebda031e3d950c11a89020eae46a2e9eb65a68891e4990f4"}diff --git a/.sqlx/query-61feae64855668289766559613c2fd6f395fedfaf78f43ac5d601b0cff4e75d9.json b/.sqlx/query-4f29a35d70bea2287ef2fdeffdadead49ac2e837edc349391ae83f5a7cf915e5.jsonsimilarity index 69%rename from .sqlx/query-61feae64855668289766559613c2fd6f395fedfaf78f43ac5d601b0cff4e75d9.jsonrename to .sqlx/query-4f29a35d70bea2287ef2fdeffdadead49ac2e837edc349391ae83f5a7cf915e5.jsonindex d25c32856c..2a0387081f 100644--- a/.sqlx/query-61feae64855668289766559613c2fd6f395fedfaf78f43ac5d601b0cff4e75d9.json+++ b/.sqlx/query-4f29a35d70bea2287ef2fdeffdadead49ac2e837edc349391ae83f5a7cf915e5.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT r.action_id, r.event_id FROM scheduled_action_event_run r\n JOIN scheduled_action a ON a.id = r.action_id\n WHERE (r.state = 'started' AND r.deadline <= $1)\n OR (r.state = 'pending' AND (NOT a.enabled OR a.trigger_type <> 'events'\n OR a.configuration_revision <> r.configuration_revision))\n ORDER BY r.admission_order LIMIT $2 FOR UPDATE OF a SKIP LOCKED\n ",+ "query": "\n SELECT r.action_id, r.event_id FROM scheduled_action_event_run r\n JOIN scheduled_action a ON a.id = r.action_id\n WHERE (r.state = 'started' AND r.deadline <= $1)\n OR (r.state = 'pending' AND (NOT a.enabled OR a.event_filters IS NULL\n OR a.configuration_revision <> r.configuration_revision))\n ORDER BY r.admission_order LIMIT $2 FOR UPDATE OF a SKIP LOCKED\n ","describe": {"columns": [{@@ -25,5 +25,5 @@false]},- "hash": "61feae64855668289766559613c2fd6f395fedfaf78f43ac5d601b0cff4e75d9"+ "hash": "4f29a35d70bea2287ef2fdeffdadead49ac2e837edc349391ae83f5a7cf915e5"}diff --git a/.sqlx/query-6975627d7250479d94dbd98e14bc0643dfb9b9e4f3700dd6d54f34c677c5f385.json b/.sqlx/query-51766e2016d89cc20d7ddbcab7da7df4c1e7554e8cd757cdefadc5dad053a973.jsonsimilarity index 78%rename from .sqlx/query-6975627d7250479d94dbd98e14bc0643dfb9b9e4f3700dd6d54f34c677c5f385.jsonrename to .sqlx/query-51766e2016d89cc20d7ddbcab7da7df4c1e7554e8cd757cdefadc5dad053a973.jsonindex 4680e732cf..dbaf255cfc 100644--- a/.sqlx/query-6975627d7250479d94dbd98e14bc0643dfb9b9e4f3700dd6d54f34c677c5f385.json+++ b/.sqlx/query-51766e2016d89cc20d7ddbcab7da7df4c1e7554e8cd757cdefadc5dad053a973.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO scheduled_action\n (id, owner, name, schedule, kind, timezone, task, next_run_at, enabled,\n trigger_type, event_filters, configuration_revision, event_activated_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n ",+ "query": "\n INSERT INTO scheduled_action\n (id, owner, name, schedule, kind, timezone, task, next_run_at, enabled,\n trigger_type, event_filters, configuration_revision, event_activated_at, trigger_config)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config\n ","describe": {"columns": [{@@ -82,6 +82,11 @@"ordinal": 15,"name": "event_activated_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "trigger_config",+ "type_info": "Jsonb"}],"parameters": {@@ -98,7 +103,8 @@"Text","Jsonb","Int8",- "Timestamptz"+ "Timestamptz",+ "Jsonb"]},"nullable": [@@ -117,8 +123,9 @@false,true,false,+ true,true]},- "hash": "6975627d7250479d94dbd98e14bc0643dfb9b9e4f3700dd6d54f34c677c5f385"+ "hash": "51766e2016d89cc20d7ddbcab7da7df4c1e7554e8cd757cdefadc5dad053a973"}diff --git a/.sqlx/query-640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6.json b/.sqlx/query-7c0612c75054dcec80d9885ac7d889facfee2c0d2810b6ae874253c9f7297552.jsonsimilarity index 63%rename from .sqlx/query-640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6.jsonrename to .sqlx/query-7c0612c75054dcec80d9885ac7d889facfee2c0d2810b6ae874253c9f7297552.jsonindex 2f7e827b5f..660d3d9fd5 100644--- a/.sqlx/query-640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6.json+++ b/.sqlx/query-7c0612c75054dcec80d9885ac7d889facfee2c0d2810b6ae874253c9f7297552.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE scheduled_action\n SET claimed = $1, claim_token = $4, updated_at = now()\n WHERE id = $2\n AND configuration_revision = $5\n AND (claimed IS NULL OR claimed < $3)\n ",+ "query": "\n UPDATE scheduled_action\n SET claimed = $1, claim_token = $4, updated_at = now()\n WHERE id = $2\n AND configuration_revision = $5\n AND next_run_at IS NOT DISTINCT FROM $6\n AND (claimed IS NULL OR claimed < $3)\n ","describe": {"columns": [],"parameters": {@@ -9,10 +9,11 @@"Uuid","Timestamptz","Uuid",- "Int8"+ "Int8",+ "Timestamptz"]},"nullable": []},- "hash": "640a0155a74ead75139874494dc1e5d02af88a1f6cb855e3fc47cf4c923f7ac6"+ "hash": "7c0612c75054dcec80d9885ac7d889facfee2c0d2810b6ae874253c9f7297552"}diff --git a/.sqlx/query-3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034.json b/.sqlx/query-80e76788123cb29ab687dd0f1e68b4b4e5e3b8185b860a26ae9a12d8454c1301.jsonsimilarity index 86%rename from .sqlx/query-3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034.jsonrename to .sqlx/query-80e76788123cb29ab687dd0f1e68b4b4e5e3b8185b860a26ae9a12d8454c1301.jsonindex f1bb8aeb02..6063191aff 100644--- a/.sqlx/query-3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034.json+++ b/.sqlx/query-80e76788123cb29ab687dd0f1e68b4b4e5e3b8185b860a26ae9a12d8454c1301.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE id = $1\n ",+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config\n FROM scheduled_action\n WHERE id = $1\n ","describe": {"columns": [{@@ -82,6 +82,11 @@"ordinal": 15,"name": "event_activated_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "trigger_config",+ "type_info": "Jsonb"}],"parameters": {@@ -105,8 +110,9 @@false,true,false,+ true,true]},- "hash": "3319425b09d174caa61311c5db42f9b1bb5bb2b9cf667e4331b6b076810dd034"+ "hash": "80e76788123cb29ab687dd0f1e68b4b4e5e3b8185b860a26ae9a12d8454c1301"}diff --git a/.sqlx/query-2f93274eec14c8c17d59251484b537247921f54e4bc87384e132668d8aa618e2.json b/.sqlx/query-8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74.jsonsimilarity index 58%rename from .sqlx/query-2f93274eec14c8c17d59251484b537247921f54e4bc87384e132668d8aa618e2.jsonrename to .sqlx/query-8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74.jsonindex dc31ec9d13..f3567ed6c2 100644--- a/.sqlx/query-2f93274eec14c8c17d59251484b537247921f54e4bc87384e132668d8aa618e2.json+++ b/.sqlx/query-8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id AS action_id, owner, enabled, configuration_revision,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE enabled AND trigger_type = 'events'\n AND ($1::uuid IS NULL OR id > $1)\n AND event_activated_at <= $2\n AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))\n AND jsonb_path_exists(event_filters,\n '$[*] ? (@.events[*] == $event && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $3::text, 'id', $4::text))\n ORDER BY id\n LIMIT $5\n ",+ "query": "\n SELECT id AS action_id, owner, enabled, configuration_revision,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action\n WHERE enabled AND event_filters IS NOT NULL\n AND ($1::uuid IS NULL OR id > $1)\n AND event_activated_at <= $2\n AND (event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))\n OR ($6::text IS NOT NULL AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($6::text)))))\n AND jsonb_path_exists(event_filters,\n '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $3::text, 'general', $6::text, 'id', $4::text))\n ORDER BY id\n LIMIT $5\n ","describe": {"columns": [{@@ -40,7 +40,8 @@"Timestamptz","Text","Text",- "Int8"+ "Int8",+ "Text"]},"nullable": [@@ -52,5 +53,5 @@true]},- "hash": "2f93274eec14c8c17d59251484b537247921f54e4bc87384e132668d8aa618e2"+ "hash": "8aeb6e474551bb19376204018239a63702e2d335f18fd474bd47d74235c9fd74"}diff --git a/.sqlx/query-0a3baa89d91ac0fd02d0562bffdf06f44686bd5d0fbf5d8ea9c2301876b3ae1d.json b/.sqlx/query-8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542.jsonsimilarity index 64%rename from .sqlx/query-0a3baa89d91ac0fd02d0562bffdf06f44686bd5d0fbf5d8ea9c2301876b3ae1d.jsonrename to .sqlx/query-8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542.jsonindex c1dcf0c660..73de6aa0c9 100644--- a/.sqlx/query-0a3baa89d91ac0fd02d0562bffdf06f44686bd5d0fbf5d8ea9c2301876b3ae1d.json+++ b/.sqlx/query-8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE scheduled_action\n SET next_run_at = $1, updated_at = now()\n WHERE id = $2 AND trigger_type = 'cron'\n ",+ "query": "\n UPDATE scheduled_action\n SET next_run_at = $1, updated_at = now()\n WHERE id = $2 AND trigger_type IN ('cron', 'multiple')\n ","describe": {"columns": [],"parameters": {@@ -11,5 +11,5 @@},"nullable": []},- "hash": "0a3baa89d91ac0fd02d0562bffdf06f44686bd5d0fbf5d8ea9c2301876b3ae1d"+ "hash": "8d484fc6738f586d946f9b99af4c33c1f0d331db120ce796a8d13170b8b0b542"}diff --git a/.sqlx/query-ebc6ea2316723aca58d21ffa1e8ce226a66a8beeb3adf5adace18422d905c716.json b/.sqlx/query-913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d.jsonsimilarity index 76%rename from .sqlx/query-ebc6ea2316723aca58d21ffa1e8ce226a66a8beeb3adf5adace18422d905c716.jsonrename to .sqlx/query-913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d.jsonindex 0959af9b34..af27e6d879 100644--- a/.sqlx/query-ebc6ea2316723aca58d21ffa1e8ce226a66a8beeb3adf5adace18422d905c716.json+++ b/.sqlx/query-913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE scheduled_action_event_run r\n SET state = 'finished', finished_at = $3,\n outcome = CASE WHEN r.state = 'started' THEN $4::jsonb\n WHEN NOT a.enabled THEN $5::jsonb ELSE $6::jsonb END\n FROM scheduled_action a\n WHERE r.action_id = $1 AND r.event_id = $2 AND a.id = r.action_id\n AND ((r.state = 'started' AND r.deadline <= $3)\n OR (r.state = 'pending' AND (NOT a.enabled OR a.trigger_type <> 'events'\n OR a.configuration_revision <> r.configuration_revision)))\n RETURNING r.claim_token\n ",+ "query": "\n UPDATE scheduled_action_event_run r\n SET state = 'finished', finished_at = $3,\n outcome = CASE WHEN r.state = 'started' THEN $4::jsonb\n WHEN NOT a.enabled THEN $5::jsonb ELSE $6::jsonb END\n FROM scheduled_action a\n WHERE r.action_id = $1 AND r.event_id = $2 AND a.id = r.action_id\n AND ((r.state = 'started' AND r.deadline <= $3)\n OR (r.state = 'pending' AND (NOT a.enabled OR a.event_filters IS NULL\n OR a.configuration_revision <> r.configuration_revision)))\n RETURNING r.claim_token\n ","describe": {"columns": [{@@ -23,5 +23,5 @@true]},- "hash": "ebc6ea2316723aca58d21ffa1e8ce226a66a8beeb3adf5adace18422d905c716"+ "hash": "913ed91869fb2be6290d3a8c53726135a89cc8ba5a1f076ac6f03a429b8c1c2d"}diff --git a/.sqlx/query-284c0e3e8f0f53e13fce4a7f67d6d9d7eaf77fac610f2275facf75c3a9f62cfe.json b/.sqlx/query-b1d38287cc76d860d2f2351d8db7e81c8fb33c9c9dd60e0fb4d5cf192ce17ea0.jsonsimilarity index 85%rename from .sqlx/query-284c0e3e8f0f53e13fce4a7f67d6d9d7eaf77fac610f2275facf75c3a9f62cfe.jsonrename to .sqlx/query-b1d38287cc76d860d2f2351d8db7e81c8fb33c9c9dd60e0fb4d5cf192ce17ea0.jsonindex c9c4920508..85b5727baa 100644--- a/.sqlx/query-284c0e3e8f0f53e13fce4a7f67d6d9d7eaf77fac610f2275facf75c3a9f62cfe.json+++ b/.sqlx/query-b1d38287cc76d860d2f2351d8db7e81c8fb33c9c9dd60e0fb4d5cf192ce17ea0.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id AS action_id, owner, enabled, configuration_revision,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action WHERE id = $1 AND trigger_type = 'events'\n ",+ "query": "\n SELECT id AS action_id, owner, enabled, configuration_revision,\n event_filters AS \"event_filters!\", event_activated_at AS \"event_activated_at!\"\n FROM scheduled_action WHERE id = $1 AND event_filters IS NOT NULL\n ","describe": {"columns": [{@@ -48,5 +48,5 @@true]},- "hash": "284c0e3e8f0f53e13fce4a7f67d6d9d7eaf77fac610f2275facf75c3a9f62cfe"+ "hash": "b1d38287cc76d860d2f2351d8db7e81c8fb33c9c9dd60e0fb4d5cf192ce17ea0"}diff --git a/.sqlx/query-fe74b0a1d240c9ca0472d60285189bb83374d4cad48ebcf2285729746544597e.json b/.sqlx/query-b2341ff8d657a9525bf71df2be787760514277531b9a3b8d7fc0379cf44d3b80.jsonsimilarity index 62%rename from .sqlx/query-fe74b0a1d240c9ca0472d60285189bb83374d4cad48ebcf2285729746544597e.jsonrename to .sqlx/query-b2341ff8d657a9525bf71df2be787760514277531b9a3b8d7fc0379cf44d3b80.jsonindex faf05eaa25..6362fd45ca 100644--- a/.sqlx/query-fe74b0a1d240c9ca0472d60285189bb83374d4cad48ebcf2285729746544597e.json+++ b/.sqlx/query-b2341ff8d657a9525bf71df2be787760514277531b9a3b8d7fc0379cf44d3b80.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT schedule, timezone, trigger_type\n FROM scheduled_action\n WHERE id = $1\n FOR UPDATE\n ",+ "query": "\n SELECT schedule, timezone, trigger_type, trigger_config\n FROM scheduled_action\n WHERE id = $1\n FOR UPDATE\n ","describe": {"columns": [{@@ -17,6 +17,11 @@"ordinal": 2,"name": "trigger_type","type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "trigger_config",+ "type_info": "Jsonb"}],"parameters": {@@ -27,8 +32,9 @@"nullable": [true,true,- false+ false,+ true]},- "hash": "fe74b0a1d240c9ca0472d60285189bb83374d4cad48ebcf2285729746544597e"+ "hash": "b2341ff8d657a9525bf71df2be787760514277531b9a3b8d7fc0379cf44d3b80"}diff --git a/.sqlx/query-e320109ff316b46278dbefa1039a37d9109a68551860e895e8d705017aca41e0.json b/.sqlx/query-b364fa333fab9bd60a2158c63add7b26c39cc3f92b66450efdb5883a89d3e296.jsonsimilarity index 86%rename from .sqlx/query-e320109ff316b46278dbefa1039a37d9109a68551860e895e8d705017aca41e0.jsonrename to .sqlx/query-b364fa333fab9bd60a2158c63add7b26c39cc3f92b66450efdb5883a89d3e296.jsonindex cac4573e16..320d3870d1 100644--- a/.sqlx/query-e320109ff316b46278dbefa1039a37d9109a68551860e895e8d705017aca41e0.json+++ b/.sqlx/query-b364fa333fab9bd60a2158c63add7b26c39cc3f92b66450efdb5883a89d3e296.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n FROM scheduled_action\n WHERE owner = $1\n ",+ "query": "\n SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config\n FROM scheduled_action\n WHERE owner = $1\n ","describe": {"columns": [{@@ -82,6 +82,11 @@"ordinal": 15,"name": "event_activated_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "trigger_config",+ "type_info": "Jsonb"}],"parameters": {@@ -105,8 +110,9 @@false,true,false,+ true,true]},- "hash": "e320109ff316b46278dbefa1039a37d9109a68551860e895e8d705017aca41e0"+ "hash": "b364fa333fab9bd60a2158c63add7b26c39cc3f92b66450efdb5883a89d3e296"}diff --git a/.sqlx/query-ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934.json b/.sqlx/query-bb82d0f1e3fe24a712cc4db9bfafd83b0053090f68cd1850978ab763267d1c2f.jsonsimilarity index 67%rename from .sqlx/query-ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934.jsonrename to .sqlx/query-bb82d0f1e3fe24a712cc4db9bfafd83b0053090f68cd1850978ab763267d1c2f.jsonindex cc158d0458..1a138233cd 100644--- a/.sqlx/query-ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934.json+++ b/.sqlx/query-bb82d0f1e3fe24a712cc4db9bfafd83b0053090f68cd1850978ab763267d1c2f.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n trigger_type = $8,\n event_filters = $9,\n configuration_revision = $10,\n event_activated_at = $11,\n updated_at = now()\n WHERE id = $12\n AND configuration_revision = $10::bigint - 1\n AND (\n claimed IS NULL OR claimed < $13\n OR (\n NOT $7 AND name = $1 AND kind = $3 AND task = $5\n AND trigger_type = $8\n AND schedule IS NOT DISTINCT FROM $2\n AND timezone IS NOT DISTINCT FROM $4\n AND event_filters IS NOT DISTINCT FROM $9\n )\n )\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at\n ",+ "query": "\n UPDATE scheduled_action\n SET name = $1,\n schedule = $2,\n kind = $3,\n timezone = $4,\n task = $5,\n next_run_at = $6,\n enabled = $7,\n trigger_type = $8,\n event_filters = $9,\n configuration_revision = $10,\n event_activated_at = $11,\n trigger_config = $14,\n updated_at = now()\n WHERE id = $12\n AND configuration_revision = $10::bigint - 1\n AND (\n claimed IS NULL OR claimed < $13\n OR (\n NOT $7 AND name = $1 AND kind = $3 AND task = $5\n AND trigger_type = $8\n AND schedule IS NOT DISTINCT FROM $2\n AND timezone IS NOT DISTINCT FROM $4\n AND event_filters IS NOT DISTINCT FROM $9\n AND trigger_config IS NOT DISTINCT FROM $14\n )\n )\n RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,\n updated_at, next_run_at, enabled, trigger_type, event_filters,\n configuration_revision, event_activated_at, trigger_config\n ","describe": {"columns": [{@@ -82,6 +82,11 @@"ordinal": 15,"name": "event_activated_at","type_info": "Timestamptz"+ },+ {+ "ordinal": 16,+ "name": "trigger_config",+ "type_info": "Jsonb"}],"parameters": {@@ -98,7 +103,8 @@"Int8","Timestamptz","Uuid",- "Timestamptz"+ "Timestamptz",+ "Jsonb"]},"nullable": [@@ -117,8 +123,9 @@false,true,false,+ true,true]},- "hash": "ede240f34972b67da0876150e37e382f7b1c28ea0ad00f2ba330dfe8a3441934"+ "hash": "bb82d0f1e3fe24a712cc4db9bfafd83b0053090f68cd1850978ab763267d1c2f"}diff --git a/.sqlx/query-e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85.json b/.sqlx/query-e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85.jsonnew file mode 100644index 0000000000..1635e54169--- /dev/null+++ b/.sqlx/query-e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85.json@@ -0,0 +1,27 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id FROM scheduled_action\n WHERE id = $1 AND enabled AND event_filters IS NOT NULL\n AND configuration_revision = $2 AND event_activated_at <= $3\n AND jsonb_path_exists(event_filters,\n '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',\n jsonb_build_object('event', $4::text, 'general', $6::text, 'id', $5::text))\n FOR UPDATE\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Int8",+ "Timestamptz",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e9143fe62b3d30824350ef192e09deababb09d166ef240b5be2edf39545ebc85"+}diff --git a/Cargo.lock b/Cargo.lockindex fb27139eed..74607ea1cb 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -902,6 +902,7 @@ dependencies = ["lazy_static","lexical_client","lexical_mention_extractor",+ "macro_auth","macro_aws_config","macro_db_client","macro_env",@@ -936,6 +937,7 @@ dependencies = ["remote_env_var","reqwest 0.13.4","rootcause",+ "routines","schemars 1.2.1","search_service_client","secretsmanager_client",@@ -15781,6 +15783,27 @@ dependencies = ["tracing-subscriber",]+[[package]]+name = "routines"+version = "0.1.0"+dependencies = [+ "ai_toolset",+ "anyhow",+ "async-trait",+ "chrono",+ "chrono-tz",+ "cron",+ "macro_authorization",+ "macro_user_id",+ "reqwest 0.13.4",+ "schemars 1.2.1",+ "serde",+ "serde_json",+ "tokio",+ "uuid",+ "workspace-hack",+]+[[package]]name = "rowan"version = "0.16.1"@@ -16197,29 +16220,26 @@ name = "scheduled_action"version = "0.1.0"dependencies = ["activity",- "agent","agent_runtime_protocol","agent_session","ai_billing",- "ai_tools",- "ai_toolset","ai_usage","anyhow","aws-sdk-secretsmanager",- "aws-sdk-sqs","axum","bot_id","bots","channel_sender","channels",- "chat","chrono","chrono-tz","connection_gateway_client","cron","database_env_vars",+ "document_sub_type","documents","doppler-config",+ "email","entity_access","entity_access_db_utils","entity_registry",@@ -16238,18 +16258,16 @@ dependencies = ["macro_env_var","macro_event_broker","macro_event_topics",- "macro_queues","macro_service_urls","macro_user_id","macro_uuid",- "memory","messages","model","model-entity",- "model_notifications","model_owner","models_permissions",- "notification",+ "models_properties",+ "properties","rdkafka","reqwest 0.13.4","roles_and_permissions",@@ -16259,6 +16277,7 @@ dependencies = ["serde_json","share_permission_db_utils","sqlx",+ "system_properties","teams","thiserror 2.0.18","tokio",diff --git a/Cargo.toml b/Cargo.tomlindex a4c2947c3d..c723579ab1 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -2,6 +2,7 @@resolver = "2"members = [+ "crates/routines","crates/activity","crates/agent", "crates/agent_changes", "crates/agent_egress", "crates/agent_fold","crates/agent_harness",diff --git a/apps/docs/AI/mcp/tools/create-routine.mdx b/apps/docs/AI/mcp/tools/create-routine.mdxnew file mode 100644index 0000000000..11b44c8d4c--- /dev/null+++ b/apps/docs/AI/mcp/tools/create-routine.mdx@@ -0,0 +1,15 @@+---+title: CreateRoutine+description: >-+ Schedule recurring or one-off work for a model or agent.+---++# CreateRoutine++Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `configuration` | RoutineConfiguration | Yes | Complete user-editable configuration, independent of execution bookkeeping. |diff --git a/apps/docs/AI/mcp/tools/edit-document.mdx b/apps/docs/AI/mcp/tools/edit-document.mdxindex 947d67a22c..999b93cff7 100644--- a/apps/docs/AI/mcp/tools/edit-document.mdx+++ b/apps/docs/AI/mcp/tools/edit-document.mdx@@ -7,7 +7,7 @@ description: >-# EditDocument-Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.+Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.## Parametersdiff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdxindex c232f3709e..ccf159d9bc 100644--- a/apps/docs/AI/mcp/tools/index.mdx+++ b/apps/docs/AI/mcp/tools/index.mdx@@ -24,6 +24,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [CreateInitiative](/AI/mcp/tools/create-initiative)- [CreateProject](/AI/mcp/tools/create-project)- [CreateReminder](/AI/mcp/tools/create-reminder)+- [CreateRoutine](/AI/mcp/tools/create-routine)- [CreateTag](/AI/mcp/tools/create-tag)- [DeleteBot](/AI/mcp/tools/delete-bot)- [DeleteCalendarEvent](/AI/mcp/tools/delete-calendar-event)@@ -59,6 +60,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ListLabels](/AI/mcp/tools/list-labels)- [ListNotifications](/AI/mcp/tools/list-notifications)- [ListReminders](/AI/mcp/tools/list-reminders)+- [ListRoutines](/AI/mcp/tools/list-routines)- [ListSkills](/AI/mcp/tools/list-skills)- [ListTags](/AI/mcp/tools/list-tags)- [ListTeamMembers](/AI/mcp/tools/list-team-members)@@ -82,6 +84,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [ReadMetadata](/AI/mcp/tools/read-metadata)- [ReadPresentation](/AI/mcp/tools/read-presentation)- [ReadProject](/AI/mcp/tools/read-project)+- [ReadRoutine](/AI/mcp/tools/read-routine)- [ReadSkill](/AI/mcp/tools/read-skill)- [ReadSpreadsheet](/AI/mcp/tools/read-spreadsheet)- [ReadThread](/AI/mcp/tools/read-thread)@@ -105,6 +108,7 @@ These pages are generated from Macro's Rust MCP tool registry.- [UpdateInitiative](/AI/mcp/tools/update-initiative)- [UpdateInitiativeSharing](/AI/mcp/tools/update-initiative-sharing)- [UpdateReminder](/AI/mcp/tools/update-reminder)+- [UpdateRoutine](/AI/mcp/tools/update-routine)- [UpdateThreadLabels](/AI/mcp/tools/update-thread-labels)- [UploadFile](/AI/mcp/tools/upload-file)- [WebFetch](/AI/mcp/tools/web-fetch)diff --git a/apps/docs/AI/mcp/tools/list-routines.mdx b/apps/docs/AI/mcp/tools/list-routines.mdxnew file mode 100644index 0000000000..f6a790b522--- /dev/null+++ b/apps/docs/AI/mcp/tools/list-routines.mdx@@ -0,0 +1,17 @@+---+title: ListRoutines+description: >-+ Find the authenticated user’s routines, including work delegated to other+ agents.+---++# ListRoutines++Find the authenticated user’s routines, including work delegated to other agents. Filter by name/instructions or enabled state. Returns up to 50 matches and the full count; narrow the query if truncated. Use ReadRoutine for history.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `query` | string | No | Optional text to match in the routine name or task. |+| `enabled` | boolean | No | Optional active/paused filter. |diff --git a/apps/docs/AI/mcp/tools/read-routine.mdx b/apps/docs/AI/mcp/tools/read-routine.mdxnew file mode 100644index 0000000000..f5aa54564b--- /dev/null+++ b/apps/docs/AI/mcp/tools/read-routine.mdx@@ -0,0 +1,16 @@+---+title: ReadRoutine+description: >-+ Read a routine owned by the authenticated user, including its saved+ configuration and recent run history.+---++# ReadRoutine++Read a routine owned by the authenticated user, including its saved configuration and recent run history. Reading a run transcript still requires its own access.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `routineId` | string | Yes | Routine UUID from CreateRoutine or ListRoutines. |diff --git a/apps/docs/AI/mcp/tools/update-routine.mdx b/apps/docs/AI/mcp/tools/update-routine.mdxnew file mode 100644index 0000000000..555882e334--- /dev/null+++ b/apps/docs/AI/mcp/tools/update-routine.mdx@@ -0,0 +1,17 @@+---+title: UpdateRoutine+description: >-+ Pause/resume or replace the configuration of a routine owned by the+ authenticated user.+---++# UpdateRoutine++Pause/resume or replace the configuration of a routine owned by the authenticated user. ReadRoutine first before replacing configuration. Select an agent to delegate the routine or a model to run as Macro. Does not change ownership. A running routine can be paused but cannot be reconfigured until it finishes.++## Parameters++| Parameter | Type | Required | Description |+| --- | --- | --- | --- |+| `routineId` | string | Yes | Routine UUID. |+| `change` | RoutineChange | Yes | Exactly one update intention avoids partially-applied configuration/activation changes. |diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.jsonindex e41807400c..c5e8720a1b 100644--- a/apps/docs/config/tool-pages.json+++ b/apps/docs/config/tool-pages.json@@ -15,6 +15,7 @@"AI/mcp/tools/create-initiative","AI/mcp/tools/create-project","AI/mcp/tools/create-reminder",+ "AI/mcp/tools/create-routine","AI/mcp/tools/create-tag","AI/mcp/tools/delete-bot","AI/mcp/tools/delete-calendar-event",@@ -50,6 +51,7 @@"AI/mcp/tools/list-labels","AI/mcp/tools/list-notifications","AI/mcp/tools/list-reminders",+ "AI/mcp/tools/list-routines","AI/mcp/tools/list-skills","AI/mcp/tools/list-tags","AI/mcp/tools/list-team-members",@@ -73,6 +75,7 @@"AI/mcp/tools/read-metadata","AI/mcp/tools/read-presentation","AI/mcp/tools/read-project",+ "AI/mcp/tools/read-routine","AI/mcp/tools/read-skill","AI/mcp/tools/read-spreadsheet","AI/mcp/tools/read-thread",@@ -96,6 +99,7 @@"AI/mcp/tools/update-initiative","AI/mcp/tools/update-initiative-sharing","AI/mcp/tools/update-reminder",+ "AI/mcp/tools/update-routine","AI/mcp/tools/update-thread-labels","AI/mcp/tools/upload-file","AI/mcp/tools/web-fetch",diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex e527b81d36..3d5cf6dda1 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -86,6 +86,7 @@"AI/mcp/tools/create-initiative","AI/mcp/tools/create-project","AI/mcp/tools/create-reminder",+ "AI/mcp/tools/create-routine","AI/mcp/tools/create-tag","AI/mcp/tools/delete-bot","AI/mcp/tools/delete-calendar-event",@@ -121,6 +122,7 @@"AI/mcp/tools/list-labels","AI/mcp/tools/list-notifications","AI/mcp/tools/list-reminders",+ "AI/mcp/tools/list-routines","AI/mcp/tools/list-skills","AI/mcp/tools/list-tags","AI/mcp/tools/list-team-members",@@ -144,6 +146,7 @@"AI/mcp/tools/read-metadata","AI/mcp/tools/read-presentation","AI/mcp/tools/read-project",+ "AI/mcp/tools/read-routine","AI/mcp/tools/read-skill","AI/mcp/tools/read-spreadsheet","AI/mcp/tools/read-thread",@@ -167,6 +170,7 @@"AI/mcp/tools/update-initiative","AI/mcp/tools/update-initiative-sharing","AI/mcp/tools/update-reminder",+ "AI/mcp/tools/update-routine","AI/mcp/tools/update-thread-labels","AI/mcp/tools/upload-file","AI/mcp/tools/web-fetch",diff --git a/apps/marketing/src/features/marketing/components/demo-agents-view.css b/apps/marketing/src/features/marketing/components/demo-agents-view.cssindex d9e0c06d13..c98342a76e 100644--- a/apps/marketing/src/features/marketing/components/demo-agents-view.css+++ b/apps/marketing/src/features/marketing/components/demo-agents-view.css@@ -1983,7 +1983,7 @@min-width: 150px;}- /* routine block page (block-automation/component/Automation.tsx) */+ /* routine block page (routines/routine-detail.tsx) */:where(.agents-view, .agents-view-portal) .switch {display: inline-flex;align-items: center;diff --git a/apps/web/src/components/app/GlobalHotkeys.tsx b/apps/web/src/components/app/GlobalHotkeys.tsxindex 37929b9596..170c4489dd 100644--- a/apps/web/src/components/app/GlobalHotkeys.tsx+++ b/apps/web/src/components/app/GlobalHotkeys.tsx@@ -15,10 +15,6 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useSubscribeToKeypress } from '@app/signal/hotkeyRoot';import { globalSplitManager } from '@app/signal/splitLayout';import { useHandleFileUpload } from '@app/util/handleFileUpload';-import {- automationComposerOpen,- setAutomationComposerOpen,-} from '@block-automation/component';import { useLogout } from '@core/auth/logout';import { useOpenInstructionsMd } from '@core/component/AI/util/instructions';import { toast } from '@core/component/Toast/Toast';@@ -148,10 +144,6 @@ export default function GlobalShortcuts() {const willOpen = !CommandState.isOpen();if (willOpen) {- if (automationComposerOpen()) {- setAutomationComposerOpen(false, false);- }-analytics.track('command_menu_open', { from: 'global_hotkey' });}@@ -164,10 +156,6 @@ export default function GlobalShortcuts() {scopeId: 'global',description: 'Create',keyDownHandler: () => {- if (automationComposerOpen()) {- return true;- }-const willOpen = !createMenuOpen();if (willOpen) {diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex cabb828203..9a585cfa0f 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -33,7 +33,6 @@ import { useOnboardingV4Flag } from '@app/features/setup/flow/useOnboardingV4Flaimport { NativeShareSheet } from '@app/features/sharing/native-share-sheet/NativeShareSheet';import { ShowFeatureFlag } from '@app/lib/analytics/posthog';import { mountGlobalFocusListener } from '@app/signal/focus';-import { AutomationComposer } from '@block-automation/component';import { CreateChannelModal } from '@channel/CreateChannelModal';import { GoToHotkeys } from '@components/app/app-sidebar/sidebar';import { registerMailtoComposerHandler } from '@components/app/mailtoComposerHandler';@@ -315,7 +314,6 @@ function LayoutInner(props: RouteSectionProps) {when={isAuthenticated() && !AUTH_URLS.includes(location.pathname)}><Launcher open={createMenuOpen()} onOpenChange={setCreateMenuOpen} />- <AutomationComposer /></Show></Suspense><DevStatusBar />diff --git a/apps/web/src/components/app/previewTarget.ts b/apps/web/src/components/app/previewTarget.tsindex 300098ee76..1fb9618b99 100644--- a/apps/web/src/components/app/previewTarget.ts+++ b/apps/web/src/components/app/previewTarget.ts@@ -31,7 +31,7 @@ type IdOnlyPreviewSelection = {id: string;type:| 'agent_session'- | 'automation'+ | 'routine'| 'call'| 'chat'| 'crm_company'diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsxindex daed4e86f4..8051b4eac4 100644--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx@@ -28,6 +28,7 @@ import { ReminderEditorSplit } from '@app/features/reminders/ReminderEditorSplitimport { REMINDER_DETAIL_COMPONENT_ID } from '@app/features/reminders/reminder-navigation';import { RemindersRouteView } from '@app/features/reminders/route-views';import { ReviewsRouteView } from '@app/features/reviews-view/route-views';+import { RoutineCreator } from '@app/features/routines/routine-creator';import { SettingsRouteView } from '@app/features/settings/route-views';import { TasksRouteView } from '@app/features/tasks-view/route-views';import { useFeatureFlag } from '@app/lib/analytics/posthog';@@ -226,6 +227,11 @@ registerComponent(NOT_FOUND_ROUTE_ID, () => <NotFound />);registerComponent('recent', () => <RecentRouteView />);registerComponent('activity', () => <ActivityRouteView />);registerComponent('reminders', () => <RemindersRouteView />);+registerComponent(+ 'routines',+ () => <AgentsRouteView />,+ () => composableLayout()+);registerComponent('agents',() => <AgentsRouteView />,@@ -314,6 +320,15 @@ registerComponent('email-compose', (params) => {/>);});+registerComponent('routine-compose', (params) => (+ <RoutineCreator+ onCreated={+ typeof params.onCreated === 'function'+ ? (params.onCreated as (id: string) => void)+ : undefined+ }+ />+));registerComponent('task-compose', (params) => {usePageViewTracking('task-compose');return <ComposeTask {...params} />;diff --git a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx b/apps/web/src/components/app/split-layout/components/SplitHeader.tsxindex 2a607dbcd3..d5fc2ae99d 100644--- a/apps/web/src/components/app/split-layout/components/SplitHeader.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitHeader.tsx@@ -113,7 +113,7 @@ function getEntitySplitContent(data: EntityDragEvent['draggable']['data']):'email','project','call',- 'automation',+ 'routine','database'),},diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.tsindex d72b50f1cd..82f40983b7 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts@@ -18,6 +18,14 @@ import {reminderDetailContent,reminderIdFromDetailContent,} from '@app/features/reminders/reminder-navigation';+import {+ ROUTINE_CREATE_ROUTE_ID,+ ROUTINE_DETAIL_ROUTE_ID,+ ROUTINES_ROUTE_ID,+ routineContent,+ routineIdFromContent,+ routineLocation,+} from '@app/features/routines/routine-navigation';import {canonicalRoute,decodePane,@@ -58,6 +66,8 @@ export function decodeLegacyPair(): SplitContent | undefined {if (!type || !id) return;+ if (type === 'routine' || type === 'automation') return routineContent(id);+const agentsRoute = agentsRouteFromSegments(type, id);if (agentsRoute) return { type: 'component', id: agentsRoute };@@ -100,6 +110,7 @@ export function decodeLegacyPair(}function legacyLocation(type: string, id: string): SplitLocation | undefined {+ if (type === 'routine' || type === 'automation') return routineLocation(id);const agentsRoute = agentsRouteFromSegments(type, id);if (agentsRoute) {return { route: paneRoute({ id: type, params: { id } }) };@@ -134,6 +145,8 @@ export function handleLegacySplitPath(if (context.matchedRouteId &&context.matchedRouteId !== 'settings' &&+ context.matchedRouteId !== ROUTINE_DETAIL_ROUTE_ID &&+ context.matchedRouteId !== ROUTINE_CREATE_ROUTE_ID &&!context.matchedRouteId.startsWith('view-') &&context.matchedRouteId !== 'legacy-content') {@@ -208,6 +221,23 @@ export function splitLocationFromContent(routes: SplitRoutesManifest,content: SplitContent): SplitLocation {+ // Persisted panes can still contain the old block discriminator.+ if (['routine', 'automation'].includes(content.type))+ return routineLocation(content.id);+ if (content.type === 'component' && content.id === 'routines') {+ return routineLocation(routineIdFromContent(content));+ }+ if (+ content.type === 'component' &&+ content.id === 'agents' &&+ content.params?.agentPage === 'routines'+ ) {+ return routineLocation(+ typeof content.params.routineId === 'string'+ ? content.params.routineId+ : undefined+ );+ }const reminderId =content.type === 'component' && content.id === REMINDER_DETAIL_COMPONENT_ID? reminderIdFromDetailContent(content)@@ -357,6 +387,15 @@ export function splitContentFromLocation(return { type: 'component', id: NOT_FOUND_ROUTE_ID };}+ if (root.id === ROUTINES_ROUTE_ID) return routineContent();+ if (root.id === ROUTINE_CREATE_ROUTE_ID) return routineContent('new');+ if (root.id === ROUTINE_DETAIL_ROUTE_ID) {+ const { routineId } = routeParams(location.route);+ if (typeof routineId === 'string' && routineId.length > 0)+ return routineContent(routineId);+ throw new Error('Invalid routine detail split route');+ }+if (root.id === REMINDER_DETAIL_ROUTE_ID) {const { reminderId } = routeParams(location.route);if (typeof reminderId === 'string' && reminderId.length > 0) {diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsxindex 88b79c4464..a5624a0cd8 100644--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx@@ -134,7 +134,7 @@ vi.mock('@core/context/user', () => ({}));vi.mock('@core/mobile/isTouchDevice', () => ({isTouchDevice: () => state.touch(),}));-vi.mock('@queries/agent-schedule/entities', () => ({}));+vi.mock('@app/features/routines/queries/entities', () => ({}));vi.mock('@ui', () => ({createVariants: () => () => '',}));diff --git a/apps/web/src/features/activity/primitives/actor-name.test.ts b/apps/web/src/features/activity/primitives/actor-name.test.tsindex 40a8663eeb..420b2fd976 100644--- a/apps/web/src/features/activity/primitives/actor-name.test.ts+++ b/apps/web/src/features/activity/primitives/actor-name.test.ts@@ -53,7 +53,7 @@ describe('createActorName', () => {);});- it('never says "Automation" for ids it cannot parse', () => {+ it('never says "Routine" for ids it cannot parse', () => {expect(nameOf(context, 'system:nightly')).toBe('Unknown');});});diff --git a/apps/web/src/features/agents-view/agents-view.css b/apps/web/src/features/agents-view/agents-view.cssindex 7f7646a4f4..cb8f3425de 100644--- a/apps/web/src/features/agents-view/agents-view.css+++ b/apps/web/src/features/agents-view/agents-view.css@@ -1984,7 +1984,7 @@min-width: 150px;}- /* routine block page (block-automation/component/Automation.tsx) */+ /* routine block page (block-routine/component/Routine.tsx) */:where(.agents-view, .agents-view-portal) .switch {display: inline-flex;align-items: center;diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsxindex 013a487f50..a115dfc038 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx@@ -148,11 +148,10 @@ describe('mixed Agents sidebar', () => {onLoadMore={vi.fn()}/>));- for (const label of ['Agents', 'Connections']) {+ for (const label of ['Agents', 'Routines', 'Connections']) {fireEvent.click(screen.getByRole('button', { name: label }));expect(openPage).toHaveBeenLastCalledWith(label.toLowerCase());}- expect(screen.queryByRole('button', { name: 'Routines' })).toBeNull();expect(screen.queryByRole('tablist')).toBeNull();const code = screen.getByRole('button', { name: /Fix build/ });const chat = screen.getByRole('button', { name: /Plan launch/ });diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.tsxindex 41689e8397..9cb27c261c 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.tsx@@ -22,6 +22,7 @@ import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { unreadFilterFn } from '@entity/utils/filter';import ChatIcon from '@phosphor/chat-circle.svg';+import RoutineIcon from '@phosphor/clock-clockwise.svg';import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';import PlugIcon from '@phosphor/plugs-connected.svg';import AgentIcon from '@phosphor/sparkle.svg';@@ -209,6 +210,7 @@ export function AgentsSidebar(props: AgentsSidebarProps) {enabled: panel.isPanelActive,search: {description: 'Search agent chats',+ condition: () => props.activePage !== 'routines',run: () => {openSearch();return true;@@ -251,6 +253,15 @@ export function AgentsSidebar(props: AgentsSidebarProps) {</ViewSidebar.Icon><span>Agents</span></ViewSidebar.Item>+ <ViewSidebar.Item+ active={props.activePage === 'routines'}+ onClick={() => props.onOpenPage('routines')}+ >+ <ViewSidebar.Icon>+ <RoutineIcon />+ </ViewSidebar.Icon>+ <span>Routines</span>+ </ViewSidebar.Item><ViewSidebar.Itemactive={props.activePage === 'connections'}onClick={() => props.onOpenPage('connections')}diff --git a/apps/web/src/features/agents-view/core/pages.ts b/apps/web/src/features/agents-view/core/pages.tsindex c1c0d3caa5..c734431313 100644--- a/apps/web/src/features/agents-view/core/pages.ts+++ b/apps/web/src/features/agents-view/core/pages.ts@@ -1,7 +1,12 @@/** Pages shown in the Agents workspace in place of a conversation. */-export type AgentsPage = 'new' | 'agents' | 'connections';+export type AgentsPage = 'new' | 'agents' | 'connections' | 'routines';export function parseAgentsPage(value: unknown): AgentsPage | undefined {- if (value === 'new' || value === 'agents' || value === 'connections')+ if (+ value === 'new' ||+ value === 'agents' ||+ value === 'connections' ||+ value === 'routines'+ )return value;}diff --git a/apps/web/src/features/agents-view/primitives/open-page.test.ts b/apps/web/src/features/agents-view/primitives/open-page.test.tsindex 23da05ad17..d2b66050fd 100644--- a/apps/web/src/features/agents-view/primitives/open-page.test.ts+++ b/apps/web/src/features/agents-view/primitives/open-page.test.ts@@ -3,6 +3,37 @@ import { describe, expect, it, vi } from 'vitest';import { openAgentsPage } from './open-page';describe('openAgentsPage', () => {+ it('opens routines using durable list and detail routes', () => {+ const openWithSplit = vi.fn(() => ({ status: 'navigating' as const }));+ openAgentsPage({ openWithSplit }, 'routines');+ openAgentsPage({ openWithSplit }, 'routines', { routineId: 'routine-1' });+ expect(openWithSplit.mock.calls).toMatchObject([+ [+ {+ id: 'routines',+ entryMetadata: {+ route: { matches: [{ id: 'app' }, { id: 'view-routines' }] },+ },+ },+ { activate: true, search: {} },+ ],+ [+ {+ id: 'routines',+ entryMetadata: {+ route: {+ matches: [+ { id: 'app' },+ { id: 'routine-detail', params: { routineId: 'routine-1' } },+ ],+ },+ },+ },+ { activate: true, search: {} },+ ],+ ]);+ });+it('requests Connections again when the workspace is already open on another page', () => {let content: SplitContent = { type: 'component', id: 'agents' };const replace = vi.fn(({ next }: { next: SplitContent }) => {diff --git a/apps/web/src/features/agents-view/primitives/open-page.ts b/apps/web/src/features/agents-view/primitives/open-page.tsindex e8f37f8056..8dfe07cfee 100644--- a/apps/web/src/features/agents-view/primitives/open-page.ts+++ b/apps/web/src/features/agents-view/primitives/open-page.ts@@ -1,16 +1,31 @@import type { SplitManager } from '@components/app/split-layout/layoutManager';+import { routineContent } from '../../routines/routine-navigation';import type { AgentsPage } from '../core/pages';/** Open a workspace page, also when an Agents split is already mounted. */export function openAgentsPage(layout: Pick<SplitManager, 'openWithSplit'>,- page: AgentsPage+ page: AgentsPage,+ params: Record<string, unknown> = {}) {+ if (page === 'routines') {+ layout.openWithSplit(+ routineContent(+ typeof params.routineId === 'string' ? params.routineId : undefined+ ),+ { activate: true, search: {} }+ );+ return;+ }const content = {type: 'component' as const,id: 'agents',preserveParams: true,- params: { agentPage: page, agentPageRequest: crypto.randomUUID() },+ params: {+ ...params,+ agentPage: page,+ agentPageRequest: crypto.randomUUID(),+ },};const split = layout.openWithSplit(content, { activate: true }).split;if (!split) return;diff --git a/apps/web/src/features/agents-view/route-views.test.tsx b/apps/web/src/features/agents-view/route-views.test.tsxindex d20e81e07c..178d747822 100644--- a/apps/web/src/features/agents-view/route-views.test.tsx+++ b/apps/web/src/features/agents-view/route-views.test.tsx@@ -49,7 +49,7 @@ vi.mock('@core/context/user', () => ({}));vi.mock('@core/mobile/isTouchDevice', () => ({isTouchDevice: () => state.touch,}));-vi.mock('@queries/agent-schedule/entities', () => ({}));+vi.mock('@app/features/routines/queries/entities', () => ({}));vi.mock('../next-soup/sidebar/soup-filter-presets', () => ({}));vi.mock('./views/AgentsView', () => ({ AgentsView: () => null }));vi.mock('../settings/McpConnections', () => ({ McpConnections: () => null }));diff --git a/apps/web/src/features/agents-view/route-views.tsx b/apps/web/src/features/agents-view/route-views.tsxindex bc227f477b..e23ec74e90 100644--- a/apps/web/src/features/agents-view/route-views.tsx+++ b/apps/web/src/features/agents-view/route-views.tsx@@ -1,4 +1,6 @@+import { useRoutineEntities } from '@app/features/routines/queries/entities';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import {RedirectSplit,@@ -9,9 +11,9 @@ import { LoadingBlock } from '@core/component/LoadingBlock';import { enableChatV3Agents } from '@core/constant/featureFlags';import { useUserContext } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { useAutomationEntities } from '@queries/agent-schedule/entities';import { createRenderEffect, lazy, Show } from 'solid-js';import { getViewPreset } from '../next-soup/sidebar/soup-filter-presets';+import { routineContent } from '../routines/routine-navigation';import { parseAgentsRoute } from './core/route';const SoupView = lazy(async () => ({@@ -20,25 +22,64 @@ const SoupView = lazy(async () => ({const AgentsView = lazy(async () => ({default: (await import('./views/AgentsView')).AgentsView,}));+const RoutinesPage = lazy(async () => ({+ default: (await import('../routines/routines-page')).RoutinesPage,+}));const McpConnections = lazy(async () => ({default: (await import('../settings/McpConnections')).McpConnections,}));function LegacyAgentsView() {+ const layout = useSplitLayout();+ const panel = useSplitPanelOrThrow();const user = useUserContext();const preset = getViewPreset('agents', undefined, {userId: user.userId(),isTeamAdmin: false,});- const entities = useAutomationEntities();+ const entities = useRoutineEntities();return (- <SoupView- viewName="Agents"- initialFilters={preset?.filters}- initialClientFilters={preset?.clientFilters}- initialGroupBy={preset?.groupBy}- additionalEntities={entities}- />+ <div class="flex size-full flex-col touch:pt-(--mobile-content-inset-top)">+ <div+ class="flex gap-1 border-b border-edge-muted px-4 py-2"+ role="group"+ aria-label="Agent workspace"+ >+ <button+ type="button"+ aria-pressed={true}+ class="rounded-md px-3 py-1.5 text-sm text-ink hover:bg-hover"+ >+ Agents+ </button>+ <button+ type="button"+ aria-pressed={false}+ class="rounded-md px-3 py-1.5 text-sm text-ink hover:bg-hover"+ onClick={() =>+ layout.openWithSplit(routineContent(), {+ handle: panel.handle,+ activate: true,+ search: {},+ })+ }+ >+ Routines+ </button>+ </div>+ <div+ class="min-h-0 flex-1 overflow-auto"+ style={{ '--mobile-content-inset-top': '0px' }}+ >+ <SoupView+ viewName="Agents"+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}+ initialGroupBy={preset?.groupBy}+ additionalEntities={entities}+ />+ </div>+ </div>);}@@ -46,6 +87,7 @@ export const AgentsRouteView = withAuth(() => {const panel = useSplitPanelOrThrow();const route = () => {const content = panel.handle.content();+ if (content.type === 'component' && content.id === 'routines') return;const requested =content.type === 'component' &&typeof content.params?.agentsRoute === 'string'@@ -66,6 +108,7 @@ export const AgentsRouteView = withAuth(() => {const content = panel.handle.content();return (content.type === 'component' &&+ content.id !== 'routines' &&content.params?.agentPage === 'connections');};@@ -77,7 +120,26 @@ export const AgentsRouteView = withAuth(() => {<Showwhen={connectionsRequested()}fallback={- <Show when={route()} fallback={<LegacyAgentsView />}>+ <Show+ when={route()}+ fallback={+ <Show+ when={(() => {+ const content = panel.handle.content();+ return (+ content.type === 'component' &&+ (content.id === 'routines' ||+ content.params?.agentPage === 'routines')+ );+ })()}+ fallback={<LegacyAgentsView />}+ >+ <div class="size-full overflow-auto touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)">+ <RoutinesPage />+ </div>+ </Show>+ }+ >{(current) => (<RedirectSplitto={{diff --git a/apps/web/src/features/agents-view/tour.ts b/apps/web/src/features/agents-view/tour.tsindex 5a3b7dd539..08de61e48c 100644--- a/apps/web/src/features/agents-view/tour.ts+++ b/apps/web/src/features/agents-view/tour.ts@@ -54,7 +54,7 @@ export const agentsTour = defineViewTour({target: APP_TOUR.createMenu,title: 'Put recurring work on a schedule',description:- 'Use Create → Automation to give an agent instructions and a schedule—for example, a weekly summary or daily triage. Review the automation’s runs and pause it when you need to.',+ 'Use Create → Routine to give an agent instructions and a schedule—for example, a weekly summary or daily triage. Review the routine’s runs and pause it when you need to.',},],});diff --git a/apps/web/src/features/agents-view/views/AgentPicker.tsx b/apps/web/src/features/agents-view/views/AgentPicker.tsxindex aa3ebe2bb2..644caefe60 100644--- a/apps/web/src/features/agents-view/views/AgentPicker.tsx+++ b/apps/web/src/features/agents-view/views/AgentPicker.tsx@@ -7,7 +7,7 @@ import CaretRightIcon from '@phosphor/caret-right.svg';import CheckIcon from '@phosphor/check.svg';import CodeIcon from '@phosphor/code.svg';import PlusIcon from '@phosphor/plus.svg';-import { Dropdown } from '@ui';+import { cn, Dropdown } from '@ui';import { tourTarget } from '@ui/components/Tour';import { createSignal, For, Show } from 'solid-js';import { AgentModelMenuItem } from '../../block-agent/component/AgentModelMenuItem';@@ -31,6 +31,7 @@ export type AgentPickerProps = {selected?: RosterAgent;modelOverride?: string;loading: boolean;+ triggerClass?: string;effortLabel?: string;effortSelection?: EffortSelection;onSelect: (agent: RosterAgent, model?: string) => void;@@ -94,7 +95,10 @@ function DesktopAgentPicker(props: AgentPickerProps) {? label(): `${props.selected?.name ?? 'Choose agent'} · ${label()}`}- class="h-[33.75px] min-w-0 max-w-full gap-[5.625px] px-[7.5px] text-base font-normal text-ink-muted light-mode:text-composer-placeholder"+ class={cn(+ 'h-[33.75px] min-w-0 max-w-full gap-[5.625px] px-[7.5px] text-base font-normal text-ink-muted light-mode:text-composer-placeholder',+ props.triggerClass+ )}><Showwhen={rawModel()}diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsxindex 423749028a..7b923e936a 100644--- a/apps/web/src/features/agents-view/views/AgentsView.tsx+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx@@ -34,6 +34,8 @@ import {Suspense,Switch,} from 'solid-js';+import { routineContent } from '../../routines/routine-navigation';+import { RoutinesPage } from '../../routines/routines-page';import '../agents-view.css';import { AgentSessionPane } from '../components/AgentSessionPane';import { AgentsSidebar } from '../components/AgentsSidebar';@@ -79,7 +81,12 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {const notifications = useGlobalNotificationSource();const mode = (): AgentsMode => props.initialRoute?.mode ?? 'chat';const dataMode = () => dataModeFor(mode());- const [page, setPage] = createSignal<AgentsPage>('new');+ const [localPage, setPage] = createSignal<AgentsPage>('new');+ const isRoutinesPage = () => {+ const content = panel.handle.content();+ return content.type === 'component' && content.id === 'routines';+ };+ const page = () => (isRoutinesPage() ? 'routines' : localPage());const [selected, setSelected] = createSignal<SelectedConversation | undefined>(@@ -90,7 +97,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {}: undefined);- const [mobileList, setMobileList] = createSignal(true);+ const [mobileList, setMobileList] = createSignal(!isRoutinesPage());const [draft, setDraft] = createSignal('');const [search, setSearch] = createSignal('');const rosterSource = createAgentRosterSource();@@ -165,6 +172,26 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {);const openPage = (next: AgentsPage) => {setMobileList(false);+ if (next === 'routines') {+ layout.openWithSplit(routineContent(), {+ handle: panel.handle,+ activate: true,+ search: {},+ });+ return;+ }+ if (isRoutinesPage()) {+ layout.openWithSplit(+ {+ type: 'component',+ id: 'agents',+ preserveParams: true,+ params: { agentPage: next, agentPageRequest: crypto.randomUUID() },+ },+ { handle: panel.handle, activate: true, search: {} }+ );+ return;+ }setSelected(undefined);setPage(next);};@@ -187,9 +214,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {));const openRoster = (_kind: AgentKind) => {- setMobileList(false);- setSelected(undefined);- setPage('agents');+ openPage('agents');};const openConversation = (conversation: AgentConversationTarget,@@ -258,6 +283,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {});};const pageTitle = () => {+ if (page() === 'routines') return 'Routines';if (page() === 'agents') return 'Agents';if (page() === 'connections') return 'Connections';return 'New conversation';@@ -324,17 +350,22 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {keyedfallback={<>- <Topbar- title={pageTitle()}- onBack={- isTouchDevice()- ? () => setMobileList(true)- : undefined- }- />+ <Show when={page() !== 'routines'}>+ <Topbar+ title={pageTitle()}+ onBack={+ isTouchDevice()+ ? () => setMobileList(true)+ : undefined+ }+ />+ </Show><div class="body"><Suspense fallback={<LoadingComposer />}><Switch>+ <Match when={page() === 'routines'}>+ <RoutinesPage />+ </Match><Match when={page() === 'connections'}><McpConnections /></Match>diff --git a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsxindex f6b22b6b62..a6ec2e7dc9 100644--- a/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx+++ b/apps/web/src/features/block-agent/component/AgentSplitHeader.tsx@@ -80,7 +80,7 @@ export function agentSessionTitle(* toolbar: static label, shared entity actions, the session's pull request* once one exists, and external-provider links.*- * Rename lives on the title menu (channel / automation), not on a tap of+ * Rename lives on the title menu (channel / routine), not on a tap of* the name — `StaticSplitLabel` without `onRename` so a touch tap opens* the dropdown instead of an inline editor.*/diff --git a/apps/web/src/features/block-automation/component/Automation.tsx b/apps/web/src/features/block-automation/component/Automation.tsxdeleted file mode 100644index ae673e3d1c..0000000000--- a/apps/web/src/features/block-automation/component/Automation.tsx+++ /dev/null@@ -1,580 +0,0 @@-import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';-import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';-import { BlockSplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';-import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';-import { SplitTitleFileMenu } from '@components/app/split-layout/components/SplitLabel';-import { useSplitLayout } from '@components/app/split-layout/layout';-import {- returnSplitToRecentListView,- useSplitPanelOrThrow,-} from '@components/app/split-layout/layoutUtils';-import { useBlockId } from '@core/block';-import { EntityIcon } from '@core/component/EntityIcon';-import { toast } from '@core/component/Toast/Toast';-import { blockNameToDefaultFile } from '@core/constant/allBlocks';-import { formatDateAndTime } from '@entity';-import CopyIcon from '@phosphor/copy.svg';-import RenameIcon from '@phosphor/pencil-line.svg';-import TrashIcon from '@phosphor/trash-simple.svg';-import { scheduleToEntity } from '@queries/agent-schedule/entities';-import {- invalidateSchedules,- useCreateScheduleMutation,- useRunScheduleNowMutation,- useScheduleHistoryQuery,- useSchedulesQuery,- useSetScheduleEnabledMutation,- useUpdateScheduleMutation,-} from '@queries/agent-schedule/schedules';-import { getCronTrigger } from '@queries/agent-schedule/triggers';-import { useAgentSessionQuery } from '@queries/agent-session/session';-import { useChatQuery } from '@queries/chat';-import { Button, cn, ToggleSwitch } from '@ui';-import {- type Accessor,- createEffect,- createMemo,- createSignal,- For,- Match,- on,- onMount,- Show,- Switch,-} from 'solid-js';-import { match } from 'ts-pattern';-import { createRoutineAutosave } from '../primitives/routine-autosave';-import { RoutineExecutionPicker } from '../routine-execution-picker';-import { type HistoryMetadata, RoutineHistory } from '../views/routine-history';-import { AutomationPromptEditor } from './AutomationPromptEditor';-import { AutomationRenameModal } from './AutomationRenameModal';-import { AutomationTimePicker } from './AutomationTimePicker';-import {- describeSchedule,- draftFromSchedule,- draftToUpdateBody,- FREQUENCY_OPTIONS,- getDefaultTimezone,- getErrorMessage,- INPUT_CLASS,- isValidTime,- scheduleToDuplicateBody,- WEEKDAY_OPTIONS,-} from './automationUtils';-import type { ScheduleDraft } from './types';--function createChatHistoryMetadata(id: string): Accessor<HistoryMetadata> {- const query = useChatQuery(() => id);- return () => {- if (query.isPending) return { status: 'pending' };- if (!query.isSuccess) return { status: 'unavailable' };- const chat = query.data?.chat;- return chat- ? { status: 'ready', name: chat.name }- : { status: 'unavailable' };- };-}--function createAgentHistoryMetadata(id: string): Accessor<HistoryMetadata> {- const query = useAgentSessionQuery(() => id);- return () => {- if (query.isPending) return { status: 'pending' };- if (!query.isSuccess) return { status: 'unavailable' };- const session = query.data;- return session- ? { status: 'ready', name: session.name }- : { status: 'unavailable' };- };-}--export function Automation() {- const scheduleId = useBlockId();- const panel = useSplitPanelOrThrow();- const { openWithSplit, replaceOrInsertSplit } = useSplitLayout();-- const schedulesQuery = useSchedulesQuery(() => true);- const schedule = createMemo(() =>- schedulesQuery.isSuccess || schedulesQuery.isError- ? schedulesQuery.data?.find((item) => item.id === scheduleId)- : undefined- );- const cronTrigger = () => {- const current = schedule();- return current ? getCronTrigger(current) : undefined;- };- const scheduleEntity = () => {- const current = schedule();- return current ? scheduleToEntity(current) : undefined;- };- const status = () => scheduleEntity()?.status;- const isRunning = () => status()?.kind === 'running';- const isActive = () => schedule()?.enabled ?? false;-- const [state, setRawState] = createSignal<ScheduleDraft | undefined>();-- const currentSummary = createMemo(() => {- const d = state();- if (!d) return '';- return describeSchedule(d, cronTrigger()?.timezone ?? getDefaultTimezone());- });-- const formError = createMemo(() => {- const d = state();- if (!d) return null;- if (!d.prompt.trim()) return 'Prompt is required.';- if (!isValidTime(d.time)) return 'Choose a valid time.';- if (d.frequency === 'week' && d.daysOfWeek.length === 0) {- return 'Select at least one day.';- }- if (d.frequency === 'month') {- const day = Number(d.dayOfMonth);- if (!Number.isInteger(day) || day < 1 || day > 31) {- return 'Pick a day between 1 and 31';- }- }- return null;- });-- const updateMutation = useUpdateScheduleMutation();- const autosave = createRoutineAutosave<ScheduleDraft>(async (draft) => {- const previous = schedule();- if (!previous || !getCronTrigger(previous)) {- throw new Error('This routine is no longer editable.');- }- const body = draftToUpdateBody(draft, previous);- if (!body) throw new Error('Choose a valid execution target.');- await updateMutation.mutateAsync({ scheduleId, body });- });-- function setState(update: (prev: ScheduleDraft) => ScheduleDraft): void {- const current = state();- if (!current || !cronTrigger() || isRunning()) return;- const next = update(current);- setRawState(next);- if (next.name !== current.name) {- panel.handle.setDisplayName(next.name);- }- autosave.queue(formError() ? undefined : next);- }-- function runNow(): void {- if (- !cronTrigger() ||- !state() ||- formError() ||- autosave.dirty() ||- autosave.saving() ||- runNowMutation.isPending ||- isRunning()- )- return;- runNowMutation.mutate({ scheduleId });- }-- function initializeDraft(): void {- const current = schedule();- if (!current) return;- setRawState(draftFromSchedule(current));- panel.handle.setDisplayName(current.name);- }-- // Only entering/leaving cron editing resets the draft, never save responses.- const cronEditable = createMemo(() => Boolean(cronTrigger()));- createEffect(- on(cronEditable, (editable) => {- autosave.cancel();- if (editable) initializeDraft();- else setRawState(undefined);- })- );-- const historyQuery = useScheduleHistoryQuery(- () => scheduleId,- () => Boolean(cronTrigger())- );- const history = createMemo(() =>- historyQuery.isSuccess ? (historyQuery.data ?? []) : []- );-- const [renameOpen, setRenameOpen] = createSignal(false);-- const runNowMutation = useRunScheduleNowMutation({- onError: (error) =>- toast.alert('Failed to start run', { subtext: getErrorMessage(error) }),- });-- const setEnabledMutation = useSetScheduleEnabledMutation({- onError: (error) =>- toast.alert('Failed to update routine', {- subtext: getErrorMessage(error),- }),- });-- const duplicateMutation = useCreateScheduleMutation({- onSuccess: (created) => {- toast.success('Duplicated');- if (created.id) {- replaceOrInsertSplit(- { type: 'automation', id: created.id },- 'entity-actions-menu'- );- }- },- onError: (error) =>- toast.alert('Failed to duplicate automation', {- subtext: getErrorMessage(error),- }),- });-- const duplicateAutomation = () => {- const current = schedule();- if (!current || duplicateMutation.isPending) return;- const body = scheduleToDuplicateBody(current);- if (!body) return;- duplicateMutation.mutate(body);- };-- // Confirms via the shared bulk-delete modal, which routes automations to- // the scheduled-action API and evicts them from the schedules cache.- const deleteAutomation = () => {- const entity = scheduleEntity();- if (!entity) return;- openBulkEditModal({- view: 'delete',- entities: [entity],- onFinish: () => {- toast.success('Deleted');- returnSplitToRecentListView(panel.handle);- },- onError: () => toast.failure('Failed to delete'),- });- };-- onMount(() => {- void invalidateSchedules();- });-- return (- <Show- when={cronTrigger() && state()}- fallback={- <div class="flex size-full flex-col items-center justify-center gap-2 p-3 text-center text-sm text-ink-muted">- <Switch fallback={<>Automation not found.</>}>- <Match when={schedulesQuery.isError && !schedule()}>- Unable to load automation. Please try again.- </Match>- <Match when={schedulesQuery.isPending}>Loading…</Match>- <Match when={schedule() && !cronTrigger()}>- <h1 class="font-semibold text-ink">Backend-managed routine</h1>- <p>- Event-triggered routines cannot be edited or duplicated here.- Manage this routine through the API. This editor only supports- cron schedules.- </p>- </Match>- </Switch>- </div>- }- >- {(d) => (- <>- <SplitHeaderLeft>- <HeaderIsland class="shrink">- <div class="z-split-header-content relative flex h-full w-screen max-w-full shrink items-center gap-2">- <EntityIcon- class="shrink-0"- targetType="automation"- size="xs"- />- <span- class="inline-block min-w-0 flex-1 truncate text-sm"- onDblClick={() => setRenameOpen(true)}- onContextMenu={(e) => {- e.preventDefault();- setRenameOpen(true);- }}- >- {d().name || blockNameToDefaultFile('automation')}- </span>- <div- class="shrink-0 flex items-center h-full"- ref={(ref) => panel.setTitleFileMenuRef(ref)}- />- </div>- </HeaderIsland>- </SplitHeaderLeft>- <SplitTitleFileMenu>- <BlockSplitFileMenu- id={scheduleId}- itemType="automation"- name={d().name || blockNameToDefaultFile('automation')}- ops={[]}- // Generic chrome can't reconstruct an AutomationEntity (it- // lacks the cron), so supply it for entity-gated menu items.- entity={scheduleEntity()}- tools={[- {- group: 'file',- label: 'Rename',- icon: RenameIcon,- action: () => setRenameOpen(true),- },- {- group: 'file',- label: 'Duplicate',- icon: CopyIcon,- action: duplicateAutomation,- },- {- group: 'delete',- label: 'Delete',- icon: TrashIcon,- action: deleteAutomation,- },- ]}- />- </SplitTitleFileMenu>- <AutomationRenameModal- isOpen={renameOpen}- setIsOpen={setRenameOpen}- name={d().name}- onRename={(newName) =>- setState((current) => ({ ...current, name: newName }))- }- />-- <div class="flex min-h-0 size-full cursor-default flex-col text-ink">- <div class="flex shrink-0 flex-col gap-3 p-3">- <div class="flex items-center gap-2">- <Button- variant="accent"- size="sm"- class="cursor-default"- disabled={- runNowMutation.isPending ||- isRunning() ||- autosave.dirty() ||- autosave.saving() ||- Boolean(formError())- }- onClick={runNow}- >- Run Now- </Button>- <ToggleSwitch- label="Active"- labelClass="text-xs text-ink-muted"- checked={isActive()}- // Resuming conflicts with the claim until the run finishes.- disabled={- setEnabledMutation.isPending || (isRunning() && !isActive())- }- onChange={(active) =>- setEnabledMutation.mutate({ scheduleId, enabled: active })- }- />- <div class="ml-auto text-xs font-mono text-right uppercase font-light">- {match(status())- .with({ kind: 'running' }, () => (- <span class="flex items-center justify-end gap-1.5 text-accent">- <span class="size-1.5 animate-pulse rounded-full bg-accent" />- Running- </span>- ))- .with({ kind: 'scheduled' }, ({ nextRunAt }) => (- <span class="text-ink-extra-muted">- Next run {formatDateAndTime(nextRunAt)}- </span>- ))- .with(- { kind: 'paused' },- { kind: 'unscheduled' },- undefined,- () => undefined- )- .exhaustive()}- </div>- </div>-- <div class="grid gap-1.5">- <h1 class="text-sm font-semibold">Execution target</h1>- <RoutineExecutionPicker- target={d().target}- onChange={(target) =>- setState((current) => ({ ...current, target }))- }- />- <Show when={isRunning()}>- <p class="text-xs text-ink-muted">- Configuration cannot be changed while running.- </p>- </Show>- </div>-- <div class="grid gap-1.5">- <h1 class="text-sm font-semibold">Instructions</h1>- <AutomationPromptEditor- initialValue={d().prompt}- onChange={(markdown) =>- setState((current) => ({- ...current,- prompt: markdown,- }))- }- />- </div>-- <div>- <h1 class="text-sm font-semibold">Schedule</h1>- <p class="mt-0.5 text-xs text-ink-muted">{currentSummary()}</p>- </div>-- <div class="flex flex-wrap gap-1">- <For each={FREQUENCY_OPTIONS}>- {(option) => (- <button- type="button"- class={cn(- 'cursor-default border rounded-sm px-2 py-1 text-xs transition-colors',- d().frequency === option.value- ? 'border-accent/30 bg-accent/10 text-accent'- : 'border-edge-muted text-ink-muted hover:bg-hover'- )}- onClick={() =>- setState((current) => ({- ...current,- frequency: option.value,- }))- }- >- {option.label}- </button>- )}- </For>- </div>-- <Show when={d().frequency === 'week'}>- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Days- </label>- <div class="flex flex-wrap gap-1">- <For each={WEEKDAY_OPTIONS}>- {(option) => {- const active = () =>- d().daysOfWeek.includes(option.value);- return (- <button- type="button"- class={cn(- 'cursor-default border rounded-sm px-2 py-1 text-xs transition-colors',- active()- ? 'border-accent/30 bg-accent/10 text-accent'- : 'border-edge-muted text-ink-muted hover:bg-hover'- )}- onClick={() =>- setState((current) => {- const has = current.daysOfWeek.includes(- option.value- );- return {- ...current,- daysOfWeek: has- ? current.daysOfWeek.filter(- (v) => v !== option.value- )- : [...current.daysOfWeek, option.value],- };- })- }- >- {option.label}- </button>- );- }}- </For>- </div>- </div>- </Show>-- <Show when={d().frequency === 'month'}>- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Day of Month- </label>- <input- type="number"- min="1"- max="31"- class={INPUT_CLASS}- value={d().dayOfMonth}- onInput={(event) =>- setState((current) => ({- ...current,- dayOfMonth: event.currentTarget.value,- }))- }- />- </div>- </Show>-- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Time- </label>- <AutomationTimePicker- value={d().time}- onChange={(value) =>- setState((current) => ({- ...current,- time: value,- }))- }- />- </div>-- <Show when={autosave.error()}>- <div role="alert" class="text-xs text-failure">- Changes not saved. {getErrorMessage(autosave.error())}- <button- type="button"- class="ml-2 underline"- onClick={autosave.retry}- >- Retry save- </button>- </div>- </Show>-- <Show when={formError()}>- {(message) => (- <div class="border border-failure/20 bg-failure/5 rounded-sm px-2 py-1.5 text-xs text-failure">- {message()}- </div>- )}- </Show>- </div>-- <div class="flex min-h-0 flex-1 flex-col">- <div class="border-b border-edge-muted px-3 py-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">- History- </div>- <RoutineHistory- records={history()}- isPending={historyQuery.isPending}- createChatMetadata={createChatHistoryMetadata}- createAgentMetadata={createAgentHistoryMetadata}- onOpen={(resource, newSplit) =>- openWithSplit(resource, {- activate: true,- preferNewSplit: newSplit,- })- }- />- </div>- </div>- </>- )}- </Show>- );-}diff --git a/apps/web/src/features/block-automation/component/AutomationComposer.test.tsx b/apps/web/src/features/block-automation/component/AutomationComposer.test.tsxdeleted file mode 100644index 9a82f505f4..0000000000--- a/apps/web/src/features/block-automation/component/AutomationComposer.test.tsx+++ /dev/null@@ -1,414 +0,0 @@-import type {- CreateScheduledAction,- ScheduledAction,-} from '@service-scheduled-action/generated/schemas';-import {- cleanup,- fireEvent,- render,- screen,- waitFor,- within,-} from '@solidjs/testing-library';-import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';-import { createSignal, type JSX } from 'solid-js';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { buildAgentRoster } from '../../agents-view/core/roster';-import { loadAutomationComposerDraft } from '../util/automationComposerStorage';-import {- AutomationComposer,- automationComposerOpen,- setAutomationComposerOpen,-} from './AutomationComposer';-import { getDefaultTimezone } from './automationUtils';--const host = vi.hoisted(() => ({- create: vi.fn<(body: CreateScheduledAction) => Promise<ScheduledAction>>(),- openWithSplit: vi.fn(),- success: vi.fn(),- alert: vi.fn(),- editorMount: vi.fn(),-}));-vi.mock('@components/app/split-layout/layout', () => ({- useSplitLayout: () => ({ openWithSplit: host.openWithSplit }),-}));-vi.mock('@core/component/Toast/Toast', () => ({- toast: { success: host.success, alert: host.alert },-}));-vi.mock('@core/constant/SettingsState', () => ({- useSettingsState: () => ({ openSettings: vi.fn() }),-}));-vi.mock('../../agents-view/primitives/open-page', () => ({- openAgentsPage: vi.fn(),-}));-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));-vi.mock('@core/mobile/virtualKeyboard', () => ({- virtualKeyboardVisible: () => false,-}));-vi.mock('@core/constant/allBlocks', () => ({- blockNameToDefaultFile: () => 'New automation',-}));-vi.mock('@queries/agent-schedule/schedules', async () => {- const { useMutation } = await import('@tanstack/solid-query');- return {- useCreateScheduleMutation: (callbacks: {- onSuccess: (schedule: ScheduledAction) => Promise<void>;- onError: (error: Error) => void;- }) => useMutation(() => ({ mutationFn: host.create, ...callbacks })),- };-});--// Keep the real dialog, picker, model discovery adapter, storage, and mutation-// lifecycle. The editor double exposes initialValue and detects any remount.-vi.mock('./AutomationPromptEditor', () => ({- AutomationPromptEditor: (props: {- initialValue: string;- onChange: (value: string) => void;- }): JSX.Element => {- host.editorMount();- const initialValue = props.initialValue;- return (- <textarea- aria-label="Instructions"- value={initialValue}- onInput={(event) => props.onChange(event.currentTarget.value)}- />- );- },-}));-vi.mock('./AutomationTimePicker', () => ({- AutomationTimePicker: (props: {- value: string;- onChange: (value: string) => void;- }): JSX.Element => (- <input- aria-label="Time"- value={props.value}- onInput={(event) => props.onChange(event.currentTarget.value)}- />- ),-}));--const agentId = '12345678-1234-1234-1234-123456789abc';-const [catalogState, setCatalogState] = createSignal<- 'pending' | 'success' | 'error'->('success');-vi.mock('../../agents-view/queries/agent-roster-source', () => ({- createAgentRosterSource: () => ({- roster: () =>- buildAgentRoster({- agents: [- {- bot: { id: agentId, name: 'Researcher', handle: 'researcher' },- harness: 'in-memory',- default_model: 'claude-sonnet-4-6',- },- ],- runtimes: [],- cursorConnected: false,- cursorNeedsConnection: true,- }),- loading: () => false,- error: () => false,- availabilityLoading: () => false,- }),-}));-vi.mock('@queries/agents/models', () => ({- useAgentModelsQuery: () => ({- get isSuccess() {- return catalogState() === 'success';- },- get isPending() {- return catalogState() === 'pending';- },- get isError() {- return catalogState() === 'error';- },- get data() {- if (catalogState() !== 'success') throw new Error('Unsafe catalog read');- return {- status: 'available',- models: [- { id: 'claude-sonnet-4-6', name: 'Sonnet' },- { id: 'vendor/custom-model', name: 'Custom model' },- ],- };- },- }),-}));--let styles: HTMLStyleElement;-beforeEach(() => {- vi.clearAllMocks();- localStorage.clear();- setAutomationComposerOpen(false, false);- setCatalogState('success');- styles = document.createElement('style');- styles.textContent = '* { animation-name: none; transition-duration: 0s; }';- document.head.append(styles);- vi.stubGlobal('scrollTo', vi.fn());-});-afterEach(() => {- cleanup();- setAutomationComposerOpen(false, false);- styles.remove();- vi.useRealTimers();- vi.unstubAllGlobals();-});--async function mount(): Promise<void> {- const client = new QueryClient({- defaultOptions: { mutations: { retry: false } },- });- render(() => (- <QueryClientProvider client={client}>- <button onClick={() => setAutomationComposerOpen(true)}>- New routine- </button>- <AutomationComposer />- </QueryClientProvider>- ));- fireEvent.click(screen.getByRole('button', { name: 'New routine' }));- await screen.findByRole('dialog');-}--function inputPrompt(value = 'Summarize updates'): HTMLTextAreaElement {- const editor = screen.getByRole<HTMLTextAreaElement>('textbox', {- name: 'Instructions',- });- fireEvent.input(editor, { target: { value } });- return editor;-}--function openPicker(): void {- const trigger = screen.getByRole('button', { name: 'Agent' });- trigger.focus();- fireEvent.keyDown(trigger, { key: 'Enter' });-}--async function selectTarget(- target: 'model' | 'agent' | 'override'-): Promise<void> {- openPicker();- if (target === 'agent') {- fireEvent.click(screen.getByRole('menuitem', { name: /^Researcher/ }));- } else {- let menu: HTMLElement | undefined;- if (target === 'override') {- const row = screen.getByRole('menuitem', { name: /^Researcher/ });- row.focus();- fireEvent.keyDown(row, { key: 'ArrowRight' });- // Do not select the same model from the root Macro catalog.- menu = await screen.findByRole('menu', { name: /^Researcher/ });- await within(menu).findByRole('textbox', { name: 'Search models' });- }- const item = (menu ? within(menu) : screen).getByRole('menuitem', {- name: 'Custom model',- });- item.focus();- fireEvent.keyDown(item, { key: 'Enter' });- }- await waitFor(() =>- expect(- screen- .getByRole('button', { name: 'Agent' })- .getAttribute('aria-expanded')- ).toBe('false')- );-}--function create(): void {- fireEvent.click(screen.getByRole('button', { name: 'Create' }));-}--function created(body: CreateScheduledAction): ScheduledAction {- if (!('trigger' in body)) throw new Error('Expected a tagged trigger');- return {- ...body,- id: 'new-routine',- owner: 'macro|[email protected]',- created_at: '2026-09-28T00:00:00Z',- updated_at: '2026-09-28T00:00:00Z',- configuration_revision: 1,- };-}--describe('automation composer execution selection', () => {- it.each(['model', 'agent', 'override'] as const)(- 'submits a %s target with unchanged cron and timezone behavior',- async (target) => {- host.create.mockImplementation(async (body) => created(body));- await mount();- inputPrompt(' Summarize updates ');- await selectTarget(target);- create();- await waitFor(() => expect(host.create).toHaveBeenCalledOnce());- const body = host.create.mock.calls[0][0];- const expectedTask: Record<string, unknown> = {- prompt: '',- user_prompt: 'Summarize updates',- };- if (target === 'model') expectedTask.model = 'vendor/custom-model';- else expectedTask.agent = { bot_id: agentId };- if (target === 'override') expectedTask.model = 'vendor/custom-model';- expect(body.task).toEqual(expectedTask);- expect(body).toMatchObject({- trigger: {- type: 'cron',- schedule: '0 0 9 * * 2,3,4,5,6',- timezone: getDefaultTimezone(),- },- });- await waitFor(() => expect(automationComposerOpen()).toBe(false));- expect(host.openWithSplit).toHaveBeenCalledWith(- { type: 'automation', id: 'new-routine' },- { referredFrom: 'launcher' }- );- }- );-- it('restores the latest selection and prompt even when closed before the save timer', async () => {- await mount();- inputPrompt();- await selectTarget('override');- vi.useFakeTimers();- inputPrompt('Last keystroke');- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- expect(loadAutomationComposerDraft()).toMatchObject({- prompt: 'Last keystroke',- target: { kind: 'agent', agentId, modelOverride: 'vendor/custom-model' },- });- setAutomationComposerOpen(true);- expect(- screen.getByRole<HTMLTextAreaElement>('textbox', { name: 'Instructions' })- .value- ).toBe('Last keystroke');- expect(screen.getByRole('button', { name: 'Agent' }).textContent).toContain(- 'Researcher'- );- vi.advanceTimersByTime(500);- expect(loadAutomationComposerDraft()?.target).toEqual({- kind: 'agent',- agentId,- modelOverride: 'vendor/custom-model',- });- });-- it('retains the draft after an API selection error and allows retry', async () => {- host.create.mockRejectedValueOnce(- new Error('The selected agent is unavailable.')- );- host.create.mockImplementation(async (body) => created(body));- await mount();- const editor = inputPrompt();- await selectTarget('agent');- create();- expect((await screen.findByRole('alert')).textContent).toBe(- 'The selected agent is unavailable.'- );- expect(automationComposerOpen()).toBe(true);- await screen.findByRole('button', { name: 'Create' });- expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- expect(loadAutomationComposerDraft()?.target).toEqual({- kind: 'agent',- agentId,- });- setAutomationComposerOpen(true);- create();- await waitFor(() => expect(host.create).toHaveBeenCalledTimes(2));- expect(host.create.mock.calls[1][0]).toEqual(host.create.mock.calls[0][0]);- await waitFor(() => expect(automationComposerOpen()).toBe(false));- });-- it('locks selection and submission while creating and cancels queued saves on success', async () => {- let resolveCreate!: (value: ScheduledAction) => void;- host.create.mockImplementation(- () =>- new Promise((resolve) => {- resolveCreate = resolve;- })- );- await mount();- await selectTarget('agent');- vi.useFakeTimers();- inputPrompt();- create();- await vi.advanceTimersByTimeAsync(0);- const picker = screen.getByRole('button', { name: 'Agent' });- expect(picker.closest('fieldset')?.disabled).toBe(true);- expect(- screen.getByRole<HTMLButtonElement>('button', { name: 'Creating…' })- .disabled- ).toBe(true);- fireEvent.click(screen.getByRole('button', { name: 'Creating…' }));- expect(host.create).toHaveBeenCalledOnce();- resolveCreate(created(host.create.mock.calls[0][0]));- await vi.advanceTimersByTimeAsync(0);- expect(automationComposerOpen()).toBe(false);- expect(loadAutomationComposerDraft()).toBeNull();- await vi.advanceTimersByTimeAsync(1000);- expect(loadAutomationComposerDraft()).toBeNull();- setAutomationComposerOpen(true);- expect(- screen.getByRole<HTMLTextAreaElement>('textbox', { name: 'Instructions' })- .value- ).toBe('');- });-- it('does not remount the prompt editor when targets or catalog status change', async () => {- await mount();- const editor = inputPrompt();- await selectTarget('agent');- setCatalogState('pending');- expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);- setCatalogState('error');- expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);- setCatalogState('success');- await selectTarget('override');- await selectTarget('model');- expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);- expect(editor.value).toBe('Summarize updates');- expect(host.editorMount).toHaveBeenCalledOnce();- });-- it('preserves validation for empty instructions, invalid time, weekdays, and monthly day', async () => {- await mount();- create();- expect(screen.getByText('Prompt is required.')).toBeTruthy();- inputPrompt();- fireEvent.input(screen.getByRole('textbox', { name: 'Time' }), {- target: { value: '25:00' },- });- create();- expect(screen.getByText('Choose a valid time.')).toBeTruthy();- fireEvent.input(screen.getByRole('textbox', { name: 'Time' }), {- target: { value: '09:00' },- });- for (const name of ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']) {- fireEvent.click(screen.getByRole('button', { name }));- }- create();- expect(screen.getByText('Select at least one day.')).toBeTruthy();- fireEvent.click(screen.getByRole('button', { name: 'Every month' }));- fireEvent.input(screen.getByRole('spinbutton'), {- target: { value: '32' },- });- create();- expect(screen.getByText('Pick a day between 1 and 31.')).toBeTruthy();- expect(host.create).not.toHaveBeenCalled();- });-- it('keeps default dialog autofocus on opening and reopening', async () => {- await mount();- const firstControl = screen.getByRole('button', { name: 'Dismiss' });- await waitFor(() => expect(document.activeElement).toBe(firstControl));- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- setAutomationComposerOpen(true);- await waitFor(() =>- expect(document.activeElement).toBe(- screen.getByRole('button', { name: 'Dismiss' })- )- );- });-});diff --git a/apps/web/src/features/block-automation/component/AutomationComposer.tsx b/apps/web/src/features/block-automation/component/AutomationComposer.tsxdeleted file mode 100644index 4e4ed2ec70..0000000000--- a/apps/web/src/features/block-automation/component/AutomationComposer.tsx+++ /dev/null@@ -1,357 +0,0 @@-import { useSplitLayout } from '@components/app/split-layout/layout';-import { toast } from '@core/component/Toast/Toast';-import { createControlledOpenSignal } from '@core/util/createControlledOpenSignal';-import { useCreateScheduleMutation } from '@queries/agent-schedule/schedules';-import { debounce } from '@solid-primitives/scheduled';-import { Button, cn, Dialog, Surface } from '@ui';-import {- createEffect,- createMemo,- createSignal,- For,- type JSX,- on,- Show,-} from 'solid-js';-import { routineTargetSchema } from '../core/routine-target';-import { RoutineExecutionPicker } from '../routine-execution-picker';-import {- clearAutomationComposerDraft,- loadAutomationComposerDraft,- saveAutomationComposerDraft,-} from '../util/automationComposerStorage';-import { AutomationPromptEditor } from './AutomationPromptEditor';-import { AutomationTimePicker } from './AutomationTimePicker';-import {- createEmptyDraft,- describeSchedule,- draftToCreateBody,- FREQUENCY_OPTIONS,- getDefaultTimezone,- getErrorMessage,- INPUT_CLASS,- isValidTime,- WEEKDAY_OPTIONS,-} from './automationUtils';-import type { ScheduleDraft } from './types';--/**- * Open/close signal for the automation composer modal. Flip to `true` from- * anywhere (e.g. launcher / unified-list create button) to pop the dialog.- */-export const [automationComposerOpen, setAutomationComposerOpen] =- createControlledOpenSignal(false, { id: 'automation-composer' });--/**- * Create-only automation composer modal. Mount once (see Layout.tsx) — the- * dialog is driven by the `automationComposerOpen` signal.- */-export function AutomationComposer(): JSX.Element {- const { openWithSplit } = useSplitLayout();-- const [draft, setRawDraft] = createSignal<ScheduleDraft>(createEmptyDraft());- const [submitAttempted, setSubmitAttempted] = createSignal(false);- const [submitError, setSubmitError] = createSignal<string | null>(null);- // Snapshots the prompt value at dialog-open time so the editor gets a- // stable initialValue per open (the editor only reads it on mount).- const [initialPrompt, setInitialPrompt] = createSignal('');-- let draftChanged = false;- const debouncedSave = debounce(saveAutomationComposerDraft, 300);-- function setDraft(update: (prev: ScheduleDraft) => ScheduleDraft): void {- if (createMutation.isPending) return;- const next = setRawDraft(update);- draftChanged = true;- setSubmitError(null);- debouncedSave(next);- }-- createEffect(- on(automationComposerOpen, (open) => {- debouncedSave.clear();- if (!open) {- // Closing before the debounce fires must still preserve the latest edit.- if (draftChanged) saveAutomationComposerDraft(draft());- draftChanged = false;- return;- }- const next = loadAutomationComposerDraft() ?? createEmptyDraft();- draftChanged = false;- setRawDraft(next);- setInitialPrompt(next.prompt);- setSubmitAttempted(false);- setSubmitError(null);- })- );-- const currentSummary = createMemo(() =>- describeSchedule(draft(), getDefaultTimezone())- );-- const formError = createMemo(() => {- if (!draft().prompt.trim()) return 'Prompt is required.';- if (!isValidTime(draft().time)) return 'Choose a valid time.';- if (draft().frequency === 'week' && draft().daysOfWeek.length === 0) {- return 'Select at least one day.';- }- if (draft().frequency === 'month') {- const day = Number(draft().dayOfMonth);- if (!Number.isInteger(day) || day < 1 || day > 31) {- return 'Pick a day between 1 and 31.';- }- }- if (!routineTargetSchema.safeParse(draft().target).success) {- return 'Choose a valid model or agent.';- }- return null;- });-- const createMutation = useCreateScheduleMutation({- onSuccess: async (schedule) => {- debouncedSave.clear();- draftChanged = false;- clearAutomationComposerDraft();- setAutomationComposerOpen(false, false);- if (schedule.id) {- openWithSplit(- { type: 'automation', id: schedule.id },- { referredFrom: 'launcher' }- );- }- toast.success('Automation created', {- subtext: 'The automation is now scheduled.',- });- },- onError: (error) => {- setSubmitError(getErrorMessage(error));- toast.alert('Failed to create automation', {- subtext: getErrorMessage(error),- });- },- });-- function handleCreate(): void {- if (createMutation.isPending) return;- setSubmitError(null);- const error = formError();- if (error) {- setSubmitAttempted(true);- return;- }- createMutation.mutate(draftToCreateBody(draft()));- }-- const toggleClass = (active: boolean) =>- cn(- 'cursor-default border rounded-sm px-2 py-1 text-xs transition-colors',- active- ? 'border-accent/30 bg-accent/10 text-accent'- : 'border-edge-muted text-ink-muted hover:bg-hover'- );-- return (- <Dialog- open={automationComposerOpen()}- onOpenChange={(open) => setAutomationComposerOpen(open, false)}- >- <Surface depth={2} class="rounded-xl">- <div class="*:max-h-[75vh]">- <div class="flex cursor-default flex-col text-ink">- <div class="flex items-center justify-between border-b border-edge-muted px-3 py-2">- <Dialog.Title class="m-0 p-0 text-sm font-semibold">- New Automation- </Dialog.Title>- <Dialog.CloseButton as={Button} variant="ghost" size="icon-sm">- ×- </Dialog.CloseButton>- </div>-- <fieldset- disabled={createMutation.isPending}- inert={createMutation.isPending}- class="grid min-w-0 max-h-[70vh] gap-3 overflow-y-auto p-3"- >- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Name- </label>- <input- class={INPUT_CLASS}- placeholder="e.g. Morning standup summary"- value={draft().name}- onInput={(event) =>- setDraft((current) => ({- ...current,- name: event.currentTarget.value,- }))- }- />- </div>-- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Instructions- </label>- <AutomationPromptEditor- initialValue={initialPrompt()}- onChange={(markdown) =>- setDraft((current) => ({- ...current,- prompt: markdown,- }))- }- />- </div>-- <RoutineExecutionPicker- target={draft().target}- onChange={(target) =>- setDraft((current) => ({ ...current, target }))- }- />-- <div class="grid gap-3 border border-edge-muted rounded-sm p-3">- <div>- <p class="text-sm font-semibold">Schedule</p>- <p class="mt-0.5 text-xs text-ink-muted">- {currentSummary()}- </p>- </div>-- <div class="flex flex-wrap gap-1">- <For each={FREQUENCY_OPTIONS}>- {(option) => (- <button- type="button"- class={toggleClass(draft().frequency === option.value)}- onClick={() =>- setDraft((current) => ({- ...current,- frequency: option.value,- }))- }- >- {option.label}- </button>- )}- </For>- </div>-- <Show when={draft().frequency === 'week'}>- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Days- </label>- <div class="flex flex-wrap gap-1">- <For each={WEEKDAY_OPTIONS}>- {(option) => {- const active = () =>- draft().daysOfWeek.includes(option.value);- return (- <button- type="button"- class={toggleClass(active())}- onClick={() =>- setDraft((current) => {- const has = current.daysOfWeek.includes(- option.value- );- return {- ...current,- daysOfWeek: has- ? current.daysOfWeek.filter(- (v) => v !== option.value- )- : [...current.daysOfWeek, option.value],- };- })- }- >- {option.label}- </button>- );- }}- </For>- </div>- </div>- </Show>-- <Show when={draft().frequency === 'month'}>- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Day of Month- </label>- <input- type="number"- min="1"- max="31"- class={INPUT_CLASS}- value={draft().dayOfMonth}- onInput={(event) =>- setDraft((current) => ({- ...current,- dayOfMonth: event.currentTarget.value,- }))- }- />- </div>- </Show>-- <div class="grid gap-1.5">- <label class="text-xs font-medium text-ink-muted cursor-default">- Time- </label>- <AutomationTimePicker- value={draft().time}- onChange={(value) =>- setDraft((current) => ({- ...current,- time: value,- }))- }- />- </div>- </div>-- <Show when={submitAttempted() && formError()}>- {(message) => (- <div class="border border-failure/20 bg-failure/5 rounded-sm px-2 py-1.5 text-xs text-failure">- {message()}- </div>- )}- </Show>- <Show when={submitError()}>- {(message) => (- <div role="alert" class="text-xs text-failure">- {message()}- </div>- )}- </Show>- </fieldset>-- <div class="flex items-center justify-end gap-2 border-t border-edge-muted px-3 py-2">- <Button- variant="ghost"- size="sm"- class="cursor-default"- onClick={() => setAutomationComposerOpen(false, false)}- >- Cancel- </Button>- <Button- variant="strong"- size="sm"- class="cursor-default"- disabled={createMutation.isPending}- onClick={handleCreate}- >- {createMutation.isPending ? 'Creating…' : 'Create'}- </Button>- </div>- </div>- </div>- </Surface>- </Dialog>- );-}diff --git a/apps/web/src/features/block-automation/component/AutomationRenameModal.tsx b/apps/web/src/features/block-automation/component/AutomationRenameModal.tsxdeleted file mode 100644index a8218a5513..0000000000--- a/apps/web/src/features/block-automation/component/AutomationRenameModal.tsx+++ /dev/null@@ -1,110 +0,0 @@-import {- EntityModalActionFooter,- EntityModalTitle,-} from '@app/features/entity/entity-modal/EntityModal';-import { getSplitPanelRef } from '@components/app/split-layout/layoutUtils';-import clickOutside from '@core/directive/clickOutside';-import { Dialog } from '@kobalte/core/dialog';-import {- type Accessor,- createSignal,- onMount,- type Setter,- Show,-} from 'solid-js';-import { Portal } from 'solid-js/web';--false && clickOutside;--export function AutomationRenameModal(props: {- isOpen: Accessor<boolean>;- setIsOpen: Setter<boolean>;- name: string;- onRename: (newName: string) => void;-}) {- return (- <Show when={props.isOpen()}>- <AutomationRenameModalContent- isOpen={props.isOpen}- setIsOpen={props.setIsOpen}- name={props.name}- onRename={props.onRename}- />- </Show>- );-}--function AutomationRenameModalContent(props: {- isOpen: Accessor<boolean>;- setIsOpen: Setter<boolean>;- name: string;- onRename: (newName: string) => void;-}) {- let inputRef: HTMLInputElement | undefined;- const [editValue, setEditValue] = createSignal(props.name);-- const close = () => props.setIsOpen(false);-- const finishEditing = () => {- const newValue = editValue().trim();- if (newValue) {- props.onRename(newValue);- }- close();- };-- const handleKeyDown = (e: KeyboardEvent) => {- if (e.key === 'Enter') {- e.preventDefault();- finishEditing();- } else if (e.key === 'Escape') {- e.preventDefault();- close();- }- };-- return (- <Dialog open={props.isOpen()} onOpenChange={props.setIsOpen} modal={true}>- <Portal mount={getSplitPanelRef() ?? undefined}>- <Dialog.Overlay- as="div"- class="absolute z-modal inset-px bg-modal-overlay"- use:clickOutside={close}- on:click={close}- />- <div class="absolute z-modal pointer-events-none px-2 inset-px">- <Dialog.Content class="pointer-events-none!">- <div class="pointer-events-auto w-full max-w-[min(36rem,calc(100%-1rem))] mx-auto mt-16 bg-surface border border-edge h-fit p-2">- <div class="w-full my-1">- <EntityModalTitle title="Rename" />- <div class="w-full">- <input- ref={(el) => {- inputRef = el;- onMount(() => {- setTimeout(() => {- inputRef?.focus();- inputRef?.select();- });- });- }}- value={editValue()}- onInput={(e) => setEditValue(e.currentTarget.value)}- onKeyDown={handleKeyDown}- class="w-full p-2 text-sm border border-edge bg-surface text-ink placeholder:text-ink-placeholder focus:outline-none focus:bg-active selection:bg-ink selection:text-surface"- placeholder="Enter title..."- />- </div>- <EntityModalActionFooter- onCancel={close}- onConfirm={finishEditing}- confirmText="Rename"- />- </div>- </div>- </Dialog.Content>- </div>- </Portal>- </Dialog>- );-}diff --git a/apps/web/src/features/block-automation/component/AutomationTimePicker.tsx b/apps/web/src/features/block-automation/component/AutomationTimePicker.tsxdeleted file mode 100644index fa3828019d..0000000000--- a/apps/web/src/features/block-automation/component/AutomationTimePicker.tsx+++ /dev/null@@ -1,190 +0,0 @@-import clickOutside from '@core/directive/clickOutside';-import { cn } from '@ui';-import { createEffect, createSignal, on, Show } from 'solid-js';-import { INPUT_CLASS, isValidTime } from './automationUtils';--false && clickOutside;--function parseHHMM(value: string): {- hour: number;- minute: number;- period: 'AM' | 'PM';-} {- if (!isValidTime(value)) return { hour: 9, minute: 0, period: 'AM' };- const [h, m] = value.split(':').map(Number);- return {- hour: h % 12 || 12,- minute: m,- period: h >= 12 ? 'PM' : 'AM',- };-}--function formatTimeLabel(value: string) {- if (!isValidTime(value)) return '—';- const [h, m] = value.split(':').map(Number);- const date = new Date(2026, 0, 1, h, m);- return new Intl.DateTimeFormat(undefined, {- hour: 'numeric',- minute: '2-digit',- }).format(date);-}--function toHHMM(hour12: number, minute: number, period: 'AM' | 'PM') {- const h24 =- period === 'AM'- ? hour12 === 12- ? 0- : hour12- : hour12 === 12- ? 12- : hour12 + 12;- return `${String(h24).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;-}--export function AutomationTimePicker(props: {- value: string;- onChange: (hhmm: string) => void;-}) {- const [open, setOpen] = createSignal(false);-- const initial = parseHHMM(props.value);- const [hour, setHour] = createSignal(initial.hour);- const [hourDisplay, setHourDisplay] = createSignal(initial.hour.toString());- const [minute, setMinute] = createSignal(initial.minute);- const [minuteDisplay, setMinuteDisplay] = createSignal(- initial.minute.toString().padStart(2, '0')- );- const [period, setPeriod] = createSignal<'AM' | 'PM'>(initial.period);-- createEffect(- on(- () => props.value,- (value) => {- const p = parseHHMM(value);- setHour(p.hour);- setHourDisplay(p.hour.toString());- setMinute(p.minute);- setMinuteDisplay(p.minute.toString().padStart(2, '0'));- setPeriod(p.period);- },- { defer: true }- )- );-- const commit = (- nextHour: number,- nextMinute: number,- nextPeriod: 'AM' | 'PM'- ) => {- props.onChange(toHHMM(nextHour, nextMinute, nextPeriod));- };-- return (- <div class="relative">- <button- type="button"- class={cn(INPUT_CLASS, 'text-left')}- onClick={() => setOpen((v) => !v)}- >- {formatTimeLabel(props.value)}- </button>- <Show when={open()}>- <div- class="absolute inset-x-0 top-full mt-1 z-action-menu border border-edge-muted bg-surface rounded-sm p-3"- use:clickOutside={() => setOpen(false)}- >- <div class="flex items-center gap-2">- <div class="flex items-center gap-1">- <input- type="text"- inputmode="numeric"- maxLength={2}- aria-label="Hour"- class="w-10 text-center bg-active border border-edge-muted rounded-sm p-1 text-sm focus:outline-none focus:border-accent"- value={hourDisplay()}- onKeyDown={(e) => {- if (e.key.length === 1 && !/\d/.test(e.key)) {- e.preventDefault();- }- }}- onInput={(e) => {- const raw = e.currentTarget.value;- setHourDisplay(raw);- const val = parseInt(raw);- if (!isNaN(val) && val >= 1 && val <= 12) {- setHour(val);- commit(val, minute(), period());- }- }}- onBlur={() => setHourDisplay(hour().toString())}- />- <span class="text-sm font-medium">:</span>- <input- type="text"- inputmode="numeric"- maxLength={2}- aria-label="Minute"- class="w-10 text-center bg-active border border-edge-muted rounded-sm p-1 text-sm focus:outline-none focus:border-accent"- value={minuteDisplay()}- onKeyDown={(e) => {- if (e.key.length === 1 && !/\d/.test(e.key)) {- e.preventDefault();- }- }}- onInput={(e) => {- const raw = e.currentTarget.value;- setMinuteDisplay(raw);- const val = parseInt(raw);- if (!isNaN(val) && val >= 0 && val <= 59) {- setMinute(val);- commit(hour(), val, period());- }- }}- onBlur={() =>- setMinuteDisplay(minute().toString().padStart(2, '0'))- }- />- </div>- <div class="flex border border-edge-muted rounded-sm text-sm overflow-hidden">- <button- type="button"- class="px-2 py-1 transition-colors"- classList={{- 'bg-accent text-surface': period() === 'AM',- 'hover:bg-active': period() !== 'AM',- }}- onClick={() => {- setPeriod('AM');- commit(hour(), minute(), 'AM');- }}- >- AM- </button>- <button- type="button"- class="px-2 py-1 transition-colors"- classList={{- 'bg-accent text-surface': period() === 'PM',- 'hover:bg-active': period() !== 'PM',- }}- onClick={() => {- setPeriod('PM');- commit(hour(), minute(), 'PM');- }}- >- PM- </button>- </div>- <button- type="button"- class="ml-auto px-2 py-1 border border-accent/30 bg-accent/10 text-accent rounded-sm text-sm hover:bg-accent/20"- onClick={() => setOpen(false)}- >- Done- </button>- </div>- </div>- </Show>- </div>- );-}diff --git a/apps/web/src/features/block-automation/component/index.ts b/apps/web/src/features/block-automation/component/index.tsdeleted file mode 100644index 419db33ad9..0000000000--- a/apps/web/src/features/block-automation/component/index.ts+++ /dev/null@@ -1,6 +0,0 @@-export { Automation } from './Automation';-export {- AutomationComposer,- automationComposerOpen,- setAutomationComposerOpen,-} from './AutomationComposer';diff --git a/apps/web/src/features/block-automation/views/routine-history.tsx b/apps/web/src/features/block-automation/views/routine-history.tsxdeleted file mode 100644index e288749f8d..0000000000--- a/apps/web/src/features/block-automation/views/routine-history.tsx+++ /dev/null@@ -1,171 +0,0 @@-import { EntityIcon } from '@core/component/EntityIcon';-import { formatDateAndTime } from '@entity';-import { getHistoryResource } from '@queries/agent-schedule/run-resource';-import { cn } from '@ui';-import {- type Accessor,- createMemo,- For,- type JSX,- Show,- Suspense,-} from 'solid-js';--export type HistoryRecord = {- id?: string | null;- resource_id?: string | null;- result: unknown;- start_time?: string | null;- is_success?: boolean | null;-};--type HistoryResource = NonNullable<ReturnType<typeof getHistoryResource>>;--export type HistoryMetadata =- | { status: 'pending' }- | { status: 'unavailable' }- | { status: 'ready'; name: string };--type RoutineHistoryProps = {- records: readonly HistoryRecord[];- isPending: boolean;- createChatMetadata: (id: string) => Accessor<HistoryMetadata>;- createAgentMetadata: (id: string) => Accessor<HistoryMetadata>;- onOpen: (resource: HistoryResource, newSplit: boolean) => void;-};--type HistoryRowProps = {- record: HistoryRecord;- resource?: HistoryResource;- metadata: HistoryMetadata;- onOpen?: (resource: HistoryResource, newSplit: boolean) => void;-};--function HistoryRow(props: HistoryRowProps): JSX.Element {- const clickable = () =>- Boolean(- props.resource && props.metadata.status === 'ready' && props.onOpen- );- const name = () => {- const metadata = props.metadata;- if (metadata.status === 'ready')- return metadata.name.trim() || 'Untitled run';- if (metadata.status === 'pending') return 'Loading…';- return 'Run unavailable';- };-- return (- <button- type="button"- disabled={!clickable()}- class={cn(- 'flex w-full items-center gap-2 border-b border-edge-muted px-3 py-2 text-left text-sm cursor-default',- clickable() && 'hover:bg-hover'- )}- onClick={(event) => {- if (clickable() && props.resource) {- props.onOpen?.(props.resource, event.shiftKey);- }- }}- >- <div class="size-4 shrink-0">- <EntityIcon- targetType={props.resource?.type ?? 'automation'}- size="xs"- />- </div>- <span class="min-w-0 flex-1 truncate" title={name()}>- {name()}- </span>- <span- class={cn(- 'ml-auto shrink-0 text-xs font-mono uppercase font-light',- // Live synthetic rows have no persisted ID and are not failures.- !props.record.id || props.record.is_success- ? 'text-ink-extra-muted'- : 'text-failure'- )}- >- {formatDateAndTime(props.record.start_time ?? new Date())}- </span>- </button>- );-}--function ResourceHistoryRow(props: {- record: HistoryRecord;- resource: HistoryResource;- createMetadata: (id: string) => Accessor<HistoryMetadata>;- onOpen: RoutineHistoryProps['onOpen'];-}): JSX.Element {- const metadata = props.createMetadata(props.resource.id);- return (- <HistoryRow- record={props.record}- resource={props.resource}- metadata={metadata()}- onOpen={props.onOpen}- />- );-}--function ResolvedHistoryRow(props: {- record: HistoryRecord;- history: RoutineHistoryProps;-}): JSX.Element {- const resource = createMemo(() => getHistoryResource(props.record));- return (- <Show- when={resource()}- keyed- fallback={- <HistoryRow- record={props.record}- metadata={{ status: 'unavailable' }}- />- }- >- {(target) => (- <Suspense- fallback={- <HistoryRow- record={props.record}- resource={target}- metadata={{ status: 'pending' }}- />- }- >- <ResourceHistoryRow- record={props.record}- resource={target}- createMetadata={- target.type === 'chat'- ? props.history.createChatMetadata- : props.history.createAgentMetadata- }- onOpen={props.history.onOpen}- />- </Suspense>- )}- </Show>- );-}--export function RoutineHistory(props: RoutineHistoryProps): JSX.Element {- return (- <Show- when={props.records.length > 0}- fallback={- <div class="px-3 py-8 text-center text-xs text-ink-muted">- {props.isPending ? 'Loading…' : 'No runs yet.'}- </div>- }- >- <div class="min-h-0 h-full overflow-y-scroll">- <For each={props.records.slice(0, 50)}>- {(record) => <ResolvedHistoryRow record={record} history={props} />}- </For>- </div>- </Show>- );-}diff --git a/apps/web/src/features/block-canvas/component/CanvasController.tsx b/apps/web/src/features/block-canvas/component/CanvasController.tsxindex 2f88bc5750..e648c6d781 100644--- a/apps/web/src/features/block-canvas/component/CanvasController.tsx+++ b/apps/web/src/features/block-canvas/component/CanvasController.tsx@@ -859,9 +859,9 @@ export function CanvasController(props: ParentProps) {if (entityType === 'channel_message' || entityType === 'channel_thread') {return;}- // Automation and foreign entities aren't yet renderable as canvas mentions.+ // Routine and foreign entities aren't yet renderable as canvas mentions.if (- entityType === 'automation' ||+ entityType === 'routine' ||entityType === 'foreign' ||entityType === 'initiative')diff --git a/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.ts b/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.tsindex 36c0bc4227..b39108a3b7 100644--- a/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/cell-mentions.test.ts@@ -31,6 +31,30 @@ const person = encodeCellMention({displayName: 'Taylor',});describe('spreadsheet mention source', () => {+ it.each(['routine', 'automation'])(+ 'renders a %s mention as a label and preserves its stored payload',+ (blockName) => {+ const value = encodeCellMention({+ type: 'document',+ documentId: 'routine-1',+ documentName: 'Review tasks',+ blockName,+ });+ expect(cellPlainText(value)).toBe('Review tasks');+ expect(cellTextParts(value)).toEqual([+ {+ text: value,+ mention: {+ type: 'document',+ documentId: 'routine-1',+ documentName: 'Review tasks',+ blockName,+ },+ },+ ]);+ }+ );+it('reuses docs tags with mixed text while treating all other Markdown literally', () => {expect(cellPlainText(`**Owner:** ${person} _review_`)).toBe('**Owner:** @Taylor _review_'diff --git a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsx b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsxindex 3668a07ee7..d17219af9f 100644--- a/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsx+++ b/apps/web/src/features/block-spreadsheet/spreadsheet-mentions.test.tsx@@ -1,4 +1,7 @@-import { encodeCellMention } from '@macro-inc/spreadsheet/cell-mentions';+import {+ cellTextParts,+ encodeCellMention,+} from '@macro-inc/spreadsheet/cell-mentions';import { cleanup, render, screen } from '@solidjs/testing-library';import { afterEach, expect, it, vi } from 'vitest';@@ -26,10 +29,31 @@ vi.mock('./spreadsheet-cell-links', () => ({SpreadsheetCellLinks: (props: { value: string }) => props.value,}));-import { spreadsheetMentions } from './spreadsheet-mentions';+import { linkMentions, spreadsheetMentions } from './spreadsheet-mentions';afterEach(cleanup);+it('turns a routine link into a rendered mention chip instead of exposing its encoding', () => {+ const value = linkMentions(+ 'https://macro.com/app/routines/routine-1',+ () => ({+ block: 'routine',+ id: 'routine-1',+ params: {},+ })+ );+ expect(cellTextParts(value)[0].mention).toMatchObject({+ type: 'document',+ blockName: 'routine',+ documentId: 'routine-1',+ });+ render(() => spreadsheetMentions.renderText(value));+ expect(+ document.querySelector('[data-spreadsheet-mention]')?.textContent+ ).toBe('document mention');+ expect(document.body.textContent).not.toContain('<m-document-mention>');+});+it('renders a date pill as a relative chip with the full date as its tooltip', () => {const tomorrow = new Date();tomorrow.setHours(9, 30, 0, 0);diff --git a/apps/web/src/features/channel/Attachments/attachment-utils.ts b/apps/web/src/features/channel/Attachments/attachment-utils.tsindex ab0320c291..4be9eb5b32 100644--- a/apps/web/src/features/channel/Attachments/attachment-utils.ts+++ b/apps/web/src/features/channel/Attachments/attachment-utils.ts@@ -57,8 +57,8 @@ export function getEntityClickContent(entity: EntityData): SplitContent {type: 'call' as const,id: e.id,}))- .with({ type: 'automation' }, (e) => ({- type: 'automation' as const,+ .with({ type: 'routine' }, (e) => ({+ type: 'routine' as const,id: e.id,})).with({ type: 'foreign' }, () => {diff --git a/apps/web/src/features/channel/Bots/use-channel-bot-management.ts b/apps/web/src/features/channel/Bots/use-channel-bot-management.tsindex 76f4e19b63..5f386abb13 100644--- a/apps/web/src/features/channel/Bots/use-channel-bot-management.ts+++ b/apps/web/src/features/channel/Bots/use-channel-bot-management.ts@@ -65,7 +65,7 @@ export function useChannelBotManagement(scopeId: options.hotkeyScopeId,description: 'Create bot for channel',icon: PlusIcon,- keywords: ['webhook', 'automation', 'agent'],+ keywords: ['webhook', 'routine', 'agent'],displayPriority: 9,condition: canManageBots,keyDownHandler: () => {diff --git a/apps/web/src/features/channel/Input/tests/message-payload.test.ts b/apps/web/src/features/channel/Input/tests/message-payload.test.tsindex 56f9e642fe..2a25013a02 100644--- a/apps/web/src/features/channel/Input/tests/message-payload.test.ts+++ b/apps/web/src/features/channel/Input/tests/message-payload.test.ts@@ -1,5 +1,8 @@import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';-import { describe, expect, it } from 'vitest';+import { verifyBlockName } from '@core/constant/allBlocks';+import { extractChannelMentionsFromMarkdown } from '@macro-inc/lexical-core/utils/markdown-mentions';+import { blockNameToItemType } from '@service-storage/client';+import { describe, expect, it, vi } from 'vitest';import { buildPostMessageRequest } from '../message-payload';const snap = (mentions: ItemMention[]) => ({@@ -8,7 +11,48 @@ const snap = (mentions: ItemMention[]) => ({attachments: [],});+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));+describe('authored group references', () => {+ it('sends routine references with the same wire type as headless extraction, including saved mentions', () => {+ const blockNames = ['routine', 'automation'];+ const snapshot = snap(+ blockNames.map((blockName) => {+ const itemType = blockNameToItemType(verifyBlockName(blockName));+ if (itemType !== 'routine')+ throw new Error('Routine misclassified as ' + itemType);+ return { itemType, itemId: 'routine-1' };+ })+ );+ const result = buildPostMessageRequest({ snapshot });+ const markdown = blockNames+ .map(+ (blockName) =>+ `<m-document-mention>${JSON.stringify({ documentId: 'routine-1', blockName, documentName: 'Review tasks', blockParams: {} })}</m-document-mention>`+ )+ .join(' ');+ expect(result.mentions).toEqual([+ { entity_type: 'automation', entity_id: 'routine-1' },+ ]);+ expect(result.mentions).toEqual(+ extractChannelMentionsFromMarkdown(markdown).map(+ ({ entityType, entityId }) => ({+ entity_type: entityType,+ entity_id: entityId,+ })+ )+ );+ });+it('preserves display-only mention chips in the body without blocking a send', () => {const snapshot = {...snap([diff --git a/apps/web/src/features/command/Launcher.test.ts b/apps/web/src/features/command/Launcher.test.tsindex 0da3865f25..d31fc7a3bd 100644--- a/apps/web/src/features/command/Launcher.test.ts+++ b/apps/web/src/features/command/Launcher.test.ts@@ -22,7 +22,7 @@ vi.mock('@app/features/block-spreadsheet/queries/spreadsheet-access', () => ({}));vi.mock('@app/features/reminders/reminder-composer', () => ({}));vi.mock('@app/lib/analytics/posthog', () => ({}));-vi.mock('@block-automation/component', () => ({}));+vi.mock('@app/features/routines', () => ({}));vi.mock('@block-md/observability', () => ({}));vi.mock('@channel/CreateChannelModal', () => ({}));vi.mock('@components/app/split-layout/layout', () => ({}));diff --git a/apps/web/src/features/command/Launcher.test.tsx b/apps/web/src/features/command/Launcher.test.tsxindex ff6db2e7ee..779b451233 100644--- a/apps/web/src/features/command/Launcher.test.tsx+++ b/apps/web/src/features/command/Launcher.test.tsx@@ -46,7 +46,6 @@ vi.mock('@core/constant/featureFlags', async (importOriginal) => ({isFeatureEnabled: (flag: { key: string }) =>flag.key === 'enable-projects' && host.projectFlag() === true,}));-vi.mock('@block-automation/component', () => ({}));vi.mock('@block-md/observability', () => ({}));vi.mock('@channel/CreateChannelModal', () => ({}));vi.mock('@core/component/AI/component/input/ChatInput', () => ({}));diff --git a/apps/web/src/features/command/Launcher.tsx b/apps/web/src/features/command/Launcher.tsxindex e979a620b6..be3fceee9f 100644--- a/apps/web/src/features/command/Launcher.tsx+++ b/apps/web/src/features/command/Launcher.tsx@@ -8,7 +8,6 @@ import { EMAIL_COMPOSE_TO_INPUT_ID } from '@app/features/email-compose/core/consimport { useQuickCallsFlag } from '@app/features/meetings/use-quick-calls-flag';import { openStandaloneReminderComposer } from '@app/features/reminders/reminder-composer';import { useFeatureFlag } from '@app/lib/analytics/posthog';-import { setAutomationComposerOpen } from '@block-automation/component';import {endTrackedDocumentSpan,registerDocumentSpan,@@ -447,9 +446,8 @@ export function runCreateAction(shouldInsert,});return;- case 'automation':- setCreateMenuOpen(false, false);- setAutomationComposerOpen(true, false);+ case 'routine':+ createComponent({ componentId: 'routine-compose', asPopover: true });return;case 'skill':createComponent({@@ -541,16 +539,16 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [},},{- label: 'Automation',- icon: getIconConfig('automation').icon,- description: 'Create automation',- launcherHint: 'Scheduled agent runs',- keywords: ['new', 'make', 'add', 'schedule', 'agent'],- blockName: 'automation',- hotkeyToken: TOKENS.create.automation,+ label: 'Routine',+ icon: getIconConfig('routine').icon,+ description: 'Run a model or agent on a schedule or Macro activity',+ launcherHint: 'Schedules and activity triggers',+ keywords: ['new', 'make', 'add', 'schedule', 'agent', 'event', 'trigger'],+ blockName: 'routine',+ hotkeyToken: TOKENS.create.routine,hotkey: 'u',keyDownHandler: () => {- runCreateAction('automation');+ runCreateAction('routine');return true;},},diff --git a/apps/web/src/features/email-view/tour.ts b/apps/web/src/features/email-view/tour.tsindex ee98304ba7..e58d67cd86 100644--- a/apps/web/src/features/email-view/tour.ts+++ b/apps/web/src/features/email-view/tour.ts@@ -29,7 +29,7 @@ export const emailTour = defineViewTour({entryLabel: 'Show the email sidebar to continue',title: 'Organize email your way',description:- 'Create tags for projects, customers, or anything you track. Apply them manually, ask an agent to tag matching email, or set up an automation to keep it organized. Choose a tag here to see its messages.',+ 'Create tags for projects, customers, or anything you track. Apply them manually, ask an agent to tag matching email, or set up a routine to keep it organized. Choose a tag here to see its messages.',},{target: [EMAIL_TOUR.list, EMAIL_TOUR.search],diff --git a/apps/web/src/features/entity/composed/list-entity/automation.test.tsx b/apps/web/src/features/entity/composed/list-entity/routine.test.tsxsimilarity index 78%rename from apps/web/src/features/entity/composed/list-entity/automation.test.tsxrename to apps/web/src/features/entity/composed/list-entity/routine.test.tsxindex b35fdd3c56..b54d746c43 100644--- a/apps/web/src/features/entity/composed/list-entity/automation.test.tsx+++ b/apps/web/src/features/entity/composed/list-entity/routine.test.tsx@@ -1,7 +1,7 @@import { render, screen } from '@solidjs/testing-library';import { describe, expect, it, vi } from 'vitest';-import type { AutomationEntity, RoutineStatus } from '../../types/entity';-import { AutomationWideContent } from './automation';+import type { RoutineEntity, RoutineStatus } from '../../types/entity';+import { RoutineWideContent } from './routine';vi.mock('../../entity', () => ({Entity: {@@ -12,10 +12,10 @@ vi.mock('../../utils/timestamp', () => ({formatDateAndTime: (value: string) => value,}));-function routine(name: string, status: RoutineStatus): AutomationEntity {+function routine(name: string, status: RoutineStatus): RoutineEntity {return {id: name,- type: 'automation',+ type: 'routine',name,ownerId: 'macro|[email protected]',cron: '0 0 9 * * 2',@@ -23,7 +23,7 @@ function routine(name: string, status: RoutineStatus): AutomationEntity {};}-describe('AutomationWideContent', () => {+describe('RoutineWideContent', () => {it.each<[RoutineStatus, string]>([[{ kind: 'running' }, 'SummaryRunning'],[{ kind: 'paused' }, 'SummaryPaused'],@@ -34,7 +34,7 @@ describe('AutomationWideContent', () => {[{ kind: 'unscheduled' }, 'Summary'],])('labels a %j routine as %j', (status, text) => {const { container } = render(() => (- <AutomationWideContent entity={routine('Summary', status)} />+ <RoutineWideContent entity={routine('Summary', status)} />));expect(container.textContent).toBe(text);});@@ -42,10 +42,10 @@ describe('AutomationWideContent', () => {it('mutes the title of a paused routine only', () => {render(() => (<>- <AutomationWideContent+ <RoutineWideContententity={routine('Paused routine', { kind: 'paused' })}/>- <AutomationWideContent+ <RoutineWideContententity={routine('Active routine', {kind: 'scheduled',nextRunAt: '2026-09-29T09:00:00Z',diff --git a/apps/web/src/features/entity/composed/list-entity/automation.tsx b/apps/web/src/features/entity/composed/list-entity/routine.tsxsimilarity index 80%rename from apps/web/src/features/entity/composed/list-entity/automation.tsxrename to apps/web/src/features/entity/composed/list-entity/routine.tsxindex 4a26d8132a..244486999d 100644--- a/apps/web/src/features/entity/composed/list-entity/automation.tsx+++ b/apps/web/src/features/entity/composed/list-entity/routine.tsx@@ -1,9 +1,9 @@import { match } from 'ts-pattern';import { Entity } from '../../entity';-import type { AutomationEntity, RoutineStatus } from '../../types/entity';+import type { RoutineEntity, RoutineStatus } from '../../types/entity';import { formatDateAndTime } from '../../utils/timestamp';-function AutomationSubtitle(props: { status: RoutineStatus }) {+function RoutineSubtitle(props: { status: RoutineStatus }) {return (<div class="text-xs font-mono text-right uppercase font-light">{match(props.status)@@ -27,7 +27,7 @@ function AutomationSubtitle(props: { status: RoutineStatus }) {);}-export function AutomationWideContent(props: { entity: AutomationEntity }) {+export function RoutineWideContent(props: { entity: RoutineEntity }) {return (<><span@@ -37,7 +37,7 @@ export function AutomationWideContent(props: { entity: AutomationEntity }) {<Entity.Title entity={props.entity} /></span><span class="">- <AutomationSubtitle status={props.entity.status} />+ <RoutineSubtitle status={props.entity.status} /></span></>);diff --git a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsxindex 3e93444a18..1d975327d4 100644--- a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx+++ b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx@@ -15,7 +15,6 @@ import { ProjectBreadCrumb } from '../../components/ProjectBreadCrumb';import { UnreadIndicator } from '../../components/UnreadIndicator';import { Entity } from '../../entity';import {- isAutomationEntity,isCallEntity,isChannelEntity,isChannelMessageEntity,@@ -26,10 +25,10 @@ import {isProjectContainedEntity,isProjectEntity,isReminderEntity,+ isRoutineEntity,isTaskEntity,} from '../../types/entity';import { isSearchEntity } from '../../types/search';-import { AutomationWideContent } from './automation';import { CalendarStamp, CalendarWideContent } from './calendar';import { CallParticipants, CallWideContent } from './call';import {@@ -44,6 +43,7 @@ import {GithubPullRequestPills,} from './foreign';import { ReminderWideContent } from './reminder';+import { RoutineWideContent } from './routine';import { RowEnd } from './row-end';import { SOUP_ROW_CLASS } from './row-geometry';import type { LayoutProps } from './shared';@@ -80,8 +80,9 @@ export function WideLayout(props: LayoutProps) {'gap-y-2 gap-x-(--soup-row-column-gap) grid grid-rows-[1fr]',// Drop the indicator column entirely when the checkbox is hidden so the// content isn't indented by an empty gutter.- // A scheduled send's badge is wider than a date, so it sizes its column.+ // Action slots and scheduled-send badges size their own column.props.actions ||+ props.leadingAction ||props.scheduleStatus ||(isEmailEntity(props.entity) && props.entity.scheduledSendTime)? props.hideCheckbox@@ -156,8 +157,8 @@ export function WideLayout(props: LayoutProps) {/>)}</Match>- <Match when={isAutomationEntity(props.entity) && props.entity}>- {(entity) => <AutomationWideContent entity={entity()} />}+ <Match when={isRoutineEntity(props.entity) && props.entity}>+ {(entity) => <RoutineWideContent entity={entity()} />}</Match><Match when={isReminderEntity(props.entity) && props.entity}>{(entity) => <ReminderWideContent entity={entity()} />}diff --git a/apps/web/src/features/entity/extractors-property/entity-key-properties.tsx b/apps/web/src/features/entity/extractors-property/entity-key-properties.tsxindex 90bbe9191b..245aa8be8f 100644--- a/apps/web/src/features/entity/extractors-property/entity-key-properties.tsx+++ b/apps/web/src/features/entity/extractors-property/entity-key-properties.tsx@@ -55,8 +55,8 @@ function getEntityType(entity: EntityData): EntityType {'agent sessions are not property-service mutation targets');})- .with({ type: 'automation' }, () => {- throw new Error('automation entities do not support properties');+ .with({ type: 'routine' }, () => {+ throw new Error('routine entities do not support properties');}).with({ type: 'foreign' }, () => {throw new Error('foreign entities do not support properties');diff --git a/apps/web/src/features/entity/extractors/entity-title.tsx b/apps/web/src/features/entity/extractors/entity-title.tsxindex c04971a638..ecd1c72b5f 100644--- a/apps/web/src/features/entity/extractors/entity-title.tsx+++ b/apps/web/src/features/entity/extractors/entity-title.tsx@@ -25,8 +25,8 @@ function extractRawTitle(entity: EntityData): JSX.Element {.with({ type: 'chat' }, (e) => e.name).with({ type: 'call' }, (e) => e.name || blockNameToDefaultFile('call')).with(- { type: 'automation' },- (e) => e.name || blockNameToDefaultFile('automation')+ { type: 'routine' },+ (e) => e.name || blockNameToDefaultFile('routine')).when(isGithubPrEntity, (e) => (<>diff --git a/apps/web/src/features/entity/queries/dss.test.tsx b/apps/web/src/features/entity/queries/dss.test.tsxindex 79755a92a8..63cf5edc27 100644--- a/apps/web/src/features/entity/queries/dss.test.tsx+++ b/apps/web/src/features/entity/queries/dss.test.tsx@@ -68,7 +68,7 @@ vi.mock('@service-storage/client', () => ({storageServiceClient: { reminders: { deleteReminder: mocks.deleteReminder } },}));-import { scheduledActionKeys } from '@queries/agent-schedule/keys';+import { scheduledActionKeys } from '@app/features/routines/queries/keys';import { callKeys } from '@queries/call/keys';import { notificationKeys } from '@queries/notification/keys';import { reminderKeys } from '@queries/reminders/keys';@@ -326,7 +326,7 @@ describe('bulk delete GraphQL optimism', () => {});- it('reconciles successful call/reminder/automation deletes despite sibling failures', async () => {+ it('reconciles successful call/reminder/routine deletes despite sibling failures', async () => {vi.spyOn(console, 'error').mockImplementation(() => {});const invalidate = vi.spyOn(client, 'invalidateQueries')@@ -352,8 +352,8 @@ describe('bulk delete GraphQL optimism', () => {entity('failed-document'),entity('deleted-call', 'call'),entity('deleted-reminder', 'reminder'),- entity('deleted-auto', 'automation'),- entity('failed-auto', 'automation'),+ entity('deleted-auto', 'routine'),+ entity('failed-auto', 'routine'),])).rejects.toBeInstanceOf(BulkDeleteFailure);expect(invalidate).toHaveBeenCalledWith({ queryKey: callKeys._def });@@ -388,7 +388,7 @@ describe('bulk delete GraphQL optimism', () => {mutation.mutateAsync([entity('failed-call', 'call'),entity('failed-reminder', 'reminder'),- entity('failed-auto', 'automation'),+ entity('failed-auto', 'routine'),])).rejects.toThrow('failed call');expect(invalidate).not.toHaveBeenCalled();diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.tsindex 28eef3c2c8..c512406a4c 100644--- a/apps/web/src/features/entity/queries/dss.ts+++ b/apps/web/src/features/entity/queries/dss.ts@@ -1,4 +1,6 @@/** Document-storage mutations used by entity surfaces. */++import { scheduledActionKeys } from '@app/features/routines/queries/keys';import {copyItem,deleteItem,@@ -10,7 +12,6 @@ import {isFeatureEnabled,} from '@core/constant/featureFlags';import { throwOnErr } from '@core/util/result';-import { scheduledActionKeys } from '@queries/agent-schedule/keys';import { deleteAgentSession } from '@queries/agent-session/entity-mutations';import { callKeys } from '@queries/call/keys';import { queryClient } from '@queries/client';@@ -50,9 +51,9 @@ function invalidateDeletedDssItems(entities: EntityData[]): void {void queryClient.invalidateQueries({ queryKey: reminderKeys._def });void queryClient.invalidateQueries({ queryKey: notificationKeys._def });}- if (entities.some((e) => e.type === 'automation')) {+ if (entities.some((e) => e.type === 'routine')) {const deletedIds = new Set(- entities.filter((e) => e.type === 'automation').map((e) => e.id)+ entities.filter((e) => e.type === 'routine').map((e) => e.id));queryClient.setQueryData(scheduledActionKeys.list.queryKey,@@ -66,6 +67,14 @@ function invalidateDeletedDssItems(entities: EntityData[]): void {void queryClient.invalidateQueries({queryKey: scheduledActionKeys.list.queryKey,});+ for (const scheduleId of deletedIds) {+ queryClient.removeQueries({+ queryKey: scheduledActionKeys.detail({ scheduleId }).queryKey,+ });+ queryClient.removeQueries({+ queryKey: scheduledActionKeys.history({ scheduleId }).queryKey,+ });+ }}}@@ -102,7 +111,7 @@ export function createBulkDeleteDssItemsMutation() {type === 'document' ||type === 'project' ||type === 'call' ||- type === 'automation' ||+ type === 'routine' ||type === 'reminder');};@@ -130,7 +139,7 @@ export function createBulkDeleteDssItemsMutation() {callServiceClient.deleteCallRecord(e.id)).then(() => true);}- if (e.type === 'automation') {+ if (e.type === 'routine') {return throwOnErr(() =>scheduledActionClient.deleteSchedule({ scheduleId: e.id })).then(() => true);diff --git a/apps/web/src/features/entity/queries/rename.ts b/apps/web/src/features/entity/queries/rename.tsindex 9a9d5514a8..0d06b51c67 100644--- a/apps/web/src/features/entity/queries/rename.ts+++ b/apps/web/src/features/entity/queries/rename.ts@@ -226,7 +226,7 @@ const renameDssSetData = (itemType !== 'email' &&itemType !== 'channel_message' &&itemType !== 'channel_thread' &&- itemType !== 'automation' &&+ itemType !== 'routine' &&itemType !== 'calendar_event' &&itemType !== 'foreign' &&itemType !== 'database' &&diff --git a/apps/web/src/features/entity/tests/buildEntityData.test.ts b/apps/web/src/features/entity/tests/buildEntityData.test.tsindex 1cb52c6347..ca5237f5cf 100644--- a/apps/web/src/features/entity/tests/buildEntityData.test.ts+++ b/apps/web/src/features/entity/tests/buildEntityData.test.ts@@ -161,24 +161,24 @@ describe('buildEntityData', () => {});});- describe('automation', () => {+ describe('routine', () => {it('returns undefined without cron', () => {expect(- buildEntityData({ ...base, blockName: 'automation' })+ buildEntityData({ ...base, blockName: 'routine' })).toBeUndefined();});- it('builds an automation with cron', () => {+ it('builds an routine with cron', () => {expect(buildEntityData({...base,- blockName: 'automation',+ blockName: 'routine',cron: '* * * * *',enabled: true,})).toEqual({...base,- type: 'automation',+ type: 'routine',cron: '* * * * *',status: { kind: 'unscheduled' },});diff --git a/apps/web/src/features/entity/types/drag.ts b/apps/web/src/features/entity/types/drag.tsindex e474d057f2..9678d863c9 100644--- a/apps/web/src/features/entity/types/drag.ts+++ b/apps/web/src/features/entity/types/drag.ts@@ -28,7 +28,7 @@ const ENTITY_DRAG_TYPES = ['call','crm_company','crm_contact',- 'automation',+ 'routine','reminder','calendar_event','foreign',diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.tsindex 0d7712fc51..0202c6136c 100644--- a/apps/web/src/features/entity/types/entity.ts+++ b/apps/web/src/features/entity/types/entity.ts@@ -353,10 +353,10 @@ export function routineStatus(facts: {return { kind: 'unscheduled' };}-export type AutomationEntity = EntityBase & {- type: 'automation';- /** Cron expression controlling when the automation runs. */- cron: string;+export type RoutineEntity = EntityBase & {+ type: 'routine';+ /** Legacy single schedule, when the routine has exactly one cron trigger. */+ cron?: string;/** Running is derived from the server claim and the backend's stale-claim* window; claims update live via the connection-gateway websocket. */status: RoutineStatus;@@ -508,7 +508,7 @@ export type EntityData =| CrmCompanyEntity| CrmContactEntity| DatabaseEntity- | AutomationEntity+ | RoutineEntity| ReminderEntity| CalendarEventEntity| ForeignEntity;@@ -527,7 +527,7 @@ const ENTITY_TYPE_VALUES = new Set<EntityData['type']>(['crm_company','crm_contact','database',- 'automation',+ 'routine','reminder','calendar_event','foreign',@@ -638,10 +638,10 @@ export const isReminderEntity = (return entity.type === 'reminder';};-export const isAutomationEntity = (+export const isRoutineEntity = (entity: EntityData-): entity is AutomationEntity => {- return entity.type === 'automation';+): entity is RoutineEntity => {+ return entity.type === 'routine';};export const isCrmCompanyEntity = (diff --git a/apps/web/src/features/entity/utils/buildEntityData.ts b/apps/web/src/features/entity/utils/buildEntityData.tsindex d1a2d29733..8f4d09bd12 100644--- a/apps/web/src/features/entity/utils/buildEntityData.ts+++ b/apps/web/src/features/entity/utils/buildEntityData.ts@@ -1,7 +1,6 @@import type { BlockAlias, BlockName } from '@core/block';import { match } from 'ts-pattern';import {- type AutomationEntity,type CallEntity,type ChannelEntity,type ChatEntity,@@ -9,6 +8,7 @@ import {type EmailEntity,type EntityData,type ProjectEntity,+ type RoutineEntity,routineStatus,type SkillEntity,type SnippetEntity,@@ -157,11 +157,11 @@ export function buildEntityData(done: args.done ?? false,}))- .with('automation', (): AutomationEntity | undefined => {+ .with('routine', (): RoutineEntity | undefined => {if (!args.cron) return undefined;return {...base,- type: 'automation',+ type: 'routine',cron: args.cron,status: routineStatus({enabled: args.enabled ?? false,diff --git a/apps/web/src/features/entity/utils/shared.test.ts b/apps/web/src/features/entity/utils/shared.test.tsindex f9a8010142..81acd02964 100644--- a/apps/web/src/features/entity/utils/shared.test.ts+++ b/apps/web/src/features/entity/utils/shared.test.ts@@ -22,7 +22,7 @@ function row(describe('isSharedWithViewer', () => {it.each([['agent_session', true],- ['automation', true],+ ['routine', true],['calendar_event', true],['chat', true],['database', true],diff --git a/apps/web/src/features/entity/utils/shared.ts b/apps/web/src/features/entity/utils/shared.tsindex 6394647db0..a653119e00 100644--- a/apps/web/src/features/entity/utils/shared.ts+++ b/apps/web/src/features/entity/utils/shared.ts@@ -4,7 +4,7 @@ import type { EntityData } from '../types/entity';const OWNER_PRINCIPAL_ROW = ['agent_session',- 'automation',+ 'routine','calendar_event','chat','database',diff --git a/apps/web/src/features/entity/utils/timestamp.ts b/apps/web/src/features/entity/utils/timestamp.tsindex 9573cdaf1c..de2b88c9df 100644--- a/apps/web/src/features/entity/utils/timestamp.ts+++ b/apps/web/src/features/entity/utils/timestamp.ts@@ -107,7 +107,7 @@ export function formatCompactRelativeTimestamp(value: string): string {/*** Formats a date + time in a single concise line, e.g. "Apr 15, 2:30 PM" or- * "1/27/24, 2:30 PM". Used when a row needs both pieces (e.g. automation+ * "1/27/24, 2:30 PM". Used when a row needs both pieces (e.g. routine* next-run times).*/export function formatDateAndTime(date: DateValue): string {diff --git a/apps/web/src/features/next-soup/actions/make-copy-action.ts b/apps/web/src/features/next-soup/actions/make-copy-action.tsindex 2f67fb74f6..2ed6f52e72 100644--- a/apps/web/src/features/next-soup/actions/make-copy-action.ts+++ b/apps/web/src/features/next-soup/actions/make-copy-action.ts@@ -15,7 +15,7 @@ export const makeCopyAction = () => {entity.type !== 'channel_message' &&entity.type !== 'channel_thread' &&entity.type !== 'foreign' &&- entity.type !== 'automation' &&+ entity.type !== 'routine' &&// There is no duplicate endpoint for reminders; the bulk copy mutation// only knows how to clone documents.entity.type !== 'reminder'diff --git a/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts b/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.tsindex a03a81d928..28f57da40d 100644--- a/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-create-reminder-action.test.ts@@ -79,7 +79,7 @@ describe('makeCreateReminderAction', () => {const { canExecute } = makeCreateReminderAction();expect(canExecute(entity('channel_message'))).toBe(false);- expect(canExecute(entity('automation'))).toBe(false);+ expect(canExecute(entity('routine'))).toBe(false);});// Thread rows are offered the action even though `channel_message` is not adiff --git a/apps/web/src/features/next-soup/filters/configs/entity-type.ts b/apps/web/src/features/next-soup/filters/configs/entity-type.tsindex b6f58e811e..dc7d446a52 100644--- a/apps/web/src/features/next-soup/filters/configs/entity-type.ts+++ b/apps/web/src/features/next-soup/filters/configs/entity-type.ts@@ -1,11 +1,11 @@import {agentFilter as agentPredicate,- automationFilter as automationPredicate,documentFilter as documentPredicate,emailFilter as emailPredicate,fileFilter as filePredicate,githubPrFilter as githubPrPredicate,peopleFilter as peoplePredicate,+ routineFilter as routinePredicate,taskFilter as taskPredicate,teamsFilter as teamsPredicate,} from '../predicates';@@ -28,11 +28,11 @@ const agentFilter = config({query: isAgent,});-const automationFilter = config({- id: 'automation',+const routineFilter = config({+ id: 'routine',group: 'entity-type',- predicate: automationPredicate,- query: {}, // No server query - automations are merged client-side via additionalEntities+ predicate: routinePredicate,+ query: {}, // No server query - routines are merged client-side via additionalEntities});const peopleFilter = config({@@ -87,7 +87,7 @@ const githubPrFilter = config({export const ENTITY_TYPE_FILTERS = [documentFilter,agentFilter,- automationFilter,+ routineFilter,peopleFilter,teamsFilter,taskFilter,diff --git a/apps/web/src/features/next-soup/filters/inbox-filters.ts b/apps/web/src/features/next-soup/filters/inbox-filters.tsindex 67d1037883..fc1f82054e 100644--- a/apps/web/src/features/next-soup/filters/inbox-filters.ts+++ b/apps/web/src/features/next-soup/filters/inbox-filters.ts@@ -128,8 +128,8 @@ export function signalFilter(entity: EntityData): boolean {case 'crm_contact':// CRM contacts only show in CRM views, not Inbox.return false;- case 'automation':- // Automations only show in the Agents > Scheduled tab, not Inbox.+ case 'routine':+ // Routines only show in the Agents > Scheduled tab, not Inbox.return false;case 'foreign':// Foreign entities (e.g. GitHub PRs) are gated by the inbox query on thediff --git a/apps/web/src/features/next-soup/filters/predicates.ts b/apps/web/src/features/next-soup/filters/predicates.tsindex b0da87eb6e..c0950b54bd 100644--- a/apps/web/src/features/next-soup/filters/predicates.ts+++ b/apps/web/src/features/next-soup/filters/predicates.ts@@ -104,8 +104,8 @@ export function agentFilter(entity: EntityData): boolean {return entity.type === 'chat' || entity.type === 'agent_session';}-export function automationFilter(entity: EntityData): boolean {- return entity.type === 'automation';+export function routineFilter(entity: EntityData): boolean {+ return entity.type === 'routine';}export function projectFilter(entity: EntityData): boolean {diff --git a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.tsindex c722998a7c..b8c62f617f 100644--- a/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts+++ b/apps/web/src/features/next-soup/sidebar/soup-filter-presets.ts@@ -300,11 +300,11 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {clientFilters: { and: ['agent', 'shared-entity'] },};},- automations: () => ({- // Server returns nothing useful here — automations are merged+ routines: () => ({+ // Server returns nothing useful here — routines are merged// into the soup client-side via `additionalEntities`.filters: defineQueryFilters({}),- clientFilters: { and: ['automation'] },+ clientFilters: { and: ['routine'] },}),skills: () => ({filters: defineQueryFilters({diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.tsxindex aaa381de55..869ee74b34 100644--- a/apps/web/src/features/next-soup/soup-view/empty-states.tsx+++ b/apps/web/src/features/next-soup/soup-view/empty-states.tsx@@ -8,7 +8,6 @@ import {import { openNewChannelModal } from '@channel/CreateChannelModal';import { useAddInboxFlow, useEmailLinksStatus } from '@core/email-link';import EmptyStateAiGraphic from '@design/empty-state-ai.svg';-import EmptyStateAutomationsGraphic from '@design/empty-state-automations.svg';import EmptyStateCallsGraphic from '@design/empty-state-calls.svg';import EmptyStateChannelsGraphic from '@design/empty-state-channels.svg';import EmptyStateDocGraphic from '@design/empty-state-doc.svg';@@ -18,6 +17,7 @@ import EmptyStateInboxTrayGraphic from '@design/empty-state-inbox-tray.svg';import EmptyStateInboxZeroGraphic from '@design/empty-state-inbox-zero.svg';import EmptyStateNoFilterMatchGraphic from '@design/empty-state-no-filter-match.svg';import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';+import EmptyStateRoutinesGraphic from '@design/empty-state-routines.svg';import EmptyStateTasksGraphic from '@design/empty-state-tasks.svg';import PlusIcon from '@phosphor/plus.svg';import { EmptyStatePanel, FilteredHiddenBanner } from '@ui';@@ -266,16 +266,16 @@ export function EmptyState(props: {</Match><Match- when={props.listView === 'agents' && soup.activeTab() === 'automations'}+ when={props.listView === 'agents' && soup.activeTab() === 'routines'}><EmptyStatePanel- graphic={EmptyStateAutomationsGraphic}- title="No automations to show"- description="Automations run in the background to handle repetitive work for you — like triaging messages, updating tasks, or sending follow-ups."+ graphic={EmptyStateRoutinesGraphic}+ title="No routines to show"+ description="Routines run in the background to handle repetitive work for you — like triaging messages, updating tasks, or sending follow-ups."primaryAction={{- label: 'New automation',+ label: 'New routine',icon: PlusIcon,- onClick: () => runCreateAction('automation'),+ onClick: () => runCreateAction('routine'),}}documentationUrl={`${DOCS_BASE}/product/agents`}/>diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsxindex 182efd4af0..46a2a0ed5c 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx@@ -30,7 +30,7 @@ import { useMaybeSoupView } from './soup-view-context';const VIEW_CREATE_BLOCKNAMES: Partial<Record<ListView, CreatableName[]>> = {documents: ['md', 'snippet', 'spreadsheet', 'canvas', 'code', 'project'],tasks: ['task'],- agents: ['agent', 'chat', 'automation', 'skill'],+ agents: ['agent', 'chat', 'routine', 'skill'],mail: ['email'],channels: ['channel'],folders: ['project'],@@ -63,7 +63,7 @@ const CREATE_COMPANY_OPTION: CreateOption = {* specific list views.*/const VIEW_ONLY_BLOCK_LABELS: Partial<Record<CreatableName, string>> = {- automation: 'Automation',+ routine: 'Routine',};const VIEW_CREATE_LABELS: Partial<Record<ListView, string>> = {diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex f2b32f3748..8101fb67c6 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -225,7 +225,7 @@ interface SoupViewProps {initialClientSort?: string[];/*** Client-side entities to merge into the soup results. Useful for entity- * types (e.g. automation) that don't come back from the soup API.+ * types (e.g. routine) that don't come back from the soup API.* Visibility is controlled by the active client filter set — use a tab* preset whose `clientFilters` include a predicate that matches them.*/diff --git a/apps/web/src/features/next-soup/soup-view/tab-lists.ts b/apps/web/src/features/next-soup/soup-view/tab-lists.tsindex 5e4debecbf..e611340b83 100644--- a/apps/web/src/features/next-soup/soup-view/tab-lists.ts+++ b/apps/web/src/features/next-soup/soup-view/tab-lists.ts@@ -29,7 +29,7 @@ export const VIEW_TAB_LISTS: Record<TabbedListView, TabItem[]> = {{ value: 'owned', label: 'Owned' },{ value: 'running', label: 'Running' },{ value: 'shared', label: 'Shared' },- { value: 'automations', label: 'Automations' },+ { value: 'routines', label: 'Routines' },{ value: 'skills', label: 'Skills' },],mail: [diff --git a/apps/web/src/features/property/tags/entityTagging.ts b/apps/web/src/features/property/tags/entityTagging.tsindex ceb25c1dc3..3ff36b15ba 100644--- a/apps/web/src/features/property/tags/entityTagging.ts+++ b/apps/web/src/features/property/tags/entityTagging.ts@@ -40,7 +40,7 @@ export function tagEntityType('crm_company','crm_contact','agent_session',- 'automation',+ 'routine','reminder','calendar_event','foreign',diff --git a/apps/web/src/features/property/utils/entityConversion.ts b/apps/web/src/features/property/utils/entityConversion.tsindex f14492e644..e7d64657f6 100644--- a/apps/web/src/features/property/utils/entityConversion.ts+++ b/apps/web/src/features/property/utils/entityConversion.ts@@ -95,8 +95,8 @@ export function macroEntityToPropertyEntityType('agent sessions are not property-service mutation targets');})- .with({ type: 'automation' }, () => {- throw new Error('automation entities do not support properties');+ .with({ type: 'routine' }, () => {+ throw new Error('routine entities do not support properties');}).with({ type: 'foreign' }, () => {throw new Error('foreign entities do not support properties');diff --git a/apps/web/src/features/reminders/TimezoneSelect.tsx b/apps/web/src/features/reminders/TimezoneSelect.tsxindex b901d6334e..18407a0bbf 100644--- a/apps/web/src/features/reminders/TimezoneSelect.tsx+++ b/apps/web/src/features/reminders/TimezoneSelect.tsx@@ -70,7 +70,9 @@ export function TimezoneSelect(props: {onChange: (zone: string) => void;options: TimezoneOption[];class?: string;+ portalScope?: 'local';}) {+ let triggerRef: HTMLButtonElement | undefined;const [search, setSearch] = createSignal('');// Keep the current zone in the collection even when the runtime no longer// lists it (a zone dropped between releases), so it resolves as the selection@@ -118,6 +120,7 @@ export function TimezoneSelect(props: {><Combobox.Control class="min-w-0 flex-1"><Combobox.Trigger+ ref={triggerRef}type="button"aria-label="Timezone"class={cn(@@ -130,7 +133,13 @@ export function TimezoneSelect(props: {</Combobox.Trigger></Combobox.Control>- <Combobox.Portal>+ <Combobox.Portal+ mount={+ props.portalScope === 'local'+ ? (triggerRef?.closest<HTMLElement>('.portal-scope') ?? undefined)+ : undefined+ }+ ><Layer depth={2}><Combobox.Content class="z-action-menu w-[24rem] max-w-[90vw] overflow-hidden rounded-xl border border-edge-muted bg-surface shadow-md"><div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2">diff --git a/apps/web/src/features/routines/components/routine-editor.tsx b/apps/web/src/features/routines/components/routine-editor.tsxnew file mode 100644index 0000000000..e935f1eea5--- /dev/null+++ b/apps/web/src/features/routines/components/routine-editor.tsx@@ -0,0 +1,200 @@+import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';+import { InlineTitleEditor } from '@core/component/InlineTitleEditor';+import { Tabs } from '@kobalte/core/tabs';+import ClockIcon from '@phosphor/clock.svg';+import { cn, EntityComposer, Layer } from '@ui';+import { For, type JSX, Show } from 'solid-js';+import type { ScheduleDraft } from '../core/draft';++/** A project-style overview and full-width run list, inside the current pane. */+export function RoutineEditor(props: {+ draft: ScheduleDraft;+ onChange: (update: (draft: ScheduleDraft) => ScheduleDraft) => void;+ disabled?: boolean;+ tab: 'settings' | 'history';+ onTab: (tab: 'settings' | 'history') => void;+ onBack: () => void;+ enabled: boolean;+ runActions?: JSX.Element;+ instructions: JSX.Element;+ executionPicker: JSX.Element;+ triggerContent?: JSX.Element;+ nextRun: string;+ history: JSX.Element;+ actions?: JSX.Element;+ feedback?: JSX.Element;+}) {+ return (+ <ViewBreadcrumbs.Root+ value="routine"+ onChange={(value) => {+ if (value === 'routines') props.onBack();+ else props.onTab('settings');+ }}+ >+ <ViewBreadcrumbs.Item value="routines" metadata={{}} order={0}>+ {(item) => (+ <ViewBreadcrumbs.ReturnButton+ onClick={item.onSelect}+ aria-label="Back to routines"+ tooltip="Routines"+ >+ Routines+ </ViewBreadcrumbs.ReturnButton>+ )}+ </ViewBreadcrumbs.Item>+ <ViewBreadcrumbs.Item value="routine" metadata={{}} order={1}>+ {(item) => (+ <div class="flex min-w-0 items-center">+ <ViewBreadcrumbs.Button+ class="gap-1.5"+ isActive={item.isActive()}+ onClick={item.onSelect}+ tooltip={props.draft.name}+ >+ <ClockIcon class="size-3 shrink-0" />+ <span class="truncate">{props.draft.name}</span>+ </ViewBreadcrumbs.Button>+ <div class="shrink-0">{props.actions}</div>+ </div>+ )}+ </ViewBreadcrumbs.Item>+ <Tabs+ value={props.tab}+ onChange={(value) => {+ if (value === 'settings' || value === 'history') props.onTab(value);+ }}+ class="@container/routine flex size-full min-h-0 min-w-0 flex-col text-ink"+ >+ <ViewShell.TopBar+ class="gap-x-3 gap-y-2 touch:flex @max-[600px]/routine:h-auto @max-[600px]/routine:flex-wrap"+ aria-label="Routine toolbar"+ >+ <ViewBreadcrumbs.Outlet+ aria-label="Routine location"+ class="min-w-0 @max-[600px]/routine:flex-1"+ />+ <div class="shrink-0 @max-[600px]/routine:order-last @max-[600px]/routine:w-full">+ <Layer depth={0}>+ <Tabs.List+ aria-label="Routine details"+ class="inline-flex shrink-0 items-center rounded-full border border-edge-muted bg-surface p-0.5"+ >+ <For+ each={[+ { value: 'settings', label: 'Overview' },+ { value: 'history', label: 'Run History' },+ ]}+ >+ {(tab) => (+ <Layer depth={2}>+ <Tabs.Trigger+ value={tab.value}+ class="rounded-full px-3 py-1 text-xs font-medium text-ink-extra-muted outline-none hover:text-ink focus-visible:ring-2 focus-visible:ring-edge-focus data-selected:bg-surface data-selected:text-ink data-selected:ring data-selected:ring-inset data-selected:ring-edge-muted"+ >+ {tab.label}+ </Tabs.Trigger>+ </Layer>+ )}+ </For>+ </Tabs.List>+ </Layer>+ </div>+ </ViewShell.TopBar>+ <Tabs.Content+ value="settings"+ class="min-h-0 flex-1 overflow-y-auto px-6 pb-8 pt-12 outline-none touch:pt-6"+ >+ <div class="mx-auto max-w-3xl">+ <div class="min-w-0">+ <Show+ when={!props.disabled}+ fallback={+ <h1 class="min-w-0 truncate text-2xl font-semibold">+ {props.draft.name}+ </h1>+ }+ >+ <InlineTitleEditor+ value={props.draft.name}+ placeholder="Routine name"+ ariaLabel="Routine name"+ class="text-2xl"+ onRename={(name) =>+ props.onChange((draft) => ({ ...draft, name }))+ }+ />+ </Show>+ </div>+ <fieldset+ disabled={props.disabled}+ inert={props.disabled}+ class="mt-3 min-w-0"+ >+ <EntityComposer.Properties aria-label="Routine properties">+ {props.executionPicker}+ </EntityComposer.Properties>+ </fieldset>+ <Layer depth={1}>+ <section+ aria-label="Routine triggers"+ class="mt-4 rounded-xl border border-edge-muted bg-surface"+ >+ <div class="flex items-start gap-4 p-4">+ <fieldset+ disabled={props.disabled}+ inert={props.disabled}+ class="min-w-0 flex-1"+ >+ <EntityComposer.Properties aria-label="Triggers">+ {props.triggerContent}+ </EntityComposer.Properties>+ </fieldset>+ <div class="shrink-0">{props.runActions}</div>+ </div>+ <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t border-edge-muted px-4 py-3 text-xs">+ <span+ aria-label="Routine status"+ class="inline-flex items-center gap-2 text-ink-muted"+ >+ <span+ aria-hidden="true"+ class={cn(+ 'size-1.5 rounded-full',+ props.enabled ? 'bg-accent' : 'bg-ink-extra-muted'+ )}+ />+ {props.enabled ? 'Enabled' : 'Disabled'}+ </span>+ <div+ class="flex min-w-0 items-center gap-2"+ aria-label="Next run"+ >+ <ClockIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ <span class="shrink-0 text-ink-muted">Next run</span>+ <span>{props.nextRun}</span>+ </div>+ </div>+ </section>+ </Layer>+ <fieldset+ disabled={props.disabled}+ inert={props.disabled}+ class="mt-6 min-w-0"+ aria-label="Routine instructions"+ >+ {props.instructions}+ </fieldset>+ <div class="mt-4 grid gap-2">{props.feedback}</div>+ </div>+ </Tabs.Content>+ <Tabs.Content+ value="history"+ class="flex min-h-0 flex-1 flex-col overflow-hidden outline-none"+ >+ {props.history}+ </Tabs.Content>+ </Tabs>+ </ViewBreadcrumbs.Root>+ );+}diff --git a/apps/web/src/features/routines/components/routine-row.tsx b/apps/web/src/features/routines/components/routine-row.tsxnew file mode 100644index 0000000000..f11f026f9c--- /dev/null+++ b/apps/web/src/features/routines/components/routine-row.tsx@@ -0,0 +1,123 @@+import { Layout as EntityLayout } from '@entity/core/Layout';+import { Slot as EntitySlot } from '@entity/core/Slot';+import ClockIcon from '@phosphor/clock-clockwise.svg';+import RobotIcon from '@phosphor/robot.svg';+import { cn, InlineCheckbox, Layer, Tooltip } from '@ui';+import type { JSX, ParentProps } from 'solid-js';+import type { RoutineRow } from '../core/types';++/** Shared geometry keeps routine properties aligned with their column headers. */+export function RoutineRowLayout(+ props: ParentProps<Pick<JSX.HTMLAttributes<HTMLDivElement>, 'class' | 'role'>>+) {+ return (+ <EntityLayout+ role={props.role}+ class={cn(+ 'grid min-h-10 min-w-[740px] grid-cols-[minmax(12rem,1fr)_8rem_7rem_minmax(8rem,12rem)_7rem] items-center gap-2 px-3',+ props.class+ )}+ >+ {props.children}+ </EntityLayout>+ );+}++export function RoutineListRow(props: {+ row: RoutineRow;+ pending: boolean;+ onOpen: (id: string, history?: boolean) => void;+ onToggle: (row: RoutineRow) => void;+}) {+ const toggleDisabled = () =>+ !props.row.editable ||+ props.pending ||+ (!props.row.enabled &&+ (props.row.status === 'Running' || props.row.status === 'Completed'));+ const toggleDescription = () => {+ if (props.pending) return 'Saving…';+ if (!props.row.enabled && props.row.status === 'Completed')+ return 'Update the schedule before enabling this routine';+ if (!props.row.enabled && props.row.status === 'Running')+ return 'Wait for the current run to finish before enabling this routine';+ return `${props.row.enabled ? 'Disable' : 'Enable'} ${props.row.name}`;+ };++ return (+ <div+ role="row"+ class="soup-list-entity @container/entity mx-1 min-w-[740px] rounded-xl py-0.5 hover:bg-list-hover focus-within:bg-list-highlighted"+ onClick={() => props.onOpen(props.row.id)}+ >+ <RoutineRowLayout class="px-2 text-sm">+ <EntitySlot role="cell" class="min-w-0">+ <Tooltip label={props.row.name} class="min-w-0 max-w-full">+ <button+ type="button"+ class="flex min-w-0 max-w-full items-center gap-2 text-left font-medium text-ink outline-none focus-visible:underline"+ >+ <ClockIcon class="size-4 shrink-0 text-ink-muted" />+ <span class="truncate">{props.row.name}</span>+ </button>+ </Tooltip>+ </EntitySlot>+ <EntitySlot role="cell" class="min-w-0 text-xs text-ink-muted">+ <Tooltip label={props.row.creator} class="max-w-full">+ <span class="truncate">{props.row.creator}</span>+ </Tooltip>+ </EntitySlot>+ <EntitySlot role="cell" class="min-w-0 text-xs">+ <span+ class={cn(+ 'inline-flex items-center gap-1.5',+ props.row.status === 'Active' || props.row.status === 'Running'+ ? 'text-accent'+ : 'text-ink-muted'+ )}+ >+ <span+ aria-hidden="true"+ class={cn(+ 'size-1.5 rounded-full',+ props.row.status === 'Active' || props.row.status === 'Running'+ ? 'bg-accent'+ : 'bg-ink-extra-muted'+ )}+ />+ {props.row.status}+ </span>+ </EntitySlot>+ <EntitySlot role="cell" class="min-w-0 text-xs text-ink-muted">+ <Tooltip label={props.row.target} class="min-w-0 max-w-full">+ <span class="inline-flex min-w-0 max-w-full items-center gap-1.5">+ <RobotIcon class="size-3.5 shrink-0" />+ <span class="truncate">{props.row.target}</span>+ </span>+ </Tooltip>+ </EntitySlot>+ <EntitySlot+ role="cell"+ class="min-w-0 text-xs"+ onClick={(event) => event.stopPropagation()}+ >+ <Layer depth={2}>+ <Tooltip label={toggleDescription()}>+ <button+ type="button"+ aria-label={`Enabled for ${props.row.name}`}+ aria-pressed={props.row.enabled}+ aria-busy={props.pending}+ disabled={toggleDisabled()}+ class="inline-flex min-w-0 items-center gap-2 rounded-full px-2 py-1.5 text-ink-muted outline-none hover:bg-surface/50 focus-visible:ring-2 focus-visible:ring-edge-focus disabled:opacity-50"+ onClick={() => props.onToggle(props.row)}+ >+ <InlineCheckbox checked={props.row.enabled} />+ <span>{props.row.enabled ? 'Enabled' : 'Disabled'}</span>+ </button>+ </Tooltip>+ </Layer>+ </EntitySlot>+ </RoutineRowLayout>+ </div>+ );+}diff --git a/apps/web/src/features/routines/components/routine-run-button.tsx b/apps/web/src/features/routines/components/routine-run-button.tsxnew file mode 100644index 0000000000..b7d2546150--- /dev/null+++ b/apps/web/src/features/routines/components/routine-run-button.tsx@@ -0,0 +1,63 @@+import CaretDownIcon from '@phosphor/caret-down.svg';+import CopyIcon from '@phosphor/copy.svg';+import PauseIcon from '@phosphor/pause.svg';+import PlayIcon from '@phosphor/play.svg';+import { Button, ButtonGroup, Dropdown } from '@ui';+import { Show } from 'solid-js';++/** Routine actions share the task's compact agent-action control. */+export function RoutineRunButton(props: {+ enabled: boolean;+ runDisabled: boolean;+ activationDisabled: boolean;+ copyDisabled: boolean;+ onRun: () => void;+ onEnabled: (enabled: boolean) => void;+ onCopyPrompt: () => void;+}) {+ return (+ <Dropdown placement="bottom-end">+ <ButtonGroup+ variant="ghost"+ size="sm"+ depth={2}+ class="rounded-full border border-edge-muted"+ >+ <Button+ disabled={props.runDisabled}+ onClick={props.onRun}+ class="bg-transparent hover:bg-ink/[0.04]"+ >+ <PlayIcon class="size-3" />+ Run now+ </Button>+ <ButtonGroup.Divider />+ <Dropdown.Trigger+ variant="ghost"+ aria-label="Run options"+ class="bg-transparent p-1 hover:bg-ink/[0.04]"+ >+ <CaretDownIcon class="size-3.5" />+ </Dropdown.Trigger>+ </ButtonGroup>+ <Dropdown.Content portalScope="local">+ <Dropdown.Item+ disabled={props.activationDisabled}+ onSelect={() => props.onEnabled(!props.enabled)}+ >+ <Show when={props.enabled} fallback={<PlayIcon class="size-4" />}>+ <PauseIcon class="size-4" />+ </Show>+ {props.enabled ? 'Disable routine' : 'Enable routine'}+ </Dropdown.Item>+ <Dropdown.Item+ disabled={props.copyDisabled}+ onSelect={props.onCopyPrompt}+ >+ <CopyIcon class="size-4" />+ Copy prompt+ </Dropdown.Item>+ </Dropdown.Content>+ </Dropdown>+ );+}diff --git a/apps/web/src/features/routines/components/routine-schedule-settings.tsx b/apps/web/src/features/routines/components/routine-schedule-settings.tsxnew file mode 100644index 0000000000..3932167fa3--- /dev/null+++ b/apps/web/src/features/routines/components/routine-schedule-settings.tsx@@ -0,0 +1,378 @@+import { DatePickerUI } from '@core/component/DatePicker/DatePickerUI';+import { WEEKDAY_OPTIONS } from '@core/util/cron';+import { parseTime } from '@core/util/dateSearch/parseTime';+import { useDateSearch } from '@core/util/dateSearch/useDateSearch';+import CalendarIcon from '@phosphor/calendar.svg';+import CaretRightIcon from '@phosphor/caret-right.svg';+import { cn } from '@ui';+import { addDays, format } from 'date-fns';+import { createSignal, For, onMount, Show } from 'solid-js';+import {+ type ScheduleTriggerDraft,+ triggerFrequencies,+} from '../core/routine-triggers';+import { parseRecurringSchedule } from '../core/schedule-language';++const timezones = Intl.supportedValuesOf('timeZone');++/** Macro's natural date search and calendar, rendered inline in the trigger panel. */+function RunOnceSettings(props: {+ trigger: ScheduleTriggerDraft;+ onChange: (patch: Partial<ScheduleTriggerDraft>) => void;+}) {+ let inputRef: HTMLInputElement | undefined;+ onMount(() => inputRef?.focus());+ const [search, setSearch] = createSignal('');+ const [calendar, setCalendar] = createSignal(false);+ const dates = useDateSearch({+ query: () =>+ search()+ .trim()+ .replace(/^in\s+/i, ''),+ defaultTime: { hours: 9, minutes: 0 },+ });+ const options = () =>+ dates().filter((option) => option.date.getTime() > Date.now());+ const selected = () => {+ const date = new Date(props.trigger.onceAt);+ return Number.isFinite(date.getTime()) ? date : undefined;+ };+ const tomorrow = addDays(new Date(), 1);+ tomorrow.setHours(9, 0, 0, 0);+ return (+ <div class="grid gap-2">+ <Show+ when={!calendar()}+ fallback={+ <>+ <button+ type="button"+ class="px-2 text-left text-xs text-ink-muted hover:text-ink"+ onClick={() => setCalendar(false)}+ >+ Type a date instead+ </button>+ <div class="[&>div]:w-full [&>div]:p-0">+ <DatePickerUI+ value={selected() ?? tomorrow}+ showTimePicker+ disablePriorToDate={new Date()}+ onChange={(date) => {+ props.onChange({ onceAt: date.toISOString() });+ setCalendar(false);+ }}+ />+ </div>+ </>+ }+ >+ <input+ ref={inputRef}+ aria-label="Run once date"+ placeholder="Tomorrow 9am, in 2 hours…"+ value={search()}+ onInput={(e) => setSearch(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && options()[0]) {+ e.preventDefault();+ props.onChange({ onceAt: options()[0].date.toISOString() });+ }+ }}+ class="w-full rounded-md border border-edge-muted bg-input px-3 py-2 text-sm outline-none focus:border-accent"+ />+ <div class="grid gap-0.5" aria-label="Suggested dates">+ <For each={options()}>+ {(option) => (+ <button+ type="button"+ class="flex items-center justify-between gap-3 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() =>+ props.onChange({ onceAt: option.date.toISOString() })+ }+ >+ <span>{option.displayText}</span>+ <span class="text-xs text-ink-muted">+ {format(option.date, 'MMM d, h:mm a')}+ </span>+ </button>+ )}+ </For>+ <Show when={search() && !options().length}>+ <p class="px-2 py-2 text-xs text-ink-muted">+ Try “tomorrow 9am” or choose a date below.+ </p>+ </Show>+ </div>+ <button+ type="button"+ class="flex items-center gap-2 rounded-md px-2 py-2 text-sm text-ink-muted hover:bg-hover"+ onClick={() => setCalendar(true)}+ >+ <CalendarIcon class="size-4" /> Custom date and time…+ </button>+ </Show>+ <Show when={selected()}>+ {(date) => (+ <p+ role="status"+ class="rounded-md bg-hover px-3 py-2 text-xs text-ink"+ >+ Run on {format(date(), 'MMM d, yyyy · h:mm a')}+ </p>+ )}+ </Show>+ <p class="px-2 text-xs text-ink-extra-muted">+ {Intl.DateTimeFormat().resolvedOptions().timeZone.replace(/_/g, ' ')}+ </p>+ </div>+ );+}++function RecurringSettings(props: {+ trigger: ScheduleTriggerDraft;+ onChange: (patch: Partial<ScheduleTriggerDraft>) => void;+}) {+ let inputRef: HTMLInputElement | undefined;+ onMount(() => inputRef?.focus());+ const [choosingZone, setChoosingZone] = createSignal(false);+ let zoneButton: HTMLButtonElement | undefined;+ const [words, setWords] = createSignal('');+ const parsed = () => parseRecurringSchedule(words());+ const [timeText, setTimeText] = createSignal(props.trigger.time);+ const describe = (text: string) => {+ setWords(text);+ const parts = parseRecurringSchedule(text);+ if (!parts) return;+ props.onChange(parts);+ setTimeText(parts.time);+ };+ return (+ <Show+ when={choosingZone()}+ fallback={+ <div class="grid gap-4">+ <input+ ref={inputRef}+ aria-label="Describe schedule"+ placeholder="Every weekday at 9am"+ value={words()}+ onInput={(e) => describe(e.currentTarget.value)}+ class="w-full rounded-md border border-edge-muted bg-input px-3 py-2 text-sm outline-none focus:border-accent"+ />+ <Show when={words() && !parsed()}>+ <p class="text-xs text-ink-muted">+ Try “every day at 9am”, or choose below.+ </p>+ </Show>+ <div class="flex flex-wrap gap-1" role="group" aria-label="Repeat">+ <For+ each={triggerFrequencies.filter((item) => item.value !== 'once')}+ >+ {(item) => (+ <button+ type="button"+ class={cn(+ 'rounded-md px-2 py-1.5 text-xs hover:bg-hover',+ props.trigger.frequency === item.value+ ? 'bg-hover text-ink'+ : 'text-ink-muted'+ )}+ aria-pressed={props.trigger.frequency === item.value}+ onClick={() => {+ setWords('');+ props.onChange({ frequency: item.value });+ }}+ >+ {item.value === 'custom' ? 'Cron' : item.label}+ </button>+ )}+ </For>+ </div>+ <Show when={props.trigger.frequency === 'week'}>+ <div class="flex gap-1" role="group" aria-label="Days of the week">+ <For each={WEEKDAY_OPTIONS}>+ {(day) => (+ <button+ type="button"+ aria-pressed={props.trigger.daysOfWeek.includes(day.value)}+ class={cn(+ 'flex-1 rounded-md py-1.5 text-xs hover:bg-hover',+ props.trigger.daysOfWeek.includes(day.value)+ ? 'bg-hover text-ink'+ : 'text-ink-muted'+ )}+ onClick={() =>+ props.onChange({+ daysOfWeek: props.trigger.daysOfWeek.includes(day.value)+ ? props.trigger.daysOfWeek.filter(+ (value) => value !== day.value+ )+ : [...props.trigger.daysOfWeek, day.value],+ })+ }+ >+ {day.label}+ </button>+ )}+ </For>+ </div>+ </Show>+ <Show when={props.trigger.frequency === 'month'}>+ <label class="flex items-center justify-between gap-3 text-xs text-ink-muted">+ Day of month+ <input+ type="number"+ min="1"+ max="31"+ value={props.trigger.dayOfMonth}+ onInput={(e) =>+ props.onChange({ dayOfMonth: e.currentTarget.value })+ }+ class="w-16 rounded-md border border-edge-muted bg-input px-2 py-1.5 text-sm text-ink"+ />+ </label>+ </Show>+ <Show+ when={+ props.trigger.frequency !== 'hour' &&+ props.trigger.frequency !== 'custom'+ }+ >+ <label class="flex items-center justify-between gap-3 text-xs text-ink-muted">+ Time+ <input+ aria-label="Run time"+ placeholder="9:00 AM"+ value={timeText()}+ onInput={(e) => {+ const text = e.currentTarget.value;+ setTimeText(text);+ const parsed = parseTime(text);+ const time =+ parsed && !parsed.rest+ ? `${String(parsed.time.hours).padStart(2, '0')}:${String(parsed.time.minutes).padStart(2, '0')}`+ : text;+ props.onChange({ time });+ }}+ class="w-28 rounded-md border border-edge-muted bg-input px-2 py-1.5 text-sm text-ink outline-none focus:border-accent"+ />+ </label>+ </Show>+ <Show when={props.trigger.frequency === 'custom'}>+ <label class="grid gap-2 text-xs text-ink-muted">+ Cron expression+ <input+ aria-label="Cron expression"+ value={props.trigger.cron}+ onInput={(e) => props.onChange({ cron: e.currentTarget.value })}+ class="w-full rounded-md border border-edge-muted bg-input p-2 font-mono text-sm text-ink outline-none focus:border-accent"+ />+ <span>+ Seconds, minutes, hours, day, month, weekday, optional year.+ </span>+ </label>+ </Show>+ <button+ ref={zoneButton}+ type="button"+ aria-label="Timezone"+ class="flex w-full items-center justify-between gap-3 rounded-md py-1 text-xs text-ink-muted hover:text-ink"+ onClick={() => setChoosingZone(true)}+ >+ <span>Time zone</span>+ <span class="ml-auto truncate">+ {props.trigger.timezone.replace(/_/g, ' ')}+ </span>+ <CaretRightIcon class="size-3 shrink-0" />+ </button>+ </div>+ }+ >+ <TimezoneChoices+ value={props.trigger.timezone}+ onChange={(timezone) => {+ props.onChange({ timezone });+ setChoosingZone(false);+ queueMicrotask(() => zoneButton?.focus());+ }}+ onBack={() => {+ setChoosingZone(false);+ queueMicrotask(() => zoneButton?.focus());+ }}+ />+ </Show>+ );+}++function TimezoneChoices(props: {+ value: string;+ onChange: (value: string) => void;+ onBack: () => void;+}) {+ let inputRef: HTMLInputElement | undefined;+ onMount(() => inputRef?.focus());+ const [search, setSearch] = createSignal('');+ const options = () =>+ [...new Set([props.value, 'UTC', ...timezones])].filter((zone) =>+ zone+ .replace(/_/g, ' ')+ .toLowerCase()+ .includes(search().trim().toLowerCase())+ );+ return (+ <div class="grid gap-2">+ <input+ ref={inputRef}+ aria-label="Search timezones"+ placeholder="Search time zones…"+ value={search()}+ onInput={(e) => setSearch(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && options()[0]) {+ e.preventDefault();+ props.onChange(options()[0]);+ }+ }}+ class="w-full rounded-md border border-edge-muted bg-input px-3 py-2 text-sm outline-none focus:border-accent"+ />+ <div class="max-h-48 overflow-y-auto" aria-label="Time zones">+ <For each={options()}>+ {(zone) => (+ <button+ type="button"+ aria-pressed={zone === props.value}+ class="block w-full rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() => props.onChange(zone)}+ >+ {zone.replace(/_/g, ' ')}+ </button>+ )}+ </For>+ <Show when={!options().length}>+ <p class="p-2 text-xs text-ink-muted">No matching time zones</p>+ </Show>+ </div>+ <button+ type="button"+ class="px-2 py-1 text-left text-xs text-ink-muted hover:text-ink"+ onClick={props.onBack}+ >+ Back to schedule+ </button>+ </div>+ );+}++export function RoutineScheduleSettings(props: {+ trigger: ScheduleTriggerDraft;+ onChange: (patch: Partial<ScheduleTriggerDraft>) => void;+}) {+ return (+ <Show+ when={props.trigger.frequency === 'once'}+ fallback={<RecurringSettings {...props} />}+ >+ <RunOnceSettings {...props} />+ </Show>+ );+}diff --git a/apps/web/src/features/routines/components/routine-triggers.tsx b/apps/web/src/features/routines/components/routine-triggers.tsxnew file mode 100644index 0000000000..326cee2cf3--- /dev/null+++ b/apps/web/src/features/routines/components/routine-triggers.tsx@@ -0,0 +1,465 @@+import { Popover } from '@kobalte/core/popover';+import ArrowLeftIcon from '@phosphor/arrow-left.svg';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CaretRightIcon from '@phosphor/caret-right.svg';+import CheckCircleIcon from '@phosphor/check-circle.svg';+import ClockIcon from '@phosphor/clock.svg';+import EnvelopeIcon from '@phosphor/envelope.svg';+import FileIcon from '@phosphor/file-text.svg';+import HashIcon from '@phosphor/hash.svg';+import SearchIcon from '@phosphor/magnifying-glass.svg';+import PlusIcon from '@phosphor/plus.svg';+import { Button, badgeTriggerClasses } from '@ui';+import { format } from 'date-fns';+import {+ type Accessor,+ createMemo,+ createSignal,+ For,+ type JSX,+ Match,+ onMount,+ Show,+ Switch,+} from 'solid-js';+import {+ type EventTriggerDraft,+ eventScopeKind,+ eventTriggerLabel,+ isGlobalEvent,+ newScheduleTrigger,+ type RoutineEventGroup,+ type RoutineTriggerDraft,+ routineEventGroups,+ routineEvents,+ type ScheduleTriggerDraft,+ validateTriggers,+} from '../core/routine-triggers';+import {+ parseRecurringSchedule,+ scheduleTriggerLabel,+} from '../core/schedule-language';+import { RoutineScheduleSettings } from './routine-schedule-settings';++type EventSlots = {+ renderEventLabel: (trigger: Accessor<EventTriggerDraft>) => JSX.Element;+ renderEventScope: (+ trigger: Accessor<EventTriggerDraft>,+ change: (ids: string[] | undefined) => void+ ) => JSX.Element;+};++function scheduleSummary(trigger: ScheduleTriggerDraft) {+ const label = scheduleTriggerLabel(trigger);+ if (trigger.frequency === 'once') {+ const date = new Date(trigger.onceAt);+ return Number.isFinite(date.getTime())+ ? format(date, 'MMM d, h:mm a')+ : 'Run once';+ }+ if (trigger.frequency === 'hour' || trigger.frequency === 'custom')+ return label;+ const date = new Date(`2000-01-01T${trigger.time}`);+ return Number.isFinite(date.getTime())+ ? `${label}, ${format(date, 'h:mm a')}`+ : label;+}++function EventIcon(props: { group: RoutineEventGroup; class: string }) {+ return (+ <Switch fallback={<FileIcon class={props.class} />}>+ <Match when={props.group === 'Channels'}>+ <HashIcon class={props.class} />+ </Match>+ <Match when={props.group === 'Tasks'}>+ <CheckCircleIcon class={props.class} />+ </Match>+ <Match when={props.group === 'Email'}>+ <EnvelopeIcon class={props.class} />+ </Match>+ </Switch>+ );+}++function TriggerIcon(props: { trigger?: RoutineTriggerDraft }) {+ const group = (): RoutineEventGroup => {+ if (props.trigger?.kind !== 'event') return 'Channels';+ const kind = eventScopeKind(props.trigger);+ if (kind === 'TASK') return 'Tasks';+ if (kind === 'THREAD') return 'Email';+ if (kind === 'DOCUMENT') return 'Documents';+ return 'Channels';+ };+ return (+ <Show+ when={props.trigger?.kind === 'event'}+ fallback={<ClockIcon class="size-3.5" />}+ >+ <EventIcon group={group()} class="size-3.5" />+ </Show>+ );+}++function TriggerChoices(props: {+ onSelect: (trigger: RoutineTriggerDraft) => void;+}) {+ let inputRef: HTMLInputElement | undefined;+ onMount(() => inputRef?.focus());+ const [search, setSearch] = createSignal('');+ const matches = (text: string) =>+ text.toLowerCase().includes(search().trim().toLowerCase());+ const recurring = createMemo(() => {+ const parts = parseRecurringSchedule(search());+ return parts+ ? { ...newScheduleTrigger(parts.frequency), ...parts }+ : undefined;+ });+ const events = () =>+ routineEvents.filter((event) =>+ matches(`${event.group} ${event.label} ${event.description}`)+ );+ return (+ <div+ class="flex min-h-0 flex-col"+ onKeyDown={(e) => {+ if (!['ArrowDown', 'ArrowUp', 'Enter'].includes(e.key)) return;+ const items = [+ ...e.currentTarget.querySelectorAll<HTMLButtonElement>(+ '[data-trigger-option]'+ ),+ ];+ const index = items.indexOf(+ document.activeElement as HTMLButtonElement+ );+ if (e.key === 'Enter') {+ if (e.target instanceof HTMLInputElement) {+ e.preventDefault();+ items[0]?.click();+ }+ return;+ }+ e.preventDefault();+ items[+ (index + (e.key === 'ArrowDown' ? 1 : -1) + items.length) %+ items.length+ ]?.focus();+ }}+ >+ <div class="flex shrink-0 items-center gap-2 border-b border-edge-muted px-3 py-2.5">+ <SearchIcon class="size-4 shrink-0 text-ink-muted" />+ <input+ ref={inputRef}+ aria-label="Search triggers"+ placeholder="Search or type “every day at 9am”"+ value={search()}+ onInput={(e) => setSearch(e.currentTarget.value)}+ class="w-full bg-transparent text-sm outline-none placeholder:text-ink-placeholder"+ />+ </div>+ <div class="min-h-0 max-h-80 overflow-y-auto p-1.5">+ <Show when={recurring()}>+ {(parts) => (+ <button+ type="button"+ data-trigger-option+ class="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() => props.onSelect(parts())}+ >+ <ClockIcon class="size-4" />+ {scheduleSummary(parts())}+ <CaretRightIcon class="ml-auto size-3" />+ </button>+ )}+ </Show>+ <Show+ when={matches('Scheduled Hourly Daily Weekly Monthly Custom Cron')}+ >+ <button+ type="button"+ data-trigger-option+ class="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() => props.onSelect(newScheduleTrigger('day'))}+ >+ <ClockIcon class="size-4 text-ink-muted" /> Scheduled{' '}+ <CaretRightIcon class="ml-auto size-3 text-ink-muted" />+ </button>+ </Show>+ <Show when={matches('Run once one-off')}>+ <button+ type="button"+ data-trigger-option+ class="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() => props.onSelect(newScheduleTrigger('once'))}+ >+ <ClockIcon class="size-4 text-ink-muted" /> Run once{' '}+ <CaretRightIcon class="ml-auto size-3 text-ink-muted" />+ </button>+ </Show>+ <For each={routineEventGroups}>+ {(group) => (+ <Show when={events().some((event) => event.group === group)}>+ <p class="px-2 pb-1 pt-3 text-xs text-ink-extra-muted">{group}</p>+ <For each={events().filter((event) => event.group === group)}>+ {(event) => (+ <button+ type="button"+ data-trigger-option+ title={event.description}+ class="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-hover focus-visible:bg-hover outline-none"+ onClick={() =>+ props.onSelect({+ id: crypto.randomUUID(),+ kind: 'event',+ events: [event.value],+ ids: isGlobalEvent([event.value]) ? undefined : [],+ })+ }+ >+ <EventIcon+ group={group}+ class="size-4 shrink-0 text-ink-muted"+ />+ {event.label}+ <CaretRightIcon class="ml-auto size-3 text-ink-muted" />+ </button>+ )}+ </For>+ </Show>+ )}+ </For>+ <Show+ when={+ !recurring() &&+ !events().length &&+ !matches('Scheduled Hourly Daily Weekly Monthly Custom Cron') &&+ !matches('Run once one-off')+ }+ >+ <p class="px-2 py-3 text-sm text-ink-muted">No matching triggers</p>+ </Show>+ </div>+ </div>+ );+}++/** One anchor and one panel for choosing and configuring a trigger. */+function TriggerChip(+ props: EventSlots & {+ trigger?: RoutineTriggerDraft;+ onSave: (trigger: RoutineTriggerDraft) => void;+ onRemove?: () => void;+ }+) {+ let triggerRef: HTMLButtonElement | undefined;+ const [open, setOpen] = createSignal(false);+ const [pending, setPending] = createSignal<RoutineTriggerDraft>();+ const [error, setError] = createSignal<string | null>(null);+ const edit = (trigger: RoutineTriggerDraft | undefined) => {+ setPending(trigger);+ setError(null);+ };+ const changeOpen = (value: boolean) => {+ if (value) edit(props.trigger);+ setOpen(value);+ };+ const schedule = () => {+ const value = pending();+ return value?.kind === 'schedule' ? value : undefined;+ };+ const event = () => {+ const value = pending();+ return value?.kind === 'event' ? value : undefined;+ };+ const savedEvent = () => {+ const value = props.trigger;+ return value?.kind === 'event' ? value : undefined;+ };+ const label = () =>+ props.trigger?.kind === 'schedule'+ ? scheduleSummary(props.trigger)+ : props.trigger+ ? eventTriggerLabel(props.trigger)+ : 'Add trigger';+ const save = () => {+ const value = pending();+ if (!value) return;+ const error = validateTriggers(+ [value],+ !props.trigger || value.kind === 'event'+ );+ if (error) {+ setError(error);+ return;+ }+ props.onSave(value);+ setOpen(false);+ };+ return (+ <Popover+ open={open()}+ onOpenChange={changeOpen}+ placement="bottom-start"+ gutter={6}+ boundary={() => document.documentElement}+ >+ <Popover.Trigger+ ref={triggerRef}+ aria-label={props.trigger ? `Edit ${label()} trigger` : 'Add trigger'}+ title={+ props.trigger?.kind === 'schedule'+ ? `${label()} · ${props.trigger.timezone.replace(/_/g, ' ')}`+ : label()+ }+ class={badgeTriggerClasses({+ variant: 'outline',+ size: 'sm',+ class: 'min-w-0 max-w-full text-left',+ })}+ >+ <Show when={props.trigger} fallback={<PlusIcon class="size-3" />}>+ <TriggerIcon trigger={props.trigger} />+ </Show>+ <span class="min-w-0 truncate">+ {label()}+ <Show when={savedEvent()}>+ {(value) => <> · {props.renderEventLabel(value)}</>}+ </Show>+ </span>+ <Show when={props.trigger}>+ <CaretDownIcon class="size-3" />+ </Show>+ </Popover.Trigger>+ <Popover.Portal+ // Stay inside the dialog's focus boundary, outside the clipped composer panel.+ mount={triggerRef?.closest<HTMLElement>('[role="dialog"]') ?? undefined}+ ref={(element) => {+ element.style.display = 'contents';+ }}+ >+ <Popover.Content+ class="z-modal flex max-h-[min(32rem,var(--kb-popper-content-available-height))] w-80 max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-xl border border-edge-muted bg-panel text-ink shadow-lg"+ onKeyDown={(e) => e.stopPropagation()}+ >+ <Popover.Title class="sr-only">+ {props.trigger ? 'Edit trigger' : 'Add trigger'}+ </Popover.Title>+ <Show when={pending()} fallback={<TriggerChoices onSelect={edit} />}>+ <div class="flex shrink-0 items-center gap-2 border-b border-edge-muted px-3 py-2">+ <Show when={!props.trigger}>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Back to triggers"+ onClick={() => edit(undefined)}+ >+ <ArrowLeftIcon class="size-4" />+ </Button>+ </Show>+ <span class="text-sm font-medium">+ {event()+ ? eventTriggerLabel(event()!)+ : schedule()?.frequency === 'once'+ ? 'Run once'+ : 'Scheduled'}+ </span>+ </div>+ <div class="min-h-0 overflow-y-auto overscroll-contain p-3">+ <Show when={schedule()}>+ {(value) => (+ <RoutineScheduleSettings+ trigger={value()}+ onChange={(patch) => edit({ ...value(), ...patch })}+ />+ )}+ </Show>+ <Show when={event()}>+ {(value) => (+ <>+ <p class="mb-3 text-xs text-ink-muted">+ {value()+ .events.map(+ (name) =>+ routineEvents.find((item) => item.value === name)+ ?.description+ )+ .join(' ')}+ </p>+ {props.renderEventScope(value, (ids) =>+ edit({ ...value(), ids })+ )}+ </>+ )}+ </Show>+ <Show when={error()}>+ {(message) => (+ <p role="alert" class="mt-3 text-xs text-failure">+ {message()}+ </p>+ )}+ </Show>+ </div>+ <div class="flex shrink-0 items-center justify-end gap-2 border-t border-edge-muted p-2">+ <Show when={props.onRemove}>+ <Button+ variant="ghost"+ size="sm"+ class="mr-auto text-ink-muted"+ onClick={() => {+ setOpen(false);+ props.onRemove?.();+ }}+ >+ Remove trigger+ </Button>+ </Show>+ <Button variant="ghost" size="sm" onClick={() => setOpen(false)}>+ Cancel+ </Button>+ <Button variant="strong" size="sm" onClick={save}>+ {props.trigger ? 'Done' : 'Add trigger'}+ </Button>+ </div>+ </Show>+ </Popover.Content>+ </Popover.Portal>+ </Popover>+ );+}++export function RoutineTriggers(+ props: EventSlots & {+ triggers: RoutineTriggerDraft[];+ onChange: (triggers: RoutineTriggerDraft[]) => void;+ }+) {+ return (+ <>+ <For each={props.triggers.map((trigger) => trigger.id)}>+ {(id) => (+ <TriggerChip+ trigger={props.triggers.find((trigger) => trigger.id === id)}+ renderEventLabel={props.renderEventLabel}+ renderEventScope={props.renderEventScope}+ onSave={(value) =>+ props.onChange(+ props.triggers.map((trigger) =>+ trigger.id === id ? value : trigger+ )+ )+ }+ onRemove={() =>+ props.onChange(+ props.triggers.filter((trigger) => trigger.id !== id)+ )+ }+ />+ )}+ </For>+ <TriggerChip+ renderEventLabel={props.renderEventLabel}+ renderEventScope={props.renderEventScope}+ onSave={(trigger) => props.onChange([...props.triggers, trigger])}+ />+ </>+ );+}diff --git a/apps/web/src/features/routines/components/routines-list.test.tsx b/apps/web/src/features/routines/components/routines-list.test.tsxnew file mode 100644index 0000000000..9b752e5fb9--- /dev/null+++ b/apps/web/src/features/routines/components/routines-list.test.tsx@@ -0,0 +1,101 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { RoutineRow } from '../core/types';+import { RoutinesList } from './routines-list';++afterEach(cleanup);+const rows: RoutineRow[] = [+ {+ id: 'mine',+ name: 'Morning briefing',+ creator: 'You',+ createdAt: '',+ target: 'Macro',+ schedule: 'Weekdays at 9 AM',+ status: 'Active',+ enabled: true,+ editable: true,+ },+ {+ id: 'revenue',+ name: 'Revenue signals',+ creator: 'You',+ createdAt: '',+ target: 'Finance agent',+ schedule: 'Every Friday',+ status: 'Paused',+ enabled: false,+ editable: true,+ },+];+function setup(overrides: { rows?: RoutineRow[]; pendingId?: string } = {}) {+ const props = {+ rows,+ loading: false,+ error: false,+ onCreate: vi.fn(),+ onOpen: vi.fn(),+ onToggle: vi.fn(),+ onRetry: vi.fn(),+ ...overrides,+ };+ render(() => <RoutinesList {...props} />);+ return props;+}+describe('routines list', () => {+ it('filters routines and agents without losing navigation', () => {+ const props = setup();+ fireEvent.input(screen.getByRole('searchbox'), {+ target: { value: 'finance' },+ });+ expect(screen.queryByText('Morning briefing')).toBeNull();+ fireEvent.click(+ screen.getByRole('button', {+ name: 'Revenue signals',+ })+ );+ expect(props.onOpen).toHaveBeenCalledWith('revenue');+ expect(props.onOpen).toHaveBeenCalledOnce();+ fireEvent.click(screen.getByRole('button', { name: 'Clear search' }));+ fireEvent.click(screen.getByRole('button', { name: 'Morning briefing' }));+ expect(props.onOpen).toHaveBeenLastCalledWith('mine');+ expect(screen.queryByRole('button', { name: /^Team$/ })).toBeNull();+ expect(+ screen.queryByRole('group', { name: 'Routine ownership' })+ ).toBeNull();+ });+ it('toggles the enabled property without opening the routine', () => {+ const props = setup();+ fireEvent.click(+ screen.getByRole('button', {+ name: 'Enabled for Morning briefing',+ pressed: true,+ })+ );+ expect(props.onToggle).toHaveBeenCalledWith(rows[0]);+ fireEvent.click(+ screen.getByRole('button', {+ name: 'Enabled for Revenue signals',+ pressed: false,+ })+ );+ expect(props.onToggle).toHaveBeenLastCalledWith(rows[1]);+ expect(props.onOpen).not.toHaveBeenCalled();+ });+ it('prevents repeated changes while a property is saving', () => {+ const props = setup({ pendingId: 'mine' });+ const button = screen.getByRole('button', {+ name: 'Enabled for Morning briefing',+ });+ expect(button.hasAttribute('disabled')).toBe(true);+ fireEvent.click(button);+ expect(props.onToggle).not.toHaveBeenCalled();+ expect(props.onOpen).not.toHaveBeenCalled();+ });+ it('opens a blank routine without a templates section', () => {+ const props = setup();+ fireEvent.click(screen.getByRole('button', { name: 'Create Routine' }));+ expect(props.onCreate).toHaveBeenCalledOnce();+ expect(screen.queryByText(/templates/i)).toBeNull();+ });+});diff --git a/apps/web/src/features/routines/components/routines-list.tsx b/apps/web/src/features/routines/components/routines-list.tsxnew file mode 100644index 0000000000..2a66fc7db3--- /dev/null+++ b/apps/web/src/features/routines/components/routines-list.tsx@@ -0,0 +1,128 @@+import { SearchBar, ViewShell } from '@app/components/view-shell';+import ClockIcon from '@phosphor/clock-clockwise.svg';+import { Button } from '@ui';+import { createSignal, For, Show } from 'solid-js';+import type { RoutineRow } from '../core/types';+import { RoutineListRow, RoutineRowLayout } from './routine-row';++export function RoutinesList(props: {+ rows: RoutineRow[];+ loading: boolean;+ error: boolean;+ pendingId?: string;+ searchRef?: (input: HTMLInputElement) => void;+ onCreate: () => void;+ onOpen: (id: string, history?: boolean) => void;+ onToggle: (row: RoutineRow) => void;+ onRetry: () => void;+}) {+ const [search, setSearch] = createSignal('');+ let list: HTMLDivElement | undefined;+ const filtered = () =>+ props.rows.filter((row) =>+ `${row.name} ${row.creator} ${row.target}`+ .toLowerCase()+ .includes(search().trim().toLowerCase())+ );+ return (+ <div class="flex size-full min-h-0 min-w-0 flex-col">+ <ViewShell.TopBar>+ <h1 class="truncate text-sm font-semibold tracking-[-0.03em] text-ink">+ Routines+ </h1>+ </ViewShell.TopBar>+ <ViewShell.Header>+ <h1 class="mb-3 text-xl font-semibold tracking-[-0.03em] text-ink not-touch:hidden">+ Routines+ </h1>+ <div class="flex min-w-0 items-center justify-between gap-3">+ <SearchBar+ ref={props.searchRef}+ label="Search routines"+ placeholder="Search routines"+ value={search()}+ onValueChange={setSearch}+ onEscape={() => list?.focus()}+ class="max-w-md flex-1"+ hotkey="cmd+f"+ />+ <Button variant="outline" onClick={props.onCreate}>+ Create Routine+ </Button>+ </div>+ </ViewShell.Header>+ <Show when={props.error}>+ <div+ role="alert"+ class="mx-4 mb-3 flex items-center justify-between gap-2 text-sm text-failure"+ >+ Could not load routines.+ <Button variant="ghost" size="sm" onClick={props.onRetry}>+ Retry+ </Button>+ </div>+ </Show>+ <div+ ref={list}+ role="table"+ aria-label="Routines"+ aria-busy={props.loading}+ tabIndex={-1}+ class="min-h-0 min-w-0 flex-1 overflow-auto outline-none"+ >+ <div role="rowgroup" class="sticky top-0 z-1 min-w-[748px] bg-panel">+ <RoutineRowLayout+ role="row"+ class="text-xs font-medium text-ink-extra-muted"+ >+ <span role="columnheader">Routine</span>+ <span role="columnheader">Created by</span>+ <span role="columnheader">Status</span>+ <span role="columnheader">Runs with</span>+ <span role="columnheader" class="px-2">+ Enabled+ </span>+ </RoutineRowLayout>+ </div>+ <div role="rowgroup" class="min-w-[748px]">+ <For each={filtered()}>+ {(row) => (+ <RoutineListRow+ row={row}+ pending={props.pendingId === row.id}+ onOpen={props.onOpen}+ onToggle={props.onToggle}+ />+ )}+ </For>+ </div>+ <Show when={!filtered().length}>+ <div role="row">+ <div+ role="cell"+ aria-colspan={5}+ class="flex min-h-48 flex-col items-center justify-center gap-3 px-4 py-10 text-center text-sm text-ink-muted"+ >+ <ClockIcon class="size-6 text-ink-extra-muted" />+ <p>+ {props.loading+ ? 'Loading routines…'+ : props.error+ ? 'Routines are unavailable'+ : search().trim()+ ? 'No matching routines'+ : 'No routines yet'}+ </p>+ <Show when={!props.loading && !props.error && !search().trim()}>+ <p>+ Create a routine to run an agent on a schedule or a Macro+ event.+ </p>+ </Show>+ </div>+ </div>+ </Show>+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/routines/context/history.ts b/apps/web/src/features/routines/context/history.tsnew file mode 100644index 0000000000..0187caafbe--- /dev/null+++ b/apps/web/src/features/routines/context/history.ts@@ -0,0 +1,5 @@+import type { AgentSessionEntity, ChatEntity } from '@entity/types/entity';+export type HistoryMetadata =+ | { status: 'pending' }+ | { status: 'unavailable' }+ | { status: 'ready'; entity: AgentSessionEntity | ChatEntity };diff --git a/apps/web/src/features/routines/context/routine-slots.ts b/apps/web/src/features/routines/context/routine-slots.tsnew file mode 100644index 0000000000..f5b105cbbb--- /dev/null+++ b/apps/web/src/features/routines/context/routine-slots.ts@@ -0,0 +1,23 @@+import type { Accessor, Component } from 'solid-js';+import type { RoutineTarget } from '../core/routine-target';+import type { RoutineTriggerDraft } from '../core/routine-triggers';+import type { HistoryMetadata } from './history';++export type RoutineEditorSlots = {+ PromptEditor: Component<{+ initialValue: string;+ onChange(value: string): void;+ }>;+ ExecutionPicker: Component<{+ target: RoutineTarget;+ onChange(target: RoutineTarget): void;+ }>;+ Triggers: Component<{+ triggers: RoutineTriggerDraft[];+ onChange(triggers: RoutineTriggerDraft[]): void;+ }>;+};+export type RoutineDetailSlots = RoutineEditorSlots & {+ createChatMetadata(id: string): Accessor<HistoryMetadata>;+ createAgentMetadata(id: string): Accessor<HistoryMetadata>;+};diff --git a/apps/web/src/features/routines/context/routine-sources.ts b/apps/web/src/features/routines/context/routine-sources.tsnew file mode 100644index 0000000000..f8fbc15d33--- /dev/null+++ b/apps/web/src/features/routines/context/routine-sources.ts@@ -0,0 +1,40 @@+import type { RoutineEntity } from '@entity/types/entity';+import type { Accessor } from 'solid-js';+import type { ScheduleDraft } from '../core/draft';+import type { HistoryRecord } from '../core/history';+import type { RoutineSnapshot } from '../core/routine';++export type RoutineDetailSource = {+ routine: Accessor<RoutineSnapshot | undefined>;+ entity: Accessor<RoutineEntity | undefined>;+ loading: Accessor<boolean>;+ error: Accessor<boolean>;+ update(draft: ScheduleDraft): Promise<RoutineSnapshot>;+ run(): void;+ runPending: Accessor<boolean>;+ setEnabled(enabled: boolean): void;+ activationPending: Accessor<boolean>;+ duplicate(): void;+ duplicationPending: Accessor<boolean>;+ history: Accessor<HistoryRecord[]>;+ historyLoading: Accessor<boolean>;+ historyError: Accessor<boolean>;+ refreshHistory(): Promise<unknown>;+};+export type RoutineCreatorSource = {+ pending: Accessor<boolean>;+ create(draft: ScheduleDraft): Promise<string>;+};+export type RoutineDraftStorage = {+ load(): ScheduleDraft | null;+ save(draft: ScheduleDraft): void;+ clear(): void;+};+export type RoutineListSource = {+ routines: Accessor<readonly RoutineSnapshot[]>;+ loading: Accessor<boolean>;+ error: Accessor<boolean>;+ refresh(): Promise<unknown>;+ setEnabled(id: string, enabled: boolean): void;+ pendingId: Accessor<string | undefined>;+};diff --git a/apps/web/src/features/routines/core/claim.ts b/apps/web/src/features/routines/core/claim.tsnew file mode 100644index 0000000000..2ca99b9053--- /dev/null+++ b/apps/web/src/features/routines/core/claim.ts@@ -0,0 +1,13 @@+// Must match `MAX_ACTION_TIME` on the backend+// (services/scheduled_action/src/domain/models.rs). After this window+// a claim is treated as stale — an executor crashed mid-run — so we stop+// reporting the action as running.+const MAX_CLAIMED_MS = 20 * 60 * 1000;++export function isClaimActive(+ claimed: string | undefined | null,+ now = Date.now()+): boolean {+ if (!claimed) return false;+ return now - Date.parse(claimed) < MAX_CLAIMED_MS;+}diff --git a/apps/web/src/features/block-automation/component/types.ts b/apps/web/src/features/routines/core/draft.tssimilarity index 54%rename from apps/web/src/features/block-automation/component/types.tsrename to apps/web/src/features/routines/core/draft.tsindex 2b0d82a924..c085809455 100644--- a/apps/web/src/features/block-automation/component/types.ts+++ b/apps/web/src/features/routines/core/draft.ts@@ -1,9 +1,12 @@-import type { RoutineTarget } from '../core/routine-target';+import type { RoutineTarget } from './routine-target';+import type { RoutineTriggerDraft } from './routine-triggers';-export type ScheduleFrequency = 'week' | 'month';+export type ScheduleFrequency = 'week' | 'month' | 'once';export type ScheduleDraft = {id?: string;+ triggers?: RoutineTriggerDraft[];+ enabled?: boolean;name: string;prompt: string;frequency: ScheduleFrequency;@@ -13,4 +16,6 @@ export type ScheduleDraft = {/** 1-31 day-of-month when frequency === "month". */dayOfMonth: string;target: RoutineTarget;+ onceAt?: string;+ timezone?: string;};diff --git a/apps/web/src/features/routines/core/history.ts b/apps/web/src/features/routines/core/history.tsnew file mode 100644index 0000000000..aadd887264--- /dev/null+++ b/apps/web/src/features/routines/core/history.ts@@ -0,0 +1,8 @@+export type HistoryResource = { type: 'chat' | 'agent'; id: string };+export type HistoryRecord = {+ id?: string | null;+ resource?: HistoryResource;+ startedAt?: string | null;+ endedAt?: string | null;+ success?: boolean | null;+};diff --git a/apps/web/src/features/routines/core/routine-draft.ts b/apps/web/src/features/routines/core/routine-draft.tsnew file mode 100644index 0000000000..1aed4342da--- /dev/null+++ b/apps/web/src/features/routines/core/routine-draft.ts@@ -0,0 +1,129 @@+import {+ buildCron as buildCronExpression,+ type CronParts,+ DEFAULT_TIME,+ DEFAULT_WEEKDAYS,+ describeCron,+ getDefaultTimezone,+ isValidTime,+ parseCron as parseCronParts,+} from '@core/util/cron';+import type { ScheduleDraft } from './draft';+import { routineTargetSchema } from './routine-target';+import { describeTriggers, validateTriggers } from './routine-triggers';++export {+ DEFAULT_TIME,+ getDefaultTimezone,+ isValidTime,+ WEEKDAY_OPTIONS,+} from '@core/util/cron';++type ParsedCron = Pick<+ ScheduleDraft,+ 'frequency' | 'time' | 'daysOfWeek' | 'dayOfMonth'+>;+function normalizePrompt(value: string) {+ return value+ .trim()+ .split(/\n+/)+ .map((line) => line.trim())+ .filter(Boolean)+ .join(' ');+}++export function deriveScheduleName(prompt: string) {+ const summary = normalizePrompt(prompt);+ if (!summary) return 'Untitled routine';+ return summary.length > 72 ? `${summary.slice(0, 71)}…` : summary;+}++export function cronParts(draft: ScheduleDraft): CronParts {+ return {+ frequency: draft.frequency === 'once' ? 'week' : draft.frequency,+ time: draft.time,+ daysOfWeek: draft.daysOfWeek,+ dayOfMonth: draft.dayOfMonth,+ };+}++export function describeSchedule(draft: ScheduleDraft, timezone: string) {+ if (draft.triggers) return describeTriggers(draft.triggers);+ if (draft.frequency === 'once') {+ return draft.onceAt && !Number.isNaN(new Date(draft.onceAt).getTime())+ ? `Once on ${formatDateTime(new Date(draft.onceAt).toISOString())}`+ : 'Choose a date and time for a single run.';+ }+ return describeCron(cronParts(draft), draft.timezone ?? timezone);+}++export function parseCron(cron: string): ParsedCron {+ return parseCronParts(cron);+}++export function buildCron(draft: ScheduleDraft) {+ return buildCronExpression(cronParts(draft));+}++export function createEmptyDraft(model: string): ScheduleDraft {+ return {+ name: '',+ prompt: '',+ frequency: 'week',+ time: DEFAULT_TIME,+ daysOfWeek: [...DEFAULT_WEEKDAYS],+ dayOfMonth: '1',+ target: { kind: 'model', model },+ };+}++export function formatDateTime(value: string | null | undefined) {+ if (!value) return 'Never';++ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return 'Invalid date';++ return new Intl.DateTimeFormat(undefined, {+ dateStyle: 'medium',+ timeStyle: 'short',+ }).format(date);+}++export function validateRoutineDraft(+ draft: ScheduleDraft,+ creating = false+): string | null {+ if (!draft.prompt.trim()) return 'Instructions are required.';+ if (!routineTargetSchema.safeParse(draft.target).success)+ return 'Choose a valid model or agent.';+ if (draft.triggers) return validateTriggers(draft.triggers, creating);+ if (draft.frequency === 'once') {+ const at = new Date(draft.onceAt ?? '').getTime();+ if (!Number.isFinite(at)) return 'Choose a date and time.';+ if (creating && at <= Date.now()) return 'Choose a time in the future.';+ return null;+ }+ if (!isValidTime(draft.time)) return 'Choose a valid time.';+ if (draft.frequency === 'week' && !draft.daysOfWeek.length)+ return 'Select at least one day.';+ if (+ draft.frequency === 'month' &&+ (!Number.isInteger(Number(draft.dayOfMonth)) ||+ Number(draft.dayOfMonth) < 1 ||+ Number(draft.dayOfMonth) > 31)+ )+ return 'Pick a day between 1 and 31.';+ try {+ new Intl.DateTimeFormat(undefined, {+ timeZone: draft.timezone ?? getDefaultTimezone(),+ });+ } catch {+ return 'Choose a valid time zone, such as America/New_York.';+ }+ return null;+}++export function getErrorMessage(error: unknown): string {+ if (error instanceof Error && error.message) return error.message;+ return 'Please try again.';+}diff --git a/apps/web/src/features/block-automation/core/routine-target.test.ts b/apps/web/src/features/routines/core/routine-target.test.tssimilarity index 100%rename from apps/web/src/features/block-automation/core/routine-target.test.tsrename to apps/web/src/features/routines/core/routine-target.test.tsdiff --git a/apps/web/src/features/block-automation/core/routine-target.ts b/apps/web/src/features/routines/core/routine-target.tssimilarity index 100%rename from apps/web/src/features/block-automation/core/routine-target.tsrename to apps/web/src/features/routines/core/routine-target.tsdiff --git a/apps/web/src/features/routines/core/routine-triggers.ts b/apps/web/src/features/routines/core/routine-triggers.tsnew file mode 100644index 0000000000..9c462a87a6--- /dev/null+++ b/apps/web/src/features/routines/core/routine-triggers.ts@@ -0,0 +1,257 @@+import { getDefaultTimezone } from '@core/util/cron';+import { z } from 'zod';++export const scheduleTriggerSchema = z.object({+ id: z.string(),+ kind: z.literal('schedule'),+ frequency: z.enum(['hour', 'day', 'week', 'month', 'once', 'custom']),+ time: z.string(),+ daysOfWeek: z.array(z.string()),+ dayOfMonth: z.string(),+ timezone: z.string(),+ onceAt: z.string(),+ cron: z.string(),+});+export const routineTriggerSchema = z.discriminatedUnion('kind', [+ scheduleTriggerSchema,+ z.object({+ id: z.string(),+ kind: z.literal('event'),+ events: z+ .array(+ z.enum([+ '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',+ ])+ )+ .min(1),+ ids: z.array(z.string().uuid()).optional(),+ }),+]);+export type ScheduleTriggerDraft = z.infer<typeof scheduleTriggerSchema>;+export type RoutineTriggerDraft = z.infer<typeof routineTriggerSchema>;+export type EventTriggerDraft = Extract<RoutineTriggerDraft, { kind: 'event' }>;+export type RoutineEventName = EventTriggerDraft['events'][number];+export const routineEventGroups = [+ 'Channels',+ 'Documents',+ 'Tasks',+ 'Email',+] as const;+export type RoutineEventGroup = (typeof routineEventGroups)[number];+export const routineEvents: {+ value: RoutineEventName;+ label: string;+ group: RoutineEventGroup;+ description: string;+}[] = [+ {+ value: 'channel.created',+ label: 'Channel created',+ group: 'Channels',+ description: 'A channel you can access is created.',+ },+ {+ value: 'channel.message_posted',+ label: 'Message sent in channel',+ group: 'Channels',+ description: 'Someone sends a message in a selected channel.',+ },+ {+ value: 'channel.mentioned',+ label: '@ mentioned in channel',+ group: 'Channels',+ description: 'You are @ mentioned in a selected channel.',+ },+ {+ value: 'document.created',+ label: 'Document created',+ group: 'Documents',+ description:+ 'A document you can access is created. Tasks have their own trigger.',+ },+ {+ value: 'document.deleted',+ label: 'Document deleted',+ group: 'Documents',+ description: 'A selected document is deleted.',+ },+ {+ value: 'task.created',+ label: 'Task created',+ group: 'Tasks',+ description: 'A task you can access is created.',+ },+ {+ value: 'task.status_changed',+ label: 'Status changed',+ group: 'Tasks',+ description: 'The status of a selected task changes.',+ },+ {+ value: 'task.priority_changed',+ label: 'Priority changed',+ group: 'Tasks',+ description: 'The priority of a selected task changes.',+ },+ {+ value: 'task.property_changed',+ label: 'Any property changed',+ group: 'Tasks',+ description:+ 'Any property on a selected task changes, including status and priority.',+ },+ {+ value: 'email.message_received',+ label: 'New email received',+ group: 'Email',+ description:+ 'New mail arrives in your inbox. Excludes spam, trash, drafts and historical imports.',+ },+];++// Preserve saved selectors while keeping the creation menu focused on the+// supported product catalog. Editing another field must not drop old triggers.+const legacyEventLabels: Partial<Record<RoutineEventName, string>> = {+ 'document.updated': 'Document details changed',+ 'channel.message_patched': 'Message edited',+ 'channel.message_attachment_created': 'Attachment added',+};++export function eventScopeKind(trigger: EventTriggerDraft) {+ if (trigger.events.every((event) => event.startsWith('task.'))) return 'TASK';+ if (trigger.events.every((event) => event.startsWith('document.')))+ return 'DOCUMENT';+ if (trigger.events.every((event) => event.startsWith('email.')))+ return 'THREAD';+ return 'CHANNEL';+}++export function isGlobalEvent(events: readonly RoutineEventName[]) {+ return events.every(+ (event) => event.endsWith('.created') || event === 'email.message_received'+ );+}++export function eventTriggerLabel(trigger: EventTriggerDraft) {+ return trigger.events+ .map(+ (event) =>+ routineEvents.find((item) => item.value === event)?.label ??+ legacyEventLabels[event] ??+ event+ )+ .join(', ');+}+export type TriggerFrequency = ScheduleTriggerDraft['frequency'];+export const triggerFrequencies: { value: TriggerFrequency; label: string }[] =+ [+ { value: 'hour', label: 'Hourly' },+ { value: 'day', label: 'Daily' },+ { value: 'week', label: 'Weekly' },+ { value: 'month', label: 'Monthly' },+ { value: 'once', label: 'Once' },+ { value: 'custom', label: 'Custom (cron)' },+ ];+export function newScheduleTrigger(+ frequency: TriggerFrequency+): ScheduleTriggerDraft {+ return {+ id: crypto.randomUUID(),+ kind: 'schedule',+ frequency,+ time: '09:00',+ daysOfWeek: ['2'],+ dayOfMonth: '1',+ timezone: getDefaultTimezone(),+ onceAt: '',+ cron: '0 0 9 * * *',+ };+}+export function validateTriggers(+ triggers: RoutineTriggerDraft[],+ creating = false+): string | null {+ if (!triggers.length)+ return 'Add a trigger to tell this routine when to run.';+ const events = triggers.filter((trigger) => trigger.kind === 'event');+ const scheduleCount = triggers.length - events.length;+ if (scheduleCount + Number(events.length > 0) > 16)+ return 'A routine can have up to 16 schedule and activity trigger groups.';+ if (events.length > 32)+ return 'A routine can have up to 32 activity filters.';+ for (const trigger of triggers) {+ if (trigger.kind === 'event') {+ if (!trigger.events.length) return 'Choose an activity event.';+ if (creating && trigger.ids?.length === 0)+ return 'Choose at least one item for this event trigger.';+ if ((trigger.ids?.length ?? 0) > 100)+ return 'Choose up to 100 items per event trigger.';+ continue;+ }+ if (trigger.frequency === 'once') {+ const at = new Date(trigger.onceAt).getTime();+ if (!Number.isFinite(at))+ return 'Choose a date and time for the one-off trigger.';+ if (creating && at <= Date.now())+ return 'Choose a future time for the one-off trigger.';+ continue;+ }+ if (trigger.frequency === 'custom') {+ const parts = trigger.cron.trim().split(/\s+/);+ if (+ parts.length < 6 ||+ parts.length > 7 ||+ parts.some((part) => !/^[-\w*/?,]+$/.test(part))+ )+ return 'Use a cron expression with seconds, minutes, hours, day, month, weekday, and an optional year.';+ } else if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(trigger.time))+ return 'Choose a valid time.';+ if (trigger.frequency === 'week' && !trigger.daysOfWeek.length)+ return 'Select at least one day for the weekly trigger.';+ if (+ trigger.frequency === 'month' &&+ (!/^\d+$/.test(trigger.dayOfMonth) ||+ Number(trigger.dayOfMonth) < 1 ||+ Number(trigger.dayOfMonth) > 31)+ )+ return 'Choose a day between 1 and 31.';+ try {+ new Intl.DateTimeFormat(undefined, { timeZone: trigger.timezone });+ } catch {+ return 'Choose a valid time zone.';+ }+ }+ return null;+}+export function describeTriggers(triggers: RoutineTriggerDraft[]): string {+ return triggers+ .map((trigger) =>+ trigger.kind === 'event'+ ? eventTriggerLabel(trigger)+ : (triggerFrequencies.find((f) => f.value === trigger.frequency)+ ?.label ?? 'Scheduled')+ )+ .join(' · ');+}++export function hasOnlyScheduledTriggers(+ triggers: RoutineTriggerDraft[] | undefined+): boolean {+ return (+ triggers !== undefined &&+ triggers.length > 0 &&+ triggers.every((trigger) => trigger.kind === 'schedule')+ );+}diff --git a/apps/web/src/features/routines/core/routine.ts b/apps/web/src/features/routines/core/routine.tsnew file mode 100644index 0000000000..21abc5a5f6--- /dev/null+++ b/apps/web/src/features/routines/core/routine.ts@@ -0,0 +1,15 @@+import type { ScheduleDraft } from './draft';++/** The editor's view of a routine, independent of scheduled-action wire fields. */+export type RoutineSnapshot = {+ id: string;+ name: string;+ ownerId: string;+ createdAt: string;+ enabled: boolean;+ nextRunAt?: string | null;+ claimedAt?: string | null;+ revision: number;+ configurationKey: string;+ draft?: ScheduleDraft;+};diff --git a/apps/web/src/features/routines/core/schedule-language.test.ts b/apps/web/src/features/routines/core/schedule-language.test.tsnew file mode 100644index 0000000000..55198c2b98--- /dev/null+++ b/apps/web/src/features/routines/core/schedule-language.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import { parseRecurringSchedule } from './schedule-language';++describe('recurring schedule language', () => {+ it.each([+ [+ 'every weekday at 9am',+ {+ frequency: 'week',+ time: '09:00',+ daysOfWeek: ['2', '3', '4', '5', '6'],+ },+ ],+ [+ 'every Monday at 3:30pm',+ { frequency: 'week', time: '15:30', daysOfWeek: ['2'] },+ ],+ ['daily 14:00', { frequency: 'day', time: '14:00', daysOfWeek: [] }],+ ['every hour', { frequency: 'hour', time: '09:00', daysOfWeek: [] }],+ ])('parses %s', (text, expected) =>+ expect(parseRecurringSchedule(text)).toEqual(expected)+ );+ it.each([+ 'every weekday at 25:00',+ 'daily at 14pm',+ 'tomorrow 9am',+ 'every 5 minutes',+ '',+ ])('does not guess unsupported input: %s', (text) =>+ expect(parseRecurringSchedule(text)).toBeUndefined()+ );+});diff --git a/apps/web/src/features/routines/core/schedule-language.ts b/apps/web/src/features/routines/core/schedule-language.tsnew file mode 100644index 0000000000..2e25ca5a33--- /dev/null+++ b/apps/web/src/features/routines/core/schedule-language.ts@@ -0,0 +1,59 @@+import { parseTime } from '@core/util/dateSearch/parseTime';+import type { ScheduleTriggerDraft } from './routine-triggers';++type ScheduleParts = Pick<+ ScheduleTriggerDraft,+ 'frequency' | 'time' | 'daysOfWeek'+>;++/** Deliberately bounded recurring phrases; one-off dates use Macro's date search. */+export function parseRecurringSchedule(+ input: string+): ScheduleParts | undefined {+ const text = input+ .trim()+ .toLowerCase()+ .replace(/\s+at\s+/g, ' ');+ if (/^(every hour|hourly)$/.test(text))+ return { frequency: 'hour', time: '09:00', daysOfWeek: [] };+ const parsed = parseTime(text);+ if (!parsed) return;+ const time = `${String(parsed.time.hours).padStart(2, '0')}:${String(parsed.time.minutes).padStart(2, '0')}`;+ if (/^(every day|daily)$/.test(parsed.rest))+ return { frequency: 'day', time, daysOfWeek: [] };+ if (/^(every weekday|every weekdays|weekdays)$/.test(parsed.rest))+ return { frequency: 'week', time, daysOfWeek: ['2', '3', '4', '5', '6'] };+ const weekday = parsed.rest.replace(/^every\s+/, '');+ const days = [+ 'sunday',+ 'monday',+ 'tuesday',+ 'wednesday',+ 'thursday',+ 'friday',+ 'saturday',+ ];+ const day = days.findIndex(+ (day) => weekday === day || weekday === day.slice(0, 3)+ );+ if (day >= 0)+ return { frequency: 'week', time, daysOfWeek: [String(day + 1)] };+}++export function scheduleTriggerLabel(trigger: ScheduleTriggerDraft): string {+ if (trigger.frequency === 'hour') return 'Every hour';+ if (trigger.frequency === 'once') return 'Run once';+ if (trigger.frequency === 'custom') return 'Custom schedule';+ if (trigger.frequency === 'day') return 'Every day';+ if (trigger.frequency === 'month')+ return `Monthly on day ${trigger.dayOfMonth}`;+ if (trigger.daysOfWeek.toSorted().join(',') === '2,3,4,5,6')+ return 'Every weekday';+ const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];+ return `Every ${+ trigger.daysOfWeek+ .toSorted()+ .map((day) => days[Number(day) - 1])+ .join(', ') || 'week'+ }`;+}diff --git a/apps/web/src/features/routines/core/types.ts b/apps/web/src/features/routines/core/types.tsnew file mode 100644index 0000000000..aa164c7ae7--- /dev/null+++ b/apps/web/src/features/routines/core/types.ts@@ -0,0 +1,11 @@+export type RoutineRow = {+ id: string;+ name: string;+ creator: string;+ createdAt: string;+ target: string;+ schedule: string;+ status: 'Active' | 'Paused' | 'Running' | 'Completed';+ editable: boolean;+ enabled: boolean;+};diff --git a/apps/web/src/features/block-automation/definition.ts b/apps/web/src/features/routines/definition.tssimilarity index 64%rename from apps/web/src/features/block-automation/definition.tsrename to apps/web/src/features/routines/definition.tsindex e02a8a40bd..f07d33446f 100644--- a/apps/web/src/features/block-automation/definition.ts+++ b/apps/web/src/features/routines/definition.ts@@ -1,13 +1,13 @@import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';import { ok } from 'neverthrow';-import { Automation } from './component/Automation';+import { Routine } from './routine-detail';export const definition = defineBlock({- name: 'automation',- description: 'view and edit a single automation',- defaultFilename: 'Untitled automation',- component: Automation,+ name: 'routine',+ description: 'view and edit a single routine',+ defaultFilename: 'Untitled routine',+ component: Routine,accepted: {},async load(source, intent) {if (source.type === 'dss') {@@ -24,4 +24,4 @@ export const definition = defineBlock({liveTrackingEnabled: false,});-export type AutomationData = ExtractLoadType<(typeof definition)['load']>;+export type RoutineData = ExtractLoadType<(typeof definition)['load']>;diff --git a/apps/web/src/features/block-automation/util/automationComposerStorage.test.ts b/apps/web/src/features/routines/draft-storage.test.tssimilarity index 73%rename from apps/web/src/features/block-automation/util/automationComposerStorage.test.tsrename to apps/web/src/features/routines/draft-storage.test.tsindex 0ad154cbba..a8d8b9781b 100644--- a/apps/web/src/features/block-automation/util/automationComposerStorage.test.ts+++ b/apps/web/src/features/routines/draft-storage.test.ts@@ -1,12 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { ScheduleDraft } from '../component/types';+import type { ScheduleDraft } from './core/draft';import {- clearAutomationComposerDraft,- loadAutomationComposerDraft,- saveAutomationComposerDraft,-} from './automationComposerStorage';+ clearRoutineComposerDraft,+ loadRoutineComposerDraft,+ saveRoutineComposerDraft,+} from './draft-storage';-const storageKey = 'automation-composer-draft';+const storageKey = 'routine-composer-draft';const expiry = 3 * 60 * 1000;const agentId = '0195a096-3d24-7000-8000-000000000001';const draft: ScheduleDraft = {@@ -34,12 +34,12 @@ afterEach(() => {vi.restoreAllMocks();});-describe('automation composer storage', () => {+describe('routine composer storage', () => {it('returns null for empty storage and clears saved drafts', () => {- expect(loadAutomationComposerDraft()).toBeNull();- saveAutomationComposerDraft(draft);- clearAutomationComposerDraft();- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();+ saveRoutineComposerDraft(draft);+ clearRoutineComposerDraft();+ expect(loadRoutineComposerDraft()).toBeNull();});it.each<ScheduleDraft['target']>([@@ -48,13 +48,13 @@ describe('automation composer storage', () => {{ kind: 'agent', agentId, modelOverride: 'runtime/custom' },])('round trips targets without a catalog: %j', (target) => {const saved = { ...draft, target };- saveAutomationComposerDraft(saved);- expect(loadAutomationComposerDraft()).toEqual(saved);+ saveRoutineComposerDraft(saved);+ expect(loadRoutineComposerDraft()).toEqual(saved);});- it('drops activation saved by older clients', () => {+ it('retains the draft activation choice', () => {store({ draft: { ...draft, enabled: false }, timestamp: Date.now() });- expect(loadAutomationComposerDraft()).toEqual(draft);+ expect(loadRoutineComposerDraft()).toEqual({ ...draft, enabled: false });});it('migrates an unexpired legacy model without refreshing its expiry', () => {@@ -64,21 +64,22 @@ describe('automation composer storage', () => {timestamp: Date.now(),});vi.advanceTimersByTime(expiry);- expect(loadAutomationComposerDraft()).toEqual({+ expect(loadRoutineComposerDraft()).toEqual({...fields,+ enabled: true,target: { kind: 'model', model: 'removed-from-catalog' },});vi.advanceTimersByTime(1);- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();expect(localStorage.getItem(storageKey)).toBeNull();});it('retains drafts at the expiry boundary, then removes them', () => {- saveAutomationComposerDraft(draft);+ saveRoutineComposerDraft(draft);vi.advanceTimersByTime(expiry);- expect(loadAutomationComposerDraft()).toEqual(draft);+ expect(loadRoutineComposerDraft()).toEqual(draft);vi.advanceTimersByTime(1);- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();expect(localStorage.getItem(storageKey)).toBeNull();});@@ -93,7 +94,7 @@ describe('automation composer storage', () => {{ draft: null, timestamp: 0 },])('clears malformed envelopes: %j', (payload) => {store(payload);- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();expect(localStorage.getItem(storageKey)).toBeNull();});@@ -119,7 +120,7 @@ describe('automation composer storage', () => {'clears malformed drafts without silently changing their selection: %j',(fields) => {store({ draft: { ...draft, ...fields }, timestamp: Date.now() });- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();expect(localStorage.getItem(storageKey)).toBeNull();});@@ -127,15 +128,15 @@ describe('automation composer storage', () => {it('handles invalid JSON and inaccessible storage', () => {vi.spyOn(console, 'warn').mockImplementation(() => {});localStorage.setItem(storageKey, '{');- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();expect(localStorage.getItem(storageKey)).toBeNull();vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {throw new Error('Unavailable');});- expect(loadAutomationComposerDraft()).toBeNull();+ expect(loadRoutineComposerDraft()).toBeNull();vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {throw new Error('Quota exceeded');});- expect(() => saveAutomationComposerDraft(draft)).not.toThrow();+ expect(() => saveRoutineComposerDraft(draft)).not.toThrow();});});diff --git a/apps/web/src/features/block-automation/util/automationComposerStorage.ts b/apps/web/src/features/routines/draft-storage.tssimilarity index 60%rename from apps/web/src/features/block-automation/util/automationComposerStorage.tsrename to apps/web/src/features/routines/draft-storage.tsindex 9e2603bd0b..9399fc25eb 100644--- a/apps/web/src/features/block-automation/util/automationComposerStorage.ts+++ b/apps/web/src/features/routines/draft-storage.ts@@ -1,20 +1,21 @@import { z } from 'zod';-import type { ScheduleDraft } from '../component/types';-import {- routineModelSchema,- routineTargetSchema,-} from '../core/routine-target';+import type { ScheduleDraft } from './core/draft';+import { routineModelSchema, routineTargetSchema } from './core/routine-target';+import { routineTriggerSchema } from './core/routine-triggers';-const STORAGE_KEY = 'automation-composer-draft';+const STORAGE_KEY = 'routine-composer-draft';const EXPIRY_TIME_MS = 3 * 60 * 1000;const draftFields = {id: z.string().optional(),+ triggers: z.array(routineTriggerSchema).max(16).optional(),name: z.string(),prompt: z.string(),- frequency: z.enum(['week', 'month']),+ frequency: z.enum(['week', 'month', 'once']),// Incomplete schedule inputs are valid drafts, even before they can be submitted.time: z.string(),+ onceAt: z.string().optional(),+ timezone: z.string().optional(),daysOfWeek: z.array(z.string()),dayOfMonth: z.string(),// Older clients saved routine activation with the draft.@@ -31,23 +32,23 @@ const draftSchema = ztarget: { kind: 'model' as const, model },})),])- .transform(({ enabled: _enabled, ...draft }): ScheduleDraft => draft);+ .transform((draft): ScheduleDraft => draft);const storedDraftSchema = z.object({draft: draftSchema,timestamp: z.number().nonnegative(),});-export function saveAutomationComposerDraft(draft: ScheduleDraft): void {+export function saveRoutineComposerDraft(draft: ScheduleDraft): void {try {const payload = { draft, timestamp: Date.now() };localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));} catch (error) {- console.warn('Failed to save automation composer draft:', error);+ console.warn('Failed to save routine composer draft:', error);}}-export function loadAutomationComposerDraft(): ScheduleDraft | null {+export function loadRoutineComposerDraft(): ScheduleDraft | null {try {const stored = localStorage.getItem(STORAGE_KEY);if (!stored) return null;@@ -57,21 +58,21 @@ export function loadAutomationComposerDraft(): ScheduleDraft | null {!payload.success ||Date.now() - payload.data.timestamp > EXPIRY_TIME_MS) {- clearAutomationComposerDraft();+ clearRoutineComposerDraft();return null;}return payload.data.draft;} catch (error) {- console.warn('Failed to load automation composer draft:', error);- clearAutomationComposerDraft();+ console.warn('Failed to load routine composer draft:', error);+ clearRoutineComposerDraft();return null;}}-export function clearAutomationComposerDraft(): void {+export function clearRoutineComposerDraft(): void {try {localStorage.removeItem(STORAGE_KEY);} catch (error) {- console.warn('Failed to clear automation composer draft:', error);+ console.warn('Failed to clear routine composer draft:', error);}}diff --git a/apps/web/src/features/block-automation/primitives/routine-autosave.test.ts b/apps/web/src/features/routines/primitives/routine-autosave.test.tssimilarity index 100%rename from apps/web/src/features/block-automation/primitives/routine-autosave.test.tsrename to apps/web/src/features/routines/primitives/routine-autosave.test.tsdiff --git a/apps/web/src/features/block-automation/primitives/routine-autosave.ts b/apps/web/src/features/routines/primitives/routine-autosave.tssimilarity index 100%rename from apps/web/src/features/block-automation/primitives/routine-autosave.tsrename to apps/web/src/features/routines/primitives/routine-autosave.tsdiff --git a/apps/web/src/features/routines/primitives/routine-composer.test.ts b/apps/web/src/features/routines/primitives/routine-composer.test.tsnew file mode 100644index 0000000000..65ed5cca51--- /dev/null+++ b/apps/web/src/features/routines/primitives/routine-composer.test.ts@@ -0,0 +1,94 @@+import { createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { RoutineDraftStorage } from '../context/routine-sources';+import { createEmptyDraft } from '../core/routine-draft';+import { createRoutineComposer } from './routine-composer';++const draft = {+ ...createEmptyDraft('claude-sonnet-4-6'),+ prompt: 'Review new tasks',+ enabled: false,+ triggers: [+ { id: 'tasks', kind: 'event' as const, events: ['task.created' as const] },+ ],+};++let dispose = () => {};+afterEach(() => dispose());++function setup(create: () => Promise<string>) {+ const storage: RoutineDraftStorage = {+ load: () => draft,+ save: vi.fn(),+ clear: vi.fn(),+ };+ const onCreated = vi.fn();+ const [pending, setPending] = createSignal(false);+ const source = {+ pending,+ create: vi.fn(async () => {+ setPending(true);+ try {+ return await create();+ } finally {+ setPending(false);+ }+ }),+ };+ const composer = createRoot((cleanup) => {+ dispose = cleanup;+ return createRoutineComposer(source, storage, 'default-model', onCreated);+ });+ return { composer, storage, onCreated, source };+}++describe('routine creation state without app providers', () => {+ it('retains a failed draft and clears storage only after a successful retry', async () => {+ const create = vi+ .fn()+ .mockRejectedValueOnce(new Error('Unavailable'))+ .mockResolvedValueOnce('routine-id');+ const { composer, storage, onCreated } = setup(create);+ composer.change((current) => ({ ...current, name: 'Task review' }));+ await composer.create();+ expect(composer.submitError()).toBe('Unavailable');+ expect(storage.clear).not.toHaveBeenCalled();+ expect(onCreated).not.toHaveBeenCalled();+ expect(composer.draft().name).toBe('Task review');+ await composer.create();+ expect(storage.clear).toHaveBeenCalledOnce();+ expect(onCreated).toHaveBeenCalledExactlyOnceWith('routine-id');+ dispose();+ expect(storage.save).not.toHaveBeenCalled();+ });++ it('rejects a duplicate submit and edits while the create request is pending', async () => {+ let resolve!: (id: string) => void;+ const { composer, source, onCreated } = setup(+ () =>+ new Promise((done) => {+ resolve = done;+ })+ );+ const request = composer.create();+ await composer.create();+ composer.change((current) => ({ ...current, prompt: 'Changed' }));+ expect(source.create).toHaveBeenCalledOnce();+ expect(composer.draft().prompt).toBe(draft.prompt);+ resolve('created');+ await request;+ expect(onCreated).toHaveBeenCalledExactlyOnceWith('created');+ });++ it('keeps an incomplete trigger in the draft without sending it to the server', async () => {+ const { composer, source, storage } = setup(async () => 'created');+ composer.change((current) => ({ ...current, triggers: [] }));+ await composer.create();+ expect(composer.attempted()).toBe(true);+ expect(source.create).not.toHaveBeenCalled();+ dispose();+ expect(storage.save).toHaveBeenCalledWith(+ expect.objectContaining({ triggers: [] })+ );+ });+});diff --git a/apps/web/src/features/routines/primitives/routine-composer.ts b/apps/web/src/features/routines/primitives/routine-composer.tsnew file mode 100644index 0000000000..f8c0a9c169--- /dev/null+++ b/apps/web/src/features/routines/primitives/routine-composer.ts@@ -0,0 +1,64 @@+import { debounce } from '@solid-primitives/scheduled';+import { createSignal, onCleanup } from 'solid-js';+import type {+ RoutineCreatorSource,+ RoutineDraftStorage,+} from '../context/routine-sources';+import type { ScheduleDraft } from '../core/draft';+import {+ createEmptyDraft,+ getErrorMessage,+ validateRoutineDraft,+} from '../core/routine-draft';++export function createRoutineComposer(+ source: RoutineCreatorSource,+ storage: RoutineDraftStorage,+ defaultModel: string,+ onCreated: (id: string) => void+) {+ const restored = storage.load();+ const [draft, setDraft] = createSignal<ScheduleDraft>(+ restored+ ? {+ ...restored,+ triggers: restored.triggers ?? [],+ enabled: restored.enabled ?? true,+ }+ : { ...createEmptyDraft(defaultModel), triggers: [], enabled: true }+ );+ const [attempted, setAttempted] = createSignal(false);+ const [submitError, setSubmitError] = createSignal<string>();+ const save = debounce((value: ScheduleDraft) => storage.save(value), 300);+ let dirty = false;+ function change(update: (draft: ScheduleDraft) => ScheduleDraft) {+ if (source.pending()) return;+ const next = update(draft());+ if (next === draft()) return;+ setDraft(next);+ dirty = true;+ setSubmitError(undefined);+ save(next);+ }+ onCleanup(() => {+ save.clear();+ if (dirty) storage.save(draft());+ });+ async function create() {+ if (source.pending()) return;+ setAttempted(true);+ if (validateRoutineDraft(draft(), true)) return;+ let id: string;+ try {+ id = await source.create(draft());+ } catch (error) {+ setSubmitError(getErrorMessage(error));+ return;+ }+ save.clear();+ dirty = false;+ storage.clear();+ onCreated(id);+ }+ return { draft, change, attempted, submitError, create };+}diff --git a/apps/web/src/features/routines/primitives/routine-detail.ts b/apps/web/src/features/routines/primitives/routine-detail.tsnew file mode 100644index 0000000000..9c09c545d2--- /dev/null+++ b/apps/web/src/features/routines/primitives/routine-detail.ts@@ -0,0 +1,151 @@+import { type Accessor, createEffect, createSignal, on } from 'solid-js';+import type { RoutineDetailSource } from '../context/routine-sources';+import { isClaimActive } from '../core/claim';+import type { ScheduleDraft } from '../core/draft';+import { formatDateTime, validateRoutineDraft } from '../core/routine-draft';+import { hasOnlyScheduledTriggers } from '../core/routine-triggers';+import { createRoutineAutosave } from './routine-autosave';++export class RoutineConflictError extends Error {+ constructor() {+ super(+ 'This routine changed elsewhere. Reload the latest settings before editing.'+ );+ }+}+export function createRoutineDetail(+ source: RoutineDetailSource,+ options: {+ userId: Accessor<string | undefined>;+ onRename(name: string): void;+ }+) {+ const schedule = source.routine;+ const isOwned = () => schedule()?.ownerId === options.userId();+ const editableTrigger = () => Boolean(schedule());+ const isRunning = () => isClaimActive(schedule()?.claimedAt);+ const isActive = () => schedule()?.enabled ?? false;+ const [state, setRawState] = createSignal<ScheduleDraft | undefined>();+ const [editorVersion, setEditorVersion] = createSignal(0);+ let baselineRevision = 0;+ let baselineKey = '';++ const isCompleted = () =>+ hasOnlyScheduledTriggers(state()?.triggers) &&+ !schedule()?.nextRunAt &&+ !isRunning();++ const formError = () => {+ const draft = state();+ return draft ? validateRoutineDraft(draft) : null;+ };++ const autosave = createRoutineAutosave<ScheduleDraft>(async (draft) => {+ const previous = schedule();+ if (!previous || !editableTrigger()) {+ throw new Error('This routine is no longer editable.');+ }+ if (+ previous.revision > baselineRevision &&+ previous.configurationKey !== baselineKey+ )+ throw new RoutineConflictError();+ const saved = await source.update(draft);+ baselineRevision = saved.revision;+ baselineKey = saved.configurationKey;+ });++ function setState(update: (prev: ScheduleDraft) => ScheduleDraft): void {+ const current = state();+ if (!isOwned() || !current || !editableTrigger() || isRunning()) return;+ const next = update(current);+ if (next === current) return;+ setRawState(next);+ if (next.name !== current.name) {+ options.onRename(next.name);+ }+ autosave.queue(formError() ? undefined : next);+ }++ function runNow(): void {+ if (+ !isOwned() ||+ !editableTrigger() ||+ !state() ||+ formError() ||+ autosave.dirty() ||+ autosave.saving() ||+ source.runPending() ||+ isRunning()+ )+ return;+ source.run();+ }++ function initializeDraft(): void {+ const current = schedule();+ if (!current) return;+ baselineRevision = current.revision;+ baselineKey = current.configurationKey;+ setRawState(current.draft);+ setEditorVersion((version) => version + 1);+ options.onRename(current.name);+ }++ // A server revision refreshes clean settings, while a pending edit keeps its+ // original revision so a conflicting remote change cannot be overwritten.+ createEffect(+ on(+ () => schedule()?.revision,+ (revision) => {+ if (revision === undefined) return;+ if (+ !state() ||+ (revision > baselineRevision &&+ !autosave.dirty() &&+ !autosave.saving())+ )+ initializeDraft();+ }+ )+ );++ const nextRun = () => {+ if (!isActive()) return 'Paused';+ const next = schedule()?.nextRunAt;+ if (next) return formatDateTime(next);+ if (isRunning()) return 'Running now';+ if (isCompleted()) return 'No upcoming runs';+ return 'On the next matching event';+ };++ const runDisabled = () =>+ !isOwned() ||+ source.runPending() ||+ isRunning() ||+ autosave.dirty() ||+ autosave.saving() ||+ Boolean(formError()) ||+ !state();+ const activationDisabled = () =>+ !isOwned() ||+ source.activationPending() ||+ (!isActive() && (isCompleted() || runDisabled()));++ return {+ schedule,+ state,+ setState,+ isOwned,+ isRunning,+ isActive,+ editorVersion,+ formError,+ autosave,+ initializeDraft,+ nextRun,+ runDisabled,+ activationDisabled,+ runNow,+ };+}diff --git a/apps/web/src/features/routines/primitives/routines-list.ts b/apps/web/src/features/routines/primitives/routines-list.tsnew file mode 100644index 0000000000..2de7678f73--- /dev/null+++ b/apps/web/src/features/routines/primitives/routines-list.ts@@ -0,0 +1,46 @@+import { type Accessor, createMemo } from 'solid-js';+import type { RoutineListSource } from '../context/routine-sources';+import { isClaimActive } from '../core/claim';+import { describeSchedule, getDefaultTimezone } from '../core/routine-draft';+import type { RoutineTarget } from '../core/routine-target';+import { hasOnlyScheduledTriggers } from '../core/routine-triggers';+import type { RoutineRow } from '../core/types';++export function createRoutineRows(+ source: RoutineListSource,+ userId: Accessor<string | undefined>,+ targetLabel: (target: RoutineTarget) => string+) {+ return createMemo<RoutineRow[]>(() =>+ source+ .routines()+ .toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))+ .map((routine) => {+ const draft = routine.draft;+ const running = isClaimActive(routine.claimedAt);+ const completed =+ hasOnlyScheduledTriggers(draft?.triggers) &&+ !routine.nextRunAt &&+ !running;+ return {+ id: routine.id,+ name: routine.name,+ creator: 'You',+ createdAt: routine.createdAt,+ target: draft?.target ? targetLabel(draft.target) : 'Agent',+ schedule: draft+ ? describeSchedule(draft, getDefaultTimezone())+ : 'Event triggered',+ status: running+ ? 'Running'+ : completed+ ? 'Completed'+ : routine.enabled+ ? 'Active'+ : 'Paused',+ enabled: routine.enabled,+ editable: routine.ownerId === userId(),+ };+ })+ );+}diff --git a/apps/web/src/lib/queries/agent-schedule/entities.query.test.tsx b/apps/web/src/features/routines/queries/entities.query.test.tsxsimilarity index 97%rename from apps/web/src/lib/queries/agent-schedule/entities.query.test.tsxrename to apps/web/src/features/routines/queries/entities.query.test.tsxindex 5c0056eaa7..83143f38e1 100644--- a/apps/web/src/lib/queries/agent-schedule/entities.query.test.tsx+++ b/apps/web/src/features/routines/queries/entities.query.test.tsx@@ -3,7 +3,7 @@ import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';import { QueryClient, type UseQueryResult } from '@tanstack/solid-query';import { type JSX, Suspense } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';-import { useAutomationEntities } from './entities';+import { useRoutineEntities } from './entities';const mocks = vi.hoisted(() => ({query: undefined as UseQueryResult<ScheduledAction[]> | undefined,@@ -31,7 +31,7 @@ vi.mock('./schedules', async () => {});function Entities(): JSX.Element {- const entities = useAutomationEntities();+ const entities = useRoutineEntities();return (<div data-testid="entities">{entities()diff --git a/apps/web/src/lib/queries/agent-schedule/entities.test.ts b/apps/web/src/features/routines/queries/entities.test.tssimilarity index 84%rename from apps/web/src/lib/queries/agent-schedule/entities.test.tsrename to apps/web/src/features/routines/queries/entities.test.tsindex 850e4e68a5..5c41051766 100644--- a/apps/web/src/lib/queries/agent-schedule/entities.test.ts+++ b/apps/web/src/features/routines/queries/entities.test.ts@@ -2,7 +2,7 @@ import type { RoutineStatus } from '@entity/types/entity';import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';import { createRoot } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { scheduleToEntity, useAutomationEntities } from './entities';+import { scheduleToEntity, useRoutineEntities } from './entities';import { getCronTrigger } from './triggers';const query = vi.hoisted(() => ({@@ -79,11 +79,11 @@ describe('routine status', () => {});});-describe('cron-only automation entities', () => {+describe('routine entities', () => {it('converts canonical cron actions', () => {expect(scheduleToEntity(cron)).toEqual({id: 'cron-id',- type: 'automation',+ type: 'routine',name: 'Summary',ownerId: 'macro|[email protected]',createdAt: '2026-09-22T12:00:00Z',@@ -93,8 +93,11 @@ describe('cron-only automation entities', () => {});});- it('omits events and actions without an id', () => {- expect(scheduleToEntity(events)).toBeUndefined();+ it('includes event routines without inventing a cron and omits drafts without an id', () => {+ expect(scheduleToEntity(events)).toMatchObject({+ id: 'event-id',+ cron: undefined,+ });expect(scheduleToEntity({ ...cron, id: null })).toBeUndefined();expect(scheduleToEntity({@@ -102,7 +105,7 @@ describe('cron-only automation entities', () => {schedule: '0 0 9 * * 2',timezone: 'UTC',} as ScheduledAction)- ).toBeUndefined();+ ).toMatchObject({ id: 'event-id', cron: undefined });});it('accepts legacy cached cron actions through the compatibility helper', () => {@@ -117,11 +120,12 @@ describe('cron-only automation entities', () => {expect(getCronTrigger({ schedule: null, timezone: null })).toBeUndefined();});- it('filters events from mixed API/cache lists', () => {+ it('includes all routine trigger types in mixed lists', () => {query.isSuccess = true;query.items = [events, cron];createRoot((dispose) => {- expect(useAutomationEntities()().map((entity) => entity.id)).toEqual([+ expect(useRoutineEntities()().map((entity) => entity.id)).toEqual([+ 'event-id','cron-id',]);dispose();@@ -135,7 +139,7 @@ describe('cron-only automation entities', () => {throw new Error('Pending resource read');});createRoot((dispose) => {- expect(useAutomationEntities()()).toEqual([]);+ expect(useRoutineEntities()()).toEqual([]);dispose();});data.mockRestore();@@ -143,11 +147,12 @@ describe('cron-only automation entities', () => {query.isPending = false;});- it('retains cached cron entities after a refetch error, excluding event routines', () => {+ it('retains cached routines after a refetch error', () => {query.isSuccess = false;query.items = [events, cron];createRoot((dispose) => {- expect(useAutomationEntities()().map((entity) => entity.id)).toEqual([+ expect(useRoutineEntities()().map((entity) => entity.id)).toEqual([+ 'event-id','cron-id',]);dispose();@@ -158,7 +163,7 @@ describe('cron-only automation entities', () => {query.isSuccess = false;query.items = [];createRoot((dispose) => {- expect(useAutomationEntities()()).toEqual([]);+ expect(useRoutineEntities()()).toEqual([]);dispose();});});diff --git a/apps/web/src/lib/queries/agent-schedule/entities.ts b/apps/web/src/features/routines/queries/entities.tssimilarity index 56%rename from apps/web/src/lib/queries/agent-schedule/entities.tsrename to apps/web/src/features/routines/queries/entities.tsindex 562f1e373a..e86b8dec33 100644--- a/apps/web/src/lib/queries/agent-schedule/entities.ts+++ b/apps/web/src/features/routines/queries/entities.ts@@ -1,33 +1,25 @@-import { type AutomationEntity, routineStatus } from '@entity/types/entity';+import { type RoutineEntity, routineStatus } from '@entity/types/entity';import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';import { createMemo } from 'solid-js';+import { isClaimActive } from '../core/claim';import { useSchedulesQuery } from './schedules';import { getCronTrigger } from './triggers';-// Must match `MAX_ACTION_TIME` on the backend-// (services/scheduled_action/src/domain/models.rs). After this window-// a claim is treated as stale — an executor crashed mid-run — so we stop-// reporting the action as running.-const MAX_CLAIMED_MS = 20 * 60 * 1000;--function isClaimActive(claimed: string | undefined | null): boolean {- if (!claimed) return false;- return Date.now() - Date.parse(claimed) < MAX_CLAIMED_MS;-}+export { isClaimActive } from '../core/claim';export function scheduleToEntity(schedule: ScheduledAction-): AutomationEntity | undefined {+): RoutineEntity | undefined {const trigger = getCronTrigger(schedule);- if (!schedule.id || !trigger) return undefined;+ if (!schedule.id) return undefined;return {id: schedule.id,- type: 'automation',+ type: 'routine',name: schedule.name,ownerId: schedule.owner,createdAt: schedule.created_at,updatedAt: schedule.updated_at,- cron: trigger.schedule,+ cron: trigger?.schedule,status: routineStatus({enabled: schedule.enabled,isRunning: isClaimActive(schedule.claimed),@@ -37,16 +29,16 @@ export function scheduleToEntity(}/**- * Reactive list of automation entities derived from the scheduled-action+ * Reactive list of routine entities derived from the scheduled-action* query. Safe to call from any component tree that's under a QueryClient —* returns `[]` until the query resolves.*/-export function useAutomationEntities() {+export function useRoutineEntities() {const schedulesQuery = useSchedulesQuery(() => true);- return createMemo<AutomationEntity[]>(() => {+ return createMemo<RoutineEntity[]>(() => {const data = schedulesQuery.isPending ? undefined : schedulesQuery.data;if (!data) return [];- const out: AutomationEntity[] = [];+ const out: RoutineEntity[] = [];for (const schedule of data) {const entity = scheduleToEntity(schedule);if (entity) out.push(entity);diff --git a/apps/web/src/features/routines/queries/history-metadata.ts b/apps/web/src/features/routines/queries/history-metadata.tsnew file mode 100644index 0000000000..4c2c0c6c33--- /dev/null+++ b/apps/web/src/features/routines/queries/history-metadata.ts@@ -0,0 +1,59 @@+import { useAgentSessionQuery } from '@queries/agent-session/session';+import { useChatQuery } from '@queries/chat';+import type { Accessor } from 'solid-js';+import type { HistoryMetadata } from '../context/history';+export function createChatHistoryMetadata(+ id: string+): Accessor<HistoryMetadata> {+ const query = useChatQuery(() => id);+ return () => {+ if (query.isPending) return { status: 'pending' };+ if (!query.isSuccess) return { status: 'unavailable' };+ const chat = query.data?.chat;+ return chat+ ? {+ status: 'ready',+ entity: {+ type: 'chat',+ id,+ name: chat.name,+ ownerId: chat.userId,+ createdAt: chat.createdAt,+ updatedAt: chat.updatedAt,+ model: chat.model,+ },+ }+ : { status: 'unavailable' };+ };+}++export function createAgentHistoryMetadata(+ id: string+): Accessor<HistoryMetadata> {+ const query = useAgentSessionQuery(() => id);+ return () => {+ if (query.isPending) return { status: 'pending' };+ if (!query.isSuccess) return { status: 'unavailable' };+ const session = query.data;+ return session+ ? {+ status: 'ready',+ entity: {+ type: 'agent_session',+ id,+ name: session.name,+ ownerId: session.ownerId,+ botId: session.botId,+ harness: session.harness,+ isArchived: session.isArchived,+ createdAt: session.createdAt,+ updatedAt: session.modifiedAt,+ status:+ session.status.kind === 'event'+ ? session.status.event+ : session.status.kind,+ },+ }+ : { status: 'unavailable' };+ };+}diff --git a/apps/web/src/lib/queries/agent-schedule/keys.ts b/apps/web/src/features/routines/queries/keys.tssimilarity index 100%rename from apps/web/src/lib/queries/agent-schedule/keys.tsrename to apps/web/src/features/routines/queries/keys.tsdiff --git a/apps/web/src/features/block-automation/component/automationUtils.test.ts b/apps/web/src/features/routines/queries/routine-draft.test.tssimilarity index 74%rename from apps/web/src/features/block-automation/component/automationUtils.test.tsrename to apps/web/src/features/routines/queries/routine-draft.test.tsindex dd111f2abf..b91f7fe291 100644--- a/apps/web/src/features/block-automation/component/automationUtils.test.ts+++ b/apps/web/src/features/routines/queries/routine-draft.test.ts@@ -1,19 +1,20 @@import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';import { describe, expect, it, vi } from 'vitest';+import type { ScheduleDraft } from '../core/draft';+import { createEmptyDraft, validateRoutineDraft } from '../core/routine-draft';import {- createEmptyDraft,draftFromSchedule,draftToCreateBody,draftToUpdateBody,+ onceFromCron,scheduleToDuplicateBody,-} from './automationUtils';-import type { ScheduleDraft } from './types';+} from './routine-draft';vi.mock('@core/component/AI/constant', () => ({DEFAULT_MODEL: 'claude-sonnet-4-6',}));vi.mock('@core/constant/allBlocks', () => ({- blockNameToDefaultFile: () => 'New automation',+ blockNameToDefaultFile: () => 'New routine',}));const cron: ScheduledAction = {@@ -51,7 +52,7 @@ const legacy = {function draft(): ScheduleDraft {return {- ...createEmptyDraft(),+ ...createEmptyDraft('anthropic/claude-sonnet-4-5'),name: ' Summary ',prompt: ' Summarize updates ',};@@ -246,7 +247,7 @@ describe('routine execution payloads', () => {});});-describe('cron automation payloads', () => {+describe('cron routine payloads', () => {it('creates a canonical trigger without legacy fields', () => {const body = draftToCreateBody(draft());expect(body).toMatchObject({@@ -276,6 +277,34 @@ describe('cron automation payloads', () => {});+ it('retains a legacy cached schedule when adding a channel event', () => {+ const loaded = draftFromSchedule(legacy)!;+ expect(loaded.triggers).toHaveLength(1);+ const body = draftToUpdateBody(+ {+ ...loaded,+ triggers: [+ ...loaded.triggers!,+ { kind: 'event', id: 'new', events: ['channel.message_posted'] },+ ],+ },+ legacy+ );+ expect(body).toMatchObject({+ trigger: {+ type: 'multiple',+ triggers: [+ {+ type: 'cron',+ schedule: '0 30 10 * * 2,4',+ timezone: 'America/New_York',+ },+ { type: 'events', filters: [{ events: ['channel.message_posted'] }] },+ ],+ },+ });+ });+it.each([cron, legacy])('duplicates cron without changing its expression or task',(action) => {@@ -311,11 +340,18 @@ describe('cron automation payloads', () => {});it.each([events, { ...events, schedule: '0 0 9 * * 2', timezone: 'UTC' }])(- 'never parses, updates, or duplicates an event trigger, even with stale legacy fields',+ 'edits and duplicates canonical event triggers without using stale legacy cron fields',(action) => {- expect(draftFromSchedule(action)).toBeUndefined();- expect(draftToUpdateBody(draft(), action)).toBeUndefined();- expect(scheduleToDuplicateBody(action)).toBeUndefined();+ const loaded = draftFromSchedule(action)!;+ expect(loaded.triggers).toMatchObject([+ { kind: 'event', events: ['document.updated'] },+ ]);+ expect(draftToUpdateBody(loaded, action)).toMatchObject({+ trigger: action.trigger,+ });+ expect(scheduleToDuplicateBody(action)).toMatchObject({+ trigger: action.trigger,+ });});@@ -327,3 +363,54 @@ describe('cron automation payloads', () => {});});});++describe('one-off routines', () => {+ it('preserves the instant of a year-bounded cron in another timezone', () => {+ const once = onceFromCron('0 0 9 3 10 * 2030', 'America/New_York');+ expect(new Date(once!.onceAt).toISOString()).toBe(+ '2030-10-03T13:00:00.000Z'+ );+ });+ it('keeps an unchanged one-off trigger and its timezone when editing instructions', () => {+ const routine = {+ ...cron,+ trigger: {+ type: 'cron' as const,+ schedule: '12 0 9 3 10 * 2030',+ timezone: 'America/New_York',+ },+ };+ const draft = loadedDraft(routine);+ expect(draft.frequency).toBe('once');+ expect(+ draftToUpdateBody({ ...draft, prompt: 'New instructions' }, routine)+ ).toEqual(expect.objectContaining({ trigger: routine.trigger }));+ const created = draftToCreateBody(draft);+ expect(+ created && 'trigger' in created ? created.trigger : undefined+ ).toEqual({+ type: 'cron',+ schedule: '12 0 13 3 10 * 2030',+ timezone: 'UTC',+ });+ });+ it('rejects past one-off creation but permits editing a completed routine', () => {+ const once = {+ ...draft(),+ frequency: 'once' as const,+ onceAt: '2000-01-01T09:00',+ };+ expect(validateRoutineDraft(once, true)).toBe(+ 'Choose a time in the future.'+ );+ expect(validateRoutineDraft(once)).toBeNull();+ });+ it('rejects empty weekdays and invalid timezones', () => {+ expect(+ validateRoutineDraft({ ...draft(), frequency: 'week', daysOfWeek: [] })+ ).toBe('Select at least one day.');+ expect(+ validateRoutineDraft({ ...draft(), timezone: 'Mars/Olympus' })+ ).toContain('valid time zone');+ });+});diff --git a/apps/web/src/features/block-automation/component/automationUtils.ts b/apps/web/src/features/routines/queries/routine-draft.tssimilarity index 54%rename from apps/web/src/features/block-automation/component/automationUtils.tsrename to apps/web/src/features/routines/queries/routine-draft.tsindex 500d24655c..e9a29dea12 100644--- a/apps/web/src/features/block-automation/component/automationUtils.ts+++ b/apps/web/src/features/routines/queries/routine-draft.ts@@ -1,22 +1,24 @@-import { DEFAULT_MODEL } from '@core/component/AI/constant';-import { blockNameToDefaultFile } from '@core/constant/allBlocks';import {- buildCron as buildCronExpression,- type CronParts,- DEFAULT_TIME,- DEFAULT_WEEKDAYS,- describeCron,- getDefaultTimezone,- parseCron as parseCronParts,-} from '@core/util/cron';-import { ThrownResultError } from '@core/util/result';-import { getCronTrigger } from '@queries/agent-schedule/triggers';+ buildCron,+ deriveScheduleName,+ parseCron,+} from '../core/routine-draft';+import {+ onceFromCron,+ parseRoutineTriggers,+ serializeTriggers,+} from './routine-trigger-mapping';++export { onceFromCron } from './routine-trigger-mapping';++import { getDefaultTimezone } from '@core/util/cron';import type {CreateScheduledAction,ScheduledAction,UpdateScheduledAction,} from '@service-scheduled-action/generated/schemas';import { z } from 'zod';+import type { ScheduleDraft } from '../core/draft';import {type RoutineTarget,routineAgentIdSchema,@@ -24,85 +26,7 @@ import {routineTargetSchema,routineTargetsEqual,} from '../core/routine-target';-import type { ScheduleDraft, ScheduleFrequency } from './types';--export {- DEFAULT_TIME,- getDefaultTimezone,- isValidTime,- WEEKDAY_OPTIONS,-} from '@core/util/cron';--export const INPUT_CLASS =- 'w-full border border-edge-muted rounded-sm bg-surface px-2 py-1.5 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:border-accent/20 cursor-default';--export const FREQUENCY_OPTIONS: Array<{- value: ScheduleFrequency;- label: string;-}> = [- { value: 'week', label: 'Every week' },- { value: 'month', label: 'Every month' },-];--function normalizePrompt(value: string) {- return value- .trim()- .split(/\n+/)- .map((line) => line.trim())- .filter(Boolean)- .join(' ');-}--function deriveScheduleName(prompt: string) {- const summary = normalizePrompt(prompt);- if (!summary) return blockNameToDefaultFile('automation');- return summary.length > 72 ? `${summary.slice(0, 71)}…` : summary;-}--/** The cron-editable parts of a draft, which is all the shared helpers need. */-function cronParts(draft: ScheduleDraft): CronParts {- return {- frequency: draft.frequency,- time: draft.time,- daysOfWeek: draft.daysOfWeek,- dayOfMonth: draft.dayOfMonth,- };-}--export function describeSchedule(draft: ScheduleDraft, timezone: string) {- return describeCron(cronParts(draft), timezone);-}--type ParsedCron = Pick<- ScheduleDraft,- 'frequency' | 'time' | 'daysOfWeek' | 'dayOfMonth'->;--/**- * Read a cron expression into the parts an automation's picker edits.- *- * A pass-through: the shared parser only ever reports frequencies this picker- * can render, so there is nothing to adapt.- */-export function parseCron(cron: string): ParsedCron {- return parseCronParts(cron);-}--function buildCron(draft: ScheduleDraft) {- return buildCronExpression(cronParts(draft));-}--export function createEmptyDraft(): ScheduleDraft {- return {- name: '',- prompt: '',- frequency: 'week',- time: DEFAULT_TIME,- daysOfWeek: [...DEFAULT_WEEKDAYS],- dayOfMonth: '1',- target: { kind: 'model', model: DEFAULT_MODEL },- };-}+import { getCronTrigger } from './triggers';const agentTaskSchema = z.looseObject({@@ -140,8 +64,14 @@ export function draftFromSchedule(schedule: ScheduledAction): ScheduleDraft | undefined {const trigger = getCronTrigger(schedule);- if (!trigger) return undefined;- const parsed = parseCron(trigger.schedule);+ const sourceTrigger = schedule.trigger ?? trigger;+ const triggers = sourceTrigger+ ? parseRoutineTriggers(sourceTrigger)+ : undefined;+ if (!trigger && !triggers) return undefined;+ const parsed = trigger+ ? parseCron(trigger.schedule)+ : parseCron('0 0 9 * * *');const task = getAgentTask(schedule);if (!task) return undefined;@@ -154,6 +84,9 @@ export function draftFromSchedule(daysOfWeek: parsed.daysOfWeek,dayOfMonth: parsed.dayOfMonth,target: targetFromTask(task),+ timezone: trigger?.timezone,+ triggers,+ ...(trigger ? onceFromCron(trigger.schedule, trigger.timezone) : {}),};}@@ -183,14 +116,10 @@ function buildAgentTask(draft: ScheduleDraft): RoutineTask {export function draftToCreateBody(draft: ScheduleDraft): CreateScheduledAction {return {name: draft.name.trim() || deriveScheduleName(draft.prompt),- trigger: {- type: 'cron',- schedule: buildCron(draft),- timezone: getDefaultTimezone(),- },+ trigger: triggerFromDraft(draft),kind: 'Agent',task: buildAgentTask(draft),- enabled: true,+ enabled: draft.enabled ?? true,};}@@ -201,7 +130,8 @@ export function draftToUpdateBody(const trigger = getCronTrigger(previous);const previousTask = getAgentTask(previous);const target = routineTargetSchema.safeParse(draft.target);- if (!trigger || !previousTask || !target.success) return undefined;+ if ((!trigger && !draft.triggers) || !previousTask || !target.success)+ return undefined;const targetChanged = !routineTargetsEqual(target.data,@@ -217,9 +147,31 @@ export function draftToUpdateBody(}// Preserve API-written cron expressions and raw task data when not edited.+ if (draft.triggers)+ return {+ name:+ draft.name === previous.name+ ? previous.name+ : draft.name.trim() || 'Untitled',+ trigger:+ previous.trigger &&+ JSON.stringify(serializeTriggers(draft.triggers)) ===+ JSON.stringify(+ serializeTriggers(parseRoutineTriggers(previous.trigger) ?? [])+ )+ ? previous.trigger+ : serializeTriggers(draft.triggers),+ kind: previous.kind,+ task,+ };+ if (!trigger) return;const parsed = parseCron(trigger.schedule);const scheduleChanged =- draft.frequency !== parsed.frequency ||+ draft.frequency !==+ (onceFromCron(trigger.schedule, trigger.timezone)?.frequency ??+ parsed.frequency) ||+ draft.onceAt !== onceFromCron(trigger.schedule, trigger.timezone)?.onceAt ||+ (draft.timezone !== undefined && draft.timezone !== trigger.timezone) ||draft.time !== parsed.time ||draft.dayOfMonth !== parsed.dayOfMonth ||draft.daysOfWeek.join(',') !== parsed.daysOfWeek.join(',');@@ -229,7 +181,7 @@ export function draftToUpdateBody(? previous.name: draft.name.trim() || deriveScheduleName(draft.prompt),trigger: scheduleChanged- ? { ...trigger, schedule: buildCron(draft) }+ ? triggerFromDraft(draft, trigger.timezone): trigger,kind: previous.kind,task,@@ -239,7 +191,7 @@ export function draftToUpdateBody(export function scheduleToDuplicateBody(schedule: ScheduledAction): CreateScheduledAction | undefined {- const trigger = getCronTrigger(schedule);+ const trigger = schedule.trigger ?? getCronTrigger(schedule);if (!trigger) return undefined;return {enabled: schedule.enabled,@@ -250,26 +202,24 @@ export function scheduleToDuplicateBody(};}-export function formatDateTime(value: string | null | undefined) {- if (!value) return 'Never';-- const date = new Date(value);- if (Number.isNaN(date.getTime())) return 'Invalid date';-- return new Intl.DateTimeFormat(undefined, {- dateStyle: 'medium',- timeStyle: 'short',- }).format(date);-}--export function getErrorMessage(error: unknown) {- if (error instanceof ThrownResultError) {- return error.errors.map((item) => item.message).join(', ');- }-- if (error instanceof Error && error.message.length > 0) {- return error.message;+function triggerFromDraft(+ draft: ScheduleDraft,+ timezone = getDefaultTimezone()+) {+ if (draft.triggers) return serializeTriggers(draft.triggers);+ if (draft.frequency === 'once') {+ const date = new Date(draft.onceAt ?? '');+ if (Number.isNaN(date.getTime()))+ throw new Error('Choose a valid date and time.');+ return {+ type: 'cron' as const,+ timezone: 'UTC',+ schedule: `${date.getUTCSeconds()} ${date.getUTCMinutes()} ${date.getUTCHours()} ${date.getUTCDate()} ${date.getUTCMonth() + 1} * ${date.getUTCFullYear()}`,+ };}-- return 'Please try again.';+ return {+ type: 'cron' as const,+ timezone: draft.timezone ?? timezone,+ schedule: buildCron(draft),+ };}diff --git a/apps/web/src/features/routines/queries/routine-sources.ts b/apps/web/src/features/routines/queries/routine-sources.tsnew file mode 100644index 0000000000..2a6b60ba58--- /dev/null+++ b/apps/web/src/features/routines/queries/routine-sources.ts@@ -0,0 +1,152 @@+import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';+import type { Accessor } from 'solid-js';+import { createMemo, onMount } from 'solid-js';+import type {+ RoutineCreatorSource,+ RoutineDetailSource,+ RoutineListSource,+} from '../context/routine-sources';+import type { RoutineSnapshot } from '../core/routine';+import { scheduleToEntity } from './entities';+import {+ draftFromSchedule,+ draftToCreateBody,+ draftToUpdateBody,+ scheduleToDuplicateBody,+} from './routine-draft';+import { useRoutineQuery } from './routines';+import { toHistoryRecord } from './run-resource';+import {+ invalidateSchedules,+ useCreateScheduleMutation,+ useRunScheduleNowMutation,+ useScheduleHistoryQuery,+ useSchedulesQuery,+ useSetScheduleEnabledMutation,+ useUpdateScheduleMutation,+} from './schedules';++function toRoutine(schedule: ScheduledAction): RoutineSnapshot {+ if (!schedule.id) throw new Error('Routine has no ID');+ return {+ id: schedule.id,+ name: schedule.name,+ ownerId: schedule.owner,+ createdAt: schedule.created_at,+ enabled: schedule.enabled,+ nextRunAt: schedule.next_run_at,+ claimedAt: schedule.claimed,+ revision: schedule.configuration_revision,+ configurationKey: JSON.stringify([+ schedule.name,+ schedule.kind,+ schedule.trigger,+ schedule.task,+ ]),+ draft: draftFromSchedule(schedule),+ };+}++type DetailCallbacks = {+ onError(title: string, error: unknown): void;+ onDuplicated(id: string): void;+};++export function createRoutineDetailSource(+ id: Accessor<string>,+ callbacks: DetailCallbacks+): RoutineDetailSource {+ const list = useSchedulesQuery(() => true);+ const detail = useRoutineQuery(id);+ const raw = createMemo(+ () =>+ (detail.isSuccess || detail.isError ? detail.data : undefined) ??+ (list.isSuccess || list.isError+ ? list.data?.find((item) => item.id === id())+ : undefined)+ );+ const routine = createMemo(() => {+ const current = raw();+ return current?.id ? toRoutine(current) : undefined;+ });+ const update = useUpdateScheduleMutation();+ const run = useRunScheduleNowMutation({+ onError: (error) => callbacks.onError('Failed to start run', error),+ });+ const activate = useSetScheduleEnabledMutation({+ onError: (error) => callbacks.onError('Failed to update routine', error),+ });+ const duplicate = useCreateScheduleMutation({+ onSuccess: (created) => {+ if (created.id) callbacks.onDuplicated(created.id);+ },+ onError: (error) => callbacks.onError('Failed to duplicate routine', error),+ });+ const history = useScheduleHistoryQuery(id, () => Boolean(raw()));+ onMount(() => {+ void invalidateSchedules();+ });+ return {+ routine,+ entity: () => {+ const current = raw();+ return current ? scheduleToEntity(current) : undefined;+ },+ loading: () => detail.isPending,+ error: () => detail.isError,+ async update(draft) {+ const previous = raw();+ const body = previous && draftToUpdateBody(draft, previous);+ if (!body) throw new Error('Choose a valid execution target.');+ return toRoutine(await update.mutateAsync({ scheduleId: id(), body }));+ },+ run: () => run.mutate({ scheduleId: id() }),+ runPending: () => run.isPending,+ setEnabled: (enabled) => activate.mutate({ scheduleId: id(), enabled }),+ activationPending: () => activate.isPending,+ duplicate() {+ const current = raw();+ const body = current && scheduleToDuplicateBody(current);+ if (body && !duplicate.isPending) duplicate.mutate(body);+ },+ duplicationPending: () => duplicate.isPending,+ history: createMemo(() =>+ history.isSuccess ? (history.data ?? []).map(toHistoryRecord) : []+ ),+ historyLoading: () => history.isPending,+ historyError: () => history.isError,+ refreshHistory: () => history.refetch(),+ };+}++export function createRoutineCreatorSource(): RoutineCreatorSource {+ const mutation = useCreateScheduleMutation();+ return {+ pending: () => mutation.isPending,+ async create(draft) {+ const created = await mutation.mutateAsync(draftToCreateBody(draft));+ if (!created.id) throw new Error('Created routine has no ID');+ return created.id;+ },+ };+}++export function createRoutineListSource(+ onError: (error: unknown) => void+): RoutineListSource {+ const query = useSchedulesQuery(() => true);+ const toggle = useSetScheduleEnabledMutation({ onError });+ return {+ routines: createMemo(() =>+ (query.isSuccess || query.isError ? (query.data ?? []) : [])+ .filter((item) => item.id)+ .map(toRoutine)+ ),+ loading: () => query.isPending,+ error: () => query.isError,+ refresh: () => query.refetch(),+ pendingId: () =>+ toggle.isPending ? toggle.variables?.scheduleId : undefined,+ setEnabled: (id, enabled) => toggle.mutate({ scheduleId: id, enabled }),+ };+}diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.tsnew file mode 100644index 0000000000..5555bfd761--- /dev/null+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.test.ts@@ -0,0 +1,155 @@+import { describe, expect, it } from 'vitest';+import {+ newScheduleTrigger,+ routineEvents,+ routineTriggerSchema,+ validateTriggers,+} from '../core/routine-triggers';+import {+ parseRoutineTriggers,+ serializeTriggers,+} from './routine-trigger-mapping';++// Conversion must preserve independently authored schedules and API expressions.+describe('routine trigger mapping', () => {+ it.each(routineEvents)(+ 'round trips $value without confusing its scope',+ (event) => {+ const config = {+ type: 'events' as const,+ filters: [{ events: [event.value] }],+ };+ const triggers = parseRoutineTriggers(config)!;+ expect(routineTriggerSchema.safeParse(triggers[0]).success).toBe(true);+ expect(serializeTriggers(triggers)).toEqual(config);+ }+ );++ it('round trips multiple schedules with different time zones and Macro events', () => {+ const configuration = {+ type: 'multiple' as const,+ triggers: [+ {+ type: 'cron' as const,+ schedule: '0 30 9 * * *',+ timezone: 'America/New_York',+ },+ {+ type: 'cron' as const,+ schedule: '0 45 17 * * 2,6',+ timezone: 'Europe/London',+ },+ {+ type: 'events' as const,+ filters: [+ {+ events: ['channel.message_posted' as const],+ ids: ['01912345-1234-7123-8123-123456789abc'],+ },+ ],+ },+ ],+ };+ const triggers = parseRoutineTriggers(configuration)!;+ expect(triggers).toMatchObject([+ { kind: 'schedule', frequency: 'day', time: '09:30' },+ {+ kind: 'schedule',+ frequency: 'week',+ time: '17:45',+ daysOfWeek: ['2', '6'],+ },+ { kind: 'event', events: ['channel.message_posted'] },+ ]);+ expect(serializeTriggers(triggers)).toEqual(configuration);+ expect(validateTriggers(triggers)).toBeNull();+ });+ it.each([+ '15 */5 1-3 * JUN MON-FRI',+ '0 0 9 * * * 2040',+ '0 0 9 12 11 3 2040',+ ])('retains an arbitrary cron expression exactly: %s', (schedule) => {+ const config = { type: 'cron' as const, schedule, timezone: 'UTC' };+ const triggers = parseRoutineTriggers(config)!;+ expect(triggers[0]).toMatchObject({ frequency: 'custom' });+ expect(serializeTriggers(triggers)).toEqual(config);+ });+ it('restores a one-off instant as an editable local date', () => {+ const config = {+ type: 'cron' as const,+ schedule: '30 15 9 12 11 * 2040',+ timezone: 'UTC',+ };+ const triggers = parseRoutineTriggers(config)!;+ expect(triggers[0]).toMatchObject({ frequency: 'once' });+ expect(serializeTriggers(triggers)).toEqual(config);+ });++ it('preserves the full backend event-filter capacity and empty selectors', () => {+ const configuration = {+ type: 'events' as const,+ filters: Array.from({ length: 32 }, () => ({+ events: ['document.updated' as const],+ ids: [],+ })),+ };+ const triggers = parseRoutineTriggers(configuration)!;+ expect(validateTriggers(triggers)).toBeNull();+ expect(serializeTriggers(triggers)).toEqual(configuration);+ expect(validateTriggers([...triggers, triggers[0]])).toMatch(/32/);+ });+ it('requires valid configuration for every schedule', () => {+ const valid = newScheduleTrigger('day');+ expect(validateTriggers([])).toMatch(/Add a trigger/);+ expect(+ validateTriggers([valid, { ...valid, timezone: 'Invalid/Zone' }])+ ).toMatch(/time zone/);+ expect(+ validateTriggers([{ ...valid, frequency: 'week', daysOfWeek: [] }])+ ).toMatch(/day/);+ expect(+ validateTriggers(+ [{ ...valid, frequency: 'once', onceAt: '2000-01-01T09:00' }],+ true+ )+ ).toMatch(/future/);+ expect(validateTriggers(Array.from({ length: 17 }, () => valid))).toMatch(+ /16/+ );+ expect(+ validateTriggers(+ [+ {+ id: 'event',+ kind: 'event',+ events: ['channel.message_posted'],+ ids: [],+ },+ ],+ true+ )+ ).toMatch(/Choose at least one/);+ });+});++describe('completed routine classification', () => {+ it('recognizes exhausted multiple and custom schedules, but not Macro events', async () => {+ const { hasOnlyScheduledTriggers } = await import(+ '../core/routine-triggers'+ );+ expect(+ hasOnlyScheduledTriggers([+ newScheduleTrigger('once'),+ newScheduleTrigger('once'),+ ])+ ).toBe(true);+ expect(hasOnlyScheduledTriggers([newScheduleTrigger('custom')])).toBe(true);+ expect(+ hasOnlyScheduledTriggers([+ newScheduleTrigger('once'),+ { kind: 'event', id: 'event', events: ['document.created'] },+ ])+ ).toBe(false);+ expect(hasOnlyScheduledTriggers([])).toBe(false);+ });+});diff --git a/apps/web/src/features/routines/queries/routine-trigger-mapping.ts b/apps/web/src/features/routines/queries/routine-trigger-mapping.tsnew file mode 100644index 0000000000..5e331fdff8--- /dev/null+++ b/apps/web/src/features/routines/queries/routine-trigger-mapping.ts@@ -0,0 +1,122 @@+import { parseCron } from '@core/util/cron';+import { TZDate } from '@date-fns/tz';+import type { ActionTrigger } from '@service-scheduled-action/generated/schemas';+import { match } from 'ts-pattern';+import {+ newScheduleTrigger,+ type RoutineTriggerDraft,+} from '../core/routine-triggers';++export function serializeTrigger(trigger: RoutineTriggerDraft) {+ if (trigger.kind === 'event')+ return {+ type: 'events' as const,+ filters: [+ {+ events: trigger.events,+ ...(trigger.ids === undefined ? {} : { ids: trigger.ids }),+ },+ ],+ };+ const [hour, minute] = trigger.time.split(':').map(Number);+ if (trigger.frequency === 'once') {+ const date = new Date(trigger.onceAt);+ if (!Number.isFinite(date.getTime()))+ throw new Error('Choose a date and time.');+ return {+ type: 'cron' as const,+ timezone: 'UTC',+ schedule: `${date.getUTCSeconds()} ${date.getUTCMinutes()} ${date.getUTCHours()} ${date.getUTCDate()} ${date.getUTCMonth() + 1} * ${date.getUTCFullYear()}`,+ };+ }+ const schedule = match(trigger.frequency)+ .with('hour', () => '0 0 * * * *')+ .with('day', () => `0 ${minute} ${hour} * * *`)+ .with(+ 'week',+ () => `0 ${minute} ${hour} * * ${trigger.daysOfWeek.toSorted().join(',')}`+ )+ .with('month', () => `0 ${minute} ${hour} ${trigger.dayOfMonth} * *`)+ .with('custom', () => trigger.cron.trim())+ .exhaustive();+ return { type: 'cron' as const, schedule, timezone: trigger.timezone };+}+export function serializeTriggers(+ triggers: RoutineTriggerDraft[]+): ActionTrigger {+ const schedules = triggers+ .filter((trigger) => trigger.kind === 'schedule')+ .map(serializeTrigger);+ const filters = triggers.flatMap((trigger) =>+ trigger.kind === 'event'+ ? [+ {+ events: trigger.events,+ ...(trigger.ids === undefined ? {} : { ids: trigger.ids }),+ },+ ]+ : []+ );+ const values = [+ ...schedules,+ ...(filters.length ? [{ type: 'events' as const, filters }] : []),+ ];+ if (values.length === 1) return values[0];+ return { type: 'multiple', triggers: values };+}+export function parseRoutineTriggers(+ trigger: ActionTrigger+): RoutineTriggerDraft[] | undefined {+ const values = trigger.type === 'multiple' ? trigger.triggers : [trigger];+ if (+ !values.every((value) => value.type === 'cron' || value.type === 'events')+ )+ return undefined;+ return values.flatMap((value): RoutineTriggerDraft[] => {+ if (value.type === 'events')+ return value.filters.map((filter) => ({+ id: crypto.randomUUID(),+ kind: 'event',+ events: filter.events,+ ids: filter.ids ?? undefined,+ }));+ const draft = {+ ...newScheduleTrigger('custom'),+ timezone: value.timezone,+ cron: value.schedule,+ };+ const once = onceFromCron(value.schedule, value.timezone);+ if (once && value.schedule.split(/\s+/)[5] === '*')+ return [{ ...draft, ...once }];+ const parsed = parseCron(value.schedule);+ // Only use a visual preset when serializing it produces the exact schedule.+ // Arbitrary API-written expressions stay editable as cron without losing fields.+ for (const frequency of ['hour', 'day', 'week', 'month'] as const) {+ const candidate = { ...draft, ...parsed, frequency };+ const serialized = serializeTrigger(candidate);+ if (serialized.type === 'cron' && serialized.schedule === value.schedule)+ return [candidate];+ }+ return [draft];+ });+}+export function onceFromCron(+ cron: string,+ timezone = 'UTC'+): { frequency: 'once'; onceAt: string } | undefined {+ const parts = cron.trim().split(/\s+/);+ if (+ parts.length !== 7 ||+ !/^\d{4}$/.test(parts[6]) ||+ !parts.slice(0, 5).every((part) => /^\d+$/.test(part))+ )+ return;+ const [second, minute, hour, day, month, , year] = parts.map(Number);+ const date = new TZDate(year, month - 1, day, hour, minute, second, timezone);+ if (Number.isNaN(date.getTime())) return;+ const instant = new Date(date.getTime());+ const local = new Date(+ instant.getTime() - instant.getTimezoneOffset() * 60000+ );+ return { frequency: 'once', onceAt: local.toISOString().slice(0, 19) };+}diff --git a/apps/web/src/features/routines/queries/routines.ts b/apps/web/src/features/routines/queries/routines.tsnew file mode 100644index 0000000000..3249d363fc--- /dev/null+++ b/apps/web/src/features/routines/queries/routines.ts@@ -0,0 +1,13 @@+import { throwOnErr } from '@core/util/result';+import { scheduledActionClient } from '@service-scheduled-action/client';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { scheduledActionKeys } from './keys';++export function useRoutineQuery(id: Accessor<string>) {+ return useQuery(() => ({+ queryKey: scheduledActionKeys.detail({ scheduleId: id() }).queryKey,+ queryFn: () => throwOnErr(() => scheduledActionClient.getRoutine(id())),+ refetchOnWindowFocus: 'always',+ }));+}diff --git a/apps/web/src/lib/queries/agent-schedule/run-resource.test.ts b/apps/web/src/features/routines/queries/run-resource.test.tssimilarity index 100%rename from apps/web/src/lib/queries/agent-schedule/run-resource.test.tsrename to apps/web/src/features/routines/queries/run-resource.test.tsdiff --git a/apps/web/src/lib/queries/agent-schedule/run-resource.ts b/apps/web/src/features/routines/queries/run-resource.tssimilarity index 79%rename from apps/web/src/lib/queries/agent-schedule/run-resource.tsrename to apps/web/src/features/routines/queries/run-resource.tsindex 80c0b94f9c..2fe311c392 100644--- a/apps/web/src/lib/queries/agent-schedule/run-resource.ts+++ b/apps/web/src/features/routines/queries/run-resource.ts@@ -3,6 +3,7 @@ import type {ExecutionResult,} from '@service-scheduled-action/generated/schemas';import { z } from 'zod';+import type { HistoryRecord } from '../core/history';const resourceSchema = z.object({type: z.enum(['chat', 'agent']),@@ -56,3 +57,20 @@ export function resourcesMatch(): boolean {return left?.type === right.type && left.id === right.id;}++export function toHistoryRecord(record: {+ id?: string | null;+ result: unknown;+ resource_id?: string | null;+ start_time?: string | null;+ end_time?: string | null;+ is_success?: boolean | null;+}): HistoryRecord {+ return {+ id: record.id,+ resource: getHistoryResource(record),+ startedAt: record.start_time,+ endedAt: record.end_time,+ success: record.is_success,+ };+}diff --git a/apps/web/src/lib/queries/agent-schedule/schedules.test.tsx b/apps/web/src/features/routines/queries/schedules.test.tsxsimilarity index 81%rename from apps/web/src/lib/queries/agent-schedule/schedules.test.tsxrename to apps/web/src/features/routines/queries/schedules.test.tsxindex a449ddda07..f8be0cc3bb 100644--- a/apps/web/src/lib/queries/agent-schedule/schedules.test.tsx+++ b/apps/web/src/features/routines/queries/schedules.test.tsx@@ -100,6 +100,27 @@ describe('routine activation', () => {expect(schedules()).toEqual([saved, other]);});+ it('rolls back activation from a detail-only cache after an error', async () => {+ queryClient.removeQueries({ queryKey: scheduledActionKeys.list.queryKey });+ const detailKey = scheduledActionKeys.detail({+ scheduleId: 'routine',+ }).queryKey;+ queryClient.setQueryData(detailKey, routine);+ const respond = respondLater();+ const pausing = mountMutation().mutateAsync({+ scheduleId: 'routine',+ enabled: false,+ });+ await vi.waitFor(() =>+ expect(+ queryClient.getQueryData<ScheduledAction>(detailKey)?.enabled+ ).toBe(false)+ );+ respond(err([{ code: 'CONFLICT', message: 'Routine changed' }]));+ await expect(pausing).rejects.toThrow('Routine changed');+ expect(queryClient.getQueryData(detailKey)).toEqual(routine);+ });+it('restores only the activation it changed when saving fails', async () => {const respond = respondLater();const pausing = mountMutation().mutateAsync({diff --git a/apps/web/src/lib/queries/agent-schedule/schedules.ts b/apps/web/src/features/routines/queries/schedules.tssimilarity index 82%rename from apps/web/src/lib/queries/agent-schedule/schedules.tsrename to apps/web/src/features/routines/queries/schedules.tsindex 130d53ba6b..b8c76c7167 100644--- a/apps/web/src/lib/queries/agent-schedule/schedules.ts+++ b/apps/web/src/features/routines/queries/schedules.ts@@ -3,7 +3,6 @@ import { queryClient } from '@queries/client';import { type MutationCallbacks, withCallbacks } from '@queries/utils';import { scheduledActionClient } from '@service-scheduled-action/client';import type {- ActionExecutionRecord,CreateScheduledAction,InProgressExecution,ScheduledAction,@@ -19,6 +18,13 @@ const QUERY_REFETCH_BEHAVIOR = {};function upsertSchedule(schedule: ScheduledAction) {+ if (schedule.id)+ queryClient.setQueryData(+ scheduledActionKeys.detail({ scheduleId: schedule.id }).queryKey,+ (current: ScheduledAction | undefined) =>+ current ? { ...current, ...schedule } : undefined+ );+queryClient.setQueryData(scheduledActionKeys.list.queryKey,(current: ScheduledAction[] | undefined) => {@@ -43,6 +49,12 @@ function removeSchedule(scheduleId: string) {}function patchScheduleEnabled(scheduleId: string, enabled: boolean) {+ queryClient.setQueryData(+ scheduledActionKeys.detail({ scheduleId }).queryKey,+ (current: ScheduledAction | undefined) =>+ current ? { ...current, enabled } : undefined+ );+queryClient.setQueryData(scheduledActionKeys.list.queryKey,(current: ScheduledAction[] | undefined) =>@@ -83,16 +95,20 @@ export function useScheduleHistoryQuery(scheduleId: currentScheduleId!,})),- placeholderData: (prev: ActionExecutionRecord[] | undefined) => prev,...QUERY_REFETCH_BEHAVIOR,};});}export function invalidateSchedules() {- return queryClient.invalidateQueries({- queryKey: scheduledActionKeys.list.queryKey,- });+ return Promise.all([+ queryClient.invalidateQueries({+ queryKey: scheduledActionKeys.list.queryKey,+ }),+ queryClient.invalidateQueries({+ queryKey: scheduledActionKeys.detail._def,+ }),+ ]);}function _invalidateScheduleHistory(scheduleId: string) {@@ -172,12 +188,23 @@ export function useSetScheduleEnabledMutation(>({onMutate: async ({ scheduleId, enabled }) => {- await queryClient.cancelQueries({- queryKey: scheduledActionKeys.list.queryKey,- });- const previousEnabled = queryClient- .getQueryData<ScheduledAction[]>(scheduledActionKeys.list.queryKey)- ?.find((item) => item.id === scheduleId)?.enabled;+ await Promise.all([+ queryClient.cancelQueries({+ queryKey: scheduledActionKeys.list.queryKey,+ }),+ queryClient.cancelQueries({+ queryKey: scheduledActionKeys.detail({ scheduleId }).queryKey,+ }),+ ]);+ const previousEnabled =+ queryClient.getQueryData<ScheduledAction>(+ scheduledActionKeys.detail({ scheduleId }).queryKey+ )?.enabled ??+ queryClient+ .getQueryData<ScheduledAction[]>(+ scheduledActionKeys.list.queryKey+ )+ ?.find((item) => item.id === scheduleId)?.enabled;patchScheduleEnabled(scheduleId, enabled);return { previousEnabled };},@@ -231,7 +258,7 @@ export function useRunScheduleNowMutation(>) {// History and claimed-state updates now arrive via the scheduled-action- // websocket sync (src/lib/queries/agent-schedule/sync.ts). Invalidating on+ // websocket sync (features/routines/queries/sync.ts). Invalidating on// HTTP success would race the synthetic pending row from the `started`// event and wipe it before the server persists the real record — so the// success path is intentionally a no-op here.diff --git a/apps/web/src/lib/queries/agent-schedule/sync.test.ts b/apps/web/src/features/routines/queries/sync.test.tssimilarity index 92%rename from apps/web/src/lib/queries/agent-schedule/sync.test.tsrename to apps/web/src/features/routines/queries/sync.test.tsindex 605089911a..3c7263c8fe 100644--- a/apps/web/src/lib/queries/agent-schedule/sync.test.ts+++ b/apps/web/src/features/routines/queries/sync.test.ts@@ -37,6 +37,9 @@ const schedule: ScheduledAction = {const historyKey = scheduledActionKeys.history({scheduleId: 'routine',}).queryKey;+const detailKey = scheduledActionKeys.detail({+ scheduleId: 'routine',+}).queryKey;const chat = { type: 'chat', id: 'same-id' } as const;const agent = { type: 'agent', id: 'same-id' } as const;@@ -69,6 +72,7 @@ beforeEach(() => {queryClient.clear();vi.useFakeTimers();vi.setSystemTime(new Date('2026-09-28T12:00:00Z'));+ queryClient.setQueryData(detailKey, schedule);queryClient.setQueryData(scheduledActionKeys.list.queryKey, [schedule,{ ...schedule, id: 'other' },@@ -90,6 +94,9 @@ describe('scheduled-action websocket synchronization', () => {const resource = fields.resource ?? chat;send(JSON.stringify(update('started', fields)));expect(schedules()?.[0].claimed).toBe('2026-09-28T12:00:00.000Z');+ expect(queryClient.getQueryData<ScheduledAction>(detailKey)?.claimed).toBe(+ '2026-09-28T12:00:00.000Z'+ );expect(schedules()?.[1]).toEqual({ ...schedule, id: 'other' });expect(history()).toEqual([{@@ -108,7 +115,15 @@ describe('scheduled-action websocket synchronization', () => {send(update('stopped', fields));expect(history()).toEqual([]);expect(schedules()?.[0].claimed).toBeUndefined();- expect(invalidate).toHaveBeenCalledTimes(2);+ expect(+ queryClient.getQueryData<ScheduledAction>(detailKey)?.claimed+ ).toBeNull();+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: scheduledActionKeys.list.queryKey,+ });+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: scheduledActionKeys.detail({ scheduleId: 'routine' }).queryKey,+ });expect(invalidate).toHaveBeenCalledWith({ queryKey: historyKey });});diff --git a/apps/web/src/lib/queries/agent-schedule/sync.ts b/apps/web/src/features/routines/queries/sync.tssimilarity index 90%rename from apps/web/src/lib/queries/agent-schedule/sync.tsrename to apps/web/src/features/routines/queries/sync.tsindex d6b9b56f8e..fda35a86d7 100644--- a/apps/web/src/lib/queries/agent-schedule/sync.ts+++ b/apps/web/src/features/routines/queries/sync.ts@@ -49,6 +49,12 @@ function parsePayload(data: unknown): UpdatePayload | undefined {}function patchClaimed(actionId: string, claimed: string | null): void {+ queryClient.setQueryData(+ scheduledActionKeys.detail({ scheduleId: actionId }).queryKey,+ (current: ScheduledAction | undefined) =>+ current ? { ...current, claimed } : undefined+ );+queryClient.setQueryData(scheduledActionKeys.list.queryKey,(current: ScheduledAction[] | undefined) => {@@ -126,6 +132,13 @@ createConnectionWebsocketEffect((data) => {return;}+ void queryClient.invalidateQueries({+ queryKey: scheduledActionKeys.detail({ scheduleId: payload.action_id })+ .queryKey,+ });+ void queryClient.invalidateQueries({+ queryKey: scheduledActionKeys.list.queryKey,+ });// stopped: drop the synthetic pending row immediately so the UI stops// showing it as running, then invalidate to refetch the server-persisted// record (with end_time, is_success, and a real id).diff --git a/apps/web/src/lib/queries/agent-schedule/triggers.ts b/apps/web/src/features/routines/queries/triggers.tssimilarity index 100%rename from apps/web/src/lib/queries/agent-schedule/triggers.tsrename to apps/web/src/features/routines/queries/triggers.tsdiff --git a/apps/web/src/features/routines/route-views.tsx b/apps/web/src/features/routines/route-views.tsxnew file mode 100644index 0000000000..b7766ce24d--- /dev/null+++ b/apps/web/src/features/routines/route-views.tsx@@ -0,0 +1,19 @@+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { withAuth } from '@components/app/split-layout/split-router/app-route-shell';+import { onMount } from 'solid-js';+import { routineContent } from './routine-navigation';++export const RoutineCreateRouteView = withAuth(() => {+ const layout = useSplitLayout();+ const panel = useSplitPanelOrThrow();+ onMount(() => {+ layout.openWithSplit(routineContent(), {+ handle: panel.handle,+ mergeHistory: true,+ search: {},+ });+ layout.popoverSplit({ type: 'component', id: 'routine-compose' });+ });+ return null;+});diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsxnew file mode 100644index 0000000000..e13b92bb0f--- /dev/null+++ b/apps/web/src/features/routines/routine-creator.test.tsx@@ -0,0 +1,611 @@+import type {+ CreateScheduledAction,+ ScheduledAction,+} from '@service-scheduled-action/generated/schemas';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { createSignal, type JSX } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { buildAgentRoster } from '../agents-view/core/roster';+import { getDefaultTimezone } from './core/routine-draft';+import { loadRoutineComposerDraft } from './draft-storage';+import { onceFromCron } from './queries/routine-trigger-mapping';+import { RoutineCreator } from './routine-creator';++const host = vi.hoisted(() => ({+ create: vi.fn<(body: CreateScheduledAction) => Promise<ScheduledAction>>(),+ openWithSplit: vi.fn(),+ created: vi.fn(),+ success: vi.fn(),+ alert: vi.fn(),+ editorMount: vi.fn(),+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ openWithSplit: host.openWithSplit }),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({ handle: { close: vi.fn() } }),+}));+vi.mock('./routine-event-scope', () => ({+ RoutineEventScope: () => <span>Any document</span>,+ RoutineEventScopeLabel: () => <span>Any document</span>,+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: host.success, alert: host.alert },+}));+vi.mock('@core/constant/SettingsState', () => ({+ useSettingsState: () => ({ openSettings: vi.fn() }),+}));+vi.mock('../agents-view/primitives/open-page', () => ({+ openAgentsPage: vi.fn(),+}));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@core/mobile/virtualKeyboard', () => ({+ virtualKeyboardVisible: () => false,+}));+vi.mock('@core/constant/allBlocks', () => ({+ blockNameToDefaultFile: () => 'New routine',+}));+vi.mock('./queries/schedules', async () => {+ const { useMutation } = await import('@tanstack/solid-query');+ return {+ useCreateScheduleMutation: (callbacks: {+ onSuccess: (schedule: ScheduledAction) => Promise<void>;+ onError: (error: Error) => void;+ }) => useMutation(() => ({ mutationFn: host.create, ...callbacks })),+ };+});++// Keep the real trigger menu, picker, model discovery adapter, storage, and mutation+// lifecycle. The editor double exposes initialValue and detects any remount.+vi.mock('./routine-prompt-editor', () => ({+ RoutinePromptEditor: (props: {+ initialValue: string;+ onChange: (value: string) => void;+ }): JSX.Element => {+ host.editorMount();+ const initialValue = props.initialValue;+ return (+ <textarea+ aria-label="Instructions"+ value={initialValue}+ onInput={(event) => props.onChange(event.currentTarget.value)}+ />+ );+ },+}));++const agentId = '12345678-1234-1234-1234-123456789abc';+const [catalogState, setCatalogState] = createSignal<+ 'pending' | 'success' | 'error'+>('success');+vi.mock('../agents-view/queries/agent-roster-source', () => ({+ createAgentRosterSource: () => ({+ roster: () =>+ buildAgentRoster({+ agents: [+ {+ bot: { id: agentId, name: 'Researcher', handle: 'researcher' },+ harness: 'in-memory',+ default_model: 'claude-sonnet-4-6',+ },+ ],+ runtimes: [],+ cursorConnected: false,+ cursorNeedsConnection: true,+ }),+ loading: () => false,+ error: () => false,+ availabilityLoading: () => false,+ }),+}));+vi.mock('@queries/agents/models', () => ({+ useAgentModelsQuery: () => ({+ get isSuccess() {+ return catalogState() === 'success';+ },+ get isPending() {+ return catalogState() === 'pending';+ },+ get isError() {+ return catalogState() === 'error';+ },+ get data() {+ if (catalogState() !== 'success') throw new Error('Unsafe catalog read');+ return {+ status: 'available',+ models: [+ { id: 'claude-sonnet-4-6', name: 'Sonnet' },+ { id: 'vendor/custom-model', name: 'Custom model' },+ ],+ };+ },+ }),+}));++let styles: HTMLStyleElement;+beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ setCatalogState('success');+ styles = document.createElement('style');+ styles.textContent = '* { animation-name: none; transition-duration: 0s; }';+ document.head.append(styles);+ vi.stubGlobal('scrollTo', vi.fn());+});+afterEach(() => {+ cleanup();+ styles.remove();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++async function mount(): Promise<void> {+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ render(() => (+ <QueryClientProvider client={client}>+ <RoutineCreator onCreated={host.created} />+ </QueryClientProvider>+ ));+ await screen.findByRole('textbox', { name: 'Routine name' });+}++function inputPrompt(value = 'Summarize updates'): HTMLTextAreaElement {+ const editor = screen.getByRole<HTMLTextAreaElement>('textbox', {+ name: 'Instructions',+ });+ fireEvent.input(editor, { target: { value } });+ return editor;+}++function openPicker(): void {+ const trigger = screen.getByRole('button', { name: 'Agent' });+ trigger.focus();+ fireEvent.keyDown(trigger, { key: 'Enter' });+}++async function selectTarget(+ target: 'model' | 'agent' | 'override'+): Promise<void> {+ openPicker();+ if (target === 'agent') {+ fireEvent.click(screen.getByRole('menuitem', { name: /^Researcher/ }));+ } else {+ let menu: HTMLElement | undefined;+ if (target === 'override') {+ const row = screen.getByRole('menuitem', { name: /^Researcher/ });+ row.focus();+ fireEvent.keyDown(row, { key: 'ArrowRight' });+ // Do not select the same model from the root Macro catalog.+ menu = await screen.findByRole('menu', { name: /^Researcher/ });+ await within(menu).findByRole('textbox', { name: 'Search models' });+ }+ const item = (menu ? within(menu) : screen).getByRole('menuitem', {+ name: 'Custom model',+ });+ item.focus();+ fireEvent.keyDown(item, { key: 'Enter' });+ }+ await waitFor(() =>+ expect(+ screen+ .getByRole('button', { name: 'Agent' })+ .getAttribute('aria-expanded')+ ).toBe('false')+ );+}++function create(): void {+ fireEvent.click(screen.getByRole('button', { name: 'Create routine' }));+}+async function addScheduled(name = 'Daily') {+ const add = screen.getByRole('button', { name: 'Add trigger' });+ fireEvent.click(add);+ fireEvent.click(await screen.findByRole('button', { name: 'Scheduled' }));+ fireEvent.click(await screen.findByRole('button', { name }));+ fireEvent.click(+ within(screen.getByRole('dialog', { name: 'Add trigger' })).getByRole(+ 'button',+ { name: 'Add trigger' }+ )+ );+ await waitFor(() => expect(add.getAttribute('aria-expanded')).toBe('false'));+}+async function addDocumentEvent() {+ const add = screen.getByRole('button', { name: 'Add trigger' });+ fireEvent.click(add);+ fireEvent.click(+ await screen.findByRole('button', { name: 'Document created' })+ );+ fireEvent.click(+ within(screen.getByRole('dialog', { name: 'Add trigger' })).getByRole(+ 'button',+ { name: 'Add trigger' }+ )+ );+ await waitFor(() => expect(add.getAttribute('aria-expanded')).toBe('false'));+}++function created(body: CreateScheduledAction): ScheduledAction {+ if (!('trigger' in body)) throw new Error('Expected a tagged trigger');+ return {+ ...body,+ id: 'new-routine',+ owner: 'macro|[email protected]',+ created_at: '2026-09-28T00:00:00Z',+ updated_at: '2026-09-28T00:00:00Z',+ configuration_revision: 1,+ };+}++describe('routine composer execution selection', () => {+ it.each(['model', 'agent', 'override'] as const)(+ 'submits a %s target with unchanged cron and timezone behavior',+ async (target) => {+ host.create.mockImplementation(async (body) => created(body));+ await mount();+ inputPrompt(' Summarize updates ');+ await addScheduled();+ await selectTarget(target);+ create();+ await waitFor(() => expect(host.create).toHaveBeenCalledOnce());+ const body = host.create.mock.calls[0][0];+ const expectedTask: Record<string, unknown> = {+ prompt: '',+ user_prompt: 'Summarize updates',+ };+ if (target === 'model') expectedTask.model = 'vendor/custom-model';+ else expectedTask.agent = { bot_id: agentId };+ if (target === 'override') expectedTask.model = 'vendor/custom-model';+ expect(body.task).toEqual(expectedTask);+ expect(body).toMatchObject({+ trigger: {+ type: 'cron',+ schedule: '0 0 9 * * *',+ timezone: getDefaultTimezone(),+ },+ });+ await waitFor(() =>+ expect(host.created).toHaveBeenCalledWith('new-routine')+ );+ expect(body.enabled).toBe(true);+ }+ );++ it('restores the latest selection and prompt even when closed before the save timer', async () => {+ await mount();+ inputPrompt();+ await selectTarget('override');+ vi.useFakeTimers();+ inputPrompt('Last keystroke');+ cleanup();+ expect(loadRoutineComposerDraft()).toMatchObject({+ prompt: 'Last keystroke',+ target: { kind: 'agent', agentId, modelOverride: 'vendor/custom-model' },+ });+ await mount();+ expect(+ screen.getByRole<HTMLTextAreaElement>('textbox', { name: 'Instructions' })+ .value+ ).toBe('Last keystroke');+ expect(screen.getByRole('button', { name: 'Agent' }).textContent).toContain(+ 'Researcher'+ );+ vi.advanceTimersByTime(500);+ expect(loadRoutineComposerDraft()?.target).toEqual({+ kind: 'agent',+ agentId,+ modelOverride: 'vendor/custom-model',+ });+ });++ it('retains the draft after an API selection error and allows retry', async () => {+ host.create.mockRejectedValueOnce(+ new Error('The selected agent is unavailable.')+ );+ host.create.mockImplementation(async (body) => created(body));+ await mount();+ const editor = inputPrompt();+ await addScheduled();+ await selectTarget('agent');+ create();+ expect((await screen.findByRole('alert')).textContent).toBe(+ 'The selected agent is unavailable.'+ );+ expect(host.created).not.toHaveBeenCalled();+ await screen.findByRole('button', { name: 'Create routine' });+ expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);+ cleanup();+ expect(loadRoutineComposerDraft()?.target).toEqual({+ kind: 'agent',+ agentId,+ });+ await mount();+ create();+ await waitFor(() => expect(host.create).toHaveBeenCalledTimes(2));+ expect(host.create.mock.calls[1][0]).toEqual(host.create.mock.calls[0][0]);+ await waitFor(() =>+ expect(host.created).toHaveBeenCalledWith('new-routine')+ );+ });++ it('locks selection and submission while creating and cancels queued saves on success', async () => {+ let resolveCreate!: (value: ScheduledAction) => void;+ host.create.mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveCreate = resolve;+ })+ );+ await mount();+ await selectTarget('agent');+ await addScheduled();+ vi.useFakeTimers();+ inputPrompt();+ create();+ await vi.advanceTimersByTimeAsync(0);+ const picker = screen.getByRole('button', { name: 'Agent' });+ expect(picker.closest('fieldset')?.disabled).toBe(true);+ expect(+ screen.getByRole<HTMLButtonElement>('button', { name: 'Creating…' })+ .disabled+ ).toBe(true);+ fireEvent.click(screen.getByRole('button', { name: 'Creating…' }));+ expect(host.create).toHaveBeenCalledOnce();+ resolveCreate(created(host.create.mock.calls[0][0]));+ await vi.advanceTimersByTimeAsync(0);+ expect(host.created).toHaveBeenCalledWith('new-routine');+ expect(loadRoutineComposerDraft()).toBeNull();+ await vi.advanceTimersByTimeAsync(1000);+ expect(loadRoutineComposerDraft()).toBeNull();+ cleanup();+ await mount();+ expect(+ screen.getByRole<HTMLTextAreaElement>('textbox', { name: 'Instructions' })+ .value+ ).toBe('');+ });++ it('does not remount the prompt editor when targets or catalog status change', async () => {+ await mount();+ const editor = inputPrompt();+ await selectTarget('agent');+ setCatalogState('pending');+ expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);+ setCatalogState('error');+ expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);+ setCatalogState('success');+ await selectTarget('override');+ await selectTarget('model');+ expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);+ expect(editor.value).toBe('Summarize updates');+ expect(host.editorMount).toHaveBeenCalledOnce();+ });++ it('requires instructions and at least one trigger, with no history in creation', async () => {+ await mount();+ create();+ expect(screen.getByText('Instructions are required.')).toBeTruthy();+ inputPrompt();+ create();+ expect(+ screen.getByText('Add a trigger to tell this routine when to run.')+ ).toBeTruthy();+ expect(screen.queryByRole('tab', { name: 'Run History' })).toBeNull();+ expect(host.create).not.toHaveBeenCalled();+ });+ it('creates recurring schedules and Macro events together', async () => {+ host.create.mockImplementation(async (body) => created(body));+ await mount();+ inputPrompt();+ await addScheduled('Daily');+ await addScheduled('Weekly');+ await addDocumentEvent();+ create();+ await waitFor(() => expect(host.create).toHaveBeenCalledOnce());+ expect(host.create.mock.calls[0][0]).toMatchObject({+ enabled: true,+ trigger: {+ type: 'multiple',+ triggers: [+ {+ type: 'cron',+ schedule: '0 0 9 * * *',+ timezone: getDefaultTimezone(),+ },+ {+ type: 'cron',+ schedule: '0 0 9 * * 2',+ timezone: getDefaultTimezone(),+ },+ { type: 'events', filters: [{ events: ['document.created'] }] },+ ],+ },+ });+ });+ it('offers the focused Macro event catalog and saves new task and email triggers', async () => {+ host.create.mockImplementation(async (body) => created(body));+ await mount();+ inputPrompt();+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));+ for (const name of ['Channels', 'Documents', 'Tasks', 'Email']) {+ expect(await screen.findByText(name)).toBeTruthy();+ }+ for (const name of [+ 'Scheduled',+ 'Run once',+ 'Channel created',+ 'Message sent in channel',+ '@ mentioned in channel',+ 'Document created',+ 'Document deleted',+ 'Task created',+ 'Status changed',+ 'Priority changed',+ 'Any property changed',+ 'New email received',+ ]) {+ expect(screen.getByRole('button', { name })).toBeTruthy();+ }+ for (const name of [+ 'Document details changed',+ 'Message edited',+ 'Attachment added',+ ]) {+ expect(screen.queryByRole('button', { name })).toBeNull();+ }+ fireEvent.click(screen.getByRole('button', { name: 'Task created' }));+ fireEvent.click(+ within(screen.getByRole('dialog', { name: 'Add trigger' })).getByRole(+ 'button',+ { name: 'Add trigger' }+ )+ );+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));+ fireEvent.click(screen.getByRole('button', { name: 'New email received' }));+ fireEvent.click(+ within(screen.getByRole('dialog', { name: 'Add trigger' })).getByRole(+ 'button',+ { name: 'Add trigger' }+ )+ );+ fireEvent.click(screen.getByRole('button', { name: /Create routine/i }));+ await waitFor(() => expect(host.create).toHaveBeenCalledTimes(1));+ expect(host.create.mock.calls[0][0]).toMatchObject({+ trigger: {+ type: 'events',+ filters: [+ { events: ['task.created'] },+ { events: ['email.message_received'] },+ ],+ },+ });+ });++ it('keeps trigger edits local until confirmed and leaves an add chip', async () => {+ await mount();+ const editor = inputPrompt();+ await addScheduled();+ fireEvent.click(screen.getByRole('button', { name: /^Edit Every day,/ }));+ fireEvent.input(screen.getByRole('textbox', { name: 'Run time' }), {+ target: { value: '3:30pm' },+ });+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(+ screen.getByRole('button', { name: 'Edit Every day, 9:00 AM trigger' })+ ).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /^Edit Every day,/ }));+ fireEvent.input(screen.getByRole('textbox', { name: 'Run time' }), {+ target: { value: '3:30pm' },+ });+ fireEvent.click(screen.getByRole('button', { name: 'Done' }));+ expect(+ screen.getByRole('button', { name: 'Edit Every day, 3:30 PM trigger' })+ ).toBeTruthy();+ expect(screen.getAllByRole('button', { name: 'Add trigger' })).toHaveLength(+ 1+ );+ expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);+ expect(host.editorMount).toHaveBeenCalledOnce();+ });++ it('creates a one-off routine from a relative date phrase', async () => {+ host.create.mockImplementation(async (body) => created(body));+ await mount();+ inputPrompt();+ const before = Date.now();+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));+ fireEvent.click(screen.getByRole('button', { name: 'Run once' }));+ const date = screen.getByRole('textbox', { name: 'Run once date' });+ fireEvent.input(date, { target: { value: 'in 2 hours' } });+ fireEvent.keyDown(date, { key: 'Enter' });+ fireEvent.click(+ within(screen.getByRole('dialog', { name: 'Add trigger' })).getByRole(+ 'button',+ { name: 'Add trigger' }+ )+ );+ expect(screen.queryByRole('dialog')).toBeNull();+ create();+ await waitFor(() => expect(host.create).toHaveBeenCalledOnce());+ const body = host.create.mock.calls[0][0];+ if (!('trigger' in body)) throw new Error('Expected a tagged trigger');+ const trigger = body.trigger;+ expect(trigger.type).toBe('cron');+ if (trigger.type !== 'cron') throw new Error('Expected one-off cron');+ const at = onceFromCron(trigger.schedule, trigger.timezone)?.onceAt;+ expect(at).toBeDefined();+ const scheduled = new Date(at!).getTime();+ expect(scheduled).toBeGreaterThanOrEqual(+ before + 2 * 60 * 60 * 1000 - 1000+ );+ expect(scheduled).toBeLessThanOrEqual(Date.now() + 2 * 60 * 60 * 1000);+ });++ it('configures one-off dates and the calendar in the same panel', async () => {+ await mount();+ inputPrompt();+ fireEvent.click(screen.getByRole('button', { name: 'Add trigger' }));+ fireEvent.click(screen.getByRole('button', { name: 'Run once' }));+ const panel = screen.getByRole('dialog', { name: 'Add trigger' });+ const confirm = () =>+ within(panel).getByRole('button', { name: 'Add trigger' });+ fireEvent.click(confirm());+ expect(within(panel).getByRole('alert').textContent).toMatch(+ /Choose a date/+ );+ fireEvent.click(+ screen.getByRole('button', { name: 'Custom date and time…' })+ );+ expect(screen.getAllByRole('dialog')).toHaveLength(1);+ expect(screen.getByRole('dialog', { name: 'Add trigger' })).toBe(panel);+ fireEvent.click(+ screen.getByRole('button', { name: 'Type a date instead' })+ );+ fireEvent.input(screen.getByRole('textbox', { name: 'Run once date' }), {+ target: { value: 'tomorrow 10am' },+ });+ fireEvent.click(screen.getByRole('button', { name: /^Tomorrow/ }));+ fireEvent.click(confirm());+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(+ screen.getByRole('button', { name: /Edit .*10:00 AM trigger/ })+ ).toBeTruthy();+ cleanup();+ expect(loadRoutineComposerDraft()?.triggers).toMatchObject([+ { kind: 'schedule', frequency: 'once', onceAt: expect.any(String) },+ ]);+ const trigger = loadRoutineComposerDraft()?.triggers?.[0];+ if (trigger?.kind !== 'schedule') throw new Error('Expected one-off');+ const date = new Date(trigger.onceAt);+ expect(date.getTime()).toBeGreaterThan(Date.now());+ expect(date.getHours()).toBe(10);+ });++ it('removes one trigger and restores the others after closing', async () => {+ await mount();+ inputPrompt();+ await addScheduled('Daily');+ await addDocumentEvent();+ fireEvent.click(screen.getByRole('button', { name: /^Edit Every day,/ }));+ fireEvent.click(screen.getByRole('button', { name: 'Remove trigger' }));+ cleanup();+ await mount();+ expect(+ screen.getByRole('button', { name: 'Edit Document created trigger' })+ ).toBeTruthy();+ expect(loadRoutineComposerDraft()?.triggers).toMatchObject([+ { kind: 'event', events: ['document.created'] },+ ]);+ });+});diff --git a/apps/web/src/features/routines/routine-creator.tsx b/apps/web/src/features/routines/routine-creator.tsxnew file mode 100644index 0000000000..45d86bb395--- /dev/null+++ b/apps/web/src/features/routines/routine-creator.tsx@@ -0,0 +1,45 @@+import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { DEFAULT_MODEL } from '@core/component/AI/constant';+import {+ clearRoutineComposerDraft,+ loadRoutineComposerDraft,+ saveRoutineComposerDraft,+} from './draft-storage';+import { createRoutineCreatorSource } from './queries/routine-sources';+import { RoutineExecutionPicker } from './routine-execution-picker';+import { RoutinePromptEditor } from './routine-prompt-editor';+import { RoutineTriggers } from './routine-triggers';+import { RoutineCreatorView } from './views/routine-creator';++/** Production composition for the shared task/project creation popover. */+export function RoutineCreator(+ props: { onCreated?: (id: string) => void } = {}+) {+ const panel = useSplitPanelOrThrow();+ const layout = useSplitLayout();+ const source = createRoutineCreatorSource();+ return (+ <RoutineCreatorView+ source={source}+ defaultModel={DEFAULT_MODEL}+ storage={{+ load: loadRoutineComposerDraft,+ save: saveRoutineComposerDraft,+ clear: clearRoutineComposerDraft,+ }}+ slots={{+ PromptEditor: RoutinePromptEditor,+ ExecutionPicker: RoutineExecutionPicker,+ Triggers: RoutineTriggers,+ }}+ onClose={() => panel.handle.close()}+ onCreated={(id) => {+ panel.handle.close();+ if (props.onCreated) props.onCreated(id);+ else openAgentsPage(layout, 'routines', { routineId: id });+ }}+ />+ );+}diff --git a/apps/web/src/features/block-automation/component/Automation.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsxsimilarity index 65%rename from apps/web/src/features/block-automation/component/Automation.test.tsxrename to apps/web/src/features/routines/routine-detail.test.tsxindex 4556c95c5d..c2e9a41b02 100644--- a/apps/web/src/features/block-automation/component/Automation.test.tsx+++ b/apps/web/src/features/routines/routine-detail.test.tsx@@ -1,10 +1,26 @@+import { toast } from '@core/component/Toast/Toast';import type { ScheduledAction } from '@service-scheduled-action/generated/schemas';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';import { createSignal, type JSX, type Setter } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { RoutineTarget } from '../core/routine-target';-import type { HistoryRecord } from '../views/routine-history';-import { Automation } from './Automation';+import type { RoutineTarget } from './core/routine-target';+import { Routine } from './routine-detail';+import type { HistoryRecord } from './views/routine-history';++vi.mock('@app/lib/split-router', () => ({+ createSearchParamsCodec: () => ({}),+ createSearchParams: () => {+ const [tab, setTab] = createSignal<'settings' | 'history'>('settings');+ return [+ {+ get tab() {+ return tab();+ },+ },+ (next: { tab: 'settings' | 'history' }) => setTab(next.tab),+ ];+ },+}));const mocks = vi.hoisted(() => ({readSchedules: (): ScheduledAction[] => [],@@ -23,6 +39,7 @@ const mocks = vi.hoisted(() => ({create: vi.fn(),run: vi.fn(),setEnabled: vi.fn(),+ writeClipboardData: vi.fn(),activationPending: (): boolean => false,openWithSplit: vi.fn(),setDisplayName: vi.fn(),@@ -31,18 +48,56 @@ const mocks = vi.hoisted(() => ({rename: (_value: string): void => {},duplicate: (): void => {},}));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('./queries/routines', () => ({+ useRoutineQuery: () => ({+ get isSuccess() {+ return mocks.status() === 'success';+ },+ get isError() {+ return mocks.status() === 'error';+ },+ get isPending() {+ return mocks.status() === 'pending';+ },+ get data() {+ return mocks.readSchedules()[0];+ },+ }),+}));+vi.mock('./routine-triggers', () => ({+ RoutineTriggers: () => <div>Triggers</div>,+}));vi.mock('@core/block', () => ({ useBlockId: () => 'routine-id' }));vi.mock('@core/component/AI/constant', () => ({DEFAULT_MODEL: 'claude-sonnet-4-6',}));vi.mock('@core/constant/allBlocks', () => ({- blockNameToDefaultFile: () => 'New automation',+ blockNameToDefaultFile: () => 'New routine',}));vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));vi.mock('@core/component/Toast/Toast', () => ({toast: { alert: vi.fn(), success: vi.fn() },}));-vi.mock('@entity', () => ({ formatDateAndTime: (value: string) => value }));+vi.mock('@core/util/dataTransfer', () => ({+ writeClipboardData: mocks.writeClipboardData,+}));+vi.mock('@entity', () => ({+ formatDateAndTime: (value: string) => value,+ ListLayoutProvider: (props: { children: JSX.Element }) => props.children,+ ListEntity: (props: {+ entity: { name: string };+ leadingAction: JSX.Element;+ onClick: JSX.EventHandler<HTMLButtonElement, MouseEvent>;+ }) => (+ <button onClick={props.onClick}>+ {props.entity.name}+ {props.leadingAction}+ </button>+ ),+}));vi.mock('@app/features/entity/bulk-edit/BulkEditEntityModal', () => ({openBulkEditModal: vi.fn(),}));@@ -72,20 +127,20 @@ vi.mock('@components/app/split-layout/components/SplitFileMenu', () => ({BlockSplitFileMenu: (props: {tools: { label: string; action: () => void }[];}) => {- mocks.duplicate = props.tools.find(- (tool) => tool.label === 'Duplicate'- )!.action;- return <button onClick={mocks.duplicate}>Duplicate</button>;- },-}));-vi.mock('./AutomationRenameModal', () => ({- AutomationRenameModal: (props: { onRename: (value: string) => void }) => {- mocks.rename = props.onRename;- return null;+ mocks.duplicate =+ props.tools.find((tool) => tool.label === 'Duplicate')?.action ??+ (() => {});+ return (+ <>+ {props.tools.some((tool) => tool.label === 'Duplicate') && (+ <button onClick={mocks.duplicate}>Duplicate</button>+ )}+ </>+ );},}));-vi.mock('./AutomationPromptEditor', () => ({- AutomationPromptEditor: (props: {+vi.mock('./routine-prompt-editor', () => ({+ RoutinePromptEditor: (props: {initialValue: string;onChange: (value: string) => void;}) => {@@ -99,7 +154,7 @@ vi.mock('./AutomationPromptEditor', () => ({);},}));-vi.mock('../routine-execution-picker', () => ({+vi.mock('./routine-execution-picker', () => ({RoutineExecutionPicker: (props: {target: RoutineTarget;onChange: (target: RoutineTarget) => void;@@ -112,27 +167,12 @@ vi.mock('../routine-execution-picker', () => ({);},}));-vi.mock('./AutomationTimePicker', () => ({ AutomationTimePicker: () => null }));-vi.mock('@ui', () => ({+vi.mock('@ui', async () => ({+ ...(await vi.importActual('@ui')),Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (<button {...props} />),cn: (...classes: string[]) => classes.join(' '),- ToggleSwitch: (props: {- label: string;- checked: boolean;- disabled?: boolean;- onChange: (checked: boolean) => void;- }) => (- <button- type="button"- role="switch"- aria-label={props.label}- aria-checked={props.checked}- disabled={props.disabled}- onClick={() => props.onChange(!props.checked)}- />- ),}));vi.mock('@queries/chat', () => ({useChatQuery: (id: () => string) => {@@ -161,12 +201,20 @@ vi.mock('@queries/agent-session/session', () => ({return mocks.metadataStatus() === 'pending';},get data() {- return mocks.agentMetadata();+ const metadata = mocks.agentMetadata();+ return metadata+ ? {+ ...metadata,+ ownerId: 'macro|[email protected]',+ botId: 'test-bot',+ status: { kind: 'event', event: 'session/end' },+ }+ : undefined;},};},}));-vi.mock('@queries/agent-schedule/schedules', () => ({+vi.mock('./queries/schedules', () => ({useSchedulesQuery: () => ({get data() {return mocks.readSchedules();@@ -235,6 +283,7 @@ let setActivationPending: Setter<boolean>;beforeEach(() => {vi.clearAllMocks();mocks.update.mockReset().mockResolvedValue(cron);+ mocks.writeClipboardData.mockReset().mockResolvedValue(true);vi.useFakeTimers();[mocks.status, setStatus] = createSignal('success');[mocks.readSchedules, setSchedules] = createSignal([cron]);@@ -263,12 +312,26 @@ const agentTarget: RoutineTarget = {modelOverride: 'runtime-model',};+function openActions() {+ const trigger = screen.getByRole('button', { name: 'Routine actions' });+ trigger.focus();+ fireEvent.keyDown(trigger, { key: 'Enter' });+}+function runButton(): HTMLButtonElement {- return screen.getByRole('button', { name: 'Run Now' });+ return screen.getByRole('button', { name: 'Run now' });}-function activeSwitch(): HTMLButtonElement {- return screen.getByRole('switch', { name: 'Active' });+function openRunOptions() {+ const trigger = screen.getByRole('button', { name: 'Run options' });+ trigger.focus();+ fireEvent.keyDown(trigger, { key: 'Enter' });+}++function activationItem(): HTMLElement {+ const name = /^(Enable|Disable) routine$/;+ if (!screen.queryByRole('menuitem', { name })) openRunOptions();+ return screen.getByRole('menuitem', { name });}function selectedTarget(): RoutineTarget {@@ -289,7 +352,35 @@ function deferredSave(): {return { promise, resolve, reject };}-describe('automation execution target autosave', () => {+describe('routine execution target autosave', () => {+ it('copies the current prompt, including unsaved edits, from the run menu', async () => {+ render(() => <Routine />);+ mocks.changePrompt('Use my latest instructions');+ openRunOptions();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Copy prompt' }), {+ key: 'Enter',+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.writeClipboardData).toHaveBeenCalledExactlyOnceWith({+ 'text/plain': 'Use my latest instructions',+ });+ expect(toast.success).toHaveBeenCalledWith('Prompt copied');+ expect(mocks.update).not.toHaveBeenCalled();+ expect(screen.queryByText('All changes saved')).toBeNull();+ });++ it('reports when the prompt could not be copied', async () => {+ mocks.writeClipboardData.mockResolvedValueOnce(false);+ render(() => <Routine />);+ openRunOptions();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Copy prompt' }), {+ key: 'Enter',+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(toast.alert).toHaveBeenCalledWith('Could not copy prompt');+ expect(toast.success).not.toHaveBeenCalled();+ });+it('initializes the stored agent and duplicates its full saved configuration', () => {const saved = {...cron,@@ -302,18 +393,21 @@ describe('automation execution target autosave', () => {},};setSchedules([saved]);- render(() => <Automation />);+ render(() => <Routine />);expect(selectedTarget()).toEqual(agentTarget);- fireEvent.click(screen.getByText('Duplicate'));+ openActions();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Duplicate' }), {+ key: 'Enter',+ });expect(mocks.create).toHaveBeenCalledWith(expect.objectContaining({ task: saved.task }));});- it('disables immediate Run Now until the latest target has saved', async () => {+ it('disables immediate Run now until the latest target has saved', async () => {const save = deferredSave();mocks.update.mockReturnValueOnce(save.promise);- render(() => <Automation />);+ render(() => <Routine />);mocks.changeTarget({ kind: 'model', model: 'first-choice' });mocks.changeTarget(agentTarget);expect(runButton().disabled).toBe(true);@@ -344,7 +438,7 @@ describe('automation execution target autosave', () => {mocks.update.mockReturnValueOnce(first.promise).mockReturnValueOnce(last.promise);- render(() => <Automation />);+ render(() => <Routine />);mocks.changeTarget(agentTarget);await vi.advanceTimersByTimeAsync(300);mocks.changeTarget({ kind: 'model', model: 'intermediate' });@@ -377,9 +471,9 @@ describe('automation execution target autosave', () => {expect(runButton().disabled).toBe(false);});- it('keeps a failed target visibly unsaved and blocks Run Now until retry succeeds', async () => {+ it('keeps a failed target visibly unsaved and blocks Run now until retry succeeds', async () => {mocks.update.mockRejectedValueOnce(new Error('Agent unavailable'));- render(() => <Automation />);+ render(() => <Routine />);mocks.changeTarget(agentTarget);await vi.advanceTimersByTimeAsync(300);expect(selectedTarget()).toEqual(agentTarget);@@ -395,8 +489,8 @@ describe('automation execution target autosave', () => {expect(runButton().disabled).toBe(false);});- it('invalid edits cancel a queued valid save and keep Run Now disabled', async () => {- render(() => <Automation />);+ it('invalid edits cancel a queued valid save and keep Run now disabled', async () => {+ render(() => <Routine />);mocks.changeTarget(agentTarget);mocks.changePrompt('');await vi.advanceTimersByTimeAsync(300);@@ -405,10 +499,10 @@ describe('automation execution target autosave', () => {});it('pauses a routine with an invalid draft without saving the draft', async () => {- render(() => <Automation />);+ render(() => <Routine />);mocks.changePrompt('');- expect(screen.getByText('Prompt is required.')).toBeTruthy();- fireEvent.click(activeSwitch());+ expect(screen.getByText('Instructions are required.')).toBeTruthy();+ fireEvent.keyDown(activationItem(), { key: 'Enter' });expect(mocks.setEnabled).toHaveBeenCalledExactlyOnceWith({scheduleId: 'routine-id',enabled: false,@@ -418,7 +512,7 @@ describe('automation execution target autosave', () => {});it('keeps a queued target through a cached-data refetch error', async () => {- render(() => <Automation />);+ render(() => <Routine />);mocks.changeTarget(agentTarget);setStatus('error');expect(selectedTarget()).toEqual(agentTarget);@@ -437,51 +531,54 @@ describe('automation execution target autosave', () => {vi.setSystemTime(new Date('2026-09-28T12:00:00Z'));const claimed = '2026-09-28T11:55:00Z';setSchedules([{ ...cron, claimed }]);- render(() => <Automation />);- expect(screen.getByText('Running')).toBeTruthy();- fireEvent.click(activeSwitch());+ render(() => <Routine />);+ expect(+ screen.getByText(/Configuration cannot be changed while running/)+ ).toBeTruthy();+ fireEvent.keyDown(activationItem(), { key: 'Enter' });expect(mocks.setEnabled).toHaveBeenCalledExactlyOnceWith({scheduleId: 'routine-id',enabled: false,});setSchedules([{ ...cron, claimed, enabled: false }]);- expect(activeSwitch().getAttribute('aria-checked')).toBe('false');- expect(activeSwitch().disabled).toBe(true);+ expect(activationItem().textContent).toContain('Enable routine');+ expect(activationItem().getAttribute('aria-disabled')).toBe('true');setSchedules([{ ...cron, enabled: false }]);- expect(activeSwitch().disabled).toBe(false);+ expect(activationItem().getAttribute('aria-disabled')).not.toBe('true');});- it('shows a paused routine switched off and still runs it on demand', () => {- render(() => <Automation />);- expect(activeSwitch().getAttribute('aria-checked')).toBe('true');- expect(screen.getByText('Next run 2026-09-28T09:00:00Z')).toBeTruthy();+ it('shows a paused routine and still runs it on demand', async () => {+ render(() => <Routine />);+ expect(activationItem().textContent).toContain('Disable routine');+ expect(screen.getByText(/Next run/)).toBeTruthy();setSchedules([{ ...cron, enabled: false }]);- expect(activeSwitch().getAttribute('aria-checked')).toBe('false');- expect(screen.queryByText(/Next run/)).toBeNull();+ expect(activationItem().textContent).toContain('Enable routine');+ expect(screen.getByText('Paused')).toBeTruthy();+ fireEvent.keyDown(activationItem(), { key: 'Escape' });+ await vi.advanceTimersByTimeAsync(0);fireEvent.click(runButton());expect(mocks.run).toHaveBeenCalledExactlyOnceWith({scheduleId: 'routine-id',});});- it('holds the switch while an activation request is pending', () => {- render(() => <Automation />);- expect(activeSwitch().disabled).toBe(false);+ it('disables activation while a request is pending', () => {+ render(() => <Routine />);+ expect(activationItem().getAttribute('aria-disabled')).not.toBe('true');setActivationPending(true);- expect(activeSwitch().disabled).toBe(true);+ expect(activationItem().getAttribute('aria-disabled')).toBe('true');});- it.each(['events', 'unmount'])(+ it.each(['unmount'])('drops queued target changes on %s even during an in-flight save',- async (transition) => {+ async () => {const first = deferredSave();mocks.update.mockReturnValueOnce(first.promise);- const { unmount } = render(() => <Automation />);+ const { unmount } = render(() => <Routine />);mocks.changeTarget(agentTarget);await vi.advanceTimersByTimeAsync(300);mocks.changeTarget({ kind: 'model', model: 'queued' });- if (transition === 'events') setSchedules([events]);- else unmount();+ unmount();first.resolve(cron);await vi.advanceTimersByTimeAsync(500);expect(mocks.update).toHaveBeenCalledTimes(1);@@ -489,7 +586,7 @@ describe('automation execution target autosave', () => {);});-describe('automation history integration', () => {+describe('routine history integration', () => {function mixedHistory(): void {const legacy = mocks.history();mocks.history = () => [@@ -506,7 +603,7 @@ describe('automation history integration', () => {it('keeps mixed history navigation stable while switching model to agent and back', async () => {mixedHistory();- render(() => <Automation />);+ render(() => <Routine />);for (const target of [agentTarget,{ kind: 'model', model: 'new-model' } satisfies RoutineTarget,@@ -515,6 +612,8 @@ describe('automation history integration', () => {await vi.advanceTimersByTimeAsync(300);const saved = mocks.update.mock.lastCall![0].body;setSchedules([{ ...cron, ...saved }]);+ fireEvent.click(screen.getByRole('tab', { name: 'Run History' }));+ fireEvent.click(screen.getByRole('tab', { name: 'Run History' }));fireEvent.click(screen.getByText('Run transcript'));expect(mocks.openWithSplit).toHaveBeenLastCalledWith({ type: 'chat', id: 'chat-id' },@@ -545,10 +644,11 @@ describe('automation history integration', () => {mocks.agentMetadata = () => {throw new Error('Unsafe agent data read');};- render(() => <Automation />);+ render(() => <Routine />);expect(screen.getByRole('textbox', { name: 'Instructions' })).toBeTruthy();+ fireEvent.click(screen.getByRole('tab', { name: 'Run History' }));const labels = screen.getAllByText(status === 'pending' ? 'Loading…' : 'Run unavailable');@@ -562,7 +662,8 @@ describe('automation history integration', () => {mixedHistory();mocks.chatMetadata = () => ({});mocks.agentMetadata = () => undefined;- render(() => <Automation />);+ render(() => <Routine />);+ fireEvent.click(screen.getByRole('tab', { name: 'Run History' }));const unavailable = screen.getAllByText('Run unavailable');expect(unavailable).toHaveLength(2);for (const label of unavailable) fireEvent.click(label);@@ -570,26 +671,72 @@ describe('automation history integration', () => {});});-describe('automation editor trigger guards', () => {- it('shows an explicit backend-managed state on a direct event route', async () => {- setSchedules([events]);- render(() => <Automation />);- expect(screen.getByText('Backend-managed routine')).toBeTruthy();- expect(- screen.getByText(/Manage this routine through the API/)- ).toBeTruthy();- expect(screen.queryByText('Loading…')).toBeNull();- expect(screen.queryByRole('textbox')).toBeNull();- expect(screen.queryByText('Duplicate')).toBeNull();- expect(screen.queryByText('Run Now')).toBeNull();- await vi.advanceTimersByTimeAsync(500);+describe('routine editor triggers', () => {+ it('refreshes clean settings when a cached cron is replaced by an event configuration', async () => {+ render(() => <Routine />);+ setSchedules([{ ...events, configuration_revision: 2 }]);+ mocks.changePrompt('Keep the newer events');+ await vi.advanceTimersByTimeAsync(300);+ expect(mocks.update).toHaveBeenCalledWith({+ scheduleId: cron.id,+ body: expect.objectContaining({ trigger: events.trigger }),+ });+ });++ it('does not overwrite a newer remote trigger while a local edit is queued', async () => {+ render(() => <Routine />);+ mocks.changePrompt('Unsaved local instructions');+ setSchedules([{ ...events, configuration_revision: 2 }]);+ await vi.advanceTimersByTimeAsync(300);expect(mocks.update).not.toHaveBeenCalled();- expect(mocks.create).not.toHaveBeenCalled();+ expect(screen.getByRole('alert').textContent).toContain(+ 'changed elsewhere'+ );+ fireEvent.click(screen.getByRole('button', { name: 'Reload latest' }));+ expect(screen.queryByRole('alert')).toBeNull();+ mocks.changePrompt('Fresh event instructions');+ await vi.advanceTimersByTimeAsync(300);+ expect(mocks.update).toHaveBeenCalledWith({+ scheduleId: cron.id,+ body: expect.objectContaining({ trigger: events.trigger }),+ });});+ it('supports keyboard switching between settings and run history', async () => {+ render(() => <Routine />);+ const settings = screen.getByRole('tab', { name: 'Overview' });+ settings.focus();+ fireEvent.keyDown(settings, { key: 'ArrowRight' });+ await vi.advanceTimersByTimeAsync(300);+ const history = screen.getByRole('tab', { name: 'Run History' });+ expect(history.getAttribute('aria-selected')).toBe('true');+ expect(history.getAttribute('aria-controls')).toBe(+ screen.getByRole('tabpanel', { name: 'Run History' }).id+ );+ expect(screen.getByText('Run transcript')).toBeTruthy();+ });++ it('edits an event routine and retains its filters through autosave and refetch errors', async () => {+ setSchedules([events]);+ setStatus('error');+ render(() => <Routine />);+ const editor = screen.getByRole('textbox', { name: 'Instructions' });+ fireEvent.input(editor, { target: { value: 'New event instructions' } });+ await vi.advanceTimersByTimeAsync(300);+ expect(mocks.update).toHaveBeenCalledWith({+ scheduleId: 'routine-id',+ body: expect.objectContaining({+ trigger: events.trigger,+ task: expect.objectContaining({+ user_prompt: 'New event instructions',+ }),+ }),+ });+ fireEvent.click(screen.getByRole('tab', { name: 'Run History' }));+ expect(screen.getByText('Run transcript')).toBeTruthy();+ });it('retains cron editing, duplication, run-now, and history navigation', async () => {- render(() => <Automation />);- expect(screen.getByText(/America\/New_York/)).toBeTruthy();+ render(() => <Routine />);fireEvent.input(screen.getByRole('textbox', { name: 'Instructions' }), {target: { value: 'New instructions' },});@@ -607,7 +754,10 @@ describe('automation editor trigger guards', () => {},},});- fireEvent.click(screen.getByText('Duplicate'));+ openActions();+ fireEvent.keyDown(screen.getByRole('menuitem', { name: 'Duplicate' }), {+ key: 'Enter',+ });expect(mocks.create).toHaveBeenCalledExactlyOnceWith({name: 'Summary copy',kind: 'Agent',@@ -615,10 +765,12 @@ describe('automation editor trigger guards', () => {task: cron.task,trigger: cron.trigger,});- fireEvent.click(screen.getByText('Run Now'));+ await vi.advanceTimersByTimeAsync(300);+ fireEvent.click(screen.getByText('Run now'));expect(mocks.run).toHaveBeenCalledExactlyOnceWith({scheduleId: 'routine-id',});+ fireEvent.click(screen.getByRole('tab', { name: 'Run History' }));fireEvent.click(screen.getByText('Run transcript'));expect(mocks.openWithSplit).toHaveBeenCalledWith({ type: 'chat', id: 'chat-id' },@@ -626,35 +778,8 @@ describe('automation editor trigger guards', () => {);});- it('blocks queued autosave and stale edit/duplicate callbacks after a trigger changes to events', async () => {- render(() => <Automation />);- mocks.changePrompt('Queued edit');- setSchedules([events]);- expect(screen.getByText('Backend-managed routine')).toBeTruthy();- mocks.rename('Stale rename');- mocks.changePrompt('Stale prompt');- mocks.duplicate();- await vi.advanceTimersByTimeAsync(500);- expect(mocks.update).not.toHaveBeenCalled();- expect(mocks.create).not.toHaveBeenCalled();- expect(mocks.setDisplayName).not.toHaveBeenCalledWith('Stale rename');- });-- it('does not resurrect queued saves when returning from an event to a cron action', async () => {- render(() => <Automation />);- mocks.changeTarget(agentTarget);- setSchedules([events]);- setSchedules([cron]);- expect(selectedTarget()).toEqual({- kind: 'model',- model: 'claude-sonnet-4-6',- });- await vi.advanceTimersByTimeAsync(500);- expect(mocks.update).not.toHaveBeenCalled();- });-it('cancels pending saves when the editor unmounts', async () => {- const { unmount } = render(() => <Automation />);+ const { unmount } = render(() => <Routine />);mocks.changePrompt('Unsaved');unmount();await vi.advanceTimersByTimeAsync(500);@@ -666,26 +791,26 @@ describe('automation editor trigger guards', () => {mocks.readSchedules = () => {throw new Error('Pending data read');};- render(() => <Automation />);+ render(() => <Routine />);expect(screen.getByText('Loading…')).toBeTruthy();});it('renders a load error rather than spinning forever', () => {setStatus('error');setSchedules([]);- render(() => <Automation />);+ render(() => <Routine />);expect(- screen.getByText('Unable to load automation. Please try again.')+ screen.getByText('Unable to load routine. Please try again.')).toBeTruthy();});it('preserves the cron editor and queued save after a background refetch error', async () => {- render(() => <Automation />);+ render(() => <Routine />);const editor = screen.getByRole('textbox', { name: 'Instructions' });fireEvent.input(editor, { target: { value: 'Queued during refetch' } });setStatus('error');expect(screen.getByRole('textbox', { name: 'Instructions' })).toBe(editor);- expect(screen.queryByText(/Unable to load automation/)).toBeNull();+ expect(screen.queryByText(/Unable to load routine/)).toBeNull();await vi.advanceTimersByTimeAsync(300);expect(mocks.update).toHaveBeenCalledExactlyOnceWith({scheduleId: 'routine-id',@@ -698,27 +823,13 @@ describe('automation editor trigger guards', () => {it('initializes the editor from cached data even when mounted after a refetch error', () => {setStatus('error');- render(() => <Automation />);+ render(() => <Routine />);expect(screen.getByRole('textbox', { name: 'Instructions' })).toBeTruthy();});- it('keeps cached event routines backend-managed after a refetch error', async () => {- render(() => <Automation />);- mocks.changePrompt('Queued edit');- setSchedules([events]);- setStatus('error');- expect(screen.getByText('Backend-managed routine')).toBeTruthy();- expect(screen.queryByRole('textbox')).toBeNull();- mocks.rename('Stale rename');- mocks.duplicate();- await vi.advanceTimersByTimeAsync(500);- expect(mocks.update).not.toHaveBeenCalled();- expect(mocks.create).not.toHaveBeenCalled();- });-it('distinguishes a missing action from a backend-managed event', () => {setSchedules([]);- render(() => <Automation />);- expect(screen.getByText('Automation not found.')).toBeTruthy();+ render(() => <Routine />);+ expect(screen.getByText('Routine not found.')).toBeTruthy();});});diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsxnew file mode 100644index 0000000000..c553c4734f--- /dev/null+++ b/apps/web/src/features/routines/routine-detail.tsx@@ -0,0 +1,105 @@+import { openAgentsPage } from '@app/features/agents-view/primitives/open-page';+import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { useBlockId } from '@core/block';+import { DEFAULT_MODEL } from '@core/component/AI/constant';+import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import { writeClipboardData } from '@core/util/dataTransfer';+import { onMount, Show } from 'solid-js';+import { getErrorMessage } from './core/routine-draft';+import {+ createAgentHistoryMetadata,+ createChatHistoryMetadata,+} from './queries/history-metadata';+import { createRoutineDetailSource } from './queries/routine-sources';+import { RoutineExecutionPicker } from './routine-execution-picker';+import { RoutinePromptEditor } from './routine-prompt-editor';+import { RoutineTriggers } from './routine-triggers';+import { RoutineDetailView } from './views/routine-detail';++export function Routine() {+ const scheduleId = useBlockId();+ const layout = useSplitLayout();+ onMount(() => {+ if (scheduleId === 'new') {+ layout.popoverSplit({ type: 'component', id: 'routine-compose' });+ openAgentsPage(layout, 'routines');+ }+ });+ return (+ <Show when={scheduleId !== 'new'}>+ <RoutineDetail scheduleId={scheduleId} />+ </Show>+ );+}++export function RoutineDetail(props: {+ scheduleId: string;+ initialTab?: 'settings' | 'history';+ onBack?: () => void;+ onOpen?: (id: string) => void;+}) {+ const layout = useSplitLayout();+ const panel = useSplitPanelOrThrow();+ const userId = useUserId();+ const back = () =>+ props.onBack ? props.onBack() : openAgentsPage(layout, 'routines');+ const open = (id: string) =>+ props.onOpen+ ? props.onOpen(id)+ : openAgentsPage(layout, 'routines', { routineId: id });+ const source = createRoutineDetailSource(() => props.scheduleId, {+ onError: (title, error) =>+ toast.alert(title, { subtext: getErrorMessage(error) }),+ onDuplicated: (id) => {+ toast.success('Duplicated');+ open(id);+ },+ });+ const remove = () => {+ const entity = source.entity();+ if (!entity || entity.ownerId !== userId()) return;+ openBulkEditModal({+ view: 'delete',+ entities: [entity],+ onFinish: () => {+ toast.success('Deleted');+ back();+ },+ onError: () => toast.failure('Failed to delete'),+ });+ };+ return (+ <RoutineDetailView+ source={source}+ userId={userId}+ defaultModel={DEFAULT_MODEL}+ initialTab={props.initialTab}+ onBack={back}+ onDelete={remove}+ onRename={(name) => {+ if (!props.onBack) panel.handle.setDisplayName(name);+ }}+ onOpenRun={(resource, newSplit) =>+ layout.openWithSplit(resource, {+ activate: true,+ preferNewSplit: newSplit,+ })+ }+ onCopyPrompt={async (prompt) => {+ if (await writeClipboardData({ 'text/plain': prompt }))+ toast.success('Prompt copied');+ else toast.alert('Could not copy prompt');+ }}+ slots={{+ PromptEditor: RoutinePromptEditor,+ ExecutionPicker: RoutineExecutionPicker,+ Triggers: RoutineTriggers,+ createChatMetadata: createChatHistoryMetadata,+ createAgentMetadata: createAgentHistoryMetadata,+ }}+ />+ );+}diff --git a/apps/web/src/features/routines/routine-event-scope.tsx b/apps/web/src/features/routines/routine-event-scope.tsxnew file mode 100644index 0000000000..f921129958--- /dev/null+++ b/apps/web/src/features/routines/routine-event-scope.tsx@@ -0,0 +1,66 @@+import { useQuickAccessEntities } from '@property/editors/selectors/entityUtils';+import { PropertyEntitySelector } from '@property/editors/selectors/PropertyEntitySelector';+import { Suspense } from 'solid-js';+import { match } from 'ts-pattern';++type ScopeProps = {+ kind: 'CHANNEL' | 'DOCUMENT' | 'TASK' | 'THREAD';+ ids?: string[];+};++function entityLabel(kind: ScopeProps['kind']) {+ return match(kind)+ .with('CHANNEL', () => 'channel')+ .with('DOCUMENT', () => 'document')+ .with('TASK', () => 'task')+ .with('THREAD', () => 'email thread')+ .exhaustive();+}++export function RoutineEventScopeLabel(props: ScopeProps) {+ const entities = useQuickAccessEntities(() => props.kind);+ const label = () => {+ const singular = entityLabel(props.kind);+ if (props.kind === 'THREAD' && props.ids === undefined) return 'Your inbox';+ if (props.ids === undefined) return `Any ${singular}`;+ if (!props.ids.length) return `Choose ${singular}s`;+ if (props.ids.length > 1) return `${props.ids.length} ${singular}s`;+ const entity = entities.items().find((item) => item.id === props.ids?.[0]);+ return entity?.data.name ?? `Selected ${singular}`;+ };+ return <span title={label()}>{label()}</span>;+}++/** Inline search inside the trigger panel; never opens another popover. */+export function RoutineEventScope(+ props: ScopeProps & {+ onChange: (ids: string[] | undefined) => void;+ }+) {+ const plural = () => `${entityLabel(props.kind)}s`;+ return (+ <Suspense fallback={<p class="p-3 text-sm text-ink-muted">Loading…</p>}>+ <PropertyEntitySelector+ config={{+ isMultiSelect: true,+ placeholder: `Search ${plural()}…`,+ specificEntityType: props.kind,+ }}+ selectedOptions={() => new Set(props.ids ?? ['__any__'])}+ setSelectedOptions={(ids) => {+ if (ids.has('__any__') && props.ids !== undefined) {+ props.onChange(undefined);+ } else {+ props.onChange([...ids].filter((id) => id !== '__any__'));+ }+ }}+ pinnedOptions={[+ {+ id: '__any__',+ label: `Any ${entityLabel(props.kind)} I can access`,+ },+ ]}+ />+ </Suspense>+ );+}diff --git a/apps/web/src/features/block-automation/routine-execution-picker.tsx b/apps/web/src/features/routines/routine-execution-picker.tsxsimilarity index 100%rename from apps/web/src/features/block-automation/routine-execution-picker.tsxrename to apps/web/src/features/routines/routine-execution-picker.tsxdiff --git a/apps/web/src/features/routines/routine-navigation.test.ts b/apps/web/src/features/routines/routine-navigation.test.tsnew file mode 100644index 0000000000..dd92aae135--- /dev/null+++ b/apps/web/src/features/routines/routine-navigation.test.ts@@ -0,0 +1,239 @@+import {+ createMemoryHistory,+ createMemoryPaneStore,+ createRoutesManifest,+ createSplitRouter,+ decodePane,+ formatPanePath,+ type SplitRoutes,+} from '@app/lib/split-router';+import {+ agentsViewRoute,+ appRoute,+ legacyContentRoute,+ notFoundRoute,+ routineCreateRoute,+ routineDetailRoute,+ routinesRoute,+} from '@app/routes/routes';+import {+ createSplitLayout,+ type SplitContent,+} from '@components/app/split-layout/layoutManager';+import { createAppPanePolicy } from '@components/app/split-layout/split-router/app-pane-policy';+import {+ resolveContentLocation,+ splitContentFromLocation,+ upgradeLegacyPath,+} from '@components/app/split-layout/split-router/legacy-route';+import { createMacroMentionLinkResolver } from '@components/app/split-layout/split-router/mention-links';+import type { BlockOrchestrator } from '@core/orchestrator';+import { createRoot } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ routineContent,+ routineIdFromContent,+ routineLocation,+} from './routine-navigation';++vi.mock('@components/app/split-layout/componentRegistry', () => ({+ resolveComponent: vi.fn(() => ({ type: 'mock-component' })),+}));+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));++const definitions: SplitRoutes = {+ definitions: [+ {+ ...appRoute,+ children: [+ routinesRoute,+ agentsViewRoute,+ routineCreateRoute,+ routineDetailRoute,+ legacyContentRoute,+ notFoundRoute,+ ],+ },+ ],+ defaultRoute: () => routineLocation().route,+};+const routes = createRoutesManifest(definitions);+let cleanup: (() => void) | undefined;++function setup(path: string) {+ const history = createMemoryHistory(upgradeLegacyPath(routes, path));+ return createRoot((dispose) => {+ let manager: ReturnType<typeof createSplitLayout> | undefined;+ const router = createSplitRouter({+ routes: definitions,+ history,+ paneStore: createMemoryPaneStore(),+ policy: createAppPanePolicy({+ manager: () => manager,+ toContent: splitContentFromLocation,+ defaultLocation: routineLocation,+ stacked: () => false,+ }),+ });+ const orchestrator = {+ isBlockMounted: vi.fn(() => false),+ createBlockInstance: vi.fn((_type, id) => ({+ node: { type: 'mock-node', id },+ detach: vi.fn(),+ dispose: vi.fn(),+ })),+ } as unknown as BlockOrchestrator;+ manager = createSplitLayout(orchestrator, {+ router,+ toLocation: (content) => resolveContentLocation(router.routes, content),+ toContent: splitContentFromLocation,+ });+ cleanup = () => {+ router.dispose();+ dispose();+ };+ return { manager, router, history };+ });+}++afterEach(() => {+ cleanup?.();+ cleanup = undefined;+});++describe('routine navigation', () => {+ it.each([undefined, 'routine-a', 'new'])(+ 'round-trips the routine destination %s through the app router',+ (id) => {+ const location = routineLocation(id);+ const path = formatPanePath(routes, location.route);+ expect(path).toBe(id ? `/routines/${id}` : '/routines');+ const decoded = decodePane(routes, path.slice(1).split('/'))!;+ expect(splitContentFromLocation({ route: decoded })).toEqual(+ routineContent(id)+ );+ }+ );++ it.each(['routine', 'automation'])(+ 'canonicalizes existing %s links, including creation links',+ (type) => {+ for (const id of ['routine-a', 'new']) {+ const route = decodePane(routes, [type, id])!;+ expect(formatPanePath(routes, route)).toBe(`/routines/${id}`);+ }+ const id = '018f18ee-9747-7152-8a5f-4aa2d83d1f62';+ expect(+ createMacroMentionLinkResolver(routes)(+ `${window.location.origin}/app/${type}/${id}`+ )+ ).toEqual({ id, block: 'routine', params: {} });+ }+ );++ it('restores older pane data and prefers the current route over stale params', () => {+ const saved: SplitContent[] = [+ { type: 'routine', id: 'routine-b' },+ {+ type: 'component',+ id: 'agents',+ params: { agentPage: 'routines', routineId: 'routine-b' },+ },+ {+ ...routineContent('routine-b'),+ params: { routineId: 'routine-a' },+ entryMetadata: {+ route: {+ matches: [+ { id: 'routine-detail', params: { routineId: 'routine-b' } },+ ],+ },+ },+ },+ ];+ for (const content of saved) {+ const location = resolveContentLocation(routes, content);+ expect(formatPanePath(routes, location.route)).toBe(+ '/routines/routine-b'+ );+ }+ expect(+ routineIdFromContent({+ ...routineContent(),+ params: { routineId: 'routine-a' },+ })+ ).toBeUndefined();+ });++ it.each([+ '/md/document-a/automation/routine-a',+ '/automation/routine-a/md/document-a',+ '/md/document-a/~/automation/routine-a',+ '/automation/routine-a/~/md/document-a',+ ])('restores every pane in a saved layout: %s', (path) => {+ const { manager, history } = setup(path);+ expect(manager.splits()).toHaveLength(2);+ const contents = manager.splits().map((split) => split.content);+ expect(contents).toContainEqual(+ expect.objectContaining({ type: 'md', id: 'document-a' })+ );+ expect(contents.some((c) => routineIdFromContent(c) === 'routine-a')).toBe(+ true+ );+ expect(history.read().path).not.toContain('automation');+ expect(history.read().path).toContain('routines/routine-a');+ });++ it('updates the same pane and restores routine identity on Back and Forward', () => {+ const { manager, history } = setup('/routines');+ const pane = manager.activeSplit()!;+ for (const id of ['routine-a', 'routine-b']) {+ manager.openWithSplit(routineContent(id), { handle: pane, search: {} });+ expect(manager.splits()).toHaveLength(1);+ expect(history.read().path).toBe(`/routines/${id}`);+ expect(routineIdFromContent(pane.content())).toBe(id);+ }+ history.back();+ expect(routineIdFromContent(pane.content())).toBe('routine-a');+ history.back();+ expect(routineIdFromContent(pane.content())).toBeUndefined();+ history.forward();+ expect(routineIdFromContent(pane.content())).toBe('routine-a');+ });+ it('restores the chosen Agents management page when leaving routines and going Back', () => {+ const { manager, history } = setup('/routines');+ const pane = manager.activeSplit()!;+ manager.openWithSplit(+ {+ type: 'component',+ id: 'agents',+ preserveParams: true,+ params: {+ agentPage: 'connections',+ agentPageRequest: 'open-connections',+ },+ },+ { handle: pane, search: {} }+ );+ manager.openWithSplit(routineContent('routine-a'), {+ handle: pane,+ search: {},+ });+ history.back();+ expect(pane.content()).toMatchObject({+ id: 'agents',+ params: { agentPage: 'connections' },+ });+ history.forward();+ expect(routineIdFromContent(pane.content())).toBe('routine-a');+ });+});diff --git a/apps/web/src/features/routines/routine-navigation.ts b/apps/web/src/features/routines/routine-navigation.tsnew file mode 100644index 0000000000..f88a9c06e0--- /dev/null+++ b/apps/web/src/features/routines/routine-navigation.ts@@ -0,0 +1,56 @@+import type { SplitLocation } from '@app/lib/split-router';+import { isRecord } from '@app/lib/split-router';+import { paneRoute } from '@app/routes/app-route';+import type { SplitContent } from '@components/app/split-layout/layoutManager';++export const ROUTINES_ROUTE_ID = 'view-routines';+export const ROUTINE_DETAIL_ROUTE_ID = 'routine-detail';+export const ROUTINE_CREATE_ROUTE_ID = 'routine-create';++export function routineLocation(routineId?: string): SplitLocation {+ return {+ route: paneRoute(+ routineId === 'new'+ ? { id: ROUTINE_CREATE_ROUTE_ID, params: {} }+ : routineId+ ? { id: ROUTINE_DETAIL_ROUTE_ID, params: { routineId } }+ : { id: ROUTINES_ROUTE_ID, params: {} }+ ),+ };+}++/** Keep routine navigation in the Agents workspace, with a durable route. */+export function routineContent(routineId?: string): SplitContent {+ return {+ type: 'component',+ id: 'routines',+ params: routineId ? { routineId } : undefined,+ entryMetadata: routineLocation(routineId),+ };+}++export function routineIdFromContent(+ content: SplitContent+): string | undefined {+ if (content.type !== 'component' || content.id !== 'routines') return;+ const metadata = isRecord(content.entryMetadata)+ ? content.entryMetadata+ : undefined;+ const location = isRecord(metadata?.location) ? metadata.location : metadata;+ const route = isRecord(location?.route) ? location.route : undefined;+ if (Array.isArray(route?.matches)) {+ for (const match of route.matches) {+ if (!isRecord(match)) continue;+ if (match.id === ROUTINES_ROUTE_ID) return;+ if (match.id === ROUTINE_CREATE_ROUTE_ID) return 'new';+ if (match.id !== ROUTINE_DETAIL_ROUTE_ID || !isRecord(match.params))+ continue;+ return typeof match.params.routineId === 'string'+ ? match.params.routineId+ : undefined;+ }+ }+ return typeof content.params?.routineId === 'string'+ ? content.params.routineId+ : undefined;+}diff --git a/apps/web/src/features/block-automation/component/AutomationPromptEditor.tsx b/apps/web/src/features/routines/routine-prompt-editor.tsxsimilarity index 66%rename from apps/web/src/features/block-automation/component/AutomationPromptEditor.tsxrename to apps/web/src/features/routines/routine-prompt-editor.tsxindex b99d6bb68d..0f04ceb243 100644--- a/apps/web/src/features/block-automation/component/AutomationPromptEditor.tsx+++ b/apps/web/src/features/routines/routine-prompt-editor.tsx@@ -2,26 +2,26 @@ import { useMacroMentionLinkResolver } from '@components/app/split-layout/split-import { EditorConfigBuilder } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';-export function AutomationPromptEditor(props: {+export function RoutinePromptEditor(props: {initialValue: string;onChange: (markdown: string) => void;}) {const editor = new EditorConfigBuilder().withAppLinkResolver(useMacroMentionLinkResolver())- .namespace('automation-prompt')+ .namespace('routine-prompt').withHistory().withLinks().withMentions().onChange(props.onChange);return (- <div class="min-h-45 border border-edge-muted rounded-sm bg-surface **:[[contenteditable]]:px-2 **:[[contenteditable]]:py-1.5 **:[[contenteditable]]:text-sm **:[[contenteditable]]:outline-none cursor-default">+ <div class="min-h-28 **:[[contenteditable]]:text-sm **:[[contenteditable]]:outline-none cursor-default"><MarkdownShellconfig={editor}initialValue={props.initialValue}- placeholder=""+ placeholder="What should this routine do? Type @ to add context…"portalScope="local"- class="min-h-45"+ class="min-h-28"/></div>);diff --git a/apps/web/src/features/routines/routine-triggers.tsx b/apps/web/src/features/routines/routine-triggers.tsxnew file mode 100644index 0000000000..00befd0c92--- /dev/null+++ b/apps/web/src/features/routines/routine-triggers.tsx@@ -0,0 +1,41 @@+import { Show, Suspense } from 'solid-js';+import { RoutineTriggers as TriggerList } from './components/routine-triggers';+import {+ eventScopeKind,+ isGlobalEvent,+ type RoutineTriggerDraft,+} from './core/routine-triggers';+import {+ RoutineEventScope,+ RoutineEventScopeLabel,+} from './routine-event-scope';++export function RoutineTriggers(props: {+ triggers: RoutineTriggerDraft[];+ onChange: (triggers: RoutineTriggerDraft[]) => void;+}) {+ return (+ <TriggerList+ {...props}+ renderEventLabel={(trigger) => (+ <Suspense fallback={<span>Selected items</span>}>+ <RoutineEventScopeLabel+ kind={eventScopeKind(trigger())}+ ids={trigger().ids}+ />+ </Suspense>+ )}+ renderEventScope={(trigger, onChange) => (+ <Show+ when={!isGlobalEvent(trigger().events) || trigger().ids !== undefined}+ >+ <RoutineEventScope+ kind={eventScopeKind(trigger())}+ ids={trigger().ids}+ onChange={onChange}+ />+ </Show>+ )}+ />+ );+}diff --git a/apps/web/src/features/routines/routines-page.tsx b/apps/web/src/features/routines/routines-page.tsxnew file mode 100644index 0000000000..6eb07e950a--- /dev/null+++ b/apps/web/src/features/routines/routines-page.tsx@@ -0,0 +1,90 @@+import { useViewControlHotkeys } from '@app/components/view-shell';+import { useSplitLayout } from '@components/app/split-layout/layout';+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { modelLabel } from '@core/component/AI/constant/model-label';+import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import { Show, Suspense } from 'solid-js';+import { createAgentRosterSource } from '../agents-view/queries/agent-roster-source';+import { getErrorMessage } from './core/routine-draft';+import { createRoutineListSource } from './queries/routine-sources';+import { RoutineDetail } from './routine-detail';+import { routineContent, routineIdFromContent } from './routine-navigation';+import { RoutinesListView } from './views/routines-list';++function RoutinesContent() {+ const userId = useUserId();+ const layout = useSplitLayout();+ const panel = useSplitPanelOrThrow();+ const selectedId = () => routineIdFromContent(panel.handle.content());+ const open = (id?: string) =>+ layout.openWithSplit(routineContent(id), {+ handle: panel.handle,+ activate: true,+ search: {},+ });+ let searchInput: HTMLInputElement | undefined;+ useViewControlHotkeys({+ scopeId: panel.splitHotkeyScope,+ enabled: () => panel.isPanelActive() && !selectedId(),+ search: {+ description: 'Search routines',+ run: () => {+ searchInput?.focus();+ searchInput?.select();+ return true;+ },+ },+ });+ const roster = createAgentRosterSource();+ const source = createRoutineListSource((error) =>+ toast.alert('Could not update routine', { subtext: getErrorMessage(error) })+ );+ function create() {+ layout.popoverSplit({+ type: 'component',+ id: 'routine-compose',+ params: {+ onCreated: (id: string) => open(id),+ },+ });+ }+ return (+ <Show+ when={selectedId()}+ keyed+ fallback={+ <RoutinesListView+ source={source}+ userId={userId}+ targetLabel={(target) =>+ target.kind === 'agent'+ ? (roster.roster().find((agent) => agent.botId === target.agentId)+ ?.name ?? 'Agent')+ : modelLabel(target.model)+ }+ searchRef={(input) => (searchInput = input)}+ onCreate={create}+ onOpen={(id) => open(id)}+ />+ }+ >+ {(id) => (+ <RoutineDetail+ scheduleId={id}+ onBack={() => open()}+ onOpen={(id) => open(id)}+ />+ )}+ </Show>+ );+}+export function RoutinesPage() {+ return (+ <Suspense+ fallback={<div class="p-6 text-sm text-ink-muted">Loading routines…</div>}+ >+ <RoutinesContent />+ </Suspense>+ );+}diff --git a/apps/web/src/features/routines/views/routine-creator.tsx b/apps/web/src/features/routines/views/routine-creator.tsxnew file mode 100644index 0000000000..7508067bbf--- /dev/null+++ b/apps/web/src/features/routines/views/routine-creator.tsx@@ -0,0 +1,123 @@+import ClockIcon from '@phosphor/clock.svg';+import XIcon from '@phosphor/x.svg';+import { Button, EntityComposer, ToggleSwitch } from '@ui';+import { Show } from 'solid-js';+import type { RoutineEditorSlots } from '../context/routine-slots';+import type {+ RoutineCreatorSource,+ RoutineDraftStorage,+} from '../context/routine-sources';+import { validateRoutineDraft } from '../core/routine-draft';+import { createRoutineComposer } from '../primitives/routine-composer';++export function RoutineCreatorView(props: {+ source: RoutineCreatorSource;+ storage: RoutineDraftStorage;+ slots: RoutineEditorSlots;+ defaultModel: string;+ onCreated(id: string): void;+ onClose(): void;+}) {+ const { draft, change, attempted, submitError, create } =+ createRoutineComposer(+ props.source,+ props.storage,+ props.defaultModel,+ props.onCreated+ );+ return (+ <EntityComposer.Root+ class="w-full h-auto max-h-[75vh]"+ onKeyDown={(event) => {+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {+ event.preventDefault();+ void create();+ }+ }}+ >+ <EntityComposer.Header>+ <ClockIcon class="ml-2 size-4 text-ink-muted" />+ <span class="flex-1 px-1 text-sm text-ink-muted">New routine</span>+ <Button+ size="icon-composer"+ variant="ghost"+ aria-label="Close routine composer"+ onClick={() => props.onClose()}+ >+ <XIcon />+ </Button>+ </EntityComposer.Header>+ <div class="min-h-0 overflow-y-auto px-2">+ <input+ aria-label="Routine name"+ placeholder="Routine name"+ value={draft().name}+ disabled={props.source.pending()}+ onInput={(e) =>+ change((draft) => ({ ...draft, name: e.currentTarget.value }))+ }+ class="mb-4 w-full bg-transparent text-xl font-medium leading-7 text-ink outline-none placeholder:text-ink-placeholder"+ />+ <fieldset+ disabled={props.source.pending()}+ inert={props.source.pending()}+ class="grid min-w-0 gap-4"+ >+ <section class="min-h-32" aria-label="Instructions">+ <props.slots.PromptEditor+ initialValue={draft().prompt}+ onChange={(prompt) =>+ change((draft) =>+ draft.prompt === prompt ? draft : { ...draft, prompt }+ )+ }+ />+ </section>+ <EntityComposer.Properties aria-label="Routine properties">+ <props.slots.ExecutionPicker+ target={draft().target}+ onChange={(target) => change((draft) => ({ ...draft, target }))}+ />+ <props.slots.Triggers+ triggers={draft().triggers ?? []}+ onChange={(triggers) =>+ change((draft) => ({ ...draft, triggers }))+ }+ />+ </EntityComposer.Properties>+ </fieldset>+ <Show when={attempted() && validateRoutineDraft(draft(), true)}>+ {(message) => (+ <p role="alert" class="mt-3 text-xs text-failure">+ {message()}+ </p>+ )}+ </Show>+ <Show when={submitError()}>+ {(message) => (+ <p role="alert" class="mt-3 text-xs text-failure">+ {message()}+ </p>+ )}+ </Show>+ </div>+ <EntityComposer.Footer class="border-t border-edge-muted px-2 pt-4 items-center">+ <ToggleSwitch+ label="Start enabled"+ labelClass="text-xs text-ink-muted"+ checked={draft().enabled ?? true}+ disabled={props.source.pending()}+ onChange={(enabled) => change((draft) => ({ ...draft, enabled }))}+ />+ <EntityComposer.Submit+ aria-label={props.source.pending() ? 'Creating…' : 'Create routine'}+ hasContent={Boolean(draft().prompt.trim())}+ disabled={props.source.pending()}+ onClick={() => void create()}+ >+ {props.source.pending() ? 'Creating…' : 'Create routine'}+ </EntityComposer.Submit>+ </EntityComposer.Footer>+ </EntityComposer.Root>+ );+}diff --git a/apps/web/src/features/routines/views/routine-detail.tsx b/apps/web/src/features/routines/views/routine-detail.tsxnew file mode 100644index 0000000000..5f89fc9ff0--- /dev/null+++ b/apps/web/src/features/routines/views/routine-detail.tsx@@ -0,0 +1,224 @@+import CopyIcon from '@phosphor/copy.svg';+import DotsIcon from '@phosphor/dots-three.svg';+import TrashIcon from '@phosphor/trash-simple.svg';+import { Dropdown } from '@ui';+import { type Accessor, createSignal, Match, Show, Switch } from 'solid-js';+import { RoutineEditor } from '../components/routine-editor';+import { RoutineRunButton } from '../components/routine-run-button';+import type { RoutineDetailSlots } from '../context/routine-slots';+import type { RoutineDetailSource } from '../context/routine-sources';+import type { HistoryResource } from '../core/history';+import { createEmptyDraft, getErrorMessage } from '../core/routine-draft';+import {+ createRoutineDetail,+ RoutineConflictError,+} from '../primitives/routine-detail';+import { RoutineHistory } from './routine-history';++export function RoutineDetailView(props: {+ source: RoutineDetailSource;+ userId: Accessor<string | undefined>;+ defaultModel: string;+ slots: RoutineDetailSlots;+ initialTab?: 'settings' | 'history';+ onRename(name: string): void;+ onBack(): void;+ onDelete(): void;+ onCopyPrompt(prompt: string): Promise<void>;+ onOpenRun(resource: HistoryResource, newSplit: boolean): void;+}) {+ const {+ schedule,+ state,+ setState,+ isOwned,+ isRunning,+ isActive,+ editorVersion,+ formError,+ autosave,+ initializeDraft,+ nextRun,+ runDisabled,+ activationDisabled,+ runNow,+ } = createRoutineDetail(props.source, props);+ const [tab, setTab] = createSignal(props.initialTab ?? 'settings');+ const back = () => props.onBack();+ const copyPrompt = async () => {+ const prompt = state()?.prompt;+ if (prompt) await props.onCopyPrompt(prompt);+ };+ return (+ <Show+ when={schedule()}+ fallback={+ <div class="flex size-full flex-col items-center justify-center gap-2 p-3 text-center text-sm text-ink-muted">+ <Switch fallback={<>Routine not found.</>}>+ <Match when={props.source.error() && !schedule()}>+ Unable to load routine. Please try again.+ </Match>+ <Match when={props.source.loading()}>Loading…</Match>+ </Switch>+ </div>+ }+ >+ {(routine) => (+ <RoutineEditor+ draft={+ state() ?? {+ ...createEmptyDraft(props.defaultModel),+ name: routine().name,+ }+ }+ onChange={setState}+ disabled={!isOwned() || isRunning() || !state()}+ tab={tab()}+ onTab={setTab}+ onBack={back}+ enabled={isActive()}+ runActions={+ <RoutineRunButton+ enabled={isActive()}+ runDisabled={runDisabled()}+ activationDisabled={activationDisabled()}+ copyDisabled={!state()?.prompt}+ onRun={runNow}+ onEnabled={(enabled) => props.source.setEnabled(enabled)}+ onCopyPrompt={() => void copyPrompt()}+ />+ }+ actions={+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger+ variant="ghost"+ size="icon-sm"+ aria-label="Routine actions"+ >+ <DotsIcon class="size-5" />+ </Dropdown.Trigger>+ <Dropdown.Content portalScope="local">+ <Dropdown.Item+ disabled={!state() || props.source.duplicationPending()}+ onSelect={() => props.source.duplicate()}+ >+ <CopyIcon class="size-4" />+ Duplicate+ </Dropdown.Item>+ <Show when={isOwned()}>+ <Dropdown.Item onSelect={props.onDelete}>+ <TrashIcon class="size-4" />+ Delete+ </Dropdown.Item>+ </Show>+ </Dropdown.Content>+ </Dropdown>+ }+ nextRun={nextRun()}+ instructions={+ <Show when={state()}>+ <Show when={{ version: editorVersion() }} keyed>+ <props.slots.PromptEditor+ initialValue={state()?.prompt ?? ''}+ onChange={(prompt) =>+ setState((draft) =>+ draft.prompt === prompt ? draft : { ...draft, prompt }+ )+ }+ />+ </Show>+ </Show>+ }+ executionPicker={+ <Show when={state()}>+ {(draft) => (+ <props.slots.ExecutionPicker+ target={draft().target}+ onChange={(target) =>+ setState((current) => ({ ...current, target }))+ }+ />+ )}+ </Show>+ }+ triggerContent={+ <Show+ when={state()}+ fallback={+ <p class="text-sm text-ink-muted">+ This routine has an unsupported task configuration.+ </p>+ }+ >+ {(draft) => (+ <props.slots.Triggers+ triggers={draft().triggers ?? []}+ onChange={(triggers) =>+ setState((current) => ({ ...current, triggers }))+ }+ />+ )}+ </Show>+ }+ feedback={+ <>+ <Show when={autosave.error()}>+ <p role="alert" class="text-sm text-failure">+ Changes not saved. {getErrorMessage(autosave.error())}+ <button+ type="button"+ class="ml-2 underline"+ onClick={() => {+ if (autosave.error() instanceof RoutineConflictError) {+ autosave.cancel();+ initializeDraft();+ } else autosave.retry();+ }}+ >+ {autosave.error() instanceof RoutineConflictError+ ? 'Reload latest'+ : 'Retry save'}+ </button>+ </p>+ </Show>+ <Show when={formError()}>+ {(message) => (+ <p role="alert" class="text-sm text-failure">+ {message()}+ </p>+ )}+ </Show>+ <Show when={isRunning()}>+ <p class="text-xs text-ink-muted">+ Running. Configuration cannot be changed while running.+ </p>+ </Show>+ </>+ }+ history={+ <>+ <Show when={props.source.historyError()}>+ <p role="alert" class="px-4 py-3 text-sm text-failure">+ Could not load run history.{' '}+ <button+ class="underline"+ onClick={() => void props.source.refreshHistory()}+ >+ Retry+ </button>+ </p>+ </Show>+ <RoutineHistory+ records={props.source.history()}+ isPending={props.source.historyLoading()}+ createChatMetadata={props.slots.createChatMetadata}+ createAgentMetadata={props.slots.createAgentMetadata}+ onOpen={props.onOpenRun}+ />+ </>+ }+ />+ )}+ </Show>+ );+}diff --git a/apps/web/src/features/block-automation/views/routine-execution-picker.test.tsx b/apps/web/src/features/routines/views/routine-execution-picker.test.tsxsimilarity index 99%rename from apps/web/src/features/block-automation/views/routine-execution-picker.test.tsxrename to apps/web/src/features/routines/views/routine-execution-picker.test.tsxindex aeb8d6f28d..642eba2483 100644--- a/apps/web/src/features/block-automation/views/routine-execution-picker.test.tsx+++ b/apps/web/src/features/routines/views/routine-execution-picker.test.tsx@@ -221,9 +221,7 @@ describe('routine execution picker', () => {kind: 'agent',agentId: name === 'Researcher' ? managedId : externalId,});- expect(- screen.getByText("Uses the agent's configured default model.")- ).toBeTruthy();+ expect(trigger.textContent).toContain(name);await expectClosed(trigger);});diff --git a/apps/web/src/features/block-automation/views/routine-execution-picker.tsx b/apps/web/src/features/routines/views/routine-execution-picker.tsxsimilarity index 93%rename from apps/web/src/features/block-automation/views/routine-execution-picker.tsxrename to apps/web/src/features/routines/views/routine-execution-picker.tsxindex 884dc1c3e6..9b8d2df3cd 100644--- a/apps/web/src/features/block-automation/views/routine-execution-picker.tsx+++ b/apps/web/src/features/routines/views/routine-execution-picker.tsx@@ -1,3 +1,4 @@+import { badgeTriggerClasses } from '@ui';import {type Accessor,ErrorBoundary,@@ -116,8 +117,17 @@ export function RoutineExecutionPickerView(props: Props): JSX.Element {}return (- <div role="group" aria-label="Routine model or agent" class="min-w-0">+ <div+ role="group"+ aria-label="Routine model or agent"+ class="min-w-0 max-w-full"+ ><AgentPicker+ triggerClass={badgeTriggerClasses({+ variant: 'outline',+ size: 'sm',+ class: 'max-w-full text-ink-muted',+ })}agents={props.roster}selected={selected()}modelOverride={model()}@@ -131,11 +141,6 @@ export function RoutineExecutionPickerView(props: Props): JSX.Element {{savedSelection(props.target)}</p></Show>- <Show when={props.target.kind === 'agent' && !model()}>- <p class="text-xs text-ink-muted">- Uses the agent's configured default model.- </p>- </Show><Show when={warning()}>{(message) => (<p role="status" class="text-xs text-ink-muted">diff --git a/apps/web/src/features/block-automation/views/routine-history.test.tsx b/apps/web/src/features/routines/views/routine-history.test.tsxsimilarity index 52%rename from apps/web/src/features/block-automation/views/routine-history.test.tsxrename to apps/web/src/features/routines/views/routine-history.test.tsxindex d3170d9787..8e535830ce 100644--- a/apps/web/src/features/block-automation/views/routine-history.test.tsx+++ b/apps/web/src/features/routines/views/routine-history.test.tsx@@ -1,6 +1,14 @@-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { createResource, createSignal, Suspense } from 'solid-js';+import type { AgentSessionEntity, ChatEntity } from '@entity';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ within,+} from '@solidjs/testing-library';+import { createResource, createSignal, type JSX, Suspense } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';+import { toHistoryRecord } from '../queries/run-resource';import {type HistoryMetadata,type HistoryRecord,@@ -12,51 +20,78 @@ vi.mock('@core/component/EntityIcon', () => ({<span data-icon={props.targetType} />),}));-vi.mock('@entity', () => ({ formatDateAndTime: (value: string) => value }));+vi.mock('@entity', () => ({+ formatDateAndTime: (value: string) => value,+ ListLayoutProvider: (props: { children: JSX.Element }) => props.children,+ ListEntity: (props: {+ entity: AgentSessionEntity | ChatEntity;+ leadingAction: JSX.Element;+ onClick: JSX.EventHandler<HTMLButtonElement, MouseEvent>;+ }) => (+ <button data-entity-type={props.entity.type} onClick={props.onClick}>+ {props.entity.name}+ {props.leadingAction}+ <time>{String(props.entity.sortTs ?? '')}</time>+ </button>+ ),+}));vi.mock('@ui', () => ({cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props} />+ ),}));afterEach(cleanup);function record(type: 'chat' | 'agent',id: string,- overrides: Partial<HistoryRecord> = {}+ overrides: Partial<Parameters<typeof toHistoryRecord>[0]> = {}): HistoryRecord {- return {+ return toHistoryRecord({id: `run-${id}`,resource_id: id,result: { version: 1, resource: { type, id } },start_time: id,is_success: true,...overrides,+ });+}+function entity(+ type: 'chat' | 'agent',+ id: string,+ name: string+): ChatEntity | AgentSessionEntity {+ const base = {+ id,+ name,+ ownerId: 'owner',+ updatedAt: '2026-10-05T12:00:00Z',};+ return type === 'agent'+ ? { ...base, type: 'agent_session', botId: 'bot', status: 'idle' }+ : { ...base, type: 'chat' };}-function sources() {return {createChatMetadata: vi.fn((id: string) => (): HistoryMetadata => ({status: 'ready',- name: `Chat ${id}`,+ entity: entity('chat', id, `Chat ${id}`),})),createAgentMetadata: vi.fn((id: string) => (): HistoryMetadata => ({status: 'ready',- name: `Agent ${id}`,+ entity: entity('agent', id, `Agent ${id}`),})),onOpen: vi.fn(),};}-function row(name: string): HTMLButtonElement {- return screen.getByRole('button', { name });-}-describe('routine history', () => {- it('resolves mixed and legacy history from each result, not resource_id or current target', () => {+ it('uses Soup entities and resolves agent and legacy resources from each result', () => {const source = sources();render(() => (<RoutineHistory@@ -79,9 +114,16 @@ describe('routine history', () => {['legacy-error'],]);expect(source.createAgentMetadata.mock.calls).toEqual([['session']]);- fireEvent.click(screen.getByText('Chat chat'));- fireEvent.click(screen.getByText('Agent session'), { shiftKey: true });- fireEvent.click(screen.getByText('Chat legacy-error'), { shiftKey: true });+ const session = screen.getByRole('listitem', { name: 'Agent session' });+ expect(+ session.querySelector('[data-entity-type="agent_session"]')+ ).not.toBeNull();+ fireEvent.click(screen.getByRole('button', { name: /^Chat chat/ }));+ fireEvent.keyDown(session, { key: 'Enter', shiftKey: true });+ fireEvent.click(+ screen.getByRole('button', { name: /^Chat legacy-error/ }),+ { shiftKey: true }+ );expect(source.onOpen.mock.calls).toEqual([[{ type: 'chat', id: 'chat' }, false],[{ type: 'agent', id: 'session' }, true],@@ -89,32 +131,41 @@ describe('routine history', () => {]);});- it('preserves neutral synthetic rows and marks only persisted unsuccessful runs as failures', () => {+ it('keeps live runs neutral, shows failures, and includes execution duration', () => {render(() => (<RoutineHistory{...sources()}isPending={false}records={[- record('agent', 'pending-agent', {- id: undefined,- is_success: false,+ record('agent', 'pending', { id: undefined, is_success: false }),+ record('agent', 'failed', { is_success: false }),+ record('agent', 'success', {+ start_time: '2026-10-04T12:00:00Z',+ end_time: '2026-10-04T12:01:12Z',}),- record('chat', 'pending-chat', { id: null, is_success: false }),- record('agent', 'failed-agent', { is_success: false }),- record('chat', 'success'),]}/>));- for (const id of ['pending-agent', 'pending-chat', 'success']) {- expect(- screen.getByText(id).classList.contains('text-ink-extra-muted')- ).toBe(true);- }expect(- screen.getByText('failed-agent').classList.contains('text-failure')+ within(screen.getByRole('listitem', { name: 'Agent pending' }))+ .getByText('Running')+ .classList.contains('text-failure')+ ).toBe(false);+ expect(+ within(screen.getByRole('listitem', { name: 'Agent failed' }))+ .getByText('Failed')+ .classList.contains('text-failure')).toBe(true);- fireEvent.click(screen.getByText('Agent pending-agent'));- expect(row('Agent pending-agent pending-agent').disabled).toBe(false);+ expect(+ within(screen.getByRole('listitem', { name: 'Agent success' })).getByText(+ '1m 12s'+ )+ ).toBeTruthy();+ expect(+ within(screen.getByRole('listitem', { name: 'Agent success' })).getByText(+ '2026-10-04T12:00:00Z'+ )+ ).toBeTruthy();});it.each([@@ -133,7 +184,7 @@ describe('routine history', () => {},{ result: undefined, resource_id: 'unsafe' },])(- 'renders missing/unknown resources without queries or links: %j',+ 'keeps unavailable resources visible without queries or navigation: %j',(invalid) => {const source = sources();render(() => (@@ -145,18 +196,16 @@ describe('routine history', () => {]}/>));- expect(row('Run unavailable missing').disabled).toBe(true);fireEvent.click(screen.getByText('Run unavailable'));+ expect(screen.queryByRole('button')).toBeNull();expect(source.onOpen).not.toHaveBeenCalled();expect(source.createChatMetadata).not.toHaveBeenCalled();expect(source.createAgentMetadata).not.toHaveBeenCalled();- expect(- screen.getByText('missing').classList.contains('text-failure')- ).toBe(true);+ expect(screen.getByText('Failed')).toBeTruthy();});- it('isolates metadata loading, unavailable resources, and empty titles', () => {+ it('isolates loading and unavailable metadata while retaining other sessions', () => {const source = sources();const [metadata, setMetadata] = createSignal<HistoryMetadata>({status: 'pending',@@ -169,21 +218,23 @@ describe('routine history', () => {records={[record('agent', 'session'), record('chat', 'ready')]}/>));- expect(row('Loading… session').disabled).toBe(true);- expect(row('Chat ready ready').disabled).toBe(false);+ expect(screen.getByText('Loading…')).toBeTruthy();+ expect(screen.getByRole('listitem', { name: 'Chat ready' })).toBeTruthy();setMetadata({ status: 'unavailable' });- expect(row('Run unavailable session').disabled).toBe(true);fireEvent.click(screen.getByText('Run unavailable'));expect(source.onOpen).not.toHaveBeenCalled();- setMetadata({ status: 'ready', name: ' ' });- expect(row('Untitled run session').disabled).toBe(false);+ setMetadata({ status: 'ready', entity: entity('agent', 'session', ' ') });+ expect(screen.getByRole('listitem', { name: 'Untitled run' })).toBeTruthy();});- it('catches a suspending metadata source at the row rather than detaching siblings', () => {+ it('catches suspending metadata at the row without detaching siblings', () => {const source = sources();source.createAgentMetadata.mockImplementation(() => {const [name] = createResource(() => new Promise<string>(() => {}));- return () => ({ status: 'ready', name: name() ?? '' });+ return () => ({+ status: 'ready',+ entity: entity('agent', 'session', name() ?? ''),+ });});render(() => (<Suspense fallback={<div>Outer loading</div>}>@@ -197,26 +248,26 @@ describe('routine history', () => {));expect(screen.queryByText('Outer loading')).toBeNull();expect(screen.getByText('Editor')).toBeTruthy();- expect(row('Loading… session').disabled).toBe(true);- expect(row('Chat ready ready').disabled).toBe(false);+ expect(screen.getByText('Loading…')).toBeTruthy();+ expect(screen.getByRole('listitem', { name: 'Chat ready' })).toBeTruthy();});- it('replaces a resource with the correct metadata source when a row changes', () => {+ it('replaces a resource with the correct metadata source when records change', () => {const source = sources();const [records, setRecords] = createSignal([record('chat', 'first')]);render(() => (<RoutineHistory {...source} records={records()} isPending={false} />));setRecords([record('agent', 'second')]);- expect(screen.queryByText('Chat first')).toBeNull();- fireEvent.click(screen.getByText('Agent second'));+ expect(screen.queryByRole('listitem', { name: 'Chat first' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: /^Agent second/ }));expect(source.onOpen).toHaveBeenCalledWith({ type: 'agent', id: 'second' },false);});- it('keeps loading/empty states and the 50-row limit', () => {+ it('loads bounded pages without fetching hidden sessions', () => {const source = sources();const [pending, setPending] = createSignal(true);const [records, setRecords] = createSignal<HistoryRecord[]>([]);@@ -227,9 +278,13 @@ describe('routine history', () => {setPending(false);expect(screen.getByText('No runs yet.')).toBeTruthy();setRecords(- Array.from({ length: 51 }, (_, index) => record('chat', String(index)))+ Array.from({ length: 51 }, (_, index) => record('agent', String(index))));- expect(screen.getAllByRole('button')).toHaveLength(50);- expect(source.createChatMetadata).toHaveBeenCalledTimes(50);+ expect(screen.getAllByRole('listitem')).toHaveLength(50);+ expect(source.createAgentMetadata).toHaveBeenCalledTimes(50);+ fireEvent.click(screen.getByRole('button', { name: 'Load more runs' }));+ expect(source.createAgentMetadata).toHaveBeenCalledTimes(51);+ expect(screen.getAllByRole('listitem')).toHaveLength(51);+ expect(screen.queryByText('Load more runs')).toBeNull();});});diff --git a/apps/web/src/features/routines/views/routine-history.tsx b/apps/web/src/features/routines/views/routine-history.tsxnew file mode 100644index 0000000000..539efe39b0--- /dev/null+++ b/apps/web/src/features/routines/views/routine-history.tsx@@ -0,0 +1,234 @@+import { EntityIcon } from '@core/component/EntityIcon';+import { formatDateAndTime, ListEntity, ListLayoutProvider } from '@entity';+import { Button, cn } from '@ui';+import {+ type Accessor,+ createMemo,+ createSignal,+ For,+ type JSX,+ Show,+ Suspense,+} from 'solid-js';++import type { HistoryRecord, HistoryResource } from '../core/history';++export type { HistoryRecord } from '../core/history';++import type { HistoryMetadata } from '../context/history';++export type { HistoryMetadata } from '../context/history';++type RoutineHistoryProps = {+ records: readonly HistoryRecord[];+ isPending: boolean;+ createChatMetadata: (id: string) => Accessor<HistoryMetadata>;+ createAgentMetadata: (id: string) => Accessor<HistoryMetadata>;+ onOpen: (resource: HistoryResource, newSplit: boolean) => void;+};++type HistoryRowProps = {+ record: HistoryRecord;+ resource?: HistoryResource;+ metadata: HistoryMetadata;+ onOpen?: (resource: HistoryResource, newSplit: boolean) => void;+};++function RunOutcome(props: { record: HistoryRecord }) {+ const outcome = () =>+ !props.record.id+ ? 'Running'+ : props.record.success+ ? 'Succeeded'+ : 'Failed';+ const duration = () => {+ if (!props.record.startedAt || !props.record.endedAt) return undefined;+ const seconds = Math.max(+ 0,+ Math.round(+ (Date.parse(props.record.endedAt) -+ Date.parse(props.record.startedAt)) /+ 1000+ )+ );+ if (!Number.isFinite(seconds)) return undefined;+ return seconds < 60+ ? `${seconds}s`+ : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;+ };+ return (+ <span class="inline-flex items-center gap-3 whitespace-nowrap text-xs text-ink-muted">+ <span class={cn(outcome() === 'Failed' && 'text-failure')}>+ {outcome()}+ </span>+ <Show when={duration()}>+ {(value) => (+ <span class="tabular-nums text-ink-extra-muted">{value()}</span>+ )}+ </Show>+ </span>+ );+}++function HistoryRow(props: HistoryRowProps): JSX.Element {+ const entity = () => {+ const metadata = props.metadata;+ return metadata.status === 'ready'+ ? {+ ...metadata.entity,+ name: metadata.entity.name.trim() || 'Untitled run',+ sortTs: props.record.startedAt ?? metadata.entity.sortTs,+ }+ : undefined;+ };+ const open = (newSplit: boolean) => {+ if (props.resource && entity()) props.onOpen?.(props.resource, newSplit);+ };+ return (+ <Show+ when={entity()}+ fallback={+ <div+ role="listitem"+ class="soup-list-entity mx-1 flex min-h-11 items-center gap-2 rounded-xl px-2 text-sm text-ink-muted"+ >+ <span class="size-4 shrink-0">+ <EntityIcon+ targetType={props.resource?.type ?? 'routine'}+ size="xs"+ />+ </span>+ <span class="min-w-0 flex-1 truncate">+ {props.metadata.status === 'pending'+ ? 'Loading…'+ : 'Run unavailable'}+ </span>+ <RunOutcome record={props.record} />+ <span class="ml-2 text-xs text-ink-extra-muted">+ {props.record.startedAt+ ? formatDateAndTime(props.record.startedAt)+ : '—'}+ </span>+ </div>+ }+ >+ {(entity) => (+ <div+ role="listitem"+ tabIndex={0}+ aria-label={entity().name}+ class="outline-none focus-visible:bg-list-highlighted"+ onKeyDown={(event) => {+ if (event.key !== 'Enter') return;+ event.preventDefault();+ open(event.shiftKey);+ }}+ >+ <ListEntity+ entity={entity()}+ hideCheckbox+ deferInteractions+ leadingAction={<RunOutcome record={props.record} />}+ onClick={(event) => open(event.shiftKey)}+ />+ </div>+ )}+ </Show>+ );+}++function ResourceHistoryRow(props: {+ record: HistoryRecord;+ resource: HistoryResource;+ createMetadata: (id: string) => Accessor<HistoryMetadata>;+ onOpen: RoutineHistoryProps['onOpen'];+}): JSX.Element {+ const metadata = props.createMetadata(props.resource.id);+ return (+ <HistoryRow+ record={props.record}+ resource={props.resource}+ metadata={metadata()}+ onOpen={props.onOpen}+ />+ );+}++function ResolvedHistoryRow(props: {+ record: HistoryRecord;+ history: RoutineHistoryProps;+}): JSX.Element {+ const resource = createMemo(() => props.record.resource);+ return (+ <Show+ when={resource()}+ keyed+ fallback={+ <HistoryRow+ record={props.record}+ metadata={{ status: 'unavailable' }}+ />+ }+ >+ {(target) => (+ <Suspense+ fallback={+ <HistoryRow+ record={props.record}+ resource={target}+ metadata={{ status: 'pending' }}+ />+ }+ >+ <ResourceHistoryRow+ record={props.record}+ resource={target}+ createMetadata={+ target.type === 'chat'+ ? props.history.createChatMetadata+ : props.history.createAgentMetadata+ }+ onOpen={props.history.onOpen}+ />+ </Suspense>+ )}+ </Show>+ );+}++export function RoutineHistory(props: RoutineHistoryProps): JSX.Element {+ const [visibleCount, setVisibleCount] = createSignal(50);+ const [listElement, setListElement] = createSignal<HTMLDivElement>();+ return (+ <div ref={setListElement} class="min-h-0 flex-1 overflow-y-auto py-3">+ <Show+ when={props.records.length > 0}+ fallback={+ <div+ role="status"+ class="px-4 py-16 text-center text-sm text-ink-muted"+ >+ {props.isPending ? 'Loading…' : 'No runs yet.'}+ </div>+ }+ >+ <ListLayoutProvider ref={listElement}>+ <div role="list" aria-label="Routine runs">+ <For each={props.records.slice(0, visibleCount())}>+ {(record) => (+ <ResolvedHistoryRow record={record} history={props} />+ )}+ </For>+ </div>+ </ListLayoutProvider>+ <Show when={props.records.length > visibleCount()}>+ <div class="flex justify-center p-3">+ <Button onClick={() => setVisibleCount((count) => count + 50)}>+ Load more runs+ </Button>+ </div>+ </Show>+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/routines/views/routines-list.tsx b/apps/web/src/features/routines/views/routines-list.tsxnew file mode 100644index 0000000000..5a243d95a0--- /dev/null+++ b/apps/web/src/features/routines/views/routines-list.tsx@@ -0,0 +1,29 @@+import type { Accessor } from 'solid-js';+import { RoutinesList } from '../components/routines-list';+import type { RoutineListSource } from '../context/routine-sources';+import type { RoutineTarget } from '../core/routine-target';+import { createRoutineRows } from '../primitives/routines-list';++export function RoutinesListView(props: {+ source: RoutineListSource;+ userId: Accessor<string | undefined>;+ targetLabel(target: RoutineTarget): string;+ searchRef(input: HTMLInputElement): void;+ onCreate(): void;+ onOpen(id: string): void;+}) {+ const rows = createRoutineRows(props.source, props.userId, props.targetLabel);+ return (+ <RoutinesList+ searchRef={props.searchRef}+ rows={rows()}+ loading={props.source.loading()}+ error={props.source.error()}+ onRetry={() => void props.source.refresh()}+ onCreate={props.onCreate}+ onOpen={props.onOpen}+ pendingId={props.source.pendingId()}+ onToggle={(row) => props.source.setEnabled(row.id, !row.enabled)}+ />+ );+}diff --git a/apps/web/src/lib/constants/block-registry.ts b/apps/web/src/lib/constants/block-registry.tsindex 6f07f8c84c..1886929704 100644--- a/apps/web/src/lib/constants/block-registry.ts+++ b/apps/web/src/lib/constants/block-registry.ts@@ -20,7 +20,7 @@ export const BlockRegistry = ['email','contact','company',- 'automation',+ 'routine','pr','agent',// A task project (`project` is a folder).diff --git a/apps/web/src/lib/core/block.ts b/apps/web/src/lib/core/block.tsindex 34c1c7d02c..e199a92f7c 100644--- a/apps/web/src/lib/core/block.ts+++ b/apps/web/src/lib/core/block.ts@@ -79,7 +79,7 @@ export const NonDocumentBlockTypes = ['email','contact','company',- 'automation',+ 'routine','pr','agent','initiative',@@ -140,7 +140,7 @@ const _ValidBlockCombinations: BlockCombinationRules = {task: allBlockNames,snippet: allBlockNames,skill: allBlockNames,- automation: allBlockNames,+ routine: allBlockNames,csv: allBlockNames,pr: allBlockNames,agent: allBlockNames,@@ -171,7 +171,7 @@ export const ValidNestingCombinations: BlockCombinationRules = {task: new Set([]),snippet: new Set([]),skill: new Set([]),- automation: new Set([]),+ routine: new Set([]),csv: new Set([]),pr: new Set([]),agent: new Set([]),diff --git a/apps/web/src/lib/core/blockMethodRegistry.ts b/apps/web/src/lib/core/blockMethodRegistry.tsindex 515c88bf30..03cb003a6d 100644--- a/apps/web/src/lib/core/blockMethodRegistry.ts+++ b/apps/web/src/lib/core/blockMethodRegistry.ts@@ -40,7 +40,7 @@ export interface BlockMethodRegistry {color: EmptySpec;component: EmptySpec;task: EmptySpec;- automation: EmptySpec;+ routine: EmptySpec;pr: EmptySpec;agent: EmptySpec;initiative: EmptySpec;diff --git a/apps/web/src/lib/core/collab-surface/blockParent.ts b/apps/web/src/lib/core/collab-surface/blockParent.tsindex 3d19aa6126..bc1f0ee64d 100644--- a/apps/web/src/lib/core/collab-surface/blockParent.ts+++ b/apps/web/src/lib/core/collab-surface/blockParent.ts@@ -11,7 +11,7 @@ import type { CollabSurfaceParent } from './createCollabSurface';* friends, incl. task/snippet/skill aliases) are `Document` rows; the rest map* to their own entity type.*- * Absent entries (contact, company, automation, pr, unknown) have no+ * Absent entries (contact, company, routine, pr, unknown) have no* backend-supported parent type — a collab surface cannot be hosted in them.*/const BLOCK_PARENT_TYPE: Partial<diff --git a/apps/web/src/lib/core/component/AI/component/tool/Routines.tsx b/apps/web/src/lib/core/component/AI/component/tool/Routines.tsxnew file mode 100644index 0000000000..60748918e8--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/Routines.tsx@@ -0,0 +1,90 @@+import { invalidateSchedules } from '@app/features/routines/queries/schedules';+import Clock from '@phosphor-icons/core/regular/clock.svg';+import { createSignal } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer, type RenderContext } from './ToolRenderer';++function RoutineResult(props: {+ label: string;+ summary?: string;+ result: unknown;+ renderContext: RenderContext['renderContext'];+}) {+ const [expanded, setExpanded] = createSignal(false);+ return (+ <BaseTool+ icon={Clock}+ renderContext={props.renderContext}+ type="call"+ response={+ expanded() && props.result !== undefined ? (+ <pre class="max-h-72 overflow-auto whitespace-pre-wrap break-words p-3 text-xs">+ {JSON.stringify(props.result, null, 2)}+ </pre>+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">+ <span class="min-w-0 truncate">{props.label}</span>+ <Tool.ResultToggle+ expanded={expanded()}+ onToggle={() => setExpanded(!expanded())}+ showToggle={props.result !== undefined}+ status={props.summary}+ />+ </div>+ </BaseTool>+ );+}++export const createRoutineHandler = createToolRenderer({+ name: 'CreateRoutine',+ handleResponse: async () => {+ await invalidateSchedules();+ },+ render: (ctx) => (+ <RoutineResult+ label={ctx.response ? 'Created routine' : 'Create routine'}+ summary={ctx.response?.data.name ?? ctx.tool.data.configuration.name}+ result={ctx.response?.data}+ renderContext={ctx.renderContext}+ />+ ),+});+export const listRoutinesHandler = createToolRenderer({+ name: 'ListRoutines',+ render: (ctx) => (+ <RoutineResult+ label="Read routines"+ summary={ctx.response ? `${ctx.response.data.total} routines` : undefined}+ result={ctx.response?.data}+ renderContext={ctx.renderContext}+ />+ ),+});+export const readRoutineHandler = createToolRenderer({+ name: 'ReadRoutine',+ render: (ctx) => (+ <RoutineResult+ label="Read routine and runs"+ summary={ctx.response?.data.routine.name}+ result={ctx.response?.data}+ renderContext={ctx.renderContext}+ />+ ),+});+export const updateRoutineHandler = createToolRenderer({+ name: 'UpdateRoutine',+ handleResponse: async () => {+ await invalidateSchedules();+ },+ render: (ctx) => (+ <RoutineResult+ label={ctx.response ? 'Updated routine' : 'Update routine'}+ summary={ctx.response?.data.name}+ result={ctx.response?.data}+ renderContext={ctx.renderContext}+ />+ ),+});diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsxindex 22fe431626..440155f90e 100644--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx@@ -101,6 +101,12 @@ import {updateReminderHandler,} from './Reminders';import { renameDocumentHandler } from './RenameDocument';+import {+ createRoutineHandler,+ listRoutinesHandler,+ readRoutineHandler,+ updateRoutineHandler,+} from './Routines';import { contentSearchHandler, nameSearchHandler } from './Search';import { listSkillsHandler, searchSkillsHandler } from './SearchSkills';import { searchToolsHandler } from './SearchTools';@@ -171,6 +177,10 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {ManageChannelParticipants: manageChannelParticipantsHandler,ListNotifications: listNotificationsHandler,ListReminders: listRemindersHandler,+ CreateRoutine: createRoutineHandler,+ ListRoutines: listRoutinesHandler,+ ReadRoutine: readRoutineHandler,+ UpdateRoutine: updateRoutineHandler,ListTags: listTagsHandler,ListTeamMembers: listTeamMembersHandler,LoadTools: loadToolsHandler,diff --git a/apps/web/src/lib/core/component/EntityIcon.test.tsx b/apps/web/src/lib/core/component/EntityIcon.test.tsxindex 85db4243dd..e51733d10e 100644--- a/apps/web/src/lib/core/component/EntityIcon.test.tsx+++ b/apps/web/src/lib/core/component/EntityIcon.test.tsx@@ -6,7 +6,7 @@ import SkillIcon from '@phosphor/blueprint.svg';import SnippetIcon from '@phosphor/brackets-curly.svg';import CompanyIcon from '@phosphor/building-office.svg';import CalendarIcon from '@phosphor/calendar.svg';-import AutomationIcon from '@phosphor/clock-clockwise.svg';+import RoutineIcon from '@phosphor/clock-clockwise.svg';import DatabaseIcon from '@phosphor/database.svg';import EnvelopeIcon from '@phosphor/envelope.svg';import EnvelopeOpenIcon from '@phosphor/envelope-open.svg';@@ -105,7 +105,7 @@ const entityGlyphs: ['task',],['call', { type: 'call' }, PhoneIcon],- ['automation', { type: 'automation' }, AutomationIcon],+ ['routine', { type: 'routine' }, RoutineIcon],['GitHub pull request',{ type: 'foreign', foreignSource: 'github_pull_request' },@@ -119,6 +119,11 @@ const entityGlyphs: [afterEach(cleanup);describe('entity glyphs', () => {+ it('keeps the routine icon and label for saved mentions using the old block name', () => {+ expect(getIconConfig('automation')).toEqual(getIconConfig('routine'));+ expect(getIconConfig('automation').icon).toBe(RoutineIcon);+ });+beforeEach(() => {vi.mocked(itemToBlockName).mockReset();});diff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsxindex 7244a7388c..bea33fa2ae 100644--- a/apps/web/src/lib/core/component/EntityIcon.tsx+++ b/apps/web/src/lib/core/component/EntityIcon.tsx@@ -427,12 +427,12 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {background: 'bg-chat/20',prettyName: 'Skill',},- automation: {+ routine: {icon: ClockClockwise,boldIcon: ClockClockwiseBold,foreground: 'text-chat',background: 'bg-chat/20',- prettyName: 'Automation',+ prettyName: 'Routine',},crm_company: {icon: BuildingOffice,@@ -469,6 +469,7 @@ export function isArchiveType(ext: string): boolean {}function validateEntity(entity: string): EntityWithValidIcon {+ if (entity === 'automation') return 'routine';if (entity in ENTITY_ICON_CONFIGS) {return entity as EntityWithValidIcon;} else if (isBlockAlias(entity)) {@@ -651,7 +652,7 @@ export function getEntityIconType(entity: EntityIconData): EntityWithValidIcon {: 'reminder').with({ type: 'call' }, () => 'call')- .with({ type: 'automation' }, () => 'automation')+ .with({ type: 'routine' }, () => 'routine').with({ type: 'foreign' }, (e) => {if (e.foreignSource !== 'github_pull_request') return 'default';return match<unknown, EntityWithValidIcon>(e.metadata?.status)diff --git a/apps/web/src/lib/core/component/FileList/constants.tsx b/apps/web/src/lib/core/component/FileList/constants.tsxindex 239a66f4a4..6c81ec8a7b 100644--- a/apps/web/src/lib/core/component/FileList/constants.tsx+++ b/apps/web/src/lib/core/component/FileList/constants.tsx@@ -81,7 +81,7 @@ const _fileTypeColors: Record<BlockName | BlockAlias | 'default', string> = {task: defaultFileColor,snippet: 'bg-snippet/20 group/item',skill: 'bg-chat/20 group/item',- automation: 'bg-chat/20 group/item',+ routine: 'bg-chat/20 group/item',pr: defaultFileColor,agent: defaultFileColor,initiative: defaultFileColor,diff --git a/apps/web/src/lib/core/component/FileList/itemOperations.ts b/apps/web/src/lib/core/component/FileList/itemOperations.tsindex 56c9ce1bc3..97e912c919 100644--- a/apps/web/src/lib/core/component/FileList/itemOperations.ts+++ b/apps/web/src/lib/core/component/FileList/itemOperations.ts@@ -196,7 +196,7 @@ export async function deleteItem(args: {itemType === 'channel' ||itemType === 'email' ||itemType === 'channel_message' ||- itemType === 'automation' ||+ itemType === 'routine' ||itemType === 'call' ||itemType === 'foreign')diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex f41ebb95ec..1d22db0b15 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -151,7 +151,7 @@ export type ItemMention = {| 'initiative'| 'foreign'| 'group'- | 'automation'+ | 'routine'| 'crm_company'| 'crm_contact'| 'skill';@@ -330,7 +330,7 @@ const getDocumentMentionItemType = (.with('initiative', () => 'initiative').with('channel_message', () => 'channel').with('channel_thread', () => 'channel')- .with('automation', () => 'automation')+ .with('routine', () => 'routine').with('call', () => 'call').with('calendar_event', () => 'calendar_event').with('foreign', () => {diff --git a/apps/web/src/lib/core/constant/allBlocks.test.ts b/apps/web/src/lib/core/constant/allBlocks.test.tsindex 65979d6b53..a686d0a6f2 100644--- a/apps/web/src/lib/core/constant/allBlocks.test.ts+++ b/apps/web/src/lib/core/constant/allBlocks.test.ts@@ -1,24 +1,65 @@import { BlockRegistry } from '@core/block';-import { describe, expect, it } from 'vitest';+import { createHeadlessEditor } from '@lexical/headless';+import { DocumentMentionNode } from '@macro-inc/lexical-core';+import { describe, expect, it, vi } from 'vitest';+import { fileTypeToBlockName, verifyBlockName } from './allBlocks';-const definitionFiles = import.meta.glob(- '../../../features/block-*/definition.ts',- {- eager: true,- import: 'default',- query: '?raw',- }-);+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));++const definitionFiles = import.meta.glob('../../../features/*/definition.ts', {+ eager: true,+ import: 'default',+ query: '?raw',+});describe('block definition discovery', () => {it('has one definition file for every block', () => {- const discoveredNames = Object.keys(definitionFiles).map((path) =>- path- .split('/')- .at(-2)- ?.replace(/^block-/, '')+ const discoveredNames = Object.values(definitionFiles).map(+ (source) => String(source).match(/\bname:\s*['"]([^'"]+)['"]/)?.[1]);expect(discoveredNames.sort()).toEqual([...BlockRegistry].sort());});});++it.each(['routine', 'automation'])(+ 'reads stored %s mention nodes as routines without changing their serialization',+ (blockName) => {+ const editor = createHeadlessEditor({ nodes: [DocumentMentionNode] });+ editor.update(+ () => {+ const serialized = {+ type: 'document-mention',+ version: 2,+ documentId: 'routine-1',+ documentName: 'Review tasks',+ blockName,+ blockParams: {},+ };+ const node = DocumentMentionNode.importJSON(serialized);+ expect(verifyBlockName(node.getBlockName())).toBe('routine');+ expect(fileTypeToBlockName(node.getBlockName())).toBe('routine');+ expect(node.exportJSON()).toMatchObject(serialized);+ const element = node.exportDOM().element;+ const conversion = DocumentMentionNode.importDOM()+ ?.span(element)+ ?.conversion(element);+ expect(conversion?.node).toBeInstanceOf(DocumentMentionNode);+ if (!(conversion?.node instanceof DocumentMentionNode))+ throw new Error('Missing mention');+ expect(verifyBlockName(conversion.node.getBlockName())).toBe('routine');+ expect(conversion.node.exportJSON()).toMatchObject(serialized);+ },+ { discrete: true }+ );+ }+);diff --git a/apps/web/src/lib/core/constant/allBlocks.ts b/apps/web/src/lib/core/constant/allBlocks.tsindex 115e08673a..69b329fa71 100644--- a/apps/web/src/lib/core/constant/allBlocks.ts+++ b/apps/web/src/lib/core/constant/allBlocks.ts@@ -18,7 +18,7 @@ import {import { DefaultFilename } from './filename';const discoveredBlockDefinitions = Object.values<AnyBlockDefinition>(- import.meta.glob('../../../features/block-*/definition.ts', {+ import.meta.glob('../../../features/*/definition.ts', {eager: true,import: 'definition',})@@ -187,6 +187,7 @@ export function fileTypeToBlockName(if (blockOrFiletype === 'channel_message') return 'channel';if (blockOrFiletype === 'agent_session') return 'agent';if (blockOrFiletype === 'calendar_event') return 'calendar';+ if (blockOrFiletype === 'automation') return 'routine';// CRM entity types map to their dedicated blocks (entity type !== block name).if (blockOrFiletype === 'crm_company') return 'company';@@ -331,6 +332,7 @@ export function verifyBlockName(name: string | undefined): BlockName | BlockAlias {if (!name) return 'unknown';+ if (name === 'automation') return 'routine';if (name === 'write') {if (isFeatureEnabled(enableDocxEditor)) return 'write';if (ENABLE_DOCX_TO_PDF) return 'pdf';diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx b/apps/web/src/lib/core/constant/settingsTabsConfig.tsxindex a7869b8c48..3b4420f292 100644--- a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx@@ -172,7 +172,7 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [tab: 'Bots',label: 'Bots',icon: BotIcon,- keywords: ['automation', 'bot'],+ keywords: ['routine', 'bot'],},],},diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.tsindex 4e1858f0ba..1c39774693 100644--- a/apps/web/src/lib/core/hotkey/tokens.ts+++ b/apps/web/src/lib/core/hotkey/tokens.ts@@ -296,7 +296,7 @@ export const TOKENS = {initiative: 'create.initiative',snippet: 'create.snippet',snippetNewSplit: 'create.snippetNewSplit',- automation: 'create.automation',+ routine: 'create.routine',skill: 'create.skill',reminder: 'create.reminder',agent: 'create.agent',diff --git a/apps/web/src/lib/core/internal/trackBlockOpened.ts b/apps/web/src/lib/core/internal/trackBlockOpened.tsindex 345d4d68a9..19ba4c9930 100644--- a/apps/web/src/lib/core/internal/trackBlockOpened.ts+++ b/apps/web/src/lib/core/internal/trackBlockOpened.ts@@ -24,7 +24,7 @@ function isSoupEntityTag('email','channel_message','channel_thread',- 'automation',+ 'routine','agent_session','database','calendar_event',diff --git a/apps/web/src/lib/core/types/index.ts b/apps/web/src/lib/core/types/index.tsindex 5b59f10a15..b5287b17dd 100644--- a/apps/web/src/lib/core/types/index.ts+++ b/apps/web/src/lib/core/types/index.ts@@ -5,7 +5,7 @@ export const EntityType = {...BaseEntityType,email: 'email',channel_message: 'channel_message',- automation: 'automation',+ routine: 'routine',channel_thread: 'channel_thread',} as const;diff --git a/apps/web/src/lib/core/util/cron.ts b/apps/web/src/lib/core/util/cron.tsindex 5666ae4537..d8ed657b38 100644--- a/apps/web/src/lib/core/util/cron.ts+++ b/apps/web/src/lib/core/util/cron.ts@@ -2,7 +2,7 @@* Cron expressions as the Rust backend reads them.** Shared by every feature that lets someone build a repeating schedule —- * automations and reminders both — so the two cannot drift on what `0 0 9 * * 2`+ * routines and reminders both — so the two cannot drift on what `0 0 9 * * 2`* means. The backend parses these with the `cron` crate, which sets two* conventions worth stating up front:*diff --git a/apps/web/src/lib/core/util/dateSearch/parseTime.ts b/apps/web/src/lib/core/util/dateSearch/parseTime.tsnew file mode 100644index 0000000000..0c80a7688f--- /dev/null+++ b/apps/web/src/lib/core/util/dateSearch/parseTime.ts@@ -0,0 +1,72 @@+export interface ParsedTime {+ hours: number; // 0-23+ minutes: number; // 0-59+}++/**+ * Parse time strings like "9am", "9 AM", "3:30pm", "14:00", "noon", "midnight"+ * Returns the parsed time and the remaining input with the time portion removed.+ */+export function parseTime(+ input: string+): { time: ParsedTime; rest: string } | null {+ const trimmed = input.trim();+ if (!trimmed) return null;++ // "noon"+ if (/^noon$/i.test(trimmed)) {+ return { time: { hours: 12, minutes: 0 }, rest: '' };+ }+ // "midnight"+ if (/^midnight$/i.test(trimmed)) {+ return { time: { hours: 0, minutes: 0 }, rest: '' };+ }++ // Try matching time at end of string: "tomorrow 9am", "feb 17 3:30 PM"+ // Also matches standalone: "9am", "3:30pm", "14:00"+ const timeAtEnd = /^(.*?)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*$/i;+ const time24AtEnd = /^(.*?)\s*(\d{1,2}):(\d{2})\s*$/;++ let match = trimmed.match(timeAtEnd);+ if (match) {+ let hours = parseInt(match[2]);+ const minutes = parseInt(match[3] || '0');+ const meridiem = match[4].toLowerCase();++ if (hours < 1 || hours > 12 || minutes > 59) return null;++ if (meridiem === 'pm' && hours !== 12) hours += 12;+ if (meridiem === 'am' && hours === 12) hours = 0;++ return { time: { hours, minutes }, rest: match[1].trim() };+ }++ // 24-hour format: "14:00", "tomorrow 14:00"+ match = trimmed.match(time24AtEnd);+ if (match) {+ const hours = parseInt(match[2]);+ const minutes = parseInt(match[3]);++ if (hours > 23 || minutes > 59) return null;++ return { time: { hours, minutes }, rest: match[1].trim() };+ }++ // Time at start: "9am tomorrow", "3:30 PM feb 17"+ const timeAtStart = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s+(.+)$/i;+ match = trimmed.match(timeAtStart);+ if (match) {+ let hours = parseInt(match[1]);+ const minutes = parseInt(match[2] || '0');+ const meridiem = match[3].toLowerCase();++ if (hours < 1 || hours > 12 || minutes > 59) return null;++ if (meridiem === 'pm' && hours !== 12) hours += 12;+ if (meridiem === 'am' && hours === 12) hours = 0;++ return { time: { hours, minutes }, rest: match[4].trim() };+ }++ return null;+}diff --git a/apps/web/src/lib/core/util/dateSearch/useDateSearch.test.ts b/apps/web/src/lib/core/util/dateSearch/useDateSearch.test.tsindex 7668728761..fb91f744f9 100644--- a/apps/web/src/lib/core/util/dateSearch/useDateSearch.test.ts+++ b/apps/web/src/lib/core/util/dateSearch/useDateSearch.test.ts@@ -756,6 +756,34 @@ describe('useDateSearch with time', () => {});describe('useDateSearch with defaultTime', () => {+ it.each([+ { defaultTime: { hours: 8, minutes: 0 }, hours: 8, minutes: 0 },+ { defaultTime: { hours: 9, minutes: 0 }, hours: 9, minutes: 0 },+ { defaultTime: undefined, hours: 23, minutes: 59 },+ ])(+ 'preserves preset time for email, reminders, and date properties: $hours:$minutes',+ ({ defaultTime, hours, minutes }) => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date(2026, 9, 5, 7, 30));+ try {+ createRoot((dispose) => {+ const options = useDateSearch({+ query: () => 'in 2 days',+ defaultTime,+ });+ const preset = options().find((option) => option.type === 'preset');+ expect(preset).toBeDefined();+ expect(preset?.date.getDate()).toBe(7);+ expect(preset?.date.getHours()).toBe(hours);+ expect(preset?.date.getMinutes()).toBe(minutes);+ dispose();+ });+ } finally {+ vi.useRealTimers();+ }+ }+ );+// Use a date far in the future so the "past" filter doesn't interfereconst baseDate = new Date('2099-06-15T06:00:00'); // 6 AM so "today" at 8am is still in the futureconst defaultTime = { hours: 8, minutes: 0 };diff --git a/apps/web/src/lib/core/util/dateSearch/useDateSearch.ts b/apps/web/src/lib/core/util/dateSearch/useDateSearch.tsindex 67e48cf14b..e53021aa60 100644--- a/apps/web/src/lib/core/util/dateSearch/useDateSearch.ts+++ b/apps/web/src/lib/core/util/dateSearch/useDateSearch.ts@@ -13,6 +13,7 @@ import {parseDateFromDuration,parseDurationString,} from './dateParser';+import { type ParsedTime, parseTime } from './parseTime';import { searchPresets } from './presets';// Max number of presets to include@@ -46,77 +47,6 @@ const possibleDateFormats = ['dd-MM-yyyy', // "15-01-2024"];-interface ParsedTime {- hours: number; // 0-23- minutes: number; // 0-59-}--/**- * Parse time strings like "9am", "9 AM", "3:30pm", "14:00", "noon", "midnight"- * Returns the parsed time and the remaining input with the time portion removed.- */-function parseTime(input: string): { time: ParsedTime; rest: string } | null {- const trimmed = input.trim();- if (!trimmed) return null;-- // "noon"- if (/^noon$/i.test(trimmed)) {- return { time: { hours: 12, minutes: 0 }, rest: '' };- }- // "midnight"- if (/^midnight$/i.test(trimmed)) {- return { time: { hours: 0, minutes: 0 }, rest: '' };- }-- // Try matching time at end of string: "tomorrow 9am", "feb 17 3:30 PM"- // Also matches standalone: "9am", "3:30pm", "14:00"- const timeAtEnd = /^(.*?)\s*(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*$/i;- const time24AtEnd = /^(.*?)\s*(\d{1,2}):(\d{2})\s*$/;-- let match = trimmed.match(timeAtEnd);- if (match) {- let hours = parseInt(match[2]);- const minutes = parseInt(match[3] || '0');- const meridiem = match[4].toLowerCase();-- if (hours < 1 || hours > 12 || minutes > 59) return null;-- if (meridiem === 'pm' && hours !== 12) hours += 12;- if (meridiem === 'am' && hours === 12) hours = 0;-- return { time: { hours, minutes }, rest: match[1].trim() };- }-- // 24-hour format: "14:00", "tomorrow 14:00"- match = trimmed.match(time24AtEnd);- if (match) {- const hours = parseInt(match[2]);- const minutes = parseInt(match[3]);-- if (hours > 23 || minutes > 59) return null;-- return { time: { hours, minutes }, rest: match[1].trim() };- }-- // Time at start: "9am tomorrow", "3:30 PM feb 17"- const timeAtStart = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s+(.+)$/i;- match = trimmed.match(timeAtStart);- if (match) {- let hours = parseInt(match[1]);- const minutes = parseInt(match[2] || '0');- const meridiem = match[3].toLowerCase();-- if (hours < 1 || hours > 12 || minutes > 59) return null;-- if (meridiem === 'pm' && hours !== 12) hours += 12;- if (meridiem === 'am' && hours === 12) hours = 0;-- return { time: { hours, minutes }, rest: match[4].trim() };- }-- return null;-}-/*** Format a parsed time for display, e.g. "9 AM", "3:30 PM"*/diff --git a/apps/web/src/lib/core/util/url.test.ts b/apps/web/src/lib/core/util/url.test.tsindex b523964a6a..ddd7c061b3 100644--- a/apps/web/src/lib/core/util/url.test.ts+++ b/apps/web/src/lib/core/util/url.test.ts@@ -7,7 +7,17 @@ import {type MockInstance,vi,} from 'vitest';-import { openExternalUrl, registerExternalUrlInterceptor } from './url';+import {+ buildSimpleEntityUrl,+ openExternalUrl,+ registerExternalUrlInterceptor,+} from './url';++it('copies routine links using the canonical route', () => {+ expect(+ new URL(buildSimpleEntityUrl({ type: 'routine', id: 'routine-1' })).pathname+ ).toBe('/app/routines/routine-1');+});describe('openExternalUrl', () => {let openSpy: MockInstance<typeof window.open>;diff --git a/apps/web/src/lib/core/util/url.ts b/apps/web/src/lib/core/util/url.tsindex 32c0b7d00d..7ae63326f3 100644--- a/apps/web/src/lib/core/util/url.ts+++ b/apps/web/src/lib/core/util/url.ts@@ -72,7 +72,8 @@ export function buildSimpleEntityUrl(entity: { type: string; id: string },params?: Record<string, string>): string {- const urlString = `${getWebOrigin()}/app/${entity.type}/${entity.id}`;+ const type = entity.type === 'routine' ? 'routines' : entity.type;+ const urlString = `${getWebOrigin()}/app/${type}/${entity.id}`;const url = new URL(urlString);if (params) {for (const [key, value] of Object.entries(params)) {diff --git a/apps/web/src/lib/design/empty-state-automations.svg b/apps/web/src/lib/design/empty-state-routines.svgsimilarity index 100%rename from apps/web/src/lib/design/empty-state-automations.svgrename to apps/web/src/lib/design/empty-state-routines.svgdiff --git a/apps/web/src/lib/queries/notification/tests/entity-mutations.test.ts b/apps/web/src/lib/queries/notification/tests/entity-mutations.test.tsindex 6257eb980f..04c6e636b7 100644--- a/apps/web/src/lib/queries/notification/tests/entity-mutations.test.ts+++ b/apps/web/src/lib/queries/notification/tests/entity-mutations.test.ts@@ -41,7 +41,7 @@ describe('toNotificationEntityRef', () => {it('has no target for entity types the notification service does not file under', () => {expect(- toNotificationEntityRef({ type: 'automation', id: 'automation-1' })+ toNotificationEntityRef({ type: 'routine', id: 'routine-1' })).toBeUndefined();});});diff --git a/apps/web/src/lib/queries/reminders/reminders.test.ts b/apps/web/src/lib/queries/reminders/reminders.test.tsindex 7cf9aed838..174a79ea22 100644--- a/apps/web/src/lib/queries/reminders/reminders.test.ts+++ b/apps/web/src/lib/queries/reminders/reminders.test.ts@@ -84,7 +84,7 @@ describe('reminderEntityType', () => {it('has no mapping for types a reminder cannot attach to', () => {expect(reminderEntityType('channel_message')).toBeUndefined();expect(reminderEntityType('channel_thread')).toBeUndefined();- expect(reminderEntityType('automation')).toBeUndefined();+ expect(reminderEntityType('routine')).toBeUndefined();});});@@ -113,7 +113,7 @@ describe('reminderTarget', () => {it('is undefined for types with no reminder target', () => {expect(reminderTarget(entity('channel_message'))).toBeUndefined();- expect(reminderTarget(entity('automation'))).toBeUndefined();+ expect(reminderTarget(entity('routine'))).toBeUndefined();});});diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsxindex 611d1d25c0..14baf3b511 100644--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx@@ -48,7 +48,7 @@ import { handleRefreshCalendar } from '../calendar/sync';// Side-effect import: registers the scheduled-action live-update websocket// listener. Must be imported somewhere that always loads on app start — this// provider is guaranteed to mount alongside the other sync handlers.-import '@queries/agent-schedule/sync';+import '@app/features/routines/queries/sync';import {createConnectionWebsocketEffect,parseWebsocketPayload,diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 616fe008ac..8157938811 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -2065,6 +2065,73 @@ export const ToolReminder = z.object({enabled: z.boolean(),});+export const CreateRoutine = z.object({+ configuration: z.object({+ name: z.string(),+ instructions: z.string(),+ target: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ model: z.string(), type: z.literal('model') }),+ z.object({ agentId: z.string().uuid(), type: z.literal('agent') }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ schedule: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({+ at: z.string().datetime({ offset: true }),+ type: z.literal('once'),+ }),+ z.object({+ expression: z.string(),+ timezone: z.string(),+ type: z.literal('cron'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ }),+});++export const RoutineInfo = z.object({+ id: z.string().uuid(),+ name: z.string(),+ enabled: z.boolean(),+ trigger: z.any(),+ task: z.any(),+ nextRunAt: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+});+export const CreateTag = z.object({label: z.string(),color: z.any().superRefine((x, ctx) => {@@ -6204,6 +6271,27 @@ export const ListRemindersResponse = z.object({summary: z.string(),});+export const ListRoutines = z.object({+ query: z.union([z.string(), z.null()]).optional(),+ enabled: z.union([z.boolean(), z.null()]).optional(),+});++export const RoutineList = z.object({+ routines: z.array(+ z.object({+ id: z.string().uuid(),+ name: z.string(),+ enabled: z.boolean(),+ trigger: z.any(),+ task: z.any(),+ nextRunAt: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ })+ ),+ total: z.number().int().gte(0),+});+export const ListSkills = z.record(z.any());export const ListSkillsResponse = z.object({@@ -8016,6 +8104,22 @@ export const ReadProjectResponse = z.object({),});+export const ReadRoutine = z.object({ routineId: z.string().uuid() });++export const RoutineDetails = z.object({+ routine: z.object({+ id: z.string().uuid(),+ name: z.string(),+ enabled: z.boolean(),+ trigger: z.any(),+ task: z.any(),+ nextRunAt: z+ .union([z.string().datetime({ offset: true }), z.null()])+ .optional(),+ }),+ runs: z.array(z.any()),+});+export const ReadSkill = z.object({ documentId: z.string().uuid() });export const ReadSkillResponse = z.object({@@ -9238,6 +9342,91 @@ export const UpdateReminder = z.object({completed: z.union([z.boolean(), z.null()]).optional(),});+export const UpdateRoutine = z.object({+ routineId: z.string().uuid(),+ change: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ enabled: z.boolean(), type: z.literal('enabled') }),+ z.object({+ configuration: z.object({+ name: z.string(),+ instructions: z.string(),+ target: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({ model: z.string(), type: z.literal('model') }),+ z.object({+ agentId: z.string().uuid(),+ type: z.literal('agent'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ schedule: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.object({+ at: z.string().datetime({ offset: true }),+ type: z.literal('once'),+ }),+ z.object({+ expression: z.string(),+ timezone: z.string(),+ type: z.literal('cron'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) =>+ result.error ? [...errors, result.error] : errors)(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+ }),+ type: z.literal('configuration'),+ }),+ ];+ const errors = schemas.reduce<z.ZodError[]>(+ (errors, schema) =>+ ((result) => (result.error ? [...errors, result.error] : errors))(+ schema.safeParse(x)+ ),+ []+ );+ if (schemas.length - errors.length !== 1) {+ ctx.addIssue({+ path: ctx.path,+ code: 'invalid_union',+ unionErrors: errors,+ message: 'Invalid input: Should pass single schema',+ });+ }+ }),+});+export const UpdateThreadLabels = z.object({thread_id: z.string().uuid(),label_id: z.string().uuid(),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.tsindex 61cca79afd..a9940a38be 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts@@ -62,6 +62,7 @@ type ToolParserMap = {response: types.CreateProjectResponse;};CreateReminder: { call: types.CreateReminder; response: types.ToolReminder };+ CreateRoutine: { call: types.CreateRoutine; response: types.RoutineInfo };CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };DeleteBot: { call: types.DeleteBot; response: types.DeleteBotResponse };DeleteCalendarEvent: {@@ -172,6 +173,7 @@ type ToolParserMap = {call: types.ListReminders;response: types.ListRemindersResponse;};+ ListRoutines: { call: types.ListRoutines; response: types.RoutineList };ListSkills: { call: types.ListSkills; response: types.ListSkillsResponse };ListTags: { call: types.ListTags; response: types.ListTagsResponse };ListTeamMembers: {@@ -243,6 +245,7 @@ type ToolParserMap = {response: types.ReadPresentationResponse;};ReadProject: { call: types.ReadProject; response: types.ReadProjectResponse };+ ReadRoutine: { call: types.ReadRoutine; response: types.RoutineDetails };ReadSkill: { call: types.ReadSkill; response: types.ReadSkillResponse };ReadSpreadsheet: {call: types.ReadSpreadsheet;@@ -320,6 +323,7 @@ type ToolParserMap = {response: types.ProjectDetails;};UpdateReminder: { call: types.UpdateReminder; response: types.ToolReminder };+ UpdateRoutine: { call: types.UpdateRoutine; response: types.RoutineInfo };UpdateThreadLabels: {call: types.UpdateThreadLabels;response: types.UpdateThreadLabelsResponse;@@ -387,6 +391,7 @@ const toolParserMap = {call: schemas.CreateReminder,response: schemas.ToolReminder,},+ CreateRoutine: { call: schemas.CreateRoutine, response: schemas.RoutineInfo },CreateTag: { call: schemas.CreateTag, response: schemas.CreateTagResponse },DeleteBot: { call: schemas.DeleteBot, response: schemas.DeleteBotResponse },DeleteCalendarEvent: {@@ -509,6 +514,7 @@ const toolParserMap = {call: schemas.ListReminders,response: schemas.ListRemindersResponse,},+ ListRoutines: { call: schemas.ListRoutines, response: schemas.RoutineList },ListSkills: {call: schemas.ListSkills,response: schemas.ListSkillsResponse,@@ -592,6 +598,7 @@ const toolParserMap = {call: schemas.ReadProject,response: schemas.ReadProjectResponse,},+ ReadRoutine: { call: schemas.ReadRoutine, response: schemas.RoutineDetails },ReadSkill: { call: schemas.ReadSkill, response: schemas.ReadSkillResponse },ReadSpreadsheet: {call: schemas.ReadSpreadsheet,@@ -675,6 +682,7 @@ const toolParserMap = {call: schemas.UpdateReminder,response: schemas.ToolReminder,},+ UpdateRoutine: { call: schemas.UpdateRoutine, response: schemas.RoutineInfo },UpdateThreadLabels: {call: schemas.UpdateThreadLabels,response: schemas.UpdateThreadLabelsResponse,@@ -750,6 +758,7 @@ type ToolDataMap = {response: types.CreateProjectResponse;};CreateReminder: { call: types.CreateReminder; response: types.ToolReminder };+ CreateRoutine: { call: types.CreateRoutine; response: types.RoutineInfo };CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };DeleteBot: { call: types.DeleteBot; response: types.DeleteBotResponse };DeleteCalendarEvent: {@@ -860,6 +869,7 @@ type ToolDataMap = {call: types.ListReminders;response: types.ListRemindersResponse;};+ ListRoutines: { call: types.ListRoutines; response: types.RoutineList };ListSkills: { call: types.ListSkills; response: types.ListSkillsResponse };ListTags: { call: types.ListTags; response: types.ListTagsResponse };ListTeamMembers: {@@ -931,6 +941,7 @@ type ToolDataMap = {response: types.ReadPresentationResponse;};ReadProject: { call: types.ReadProject; response: types.ReadProjectResponse };+ ReadRoutine: { call: types.ReadRoutine; response: types.RoutineDetails };ReadSkill: { call: types.ReadSkill; response: types.ReadSkillResponse };ReadSpreadsheet: {call: types.ReadSpreadsheet;@@ -1008,6 +1019,7 @@ type ToolDataMap = {response: types.ProjectDetails;};UpdateReminder: { call: types.UpdateReminder; response: types.ToolReminder };+ UpdateRoutine: { call: types.UpdateRoutine; response: types.RoutineInfo };UpdateThreadLabels: {call: types.UpdateThreadLabels;response: types.UpdateThreadLabelsResponse;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 202b8edbe0..a7dff6d298 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -396,6 +396,46 @@ export type ReminderEntityType =| 'channel'| 'call'| 'calendar_event';+/**+ * Who executes the routine. Agent IDs refer to personas, never conversation IDs.+ */+export type RoutineTarget =+ | {+ /**+ * Runtime model ID.+ */+ model: string;+ type: 'model';+ }+ | {+ /**+ * Persona/bot UUID (`bot.botId`) from ListAgents. Use your own persona ID to schedule yourself.+ */+ agentId: string;+ type: 'agent';+ };+/**+ * A recurring or one-off schedule.+ */+export type RoutineSchedule =+ | {+ /**+ * RFC3339 timestamp including UTC offset.+ */+ at: string;+ type: 'once';+ }+ | {+ /**+ * Seconds, minutes, hours, day-of-month, month, weekday (optional year).+ */+ expression: string;+ /**+ * IANA time zone, e.g. America/New_York.+ */+ timezone: string;+ type: 'cron';+ };/*** A tag color from the fixed palette.*/@@ -3606,6 +3646,21 @@ export type ProjectShareAccess = 'off' | 'view' | 'comment' | 'edit';* Scope admitted by a project's share link.*/export type ProjectLinkScope = 'off' | 'public' | 'team';+/**+ * Exactly one update intention avoids partially-applied configuration/activation changes.+ */+export type RoutineChange =+ | {+ /**+ * New activation state.+ */+ enabled: boolean;+ type: 'enabled';+ }+ | {+ configuration: RoutineConfiguration;+ type: 'configuration';+ };/*** Content of a web fetch response - either a successful result or an error*/@@ -5707,6 +5762,60 @@ export interface ToolReminder {*/enabled: boolean;}+/**+ * Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine.+ */+export interface CreateRoutine {+ configuration: RoutineConfiguration;+}+/**+ * Complete user-editable configuration, independent of execution bookkeeping.+ */+export interface RoutineConfiguration {+ /**+ * Short descriptive name.+ */+ name: string;+ /**+ * Instructions passed to the model or agent on every run.+ */+ instructions: string;+ target: RoutineTarget;+ schedule: RoutineSchedule;+}+/**+ * Compact routine details returned to the caller.+ */+export interface RoutineInfo {+ /**+ * Routine identifier.+ */+ id: string;+ /**+ * Display name.+ */+ name: string;+ /**+ * Whether automatic runs are enabled.+ */+ enabled: boolean;+ /**+ * Cron expression or event trigger, as stored by the scheduler.+ */+ trigger: {+ [k: string]: unknown;+ };+ /**+ * Execution target and instructions.+ */+ task: {+ [k: string]: unknown;+ };+ /**+ * Next scheduled firing, absent after a one-off completes.+ */+ nextRunAt?: string | null;+}/*** Create a new tag — a colored label the user can apply to documents, emails, tasks, AI chats, and projects — in the user's personal set or their team's shared set. The set is provisioned automatically the first time a tag is created. Tags are matched by label, so call ListTags first and avoid creating one whose label duplicates an existing tag in the same set. Returns the new tag's id and its set's propertyDefinitionId, which you can pass straight to SetEntityProperty (add_option_ids) to apply the tag to an item. Use this only to create a brand-new tag; to apply an existing tag to an item, use ListTags then SetEntityProperty instead.*/@@ -6087,7 +6196,7 @@ export interface DisplayResultsResponse {message: string;}/**- * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.+ * Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.*/export interface EditDocument {/**@@ -8087,6 +8196,32 @@ export interface ListRemindersResponse {*/summary: string;}+/**+ * Find the authenticated user’s routines, including work delegated to other agents. Filter by name/instructions or enabled state. Returns up to 50 matches and the full count; narrow the query if truncated. Use ReadRoutine for history.+ */+export interface ListRoutines {+ /**+ * Optional text to match in the routine name or task.+ */+ query?: string | null;+ /**+ * Optional active/paused filter.+ */+ enabled?: boolean | null;+}+/**+ * A bounded list with the full matching count.+ */+export interface RoutineList {+ /**+ * Matching routines (most recent first).+ */+ routines: RoutineInfo[];+ /**+ * Total matches before the response limit.+ */+ total: number;+}/*** List up to 100 of the most recently updated skills the user can access, plus built-in skills. Skills are markdown documents containing instructions for AI to read and follow; after finding a relevant skill, read its instructions with ReadSkill using the returned document id. Use this to discover what skills exist; when looking for a specific skill by name or an older skill not in this list, use SearchSkills.*/@@ -9596,6 +9731,25 @@ export interface ProjectItem {*/updatedAt?: string | null;}+/**+ * Read a routine owned by the authenticated user, including its saved configuration and recent run history. Reading a run transcript still requires its own access.+ */+export interface ReadRoutine {+ /**+ * Routine UUID from CreateRoutine or ListRoutines.+ */+ routineId: string;+}+/**+ * Routine configuration and recent execution history.+ */+export interface RoutineDetails {+ routine: RoutineInfo;+ /**+ * Most recent runs, up to fifty, including status and transcript references.+ */+ runs: unknown[];+}/*** Read a skill's complete markdown instructions by its documentId from ListSkills or SearchSkills, or a skill mention. Supports user-authored and built-in skills. Read a relevant skill before performing the task and follow its instructions for that request. Returns the skill name and full content; only skill documents the user can view are readable.*/@@ -10488,6 +10642,16 @@ export interface UpdateReminder {*/completed?: boolean | null;}+/**+ * Pause/resume or replace the configuration of a routine owned by the authenticated user. ReadRoutine first before replacing configuration. Select an agent to delegate the routine or a model to run as Macro. Does not change ownership. A running routine can be paused but cannot be reconfigured until it finishes.+ */+export interface UpdateRoutine {+ /**+ * Routine UUID.+ */+ routineId: string;+ change: RoutineChange;+}/*** Add or remove a single label from every message in a Gmail thread. In Gmail, nearly all inbox operations are just label add/remove operations, so this tool is the primitive for archiving, marking read/unread, starring, trashing, marking important/spam, and applying or removing custom labels.*diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/client.tsindex 347959fe15..4f2674d197 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/client.ts@@ -35,8 +35,11 @@ function scheduledActionFetch<T extends ObjectLike = never>(}export const scheduledActionClient = {- // Include backend-managed routines so direct routes can identify them.- // Cron-only entity lists filter these out before rendering.+ getRoutine: (id: string) =>+ scheduledActionFetch<ScheduledAction>(`/scheduled-actions/${id}`, {+ method: 'GET',+ }),+ // Include every trigger type in the routine list.listSchedules: async () =>scheduledActionFetch<ScheduledAction[]>('/scheduled-actions?include_events=true',diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.tsindex d9feec36d5..eebc9295f2 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/client.ts@@ -198,6 +198,65 @@ export const createScheduledAction = async (} as createScheduledActionResponse;};+export type getScheduledActionResponse200 = {+ data: ScheduledActionResponse;+ status: 200;+};++export type getScheduledActionResponse401 = {+ data: string;+ status: 401;+};++export type getScheduledActionResponse404 = {+ data: string;+ status: 404;+};++export type getScheduledActionResponse500 = {+ data: string;+ status: 500;+};++export type getScheduledActionResponseSuccess =+ getScheduledActionResponse200 & {+ headers: Headers;+ };+export type getScheduledActionResponseError = (+ | getScheduledActionResponse401+ | getScheduledActionResponse404+ | getScheduledActionResponse500+) & {+ headers: Headers;+};++export type getScheduledActionResponse =+ | getScheduledActionResponseSuccess+ | getScheduledActionResponseError;++export const getGetScheduledActionUrl = (id: string) => {+ return `/scheduled-actions/${id}`;+};++export const getScheduledAction = async (+ id: string,+ options?: RequestInit+): Promise<getScheduledActionResponse> => {+ const res = await fetch(getGetScheduledActionUrl(id), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getScheduledActionResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getScheduledActionResponse;+};+export type updateScheduledActionResponse200 = {data: ScheduledActionResponse;status: 200;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.tsindex 033b08b4bb..f8566a1f9c 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTrigger.ts@@ -6,9 +6,13 @@* OpenAPI spec version: 0.1.0*/import type { ActionTriggerOneOf } from './actionTriggerOneOf';+import type { ActionTriggerOneOfFive } from './actionTriggerOneOfFive';import type { ActionTriggerOneOfThree } from './actionTriggerOneOfThree';/**- * Exactly one trigger per action. Existing cron validation is reused.+ * A routine may run on one trigger or any of several schedules and Macro events.*/-export type ActionTrigger = ActionTriggerOneOf | ActionTriggerOneOfThree;+export type ActionTrigger =+ | ActionTriggerOneOf+ | ActionTriggerOneOfThree+ | ActionTriggerOneOfFive;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.tsnew file mode 100644index 0000000000..c2cba6cb20--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFive.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++import type { ActionTriggerOneOfFiveType } from './actionTriggerOneOfFiveType';+import type { RoutineTriggers } from './routineTriggers';++export type ActionTriggerOneOfFive = {+ triggers: RoutineTriggers;+ type: ActionTriggerOneOfFiveType;+};diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.tsnew file mode 100644index 0000000000..d38fb100b7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/actionTriggerOneOfFiveType.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export type ActionTriggerOneOfFiveType =+ (typeof ActionTriggerOneOfFiveType)[keyof typeof ActionTriggerOneOfFiveType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ActionTriggerOneOfFiveType = {+ multiple: 'multiple',+} as const;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.tsindex b4695c0ce5..ec7598b579 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/eventName.ts@@ -16,6 +16,12 @@ export type EventName = (typeof EventName)[keyof typeof EventName];export const EventName = {documentcreated: 'document.created',documentupdated: 'document.updated',+ documentdeleted: 'document.deleted',+ taskcreated: 'task.created',+ taskstatus_changed: 'task.status_changed',+ taskpriority_changed: 'task.priority_changed',+ taskproperty_changed: 'task.property_changed',+ emailmessage_received: 'email.message_received',channelcreated: 'channel.created',channelmessage_posted: 'channel.message_posted',channelmentioned: 'channel.mentioned',diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.tsindex 473ae0fa8b..82667e9215 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts@@ -18,6 +18,8 @@ export * from './actionExecutionRecordResult';export * from './actionKind';export * from './actionTrigger';export * from './actionTriggerOneOf';+export * from './actionTriggerOneOfFive';+export * from './actionTriggerOneOfFiveType';export * from './actionTriggerOneOfThree';export * from './actionTriggerOneOfThreeType';export * from './actionTriggerOneOfType';@@ -44,6 +46,12 @@ export * from './legacyActionConfiguration';export * from './legacyActionConfigurationTask';export * from './listScheduledActionsParams';export * from './routineModelId';+export * from './routineTrigger';+export * from './routineTriggerOneOf';+export * from './routineTriggerOneOfThree';+export * from './routineTriggerOneOfThreeType';+export * from './routineTriggerOneOfType';+export * from './routineTriggers';export * from './schedule';export * from './scheduledAction';export * from './scheduledActionClaimed';diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.tsnew file mode 100644index 0000000000..b51721dba2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTrigger.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineTriggerOneOf } from './routineTriggerOneOf';+import type { RoutineTriggerOneOfThree } from './routineTriggerOneOfThree';++/**+ * An individual trigger in a routine's trigger list.+ */+export type RoutineTrigger = RoutineTriggerOneOf | RoutineTriggerOneOfThree;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOf.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOf.tsnew file mode 100644index 0000000000..dca2e107ef--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++import type { RoutineTriggerOneOfType } from './routineTriggerOneOfType';+import type { Schedule } from './schedule';++export type RoutineTriggerOneOf = {+ schedule: Schedule;+ timezone: string;+ type: RoutineTriggerOneOfType;+};diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfThree.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfThree.tsnew file mode 100644index 0000000000..6123bb8649--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfThree.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { EventFilters } from './eventFilters';+import type { RoutineTriggerOneOfThreeType } from './routineTriggerOneOfThreeType';++export type RoutineTriggerOneOfThree = {+ filters: EventFilters;+ type: RoutineTriggerOneOfThreeType;+};diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfThreeType.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfThreeType.tsnew file mode 100644index 0000000000..1408b40d1a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfThreeType.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export type RoutineTriggerOneOfThreeType =+ (typeof RoutineTriggerOneOfThreeType)[keyof typeof RoutineTriggerOneOfThreeType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RoutineTriggerOneOfThreeType = {+ events: 'events',+} as const;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfType.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfType.tsnew file mode 100644index 0000000000..1d32026fc1--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggerOneOfType.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++export type RoutineTriggerOneOfType =+ (typeof RoutineTriggerOneOfType)[keyof typeof RoutineTriggerOneOfType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const RoutineTriggerOneOfType = {+ cron: 'cron',+} as const;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggers.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggers.tsnew file mode 100644index 0000000000..fc767cd30e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/routineTriggers.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */+import type { RoutineTrigger } from './routineTrigger';++/**+ * Bounded schedules and one combined set of event filters.+ */+export type RoutineTriggers = RoutineTrigger[];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 00b6c827e0..50a8dcb321 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@@ -158,6 +158,63 @@}},"/scheduled-actions/{id}": {+ "get": {+ "tags": ["scheduled actions"],+ "operationId": "get_scheduled_action",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "ID of the scheduled action",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScheduledActionResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },"put": {"tags": ["scheduled actions"],"operationId": "update_scheduled_action",@@ -674,9 +731,22 @@"enum": ["events"]}}+ },+ {+ "type": "object",+ "required": ["triggers", "type"],+ "properties": {+ "triggers": {+ "$ref": "#/components/schemas/RoutineTriggers"+ },+ "type": {+ "type": "string",+ "enum": ["multiple"]+ }+ }}],- "description": "Exactly one trigger per action. Existing cron validation is reused."+ "description": "A routine may run on one trigger or any of several schedules and Macro events."},"AgentTask": {"type": "object",@@ -689,7 +759,7 @@},{"$ref": "#/components/schemas/AgentTaskAgent",- "description": "Absent for legacy model-only tasks."+ "description": "Absent when using Macro's agent-session runtime with a selected model."}]},@@ -785,6 +855,12 @@"enum": ["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",@@ -889,6 +965,47 @@"type": "string","description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."},+ "RoutineTrigger": {+ "oneOf": [+ {+ "type": "object",+ "required": ["schedule", "timezone", "type"],+ "properties": {+ "schedule": {+ "$ref": "#/components/schemas/Schedule"+ },+ "timezone": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "enum": ["cron"]+ }+ }+ },+ {+ "type": "object",+ "required": ["filters", "type"],+ "properties": {+ "filters": {+ "$ref": "#/components/schemas/EventFilters"+ },+ "type": {+ "type": "string",+ "enum": ["events"]+ }+ }+ }+ ],+ "description": "An individual trigger in a routine's trigger list."+ },+ "RoutineTriggers": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/RoutineTrigger"+ },+ "description": "Bounded schedules and one combined set of event filters."+ },"Schedule": {"type": "string"},diff --git a/apps/web/src/lib/service-clients/service-storage/itemType.test.ts b/apps/web/src/lib/service-clients/service-storage/itemType.test.tsindex e2d1023da1..11bdc85414 100644--- a/apps/web/src/lib/service-clients/service-storage/itemType.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/itemType.test.ts@@ -23,6 +23,9 @@ describe('itemTypeToReferenceEntityType', () => {test('maps email to the thread type used by referencium', () => {expect(itemTypeToReferenceEntityType('email')).toBe('thread');});+ test('preserves the routine reference wire contract', () => {+ expect(itemTypeToReferenceEntityType('routine')).toBe('automation');+ });test.each(['document',@@ -60,7 +63,14 @@ describe('stringToItemType', () => {expect(stringToItemType(raw)).toBe(raw);});- test.each(['crm_contact', 'automation', 'channel_message', 'bogus'])(+ test.each(['routine', 'automation'])(+ 'reads %s references as routines',+ (raw) => {+ expect(stringToItemType(raw)).toBe('routine');+ }+ );++ test.each(['crm_contact', 'channel_message', 'bogus'])('rejects %s',(raw) => {expect(stringToItemType(raw)).toBeUndefined();@@ -76,7 +86,7 @@ describe('blockNameToItemType', () => {['channel', 'channel'],['project', 'project'],['email', 'email'],- ['automation', 'automation'],+ ['routine', 'routine'],['company', 'crm_company'],['contact', 'crm_contact'],['pr', 'foreign'],@@ -100,6 +110,7 @@ describe('reference entity type round trip', () => {'calendar_event','crm_company','email',+ 'routine',] as const satisfies readonly ItemType[])('%s survives store and parse',(itemType) => {diff --git a/apps/web/src/lib/service-clients/service-storage/itemType.ts b/apps/web/src/lib/service-clients/service-storage/itemType.tsindex e4211580cf..816658212c 100644--- a/apps/web/src/lib/service-clients/service-storage/itemType.ts+++ b/apps/web/src/lib/service-clients/service-storage/itemType.ts@@ -12,7 +12,7 @@ export type ItemType =| 'call'| 'database'| 'agent_session'- | 'automation'+ | 'routine'| 'calendar_event'| 'foreign'| 'crm_company'@@ -30,6 +30,8 @@ export const DEFAULT_ITEM_TYPE: ItemType = 'document';* or they will not appear in the references side panel.*/export function itemTypeToReferenceEntityType(itemType: ItemType): string {+ // The reference API retains its original discriminator for routines.+ if (itemType === 'routine') return 'automation';return itemType === 'email' ? 'thread' : itemType;}@@ -43,6 +45,7 @@ export function itemTypeToReferenceEntityType(itemType: ItemType): string {export function stringToItemType(str: string): ItemType | undefined {return match<string, ItemType | undefined>(str).with('email', 'thread', 'email_thread', () => 'email')+ .with('routine', 'automation', () => 'routine').with('database','agent_session',@@ -69,7 +72,7 @@ export function blockNameToItemType('channel','project','email',- 'automation',+ 'routine','database','initiative',(b) => b@@ -96,7 +99,7 @@ export const ITEM_TYPES = ['call','database','agent_session',- 'automation',+ 'routine','calendar_event','foreign','crm_company',diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 8afacdf6af..5385e55c6d 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -23405,6 +23405,17 @@"project_id": {"type": ["string", "null"],"description": "Project the document belonged to, when any."+ },+ "sub_type": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/DocumentSubType",+ "description": "Subtype captured before deletion, so consumers can distinguish tasks."+ }+ ]}}},diff --git a/apps/web/src/routes/app-router-view.tsx b/apps/web/src/routes/app-router-view.tsxindex d226a04d2b..1be14370ca 100644--- a/apps/web/src/routes/app-router-view.tsx+++ b/apps/web/src/routes/app-router-view.tsx@@ -41,6 +41,7 @@ import {ReviewsPrDetailRouteView,ReviewsRouteView,} from '@app/features/reviews-view/route-views';+import { RoutineCreateRouteView } from '@app/features/routines/route-views';import { SettingsRouteView } from '@app/features/settings/route-views';import { TasksDetailRouteView } from '@app/features/tasks-view/components/TasksDetailView';import {@@ -137,6 +138,9 @@ import {remindersRoute,reviewsPrRoute,reviewsSplitRoute,+ routineCreateRoute,+ routineDetailRoute,+ routinesRoute,searchRoute,settingsRoute,setupRoute,@@ -248,6 +252,12 @@ export function AppRouterView() {/></Route><Route definition={settingsRoute} component={SettingsRouteView} />+ <Route+ definition={routineCreateRoute}+ component={RoutineCreateRouteView}+ />+ <Route definition={routineDetailRoute} component={AgentsRouteView} />+ <Route definition={routinesRoute} component={AgentsRouteView} /><Route definition={agentsRoute} component={AgentsRouteView} /><Route definition={codersRoute} component={AgentsRouteView} /><Route definition={agentChatsRoute} component={AgentsRouteView} />diff --git a/apps/web/src/routes/routes.ts b/apps/web/src/routes/routes.tsindex 25fa22ae8e..b81892e07d 100644--- a/apps/web/src/routes/routes.ts+++ b/apps/web/src/routes/routes.ts@@ -25,6 +25,11 @@ import {REMINDER_DETAIL_ROUTE_ID,} from '@app/features/reminders/reminder-navigation';import { reviewsTabSearch } from '@app/features/reviews-view/reviews-tab-search';+import {+ ROUTINE_CREATE_ROUTE_ID,+ ROUTINE_DETAIL_ROUTE_ID,+ ROUTINES_ROUTE_ID,+} from '@app/features/routines/routine-navigation';import { defineRoute, type Entry, routeParams } from '@app/lib/split-router';import { callDetailSearch } from '@block-call/call-route';import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';@@ -466,6 +471,29 @@ export const remindersRoute = defineRoute({claim: () => ({ namespace: 'component', id: 'reminders' }),});+export const routinesRoute = defineRoute({+ id: ROUTINES_ROUTE_ID,+ path: 'routines',+ claim: () => ({ namespace: 'component', id: 'routines' }),+});++export const routineCreateRoute = defineRoute({+ id: ROUTINE_CREATE_ROUTE_ID,+ path: 'routines/new',+ aliases: ['routine/new', 'automation/new'],+ claim: () => ({ namespace: 'component', id: 'routine-compose' }),+});++export const routineDetailRoute = defineRoute({+ id: ROUTINE_DETAIL_ROUTE_ID,+ path: 'routines/:routineId',+ aliases: ['routine/:routineId', 'automation/:routineId'],+ params: z.object({ routineId: z.string().min(1) }),+ remountKey: ({ routineId }) => routineId,+ claim: ({ routineId }) => ({ namespace: 'routine', id: routineId }),+ toReference: ({ routineId }) => uuidRouteReference(routineId, 'routine'),+});+export const agentsViewRoute = defineRoute({id: 'view-agents',path: 'agents',diff --git a/apps/web/tests/e2e/local-sidebar.spec.ts b/apps/web/tests/e2e/local-sidebar.spec.tsindex 233b0ec16c..8e7a4f2761 100644--- a/apps/web/tests/e2e/local-sidebar.spec.ts+++ b/apps/web/tests/e2e/local-sidebar.spec.ts@@ -14,7 +14,7 @@ const SIDEBAR_LIST_VIEWS = [{id: 'agents',label: 'Agents',- tabs: ['Owned', 'Running', 'Shared', 'Automations'],+ tabs: ['Owned', 'Running', 'Shared', 'Routines'],},{id: 'mail',diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.jsonindex c2a0ec492e..e501053f68 100644--- a/apps/web/tsconfig.json+++ b/apps/web/tsconfig.json@@ -155,9 +155,6 @@"@block-channel/*": ["./src/features/block-channel/*"],- "@block-automation/*": [- "./src/features/block-automation/*"- ],"@channel/*": ["./src/features/channel/*"],diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex afbd64b93a..b41f246f31 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -8,6 +8,8 @@ version = "0.1.0"test-support = [][dependencies]+routines = { path = "../routines" }+macro_auth = { path = "../macro_auth" }ai_billing = { path = "../ai_billing", features = ["pg-admission"] }collab_surface = { path = "../collab_surface", features = ["postgres"] }initiative = { path = "../initiative", default-features = false, features = ["postgres", "resources", "toolset"] }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 1e9aa2ce1a..f973949e31 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -520,7 +520,7 @@ pub async fn build_tool_service_context_from_env(team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),crm_tool_context: crate::tool_context::build_crm_tool_context(pool.clone()),skill_tool_context,- schedule_tool_context: crate::NoOpScheduleContext,+ schedule_tool_context: crate::build_routine_tool_context()?,anthropic_tool_context,admission: ai_billing::composition::pg_admission_service(pool.clone(), enforcement),recorder,diff --git a/crates/ai_tools/src/display_results/schema.generated.json b/crates/ai_tools/src/display_results/schema.generated.jsonindex c28d298d1d..69ed5f8e0b 100644--- a/crates/ai_tools/src/display_results/schema.generated.json+++ b/crates/ai_tools/src/display_results/schema.generated.json@@ -102,7 +102,7 @@"database","database_row","email",- "automation",+ "routine","channel_thread"]}@@ -198,7 +198,7 @@"database","database_row","email",- "automation",+ "routine","channel_thread"]}diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 2d76559644..0bdcd0963f 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -59,8 +59,8 @@ pub use mcp_app_catalog::{PipedreamMcpAppCatalog, pipedream_client_from_env};pub use search::search_toolset;pub use tool_context::{ChannelSideEffectClients, MaybeToolEventBroker, NoOpCallRtcClient, NoOpConnectionService,- NoOpNotificationIngress, NoOpNotificationService, NoOpScheduleContext, NoOpSnsEndpointManager,- NoOpTaskProperties, RequestContext, TaskPropertiesAdapter, ToolActivityToolContext,+ NoOpNotificationIngress, NoOpNotificationService, NoOpSnsEndpointManager, NoOpTaskProperties,+ RequestContext, RoutineToolContext, TaskPropertiesAdapter, ToolActivityToolContext,ToolBotService, ToolBotToolContext, ToolCalendarMutationService, ToolCalendarReadService,ToolCalendarToolContext, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,@@ -83,8 +83,9 @@ pub use tool_context::{build_image_generation_tool_context, build_initiative_tool_context,build_message_service_with_side_effects, build_message_service_without_side_effects,build_project_tool_context, build_properties_service, build_properties_service_with_broker,- build_properties_tool_context, build_reminders_tool_context, build_skill_tool_context,- build_task_properties_adapter, build_team_repository, build_team_tool_context,+ build_properties_tool_context, build_reminders_tool_context, build_routine_tool_context,+ build_skill_tool_context, build_task_properties_adapter, build_team_repository,+ build_team_tool_context,};#[cfg(any(test, feature = "test-support"))]pub use tool_context::{build_image_generation_tool_context_test, no_op_schedule_context};@@ -185,7 +186,8 @@ pub enum AiHost {pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {let toolset = subagent_toolset().add_subtoolset::<ToolNotificationToolContext>(notification_toolset())- .add_subtoolset::<ToolRemindersToolContext>(reminders_toolset());+ .add_subtoolset::<ToolRemindersToolContext>(reminders_toolset())+ .add_subtoolset::<RoutineToolContext>(routines::inbound::routine_toolset());let toolset = match host {AiHost::Chat | AiHost::AgentSession => toolset.add_subtoolset::<ToolEmailToolContext>(email_toolset())diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex d887430166..bc80fbf224 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -1561,12 +1561,21 @@ pub fn build_activity_tool_context())}-#[derive(Clone, Default)]-pub struct NoOpScheduleContext;+pub use routines::inbound::RoutineToolContext;++/// Build the routine client from standard service URL and auth configuration.+pub fn build_routine_tool_context() -> anyhow::Result<RoutineToolContext> {+ Ok(RoutineToolContext {+ service: Some(routines::outbound::RoutineClient::new(+ macro_service_urls::ScheduledActionServiceUrl::new()?.as_ref(),+ ¯o_auth::InternalApiKey::new()?,+ )?),+ })+}#[cfg(any(test, feature = "test-support"))]-pub fn no_op_schedule_context() -> NoOpScheduleContext {- NoOpScheduleContext+pub fn no_op_schedule_context() -> RoutineToolContext {+ RoutineToolContext::default()}/// The full service context containing all API clients.@@ -1605,7 +1614,7 @@ pub struct ToolServiceContext {pub team_tool_context: ToolTeamToolContext,pub crm_tool_context: ToolCrmToolContext,pub skill_tool_context: ToolSkillToolContext,- pub schedule_tool_context: NoOpScheduleContext,+ pub schedule_tool_context: RoutineToolContext,#[from_ref(skip)]pub anthropic_tool_context: AnthropicToolContext,/// Shared admission for independently initiated AI work. Hosts must injectdiff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rsindex 33bf7d0149..a250505711 100644--- a/crates/complete_graph/src/sdl_test.rs+++ b/crates/complete_graph/src/sdl_test.rs@@ -521,12 +521,18 @@ fn scheduled_actions_hang_off_the_authenticated_user() {assert_sdl_line(&sdl, "scheduledActions: [GraphqlScheduledAction!]!");assert_sdl_line(&sdl,- "union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger",+ "union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger | GraphqlScheduledActionMultipleTrigger",);assert!(sdl.contains("AI routines the authenticated user can access."));for value in ["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",diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rsindex b7ecf51e60..c77e31b0b0 100644--- a/crates/documents/src/domain/activity/test.rs+++ b/crates/documents/src/domain/activity/test.rs@@ -127,6 +127,7 @@ fn attributed_update_and_delete_map_to_activities() {assert_eq!(activity.subject_id, "macro|[email protected]");let deleted = envelope(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user("macro|[email protected]")),actor: None,@@ -177,6 +178,7 @@ fn unattributable_mutations_are_dropped() {assert_eq!(updated.event.ingest(updated.event_id), Ingest::Ignore);let deleted = envelope(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_string(),actor_user_id: None,actor: None,@@ -375,6 +377,7 @@ fn attributed_sync_content_is_an_edited_activity() {#[test]fn replaying_an_event_derives_identical_activity_ids() {let event = envelope(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user("macro|[email protected]")),actor: None,@@ -528,6 +531,7 @@ async fn unavailable_debounce_is_best_effort_and_does_not_stall_other_activity().unwrap();assert_eq!(result, Ingest::Ignore);let deleted = DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_owned(),actor_user_id: Some(user("macro|[email protected]")),actor: None,diff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rsindex 24be04a55a..64d5cba3d3 100644--- a/crates/documents/src/domain/events.rs+++ b/crates/documents/src/domain/events.rs@@ -91,6 +91,9 @@ pub struct DocumentUpdatedMetadata {pub struct DocumentDeletedMetadata {/// The id of the deleted document.pub document_id: String,+ /// Subtype captured before deletion, so consumers can distinguish tasks.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sub_type: Option<DocumentSubType>,/// The authenticated user who deleted the document; `None` for/// unauthenticated or internal callers.pub actor_user_id: Option<MacroUserIdStr<'static>>,diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex e47b70b0a0..63d97a4e65 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -1132,6 +1132,7 @@ impl<entity_access_receipt.entity().entity_id.clone(),DocumentDeletedMetadata {document_id: entity_access_receipt.entity().entity_id.clone(),+ sub_type: metadata.sub_type,actor_user_id,actor,on_behalf_of,diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex b49cc106d9..ebbd08dc25 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -1871,8 +1871,11 @@ async fn content_uploaded_maps_an_immediate_broker_failure_to_internal() {#[tokio::test]async fn test_delete_document_publishes_document_deleted_event() {let mut repo = make_mock_repo();- repo.expect_get_document_metadata()- .returning(|_| Box::pin(std::future::ready(Ok(make_test_metadata()))));+ repo.expect_get_document_metadata().returning(|_| {+ let mut metadata = make_test_metadata();+ metadata.sub_type = Some(DocumentSubType::Task);+ Box::pin(std::future::ready(Ok(metadata)))+ });repo.expect_soft_delete_document().withf(|id| id == "doc-1").returning(|_| Box::pin(std::future::ready(Ok(()))));@@ -1896,6 +1899,7 @@ async fn test_delete_document_publishes_document_deleted_event() {assert_eq!(event.payload["event_type"], "document.deleted");assert_eq!(event.payload["schema_version"], 1);assert_eq!(event.payload["metadata"]["document_id"], "doc-1");+ assert_eq!(event.payload["metadata"]["sub_type"], "task");assert_eq!(event.payload["metadata"]["actor_user_id"],"macro|[email protected]"diff --git a/crates/documents/src/inbound/toolset/edit_document.rs b/crates/documents/src/inbound/toolset/edit_document.rsindex 76e96ce19f..cd9a9ec1ab 100644--- a/crates/documents/src/inbound/toolset/edit_document.rs+++ b/crates/documents/src/inbound/toolset/edit_document.rs@@ -27,7 +27,7 @@ pub(super) mod test;#[derive(Debug, Deserialize, JsonSchema)]#[schemars(title = "EditDocument",- description = "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and automations; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName."+ description = "Apply AI-driven edits to a Macro markdown document in place -- rewriting, inserting, formatting, or restructuring. Use EditSpreadsheet for native Macro spreadsheets. Markdown documents only: these are authored in Macro's collaborative editor, and are the only documents whose content this tool can rewrite. Edit uploaded Word (.docx) files with ReadWordDocument and EditWordDocument instead. Other uploaded files -- PDFs, images, source files such as .py or .ts -- are readable but not editable, and are rejected. If the response contains a `clarification` field, invoke again with the requested info appended to `instructions`. To insert @-mention chips, include each referenced item's ids and details in `instructions`: userId/email for people; documentId/documentName/blockName (and blockParams when needed) for documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, and routines; session id (and optional expanded card) for agent sessions; ISO datetime plus displayFormat for time chips. To insert document-card(s), include each document's documentId and documentName.")]pub struct EditDocument {#[schemars(diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rsindex 563f0c679e..ad91271ced 100644--- a/crates/graphql_scheduled_action/src/objects.rs+++ b/crates/graphql_scheduled_action/src/objects.rs@@ -1,7 +1,7 @@use async_graphql::{Enum, ID, SimpleObject, Union};use rootcause::Report;use scheduled_action::domain::{- event_trigger::{ActionTrigger, EventName},+ event_trigger::{ActionTrigger, EventName, RoutineTrigger},models::{ActionKind, AgentTask, ScheduledAction},};use serde_json::Value;@@ -33,6 +33,7 @@ pub struct GraphqlScheduledAction {pub(crate) enum GraphqlScheduledActionTrigger {Cron(GraphqlScheduledActionCronTrigger),Events(GraphqlScheduledActionEventsTrigger),+ Multiple(GraphqlScheduledActionMultipleTrigger),}/// A routine that runs on a cron schedule.@@ -46,6 +47,15 @@ pub(crate) struct GraphqlScheduledActionCronTrigger {next_run_at: Option<String>,}+/// Any of several schedules and optional Macro event filters.+#[derive(SimpleObject)]+pub(crate) struct GraphqlScheduledActionMultipleTrigger {+ /// Each schedule retains its own timezone and next firing.+ schedules: Vec<GraphqlScheduledActionCronTrigger>,+ /// Events that can also trigger this routine.+ events: Option<GraphqlScheduledActionEventsTrigger>,+}+/// A routine that runs when matching events are published.#[derive(SimpleObject)]pub(crate) struct GraphqlScheduledActionEventsTrigger {@@ -89,6 +99,18 @@ pub(crate) enum GraphqlScheduledActionEventName {DocumentCreated,/// A document was updated.DocumentUpdated,+ /// A document was deleted.+ DocumentDeleted,+ /// A task was created.+ TaskCreated,+ /// A task's status changed.+ TaskStatusChanged,+ /// A task's priority changed.+ TaskPriorityChanged,+ /// A task property changed.+ TaskPropertyChanged,+ /// A new email was received.+ EmailMessageReceived,/// A channel was created.ChannelCreated,/// A channel message was posted.@@ -106,6 +128,12 @@ impl From<EventName> for GraphqlScheduledActionEventName {match name {EventName::DocumentCreated => Self::DocumentCreated,EventName::DocumentUpdated => Self::DocumentUpdated,+ EventName::DocumentDeleted => Self::DocumentDeleted,+ EventName::TaskCreated => Self::TaskCreated,+ EventName::TaskStatusChanged => Self::TaskStatusChanged,+ EventName::TaskPriorityChanged => Self::TaskPriorityChanged,+ EventName::TaskPropertyChanged => Self::TaskPropertyChanged,+ EventName::EmailMessageReceived => Self::EmailMessageReceived,EventName::ChannelCreated => Self::ChannelCreated,EventName::ChannelMessagePosted => Self::ChannelMessagePosted,EventName::ChannelMentioned => Self::ChannelMentioned,@@ -152,20 +180,35 @@ fn trigger(action: &ScheduledAction) -> GraphqlScheduledActionTrigger {next_run_at,})}- ActionTrigger::Events { filters } => {- GraphqlScheduledActionTrigger::Events(GraphqlScheduledActionEventsTrigger {- filters: filters+ ActionTrigger::Multiple { triggers } => {+ GraphqlScheduledActionTrigger::Multiple(GraphqlScheduledActionMultipleTrigger {+ schedules: triggers.as_slice().iter()- .map(|filter| GraphqlScheduledActionEventFilter {- events: filter.events().iter().copied().map(Into::into).collect(),- entity_ids: filter- .ids()- .map(|ids| ids.iter().map(|id| ID(id.to_string())).collect()),+ .filter_map(|trigger| match trigger {+ RoutineTrigger::Cron { schedule, timezone } => {+ Some(GraphqlScheduledActionCronTrigger {+ schedule: schedule.as_str().to_owned(),+ timezone: timezone.to_string(),+ next_run_at: action+ .enabled+ .then(|| {+ schedule+ .next_run_after_now(*timezone)+ .map(|at| at.to_rfc3339())+ })+ .flatten(),+ })+ }+ RoutineTrigger::Events { .. } => None,}).collect(),+ events: action.trigger.event_filters().map(event_filters),})}+ ActionTrigger::Events { filters } => {+ GraphqlScheduledActionTrigger::Events(event_filters(filters))+ }}}@@ -185,3 +228,20 @@ fn agent_task(kind: &ActionKind, task: &Value) -> Option<GraphqlScheduledActionA}}}++fn event_filters(+ filters: &scheduled_action::domain::event_trigger::EventFilters,+) -> GraphqlScheduledActionEventsTrigger {+ GraphqlScheduledActionEventsTrigger {+ filters: filters+ .as_slice()+ .iter()+ .map(|filter| GraphqlScheduledActionEventFilter {+ events: filter.events().iter().copied().map(Into::into).collect(),+ entity_ids: filter+ .ids()+ .map(|ids| ids.iter().map(|id| ID(id.to_string())).collect()),+ })+ .collect(),+ }+}diff --git a/crates/macro_db_client/migrations/20261004052752_routine_trigger_configuration.sql b/crates/macro_db_client/migrations/20261004052752_routine_trigger_configuration.sqlnew file mode 100644index 0000000000..931fd485f8--- /dev/null+++ b/crates/macro_db_client/migrations/20261004052752_routine_trigger_configuration.sql@@ -0,0 +1,59 @@+-- Extend the existing scheduled action schema for completed one-offs and+-- routines that combine schedules with Macro activity events.+ALTER TABLE scheduled_action ADD COLUMN trigger_config JSONB;++ALTER TABLE scheduled_action DROP CONSTRAINT scheduled_action_trigger_shape_check;+ALTER TABLE scheduled_action+ADD CONSTRAINT scheduled_action_trigger_shape_check CHECK (+ (+ (trigger_type = 'cron'+ AND schedule IS NOT NULL+ AND timezone IS NOT NULL+ AND event_filters IS NULL+ AND event_activated_at IS NULL)+ OR+ (trigger_type = 'events'+ AND schedule IS NULL+ AND timezone IS NULL+ AND next_run_at IS NULL+ AND event_filters IS NOT NULL+ AND CASE WHEN jsonb_typeof(event_filters) = 'array'+ THEN jsonb_array_length(event_filters) BETWEEN 1 AND 32+ ELSE FALSE END+ AND event_activated_at IS NOT NULL)+ OR+ (trigger_type = 'multiple'+ AND schedule IS NULL+ AND timezone IS NULL+ AND trigger_config IS NOT NULL+ AND trigger_config->>'type' = 'multiple'+ AND (+ (event_filters IS NULL AND event_activated_at IS NULL)+ OR+ (event_filters IS NOT NULL AND event_activated_at IS NOT NULL+ AND CASE WHEN jsonb_typeof(event_filters) = 'array'+ THEN jsonb_array_length(event_filters) BETWEEN 1 AND 32+ ELSE FALSE END)+ ))+ ) IS TRUE+);++-- A routine contains between one and sixteen schedule/event trigger groups.+ALTER TABLE scheduled_action+ADD CONSTRAINT scheduled_action_supported_triggers_check CHECK (+ (trigger_type IN ('cron', 'events') OR (+ trigger_type = 'multiple'+ AND CASE WHEN jsonb_typeof(trigger_config->'triggers') = 'array'+ THEN jsonb_array_length(trigger_config->'triggers') BETWEEN 1 AND 16+ AND jsonb_array_length(jsonb_path_query_array(+ trigger_config, '$.triggers[*] ? (@.type == "cron" || @.type == "events")'+ )) = jsonb_array_length(trigger_config->'triggers')+ ELSE FALSE END+ )) IS TRUE+);++-- Event-only and mixed routines use the same event matching query.+DROP INDEX scheduled_action_event_filters_idx;+CREATE INDEX scheduled_action_event_filters_idx+ ON scheduled_action USING GIN (event_filters jsonb_path_ops)+ WHERE event_filters IS NOT NULL AND enabled;diff --git a/crates/routines/Cargo.toml b/crates/routines/Cargo.tomlnew file mode 100644index 0000000000..1de338324d--- /dev/null+++ b/crates/routines/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "routines"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+ai_toolset = { path = "../ai_toolset" }+anyhow.workspace = true+async-trait.workspace = true+chrono.workspace = true+chrono-tz.workspace = true+cron.workspace = true+macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"] }+macro_user_id = { path = "../macro_user_id" }+reqwest.workspace = true+schemars.workspace = true+serde.workspace = true+serde_json.workspace = true+uuid.workspace = true+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+tokio.workspace = truediff --git a/crates/routines/src/domain.rs b/crates/routines/src/domain.rsnew file mode 100644index 0000000000..116641a76a--- /dev/null+++ b/crates/routines/src/domain.rs@@ -0,0 +1,176 @@+//! Commands use the scheduler's existing cron engine, including single-year one-off schedules.+use anyhow::{Result, ensure};+use async_trait::async_trait;+use chrono::{DateTime, Datelike, Timelike, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++#[cfg(test)]+mod test;++/// Who executes the routine. Agent IDs refer to personas, never conversation IDs.+#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum RoutineTarget {+ /// A model running as Macro.+ Model {+ /// Runtime model ID.+ model: String,+ },+ /// An agent with its configured runtime, tools and default model.+ Agent {+ /// Persona/bot UUID (`bot.botId`) from ListAgents. Use your own persona ID to schedule yourself.+ #[serde(rename = "agentId")]+ agent_id: Uuid,+ },+}+/// A recurring or one-off schedule.+#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum RoutineSchedule {+ /// Execute once at a future timestamp, even if the creating session has ended.+ Once {+ /// RFC3339 timestamp including UTC offset.+ at: DateTime<Utc>,+ },+ /// Repeat using a six-field cron expression and an IANA time zone.+ Cron {+ /// Seconds, minutes, hours, day-of-month, month, weekday (optional year).+ expression: String,+ /// IANA time zone, e.g. America/New_York.+ timezone: String,+ },+}+impl RoutineSchedule {+ /// Validate and translate to the existing scheduler contract.+ pub fn cron(&self, now: DateTime<Utc>) -> Result<(String, String)> {+ let (schedule, timezone) = match self {+ Self::Once { at } => {+ ensure!(*at > now, "Choose a one-off time in the future.");+ (+ format!(+ "{} {} {} {} {} * {}",+ at.second(),+ at.minute(),+ at.hour(),+ at.day(),+ at.month(),+ at.year()+ ),+ "UTC".to_owned(),+ )+ }+ Self::Cron {+ expression,+ timezone,+ } => {+ let cron = expression.parse::<cron::Schedule>().map_err(|_| {+ anyhow::anyhow!(+ "Use a six-field cron: seconds minutes hours day-of-month month weekday."+ )+ })?;+ let zone = timezone.parse::<chrono_tz::Tz>().map_err(|_| {+ anyhow::anyhow!("Use an IANA timezone such as America/New_York.")+ })?;+ ensure!(+ cron.after(&now.with_timezone(&zone)).next().is_some(),+ "This schedule has no future runs."+ );+ (expression.clone(), timezone.clone())+ }+ };+ Ok((schedule, timezone))+ }+}+/// Complete user-editable configuration, independent of execution bookkeeping.+#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RoutineConfiguration {+ /// Short descriptive name.+ pub name: String,+ /// Instructions passed to the model or agent on every run.+ pub instructions: String,+ /// Explicit model or agent selection.+ pub target: RoutineTarget,+ /// Time and repetition.+ pub schedule: RoutineSchedule,+}+impl RoutineConfiguration {+ /// Validate the user's intent independently of its transport representation.+ pub fn validate(&self, now: DateTime<Utc>) -> Result<()> {+ ensure!(!self.name.trim().is_empty(), "A routine name is required.");+ ensure!(+ !self.instructions.trim().is_empty(),+ "Routine instructions are required."+ );+ if let RoutineTarget::Model { model } = &self.target {+ ensure!(!model.trim().is_empty(), "Choose a nonblank model ID.");+ }+ self.schedule.cron(now)?;+ Ok(())+ }+}+/// Compact routine details returned to the caller.+#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RoutineInfo {+ /// Routine identifier.+ pub id: Uuid,+ /// Display name.+ pub name: String,+ /// Whether automatic runs are enabled.+ pub enabled: bool,+ /// Cron expression or event trigger, as stored by the scheduler.+ pub trigger: serde_json::Value,+ /// Execution target and instructions.+ pub task: serde_json::Value,+ /// Next scheduled firing, absent after a one-off completes.+ pub next_run_at: Option<DateTime<Utc>>,+}+/// A bounded list with the full matching count.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RoutineList {+ /// Matching routines (most recent first).+ pub routines: Vec<RoutineInfo>,+ /// Total matches before the response limit.+ pub total: usize,+}+/// Routine configuration and recent execution history.+#[derive(Debug, Serialize, JsonSchema)]+pub struct RoutineDetails {+ /// Current saved configuration.+ pub routine: RoutineInfo,+ /// Most recent runs, up to fifty, including status and transcript references.+ pub runs: Vec<serde_json::Value>,+}+/// Owning-service capability: authorization remains in the scheduler, never the tools.+#[async_trait]+pub trait RoutineService: Send + Sync {+ /// Create for the authenticated user; target accessibility is checked server-side.+ async fn create(+ &self,+ user: &MacroUserIdStr<'static>,+ config: &RoutineConfiguration,+ ) -> Result<RoutineInfo>;+ /// List the authenticated user's routines, including routines targeting agents.+ async fn list(&self, user: &MacroUserIdStr<'static>) -> Result<Vec<RoutineInfo>>;+ /// Read an accessible routine and its history.+ async fn read(&self, user: &MacroUserIdStr<'static>, id: Uuid) -> Result<RoutineDetails>;+ /// Replace configuration of an owned routine; activation is preserved.+ async fn update(+ &self,+ user: &MacroUserIdStr<'static>,+ id: Uuid,+ config: &RoutineConfiguration,+ ) -> Result<RoutineInfo>;+ /// Pause/resume an owned routine independently of its configuration.+ async fn set_enabled(+ &self,+ user: &MacroUserIdStr<'static>,+ id: Uuid,+ enabled: bool,+ ) -> Result<RoutineInfo>;+}diff --git a/crates/routines/src/domain/test.rs b/crates/routines/src/domain/test.rsnew file mode 100644index 0000000000..c6dd9f66ec--- /dev/null+++ b/crates/routines/src/domain/test.rs@@ -0,0 +1,47 @@+use super::*;+use chrono::TimeZone;+#[test]+fn once_has_exactly_one_future_firing_and_normalizes_offsets() {+ let now = Utc.with_ymd_and_hms(2026, 10, 2, 0, 0, 0).unwrap();+ let schedule: RoutineSchedule = serde_json::from_value(+ serde_json::json!({"type":"once", "at":"2026-10-03T09:15:00-04:00"}),+ )+ .unwrap();+ let trigger = schedule.cron(now).unwrap();+ assert_eq!(trigger.1, "UTC");+ let cron = trigger.0.parse::<cron::Schedule>().unwrap();+ let runs: Vec<_> = cron.after(&now).take(2).collect();+ assert_eq!(+ runs,+ vec![Utc.with_ymd_and_hms(2026, 10, 3, 13, 15, 0).unwrap()]+ );+ assert!(schedule.cron(runs[0]).is_err());+}+#[test]+fn recurring_schedules_validate_timezone_and_future_runs() {+ let now = Utc::now();+ assert!(+ RoutineSchedule::Cron {+ expression: "0 0 9 * * MON-FRI".into(),+ timezone: "America/New_York".into()+ }+ .cron(now)+ .is_ok()+ );+ assert!(+ RoutineSchedule::Cron {+ expression: "0 0 9 * * *".into(),+ timezone: "imaginary".into()+ }+ .cron(now)+ .is_err()+ );+ assert!(+ RoutineSchedule::Cron {+ expression: "0 0 9 1 1 * 2000".into(),+ timezone: "UTC".into()+ }+ .cron(now)+ .is_err()+ );+}diff --git a/crates/routines/src/inbound.rs b/crates/routines/src/inbound.rsnew file mode 100644index 0000000000..494877c0b9--- /dev/null+++ b/crates/routines/src/inbound.rs@@ -0,0 +1,199 @@+//! AI workflow tools. Request identity is supplied by the host, never by the model.+use crate::domain::{+ RoutineConfiguration, RoutineDetails, RoutineInfo, RoutineList, RoutineService,+};+use ai_toolset::{+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,+ ToolCallError, ToolResult,+};+use async_trait::async_trait;+use schemars::JsonSchema;+use serde::Deserialize;+use std::sync::Arc;+use uuid::Uuid;++/// Routine capability injected by each tool host; default is explicitly unavailable for test hosts.+#[derive(Clone, Default)]+pub struct RoutineToolContext {+ /// Owning-service client.+ pub service: Option<Arc<dyn RoutineService>>,+}+impl RoutineToolContext {+ fn service(&self) -> ToolResult<&dyn RoutineService> {+ self.service.as_deref().ok_or_else(|| {+ error(anyhow::anyhow!(+ "Routine tools are unavailable in this host."+ ))+ })+ }+}+fn error(error: anyhow::Error) -> ToolCallError {+ ToolCallError {+ description: error.to_string(),+ internal_error: error,+ }+}+/// Register the routine workflows for MCP, chats, and agents.+pub fn routine_toolset() -> AsyncToolCollection<RoutineToolContext> {+ AsyncToolCollection::new()+ .add_tool::<CreateRoutine, RoutineToolContext>()+ .add_tool::<ListRoutines, RoutineToolContext>()+ .add_tool::<ReadRoutine, RoutineToolContext>()+ .add_tool::<UpdateRoutine, RoutineToolContext>()+}+/// Schedule future work.+#[derive(Deserialize, JsonSchema)]+#[schemars(+ title = "CreateRoutine",+ description = "Schedule recurring or one-off work for a model or agent. To schedule yourself, use your persona/bot ID as the agent target; to delegate, select an accessible agent from ListAgents using its bot.botId. Routines run as the authenticated user after this session ends, using the selected agent’s tools and configuration. Use Once with a future RFC3339 timestamp for a single run; use Cron for repetition. Returns the saved routine ID and next firing. Do not use reminders for work that should execute. Do not automatically create a new routine on every run of an existing routine."+)]+pub struct CreateRoutine {+ /// Name, instructions, target, and schedule.+ pub configuration: RoutineConfiguration,+}+impl ToolAnnotated for CreateRoutine {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::additive("Create routine");+}+#[async_trait]+impl AsyncTool<RoutineToolContext> for CreateRoutine {+ type Output = RoutineInfo;+ async fn call(+ &self,+ context: ServiceContext<RoutineToolContext>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ context+ .service()?+ .create(&request.user_id, &self.configuration)+ .await+ .map_err(error)+ }+}+/// Find existing routines before scheduling or editing.+#[derive(Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ListRoutines",+ description = "Find the authenticated user’s routines, including work delegated to other agents. Filter by name/instructions or enabled state. Returns up to 50 matches and the full count; narrow the query if truncated. Use ReadRoutine for history."+)]+pub struct ListRoutines {+ /// Optional text to match in the routine name or task.+ pub query: Option<String>,+ /// Optional active/paused filter.+ pub enabled: Option<bool>,+}+impl ToolAnnotated for ListRoutines {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("List routines");+}+#[async_trait]+impl AsyncTool<RoutineToolContext> for ListRoutines {+ type Output = RoutineList;+ async fn call(+ &self,+ context: ServiceContext<RoutineToolContext>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let query = self.query.as_deref().unwrap_or("").to_lowercase();+ let routines: Vec<_> = context+ .service()?+ .list(&request.user_id)+ .await+ .map_err(error)?+ .into_iter()+ .filter(|routine| {+ self.enabled+ .is_none_or(|enabled| routine.enabled == enabled)+ && (routine.name.to_lowercase().contains(&query)+ || routine.task.to_string().to_lowercase().contains(&query))+ })+ .collect();+ Ok(RoutineList {+ total: routines.len(),+ routines: routines.into_iter().take(50).collect(),+ })+ }+}+/// Inspect settings and execution results.+#[derive(Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "ReadRoutine",+ description = "Read a routine owned by the authenticated user, including its saved configuration and recent run history. Reading a run transcript still requires its own access."+)]+pub struct ReadRoutine {+ /// Routine UUID from CreateRoutine or ListRoutines.+ pub routine_id: Uuid,+}+impl ToolAnnotated for ReadRoutine {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Read routine");+}+#[async_trait]+impl AsyncTool<RoutineToolContext> for ReadRoutine {+ type Output = RoutineDetails;+ async fn call(+ &self,+ context: ServiceContext<RoutineToolContext>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ context+ .service()?+ .read(&request.user_id, self.routine_id)+ .await+ .map_err(error)+ }+}+/// Exactly one update intention avoids partially-applied configuration/activation changes.+#[derive(Deserialize, JsonSchema)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum RoutineChange {+ /// Pause or resume without rewriting configuration.+ Enabled {+ /// New activation state.+ enabled: bool,+ },+ /// Replace the saved name, instructions, target and schedule. Read first; activation is preserved.+ Configuration {+ /// Complete replacement configuration.+ configuration: RoutineConfiguration,+ },+}+/// Edit or pause an owned routine.+#[derive(Deserialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+#[schemars(+ title = "UpdateRoutine",+ description = "Pause/resume or replace the configuration of a routine owned by the authenticated user. ReadRoutine first before replacing configuration. Select an agent to delegate the routine or a model to run as Macro. Does not change ownership. A running routine can be paused but cannot be reconfigured until it finishes."+)]+pub struct UpdateRoutine {+ /// Routine UUID.+ pub routine_id: Uuid,+ /// One explicit change.+ pub change: RoutineChange,+}+impl ToolAnnotated for UpdateRoutine {+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::destructive("Update routine");+}+#[async_trait]+impl AsyncTool<RoutineToolContext> for UpdateRoutine {+ type Output = RoutineInfo;+ async fn call(+ &self,+ context: ServiceContext<RoutineToolContext>,+ request: RequestContext,+ ) -> ToolResult<Self::Output> {+ let service = context.service()?;+ match &self.change {+ RoutineChange::Enabled { enabled } => {+ service+ .set_enabled(&request.user_id, self.routine_id, *enabled)+ .await+ }+ RoutineChange::Configuration { configuration } => {+ service+ .update(&request.user_id, self.routine_id, configuration)+ .await+ }+ }+ .map_err(error)+ }+}diff --git a/crates/routines/src/lib.rs b/crates/routines/src/lib.rsnew file mode 100644index 0000000000..53d5a4ea6a--- /dev/null+++ b/crates/routines/src/lib.rs@@ -0,0 +1,8 @@+//! Routine tools and a client for the owning scheduled-action service.+#![deny(missing_docs)]+/// Validated routine commands and service capabilities.+pub mod domain;+/// AI tools available to MCP and embedded agents.+pub mod inbound;+/// HTTP implementation of the routine capability.+pub mod outbound;diff --git a/crates/routines/src/outbound.rs b/crates/routines/src/outbound.rsnew file mode 100644index 0000000000..948e78f668--- /dev/null+++ b/crates/routines/src/outbound.rs@@ -0,0 +1,211 @@+//! Authenticated, bounded HTTP calls to the scheduled-action service.+use crate::domain::{+ RoutineConfiguration, RoutineDetails, RoutineInfo, RoutineService, RoutineTarget,+};+use anyhow::{Context, Result, bail, ensure};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER};+use macro_user_id::user_id::MacroUserIdStr;+use reqwest::{Client, Method, Url, header::HeaderValue};+use serde::Deserialize;+use serde_json::Value;+use std::{sync::Arc, time::Duration};+use uuid::Uuid;++/// Reusable client; internal credentials never come from model arguments.+pub struct RoutineClient {+ client: Client,+ base: Url,+ key: HeaderValue,+}+impl RoutineClient {+ /// Build with a trusted service URL and internal key from application configuration.+ pub fn new(base: &str, key: &str) -> Result<Arc<Self>> {+ let base = Url::parse(&format!("{}/", base.trim_end_matches('/')))?;+ ensure!(+ matches!(base.scheme(), "http" | "https")+ && base.host_str().is_some()+ && base.username().is_empty()+ && base.password().is_none()+ && base.query().is_none()+ && base.fragment().is_none(),+ "Invalid routine service URL"+ );+ ensure!(+ !key.trim().is_empty(),+ "Routine service credentials are required"+ );+ let mut key = HeaderValue::from_str(key)?;+ key.set_sensitive(true);+ let client = Client::builder()+ .connect_timeout(Duration::from_secs(5))+ .timeout(Duration::from_secs(30))+ .redirect(reqwest::redirect::Policy::none())+ .retry(reqwest::retry::never())+ .build()?;+ Ok(Arc::new(Self { client, base, key }))+ }+ async fn request<T: serde::de::DeserializeOwned>(+ &self,+ user: &MacroUserIdStr<'static>,+ method: Method,+ path: &str,+ body: Option<Value>,+ ) -> Result<T> {+ let mut request = self+ .client+ .request(method, self.base.join(path)?)+ .header(INTERNAL_API_KEY_HEADER, self.key.clone())+ .header(INTERNAL_MACRO_USER_ID_HEADER, user.as_ref());+ if let Some(body) = body {+ request = request.json(&body);+ }+ let mut response = request.send().await.context("Routine request failed. Check ListRoutines before retrying a creation; the write may have succeeded.")?;+ match response.status().as_u16() {+ 200..=299 => {+ const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;+ ensure!(+ response+ .content_length()+ .is_none_or(|length| length <= MAX_RESPONSE_BYTES as u64),+ "Routine response is too large."+ );+ let mut body = Vec::new();+ while let Some(chunk) = response.chunk().await? {+ ensure!(+ body.len() + chunk.len() <= MAX_RESPONSE_BYTES,+ "Routine response is too large."+ );+ body.extend_from_slice(&chunk);+ }+ serde_json::from_slice(&body).context("Invalid routine service response")+ }+ 400 | 422 => bail!(+ "Invalid routine configuration or unavailable model/agent. Check the schedule and select an accessible agent from ListAgents using its bot.botId."+ ),+ 401 | 403 | 404 => bail!("Routine or target is unavailable to this user."),+ 409 => bail!("Routine is running or changed. Read it again before editing."),+ _ => bail!(+ "Routine service is unavailable. Check ListRoutines before retrying a creation."+ ),+ }+ }+}+#[derive(Deserialize)]+struct WireRoutine {+ id: Uuid,+ name: String,+ enabled: bool,+ trigger: Value,+ task: Value,+ next_run_at: Option<DateTime<Utc>>,+}+impl From<WireRoutine> for RoutineInfo {+ fn from(r: WireRoutine) -> Self {+ Self {+ id: r.id,+ name: r.name,+ enabled: r.enabled,+ trigger: r.trigger,+ task: r.task,+ next_run_at: r.next_run_at,+ }+ }+}+#[async_trait]+impl RoutineService for RoutineClient {+ async fn create(+ &self,+ user: &MacroUserIdStr<'static>,+ config: &RoutineConfiguration,+ ) -> Result<RoutineInfo> {+ let mut body = configuration_body(config, Utc::now())?;+ body["enabled"] = true.into();+ Ok(self+ .request::<WireRoutine>(user, Method::POST, "scheduled-actions", Some(body))+ .await?+ .into())+ }+ async fn list(&self, user: &MacroUserIdStr<'static>) -> Result<Vec<RoutineInfo>> {+ Ok(self+ .request::<Vec<WireRoutine>>(+ user,+ Method::GET,+ "scheduled-actions?include_events=true",+ None,+ )+ .await?+ .into_iter()+ .rev()+ .map(Into::into)+ .collect())+ }+ async fn read(&self, user: &MacroUserIdStr<'static>, id: Uuid) -> Result<RoutineDetails> {+ let routine = self+ .request::<WireRoutine>(user, Method::GET, &format!("scheduled-actions/{id}"), None)+ .await?+ .into();+ let runs = self+ .request::<Vec<Value>>(+ user,+ Method::GET,+ &format!("scheduled-actions/{id}/history"),+ None,+ )+ .await?+ .into_iter()+ .take(50)+ .collect();+ Ok(RoutineDetails { routine, runs })+ }+ async fn update(+ &self,+ user: &MacroUserIdStr<'static>,+ id: Uuid,+ config: &RoutineConfiguration,+ ) -> Result<RoutineInfo> {+ Ok(self+ .request::<WireRoutine>(+ user,+ Method::PUT,+ &format!("scheduled-actions/{id}"),+ Some(configuration_body(config, Utc::now())?),+ )+ .await?+ .into())+ }+ async fn set_enabled(+ &self,+ user: &MacroUserIdStr<'static>,+ id: Uuid,+ enabled: bool,+ ) -> Result<RoutineInfo> {+ Ok(self+ .request::<WireRoutine>(+ user,+ Method::PUT,+ &format!("scheduled-actions/{id}/enabled"),+ Some(serde_json::json!({ "enabled": enabled })),+ )+ .await?+ .into())+ }+}++fn configuration_body(config: &RoutineConfiguration, now: DateTime<Utc>) -> Result<Value> {+ config.validate(now)?;+ let (schedule, timezone) = config.schedule.cron(now)?;+ let mut task = serde_json::json!({ "prompt": "", "user_prompt": config.instructions });+ match &config.target {+ RoutineTarget::Model { model } => task["model"] = model.clone().into(),+ RoutineTarget::Agent { agent_id } => {+ task["agent"] = serde_json::json!({ "bot_id": agent_id })+ }+ }+ Ok(+ serde_json::json!({ "name": config.name, "kind": "Agent", "trigger": { "type": "cron", "schedule": schedule, "timezone": timezone }, "task": task }),+ )+}+#[cfg(test)]+mod test;diff --git a/crates/routines/src/outbound/test.rs b/crates/routines/src/outbound/test.rsnew file mode 100644index 0000000000..118eae5990--- /dev/null+++ b/crates/routines/src/outbound/test.rs@@ -0,0 +1,109 @@+use super::*;+use crate::domain::RoutineSchedule;+#[test]+fn agent_tasks_do_not_silently_become_model_tasks_or_override_defaults() {+ let agent_id = Uuid::from_u128(1);+ let config = RoutineConfiguration {+ name: "Check in".into(),+ instructions: "Summarize blockers".into(),+ target: RoutineTarget::Agent { agent_id },+ schedule: RoutineSchedule::Cron {+ expression: "0 0 9 * * *".into(),+ timezone: "UTC".into(),+ },+ };+ let body = configuration_body(&config, Utc::now()).unwrap();+ assert_eq!(body["task"]["agent"]["bot_id"], agent_id.to_string());+ assert!(body["task"].get("model").is_none());+ assert!(body.get("enabled").is_none());+ assert!(body.get("owner").is_none());+}++#[tokio::test]+async fn requests_forward_authenticated_identity_and_preserve_target_and_activation() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/scheduled-action", listener.local_addr().unwrap());+ let id = Uuid::from_u128(1);+ let wire = serde_json::json!({ "id": id, "name": "Check in", "enabled": true, "trigger": { "type": "cron", "schedule": "0 0 9 * * *", "timezone": "UTC" }, "task": {}, "next_run_at": null }).to_string();+ let history = serde_json::json!([{ "id": id, "status": "Completed" }]);+ let responses = [+ wire.clone(),+ wire.clone(),+ wire.clone(),+ wire,+ history.to_string(),+ ];+ let server = tokio::spawn(async move {+ let mut requests = Vec::new();+ for wire in responses {+ let (mut stream, _) = listener.accept().await.unwrap();+ let mut bytes = Vec::new();+ loop {+ let mut chunk = [0_u8; 4096];+ let read = stream.read(&mut chunk).await.unwrap();+ assert!(read > 0);+ bytes.extend_from_slice(&chunk[..read]);+ let text = String::from_utf8_lossy(&bytes);+ if let Some(header_end) = text.find("\r\n\r\n") {+ let length = text[..header_end]+ .lines()+ .find_map(|line| {+ line.to_lowercase()+ .strip_prefix("content-length: ")+ .map(|n| n.parse::<usize>().unwrap())+ })+ .unwrap_or(0);+ if bytes.len() >= header_end + 4 + length {+ break;+ }+ }+ }+ requests.push(String::from_utf8(bytes).unwrap());+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",+ wire.len(),+ wire+ );+ stream.write_all(response.as_bytes()).await.unwrap();+ }+ requests+ });+ let client = RoutineClient::new(&url, "test-internal-key").unwrap();+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let config = RoutineConfiguration {+ name: "Check in".into(),+ instructions: "Prepare a brief".into(),+ target: RoutineTarget::Agent { agent_id: id },+ schedule: RoutineSchedule::Once {+ at: Utc::now() + chrono::Duration::hours(1),+ },+ };+ client.create(&user, &config).await.unwrap();+ client.update(&user, id, &config).await.unwrap();+ client.set_enabled(&user, id, false).await.unwrap();+ let details = client.read(&user, id).await.unwrap();+ assert_eq!(details.routine.id, id);+ assert_eq!(serde_json::to_value(details.runs).unwrap(), history);+ let requests = server.await.unwrap();+ for request in &requests {+ assert!(request.contains("x-internal-auth-key: test-internal-key\r\n"));+ assert!(request.contains("x-internal-macro-user-id: macro|[email protected]\r\n"));+ }+ assert!(requests[0].starts_with("POST /scheduled-action/scheduled-actions HTTP/1.1"));+ assert!(requests[3].starts_with(&format!(+ "GET /scheduled-action/scheduled-actions/{id} HTTP/1.1"+ )));+ assert!(requests[4].starts_with(&format!(+ "GET /scheduled-action/scheduled-actions/{id}/history HTTP/1.1"+ )));+ let bodies: Vec<Value> = requests[..3]+ .iter()+ .map(|r| serde_json::from_str(r.split_once("\r\n\r\n").unwrap().1).unwrap())+ .collect();+ assert_eq!(bodies[0]["enabled"], true);+ assert!(bodies[0].get("owner").is_none());+ assert_eq!(bodies[0]["task"]["agent"]["bot_id"], id.to_string());+ assert!(bodies[1].get("enabled").is_none());+ assert_eq!(bodies[2], serde_json::json!({"enabled": false}));+}diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rsindex 465333d077..91b580427a 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs@@ -139,6 +139,7 @@ fn document_lifecycle_events_map_to_updated_and_deleted_patches() {created_at: None,});let deleted = DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_string(),actor_user_id: None,actor: None,diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rsindex 8cbf4ded69..555f2811b4 100644--- a/crates/webhook/src/domain/ingestion/test.rs+++ b/crates/webhook/src/domain/ingestion/test.rs@@ -502,6 +502,7 @@ fn document_event_cases() -> Vec<EventCase> {EventCase::new(TestBrokerEvent::Document(Event::with_schema_version(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user_id("macro|[email protected]")),actor: None,@@ -1297,6 +1298,7 @@ async fn malformed_document_id_is_permanent_and_skips_access_resolution() {let enqueuer = MockEnqueuer::default();let service = service(access.clone(), repository, enqueuer);let event = Event::new(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: "not-a-uuid".to_string(),actor_user_id: None,actor: None,diff --git a/crates/webhook/src/inbound/kafka_consumer/test.rs b/crates/webhook/src/inbound/kafka_consumer/test.rsindex 3152b17893..0a5a784757 100644--- a/crates/webhook/src/inbound/kafka_consumer/test.rs+++ b/crates/webhook/src/inbound/kafka_consumer/test.rs@@ -39,6 +39,7 @@ fn decode_message(topic: &str, payload: &[u8]) -> Result<DeclaredMacroEvent, Evefn document_event() -> Event<DocumentTopicEvent> {Event::new(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: "doc_1".to_string(),actor_user_id: None,actor: None,diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 71c5e6b253..b06ab84f1c 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -90,7 +90,9 @@ successfully rather than hashing the empty JavaScript placeholder.| `/app/database/<uuid>` | A database with table and board views; stays at this URL rather than moving into Drive (requires the Databases flag) || `/app/documents`, `/app/files` | Legacy Files views; redirect to `/app/drive` || `/app/chat/<uuid>` | A standalone AI chat |-| `/app/automation/<uuid>` | Cron routine editor; event routines show a backend-managed notice |+| `/app/routines` | Routines list in the Agents workspace |+| `/app/routines/new` | Opens the routine creation modal |+| `/app/routines/<uuid>` | Routine settings, triggers, and run history in the Agents workspace || `/app/agent/<uuid>` | An agent session (opened from `@macro` under the agents rollout, or `@coder` / `@cursor`) || `/app/md/<doc>/chat/<chat>` | Doc + doc-scoped chat in a split || `/app/md/<doc>/channel/<channel>` | Doc + channel in a split |@@ -487,7 +489,7 @@ or the picture opens that same card as a bottom sheet; any action there runs anddismisses the sheet. Desktop keeps click-to-DM on the picture itself, which touchdrops in favour of the card's DM action.-`Create` button (top-left) opens a menu of: Email E, Automation U, Agent A, Skill K,+`Create` button (top-left) opens a menu of: Email E, Routine U, Agent A, Skill K,Document D, Task T, Project P, Reminder R, Snippet S, Message M, Channel G, Call C, Canvas N, Folder F, Code O.Document navigates straight into a new doc; Task, Project, and Channel open dialogs.When calls are enabled, `C C` (Create → Call) opens `/app/meet/new`. The call is@@ -506,32 +508,102 @@ Release, cancellation, or dragging outsiderestores the surface. Disabled controls stay still; reduced motion keeps onlythe static highlight.-## Routines (automations)--Create → Automation creates an active cron-scheduled routine. Cron routines support-editing instructions, schedule, and the **Execution target** model/agent picker,-Rename, the **Active** switch, Duplicate, Run Now, and History links to run chats.-The **Active** switch next to **Run Now** pauses or resumes the routine at once,-separately from autosave and even while the draft is invalid. A paused routine-shows no next run in its editor; routine lists mute its title and label it-**Paused**. Edits autosave in order and never change whether the routine is-active. **Run Now** stays disabled until the latest valid edit saves successfully;-it also works while paused. A failed save keeps the selection visible with-**Changes not saved** and **Retry save**. While running, configuration cannot be-changed, and the switch can pause the routine but cannot resume it until the run-ends. Duplicate retains the saved execution configuration and active state, not-unsaved edits.-If a background refresh fails, cached cron routines stay listed and their editor-and queued autosave remain available. An initial load failure without cached data-shows **Unable to load automation** instead. Cached event routines remain-backend-managed even after a refresh failure.--Event-triggered routines are backend-managed through the scheduled-action API.-They do not appear in the frontend's cron-only automation lists. Opening an-API-created event routine at `/app/automation/<uuid>` shows **Backend-managed-routine**, not a cron editor. This surface offers no event editing, duplication,-or run/history controls; manage those through the API. It never replaces an-event trigger with a cron schedule. There is no event-filter composer yet.+## Routines++Open **Agents → Routines** for your routines. Opening a routine updates the URL+to `/app/routines/<uuid>` while keeping the Agents workspace. Reloading a detail+URL restores that routine; browser Back and Forward restore the list or detail.+Existing `/app/automation/<uuid>` links resolve to the canonical routine URL.+Saved split layouts and document/channel/spreadsheet mentions using the old+block name also open routines; newly copied links use `/app/routines/<uuid>`.+On the legacy Agents screen, use the **Routines** button above the list. On touch devices,+`/app/routines` opens the routines list directly. Routines use+full-width entity rows with **Created by**, **Status**, **Runs with**, and **Enabled**+columns. The search field sits below the top bar, as in Projects; search by name,+creator, or model/agent, or press **Cmd/Ctrl+F** to focus it. **Create Routine** sits+to the right of search. Click a row to open its settings in the same pane. Toggle+the **Enabled** checkbox property directly in the list to pause or resume it.+Open the routine and use its **Run History** tab to see past runs.++**Create → Routine** (U) and **Create Routine** open the same popover host as task+and project creation. Enter a name and instructions, then choose a model or agent+with the first property chip below the prompt. **Add trigger** follows it; each+saved trigger becomes a chip, with another **Add trigger** always at the end.+**Start enabled** controls whether the saved routine starts listening immediately. **Create routine** opens+its details inside the Agents pane, retaining the sidebar. Creation has no history+tab or templates. Unsaved drafts are retained for three minutes.++**Add trigger → Scheduled** offers Hourly, Daily, Weekly, Monthly, and Custom+(cron) in a single anchored panel. Choose the frequency and type a time, or type+**every weekday at 9am** or **every Monday at 3:30pm**. **Run once** offers Macro’s+natural date search (**tomorrow 9am**, **in 2 hours**) and an inline calendar with+time controls. Click **Add trigger** to confirm. Click a saved chip to edit it;+**Done** applies changes and **Cancel** leaves it unchanged. The panel floats over+the composer without moving it. Recurring schedules retain their time zones;+one-off times use the browser’s local time.++The event menu groups Macro activity triggers by surface:++- **Channels:** **Channel created**, **Message sent in channel**, and **@ mentioned in channel**.+- **Documents:** **Document created** and **Document deleted**. Tasks are separate.+- **Tasks:** **Task created**, **Status changed**, **Priority changed**, and **Any property changed**.+- **Email:** **New email received** in the routine owner's inbox, excluding spam, trash, drafts, and historical imports.++For messages, mentions, deletion, and task changes, choose specific accessible+channels/documents/tasks or any accessible item in the same panel. Creation+triggers cover newly created accessible items; email covers the owner's inbox.+Mentions match only @ mentions of the routine owner. **Any property changed**+also includes status and priority; overlapping selectors start only one run for+the same event. These are Macro events, not incoming HTTP webhooks. Bot-authored+or delegated changes do not retrigger routines. Saved legacy selectors remain+editable but are no longer offered in the new-trigger menu.++A routine can combine up to sixteen trigger groups: each schedule is a group,+and up to thirty-two activity filters share one event group;+matching any trigger runs it. Open a trigger chip and choose **Remove trigger**+to remove it. The routine's top bar uses the task breadcrumb layout:+**Routines → routine name**, followed by the three-dot menu for duplication and+deletion. Tabs immediately beside that menu switch between **Overview** and+**Run History**. Overview follows the project home layout: an editable title,+a model property chip, and a plain prompt editor. A trigger card sits below the+model: trigger chips at the top left, **Run now** at the top right, and the+**Enabled** / **Disabled** status with **Next run** along the bottom.+The **Run options** dropdown contains+**Enable routine** / **Disable routine** and **Copy prompt**, which copies the+current instructions, including unsaved edits. **Run History** uses full-width+Soup rows for past agent sessions, with each run's+outcome, duration, and time. Click a row or press Enter to open its session;+Shift opens it in another split. **Back to routines** returns to the list in the+same pane.++**Disable routine** pauses immediately, including with invalid+unsaved edits. Resuming waits for valid settings to save. Settings autosave in+order without changing activation. **Run Now** waits for the latest valid edit+to save; it also works while paused. A failed save keeps the draft and offers+**Retry save**. If another editor changed the configuration, **Reload latest**+loads those settings before further edits. While running, configuration is locked; the routine can be paused+but cannot resume until the run ends. Completed one-offs remain visible with+their history and do not repeat.++Routines are private to their owner. Other users cannot list or open the routine+or its history, even if they belong to the same team. Run conversations keep+their own permissions.++**Run History** shows outcome, duration, and firing time. History loads fifty+rows at a time; **Load more runs** reveals older records. Accessible run rows+open the agent session created by that run. Selecting a model uses the same+Macro agent-session runtime as the new AI chat composer, with that model;+selecting an agent uses its runtime and default model or selected override.+Historical runs that created legacy chats still open those chats. Unavailable conversations+remain non-clickable. Macro event routines also support editing, history, and+activation.++MCP and Macro agent tools expose **CreateRoutine**, **ListRoutines**,+**ReadRoutine**, and **UpdateRoutine**. Select `target.type: "agent"` with the+`bot.botId` from **ListAgents** as `agentId`, or `target.type: "model"` with a runtime+model ID. `schedule.type: "once"` accepts a future RFC3339 `at` timestamp;+`"cron"` accepts a six-field `expression` and IANA `timezone`. Routine ownership+comes from the authenticated caller, never a model-supplied user ID.## Command menu (Ctrl+K)diff --git a/packages/lexical-core/tests/channel-mentions.test.ts b/packages/lexical-core/tests/channel-mentions.test.tsindex 90ed9b5fd6..d95b6734a0 100644--- a/packages/lexical-core/tests/channel-mentions.test.ts+++ b/packages/lexical-core/tests/channel-mentions.test.ts@@ -28,6 +28,7 @@ describe('extractChannelMentionsFromMarkdown', () => {['call', 'call'],['calendar', 'calendar_event'],['automation', 'automation'],+ ['routine', 'automation'],['company', 'crm_company'],['contact', 'crm_contact'],];@@ -67,6 +68,14 @@ describe('extractChannelMentionsFromMarkdown', () => {expect(extractChannelMentionsFromMarkdown(markdown)).toHaveLength(1);});+ it('deduplicates routines across current and saved block names', () => {+ expect(+ extractChannelMentionsFromMarkdown(+ `${documentMention('routine-1', 'routine')} ${documentMention('routine-1', 'automation')}`+ )+ ).toEqual([{ entityType: 'automation', entityId: 'routine-1' }]);+ });+it('extracts mentions from content containing bare angle brackets', () => {const markdown = `1 < 2 and ${documentMention('doc-1', 'md')}`;expect(extractChannelMentionsFromMarkdown(markdown)).toEqual([diff --git a/packages/lexical-core/utils/mentions.ts b/packages/lexical-core/utils/mentions.tsindex e763eeaaec..48256f2289 100644--- a/packages/lexical-core/utils/mentions.ts+++ b/packages/lexical-core/utils/mentions.ts@@ -105,6 +105,7 @@ function documentMentionEntityType(blockName: string): string {return 'call';case 'calendar':return 'calendar_event';+ case 'routine':case 'automation':return 'automation';case 'company':diff --git a/packages/lexical-core/utils/message-references.ts b/packages/lexical-core/utils/message-references.tsindex 9690858ce4..989021ac99 100644--- a/packages/lexical-core/utils/message-references.ts+++ b/packages/lexical-core/utils/message-references.ts@@ -25,6 +25,8 @@ export function messageReference(id: string): AuthoredMessageReference | undefined {if (kind === 'email' || kind === 'email_thread') kind = 'thread';+ // Keep the server's reference wire type while accepting the current UI name.+ if (kind === 'routine') kind = 'automation';if (kind === 'user' && id.startsWith('bot|')) kind = 'bot';switch (kind) {case 'user':diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.tsindex b5f5823410..c44b139bb1 100644--- a/packages/sdk/generated/scheduled-action/index.ts+++ b/packages/sdk/generated/scheduled-action/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTrigger, RoutineTriggers, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';diff --git a/packages/sdk/generated/scheduled-action/sdk.gen.ts b/packages/sdk/generated/scheduled-action/sdk.gen.tsindex b03eebb939..e63d5ba2ac 100644--- a/packages/sdk/generated/scheduled-action/sdk.gen.ts+++ b/packages/sdk/generated/scheduled-action/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { CreateScheduledActionData, CreateScheduledActionErrors, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionErrors, DeleteScheduledActionResponses, ExecuteScheduledActionNowData, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponses, ListScheduledActionHistoryData, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsErrors, ListScheduledActionsResponses, ScheduledActionHealthData, ScheduledActionHealthResponses, SetScheduledActionEnabledData, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponses, UpdateScheduledActionData, UpdateScheduledActionErrors, UpdateScheduledActionResponses } from './types.gen';+import type { CreateScheduledActionData, CreateScheduledActionErrors, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionErrors, DeleteScheduledActionResponses, ExecuteScheduledActionNowData, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponses, GetScheduledActionData, GetScheduledActionErrors, GetScheduledActionResponses, ListScheduledActionHistoryData, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsErrors, ListScheduledActionsResponses, ScheduledActionHealthData, ScheduledActionHealthResponses, SetScheduledActionEnabledData, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponses, UpdateScheduledActionData, UpdateScheduledActionErrors, UpdateScheduledActionResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -80,6 +80,10 @@ export class Sdk extends HeyApiClient {return (options.client ?? this.client).delete<DeleteScheduledActionResponses, DeleteScheduledActionErrors, ThrowOnError>({ url: '/scheduled-actions/{id}', ...options });}+ public getScheduledAction<ThrowOnError extends boolean = false>(options: Options<GetScheduledActionData, ThrowOnError>): RequestResult<GetScheduledActionResponses, GetScheduledActionErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetScheduledActionResponses, GetScheduledActionErrors, ThrowOnError>({ url: '/scheduled-actions/{id}', ...options });+ }+public updateScheduledAction<ThrowOnError extends boolean = false>(options: Options<UpdateScheduledActionData, ThrowOnError>): RequestResult<UpdateScheduledActionResponses, UpdateScheduledActionErrors, ThrowOnError> {return (options.client ?? this.client).put<UpdateScheduledActionResponses, UpdateScheduledActionErrors, ThrowOnError>({url: '/scheduled-actions/{id}',diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.tsindex 5cccba9465..76eff45dac 100644--- a/packages/sdk/generated/scheduled-action/types.gen.ts+++ b/packages/sdk/generated/scheduled-action/types.gen.ts@@ -56,7 +56,7 @@ export type ActionExecutionRecord = {export type ActionKind = 'Agent';/**- * Exactly one trigger per action. Existing cron validation is reused.+ * A routine may run on one trigger or any of several schedules and Macro events.*/export type ActionTrigger = {schedule: Schedule;@@ -65,6 +65,9 @@ export type ActionTrigger = {} | {filters: EventFilters;type: 'events';+} | {+ triggers: RoutineTriggers;+ type: 'multiple';};export type AgentTask = {@@ -125,7 +128,7 @@ export type EventFilters = Array<EventFilter>;* Closed allowlist: unknown names, deletions and ambiguous attribution are not* selectors. Adding a broker variant does not automatically enable routines.*/-export type EventName = 'document.created' | 'document.updated' | 'channel.created' | 'channel.message_posted' | 'channel.mentioned' | 'channel.message_patched' | 'channel.message_attachment_created';+export type 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';/*** Transcript resource created by a run. Never infer this from current task configuration.@@ -175,6 +178,23 @@ export type LegacyActionConfiguration = {*/export type RoutineModelId = string;+/**+ * An individual trigger in a routine's trigger list.+ */+export type RoutineTrigger = {+ schedule: Schedule;+ timezone: string;+ type: 'cron';+} | {+ filters: EventFilters;+ type: 'events';+};++/**+ * Bounded schedules and one combined set of event filters.+ */+export type RoutineTriggers = Array<RoutineTrigger>;+export type Schedule = string;export type ScheduledAction = {@@ -356,6 +376,32 @@ export type DeleteScheduledActionResponses = {export type DeleteScheduledActionResponse = DeleteScheduledActionResponses[keyof DeleteScheduledActionResponses];+export type GetScheduledActionData = {+ body?: never;+ path: {+ /**+ * ID of the scheduled action+ */+ id: string;+ };+ query?: never;+ url: '/scheduled-actions/{id}';+};++export type GetScheduledActionErrors = {+ 401: string;+ 404: string;+ 500: string;+};++export type GetScheduledActionError = GetScheduledActionErrors[keyof GetScheduledActionErrors];++export type GetScheduledActionResponses = {+ 200: ScheduledActionResponse;+};++export type GetScheduledActionResponse = GetScheduledActionResponses[keyof GetScheduledActionResponses];+export type UpdateScheduledActionData = {body: UpdateScheduledAction;path: {diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex a0abcbffc9..4b4211a435 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -4879,6 +4879,7 @@ export type DocumentDeletedMetadata = {* Project the document belonged to, when any.*/project_id?: string | null;+ sub_type?: null | DocumentSubType;};/**diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.jsonindex 00b6c827e0..50a8dcb321 100644--- a/packages/sdk/specs/scheduled-action.json+++ b/packages/sdk/specs/scheduled-action.json@@ -158,6 +158,63 @@}},"/scheduled-actions/{id}": {+ "get": {+ "tags": ["scheduled actions"],+ "operationId": "get_scheduled_action",+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "ID of the scheduled action",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScheduledActionResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ },"put": {"tags": ["scheduled actions"],"operationId": "update_scheduled_action",@@ -674,9 +731,22 @@"enum": ["events"]}}+ },+ {+ "type": "object",+ "required": ["triggers", "type"],+ "properties": {+ "triggers": {+ "$ref": "#/components/schemas/RoutineTriggers"+ },+ "type": {+ "type": "string",+ "enum": ["multiple"]+ }+ }}],- "description": "Exactly one trigger per action. Existing cron validation is reused."+ "description": "A routine may run on one trigger or any of several schedules and Macro events."},"AgentTask": {"type": "object",@@ -689,7 +759,7 @@},{"$ref": "#/components/schemas/AgentTaskAgent",- "description": "Absent for legacy model-only tasks."+ "description": "Absent when using Macro's agent-session runtime with a selected model."}]},@@ -785,6 +855,12 @@"enum": ["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",@@ -889,6 +965,47 @@"type": "string","description": "A nonblank model identifier. Runtime catalogs, not the scheduler, own availability."},+ "RoutineTrigger": {+ "oneOf": [+ {+ "type": "object",+ "required": ["schedule", "timezone", "type"],+ "properties": {+ "schedule": {+ "$ref": "#/components/schemas/Schedule"+ },+ "timezone": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "enum": ["cron"]+ }+ }+ },+ {+ "type": "object",+ "required": ["filters", "type"],+ "properties": {+ "filters": {+ "$ref": "#/components/schemas/EventFilters"+ },+ "type": {+ "type": "string",+ "enum": ["events"]+ }+ }+ }+ ],+ "description": "An individual trigger in a routine's trigger list."+ },+ "RoutineTriggers": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/RoutineTrigger"+ },+ "description": "Bounded schedules and one combined set of event filters."+ },"Schedule": {"type": "string"},diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 8afacdf6af..5385e55c6d 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -23405,6 +23405,17 @@"project_id": {"type": ["string", "null"],"description": "Project the document belonged to, when any."+ },+ "sub_type": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/DocumentSubType",+ "description": "Subtype captured before deletion, so consumers can distinguish tasks."+ }+ ]}}},diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex 90de6940fc..fe90b6fef5 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -263,6 +263,7 @@ export const scheduledActionBacklog = ['createScheduledAction','deleteScheduledAction','executeScheduledActionNow',+ 'getScheduledAction','listScheduledActionHistory','listScheduledActions','setScheduledActionEnabled',diff --git a/packages/spreadsheet/src/cell-mentions.ts b/packages/spreadsheet/src/cell-mentions.tsindex c0ad875a43..89ce7f799f 100644--- a/packages/spreadsheet/src/cell-mentions.ts+++ b/packages/spreadsheet/src/cell-mentions.ts@@ -25,6 +25,7 @@ const blocks = new Set(['csv','write','automation',+ 'routine','pr','md','task',diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.ymlindex 6282689f06..26602b5063 100644--- a/rules/ast-grep/ts-feature-components-presentational.yml+++ b/rules/ast-grep/ts-feature-components-presentational.yml@@ -13,6 +13,7 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/routines/components/**- apps/web/src/features/scheduling/components/**- apps/web/src/features/crm/components/**- apps/web/src/features/slack-import/components/**diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.ymlindex a9f053e4c2..5a2a435f4b 100644--- a/rules/ast-grep/ts-feature-core-pure.yml+++ b/rules/ast-grep/ts-feature-core-pure.yml@@ -12,9 +12,10 @@ note: |-reactive view models in `primitives/`. The `dateBucket` import from`soup/collection/date-buckets` (a pure date-fns module, not the soup barrel)is the documented exception for feed labels that must match soup views.- The shared @core/util/base64 codec is also pure and may be reused by email.+ The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/routines/core/**- apps/web/src/features/scheduling/core/**- apps/web/src/features/crm/core/**- apps/web/src/features/slack-import/core/**@@ -37,7 +38,7 @@ rule:kind: stringregex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))not:- regex: ^['"]@core/util/base64['"]+ regex: ^['"]@core/util/(base64|cron|dateSearch/parseTime)['"]any:- inside:kind: import_statementdiff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.ymlindex c5a1b5698c..e835241355 100644--- a/rules/ast-grep/ts-feature-data-no-ui.yml+++ b/rules/ast-grep/ts-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/routines/queries/**+ - apps/web/src/features/routines/primitives/**- apps/web/src/features/scheduling/core/**- apps/web/src/features/scheduling/context/**- apps/web/src/features/scheduling/queries/**diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.ymlindex 6591bf18c8..0709bb8c97 100644--- a/rules/ast-grep/ts-feature-layers-use-context.yml+++ b/rules/ast-grep/ts-feature-layers-use-context.yml@@ -15,6 +15,10 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/routines/queries/**+ - apps/web/src/features/routines/primitives/**+ - apps/web/src/features/routines/components/**+ - apps/web/src/features/routines/views/**- apps/web/src/features/scheduling/context/**- apps/web/src/features/scheduling/queries/**- apps/web/src/features/scheduling/primitives/**diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.ymlindex c1de968ebe..0940f2092f 100644--- a/rules/ast-grep/tsx-feature-components-presentational.yml+++ b/rules/ast-grep/tsx-feature-components-presentational.yml@@ -13,6 +13,7 @@ note: |-untyped wire JSON for property-changed rows. In block-agent, `ui/` isthe presentation layer and `component/` is the composition layer.files:+ - apps/web/src/features/routines/components/**- apps/web/src/features/scheduling/components/**- apps/web/src/features/crm/components/**- apps/web/src/features/slack-import/components/**diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.ymlindex 88de22ae64..2e1ff30aaa 100644--- a/rules/ast-grep/tsx-feature-core-pure.yml+++ b/rules/ast-grep/tsx-feature-core-pure.yml@@ -12,9 +12,10 @@ note: |-reactive view models in `primitives/`. The `dateBucket` import from`soup/collection/date-buckets` (a pure date-fns module, not the soup barrel)is the documented exception for feed labels that must match soup views.- The shared @core/util/base64 codec is also pure and may be reused by email.+ The shared @core/util/base64 codec, cron helpers, and dateSearch/parseTime parser are pure utilities and may be reused.Block-agent names its rendering layers `ui/` and `component/`.files:+ - apps/web/src/features/routines/core/**- apps/web/src/features/scheduling/core/**- apps/web/src/features/crm/core/**- apps/web/src/features/slack-import/core/**@@ -37,7 +38,7 @@ rule:kind: stringregex: ^['"](solid-js|@urql|urql|@app/lib/urql|@queries/|@service-storage/|@core/|@property/|@components/|@ui|@entity/|(\.\./)+(queries|primitives|components|views|ui|component|context)(/|['"]))not:- regex: ^['"]@core/util/base64['"]+ regex: ^['"]@core/util/(base64|cron|dateSearch/parseTime)['"]any:- inside:kind: import_statementdiff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.ymlindex 24b14e4725..d32a2c0d77 100644--- a/rules/ast-grep/tsx-feature-data-no-ui.yml+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml@@ -11,6 +11,8 @@ note: |-with fake clients and controllers with fake capabilities; neither importsrendering code, including block-agent’s `ui/` and `component/` layers.files:+ - apps/web/src/features/routines/queries/**+ - apps/web/src/features/routines/primitives/**- apps/web/src/features/scheduling/core/**- apps/web/src/features/scheduling/context/**- apps/web/src/features/scheduling/queries/**diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.ymlindex 2fb2c41c6b..f7faa293a2 100644--- a/rules/ast-grep/tsx-feature-layers-use-context.yml+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml@@ -15,6 +15,10 @@ note: |-`files` in each ts-/tsx-feature-* rule. Block-agent uses `ui/` forpresentation and `component/` for composition.files:+ - apps/web/src/features/routines/queries/**+ - apps/web/src/features/routines/primitives/**+ - apps/web/src/features/routines/components/**+ - apps/web/src/features/routines/views/**- apps/web/src/features/scheduling/context/**- apps/web/src/features/scheduling/queries/**- apps/web/src/features/scheduling/primitives/**diff --git a/services/bots/ROUTINES.md b/services/bots/ROUTINES.mdnew file mode 100644index 0000000000..30b5389a54--- /dev/null+++ b/services/bots/ROUTINES.md@@ -0,0 +1,40 @@+# Routines for Macro and integrations++Routines complement the event-driven bots in this directory. The Stripe bot posts+payment and cancellation notifications; the Anthropic status bot posts provider+incident updates. A routine can turn those messages into a useful briefing+without changing either bot's ingestion behavior.++Ideas to configure through **Agents → Routines → Create Routine**:++| Routine | Sources | Suggested cadence | Result |+| --- | --- | --- | --- |+| Start the day informed | Tasks, conversations, calendar | Weekdays, 09:00 | Deadlines, blockers, decisions, source links |+| Keep the team in sync | Referenced project channels | Friday, 16:00 | Draft progress report and next priorities |+| Catch work that slipped | Open tasks and project conversations | Monday/Wednesday/Friday, 15:00 | Prioritized follow-up list |+| Walk into meetings prepared | Calendar and linked Macro context | Weekdays, 08:30 | Objectives, recent decisions, open questions |+| Spot revenue signals | Stripe bot channel messages | Weekdays, 09:30 | Payment events and cancellation follow-ups |+| Follow up on incidents | Anthropic status bot posts | Daily, 10:00 | Active incidents, latest updates, observed impact |+| Review what shipped | An agent's GitHub connection | Weekdays, 16:30 | Merges, releases, failed checks, waiting reviews |+| Keep the issue queue moving | An agent's Linear connection | Weekdays, 10:30 | Urgent unassigned, blocked, or duplicate issues |++Add the relevant channels, repositories, or teams to the instructions and select+an agent with access. Reports link their+sources and distinguish observed facts from inference. Stripe notifications are+not a complete revenue ledger; status-channel posts are not a live status probe.+Ask for a report to review when the routine should summarize information without+changing external systems.++Useful one-offs include checking an incident again in an hour, preparing tomorrow's+customer meeting, asking a release agent for a post-release summary, or delegating+a follow-up to a specialist agent after the current session ends.++Agents can use `CreateRoutine` with `target: {"type":"agent","agentId":"…"}`+(the persona `bot.botId` from `ListAgents`) and+`schedule: {"type":"once","at":"2030-10-03T09:00:00-04:00"}`. To schedule+itself, an agent selects its own persona ID. The authenticated user owns the+routine, and the scheduler validates access to the selected agent. Recurring+routines use `{"type":"cron","expression":"0 0 9 * * 2-6","timezone":"America/New_York"}`.+Use `ListRoutines` to avoid duplicates, `ReadRoutine` to inspect settings/results,+and `UpdateRoutine` to pause or change future work. A routine should not create+a replacement of itself on each run.diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex f99345c133..7c32b9c921 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -741,7 +741,7 @@ async fn main() -> anyhow::Result<()> {soup_service.clone(),&document_tool_context,),- schedule_tool_context: ai_tools::NoOpScheduleContext,+ schedule_tool_context: ai_tools::build_routine_tool_context()?,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),admission,recorder,diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 830885672c..f88459c241 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -1,8 +1,8 @@use std::sync::Arc;use ai_tools::{- NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpScheduleContext,- NoOpSnsEndpointManager, ToolImportToolContext, ToolNotificationQueue, ToolServiceContext,+ NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress, NoOpSnsEndpointManager,+ ToolImportToolContext, ToolNotificationQueue, ToolServiceContext,};use anyhow::Context;use bots::outbound::pg_bots_repo::PgBotsRepo;@@ -474,7 +474,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<Toteam_tool_context: ai_tools::build_team_tool_context(db.clone()),crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),skill_tool_context,- schedule_tool_context: NoOpScheduleContext,+ schedule_tool_context: ai_tools::build_routine_tool_context()?,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),admission: ai_billing::composition::pg_admission_service(db.clone(),diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.tomlindex 7cff8d7e5c..aa0f0991a0 100644--- a/services/scheduled_action/Cargo.toml+++ b/services/scheduled_action/Cargo.toml@@ -21,23 +21,29 @@ default = []local_auth = ["macro_authorization/local_auth"][dependencies]-ai_billing = { path = "../../crates/ai_billing" }+ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }+ai_usage = { path = "../../crates/ai_usage" }+bots = { path = "../../crates/bots", features = ["outbound"] }roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }activity = { path = "../../crates/activity", default-features = false }agent_runtime_protocol = { path = "../../crates/agent_runtime_protocol", default-features = false }agent_session = { path = "../../crates/agent_session", default-features = false, features = ["admission"] }bot_id = { path = "../../crates/bot_id" }-bots = { path = "../../crates/bots", default-features = false, features = ["outbound"] }channel_sender = { path = "../../crates/channel_sender" }channels = { path = "../../crates/channels", default-features = false }documents = { path = "../../crates/documents", default-features = false }+document_sub_type = { path = "../../crates/document_sub_type" }+email = { path = "../../crates/email", default-features = false }entity_access = { path = "../../crates/entity_access", default-features = false, features = ["inbound", "outbound"] }entity_access_db_utils = { path = "../../crates/entity_access_db_utils" }kafka_util = { path = "../../crates/kafka_util" }macro_event_broker = { path = "../../crates/macro_event_broker", features = ["outbound"] }macro_event_topics = { path = "../../crates/macro_event_topics" }messages = { path = "../../crates/messages", features = ["broker"] }+models_properties = { path = "../../crates/models_properties" }+properties = { path = "../../crates/properties", default-features = false }+system_properties = { path = "../../crates/system_properties" }rdkafka = { workspace = true }reqwest = { workspace = true }rootcause = { workspace = true }@@ -45,7 +51,6 @@ thiserror = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }macro_env_var = { path = "../../crates/macro_env_var" }-macro_queues = { path = "../../crates/macro_queues" }macro_config = { path = "../../crates/macro_config" }macro_authorization = { path = "../../crates/macro_authorization", features = ["postgres",@@ -59,29 +64,20 @@ anyhow = { workspace = true }macro_uuid = { path = "../../crates/macro_uuid"}chrono = { workspace = true}chrono-tz = { workspace = true }-agent = { path = "../../crates/agent" }-ai_usage = { path = "../../crates/ai_usage" }tokio = { workspace = true, features = ["signal"] }tokio-util = { workspace = true, features = ["rt"] }futures = { workspace = true }tracing = { workspace = true }axum = { workspace = true }-ai_tools = { path = "../../crates/ai_tools" }-ai_toolset = { path = "../../crates/ai_toolset" }-aws-sdk-sqs = { workspace = true }-chat = { path = "../../crates/chat" }connection_gateway_client = { path = "../../crates/connection_gateway_client" }share_permission_db_utils = { path = "../../crates/share_permission_db_utils" }models_permissions = { path = "../../crates/models_permissions" }macro_db_client = { path = "../../crates/macro_db_client" }-memory = { path = "../../crates/memory" }model = { path = "../../crates/model" }model-entity = { path = "../../crates/model-entity" }model_owner = { path = "../../crates/model_owner" }entity_registry = { path = "../../crates/entity_registry/entity_registry", features = ["axum"] }entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }-model_notifications = { path = "../../crates/model_notifications" }-notification = { path = "../../crates/notification" }utoipa = { workspace = true, features = ["axum_extras", "chrono"] }utoipa-swagger-ui = { workspace = true }tower = { workspace = true }diff --git a/services/scheduled_action/src/bins/service.rs b/services/scheduled_action/src/bins/service.rsindex a274a68ab9..1f973150b2 100644--- a/services/scheduled_action/src/bins/service.rs+++ b/services/scheduled_action/src/bins/service.rs@@ -1,11 +1,9 @@#![recursion_limit = "256"]use std::{future::Future, sync::Arc, time::Duration};-use ai_tools::{AiHost, build_tool_service_context_from_env, tools_for};use anyhow::{Context, Result};use axum::Router;use bots::outbound::pg_bots_repo::PgBotsRepo;-use chat::outbound::postgres::PgChatRepo;use connection_gateway_client::client::ConnectionGatewayClient;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use entity_registry::OwnerGrantPolicy;@@ -17,10 +15,6 @@ use macro_authorization::{};use macro_entrypoint::MacroEntrypoint;use macro_service_urls::{AgentHarnessServiceUrl, ConnectionGatewayUrl};-use memory::domain::service::MemoryServiceImpl;-use memory::outbound::pg_memory_repo::PgMemoryRepo;-use notification::domain::service::SqsNotificationIngress;-use notification::outbound::queue::SqsQueue;use scheduled_action::config::Config;use scheduled_action::domain::event_runs::{PageSize, admission::EventAdmissionService, dispatch::EventDispatchService,@@ -37,9 +31,7 @@ use scheduled_action::inbound::kafka_consumer::run_scheduled_action_event_consumuse scheduled_action::outbound::agent_session_client::AgentSessionClient;use scheduled_action::outbound::conn_gateway_live_updates::ConnGatewayLiveUpdates;use scheduled_action::outbound::event_access::EventAccessAdapter;-use scheduled_action::outbound::inprocess_executor::{- InProcessExecutor, agent_task::AgentTaskRunner,-};+use scheduled_action::outbound::inprocess_executor::InProcessExecutor;use scheduled_action::outbound::pg_event_run_repo::PgEventRunRepo;use scheduled_action::outbound::pg_polling_dispatcher::{PgPollingDispatcher, PgPollingDispatcherLifecycle,@@ -55,7 +47,7 @@ use utoipa_swagger_ui::SwaggerUi;mod test;// ECS stopTimeout is ten seconds. One shared budget includes HTTP, all-// dispatch/execution bookkeeping, and final broker publishes, leaving two seconds.+// dispatch/execution bookkeeping, leaving two seconds.const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(8);const CONSUMER_RESTART_DELAY: Duration = Duration::from_secs(5);// Keep event agent work well below the shared pool's ten connections, leaving@@ -80,21 +72,6 @@ async fn main() -> Result<()> {.context("failed to connect to macrodb")?;let lifecycle = ServiceLifecycle::default();- let tool_context = build_tool_service_context_from_env(- db.clone(),- lifecycle.publishes.clone(),- config.enable_ai_usage_enforcement,- )- .await- .context("failed to build tool service context")?;-- let aws_config = macro_aws_config::get_macro_aws_config().await;- let notification_ingress = Arc::new(SqsNotificationIngress {- queue: SqsQueue::new(- aws_sdk_sqs::Client::new(&aws_config),- macro_queues::NotificationIngressQueue::new().to_string(),- ),- });let secretsmanager_client = secretsmanager_client::SecretsManager::new(aws_sdk_secretsmanager::Client::new(¯o_aws_config::get_macro_aws_config().await),@@ -115,24 +92,15 @@ async fn main() -> Result<()> {db.clone(),)));let event_access = Arc::new(EventAccessAdapter::new(access.as_ref().clone()));- let memory = MemoryServiceImpl::new(- PgMemoryRepo::new(db.clone()),- tool_context.clone(),- tools_for(AiHost::Chat),+ let ai_admission = ai_billing::composition::pg_admission_service(+ db.clone(),+ config.enable_ai_usage_enforcement,);- let ai_admission = tool_context.admission.clone();- let runner = Arc::new(AgentTaskRunner::new(- Arc::clone(&tool_context.chat_tool_context.service),- PgChatRepo::new(db.clone(), registrar),- memory,- tool_context,- notification_ingress,- ));let sessions = Arc::new(AgentSessionClient::new(AgentHarnessServiceUrl::new()?.as_ref(),&config.internal_api_key,)?);- let runner = Arc::new(TargetRunner::new(runner, Arc::clone(&sessions)));+ let runner = Arc::new(TargetRunner::new(Arc::clone(&sessions)));let dispatcher_executor = InProcessExecutor::new(Arc::clone(&repo),runner,@@ -264,7 +232,6 @@ struct ServiceLifecycle {consumers: TaskTracker,workers: TaskTracker,executions: TaskTracker,- publishes: TaskTracker,}impl ServiceLifecycle {@@ -283,8 +250,6 @@ impl ServiceLifecycle {// before considering the execution tracker permanently empty.tokio::join!(self.consumers.wait(), self.workers.wait());self.executions.wait().await;- self.publishes.close();- self.publishes.wait().await;}}@@ -358,7 +323,6 @@ async fn serve_until_shutdown(consumers = lifecycle.consumers.len(),workers = lifecycle.workers.len(),executions = lifecycle.executions.len(),- publishes = lifecycle.publishes.len(),"shutdown deadline reached; unresolved started event runs remain non-retryable");// The process exits next. Never turn uncertain started work back intodiff --git a/services/scheduled_action/src/bins/test.rs b/services/scheduled_action/src/bins/test.rsindex 026ec3a84a..1f3959ef2d 100644--- a/services/scheduled_action/src/bins/test.rs+++ b/services/scheduled_action/src/bins/test.rs@@ -87,18 +87,14 @@ async fn shutdown_interrupts_consumer_restart_backoff() {}#[tokio::test]-async fn shutdown_drains_executions_before_final_publishes() {+async fn shutdown_drains_executions() {let lifecycle = ServiceLifecycle::default();let stop = lifecycle.stop_executions.clone();- let publishes = lifecycle.publishes.clone();let finished = Arc::new(AtomicUsize::new(0));- let published = Arc::clone(&finished);+ let completed = Arc::clone(&finished);lifecycle.executions.spawn(async move {stop.cancelled().await;- assert!(!publishes.is_closed());- publishes.spawn(async move {- published.fetch_add(1, Ordering::SeqCst);- });+ completed.fetch_add(1, Ordering::SeqCst);});let stop_http = lifecycle.stop_http.clone();serve_until_shutdown(@@ -114,7 +110,6 @@ async fn shutdown_drains_executions_before_final_publishes() {.unwrap();assert_eq!(finished.load(Ordering::SeqCst), 1);assert!(lifecycle.executions.is_empty());- assert!(lifecycle.publishes.is_empty());}#[tokio::test]diff --git a/services/scheduled_action/src/config.rs b/services/scheduled_action/src/config.rsindex b64df0b1b9..8e0af01b10 100644--- a/services/scheduled_action/src/config.rs+++ b/services/scheduled_action/src/config.rs@@ -4,11 +4,6 @@//! All required env vars are declared here as typed fields. The//! `doppler_config` binary loads this `Config` from Doppler for both the dev//! and prod environments, surfacing any missing or mistyped values at CI time.-//!-//! The AI tool service context built by-//! [`ai_tools::build_tool_service_context_from_env`] reads several env vars of-//! its own; those are mirrored here so the Doppler validation binary covers-//! them as well.use anyhow::Context;use database_env_vars::DatabaseUrl;@@ -20,20 +15,6 @@ use macro_env_var::env_vars;mod test;env_vars! {- /// Auth key used by the document storage / search / lexical clients.- pub struct DocumentStorageServiceAuthKey;- /// Secrets Manager secret name for the sync service auth key.- pub struct SyncServiceAuthKey;- /// S3 bucket for document storage.- pub struct DocumentStorageBucket;- /// S3 bucket for docx document uploads.- pub struct DocxDocumentUploadBucket;- /// CloudFront distribution URL for document storage.- pub struct DocumentStorageServiceCloudfrontDistributionUrl;- /// CloudFront signer public key id for document storage.- pub struct DocumentStorageServiceCloudfrontSignerPublicKeyId;- /// Secrets Manager secret name for the CloudFront signer private key.- pub struct DocumentStorageServiceCloudfrontSignerPrivateKeySecretName;/// Comma-separated Kafka bootstrap servers for the macro event broker.pub struct KafkaBrokers;}@@ -53,16 +34,6 @@ pub struct Config {pub port: usize,/// The connection URL for the Postgres database this application uses.pub database_url: DatabaseUrl,- pub document_storage_service_auth_key: DocumentStorageServiceAuthKey,- pub sync_service_auth_key: SyncServiceAuthKey,- pub document_storage_bucket: DocumentStorageBucket,- pub docx_document_upload_bucket: DocxDocumentUploadBucket,- pub document_storage_service_cloudfront_distribution_url:- DocumentStorageServiceCloudfrontDistributionUrl,- pub document_storage_service_cloudfront_signer_public_key_id:- DocumentStorageServiceCloudfrontSignerPublicKeyId,- pub document_storage_service_cloudfront_signer_private_key_secret_name:- DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,pub kafka_brokers: KafkaBrokers,/// Enables event-trigger management, Kafka intake, and pending dispatch together./// Register EVENT_ROUTINES_ENABLED as a raw boolean in Doppler before rollout.diff --git a/services/scheduled_action/src/config/test.rs b/services/scheduled_action/src/config/test.rsindex efb772f0eb..1172d93cc3 100644--- a/services/scheduled_action/src/config/test.rs+++ b/services/scheduled_action/src/config/test.rs@@ -5,13 +5,6 @@ fn config_values() -> Value {json!({"ENVIRONMENT": "local","DATABASE_URL": "postgres://localhost/macro",- "DOCUMENT_STORAGE_SERVICE_AUTH_KEY": "test",- "SYNC_SERVICE_AUTH_KEY": "test",- "DOCUMENT_STORAGE_BUCKET": "test",- "DOCX_DOCUMENT_UPLOAD_BUCKET": "test",- "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL": "test",- "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID": "test",- "DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME": "test","KAFKA_BROKERS": "existing-broker:9092","INTERNAL_API_KEY": "test"})diff --git a/services/scheduled_action/src/domain/event_runs.rs b/services/scheduled_action/src/domain/event_runs.rsindex 884e2435b6..900a546d82 100644--- a/services/scheduled_action/src/domain/event_runs.rs+++ b/services/scheduled_action/src/domain/event_runs.rs@@ -203,6 +203,7 @@ impl PendingEventRun {pub enum EventAccessCapability {Document(EntityAccessReceipt<ViewAccessLevel>),Channel(EntityAccessReceipt<ViewOnly>),+ EmailThread(EntityAccessReceipt<ViewAccessLevel>),}impl EventAccessCapability {@@ -216,6 +217,9 @@ impl EventAccessCapability {(Self::Channel(receipt), EventEntityType::Channel) => {receipt_matches(receipt, owner, event, EntityType::Channel)}+ (Self::EmailThread(receipt), EventEntityType::EmailThread) => {+ receipt_matches(receipt, owner, event, EntityType::EmailThread)+ }_ => false,}}diff --git a/services/scheduled_action/src/domain/event_runs/admission.rs b/services/scheduled_action/src/domain/event_runs/admission.rsindex 573b0d6d95..b2e293e400 100644--- a/services/scheduled_action/src/domain/event_runs/admission.rs+++ b/services/scheduled_action/src/domain/event_runs/admission.rs@@ -68,6 +68,9 @@ impl<R: EventRunRepository, A: CurrentOwnerAccess> EventIngestion for EventAdmislet Owner::User(owner) = &configuration.owner else {continue;};+ if !incoming.is_for_owner(owner) {+ continue;+ }let Some(access) = self.access.authorize(owner, &event).await? else {continue;};diff --git a/services/scheduled_action/src/domain/event_runs/admission/test.rs b/services/scheduled_action/src/domain/event_runs/admission/test.rsindex bba8ae2e13..2ac50f3f16 100644--- a/services/scheduled_action/src/domain/event_runs/admission/test.rs+++ b/services/scheduled_action/src/domain/event_runs/admission/test.rs@@ -124,3 +124,66 @@ async fn denied_and_mismatched_receipts_skip_but_unavailable_access_defers_intakassert!(service.ingest(&incoming()).await.is_err());assert!(repo.0.lock().unwrap().pending.is_empty());}++#[tokio::test]+async fn mentions_and_mail_only_admit_their_recipient_even_when_others_have_access() {+ use crate::domain::event_trigger::{EventPayload, MessageFact};+ for is_email in [false, true] {+ let owner = user();+ let mut subscribed = configuration();+ let name = if is_email {+ "email.message_received"+ } else {+ "channel.mentioned"+ };+ subscribed.filters = serde_json::from_value(json!([{"events":[name]}])).unwrap();+ let mut other = subscribed.clone();+ other.action_id = generate_uuid_v7();+ other.owner = Owner::User(MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());+ let action_id = subscribed.action_id;+ let repo = Arc::new(Repo::default());+ repo.0.lock().unwrap().configurations = vec![subscribed, other];+ repo.0+ .lock()+ .unwrap()+ .configurations+ .sort_by_key(|c| c.action_id);+ let access = Arc::new(Access::default());+ let service =+ EventAdmissionService::new(repo.clone(), access.clone(), 10.try_into().unwrap());+ let id = generate_uuid_v7();+ let payload = if is_email {+ EventPayload::Email(serde_json::from_value(json!({+ "event_type":"email.message_received", "metadata": {+ "link_id": id, "owner": owner, "message_id": id, "thread_id": id,+ "provider_message_id": "message", "provider_thread_id": "thread",+ "is_new_thread": true, "to_emails": [], "attachment_count": 0, "is_spam_or_trash": false+ }+ })).unwrap())+ } else {+ EventPayload::Message(MessageFact::Mentioned(+ serde_json::from_value(json!({+ "parent": {"type":"channel", "id": id}, "message_id": id, "root_id": id,+ "sender": "macro|[email protected]", "content":"", "created_at": Utc::now(),+ "mentioned": {"entity_type":"user", "entity_id": owner}+ }))+ .unwrap(),+ ))+ };+ let event = IncomingEvent {+ event_id: generate_uuid_v7(),+ schema_version: 1,+ payload,+ };+ assert_eq!(+ service.ingest(&event).await.unwrap(),+ EventIngestionResult::Admitted { inserted: 1 }+ );+ assert_eq!(repo.0.lock().unwrap().pending[0].action_id, action_id);+ assert_eq!(*access.calls.lock().unwrap(), vec![owner]);+ assert_eq!(+ service.ingest(&event).await.unwrap(),+ EventIngestionResult::Admitted { inserted: 0 }+ );+ }+}diff --git a/services/scheduled_action/src/domain/event_runs/test_support.rs b/services/scheduled_action/src/domain/event_runs/test_support.rsindex 31c2a0edd5..3282bfcc8e 100644--- a/services/scheduled_action/src/domain/event_runs/test_support.rs+++ b/services/scheduled_action/src/domain/event_runs/test_support.rs@@ -60,6 +60,7 @@ pub fn capability(owner: MacroUserIdStr<'static>, event: &EventReference) -> Eveentity_type: match event.entity_type() {EventEntityType::Document => EntityType::Document,EventEntityType::Channel => EntityType::Channel,+ EventEntityType::EmailThread => EntityType::EmailThread,},};match event.entity_type() {@@ -81,6 +82,16 @@ pub fn capability(owner: MacroUserIdStr<'static>, event: &EventReference) -> Eve).unwrap(),),+ EventEntityType::EmailThread => EventAccessCapability::EmailThread(+ EntityAccessReceipt::try_new_authenticated_user(+ owner,+ entity,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+ .unwrap(),+ ),}}diff --git a/services/scheduled_action/src/domain/event_trigger.rs b/services/scheduled_action/src/domain/event_trigger.rsindex 89b0a944ed..477c8ee7c3 100644--- a/services/scheduled_action/src/domain/event_trigger.rs+++ b/services/scheduled_action/src/domain/event_trigger.rs@@ -1,13 +1,15 @@//! Routine-owned event eligibility and exact selector matching.//!//! Adapters strip the broker envelope into [`IncomingEvent`]. Only explicitly-//! allowlisted, human-authored events can become compact [`EventReference`]s.+//! allowlisted human actions and inbound emails become compact [`EventReference`]s.use activity::Actor;use channels::domain::broker_events::ChannelTopicEvent;use chrono::{DateTime, Utc};use chrono_tz::Tz;+use document_sub_type::DocumentSubType;use documents::domain::events::DocumentTopicEvent;+use email::domain::events::EmailTopicEvent;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use messages::domain::{@@ -17,7 +19,10 @@ use messages::domain::{},models::MessageParent,};+use models_properties::EntityType as PropertyEntityType;+use properties::domain::events::PropertyTopicEvent;use serde::{Deserialize, Serialize};+use system_properties::SystemPropertyKey;use utoipa::ToSchema;use super::models::Schedule;@@ -27,11 +32,11 @@ mod test;/// Limits apply before deduplication, including repeated values.pub const MAX_FILTERS: usize = 32;-pub const MAX_EVENTS_PER_FILTER: usize = 7;+pub const MAX_EVENTS_PER_FILTER: usize = 13;pub const MAX_IDS_PER_FILTER: usize = 100;-/// Exactly one trigger per action. Existing cron validation is reused.-#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+/// A routine may run on one trigger or any of several schedules and Macro events.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]pub enum ActionTrigger {Cron {@@ -42,6 +47,106 @@ pub enum ActionTrigger {Events {filters: EventFilters,},+ Multiple {+ triggers: RoutineTriggers,+ },+}++/// An individual trigger in a routine's trigger list.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]+pub enum RoutineTrigger {+ Cron {+ schedule: Schedule,+ #[schema(value_type = String)]+ timezone: Tz,+ },+ Events {+ filters: EventFilters,+ },+}++/// Bounded schedules and one combined set of event filters.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]+#[serde(try_from = "Vec<RoutineTrigger>", into = "Vec<RoutineTrigger>")]+pub struct RoutineTriggers(Vec<RoutineTrigger>);++impl TryFrom<Vec<RoutineTrigger>> for RoutineTriggers {+ type Error = &'static str;++ fn try_from(triggers: Vec<RoutineTrigger>) -> Result<Self, Self::Error> {+ if triggers.is_empty() || triggers.len() > 16 {+ return Err("a routine needs between 1 and 16 triggers");+ }+ if triggers+ .iter()+ .filter(|t| matches!(t, RoutineTrigger::Events { .. }))+ .count()+ > 1+ {+ return Err("combine event selectors in one event trigger");+ }+ Ok(Self(triggers))+ }+}++impl RoutineTriggers {+ pub fn as_slice(&self) -> &[RoutineTrigger] {+ &self.0+ }+}++impl From<RoutineTriggers> for Vec<RoutineTrigger> {+ fn from(triggers: RoutineTriggers) -> Self {+ triggers.0+ }+}++impl ActionTrigger {+ pub fn event_filters(&self) -> Option<&EventFilters> {+ match self {+ Self::Events { filters } => Some(filters),+ Self::Multiple { triggers } => triggers.0.iter().find_map(|trigger| match trigger {+ RoutineTrigger::Events { filters } => Some(filters),+ _ => None,+ }),+ _ => None,+ }+ }++ pub fn has_schedule(&self) -> bool {+ match self {+ Self::Cron { .. } => true,+ Self::Multiple { triggers } => triggers+ .0+ .iter()+ .any(|t| matches!(t, RoutineTrigger::Cron { .. })),+ _ => false,+ }+ }++ /// The first upcoming firing across all schedules. Simultaneous firings run once.+ pub fn next_run_after(&self, after: DateTime<Utc>) -> Option<DateTime<Utc>> {+ let next = |schedule: &Schedule, timezone: Tz| {+ schedule+ .as_cron()+ .after(&after.with_timezone(&timezone))+ .next()+ .map(|time| time.with_timezone(&Utc))+ };+ match self {+ Self::Cron { schedule, timezone } => next(schedule, *timezone),+ Self::Multiple { triggers } => triggers+ .0+ .iter()+ .filter_map(|trigger| match trigger {+ RoutineTrigger::Cron { schedule, timezone } => next(schedule, *timezone),+ RoutineTrigger::Events { .. } => None,+ })+ .min(),+ _ => None,+ }+ }}/// Closed allowlist: unknown names, deletions and ambiguous attribution are not@@ -52,6 +157,18 @@ pub enum EventName {DocumentCreated,#[serde(rename = "document.updated")]DocumentUpdated,+ #[serde(rename = "document.deleted")]+ DocumentDeleted,+ #[serde(rename = "task.created")]+ TaskCreated,+ #[serde(rename = "task.status_changed")]+ TaskStatusChanged,+ #[serde(rename = "task.priority_changed")]+ TaskPriorityChanged,+ #[serde(rename = "task.property_changed")]+ TaskPropertyChanged,+ #[serde(rename = "email.message_received")]+ EmailMessageReceived,#[serde(rename = "channel.created")]ChannelCreated,#[serde(rename = "channel.message_posted")]@@ -69,6 +186,12 @@ impl EventName {match self {Self::DocumentCreated => "document.created",Self::DocumentUpdated => "document.updated",+ Self::DocumentDeleted => "document.deleted",+ Self::TaskCreated => "task.created",+ Self::TaskStatusChanged => "task.status_changed",+ Self::TaskPriorityChanged => "task.priority_changed",+ Self::TaskPropertyChanged => "task.property_changed",+ Self::EmailMessageReceived => "email.message_received",Self::ChannelCreated => "channel.created",Self::ChannelMessagePosted => "channel.message_posted",Self::ChannelMentioned => "channel.mentioned",@@ -79,17 +202,37 @@ impl EventName {pub const fn entity_type(self) -> EventEntityType {match self {- Self::DocumentCreated | Self::DocumentUpdated => EventEntityType::Document,+ Self::DocumentCreated+ | Self::DocumentUpdated+ | Self::DocumentDeleted+ | Self::TaskCreated+ | Self::TaskStatusChanged+ | Self::TaskPriorityChanged+ | Self::TaskPropertyChanged => EventEntityType::Document,+ Self::EmailMessageReceived => EventEntityType::EmailThread,_ => EventEntityType::Channel,}}const fn has_message(self) -> bool {- !matches!(+ matches!(self,- Self::DocumentCreated | Self::DocumentUpdated | Self::ChannelCreated+ Self::ChannelMessagePosted+ | Self::ChannelMentioned+ | Self::ChannelMessagePatched+ | Self::ChannelMessageAttachmentCreated+ | Self::EmailMessageReceived)}++ /// Status and priority also match any-property selectors. The original+ /// event ID still deduplicates routines that subscribe to both names.+ pub const fn general_event(self) -> Option<Self> {+ match self {+ Self::TaskStatusChanged | Self::TaskPriorityChanged => Some(Self::TaskPropertyChanged),+ _ => None,+ }+ }}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]@@ -97,13 +240,14 @@ impl EventName {pub enum EventEntityType {Document,Channel,+ EmailThread,}#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]pub enum FilterValidationError {#[error("expected between 1 and 32 filters")]FilterCount,- #[error("expected between 1 and 7 event names per filter")]+ #[error("expected between 1 and 13 event names per filter")]EventCount,#[error("expected at most 100 entity IDs per filter")]IdCount,@@ -168,7 +312,11 @@ impl EventFilter {}pub fn accepts(&self, name: EventName, entity_id: Uuid) -> bool {- self.events.contains(&name) && self.ids.as_ref().is_none_or(|ids| ids.contains(&entity_id))+ (self.events.contains(&name)+ || name+ .general_event()+ .is_some_and(|general| self.events.contains(&general)))+ && self.ids.as_ref().is_none_or(|ids| ids.contains(&entity_id))}}@@ -313,6 +461,8 @@ pub enum EventPayload {Document(DocumentTopicEvent),Channel(ChannelTopicEvent),Message(MessageFact),+ Property(PropertyTopicEvent),+ Email(EmailTopicEvent),}/// The message facts routines can trigger on, from `macro.messages`. Anything@@ -381,10 +531,23 @@ fn document_actor(}impl IncomingEvent {+ /// Mentions belong to the mentioned user and inbound mail to its inbox+ /// owner. Entity access is checked separately at admission and dispatch.+ /// These audience restrictions never turn an event into an access grant.+ pub fn is_for_owner(&self, owner: &MacroUserIdStr<'static>) -> bool {+ match &self.payload {+ EventPayload::Message(MessageFact::Mentioned(data)) => {+ data.mentioned.entity_type == "user" && data.mentioned.entity_id == owner.as_ref()+ }+ EventPayload::Email(EmailTopicEvent::MessageReceived(data)) => &data.owner == owner,+ _ => true,+ }+ }+/// Fail closed on attribution, identity and schema. Wildcard arms are/// deliberate: future source variants remain non-triggering by default.pub fn normalize(&self) -> Result<EventReference, EventRejection> {- // Both currently supported source schemas are version 1. A producer+ // All currently supported source schemas are version 1. A producer// version change requires reviewing eligibility before accepting it.if self.schema_version != 1 {return Err(EventRejection::UnsupportedSchema);@@ -395,7 +558,23 @@ impl IncomingEvent {let (name, id) = match event {DocumentTopicEvent::Created(data) => {require_human(data.actor.as_ref(), data.on_behalf_of.is_some())?;- (EventName::DocumentCreated, &data.document_id)+ let name = if data.sub_type == Some(DocumentSubType::Task) {+ EventName::TaskCreated+ } else {+ EventName::DocumentCreated+ };+ (name, &data.document_id)+ }+ DocumentTopicEvent::Deleted(data) => {+ document_actor(+ data.actor.as_ref(),+ data.actor_user_id.as_ref(),+ data.on_behalf_of.is_some(),+ )?;+ if data.sub_type == Some(DocumentSubType::Task) {+ return Err(EventRejection::UnsupportedEvent);+ }+ (EventName::DocumentDeleted, &data.document_id)}DocumentTopicEvent::Updated(data) => {document_actor(@@ -430,6 +609,9 @@ impl IncomingEvent {MessageFact::Mentioned(data) => {let channel_id = channel_parent(&data.parent)?;require_human(Some(&data.sender), false)?;+ if data.mentioned.entity_type != "user" {+ return Err(EventRejection::UnsupportedEvent);+ }(EventName::ChannelMentioned,channel_id,@@ -456,6 +638,24 @@ impl IncomingEvent {}MessageFact::Other => return Err(EventRejection::UnsupportedEvent),},+ EventPayload::Property(event) => {+ let (name, id) = task_property_event(event)?;+ let id = Uuid::parse_str(id).map_err(|_| EventRejection::InvalidEntityId)?;+ (name, id, None)+ }+ EventPayload::Email(EmailTopicEvent::MessageReceived(data)) => {+ // The email domain emits this only for newly received mail,+ // never sent messages, drafts or historical backfills.+ if data.is_spam_or_trash {+ return Err(EventRejection::UnsupportedEvent);+ }+ (+ EventName::EmailMessageReceived,+ data.thread_id,+ Some(data.message_id),+ )+ }+ EventPayload::Email(_) => return Err(EventRejection::UnsupportedEvent),};Ok(EventReference {event_id,@@ -465,3 +665,49 @@ impl IncomingEvent {})}}++fn task_property_event(event: &PropertyTopicEvent) -> Result<(EventName, &str), EventRejection> {+ let (entity_type, entity_id, property_id, actor, fallback, delegated) = match event {+ PropertyTopicEvent::EntityPropertyUpdated(data) => {+ if data.value == data.previous_value {+ return Err(EventRejection::UnsupportedEvent);+ }+ (+ &data.entity_type,+ data.entity_id.as_str(),+ Some(data.property_definition_id),+ data.actor.as_ref(),+ data.actor_user_id.as_ref(),+ data.on_behalf_of.is_some(),+ )+ }+ PropertyTopicEvent::EntityPropertyDeleted(data) => (+ &data.entity_type,+ data.entity_id.as_str(),+ Some(data.property_definition_id),+ data.actor.as_ref(),+ data.actor_user_id.as_ref(),+ data.on_behalf_of.is_some(),+ ),+ PropertyTopicEvent::EntityPropertiesCleared(data) => (+ &data.entity_type,+ data.entity_id.as_str(),+ None,+ data.actor.as_ref(),+ data.actor_user_id.as_ref(),+ data.on_behalf_of.is_some(),+ ),+ _ => return Err(EventRejection::UnsupportedEvent),+ };+ // The properties domain resolves document subtypes before publishing.+ if *entity_type != PropertyEntityType::Task {+ return Err(EventRejection::UnsupportedEvent);+ }+ document_actor(actor, fallback, delegated)?;+ let name = match property_id {+ Some(SystemPropertyKey::STATUS_UUID) => EventName::TaskStatusChanged,+ Some(SystemPropertyKey::PRIORITY_UUID) => EventName::TaskPriorityChanged,+ _ => EventName::TaskPropertyChanged,+ };+ Ok((name, entity_id))+}diff --git a/services/scheduled_action/src/domain/event_trigger/test.rs b/services/scheduled_action/src/domain/event_trigger/test.rsindex 27192271d5..d824004bb4 100644--- a/services/scheduled_action/src/domain/event_trigger/test.rs+++ b/services/scheduled_action/src/domain/event_trigger/test.rs@@ -204,7 +204,6 @@ fn update_prefers_explicit_actor_and_requires_a_fallback_when_absent() {#[test]fn every_non_allowlisted_variant_is_rejected() {for name in [- "document.deleted","document.content_uploaded","document.sync_content_updated","document.purged",@@ -380,3 +379,225 @@ fn tagged_trigger_round_trips_and_rejects_conflicting_fields() {}assert!(serde_json::from_value::<ActionTrigger>(json!({"type": "events", "filters": [{"events": ["document.created"]}], "schedule": "0 0 9 * * *"})).is_err());}++#[test]+fn multiple_triggers_preserve_event_filters_and_choose_the_next_schedule() {+ let trigger: ActionTrigger = serde_json::from_value(serde_json::json!({+ "type": "multiple",+ "triggers": [+ {"type":"cron", "schedule":"0 0 9 * * *", "timezone":"UTC"},+ {"type":"cron", "schedule":"0 0 17 * * *", "timezone":"UTC"},+ {"type":"events", "filters":[{"events":["channel.message_posted"]}]}+ ]+ }))+ .unwrap();+ let after = chrono::DateTime::parse_from_rfc3339("2040-01-01T10:00:00Z")+ .unwrap()+ .with_timezone(&chrono::Utc);+ assert_eq!(+ trigger.next_run_after(after).unwrap().to_rfc3339(),+ "2040-01-01T17:00:00+00:00"+ );+ assert_eq!(+ trigger.event_filters().unwrap().as_slice()[0].events(),+ &[EventName::ChannelMessagePosted]+ );+ assert!(trigger.has_schedule());+}++#[test]+fn event_groups_must_be_combined_and_external_webhooks_are_rejected() {+ let events = serde_json::json!({"type":"events", "filters":[{"events":["document.created"]}]});+ assert!(+ serde_json::from_value::<ActionTrigger>(+ serde_json::json!({"type":"multiple", "triggers":[events.clone(),events]})+ )+ .is_err()+ );+ assert!(+ serde_json::from_value::<ActionTrigger>(serde_json::json!({"type":"webhook"})).is_err()+ );+}++fn property_event(name: &str, metadata: Value) -> IncomingEvent {+ IncomingEvent {+ event_id: Uuid::parse_str(EVENT_ID).unwrap(),+ schema_version: 1,+ payload: EventPayload::Property(+ serde_json::from_value(json!({+ "event_type": name, "metadata": metadata+ }))+ .unwrap(),+ ),+ }+}++fn property_metadata() -> Value {+ json!({+ "entity_property_id": OTHER_ID, "entity_id": ENTITY_ID,+ "entity_type": "TASK", "property_definition_id": SystemPropertyKey::STATUS_UUID,+ "actor": HUMAN, "actor_user_id": HUMAN,+ "value": {"type": "SelectOption", "value": [OTHER_ID]},+ "previous_value": null, "updated_at": "2024-01-01T00:00:00Z"+ })+}++#[test]+fn document_lifecycle_distinguishes_tasks() {+ let mut data = metadata();+ assert_eq!(+ incoming("document.created", data.clone())+ .normalize()+ .unwrap()+ .event_name(),+ EventName::DocumentCreated+ );+ assert_eq!(+ incoming("document.deleted", data.clone())+ .normalize()+ .unwrap()+ .event_name(),+ EventName::DocumentDeleted+ );+ data["sub_type"] = json!("task");+ assert_eq!(+ incoming("document.created", data.clone())+ .normalize()+ .unwrap()+ .event_name(),+ EventName::TaskCreated+ );+ assert_eq!(+ incoming("document.deleted", data.clone()).normalize(),+ Err(EventRejection::UnsupportedEvent)+ );+ data["actor"] = json!(BOT);+ assert_eq!(+ incoming("document.created", data).normalize(),+ Err(EventRejection::UnsafeAttribution)+ );+}++#[test]+fn task_changes_match_specific_and_any_property_selectors() {+ for (property, name) in [+ (SystemPropertyKey::STATUS_UUID, EventName::TaskStatusChanged),+ (+ SystemPropertyKey::PRIORITY_UUID,+ EventName::TaskPriorityChanged,+ ),+ (+ SystemPropertyKey::DUE_DATE_UUID,+ EventName::TaskPropertyChanged,+ ),+ ] {+ let mut data = property_metadata();+ data["property_definition_id"] = json!(property);+ for source in ["entity_property.updated", "entity_property.deleted"] {+ let event = property_event(source, data.clone()).normalize().unwrap();+ assert_eq!(event.event_name(), name);+ let any = EventFilter::new(vec![EventName::TaskPropertyChanged], None).unwrap();+ assert!(any.accepts(event.event_name(), event.entity_id()));+ let other_task =+ EventFilter::new(vec![name], Some(vec![Uuid::parse_str(OTHER_ID).unwrap()]))+ .unwrap();+ assert!(!other_task.accepts(name, event.entity_id()));+ let stored = serde_json::to_value(&event).unwrap();+ assert_eq!(stored.as_object().unwrap().len(), 4);+ assert_eq!(+ serde_json::from_value::<EventReference>(stored).unwrap(),+ event+ );+ }+ }+ let event = property_event("entity_properties.cleared", property_metadata())+ .normalize()+ .unwrap();+ assert_eq!(event.event_name(), EventName::TaskPropertyChanged);+}++#[test]+fn property_changes_ignore_other_entities_noops_and_bot_writes() {+ let original = property_metadata();+ for kind in ["DOCUMENT", "PROJECT", "INITIATIVE", "THREAD"] {+ let mut data = original.clone();+ data["entity_type"] = json!(kind);+ assert_eq!(+ property_event("entity_property.updated", data).normalize(),+ Err(EventRejection::UnsupportedEvent)+ );+ }+ let mut data = original.clone();+ data["previous_value"] = data["value"].clone();+ assert_eq!(+ property_event("entity_property.updated", data).normalize(),+ Err(EventRejection::UnsupportedEvent)+ );+ for field in ["actor", "on_behalf_of"] {+ let mut data = original.clone();+ data[field] = json!(if field == "actor" { BOT } else { HUMAN });+ assert_eq!(+ property_event("entity_property.updated", data).normalize(),+ Err(EventRejection::UnsafeAttribution)+ );+ }+}++#[test]+fn mention_trigger_is_only_for_the_mentioned_user() {+ let owner = MacroUserIdStr::parse_from_str(HUMAN).unwrap();+ let other = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let event = incoming("channel.mentioned", metadata());+ assert!(event.is_for_owner(&owner));+ assert!(!event.is_for_owner(&other));+ let mut data = metadata();+ data["mentioned"]["entity_type"] = json!("document");+ assert_eq!(+ incoming("channel.mentioned", data).normalize(),+ Err(EventRejection::UnsupportedEvent)+ );+}++#[test]+fn email_receipts_keep_only_ids_and_exclude_spam_and_backfills() {+ use email::domain::events::ThreadBackfilledMetadata;+ let owner = MacroUserIdStr::parse_from_str(HUMAN).unwrap();+ let mut event = IncomingEvent {+ event_id: Uuid::parse_str(EVENT_ID).unwrap(),+ schema_version: 1,+ payload: EventPayload::Email(+ serde_json::from_value(json!({+ "event_type":"email.message_received", "metadata": {+ "link_id": OTHER_ID, "owner": HUMAN, "message_id": OTHER_ID,+ "provider_message_id": "provider-msg", "thread_id": ENTITY_ID,+ "provider_thread_id": "provider-thread", "is_new_thread": false,+ "subject": "private subject", "from_email": "[email protected]",+ "to_emails": [], "attachment_count": 0, "is_spam_or_trash": false+ }+ }))+ .unwrap(),+ ),+ };+ let normalized = event.normalize().unwrap();+ assert_eq!(normalized.event_name(), EventName::EmailMessageReceived);+ assert_eq!(normalized.entity_type(), EventEntityType::EmailThread);+ let stored = serde_json::to_string(&normalized).unwrap();+ assert!(!stored.contains("private"));+ assert!(!stored.contains("provider"));+ assert!(event.is_for_owner(&owner));+ assert!(+ !event.is_for_owner(&MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap())+ );+ if let EventPayload::Email(EmailTopicEvent::MessageReceived(ref mut data)) = event.payload {+ data.is_spam_or_trash = true;+ }+ assert_eq!(event.normalize(), Err(EventRejection::UnsupportedEvent));+ event.payload = EventPayload::Email(EmailTopicEvent::ThreadBackfilled(+ ThreadBackfilledMetadata {+ link_id: Uuid::parse_str(OTHER_ID).unwrap(),+ owner,+ thread_id: Uuid::parse_str(ENTITY_ID).unwrap(),+ },+ ));+ assert_eq!(event.normalize(), Err(EventRejection::UnsupportedEvent));+}diff --git a/services/scheduled_action/src/domain/execution.rs b/services/scheduled_action/src/domain/execution.rsindex d7d83abfd5..4a4a40739c 100644--- a/services/scheduled_action/src/domain/execution.rs+++ b/services/scheduled_action/src/domain/execution.rs@@ -25,9 +25,9 @@ use crate::domain::ports::{/// partially created remote sessions even when preparation never returns.#[derive(Debug)]pub struct ExecutionHandle {- /// Caller-generated remote session ID; unused by the legacy chat runner.+ /// Caller-generated agent session ID, available before preparation starts.pub session_id: Uuid,- /// Caller-generated initial remote action ID; unused by the legacy chat runner.+ /// Caller-generated initial action ID for prompt delivery and status checks.pub action_id: Uuid,/// Set as soon as resource existence is established, even if preparation later fails.pub resource: Option<ExecutionResource>,@@ -245,7 +245,7 @@ whereexecutor.cancellation.cancelled(),executor.repo- .claim_action(&id, action.configuration_revision),+ .claim_action(&id, action.configuration_revision, action.next_run_at),).await;let token = match claim {diff --git a/services/scheduled_action/src/domain/execution/test.rs b/services/scheduled_action/src/domain/execution/test.rsindex 747860b54f..91a8f7a52f 100644--- a/services/scheduled_action/src/domain/execution/test.rs+++ b/services/scheduled_action/src/domain/execution/test.rs@@ -161,7 +161,12 @@ struct Repo {}impl ScheduledActionRepo for Repo {- async fn claim_action(&self, _: &Uuid, revision: ConfigurationRevision) -> Result<ClaimToken> {+ async fn claim_action(+ &self,+ _: &Uuid,+ revision: ConfigurationRevision,+ _expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,+ ) -> Result<ClaimToken> {self.claims.fetch_add(1, Ordering::SeqCst);self.claimed_revisions.lock().unwrap().push(revision.get());let mut claim = self.claim.lock().unwrap();diff --git a/services/scheduled_action/src/domain/models.rs b/services/scheduled_action/src/domain/models.rsindex 5635e5b7d7..1799d25965 100644--- a/services/scheduled_action/src/domain/models.rs+++ b/services/scheduled_action/src/domain/models.rs@@ -19,7 +19,7 @@ mod test;pub const MAX_ACTION_TIME: Duration = Duration::minutes(20);-#[derive(Serialize, Debug, Clone, ToSchema)]+#[derive(Serialize, Debug, Clone, PartialEq, Eq, ToSchema)]pub struct Schedule(String);impl Schedule {@@ -67,7 +67,7 @@ pub struct AgentTask {/// Required for model targets; overrides the persona default for agent targets.#[serde(default, skip_serializing_if = "Option::is_none")]pub model: Option<RoutineModelId>,- /// Absent for legacy model-only tasks.+ /// Absent when using Macro's agent-session runtime with a selected model.#[serde(default, skip_serializing_if = "Option::is_none")]pub agent: Option<AgentTaskAgent>,pub prompt: String,@@ -116,6 +116,17 @@ pub enum ResolvedTaskTarget<'a> {},}+impl<'a> ResolvedTaskTarget<'a> {+ /// Use the same Macro runtime as the new AI composer for model selections.+ /// Explicit agent selections keep their own runtime and optional model override.+ pub fn session_target(self) -> (BotId, Option<&'a RoutineModelId>) {+ match self {+ Self::Model { model } => (bot_id::MACRO_NEW_BOT_ID, Some(model)),+ Self::Agent { bot_id, model } => (bot_id, model),+ }+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]pub enum TaskTargetError {#[error("a supplied model must not be blank")]diff --git a/services/scheduled_action/src/domain/ports.rs b/services/scheduled_action/src/domain/ports.rsindex 8a1291aee7..5ff913f849 100644--- a/services/scheduled_action/src/domain/ports.rs+++ b/services/scheduled_action/src/domain/ports.rs@@ -71,11 +71,13 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {fn delete_action(&self, id: &Uuid) -> impl Future<Output = Result<()>> + Send;/// Claim only while the stored configuration is still `revision`, so a- /// snapshot read before a pause or update can never start a run.+ /// snapshot read before a pause or update can never start a run. The stored+ /// firing must also match, fencing candidates fetched before a completed run.fn claim_action(&self,id: &Uuid,revision: ConfigurationRevision,+ expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,) -> impl Future<Output = Result<ClaimToken>> + Send;/// Release only this execution's claim; stale tokens must not mutate a newer run.@@ -117,6 +119,12 @@ pub trait ScheduledActionReadService: Send + Sync + 'static {}pub trait ScheduledActionService: Send + Sync + 'static {+ /// Read a routine only when the caller is its owner.+ fn get_action(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> impl Future<Output = Result<ScheduledAction>> + Send;+/// Delete all of a user's actions before account deletion, including disabled/// and claimed actions. Repeating a completed cleanup succeeds.fn delete_user_actions(diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rsindex 71c817e1b0..75d3d8f7c1 100644--- a/services/scheduled_action/src/domain/service.rs+++ b/services/scheduled_action/src/domain/service.rs@@ -89,13 +89,19 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>bail!("scheduled action receipt id is not a uuid");};match self.repo.get_action(&id).await? {- Some(action) => Ok(action),- None => Err(ActionPolicyError::NotFound.into()),+ Some(action)+ if receipt+ .acting_user_id()+ .is_some_and(|user| action.owner.is_user(user)) =>+ {+ Ok(action)+ }+ _ => Err(ActionPolicyError::NotFound.into()),}}fn check_event_management(&self, trigger: &ActionTrigger) -> Result<()> {- if matches!(trigger, ActionTrigger::Events { .. }) && !self.event_management_enabled {+ if trigger.event_filters().is_some() && !self.event_management_enabled {return Err(ActionPolicyError::EventManagementDisabled.into());}Ok(())@@ -130,16 +136,18 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>self.targets.validate_task(&input.task, action.owner_user()?).await?;- action.next_run_at = next_run(&input.trigger)?;+ if trigger_changed || (!action.enabled && input.enabled) {+ action.next_run_at = next_run(&input.trigger)?;+ }}- action.event_activated_at = match &input.trigger {- ActionTrigger::Cron { .. } => None,- ActionTrigger::Events { .. }- if trigger_changed || (!action.enabled && input.enabled) =>- {+ action.event_activated_at = if input.trigger.event_filters().is_some() {+ if trigger_changed || (!action.enabled && input.enabled) {Some(now)+ } else {+ action.event_activated_at}- ActionTrigger::Events { .. } => action.event_activated_at,+ } else {+ None};action.configuration_revision = action.configuration_revision.next()?;action.name = input.name;@@ -159,15 +167,11 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>}fn next_run(trigger: &ActionTrigger) -> Result<Option<DateTime<Utc>>> {- match trigger {- ActionTrigger::Cron { schedule, timezone } => schedule- .next_run_after_now(*timezone)- .map(Some)- .ok_or_else(|| ActionPolicyError::NoFutureFirings.into()),- // Filters are validated value objects: neither deserialization nor Rust- // constructors can supply unbounded, empty or unsupported selectors.- ActionTrigger::Events { .. } => Ok(None),+ let next = trigger.next_run_after(Utc::now());+ if trigger.has_schedule() && next.is_none() && trigger.event_filters().is_none() {+ return Err(ActionPolicyError::NoFutureFirings.into());}+ Ok(next)}pub(crate) async fn list_accessible_actions<R, G>(@@ -187,6 +191,7 @@ wherereturn Ok(Vec::new());}let mut actions = repo.get_actions_by_ids(&ids).await?;+ actions.retain(|action| action.owner.is_user(user_id));actions.sort_by(|left, right| {left.created_at.cmp(&right.created_at)@@ -202,20 +207,7 @@ fn claim_blocks_replacement(action: &ScheduledAction, now: DateTime<Utc>) -> boo}fn same_trigger(left: &ActionTrigger, right: &ActionTrigger) -> bool {- match (left, right) {- (- ActionTrigger::Cron {- schedule: a,- timezone: at,- },- ActionTrigger::Cron {- schedule: b,- timezone: bt,- },- ) => a.as_str() == b.as_str() && at == bt,- (ActionTrigger::Events { filters: a }, ActionTrigger::Events { filters: b }) => a == b,- _ => false,- }+ left == right}impl<Rpo, Exe, Grants, Targets> ScheduledActionService@@ -226,6 +218,13 @@ whereTargets: TaskTargetValidator,Exe: ScheduledActionExecutor + Send + Sync + 'static,{+ async fn get_action(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<ScheduledAction> {+ self.load_granted(&receipt).await+ }+async fn delete_user_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<()> {// Use the repository list, not the legacy cron-only service list, so// event-triggered actions are also removed regardless of rollout gates.@@ -259,10 +258,7 @@ whereself.targets.validate_task(&input.task, owner_user).await?;let now = Utc::now();let next_run_at = next_run(&input.trigger)?;- let event_activated_at = match &input.trigger {- ActionTrigger::Events { .. } => Some(now),- ActionTrigger::Cron { .. } => None,- };+ let event_activated_at = input.trigger.event_filters().is_some().then_some(now);let created = self.repo.create_action(ScheduledAction {diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rsindex 50ade7d2af..a3718bfd72 100644--- a/services/scheduled_action/src/domain/service/test.rs+++ b/services/scheduled_action/src/domain/service/test.rs@@ -8,7 +8,6 @@ use crate::domain::models::{MAX_ACTION_TIME,};use crate::domain::{- event_trigger::EventReference,execution::ExecutionHandle,ports::{ScheduledActionReadService, ScheduledAgentRunner},read_service::ScheduledActionReadServiceImpl,@@ -102,6 +101,7 @@ impl ScheduledActionRepo for FakeRepo {&self,_id: &Uuid,_revision: ConfigurationRevision,+ _expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,) -> Result<ClaimToken> {unimplemented!()}@@ -473,25 +473,6 @@ async fn unavailable_agents_can_be_paused_deleted_and_have_history_read_without_}}-struct NoModelFallback;--impl ScheduledAgentRunner for NoModelFallback {- async fn prepare(&self, _: &ScheduledAction, _: &mut ExecutionHandle) -> Result<()> {- panic!("must not fall back")- }- async fn run(- &self,- _: &ScheduledAction,- _: &ExecutionHandle,- _: Option<&EventReference>,- ) -> Result<()> {- panic!("must not fall back")- }- async fn cancel(&self, _: &ScheduledAction, _: &ExecutionHandle) -> Result<()> {- panic!("must not fall back")- }-}-#[tokio::test]async fn preparation_reauthorizes_previously_saved_selection_after_deletion_or_revocation() {for denial in [@@ -515,7 +496,7 @@ async fn preparation_reauthorizes_previously_saved_selection_after_deletion_or_r.unwrap();assert!(sessions.preparations.lock().unwrap().is_empty());*sessions.error.lock().unwrap() = Some(denial);- let runner = TargetRunner::new(Arc::new(NoModelFallback), sessions.clone());+ let runner = TargetRunner::new(sessions.clone());let mut handle = ExecutionHandle::default();let error = runner.prepare(&created, &mut handle).await.unwrap_err();assert_eq!(error.downcast_ref(), Some(&denial));@@ -677,92 +658,64 @@ async fn list_is_cron_only_by_default_but_id_operations_reach_events() {}#[tokio::test]-async fn receipt_manages_another_owners_row_and_missing_row_is_not_found() {+async fn grants_do_not_allow_access_to_another_owners_routine() {let svc = service(true);- let created = svc- .create_action(- &user_principal(),- CreateScheduledAction::Canonical(configuration(false)),- )- .await- .unwrap();- let id = created.id.unwrap();- svc.repo.actions.lock().unwrap()[0].owner = Owner::from_principal_str(FOREIGN_USER).unwrap();- svc.delete_action(owner_receipt(id)).await.unwrap();- assert!(svc.repo.actions.lock().unwrap().is_empty());- let error = svc.execute_action_now(owner_receipt(id)).await.unwrap_err();- assert!(matches!(- error.downcast_ref(),- Some(ActionPolicyError::NotFound)- ));-}--#[tokio::test]-async fn bot_owned_execution_and_validating_update_need_a_user_owner() {- use crate::domain::target_validation::{- TargetValidation,- test::{Sessions, agent_task},- };- let base = service(true);- let sessions = Arc::new(Sessions::default());- let svc = TestService::new(- base.repo.clone(),- base.executor.clone(),- base.dispatcher_tx.clone(),- grants(&base.repo),- )- .with_target_validation(TargetValidation::new(sessions.clone(), true));- let mut config = configuration(false);- config.task = agent_task();- let created = svc- .create_action(- &user_principal(),- CreateScheduledAction::Canonical(config.clone()),- )- .await- .unwrap();- let id = created.id.unwrap();- let editor = EntityAccessReceipt::<EditAccessLevel>::dangerously_assert_authenticated_user(- MacroUserIdStr::parse_from_str(FOREIGN_USER).unwrap(),- &id.to_string(),- EntityType::ScheduledAction,- );- config.task["prompt"] = json!("changed");- svc.update_action(editor, update(config.clone()))- .await- .unwrap();- assert_eq!(- sessions- .validations+ for owner in [+ Owner::from_principal_str(FOREIGN_USER).unwrap(),+ Owner::from_principal_str(&format!("bot|{}", generate_uuid_v7())).unwrap(),+ Owner::from_principal_str(&generate_uuid_v7().to_string()).unwrap(),+ ] {+ let created = svc+ .create_action(+ &user_principal(),+ CreateScheduledAction::Canonical(configuration(true)),+ )+ .await+ .unwrap();+ let id = created.id.unwrap();+ assert_eq!(svc.get_action(view_receipt(id)).await.unwrap().id, Some(id));+ svc.repo.actions.lock().unwrap().last_mut().unwrap().owner = owner;+ assert_policy(+ svc.get_action(view_receipt(id)).await,+ ActionPolicyError::NotFound,+ );+ assert_policy(+ svc.update_action(edit_receipt(id), update(configuration(true)))+ .await,+ ActionPolicyError::NotFound,+ );+ assert_policy(+ svc.set_enabled(edit_receipt(id), false).await,+ ActionPolicyError::NotFound,+ );+ assert_policy(+ svc.delete_action(owner_receipt(id)).await,+ ActionPolicyError::NotFound,+ );+ assert_policy(+ svc.get_execution_records(view_receipt(id)).await,+ ActionPolicyError::NotFound,+ );+ assert_policy(+ svc.execute_action_now(owner_receipt(id)).await,+ ActionPolicyError::NotFound,+ );+ }+ assert!(svc.get_actions(user(), true).await.unwrap().is_empty());+ assert!(+ svc.repo+ .actions.lock().unwrap()- .last()- .unwrap()- .owner- .as_ref(),- USER+ .iter()+ .all(|action| action.enabled)+ );+ assert!(svc.executor.calls.lock().unwrap().is_empty());+ assert_policy(+ svc.execute_action_now(owner_receipt(generate_uuid_v7()))+ .await,+ ActionPolicyError::NotFound,);-- svc.repo.actions.lock().unwrap()[0].owner = Owner::Bot(bot_id::BotId::TEST_A);- let before = sessions.validations.lock().unwrap().len();- let error = svc- .update_action(edit_receipt(id), update(config.clone()))- .await- .unwrap_err();- assert!(error.downcast_ref::<OwnerNotUserError>().is_some());- assert_eq!(sessions.validations.lock().unwrap().len(), before);-- let disabled = svc.set_enabled(edit_receipt(id), false).await.unwrap();- assert!(!disabled.enabled);- assert_eq!(sessions.validations.lock().unwrap().len(), before);-- let error = svc.execute_action_now(owner_receipt(id)).await.unwrap_err();- assert!(error.to_string().contains("owner is a bot"));- assert!(base.executor.calls.lock().unwrap().is_empty());-- svc.repo.actions.lock().unwrap()[0].owner = Owner::User(user());- svc.execute_action_now(owner_receipt(id)).await.unwrap();- assert_eq!(base.executor.calls.lock().unwrap().len(), 1);}#[tokio::test]@@ -1121,7 +1074,6 @@ async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {let reader = ScheduledActionReadServiceImpl::new(repo.clone(), accessible);let expected = vec![- "foreign","early-cron","low-id","first-equal",@@ -1136,7 +1088,7 @@ async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {.collect::<Vec<_>>()};assert_eq!(names(&read), expected);- assert!(read.iter().any(|action| action.name == "foreign"));+ assert!(read.iter().all(|action| action.name != "foreign"));assert!(read.iter().all(|action| action.name != "bot" && action.name != "team")@@ -1155,13 +1107,7 @@ async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {);assert_eq!(names(&svc.get_actions(user(), false).await.unwrap()),- vec![- "foreign",- "early-cron",- "low-id",- "first-equal",- "second-equal"- ]+ vec!["early-cron", "low-id", "first-equal", "second-equal"]);}@@ -1284,3 +1230,40 @@ async fn configuration_updates_that_omit_activation_keep_it() {assert_eq!(updated.name, format!("renamed while enabled={enabled}"));}}++#[tokio::test]+async fn editing_an_overdue_one_off_keeps_its_unconsumed_firing() {+ let svc = service(false);+ let mut config = configuration(false);+ let created = svc+ .create_action(+ &user_principal(),+ CreateScheduledAction::Canonical(config.clone()),+ )+ .await+ .unwrap();+ let id = created.id.unwrap();+ config.trigger = ActionTrigger::Cron {+ schedule: crate::domain::models::Schedule::from_cron("0 0 9 1 1 * 2000".into()).unwrap(),+ timezone: chrono_tz::UTC,+ };+ let firing = Utc::now() - chrono::Duration::minutes(1);+ {+ let mut actions = svc.repo.actions.lock().unwrap();+ actions[0].trigger = config.trigger.clone();+ actions[0].next_run_at = Some(firing);+ }+ config.name = "Renamed while waiting for the worker".into();+ let updated = svc+ .update_action(edit_receipt(id), update(config.clone()))+ .await+ .unwrap();+ assert_eq!(updated.next_run_at, Some(firing));+ svc.repo.actions.lock().unwrap()[0].next_run_at = None;+ config.name = "Renamed after completion".into();+ let updated = svc+ .update_action(edit_receipt(id), update(config))+ .await+ .unwrap();+ assert_eq!(updated.next_run_at, None);+}diff --git a/services/scheduled_action/src/domain/service/test/admission.rs b/services/scheduled_action/src/domain/service/test/admission.rsindex 8af18edd66..3927d0dc35 100644--- a/services/scheduled_action/src/domain/service/test/admission.rs+++ b/services/scheduled_action/src/domain/service/test/admission.rs@@ -17,8 +17,7 @@ async fn manual_admission_keeps_error_type_and_uses_stored_owner_without_gating_.await.unwrap();let id = action.id.unwrap();- let stored_owner = MacroUserIdStr::parse_from_str(FOREIGN_USER).unwrap();- set_stored_owner(&service, id, Owner::User(stored_owner.clone()));+ let stored_owner = user();let returned = service.execute_action_now(owner_receipt(id)).awaitdiff --git a/services/scheduled_action/src/domain/service/test/user_cleanup.rs b/services/scheduled_action/src/domain/service/test/user_cleanup.rsindex 0db564adb7..1e5cc75855 100644--- a/services/scheduled_action/src/domain/service/test/user_cleanup.rs+++ b/services/scheduled_action/src/domain/service/test/user_cleanup.rs@@ -59,7 +59,12 @@ impl ScheduledActionRepo for FakeRepo {async fn update_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {unreachable!()}- async fn claim_action(&self, _: &Uuid, _: ConfigurationRevision) -> Result<ClaimToken> {+ async fn claim_action(+ &self,+ _: &Uuid,+ _: ConfigurationRevision,+ _expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,+ ) -> Result<ClaimToken> {unreachable!()}async fn release_action(&self, _: &Uuid, _: ClaimToken) -> Result<()> {diff --git a/services/scheduled_action/src/domain/target_runner.rs b/services/scheduled_action/src/domain/target_runner.rsindex 2a46ca887c..b0af52acda 100644--- a/services/scheduled_action/src/domain/target_runner.rs+++ b/services/scheduled_action/src/domain/target_runner.rs@@ -16,9 +16,7 @@ use bot_id::BotId;use super::{event_trigger::EventReference,execution::ExecutionHandle,- models::{- AgentTask, ExecutionResource, ExecutionResourceType, ResolvedTaskTarget, ScheduledAction,- },+ models::{AgentTask, ExecutionResource, ExecutionResourceType, ScheduledAction},ports::ScheduledAgentRunner,};@@ -26,34 +24,25 @@ const INITIAL_POLL_DELAY: Duration = Duration::from_secs(1);const MAX_POLL_DELAY: Duration = Duration::from_secs(10);const STATUS_TIMEOUT: Duration = Duration::from_secs(5);const MAX_STATUS_FAILURES: u8 = 5;-const SCHEDULED_GUIDANCE: &str = "You are executing a user automation that has already been triggered. Do not schedule it again or wait for its requested time or event. Follow your configured persona instructions while carrying out this routine.";+const SCHEDULED_GUIDANCE: &str = "You are executing a user routine that has already been triggered. Do not schedule it again or wait for its requested time or event. Follow your configured persona instructions while carrying out this routine.";-/// Keeps model execution unchanged and delegates agent work to the session domain.+/// Executes every routine through the agent-session domain./// The shared executor bounds preparation and polling by its original deadline,/// drops in-flight reads on timeout/shutdown, and invokes `cancel` separately.-pub struct TargetRunner<Model, Sessions> {- model: Arc<Model>,+pub struct TargetRunner<Sessions> {sessions: Arc<Sessions>,}-impl<Model, Sessions> TargetRunner<Model, Sessions> {- pub fn new(model: Arc<Model>, sessions: Arc<Sessions>) -> Self {- Self { model, sessions }+impl<Sessions> TargetRunner<Sessions> {+ pub fn new(sessions: Arc<Sessions>) -> Self {+ Self { sessions }}}-impl<Model: ScheduledAgentRunner, Sessions: RoutineSessions> ScheduledAgentRunner- for TargetRunner<Model, Sessions>-{+impl<Sessions: RoutineSessions> ScheduledAgentRunner for TargetRunner<Sessions> {async fn prepare(&self, action: &ScheduledAction, handle: &mut ExecutionHandle) -> Result<()> {let task = task(action)?;- let (bot_id, model) = match task.resolve_target()? {- ResolvedTaskTarget::Model { .. } => return self.model.prepare(action, handle).await,- // The session/harness service owns funding classification and gates- // managed work before provisioning; external targets are not charged- // as scheduler-owned model execution.- ResolvedTaskTarget::Agent { bot_id, model } => (bot_id, model),- };+ let (bot_id, model) = task.resolve_target()?.session_target();let identity = session_action(action, handle, bot_id)?;let prepared = self.sessions@@ -107,10 +96,7 @@ impl<Model: ScheduledAgentRunner, Sessions: RoutineSessions> ScheduledAgentRunneevent: Option<&EventReference>,) -> Result<()> {let task = task(action)?;- let bot_id = match task.resolve_target()? {- ResolvedTaskTarget::Model { .. } => return self.model.run(action, handle, event).await,- ResolvedTaskTarget::Agent { bot_id, .. } => bot_id,- };+ let (bot_id, _) = task.resolve_target()?.session_target();let resource = handle.resource.as_ref()@@ -135,20 +121,16 @@ impl<Model: ScheduledAgentRunner, Sessions: RoutineSessions> ScheduledAgentRunne}async fn cancel(&self, action: &ScheduledAction, handle: &ExecutionHandle) -> Result<()> {- match task(action)?.resolve_target()? {- ResolvedTaskTarget::Model { .. } => self.model.cancel(action, handle).await,- ResolvedTaskTarget::Agent { bot_id, .. } => {- // Also stop partially prepared sessions; resource may still be None.- self.sessions- .cancel(session_action(action, handle, bot_id)?)- .await?;- Ok(())- }- }+ let (bot_id, _) = task(action)?.resolve_target()?.session_target();+ // Also stop partially prepared sessions; resource may still be None.+ self.sessions+ .cancel(session_action(action, handle, bot_id)?)+ .await?;+ Ok(())}}-impl<Model, Sessions: RoutineSessions> TargetRunner<Model, Sessions> {+impl<Sessions: RoutineSessions> TargetRunner<Sessions> {async fn await_completion(&self, identity: RoutineSessionAction) -> Result<()> {let mut delay = INITIAL_POLL_DELAY;let mut failures = 0;diff --git a/services/scheduled_action/src/domain/target_runner/test.rs b/services/scheduled_action/src/domain/target_runner/test.rsindex a03653c58a..4f8340b342 100644--- a/services/scheduled_action/src/domain/target_runner/test.rs+++ b/services/scheduled_action/src/domain/target_runner/test.rs@@ -71,7 +71,6 @@ async fn agent_targets_delegate_admission_and_never_apply_the_model_gate() {&preparations[0].selection.owner,run.action.owner_user().unwrap());- assert!(runner.model.calls.lock().unwrap().is_empty());assert!(runner.sessions.stops.lock().unwrap().is_empty());if let Some(error) = admission_error {assert_eq!(result.outcome, EventRunOutcome::Failed);@@ -108,37 +107,6 @@ async fn agent_preparation_preserves_typed_admission_failures() {}}-#[derive(Default)]-struct Model {- calls: Mutex<Vec<&'static str>>,- events: Mutex<Vec<Option<EventReference>>>,-}--impl ScheduledAgentRunner for Model {- async fn prepare(&self, _: &ScheduledAction, handle: &mut ExecutionHandle) -> Result<()> {- self.calls.lock().unwrap().push("prepare");- handle.resource = Some(ExecutionResource {- resource_type: ExecutionResourceType::Chat,- id: "legacy-chat".into(),- });- Ok(())- }- async fn run(- &self,- _: &ScheduledAction,- _: &ExecutionHandle,- event: Option<&EventReference>,- ) -> Result<()> {- self.calls.lock().unwrap().push("run");- self.events.lock().unwrap().push(event.cloned());- Ok(())- }- async fn cancel(&self, _: &ScheduledAction, _: &ExecutionHandle) -> Result<()> {- self.calls.lock().unwrap().push("cancel");- Ok(())- }-}-#[derive(Default)]struct Sessions {preparations: Mutex<Vec<PrepareRoutineSession>>,@@ -251,8 +219,8 @@ fn event() -> EventReference {.unwrap()}-fn runner(sessions: Sessions) -> TargetRunner<Model, Sessions> {- TargetRunner::new(Arc::new(Model::default()), Arc::new(sessions))+fn runner(sessions: Sessions) -> TargetRunner<Sessions> {+ TargetRunner::new(Arc::new(sessions))}fn assert_identity(@@ -265,26 +233,63 @@ fn assert_identity(assert_eq!(identity.action_id.as_uuid(), handle.action_id);assert_eq!(serde_json::to_value(identity.bot_id).unwrap(),- action.task["agent"]["bot_id"]+ action+ .task+ .get("agent")+ .filter(|agent| !agent.is_null())+ .map(|agent| agent["bot_id"].clone())+ .unwrap_or_else(|| json!(bot_id::MACRO_NEW_BOT_ID)));}#[tokio::test]-async fn model_targets_delegate_all_operations_and_event_context() {- let runner = runner(Sessions::default());- let mut action = action();- action.task.as_object_mut().unwrap().remove("agent");- let mut handle = ExecutionHandle::default();- let event = event();- runner.prepare(&action, &mut handle).await.unwrap();- runner.run(&action, &handle, Some(&event)).await.unwrap();- runner.cancel(&action, &handle).await.unwrap();- assert_eq!(- *runner.model.calls.lock().unwrap(),- ["prepare", "run", "cancel"]- );- assert_eq!(*runner.model.events.lock().unwrap(), [Some(event)]);- assert!(runner.sessions.preparations.lock().unwrap().is_empty());+async fn model_targets_use_macro_sessions_with_the_selected_model_and_event_context() {+ for event in [None, Some(event())] {+ let runner = runner(Sessions {+ statuses: Mutex::new([Ok(RoutineActionStatus::Succeeded)].into()),+ ..Default::default()+ });+ let mut action = action();+ action.task.as_object_mut().unwrap().remove("agent");+ let mut handle = ExecutionHandle::default();+ runner.prepare(&action, &mut handle).await.unwrap();+ runner.run(&action, &handle, event.as_ref()).await.unwrap();+ runner.cancel(&action, &handle).await.unwrap();++ let preparations = runner.sessions.preparations.lock().unwrap();+ assert_eq!(preparations.len(), 1);+ assert_eq!(preparations[0].selection.bot_id, bot_id::MACRO_NEW_BOT_ID);+ assert_eq!(+ preparations[0].selection.model.as_deref(),+ Some("runtime/model")+ );+ assert_eq!(+ &preparations[0].selection.owner,+ action.owner_user().unwrap()+ );+ assert_eq!(preparations[0].session_id.as_uuid(), handle.session_id);++ let prompts = runner.sessions.prompts.lock().unwrap();+ assert_eq!(prompts.len(), 1);+ assert_eq!(+ prompts[0].prompt,+ first_prompt(&task(&action).unwrap(), event.as_ref()).unwrap()+ );+ let identity = &prompts[0].action;+ assert_eq!(identity.bot_id, bot_id::MACRO_NEW_BOT_ID);+ assert_eq!(identity.session_id.as_uuid(), handle.session_id);+ assert_eq!(identity.action_id.as_uuid(), handle.action_id);+ assert_eq!(&identity.owner, action.owner_user().unwrap());+ assert_identity(+ &runner.sessions.reads.lock().unwrap()[0].1,+ &action,+ &handle,+ );+ assert_identity(&runner.sessions.stops.lock().unwrap()[0], &action, &handle);+ let resource = handle.resource.unwrap();+ assert_eq!(resource.resource_type, ExecutionResourceType::Agent);+ assert_eq!(resource.id, handle.session_id.to_string());+ }}#[tokio::test(start_paused = true)]@@ -327,7 +332,6 @@ async fn fast_completion_keeps_owner_override_ids_and_context_in_one_prompt() {handle.resource.unwrap().resource_type,ExecutionResourceType::Agent);- assert!(runner.model.calls.lock().unwrap().is_empty());assert!(runner.sessions.stops.lock().unwrap().is_empty());}@@ -441,7 +445,6 @@ async fn ambiguous_prompt_is_never_retried_and_keeps_resource_for_failed_historyassert!(runner.sessions.reads.lock().unwrap().is_empty());assert_identity(&runner.sessions.stops.lock().unwrap()[0], &action, &handle);assert_eq!(handle.resource.unwrap().id, handle.session_id.to_string());- assert!(runner.model.calls.lock().unwrap().is_empty());}#[tokio::test]@@ -474,7 +477,6 @@ async fn offline_byoa_and_rejected_overrides_never_fall_back() {runner.cancel(&action, &handle).await.unwrap();assert_identity(&runner.sessions.stops.lock().unwrap()[0], &action, &handle);assert!(runner.sessions.prompts.lock().unwrap().is_empty());- assert!(runner.model.calls.lock().unwrap().is_empty());assert_eq!(runner.sessions.preparations.lock().unwrap().len(), 1);}}@@ -544,7 +546,6 @@ async fn all_terminal_failures_and_authorization_errors_fail_without_retry() {runner.prepare(&action, &mut handle).await.unwrap();assert!(runner.run(&action, &handle, None).await.is_err());assert_eq!(runner.sessions.reads.lock().unwrap().len(), 1);- assert!(runner.model.calls.lock().unwrap().is_empty());}}@@ -572,7 +573,12 @@ impl ScheduledActionRepo for UnusedRepo {async fn delete_action(&self, _: &Uuid) -> Result<()> {unimplemented!()}- async fn claim_action(&self, _: &Uuid, _: ConfigurationRevision) -> Result<ClaimToken> {+ async fn claim_action(+ &self,+ _: &Uuid,+ _: ConfigurationRevision,+ _expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,+ ) -> Result<ClaimToken> {unimplemented!()}async fn release_action(&self, _: &Uuid, _: ClaimToken) -> Result<()> {@@ -678,10 +684,39 @@ async fn executor_deadline_stops_preallocated_session_even_during_preparation()]));}- assert!(runner.model.calls.lock().unwrap().is_empty());}}+#[tokio::test]+async fn executor_failed_model_prompt_keeps_session_history_and_stops_once() {+ let runner = Arc::new(runner(Sessions {+ prompt_error: Some(RoutineSessionError::PromptDeliveryUnknown),+ ..Default::default()+ }));+ let executor = InProcessExecutor::new(+ Arc::new(UnusedRepo),+ runner.clone(),+ Arc::new(Live::default()),+ TaskTracker::new(),+ CancellationToken::new(),+ );+ let mut run = event_run();+ run.action.task.as_object_mut().unwrap().remove("agent");+ let result = executor.execute(&run, std::future::pending()).await;+ assert_eq!(result.outcome, EventRunOutcome::Failed);+ let record = result.record.unwrap();+ let metadata: ExecutionResult = serde_json::from_value(record.result).unwrap();+ let resource = metadata.resource.unwrap();+ assert_eq!(resource.resource_type, ExecutionResourceType::Agent);+ assert_eq!(record.resource_id, Some(resource.id));+ assert_eq!(runner.sessions.prompts.lock().unwrap().len(), 1);+ assert_eq!(runner.sessions.stops.lock().unwrap().len(), 1);+ assert_eq!(+ runner.sessions.stops.lock().unwrap()[0].bot_id,+ bot_id::MACRO_NEW_BOT_ID+ );+}+#[tokio::test]async fn executor_failed_prompt_finalizes_agent_history_and_stops_once() {use ai_billing::{AiAdmissionError, DenyReason};@@ -750,5 +785,4 @@ async fn invalid_targets_and_non_user_owners_never_reach_sessions() {);}assert!(runner.sessions.preparations.lock().unwrap().is_empty());- assert!(runner.model.calls.lock().unwrap().is_empty());}diff --git a/services/scheduled_action/src/domain/target_validation.rs b/services/scheduled_action/src/domain/target_validation.rsindex 2f7d8ef947..c74d2704e4 100644--- a/services/scheduled_action/src/domain/target_validation.rs+++ b/services/scheduled_action/src/domain/target_validation.rs@@ -51,15 +51,14 @@ impl<Sessions> TargetValidation<Sessions> {impl<Sessions: RoutineSessions> TaskTargetValidator for TargetValidation<Sessions> {async fn validate_task(&self, task: &Value, owner: &MacroUserIdStr<'static>) -> Result<()> {let task = parse_task(task, self.agents_enabled)?;- if let ResolvedTaskTarget::Agent { bot_id, model } = task.resolve_target()? {- self.sessions- .validate(ValidateRoutineSession {- owner: owner.clone(),- bot_id,- model: model.map(|model| model.as_str().to_owned()),- })- .await?;- }+ let (bot_id, model) = task.resolve_target()?.session_target();+ self.sessions+ .validate(ValidateRoutineSession {+ owner: owner.clone(),+ bot_id,+ model: model.map(|model| model.as_str().to_owned()),+ })+ .await?;Ok(())}}diff --git a/services/scheduled_action/src/domain/target_validation/test.rs b/services/scheduled_action/src/domain/target_validation/test.rsindex 391718f234..ae74bf3c36 100644--- a/services/scheduled_action/src/domain/target_validation/test.rs+++ b/services/scheduled_action/src/domain/target_validation/test.rs@@ -25,7 +25,7 @@ impl RoutineSessions for Sessions {if command.owner.as_ref() != OWNER {return Err(RoutineSessionError::Forbidden);}- if command.bot_id.to_string() != BOT {+ if command.bot_id.to_string() != BOT && command.bot_id != bot_id::MACRO_NEW_BOT_ID {return Err(RoutineSessionError::PersonaUnavailable);}if let Some(error) = *self.error.lock().unwrap() {@@ -86,15 +86,31 @@ async fn local_validation_precedes_gate_and_remote_authorization() {Some(&TargetValidationError::InvalidTask));}- validator+ }+ assert!(sessions.validations.lock().unwrap().is_empty());+}++#[tokio::test]+async fn model_selection_validates_macro_session_without_the_named_agent_gate() {+ let sessions = Arc::new(Sessions::default());+ let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();+ for enabled in [false, true] {+ TargetValidation::new(sessions.clone(), enabled).validate_task(- &json!({"model":"legacy/model", "prompt":"instructions", "user_prompt":"task"}),+ &json!({"model":"runtime/model", "prompt":"instructions", "user_prompt":"task"}),&owner,).await.unwrap();}- assert!(sessions.validations.lock().unwrap().is_empty());+ let validations = sessions.validations.lock().unwrap();+ assert_eq!(validations.len(), 2);+ for selection in validations.iter() {+ assert_eq!(selection.bot_id, bot_id::MACRO_NEW_BOT_ID);+ assert_eq!(selection.model.as_deref(), Some("runtime/model"));+ assert_eq!(selection.owner, owner);+ }+ assert!(sessions.preparations.lock().unwrap().is_empty());}#[tokio::test]diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rsindex a13f0db1ab..ae6f27a0cb 100644--- a/services/scheduled_action/src/inbound/axum_router.rs+++ b/services/scheduled_action/src/inbound/axum_router.rs@@ -54,7 +54,7 @@ impl From<ScheduledAction> for ScheduledActionResponse {fn from(action: ScheduledAction) -> Self {let (schedule, timezone) = match &action.trigger {ActionTrigger::Cron { schedule, timezone } => (Some(schedule.clone()), Some(*timezone)),- ActionTrigger::Events { .. } => (None, None),+ _ => (None, None),};Self {action,@@ -137,7 +137,9 @@ where).route("/scheduled-actions/{id}",- put(update_action::<S, Svc, Auth>).delete(delete_action::<S, Svc, Auth>),+ get(get_action::<S, Svc, Auth>)+ .put(update_action::<S, Svc, Auth>)+ .delete(delete_action::<S, Svc, Auth>),).route("/scheduled-actions/{id}/enabled",@@ -249,6 +251,35 @@ where))}+#[utoipa::path(+ get,+ path = "/scheduled-actions/{id}",+ tag = "scheduled actions",+ operation_id = "get_scheduled_action",+ params(("id" = String, Path, description = "ID of the scheduled action")),+ responses(+ (status = 200, body = ScheduledActionResponse),+ (status = 401, body = String),+ (status = 404, body = String),+ (status = 500, body = String),+ )+)]+pub async fn get_action<S, Svc, Auth>(+ State(state): State<ScheduledActionRouterState<S, Svc, Auth>>,+ ScheduledActionAccessExtractor {+ entity_access_receipt,+ ..+ }: ScheduledActionAccessExtractor<ViewAccessLevel, Svc, Auth>,+) -> Result<Json<ScheduledActionResponse>, ScheduledActionApiError>+where+ S: ScheduledActionService,+ Svc: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let action = state.service.get_action(entity_access_receipt).await?;+ Ok(Json(action.into()))+}+#[utoipa::path(put,path = "/scheduled-actions/{id}",diff --git a/services/scheduled_action/src/inbound/axum_router/test.rs b/services/scheduled_action/src/inbound/axum_router/test.rsindex 7ed9d09b86..2066310726 100644--- a/services/scheduled_action/src/inbound/axum_router/test.rs+++ b/services/scheduled_action/src/inbound/axum_router/test.rs@@ -481,6 +481,35 @@ async fn mixed_unknown_and_server_owned_input_is_bad_request_for_create_and_upda}}+#[tokio::test]+async fn owner_can_read_cron_and_event_routines_but_missing_ids_return_not_found() {+ let app = router(true);+ for events in [false, true] {+ let (status, created) = request(+ &app,+ "POST",+ "/scheduled-actions",+ "owner",+ serde_json::to_value(configuration(events)).unwrap(),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED);+ let url = format!("/scheduled-actions/{}", created["id"].as_str().unwrap());+ let (status, routine) = request(&app, "GET", &url, "owner", Value::Null).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(routine, created);+ assert_eq!(+ request(&app, "GET", &url, "invalid", Value::Null).await.0,+ StatusCode::UNAUTHORIZED+ );+ }+ let missing = format!("/scheduled-actions/{}", macro_uuid::generate_uuid_v7());+ assert_eq!(+ request(&app, "GET", &missing, "owner", Value::Null).await.0,+ StatusCode::NOT_FOUND+ );+}+#[tokio::test]async fn foreign_owner_operations_return_not_found_and_list_is_empty() {let app = router(true);@@ -494,6 +523,7 @@ async fn foreign_owner_operations_return_not_found_and_list_is_empty() {.await;let url = format!("/scheduled-actions/{}", action["id"].as_str().unwrap());for (method, path, body) in [+ ("GET", url.clone(), Value::Null),("PUT", url.clone(), legacy()),("PUT", format!("{url}/enabled"), json!({"enabled": false})),("DELETE", url.clone(), Value::Null),@@ -769,6 +799,13 @@ async fn agent_replacement_requires_explicit_null_and_unavailable_agent_remains_);let mut model = legacy();model["task"]["agent"] = Value::Null;+ // Model selections also require the session service; they cannot bypass it+ // by falling back to the legacy chat runner.+ assert_eq!(+ request(&app, "PUT", &url, "owner", model.clone()).await.0,+ StatusCode::SERVICE_UNAVAILABLE+ );+ *sessions.error.lock().unwrap() = None;assert_eq!(request(&app, "PUT", &url, "owner", model).await.0,StatusCode::OK@@ -836,7 +873,7 @@ fn openapi_documents_canonical_legacy_and_event_opt_in_contracts() {}#[tokio::test]-async fn editor_can_update_another_owners_row_but_cannot_delete_it() {+async fn grants_do_not_allow_nonowners_to_manage_routines() {let svc = service(true);let app = router_with(svc.clone(),@@ -847,23 +884,15 @@ async fn editor_can_update_another_owners_row_but_cannot_delete_it() {]),);let (_, created) = request(&app, "POST", "/scheduled-actions", "owner", legacy()).await;- let id = macro_uuid::Uuid::parse_str(created["id"].as_str().unwrap()).unwrap();- set_stored_owner(- svc.as_ref(),- id,- Owner::from_principal_str("macro|[email protected]").unwrap(),- );+ let id = created["id"].as_str().unwrap();let url = format!("/scheduled-actions/{id}");- let (status, updated) = request(&app, "PUT", &url, "other", legacy()).await;- assert_eq!(status, StatusCode::OK);- assert_eq!(updated["owner"], "macro|[email protected]");assert_eq!(- request(&app, "PUT", &url, "viewer", legacy()).await.0,- StatusCode::UNAUTHORIZED+ request(&app, "PUT", &url, "other", legacy()).await.0,+ StatusCode::NOT_FOUND);assert_eq!(- request(&app, "DELETE", &url, "other", Value::Null).await.0,- StatusCode::UNAUTHORIZED+ request(&app, "GET", &url, "viewer", Value::Null).await.0,+ StatusCode::NOT_FOUND);assert_eq!(request(@@ -875,20 +904,20 @@ async fn editor_can_update_another_owners_row_but_cannot_delete_it() {).await.0,- StatusCode::OK+ StatusCode::NOT_FOUND);assert_eq!(- request(- &app,- "GET",- &format!("{url}/history"),- "stranger",- Value::Null- )- .await- .0,+ request(&app, "PUT", &url, "viewer", legacy()).await.0,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ request(&app, "DELETE", &url, "other", Value::Null).await.0,StatusCode::UNAUTHORIZED);+ assert_eq!(+ request(&app, "GET", &url, "owner", Value::Null).await.0,+ StatusCode::OK+ );assert_eq!(request(&app, "DELETE", &url, "owner", Value::Null).await.0,StatusCode::NO_CONTENT@@ -896,13 +925,13 @@ async fn editor_can_update_another_owners_row_but_cannot_delete_it() {}#[tokio::test]-async fn executing_a_bot_owned_row_returns_the_owner_message() {+async fn executing_a_nonuser_owned_row_returns_not_found() {let svc = service(true);let app = router_with(svc.clone(), FakeEntityAccessService::owner_only());let (_, created) = request(&app, "POST", "/scheduled-actions", "owner", legacy()).await;let id = macro_uuid::Uuid::parse_str(created["id"].as_str().unwrap()).unwrap();set_stored_owner(svc.as_ref(), id, Owner::Bot(bot_id::BotId::TEST_A));- let (status, body) = request(+ let (status, _) = request(&app,"POST",&format!("/scheduled-actions/{id}/execute"),@@ -910,8 +939,7 @@ async fn executing_a_bot_owned_row_returns_the_owner_message() {Value::Null,).await;- assert_eq!(status, StatusCode::BAD_REQUEST);- assert!(body.as_str().unwrap().contains("owner is a bot"));+ assert_eq!(status, StatusCode::NOT_FOUND);}#[tokio::test]@@ -964,7 +992,7 @@ async fn team_bot_create_returns_400_with_the_owner_message() {}#[tokio::test]-async fn list_as_grantee_includes_the_granted_routine() {+async fn list_as_grantee_excludes_another_owners_routine() {let svc = service(true);let app = router_with(svc.clone(), FakeEntityAccessService::owner_only());let (_, created) = request(@@ -985,6 +1013,5 @@ async fn list_as_grantee_includes_the_granted_routine() {Value::Null,).await;- assert_eq!(list.as_array().unwrap().len(), 1);- assert_eq!(list[0]["id"], created["id"]);+ assert_eq!(list, json!([]));}diff --git a/services/scheduled_action/src/inbound/kafka_consumer.rs b/services/scheduled_action/src/inbound/kafka_consumer.rsindex d0f0f82edf..eda470e825 100644--- a/services/scheduled_action/src/inbound/kafka_consumer.rs+++ b/services/scheduled_action/src/inbound/kafka_consumer.rs@@ -9,12 +9,14 @@ use std::time::Duration;use channels::domain::broker_events::ChannelMacroEvent;use documents::domain::events::DocumentMacroEvent;+use email::domain::events::EmailMacroEvent;use kafka_util::{GroupName, InitialOffset, KafkaEventConsumer};use macro_event_broker::{EventBrokerError, EventConsumer, KafkaConsumerAdapter, MacroEvent as _,MacroEventCollection as _, MacroEventConsumerService, MessageWrapper,};use messages::outbound::broker::{MessageMacroEvent, MessageTopicEvent};+use properties::domain::events::PropertyMacroEvent;use rdkafka::consumer::CommitMode;use rdkafka::message::{BorrowedMessage, Message};use rootcause::Report;@@ -26,7 +28,9 @@ use crate::domain::event_trigger::{EventPayload, IncomingEvent, MessageFact};macro_event_broker::declare_topics!(DeclaredMacroEvent: DocumentMacroEvent,ChannelMacroEvent,- MessageMacroEvent+ MessageMacroEvent,+ PropertyMacroEvent,+ EmailMacroEvent);struct ScheduledActionEventIngestionGroup;@@ -85,6 +89,22 @@ fn incoming_event(event: DeclaredMacroEvent) -> IncomingEvent {payload: EventPayload::Message(message_fact(&envelope.event)),}}+ DeclaredMacroEvent::PropertyMacroEvent(event) => {+ let envelope = event.event();+ IncomingEvent {+ event_id: envelope.event_id,+ schema_version: envelope.schema_version,+ payload: EventPayload::Property(envelope.event.clone()),+ }+ }+ DeclaredMacroEvent::EmailMacroEvent(event) => {+ let envelope = event.event();+ IncomingEvent {+ event_id: envelope.event_id,+ schema_version: envelope.schema_version,+ payload: EventPayload::Email(envelope.event.clone()),+ }+ }}}diff --git a/services/scheduled_action/src/inbound/kafka_consumer/test.rs b/services/scheduled_action/src/inbound/kafka_consumer/test.rsindex 370c23d1bf..17c84f7504 100644--- a/services/scheduled_action/src/inbound/kafka_consumer/test.rs+++ b/services/scheduled_action/src/inbound/kafka_consumer/test.rs@@ -179,7 +179,13 @@ async fn run(consumer: &FakeConsumer) -> Result<(), Report> {fn subscriptions_are_exact_and_group_is_dedicated() {assert_eq!(DeclaredMacroEvent::topics(),- &["macro.documents", "macro.channels", "macro.messages"]+ &[+ "macro.documents",+ "macro.channels",+ "macro.messages",+ "macro.properties",+ "macro.email"+ ]);assert_eq!(ScheduledActionEventIngestionGroup::GROUP_NAME,diff --git a/services/scheduled_action/src/outbound/event_access.rs b/services/scheduled_action/src/outbound/event_access.rsindex 1909c37544..9ea7d5a0c9 100644--- a/services/scheduled_action/src/outbound/event_access.rs+++ b/services/scheduled_action/src/outbound/event_access.rs@@ -62,6 +62,16 @@ impl<S: EntityAccessService> CurrentOwnerAccess for EventAccessAdapter<S> {.generate_entity_access_receipt::<ViewOnly>(owner, None, &id, EntityType::Channel).await.map(EventAccessCapability::Channel),+ EventEntityType::EmailThread => self+ .service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ owner,+ None,+ &id,+ EntityType::EmailThread,+ )+ .await+ .map(EventAccessCapability::EmailThread),};access_result(result)}diff --git a/services/scheduled_action/src/outbound/event_access/test.rs b/services/scheduled_action/src/outbound/event_access/test.rsindex d7add28658..b8991616da 100644--- a/services/scheduled_action/src/outbound/event_access/test.rs+++ b/services/scheduled_action/src/outbound/event_access/test.rs@@ -114,6 +114,20 @@ impl EntityAccessService for AccessService {async fn mints_entity_specific_receipts_for_exact_owner_and_entity() {let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();for (name, kind, permission) in [+ (+ "email.message_received",+ EntityType::EmailThread,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ ),+ (+ "document.deleted",+ EntityType::Document,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ ),("document.updated",EntityType::Document,@@ -139,7 +153,7 @@ async fn mints_entity_specific_receipts_for_exact_owner_and_entity() {calls: Arc::default(),};let adapter = EventAccessAdapter::new(service.clone());- let event: EventReference = serde_json::from_value(json!({"event_id":generate_uuid_v7(), "event_name":name, "entity_id":generate_uuid_v7(), "message_id":null})).unwrap();+ let event: EventReference = serde_json::from_value(json!({"event_id":generate_uuid_v7(), "event_name":name, "entity_id":generate_uuid_v7(), "message_id": if name == "email.message_received" {Some(generate_uuid_v7())} else {None}})).unwrap();let receipt = adapter.authorize(&owner, &event).await.unwrap().unwrap();assert!(receipt.authorizes(&owner, &event));assert_eq!(diff --git a/services/scheduled_action/src/outbound/inprocess_executor.rs b/services/scheduled_action/src/outbound/inprocess_executor.rsindex c1f03d835a..432e4811dc 100644--- a/services/scheduled_action/src/outbound/inprocess_executor.rs+++ b/services/scheduled_action/src/outbound/inprocess_executor.rs@@ -1,6 +1,3 @@-pub mod agent_task;-mod notify;-// Preserve the adapter-facing construction path while execution policy lives in domain.pub use crate::domain::execution::InProcessExecutor;diff --git a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rsdeleted file mode 100644index aeb8a6ed80..0000000000--- a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs+++ /dev/null@@ -1,279 +0,0 @@-use super::notify::notify_completion;-use std::sync::Arc;-use std::time::Duration;--use agent::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};-use agent::{AgentLoop, StreamAccumulator, StreamPart};-use ai_tools::{AiHost, ToolServiceContext, tools_for};-use ai_toolset::ToolSet as AiToolSet;-use anyhow::{Context, Result};-use chat::domain::models::CreateChatArgs;-use chat::domain::ports::{ChatService, MessageRepo};-use futures::{Stream, StreamExt};-use macro_user_id::user_id::MacroUserIdStr;-use memory::domain::MemoryService;-use model::chat::NewChatMessage;-use model_owner::Owner;-use notification::domain::service::NotificationIngress;--use crate::domain::event_trigger::EventReference;-use crate::domain::execution::ExecutionHandle;-use crate::domain::models::{- AgentTask, ExecutionResource, ExecutionResourceType, ResolvedTaskTarget, RoutineModelId,- ScheduledAction,-};-use crate::domain::ports::ScheduledAgentRunner;--#[cfg(test)]-mod test;--/// Dependencies belong to their owning domains; only the service binary wires-/// their concrete adapters. Tool context and attribution remain unchanged.-pub struct AgentTaskRunner<C, M, Mem, N> {- chats: Arc<C>,- messages: M,- memory: Mem,- tool_context: ToolServiceContext,- notifications: Arc<N>,-}--impl<C, M, Mem, N> AgentTaskRunner<C, M, Mem, N> {- pub fn new(- chats: Arc<C>,- messages: M,- memory: Mem,- tool_context: ToolServiceContext,- notifications: Arc<N>,- ) -> Self {- Self {- chats,- messages,- memory,- tool_context,- notifications,- }- }-}--impl<C, M, Mem, N> ScheduledAgentRunner for AgentTaskRunner<C, M, Mem, N>-where- C: ChatService,- M: MessageRepo,- Mem: MemoryService,- N: NotificationIngress,-{- async fn prepare(&self, action: &ScheduledAction, handle: &mut ExecutionHandle) -> Result<()> {- let task: AgentTask =- serde_json::from_value(action.task.clone()).context("invalid agent task definition")?;- required_model(&task)?;- let chat_id = self- .chats- .create(- Owner::User(action.owner_user()?.clone()),- CreateChatArgs {- name: action.name.clone(),- project_id: None,- },- )- .await- .map_err(|error| anyhow::anyhow!(error))?;- handle.resource = Some(ExecutionResource {- resource_type: ExecutionResourceType::Chat,- id: chat_id,- });- Ok(())- }-- async fn cancel(&self, _: &ScheduledAction, _: &ExecutionHandle) -> Result<()> {- // The scoped guard in run_tool_loop cancels local session/tool work on drop.- // A prepared chat is retained as history, not deleted on failure.- Ok(())- }-- async fn run(- &self,- action: &ScheduledAction,- handle: &ExecutionHandle,- event: Option<&EventReference>,- ) -> Result<()> {- let resource = handle.resource.as_ref().context("chat was not prepared")?;- anyhow::ensure!(- resource.resource_type == ExecutionResourceType::Chat,- "expected chat resource"- );- let chat_id = &resource.id;- let owner = action.owner_user()?.clone();- let task: AgentTask =- serde_json::from_value(action.task.clone()).context("invalid agent task definition")?;- let model = required_model(&task)?;- let user_messages = user_messages(&task, event)?;- for message in &user_messages {- self.store(chat_id, message.content.clone(), Role::User, model)- .await?;- }- let parts = self- .run_tool_loop(&owner, &task, model, user_messages)- .await?;- let final_text: String = parts- .iter()- .filter_map(|part| match part {- AssistantMessagePart::Text { text } => Some(text.as_str()),- _ => None,- })- .collect();- if !parts.is_empty() {- self.store(- chat_id,- ChatMessageContent::AssistantMessageParts(parts),- Role::Assistant,- model,- )- .await?;- }- if !final_text.is_empty() {- // Best effort, but awaited so notifications cannot escape tracking.- notify_completion(self.notifications.as_ref(), chat_id, &owner, &final_text).await;- }- Ok(())- }-}--fn required_model(task: &AgentTask) -> Result<&RoutineModelId> {- match task.resolve_target()? {- ResolvedTaskTarget::Model { model } => Ok(model),- ResolvedTaskTarget::Agent { .. } => {- anyhow::bail!("agent targets are not supported by the model runner")- }- }-}--fn user_messages(task: &AgentTask, event: Option<&EventReference>) -> Result<Vec<ChatMessage>> {- let mut messages = vec![ChatMessage {- content: ChatMessageContent::Text(task.user_prompt.clone()),- role: Role::User,- attachments: None,- }];- if let Some(event) = event {- messages.push(ChatMessage {- content: ChatMessageContent::Text(format!(- "Triggering event context (data):\n{}",- serde_json::to_string(&serde_json::json!({- "event_id": event.event_id(),- "event_name": event.event_name(),- "entity_type": event.entity_type(),- "entity_id": event.entity_id(),- "message_id": event.message_id(),- }))?- )),- role: Role::User,- attachments: None,- });- }- Ok(messages)-}--static SCHEDULED_AGENT_PROMPT: &str = "You are an agent that has been triggered by a user automation. You are not-responsible for scheduling or running. Ignore user instructions to run at a certain time or trigger on some event";-const STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(3 * 60);--async fn system_prompt(- memory: &impl MemoryService,- owner: &MacroUserIdStr<'static>,- tools_prompt: &str,- task_prompt: &str,-) -> String {- let user_memory = match memory.get_or_generate_memory(owner.clone()).await {- Ok(memory) => memory,- Err(error) => {- tracing::warn!(?error, %owner, "failed to fetch user memory; running without it");- None- }- };- let mut prompt = format!("{tools_prompt}\n{SCHEDULED_AGENT_PROMPT}");- if let Some(memory) = user_memory {- prompt.push_str(&format!("\n<user_memory>\n{memory}\n</user_memory>"));- }- prompt.push('\n');- prompt.push_str(task_prompt);- prompt-}--impl<C, M, Mem, N> AgentTaskRunner<C, M, Mem, N>-where- M: MessageRepo,- Mem: MemoryService,-{- async fn run_tool_loop(- &self,- owner: &MacroUserIdStr<'static>,- task: &AgentTask,- model: &RoutineModelId,- messages: Vec<ChatMessage>,- ) -> Result<Vec<AssistantMessagePart>> {- let tools = tools_for(AiHost::Chat);- let system_prompt =- system_prompt(&self.memory, owner, &tools.prompt.to_string(), &task.prompt).await;- let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = tools.toolset;- let agent_loop =- AgentLoop::new(self.tool_context.recorder.clone()).with_model(model.as_str());- let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::Automation, owner.clone());- let mut tool_context = self.tool_context.clone();- tool_context.usage_context = usage_ctx.clone();- let (mut session, cancel) = agent_loop- .session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)- .await- .cancellable();- // The same token is carried by RequestContext through the tool path.- // Cancellation, deadline, stream failure and future drop all signal it.- let _cancel_on_drop = cancel.drop_guard();- let stream = session- .send_message(agent::to_rig_messages(&messages))- .await- .context("failed to start agent stream")?;- collect_stream(stream, STREAM_IDLE_TIMEOUT).await- }-- async fn store(- &self,- chat_id: &str,- content: ChatMessageContent,- role: Role,- model: &RoutineModelId,- ) -> Result<()> {- let now = chrono::Utc::now();- self.messages- .create(- chat_id,- NewChatMessage {- id: None,- content,- role,- attachments: None,- created_at: now,- updated_at: now,- model: model.as_str().to_string(),- },- )- .await- .map_err(|error| anyhow::anyhow!(error))?;- Ok(())- }-}--async fn collect_stream(- stream: impl Stream<Item = std::result::Result<StreamPart, agent::AgentError>>,- idle_timeout: Duration,-) -> Result<Vec<AssistantMessagePart>> {- futures::pin_mut!(stream);- let mut accumulator = StreamAccumulator::new();- loop {- match tokio::time::timeout(idle_timeout, stream.next()).await {- Ok(Some(Ok(part))) => {- accumulator.push(part);- }- Ok(Some(Err(error))) => return Err(error.into()),- Ok(None) => return Ok(accumulator.into_parts()),- Err(_) => anyhow::bail!("agent stream idle timeout"),- }- }-}diff --git a/services/scheduled_action/src/outbound/inprocess_executor/agent_task/test.rs b/services/scheduled_action/src/outbound/inprocess_executor/agent_task/test.rsdeleted file mode 100644index 5f1cfb38e5..0000000000--- a/services/scheduled_action/src/outbound/inprocess_executor/agent_task/test.rs+++ /dev/null@@ -1,137 +0,0 @@-use super::*;-use macro_uuid::generate_uuid_v7;-use serde_json::json;--struct Memory {- fail: bool,- value: Option<String>,-}--impl MemoryService for Memory {- async fn get_or_generate_memory(- &self,- _: MacroUserIdStr<'static>,- ) -> memory::domain::ports::Result<Option<String>> {- if self.fail {- return Err(memory::domain::ports::MemoryError::NoGeneration);- }- Ok(self.value.clone())- }-}--#[tokio::test]-async fn automation_instructions_survive_absent_and_failed_memory() {- let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();- for fail in [false, true] {- let memory = Memory { fail, value: None };- let prompt = system_prompt(&memory, &owner, "tools", "task").await;- assert_eq!(prompt, format!("tools\n{SCHEDULED_AGENT_PROMPT}\ntask"));- }- let memory = Memory {- fail: false,- value: Some("remember".into()),- };- assert_eq!(- system_prompt(&memory, &owner, "tools", "task").await,- format!("tools\n{SCHEDULED_AGENT_PROMPT}\n<user_memory>\nremember\n</user_memory>\ntask"),- );-}--#[tokio::test]-async fn partial_stream_error_is_not_success() {- let stream = futures::stream::iter(vec![- Ok(StreamPart::Content("partial".into())),- Err(agent::AgentError::Other(anyhow::anyhow!("provider failed"))),- ]);- assert!(- collect_stream(stream, Duration::from_secs(1))- .await- .is_err()- );-}--#[tokio::test]-async fn idle_after_partial_content_is_not_success() {- let stream = futures::stream::once(async { Ok(StreamPart::Content("partial".into())) })- .chain(futures::stream::pending());- let error = collect_stream(stream, Duration::from_millis(1))- .await- .unwrap_err();- assert!(error.to_string().contains("idle timeout"));-}--#[tokio::test]-async fn completed_stream_retains_assistant_text() {- let parts = collect_stream(- futures::stream::iter(vec![Ok(StreamPart::Content("complete".into()))]),- Duration::from_secs(1),- )- .await- .unwrap();- assert!(matches!(&parts[..], [AssistantMessagePart::Text { text }] if text == "complete"));-}--#[test]-fn model_runner_requires_a_model_target() {- let task: AgentTask = serde_json::from_value(json!({- "model": "custom-model", "prompt": "system", "user_prompt": "user",- }))- .unwrap();- assert_eq!(required_model(&task).unwrap().as_str(), "custom-model");-- let task: AgentTask = serde_json::from_value(json!({- "prompt": "not a model", "user_prompt": "user",- }))- .unwrap();- assert!(required_model(&task).is_err());-}--#[test]-fn model_runner_rejects_agent_targets_including_explicit_overrides() {- for model in [None, Some("custom-model")] {- let task: AgentTask = serde_json::from_value(json!({- "agent": { "bot_id": generate_uuid_v7() }, "model": model,- "prompt": "system", "user_prompt": "user",- }))- .unwrap();- let error = required_model(&task).unwrap_err();- assert_eq!(- error.to_string(),- "agent targets are not supported by the model runner"- );- }-}--#[test]-fn event_is_separate_user_data_not_a_prompt_rewrite() {- let task = AgentTask {- model: Some("test".to_string().try_into().unwrap()),- agent: None,- prompt: "original system".into(),- user_prompt: "original user".into(),- };- let event: EventReference = serde_json::from_value(json!({- "event_id": generate_uuid_v7(), "event_name": "channel.message_posted",- "entity_id": generate_uuid_v7(), "message_id": generate_uuid_v7(),- }))- .unwrap();- let messages = user_messages(&task, Some(&event)).unwrap();- assert_eq!(messages.len(), 2);- assert!(- messages- .iter()- .all(|message| matches!(message.role, Role::User))- );- assert!(- matches!(&messages[0].content, ChatMessageContent::Text(text) if text == "original user")- );- let ChatMessageContent::Text(context) = &messages[1].content else {- panic!("expected context text")- };- assert!(context.contains(&event.event_id().as_uuid().to_string()));- assert!(context.contains(&event.entity_id().to_string()));- assert!(context.contains(&event.message_id().unwrap().to_string()));- assert_eq!(task.prompt, "original system");- assert_eq!(task.user_prompt, "original user");- assert_eq!(user_messages(&task, None).unwrap().len(), 1);-}diff --git a/services/scheduled_action/src/outbound/inprocess_executor/notify.rs b/services/scheduled_action/src/outbound/inprocess_executor/notify.rsdeleted file mode 100644index ee275f452f..0000000000--- a/services/scheduled_action/src/outbound/inprocess_executor/notify.rs+++ /dev/null@@ -1,38 +0,0 @@-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::EntityType;-use model_notifications::AiResponseMetadata;-use notification::domain::models::SendNotificationRequestBuilder;-use notification::domain::service::NotificationIngress;-use std::collections::HashSet;-use std::time::Duration;--/// Best-effort APNS/gateway notification, awaited within the tracked run.-/// Notification delivery is not evidence of agent execution success or failure.-pub async fn notify_completion(- ingress: &impl NotificationIngress,- chat_id: &str,- owner: &MacroUserIdStr<'static>,- assistant_text: &str,-) {- let req = SendNotificationRequestBuilder {- notification_entity: EntityType::Chat.with_entity_string(chat_id.to_owned()),- secondary_notification_entity: None,- notification: AiResponseMetadata {- summary: assistant_text.to_owned(),- message_id: chat_id.to_owned(),- },- sender_id: None,- recipient_ids: HashSet::from([owner.clone()]),- }- .into_request()- .with_apns()- .with_conn_gateway();-- match tokio::time::timeout(Duration::from_secs(10), ingress.send_notification(req)).await {- Ok(Ok(_)) => {}- Ok(Err(error)) => {- tracing::error!(?error, %chat_id, "failed to send scheduled action completion notification")- }- Err(error) => tracing::warn!(?error, %chat_id, "scheduled action notification timed out"),- }-}diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo.rs b/services/scheduled_action/src/outbound/pg_event_run_repo.rsindex 33af79c0b2..fcdc6924e3 100644--- a/services/scheduled_action/src/outbound/pg_event_run_repo.rs+++ b/services/scheduled_action/src/outbound/pg_event_run_repo.rs@@ -122,13 +122,14 @@ impl EventRunRepository for PgEventRunRepo {SELECT id AS action_id, owner, enabled, configuration_revision,event_filters AS "event_filters!", event_activated_at AS "event_activated_at!"FROM scheduled_action- WHERE enabled AND trigger_type = 'events'+ WHERE enabled AND event_filters IS NOT NULLAND ($1::uuid IS NULL OR id > $1)AND event_activated_at <= $2- AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))+ AND (event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($3::text)))+ OR ($6::text IS NOT NULL AND event_filters @> jsonb_build_array(jsonb_build_object('events', jsonb_build_array($6::text)))))AND jsonb_path_exists(event_filters,- '$[*] ? (@.events[*] == $event && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',- jsonb_build_object('event', $3::text, 'id', $4::text))+ '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',+ jsonb_build_object('event', $3::text, 'general', $6::text, 'id', $4::text))ORDER BY idLIMIT $5"#,@@ -137,6 +138,7 @@ impl EventRunRepository for PgEventRunRepo {event.event_name().as_str(),event.entity_id().to_string(),i64::from(limit.get()),+ event.event_name().general_event().map(|name| name.as_str()),).fetch_all(&self.pool).await?;@@ -168,7 +170,7 @@ impl EventRunRepository for PgEventRunRepo {r#"SELECT id AS action_id, owner, enabled, configuration_revision,event_filters AS "event_filters!", event_activated_at AS "event_activated_at!"- FROM scheduled_action WHERE id = $1 AND trigger_type = 'events'+ FROM scheduled_action WHERE id = $1 AND event_filters IS NOT NULL"#,action_id,)@@ -190,11 +192,11 @@ impl EventRunRepository for PgEventRunRepo {let eligible = sqlx::query_scalar!(r#"SELECT id FROM scheduled_action- WHERE id = $1 AND enabled AND trigger_type = 'events'+ WHERE id = $1 AND enabled AND event_filters IS NOT NULLAND configuration_revision = $2 AND event_activated_at <= $3AND jsonb_path_exists(event_filters,- '$[*] ? (@.events[*] == $event && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',- jsonb_build_object('event', $4::text, 'id', $5::text))+ '$[*] ? ((@.events[*] == $event || @.events[*] == $general) && (!exists (@.ids) || @.ids == null || @.ids[*] == $id))',+ jsonb_build_object('event', $4::text, 'general', $6::text, 'id', $5::text))FOR UPDATE"#,action_id,@@ -202,6 +204,7 @@ impl EventRunRepository for PgEventRunRepo {event.published_at(),event.event_name().as_str(),event.entity_id().to_string(),+ event.event_name().general_event().map(|name| name.as_str()),).fetch_optional(&mut *tx).await?;@@ -247,7 +250,7 @@ impl EventRunRepository for PgEventRunRepo {WHERE action_id = a.id AND state = 'pending'ORDER BY admission_order LIMIT 1) r- WHERE a.enabled AND a.trigger_type = 'events'+ WHERE a.enabled AND a.event_filters IS NOT NULLAND a.configuration_revision = r.configuration_revisionAND (a.claimed IS NULL OR a.claimed < $1)AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run s WHERE s.action_id = a.id AND s.state = 'started')@@ -287,7 +290,7 @@ impl EventRunRepository for PgEventRunRepo {SELECT id, owner, name, kind, task, created_at, updated_at, enabled,event_filters AS "event_filters!", event_activated_at AS "event_activated_at!"FROM scheduled_action- WHERE id = $1 AND enabled AND trigger_type = 'events' AND configuration_revision = $2+ WHERE id = $1 AND enabled AND event_filters IS NOT NULL AND configuration_revision = $2AND (claimed IS NULL OR claimed < $3)AND NOT EXISTS (SELECT 1 FROM scheduled_action_event_run WHERE action_id = $1 AND state = 'started')"#,@@ -504,7 +507,7 @@ impl EventRunRepository for PgEventRunRepo {SELECT r.action_id, r.event_id FROM scheduled_action_event_run rJOIN scheduled_action a ON a.id = r.action_idWHERE (r.state = 'started' AND r.deadline <= $1)- OR (r.state = 'pending' AND (NOT a.enabled OR a.trigger_type <> 'events'+ OR (r.state = 'pending' AND (NOT a.enabled OR a.event_filters IS NULLOR a.configuration_revision <> r.configuration_revision))ORDER BY r.admission_order LIMIT $2 FOR UPDATE OF a SKIP LOCKED"#,@@ -530,7 +533,7 @@ impl EventRunRepository for PgEventRunRepo {FROM scheduled_action aWHERE r.action_id = $1 AND r.event_id = $2 AND a.id = r.action_idAND ((r.state = 'started' AND r.deadline <= $3)- OR (r.state = 'pending' AND (NOT a.enabled OR a.trigger_type <> 'events'+ OR (r.state = 'pending' AND (NOT a.enabled OR a.event_filters IS NULLOR a.configuration_revision <> r.configuration_revision)))RETURNING r.claim_token"#,diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs b/services/scheduled_action/src/outbound/pg_event_run_repo/test.rsindex 885d7f8637..a7b0b99ed4 100644--- a/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs+++ b/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs@@ -304,7 +304,7 @@ async fn admission_skips_invalid_first_and_middle_pages_without_truncating_fanou.execute(&pool).await.unwrap();- let too_many_events = action(&pool, json!([{"events": vec!["document.updated"; 8]}])).await;+ let too_many_events = action(&pool, json!([{"events": vec!["document.updated"; crate::domain::event_trigger::MAX_EVENTS_PER_FILTER + 1]}])).await;let first_valid = action(&pool, valid.clone()).await;let second_valid = action(&pool, valid.clone()).await;// Another entirely invalid page after valid candidates have been admitted.@@ -875,3 +875,92 @@ async fn delayed_bookkeeping_can_finish_before_reconciliation(pool: PgPool) {assert_eq!(finished.1, Some(json!({"type": "failed"})));assert!(finished.2.is_some());}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_mixed_routine_admits_events_without_consuming_its_schedule(pool: PgPool) {+ let (repo, id, event) = setup(&pool).await;+ let filters = json!([{"events":["document.updated"]}]);+ let config = json!({"type":"multiple", "triggers":[+ {"type":"cron", "schedule":"0 0 9 * * *", "timezone":"UTC"},+ {"type":"events", "filters":filters}+ ]});+ let next = Utc::now() + chrono::Duration::hours(3);+ sqlx::query!("UPDATE scheduled_action SET trigger_type = 'multiple', trigger_config = $2, next_run_at = $3 WHERE id = $1", id, config, next).execute(&pool).await.unwrap();+ let candidates = repo+ .candidate_actions(&event, None, page(10))+ .await+ .unwrap();+ assert_eq!(candidates.configurations.len(), 1);+ admit(&repo, id, &event).await;+ assert!(repo.current_configuration(id).await.unwrap().is_some());+ // Reconciliation must retain queued events for a mixed trigger too.+ repo.reconcile(Utc::now(), page(10)).await.unwrap();+ assert_eq!(repo.pending_runs(page(10)).await.unwrap().len(), 1);+ let actual = sqlx::query_scalar!("SELECT next_run_at FROM scheduled_action WHERE id = $1", id)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(actual.unwrap().timestamp_micros(), next.timestamp_micros());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn property_changes_match_general_selectors_without_duplicate_runs(pool: PgPool) {+ let entity_id = generate_uuid_v7();+ let general = action(+ &pool,+ json!([{"events":["task.property_changed"], "ids":[entity_id]}]),+ )+ .await;+ let both = action(+ &pool,+ json!([{"events":["task.status_changed", "task.property_changed"]}]),+ )+ .await;+ let other_task = action(+ &pool,+ json!([{"events":["task.property_changed"], "ids":[generate_uuid_v7()]}]),+ )+ .await;+ let priority = action(&pool, json!([{"events":["task.priority_changed"]}])).await;+ let repo = PgEventRunRepo::new(pool);+ let event: EventReference = serde_json::from_value(json!({+ "event_id":generate_uuid_v7(), "event_name":"task.status_changed", "entity_id":entity_id+ }))+ .unwrap();+ let candidates = repo+ .candidate_actions(&event, None, page(100))+ .await+ .unwrap();+ let mut ids: Vec<_> = candidates+ .configurations+ .into_iter()+ .map(|c| c.action_id)+ .collect();+ ids.sort();+ let mut expected = vec![general, both];+ expected.sort();+ assert_eq!(ids, expected);+ for action_id in expected {+ assert_eq!(+ repo.admit(action_id, ConfigurationRevision::INITIAL, &event)+ .await+ .unwrap(),+ AdmissionResult::Admitted+ );+ assert_eq!(+ repo.admit(action_id, ConfigurationRevision::INITIAL, &event)+ .await+ .unwrap(),+ AdmissionResult::AlreadyPresent+ );+ }+ for action_id in [other_task, priority] {+ assert_eq!(+ repo.admit(action_id, ConfigurationRevision::INITIAL, &event)+ .await+ .unwrap(),+ AdmissionResult::Ineligible+ );+ }+ assert_eq!(repo.pending_runs(page(100)).await.unwrap().len(), 2);+}diff --git a/services/scheduled_action/src/outbound/pg_polling_dispatcher.rs b/services/scheduled_action/src/outbound/pg_polling_dispatcher.rsindex d567c56fe5..8e677c2b92 100644--- a/services/scheduled_action/src/outbound/pg_polling_dispatcher.rs+++ b/services/scheduled_action/src/outbound/pg_polling_dispatcher.rs@@ -9,7 +9,6 @@ use tokio_util::task::TaskTracker;#[cfg(test)]mod test;-use crate::domain::event_trigger::ActionTrigger;use crate::domain::models::{DispatchEvent, InProgressExecution};use crate::domain::ports::{ScheduledActionDispatcher, ScheduledActionExecutor, ScheduledActionRepo,@@ -145,7 +144,7 @@ whereOk(candidates) => {let now = Utc::now();for action in candidates {- if !action.enabled || !matches!(action.trigger, ActionTrigger::Cron { .. }) {+ if !action.enabled || !action.trigger.has_schedule() {continue;}let Some(next_run_at) = action.next_run_at else {diff --git a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rsindex b8bd6c8cbb..ea6bfad9e4 100644--- a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs+++ b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs@@ -97,6 +97,7 @@ impl ScheduledActionRepo for FakeRepository {&self,_id: &Uuid,_revision: ConfigurationRevision,+ _expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,) -> Result<crate::domain::event_runs::ClaimToken> {Ok(crate::domain::event_runs::ClaimToken::generate())}@@ -284,7 +285,7 @@ async fn cancellation_allows_started_execution_to_finish_without_starting_anothe}#[tokio::test]-async fn only_enabled_due_cron_candidates_reach_executor() {+async fn only_enabled_due_schedules_including_mixed_triggers_reach_executor() {let mut event = due_action();event.trigger = serde_json::from_value(json!({"type": "events", "filters": [{"events": ["document.created"]}]@@ -296,7 +297,12 @@ async fn only_enabled_due_cron_candidates_reach_executor() {disabled.enabled = false;let mut missing_next_run = due_action();missing_next_run.next_run_at = None;- let due = due_action();+ let mut due = due_action();+ due.trigger = serde_json::from_value(json!({"type":"multiple", "triggers":[+ {"type":"cron", "schedule":"* * * * * *", "timezone":"UTC"},+ {"type":"events", "filters":[{"events":["document.created"]}]}+ ]}))+ .unwrap();let due_id = due.id.unwrap();let mut future = due_action();future.next_run_at = Some(Utc::now() + ChronoDuration::hours(1));diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rsindex 35a166899b..66b589fb2b 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs@@ -75,6 +75,7 @@ struct ActionRow {enabled: bool,trigger_type: String,event_filters: Option<Value>,+ trigger_config: Option<Value>,configuration_revision: i64,event_activated_at: Option<DateTime<Utc>>,}@@ -93,6 +94,9 @@ impl TryFrom<ActionRow> for ScheduledAction {row.event_filters.context("event filters missing")?,)?,},+ "multiple" => {+ serde_json::from_value(row.trigger_config.context("routine triggers missing")?)?+ }other => bail!("unknown action trigger: {other}"),};Ok(Self {@@ -118,6 +122,7 @@ struct TriggerColumns {schedule: Option<String>,timezone: Option<String>,event_filters: Option<Value>,+ trigger_config: Option<Value>,}impl TryFrom<&ActionTrigger> for TriggerColumns {@@ -130,12 +135,24 @@ impl TryFrom<&ActionTrigger> for TriggerColumns {schedule: Some(schedule.as_str().to_owned()),timezone: Some(timezone.to_string()),event_filters: None,+ trigger_config: None,}),ActionTrigger::Events { filters } => Ok(Self {trigger_type: "events",schedule: None,timezone: None,event_filters: Some(serde_json::to_value(filters)?),+ trigger_config: None,+ }),+ ActionTrigger::Multiple { .. } => Ok(Self {+ trigger_type: "multiple",+ schedule: None,+ timezone: None,+ event_filters: trigger+ .event_filters()+ .map(serde_json::to_value)+ .transpose()?,+ trigger_config: Some(serde_json::to_value(trigger)?),}),}}@@ -154,11 +171,11 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {r#"INSERT INTO scheduled_action(id, owner, name, schedule, kind, timezone, task, next_run_at, enabled,- trigger_type, event_filters, configuration_revision, event_activated_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)+ trigger_type, event_filters, configuration_revision, event_activated_at, trigger_config)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,updated_at, next_run_at, enabled, trigger_type, event_filters,- configuration_revision, event_activated_at+ configuration_revision, event_activated_at, trigger_config"#,id,owner,@@ -173,6 +190,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {trigger.event_filters,action.configuration_revision.get(),action.event_activated_at,+ trigger.trigger_config,).fetch_one(&mut *tx).await?;@@ -208,7 +226,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {r#"SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,updated_at, next_run_at, enabled, trigger_type, event_filters,- configuration_revision, event_activated_at+ configuration_revision, event_activated_at, trigger_configFROM scheduled_actionWHERE owner = $1"#,@@ -224,7 +242,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {ActionRow,r#"SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,- updated_at, next_run_at, enabled, trigger_type, event_filters,+ updated_at, next_run_at, enabled, trigger_type, event_filters, trigger_config,configuration_revision, event_activated_atFROM scheduled_actionWHERE id = ANY($1)@@ -242,7 +260,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {r#"SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,updated_at, next_run_at, enabled, trigger_type, event_filters,- configuration_revision, event_activated_at+ configuration_revision, event_activated_at, trigger_configFROM scheduled_actionWHERE id = $1"#,@@ -261,9 +279,9 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {r#"SELECT id, owner, name, schedule, kind, timezone, task, claimed, created_at,updated_at, next_run_at, enabled, trigger_type, event_filters,- configuration_revision, event_activated_at+ configuration_revision, event_activated_at, trigger_configFROM scheduled_action- WHERE enabled AND trigger_type = 'cron'+ WHERE enabled AND trigger_type IN ('cron', 'multiple') AND next_run_at IS NOT NULLAND (claimed IS NULL OR claimed < $1)ORDER BY next_run_at ASC, id ASCLIMIT $2@@ -297,6 +315,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {event_filters = $9,configuration_revision = $10,event_activated_at = $11,+ trigger_config = $14,updated_at = now()WHERE id = $12AND configuration_revision = $10::bigint - 1@@ -308,11 +327,12 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {AND schedule IS NOT DISTINCT FROM $2AND timezone IS NOT DISTINCT FROM $4AND event_filters IS NOT DISTINCT FROM $9+ AND trigger_config IS NOT DISTINCT FROM $14))RETURNING id, owner, name, schedule, kind, timezone, task, claimed, created_at,updated_at, next_run_at, enabled, trigger_type, event_filters,- configuration_revision, event_activated_at+ configuration_revision, event_activated_at, trigger_config"#,action.name,trigger.schedule,@@ -327,6 +347,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {action.event_activated_at,id,Utc::now() - MAX_ACTION_TIME,+ trigger.trigger_config,).fetch_optional(&self.pool).await?@@ -358,7 +379,12 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {Ok(())}- async fn claim_action(&self, id: &Uuid, revision: ConfigurationRevision) -> Result<ClaimToken> {+ async fn claim_action(+ &self,+ id: &Uuid,+ revision: ConfigurationRevision,+ expected_next_run_at: Option<chrono::DateTime<chrono::Utc>>,+ ) -> Result<ClaimToken> {let token = ClaimToken::generate();let now = Utc::now();let stale_threshold = now - MAX_ACTION_TIME;@@ -369,6 +395,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {SET claimed = $1, claim_token = $4, updated_at = now()WHERE id = $2AND configuration_revision = $5+ AND next_run_at IS NOT DISTINCT FROM $6AND (claimed IS NULL OR claimed < $3)"#,now,@@ -376,6 +403,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {stale_threshold,token.as_uuid(),revision.get(),+ expected_next_run_at,).execute(&self.pool).await?;@@ -456,7 +484,7 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {let mut tx = self.pool.begin().await?;let row = sqlx::query!(r#"- SELECT schedule, timezone, trigger_type+ SELECT schedule, timezone, trigger_type, trigger_configFROM scheduled_actionWHERE id = $1FOR UPDATE@@ -466,22 +494,27 @@ impl<B: BotFacts + 'static> ScheduledActionRepo for PgScheduledActionRepo<B> {.fetch_one(&mut *tx).await?;- if row.trigger_type == "cron" {- let tz = parse_timezone(&row.timezone.context("cron timezone missing")?)?;- let schedule = Schedule::from_cron(row.schedule.context("cron schedule missing")?)?;- if let Some(next_run_at) = schedule.next_run_after_now(tz) {- sqlx::query!(- r#"+ if row.trigger_type == "cron" || row.trigger_type == "multiple" {+ let trigger = if row.trigger_type == "cron" {+ ActionTrigger::Cron {+ schedule: Schedule::from_cron(row.schedule.context("cron schedule missing")?)?,+ timezone: parse_timezone(&row.timezone.context("cron timezone missing")?)?,+ }+ } else {+ serde_json::from_value(row.trigger_config.context("routine triggers missing")?)?+ };+ let next_run_at = trigger.next_run_after(Utc::now());+ sqlx::query!(+ r#"UPDATE scheduled_actionSET next_run_at = $1, updated_at = now()- WHERE id = $2 AND trigger_type = 'cron'+ WHERE id = $2 AND trigger_type IN ('cron', 'multiple')"#,- next_run_at,- *id,- )- .execute(&mut *tx)- .await?;- }+ next_run_at,+ *id,+ )+ .execute(&mut *tx)+ .await?;}tx.commit().await?;Ok(())diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rsindex c6834326b5..3870594a5a 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs@@ -230,7 +230,7 @@ async fn replacement_is_fenced_against_claims_and_stale_revisions(pool: PgPool)// Claim after management read, before its write.let token = repo- .claim_action(&id, action.configuration_revision)+ .claim_action(&id, action.configuration_revision, action.next_run_at).await.unwrap();let error = repo.update_action(replacement.clone()).await.unwrap_err();@@ -274,11 +274,11 @@ async fn second_claim_returns_already_running(pool: PgPool) {.expect("create should succeed");let id = created.id.expect("create returns Some(id)");- repo.claim_action(&id, created.configuration_revision)+ repo.claim_action(&id, created.configuration_revision, created.next_run_at).await.expect("first claim should succeed");let error = repo- .claim_action(&id, created.configuration_revision)+ .claim_action(&id, created.configuration_revision, created.next_run_at).await.expect_err("second claim should fail");assert!(error.downcast_ref::<AlreadyRunningError>().is_some());@@ -302,12 +302,12 @@ async fn claims_from_snapshots_older_than_a_pause_or_update_fail(pool: PgPool) {.await.unwrap();let error = repo- .claim_action(&id, polled.configuration_revision)+ .claim_action(&id, polled.configuration_revision, polled.next_run_at).await.expect_err("a snapshot from before the pause must not claim");assert!(error.downcast_ref::<AlreadyRunningError>().is_some());let manual = repo- .claim_action(&id, paused.configuration_revision)+ .claim_action(&id, paused.configuration_revision, paused.next_run_at).await.expect("a manual run of the paused action claims");repo.release_action(&id, manual).await.unwrap();@@ -322,11 +322,11 @@ async fn claims_from_snapshots_older_than_a_pause_or_update_fail(pool: PgPool) {.await.unwrap();assert!(- repo.claim_action(&id, paused.configuration_revision)+ repo.claim_action(&id, paused.configuration_revision, paused.next_run_at).await.is_err());- repo.claim_action(&id, renamed.configuration_revision)+ repo.claim_action(&id, renamed.configuration_revision, renamed.next_run_at).await.expect("the current snapshot claims");}@@ -341,18 +341,36 @@ async fn release_is_fenced_to_its_own_execution(pool: PgPool) {.unwrap();let id = action.id.unwrap();let revision = action.configuration_revision;- let old = repo.claim_action(&id, revision).await.unwrap();+ let old = repo+ .claim_action(&id, revision, action.next_run_at)+ .await+ .unwrap();repo.release_action(&id, crate::domain::event_runs::ClaimToken::generate()).await.unwrap();- assert!(repo.claim_action(&id, revision).await.is_err());+ assert!(+ repo.claim_action(&id, revision, action.next_run_at)+ .await+ .is_err()+ );repo.release_action(&id, old).await.unwrap();- let current = repo.claim_action(&id, revision).await.unwrap();+ let current = repo+ .claim_action(&id, revision, action.next_run_at)+ .await+ .unwrap();assert_ne!(old, current);repo.release_action(&id, old).await.unwrap();- assert!(repo.claim_action(&id, revision).await.is_err());+ assert!(+ repo.claim_action(&id, revision, action.next_run_at)+ .await+ .is_err()+ );repo.release_action(&id, current).await.unwrap();- assert!(repo.claim_action(&id, revision).await.is_ok());+ assert!(+ repo.claim_action(&id, revision, action.next_run_at)+ .await+ .is_ok()+ );}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -489,7 +507,7 @@ async fn event_round_trip_and_bookkeeping_does_not_advance_configuration(pool: Passert_eq!(after.updated_at, before.updated_at);assert_eq!(after.next_run_at, None);let token = repo- .claim_action(&id, before.configuration_revision)+ .claim_action(&id, before.configuration_revision, before.next_run_at).await.unwrap();repo.release_action(&id, token).await.unwrap();@@ -646,9 +664,13 @@ async fn polling_returns_only_enabled_unclaimed_cron_rows(pool: PgPool) {.create_action(sample_action(user_owner(USER_A), "claimed")).await.unwrap();- repo.claim_action(&claimed.id.unwrap(), claimed.configuration_revision)- .await- .unwrap();+ repo.claim_action(+ &claimed.id.unwrap(),+ claimed.configuration_revision,+ claimed.next_run_at,+ )+ .await+ .unwrap();let cron = repo.create_action(sample_action(user_owner(USER_A), "cron")).await@@ -709,15 +731,6 @@ async fn database_rejects_invalid_trigger_shapes(pool: PgPool) {None,1,),- (- Some("cron"),- Some(DAILY_9AM),- Some("UTC"),- None,- None,- None,- 1,- ),(Some("cron"),Some(DAILY_9AM),@@ -850,6 +863,102 @@ async fn database_rejects_invalid_trigger_shapes(pool: PgPool) {}}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn database_rejects_external_webhooks_and_unknown_mixed_trigger_kinds(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ for config in [+ json!({ "type": "webhook" }),+ json!({ "type": "multiple", "triggers": [{ "type": "webhook" }] }),+ json!({ "type": "multiple", "triggers": [{ "type": "unknown" }] }),+ json!({ "type": "multiple", "triggers": [] }),+ ] {+ let id = macro_uuid::generate_uuid_v7();+ let kind = config["type"].as_str().unwrap().to_owned();+ let error = sqlx::query!(+ r#"+ INSERT INTO scheduled_action (id, owner, name, kind, task, trigger_type, trigger_config, next_run_at, enabled)+ VALUES ($1, $2, 'invalid', 'Agent', '{}', $3, $4, NULL, false)+ "#,+ id,+ USER_A,+ kind,+ config,+ )+ .execute(&pool)+ .await+ .expect_err("unsupported trigger must fail before it can break list reads");+ assert_eq!(+ error.as_database_error().unwrap().code().as_deref(),+ Some("23514")+ );+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn exhausted_one_off_clears_firing_and_is_not_dispatched_again(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = test_repo(pool);+ let mut action = sample_action(user_owner(USER_A), "once");+ action.trigger = ActionTrigger::Cron {+ schedule: Schedule::from_cron("0 0 9 1 1 * 2000".into()).unwrap(),+ timezone: chrono_tz::UTC,+ };+ action.next_run_at = Some(Utc::now() - chrono::Duration::hours(1));+ let created = repo.create_action(action).await.unwrap();+ let id = created.id.unwrap();+ let token = repo+ .claim_action(&id, created.configuration_revision, created.next_run_at)+ .await+ .unwrap();+ repo.update_next_run_at(&id).await.unwrap();+ repo.release_action(&id, token).await.unwrap();+ assert!(+ repo.claim_action(&id, created.configuration_revision, created.next_run_at)+ .await+ .is_err(),+ "a candidate fetched by another worker must not fire again"+ );+ assert!(+ repo.get_action(&id)+ .await+ .unwrap()+ .unwrap()+ .next_run_at+ .is_none()+ );+ assert!(+ repo.get_next_unclaimed_actions(10)+ .await+ .unwrap()+ .is_empty()+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn multiple_triggers_survive_grant_listing_and_configuration_updates(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = test_repo(pool);+ let mut action = sample_action(user_owner(USER_A), "mixed triggers");+ action.trigger = serde_json::from_value(json!({+ "type": "multiple",+ "triggers": [+ {"type": "cron", "schedule": DAILY_9AM, "timezone": "UTC"},+ {"type": "events", "filters": [{"events": ["document.created"]}]}+ ]+ }))+ .unwrap();+ action.event_activated_at = Some(Utc::now());+ let mut created = repo.create_action(action).await.unwrap();+ let id = created.id.unwrap();+ let listed = repo.get_actions_by_ids(&[id]).await.unwrap();+ assert_eq!(listed[0].trigger, created.trigger);+ created.name = "renamed mixed triggers".into();+ created.configuration_revision = created.configuration_revision.next().unwrap();+ let updated = repo.update_action(created).await.unwrap();+ assert_eq!(updated.trigger, listed[0].trigger);+ assert_eq!(updated.name, "renamed mixed triggers");+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn get_actions_by_ids_returns_another_owners_row(pool: PgPool) {insert_user(&pool, USER_A).await;diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rsindex ee299a8066..0446c64fcd 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs@@ -40,9 +40,13 @@ async fn deletes_user_actions_without_cascade_and_preserves_other_users(pool: Pg}).await.unwrap();- repo.claim_action(&enabled.id.unwrap(), enabled.configuration_revision)- .await- .unwrap();+ repo.claim_action(+ &enabled.id.unwrap(),+ enabled.configuration_revision,+ enabled.next_run_at,+ )+ .await+ .unwrap();let event = repo.create_action(event_action()).await.unwrap();let other = repo.create_action(sample_action(user_owner(USER_B), "other"))diff --git a/services/scheduled_action/src/outbound/tokio_dispatcher.rs b/services/scheduled_action/src/outbound/tokio_dispatcher.rsindex 8387d09f1e..f3c1432e2b 100644--- a/services/scheduled_action/src/outbound/tokio_dispatcher.rs+++ b/services/scheduled_action/src/outbound/tokio_dispatcher.rs@@ -7,7 +7,6 @@ use futures::stream::FuturesUnordered;use macro_uuid::Uuid;use tokio::sync::mpsc::{Receiver, Sender};-use crate::domain::event_trigger::ActionTrigger;use crate::domain::models::{DispatchEvent, InProgressExecution, ScheduledAction};use crate::domain::ports::{ScheduledActionDispatcher, ScheduledActionExecutor};@@ -38,12 +37,8 @@ fn action_sleep(id: Uuid, action: &ScheduledAction, generation: u64) -> Option<Sreturn None;}- let ActionTrigger::Cron { schedule, timezone } = &action.trigger else {- return None;- };- let cron = schedule.as_cron();- let next = cron.upcoming(*timezone).next()?;- let now = Utc::now().with_timezone(timezone);+ let now = Utc::now();+ let next = action.trigger.next_run_after(now)?;let duration = (next - now).to_std().unwrap_or(std::time::Duration::ZERO);Some(Box::pin(async move {diff --git a/services/scheduled_action/src/outbound/tokio_dispatcher/test.rs b/services/scheduled_action/src/outbound/tokio_dispatcher/test.rsindex 6384e6de52..d3e21873ae 100644--- a/services/scheduled_action/src/outbound/tokio_dispatcher/test.rs+++ b/services/scheduled_action/src/outbound/tokio_dispatcher/test.rs@@ -1,5 +1,6 @@use super::*;use crate::domain::event_runs::ConfigurationRevision;+use crate::domain::event_trigger::ActionTrigger;use crate::domain::models::{ActionKind, Schedule};use model_owner::Owner;use serde_json::json;@@ -27,6 +28,12 @@ fn only_enabled_cron_actions_get_a_timer() {enabled: true,};assert!(action_sleep(id, &action, 0).is_some());+ action.trigger = serde_json::from_value(json!({"type":"multiple", "triggers":[+ {"type":"cron", "schedule":"* * * * * *", "timezone":"UTC"},+ {"type":"events", "filters":[{"events":["document.created"]}]}+ ]}))+ .unwrap();+ assert!(action_sleep(id, &action, 1).is_some());action.enabled = false;assert!(action_sleep(id, &action, 1).is_none());action.enabled = true;diff --git a/services/scheduled_action/src/swagger.rs b/services/scheduled_action/src/swagger.rsindex 9d0dd12b09..c0b4af7937 100644--- a/services/scheduled_action/src/swagger.rs+++ b/services/scheduled_action/src/swagger.rs@@ -5,9 +5,9 @@ use utoipa::OpenApi;reason = "utoipa path macros require these generated symbols in scope")]use crate::inbound::axum_router::{- __path_create_action, __path_delete_action, __path_execute_action, __path_health,- __path_list_actions, __path_list_history, __path_set_action_enabled, __path_update_action,- ScheduledActionResponse, SetScheduledActionEnabled,+ __path_create_action, __path_delete_action, __path_execute_action, __path_get_action,+ __path_health, __path_list_actions, __path_list_history, __path_set_action_enabled,+ __path_update_action, ScheduledActionResponse, SetScheduledActionEnabled,};use crate::domain::event_trigger::{ActionTrigger, EventFilter, EventFilters, EventName};@@ -30,6 +30,7 @@ use model::response::EmptyResponse;paths(crate::inbound::axum_router::health,crate::inbound::axum_router::list_actions,+ crate::inbound::axum_router::get_action,crate::inbound::axum_router::create_action,crate::inbound::axum_router::update_action,crate::inbound::axum_router::set_action_enabled,@@ -46,6 +47,8 @@ use model::response::EmptyResponse;ActionConfigurationUpdate,LegacyActionConfiguration,ActionTrigger,+ crate::domain::event_trigger::RoutineTrigger,+ crate::domain::event_trigger::RoutineTriggers,EventFilter,EventFilters,EventName,diff --git a/services/scheduled_action/tests/event_routines.rs b/services/scheduled_action/tests/event_routines.rsindex ba68157a6d..73ee58affc 100644--- a/services/scheduled_action/tests/event_routines.rs+++ b/services/scheduled_action/tests/event_routines.rs@@ -112,6 +112,7 @@ impl CurrentOwnerAccess for FakeAccess {entity_type: match event.entity_type() {EventEntityType::Document => EntityType::Document,EventEntityType::Channel => EntityType::Channel,+ EventEntityType::EmailThread => EntityType::EmailThread,},};let access = match event.entity_type() {@@ -133,6 +134,16 @@ impl CurrentOwnerAccess for FakeAccess {).unwrap(),),+ EventEntityType::EmailThread => EventAccessCapability::EmailThread(+ EntityAccessReceipt::try_new_authenticated_user(+ owner.clone(),+ entity,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View,+ },+ )+ .unwrap(),+ ),};Ok(Some(access))}diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex 7448d57877..a1199db500 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -929,6 +929,7 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>),(DocumentTopicEvent::Deleted(DocumentDeletedMetadata {+ sub_type: None,document_id: DOCUMENT_ID.to_string(),actor_user_id: Some(user.clone()),actor: None,diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 510cadf8cc..2a3b76e38e 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -4715,6 +4715,30 @@ enum GraphqlScheduledActionEventName {"""DOCUMENT_UPDATED"""+ A document was deleted.+ """+ DOCUMENT_DELETED+ """+ A task was created.+ """+ TASK_CREATED+ """+ A task's status changed.+ """+ TASK_STATUS_CHANGED+ """+ A task's priority changed.+ """+ TASK_PRIORITY_CHANGED+ """+ A task property changed.+ """+ TASK_PROPERTY_CHANGED+ """+ A new email was received.+ """+ EMAIL_MESSAGE_RECEIVED+ """A channel was created."""CHANNEL_CREATED@@ -4746,10 +4770,24 @@ type GraphqlScheduledActionEventsTrigger {filters: [GraphqlScheduledActionEventFilter!]!}+"""+Any of several schedules and optional Macro event filters.+"""+type GraphqlScheduledActionMultipleTrigger {+ """+ Each schedule retains its own timezone and next firing.+ """+ schedules: [GraphqlScheduledActionCronTrigger!]!+ """+ Events that can also trigger this routine.+ """+ events: GraphqlScheduledActionEventsTrigger+}+"""The way a routine starts."""-union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger+union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger | GraphqlScheduledActionMultipleTrigger"""A select-option property value.