Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(routines): expose to gql (#7179)

Will Hutchinson54938096b039
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 305b1f2b83..9f123eb094 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2812,8 +2812,11 @@
"crates/agent_fold",
"crates/agent_runtime_protocol",
"crates/agent_session",
+ "crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
+ "crates/analytics_client",
+ "crates/anthropic",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
@@ -2838,6 +2841,7 @@
"crates/documents",
"crates/dynamodb_client",
"crates/email",
+ "crates/email_service_client",
"crates/email_utils",
"crates/embedding",
"crates/entity_access",
@@ -2853,6 +2857,7 @@
"crates/frecency",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/generic_email_domains",
"crates/github",
"crates/google_token",
"crates/graphql_activity",
@@ -2865,11 +2870,14 @@
"crates/graphql_notification",
"crates/graphql_permission",
"crates/graphql_properties",
+ "crates/graphql_scheduled_action",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
"crates/harness_id",
"crates/harness_token",
+ "crates/import",
"crates/initiative",
+ "crates/initiative_documents",
"crates/invite_email",
"crates/ip_extractor",
"crates/item_filter_index",
@@ -2877,21 +2885,30 @@
"crates/kafka_util",
"crates/last_online_tracker",
"crates/lexical_client",
+ "crates/lexical_mention_extractor",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_aws_config",
+ "crates/macro_config",
+ "crates/macro_config_derive",
+ "crates/macro_cors",
"crates/macro_db_client",
"crates/macro_entrypoint",
"crates/macro_env",
"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/mcp_client",
+ "crates/mcp_select",
+ "crates/mcp_toolset",
+ "crates/memory",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -2911,12 +2928,17 @@
"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/predicate_index",
"crates/projects",
"crates/prompt",
@@ -2927,8 +2949,10 @@
"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",
@@ -2940,9 +2964,11 @@
"crates/system_properties",
"crates/system_skills",
"crates/task_dedup",
+ "crates/teams",
"crates/unfurl",
"crates/user_quota",
- "crates/workspace-hack"
+ "crates/workspace-hack",
+ "services/scheduled_action"
],
"connection": [
"crates/agent",
@@ -3771,6 +3797,7 @@
"crates/graphql_notification",
"crates/graphql_permission",
"crates/graphql_properties",
+ "crates/graphql_scheduled_action",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
"crates/harness_id",
@@ -3811,6 +3838,7 @@
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
+ "crates/memory",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3878,7 +3906,8 @@
"crates/webhook",
"crates/webhook_signature",
"crates/workspace-hack",
- "services/document_storage_service"
+ "services/document_storage_service",
+ "services/scheduled_action"
],
"document_storage_service_client": [
"crates/agent",
@@ -6041,6 +6070,154 @@
"crates/system_properties",
"crates/workspace-hack"
],
+ "graphql_scheduled_action": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_changes",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/agent_session",
+ "crates/ai_tools",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/analytics_client",
+ "crates/anthropic",
+ "crates/attachment",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bot_token",
+ "crates/bots",
+ "crates/broadcast",
+ "crates/calendar_events",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/chat",
+ "crates/comms_db_client",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/database_env_vars",
+ "crates/document_sub_type",
+ "crates/documents",
+ "crates/dynamodb_client",
+ "crates/email",
+ "crates/email_service_client",
+ "crates/email_utils",
+ "crates/embedding",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "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",
+ "crates/fusionauth",
+ "crates/genai_telemetry",
+ "crates/generic_email_domains",
+ "crates/github",
+ "crates/google_token",
+ "crates/graphql_scheduled_action",
+ "crates/harness_id",
+ "crates/harness_token",
+ "crates/import",
+ "crates/initiative",
+ "crates/initiative_documents",
+ "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",
+ "crates/macro_config",
+ "crates/macro_config_derive",
+ "crates/macro_cors",
+ "crates/macro_db_client",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "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/mcp_client",
+ "crates/mcp_select",
+ "crates/mcp_toolset",
+ "crates/memory",
+ "crates/mention_utils",
+ "crates/messages",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "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/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_service_client",
+ "crates/sync_service",
+ "crates/sync_service_client",
+ "crates/system_properties",
+ "crates/system_skills",
+ "crates/task_dedup",
+ "crates/teams",
+ "crates/unfurl",
+ "crates/user_quota",
+ "crates/workspace-hack",
+ "services/scheduled_action"
+ ],
"graphql_soup": [
"crates/activity",
"crates/agent",
diff --git a/Cargo.lock b/Cargo.lock
index d3a92e9226..d2da49abff 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4265,6 +4265,7 @@ dependencies = [
"graphql_notification",
"graphql_permission",
"graphql_properties",
+ "graphql_scheduled_action",
"graphql_soup",
"macro_authorization",
"macro_user_id",
@@ -4278,6 +4279,7 @@ dependencies = [
"notification",
"predicate-index",
"rootcause",
+ "scheduled_action",
"serde",
"soup",
"soup-filter-projection",
@@ -5907,6 +5909,7 @@ dependencies = [
"futures",
"github",
"graphql_initiative",
+ "graphql_scheduled_action",
"graphql_soup",
"harnesses",
"hex",
@@ -5967,6 +5970,7 @@ dependencies = [
"rootcause",
"s3_key",
"saved_views",
+ "scheduled_action",
"schemars 1.2.1",
"search_service",
"secretsmanager_client",
@@ -8194,6 +8198,23 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "graphql_scheduled_action"
+version = "0.1.0"
+dependencies = [
+ "async-graphql",
+ "chrono",
+ "macro_user_id",
+ "macro_uuid",
+ "model_owner",
+ "rootcause",
+ "scheduled_action",
+ "serde_json",
+ "tokio",
+ "tracing",
+ "workspace-hack",
+]
+
[[package]]
name = "graphql_soup"
version = "0.1.0"
@@ -20649,6 +20670,7 @@ dependencies = [
"ahash",
"aho-corasick",
"anyhow",
+ "async-graphql",
"async-openai",
"aws-config",
"aws-credential-types",
diff --git a/Cargo.toml b/Cargo.toml
index 2155d27839..3b0806b949 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -56,6 +56,7 @@ members = [
"crates/graphql_notification",
"crates/graphql_permission",
"crates/graphql_properties",
+ "crates/graphql_scheduled_action",
"crates/graphql_soup",
"crates/graphql_soup_filter_input",
"crates/gtm_invite",
diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.toml
index e4009d2a7f..e85a7b2540 100644
--- a/crates/complete_graph/Cargo.toml
+++ b/crates/complete_graph/Cargo.toml
@@ -29,6 +29,7 @@ graphql_initiative = { path = "../graphql_initiative" }
graphql_notification = { path = "../graphql_notification" }
graphql_permission = { path = "../graphql_permission" }
graphql_properties = { path = "../graphql_properties" }
+graphql_scheduled_action = { path = "../graphql_scheduled_action" }
graphql_soup = { path = "../graphql_soup" }
macro_authorization = { path = "../macro_authorization", features = [
"axum",
@@ -58,6 +59,7 @@ models_pagination = { path = "../models_pagination" }
models_properties = { path = "../models_properties" }
models_soup = { path = "../models_soup" }
rootcause = { workspace = true }
+scheduled_action = { path = "../../services/scheduled_action" }
serde = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index ef1c88fad5..93a2000c5a 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -46,6 +46,7 @@ use graphql_properties::{
NoOpEntityPropertyWriter, PropertiesMutationRoot, load_property_definitions,
load_property_options,
};
+use graphql_scheduled_action::{GraphqlScheduledAction, resolve_scheduled_actions};
use graphql_soup::{
GraphqlSoupEmailThread, GraphqlSoupInitiative, GroupedSoup, GroupedSoupInput,
SoupEmailThreadMutationOutput, SoupEntityEdges, SoupInput, SoupPage, SoupPatch,
@@ -667,6 +668,14 @@ where
resolve_task_initiative_references(ctx, self.user_id.clone(), task_ids).await
}
+ /// AI routines owned by the authenticated user.
+ async fn scheduled_actions(
+ &self,
+ ctx: &Context<'_>,
+ ) -> async_graphql::Result<Vec<GraphqlScheduledAction>> {
+ resolve_scheduled_actions(ctx, self.user_id.clone()).await
+ }
+
/// Authorized property definitions available to this viewer.
async fn property_definitions(
&self,
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index df99d621a8..9c0d910c33 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -46,6 +46,7 @@ use super::*;
mod email_archive;
mod initiative;
+mod scheduled_actions;
mod soup_patches;
const VALID_USER_ID: &str = "macro|[email protected]";
diff --git a/crates/complete_graph/src/schema/test/scheduled_actions.rs b/crates/complete_graph/src/schema/test/scheduled_actions.rs
new file mode 100644
index 0000000000..078edaafc7
--- /dev/null
+++ b/crates/complete_graph/src/schema/test/scheduled_actions.rs
@@ -0,0 +1,65 @@
+use std::sync::{Arc, Mutex};
+
+use rootcause::Report;
+use scheduled_action::domain::{models::ScheduledAction, ports::ScheduledActionReadService};
+
+use super::*;
+
+#[derive(Default)]
+struct RecordingScheduledActionReader {
+ calls: Mutex<Vec<MacroUserIdStr<'static>>>,
+}
+
+impl ScheduledActionReadService for RecordingScheduledActionReader {
+ async fn list_owned(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>, Report> {
+ self.calls.lock().expect("call lock").push(user_id);
+ Ok(Vec::new())
+ }
+}
+
+#[tokio::test]
+async fn user_id_does_not_read_routines_and_the_list_receives_the_viewer() {
+ let harness = harness();
+ let reader = Arc::new(RecordingScheduledActionReader::default());
+ let context = graphql_scheduled_action::ScheduledActionGraphqlContext::new(Arc::clone(&reader));
+
+ let id_only = harness
+ .schema
+ .execute(
+ harness
+ .request("{ user { id } }", authenticated_parts())
+ .data(context.clone()),
+ )
+ .await;
+ assert!(id_only.errors.is_empty(), "{:?}", id_only.errors);
+ assert_eq!(
+ id_only.data.into_json().unwrap()["user"]["id"],
+ VALID_USER_ID
+ );
+ assert!(reader.calls.lock().expect("call lock").is_empty());
+
+ let listed = harness
+ .schema
+ .execute(
+ harness
+ .request(
+ "{ user { scheduledActions { id } } }",
+ authenticated_parts(),
+ )
+ .data(context),
+ )
+ .await;
+ assert!(listed.errors.is_empty(), "{:?}", listed.errors);
+ assert!(
+ listed.data.into_json().unwrap()["user"]["scheduledActions"]
+ .as_array()
+ .expect("list")
+ .is_empty()
+ );
+ let calls = reader.calls.lock().expect("call lock");
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].as_ref(), VALID_USER_ID);
+}
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 13e585d49c..43167259d2 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -466,6 +466,198 @@ fn initiative_reads_and_mutations_share_the_canonical_soup_entity() {
}
}
+#[test]
+fn scheduled_actions_hang_off_the_authenticated_user() {
+ use apollo_compiler::schema::ExtendedType;
+
+ let sdl = crate::build_schema().sdl();
+ assert_sdl_line(&sdl, "scheduledActions: [GraphqlScheduledAction!]!");
+ assert_sdl_line(
+ &sdl,
+ "union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger",
+ );
+ assert!(sdl.contains("AI routines owned by the authenticated user."));
+ for value in [
+ "DOCUMENT_CREATED",
+ "DOCUMENT_UPDATED",
+ "CHANNEL_CREATED",
+ "CHANNEL_MESSAGE_POSTED",
+ "CHANNEL_MENTIONED",
+ "CHANNEL_MESSAGE_PATCHED",
+ "CHANNEL_MESSAGE_ATTACHMENT_CREATED",
+ ] {
+ assert_sdl_line(&sdl, value);
+ }
+
+ let schema = apollo_compiler::Schema::parse_and_validate(sdl.as_str(), "schema.graphql")
+ .expect("generated SDL is valid");
+ let ExtendedType::Object(user) = schema.types.get("GraphqlUser").expect("user type") else {
+ panic!("GraphqlUser must be an object");
+ };
+ assert!(user.fields.contains_key("scheduledActions"));
+ assert!(
+ user.fields["scheduledActions"]
+ .description
+ .as_ref()
+ .expect("scheduledActions documentation")
+ .to_string()
+ .contains("authenticated user")
+ );
+
+ let ExtendedType::Object(root) = schema.types.get("SoupQueryRoot").expect("query root") else {
+ panic!("SoupQueryRoot must be an object");
+ };
+ assert!(!root.fields.contains_key("scheduledActions"));
+
+ let ExtendedType::Interface(soup) = schema
+ .types
+ .get("GraphqlSoupEntity")
+ .expect("soup entity interface")
+ else {
+ panic!("GraphqlSoupEntity must be an interface");
+ };
+ assert!(!soup.fields.contains_key("scheduledActions"));
+
+ let ExtendedType::Enum(soup_types) = schema
+ .types
+ .get("GraphqlSoupEntityType")
+ .expect("soup entity type enum")
+ else {
+ panic!("GraphqlSoupEntityType must be an enum");
+ };
+ assert!(!soup_types.values.contains_key("SCHEDULED_ACTION"));
+ let ExtendedType::Enum(entity_types) = schema
+ .types
+ .get("GraphqlEntityType")
+ .expect("entity type enum")
+ else {
+ panic!("GraphqlEntityType must be an enum");
+ };
+ assert!(entity_types.values.contains_key("SCHEDULED_ACTION"));
+
+ let ExtendedType::Object(action) = schema
+ .types
+ .get("GraphqlScheduledAction")
+ .expect("routine object")
+ else {
+ panic!("GraphqlScheduledAction must be an object");
+ };
+ assert_eq!(action.fields["id"].ty.to_string(), "ID!");
+ assert_eq!(
+ action
+ .fields
+ .keys()
+ .map(|name| name.to_string())
+ .collect::<Vec<_>>(),
+ vec![
+ "id",
+ "name",
+ "enabled",
+ "trigger",
+ "agentTask",
+ "claimExpiresAt",
+ "createdAt",
+ "updatedAt",
+ ]
+ );
+ for absent in [
+ "owner",
+ "kind",
+ "task",
+ "configurationRevision",
+ "eventActivatedAt",
+ "isRunning",
+ "nextRunAt",
+ ] {
+ assert!(
+ !action.fields.contains_key(absent),
+ "{absent} must stay off the routine object"
+ );
+ }
+ assert!(
+ action.fields["claimExpiresAt"]
+ .description
+ .as_ref()
+ .expect("claimExpiresAt documentation")
+ .to_string()
+ .contains("after that instant")
+ );
+
+ let ExtendedType::Object(cron) = schema
+ .types
+ .get("GraphqlScheduledActionCronTrigger")
+ .expect("cron trigger")
+ else {
+ panic!("cron trigger must be an object");
+ };
+ assert!(!cron.fields.contains_key("id"));
+ assert_eq!(cron.fields["nextRunAt"].ty.to_string(), "String");
+ assert!(
+ cron.fields["nextRunAt"]
+ .description
+ .as_ref()
+ .expect("nextRunAt documentation")
+ .to_string()
+ .contains("disabled")
+ );
+
+ let ExtendedType::Object(task) = schema
+ .types
+ .get("GraphqlScheduledActionAgentTask")
+ .expect("agent task")
+ else {
+ panic!("agent task must be an object");
+ };
+ assert_eq!(task.fields["model"].ty.to_string(), "String");
+ assert_eq!(
+ task.fields["agent"].ty.to_string(),
+ "GraphqlScheduledActionAgent"
+ );
+
+ for embedded in [
+ "GraphqlScheduledActionEventsTrigger",
+ "GraphqlScheduledActionEventFilter",
+ "GraphqlScheduledActionAgentTask",
+ "GraphqlScheduledActionAgent",
+ ] {
+ let ExtendedType::Object(value) = schema.types.get(embedded).expect(embedded) else {
+ panic!("{embedded} must be an object");
+ };
+ assert!(
+ !value.fields.contains_key("id"),
+ "{embedded} must stay embedded"
+ );
+ }
+
+ let ExtendedType::Object(agent) = schema
+ .types
+ .get("GraphqlScheduledActionAgent")
+ .expect("scheduled action agent")
+ else {
+ panic!("scheduled action agent must be an object");
+ };
+ assert_eq!(agent.fields["botId"].ty.to_string(), "ID!");
+
+ let ExtendedType::Object(filter) = schema
+ .types
+ .get("GraphqlScheduledActionEventFilter")
+ .expect("event filter")
+ else {
+ panic!("event filter must be an object");
+ };
+ assert_eq!(filter.fields["entityIds"].ty.to_string(), "[ID!]");
+ let entity_ids = filter.fields["entityIds"]
+ .description
+ .as_ref()
+ .expect("entityIds documentation")
+ .to_string();
+ assert!(entity_ids.contains("Null matches every id"), "{entity_ids}");
+ assert!(
+ entity_ids.contains("empty list matches nothing"),
+ "{entity_ids}"
+ );
+}
+
/// The exported SDL is a frontend contract: `schema.graphql` feeds the client
/// codegen and the normalized-cache metadata. Splitting the schema across
/// crates must never change it silently — regenerate with
diff --git a/crates/graphql_scheduled_action/Cargo.toml b/crates/graphql_scheduled_action/Cargo.toml
new file mode 100644
index 0000000000..a05ece0d87
--- /dev/null
+++ b/crates/graphql_scheduled_action/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "graphql_scheduled_action"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+async-graphql = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+rootcause = { workspace = true }
+scheduled_action = { path = "../../services/scheduled_action" }
+serde_json = { workspace = true }
+tracing = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+chrono = { workspace = true }
+macro_uuid = { path = "../macro_uuid" }
+model_owner = { path = "../model_owner" }
+tokio = { workspace = true, features = ["macros", "rt"] }
diff --git a/crates/graphql_scheduled_action/src/context.rs b/crates/graphql_scheduled_action/src/context.rs
new file mode 100644
index 0000000000..c4a9e07c7c
--- /dev/null
+++ b/crates/graphql_scheduled_action/src/context.rs
@@ -0,0 +1,34 @@
+use std::{future::Future, pin::Pin, sync::Arc};
+
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use scheduled_action::domain::{models::ScheduledAction, ports::ScheduledActionReadService};
+
+pub(crate) type ListFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<Vec<ScheduledAction>, Report>> + Send + 'a>>;
+
+pub(crate) trait ScheduledActionReader: Send + Sync {
+ fn list_owned(&self, user_id: MacroUserIdStr<'static>) -> ListFuture<'_>;
+}
+
+/// Type-erased routine reader stored in GraphQL request data.
+#[derive(Clone)]
+pub struct ScheduledActionGraphqlContext(pub(crate) Arc<dyn ScheduledActionReader>);
+
+impl ScheduledActionGraphqlContext {
+ /// Erase `service` so request data does not carry its type parameters.
+ pub fn new<S: ScheduledActionReadService>(service: Arc<S>) -> Self {
+ Self(Arc::new(ReadServiceAdapter { service }))
+ }
+}
+
+struct ReadServiceAdapter<S> {
+ service: Arc<S>,
+}
+
+impl<S: ScheduledActionReadService> ScheduledActionReader for ReadServiceAdapter<S> {
+ fn list_owned(&self, user_id: MacroUserIdStr<'static>) -> ListFuture<'_> {
+ let service = Arc::clone(&self.service);
+ Box::pin(async move { service.list_owned(user_id).await })
+ }
+}
diff --git a/crates/graphql_scheduled_action/src/lib.rs b/crates/graphql_scheduled_action/src/lib.rs
new file mode 100644
index 0000000000..200013ef2c
--- /dev/null
+++ b/crates/graphql_scheduled_action/src/lib.rs
@@ -0,0 +1,20 @@
+//! GraphQL inbound adapter for listing AI routines (`ScheduledAction`).
+#![deny(missing_docs)]
+
+mod context;
+mod objects;
+mod query;
+
+pub use context::ScheduledActionGraphqlContext;
+pub use objects::GraphqlScheduledAction;
+pub use query::resolve_scheduled_actions;
+
+use async_graphql::ErrorExtensions;
+use rootcause::Report;
+
+pub(crate) fn unavailable(error: Report) -> async_graphql::Error {
+ tracing::error!(error = ?error, "scheduled action list failed");
+ async_graphql::Error::new("scheduled actions are unavailable").extend_with(|_, extensions| {
+ extensions.set("code", "INTERNAL_SERVER_ERROR");
+ })
+}
diff --git a/crates/graphql_scheduled_action/src/objects.rs b/crates/graphql_scheduled_action/src/objects.rs
new file mode 100644
index 0000000000..f610ba1454
--- /dev/null
+++ b/crates/graphql_scheduled_action/src/objects.rs
@@ -0,0 +1,187 @@
+use async_graphql::{Enum, ID, SimpleObject, Union};
+use rootcause::Report;
+use scheduled_action::domain::{
+ event_trigger::{ActionTrigger, EventName},
+ models::{ActionKind, AgentTask, ScheduledAction},
+};
+use serde_json::Value;
+
+/// An AI routine owned by the authenticated user.
+#[derive(SimpleObject)]
+pub struct GraphqlScheduledAction {
+ /// Stable identifier of the routine.
+ id: ID,
+ /// Name shown for the routine.
+ name: String,
+ /// Whether automatic dispatch runs this routine.
+ enabled: bool,
+ /// What starts a run of this routine.
+ trigger: GraphqlScheduledActionTrigger,
+ /// Agent task for this routine. Null when the stored task is not an agent task.
+ agent_task: Option<GraphqlScheduledActionAgentTask>,
+ /// When the current execution claim stops blocking configuration changes.
+ /// The timestamp stays present after that instant so clients can compare it themselves.
+ claim_expires_at: Option<String>,
+ /// When the routine was created, as RFC 3339.
+ created_at: String,
+ /// When the routine row last changed, including execution bookkeeping, as RFC 3339.
+ updated_at: String,
+}
+
+/// The way a routine starts.
+#[derive(Union)]
+pub(crate) enum GraphqlScheduledActionTrigger {
+ Cron(GraphqlScheduledActionCronTrigger),
+ Events(GraphqlScheduledActionEventsTrigger),
+}
+
+/// A routine that runs on a cron schedule.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionCronTrigger {
+ /// Cron expression in the six- or seven-field format the scheduler accepts.
+ schedule: String,
+ /// Time zone name the cron expression is evaluated in.
+ timezone: String,
+ /// Next cron firing, as RFC 3339. Null when the routine is disabled.
+ next_run_at: Option<String>,
+}
+
+/// A routine that runs when matching events are published.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionEventsTrigger {
+ /// Event filters. A run starts when any filter matches.
+ filters: Vec<GraphqlScheduledActionEventFilter>,
+}
+
+/// One event filter. The event name and entity id must both match.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionEventFilter {
+ /// Event names that can satisfy this filter.
+ events: Vec<GraphqlScheduledActionEventName>,
+ /// Entity ids that can satisfy this filter. Null matches every id; an empty list matches nothing.
+ entity_ids: Option<Vec<ID>>,
+}
+
+/// The agent task a routine runs.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionAgentTask {
+ /// Model the task runs. Null when the selected agent uses its default model.
+ model: Option<String>,
+ /// Selected agent. Null for model-only tasks.
+ agent: Option<GraphqlScheduledActionAgent>,
+ /// System prompt for the agent.
+ prompt: String,
+ /// User prompt for the agent.
+ user_prompt: String,
+}
+
+/// An agent selected to run a routine.
+#[derive(SimpleObject)]
+pub(crate) struct GraphqlScheduledActionAgent {
+ /// Stable identifier of the selected agent.
+ bot_id: ID,
+}
+
+/// Events a routine filter can name.
+#[derive(Enum, Copy, Clone, Eq, PartialEq)]
+pub(crate) enum GraphqlScheduledActionEventName {
+ /// A document was created.
+ DocumentCreated,
+ /// A document was updated.
+ DocumentUpdated,
+ /// A channel was created.
+ ChannelCreated,
+ /// A channel message was posted.
+ ChannelMessagePosted,
+ /// A user was mentioned in a channel.
+ ChannelMentioned,
+ /// A channel message was patched.
+ ChannelMessagePatched,
+ /// A channel message attachment was created.
+ ChannelMessageAttachmentCreated,
+}
+
+impl From<EventName> for GraphqlScheduledActionEventName {
+ fn from(name: EventName) -> Self {
+ match name {
+ EventName::DocumentCreated => Self::DocumentCreated,
+ EventName::DocumentUpdated => Self::DocumentUpdated,
+ EventName::ChannelCreated => Self::ChannelCreated,
+ EventName::ChannelMessagePosted => Self::ChannelMessagePosted,
+ EventName::ChannelMentioned => Self::ChannelMentioned,
+ EventName::ChannelMessagePatched => Self::ChannelMessagePatched,
+ EventName::ChannelMessageAttachmentCreated => Self::ChannelMessageAttachmentCreated,
+ }
+ }
+}
+
+pub(crate) fn scheduled_action(action: ScheduledAction) -> Result<GraphqlScheduledAction, Report> {
+ let Some(id) = action.id else {
+ return Err(rootcause::report!(
+ "listed scheduled action is missing an id"
+ ));
+ };
+ let trigger = trigger(&action);
+ let agent_task = agent_task(&action.kind, &action.task);
+ let claim_expires_at = action.claim_expires_at().map(|at| at.to_rfc3339());
+ let created_at = action.created_at.to_rfc3339();
+ let updated_at = action.updated_at.to_rfc3339();
+ Ok(GraphqlScheduledAction {
+ id: ID(id.to_string()),
+ name: action.name,
+ enabled: action.enabled,
+ trigger,
+ agent_task,
+ claim_expires_at,
+ created_at,
+ updated_at,
+ })
+}
+
+fn trigger(action: &ScheduledAction) -> GraphqlScheduledActionTrigger {
+ match &action.trigger {
+ ActionTrigger::Cron { schedule, timezone } => {
+ let next_run_at = if action.enabled {
+ action.next_run_at.map(|at| at.to_rfc3339())
+ } else {
+ None
+ };
+ GraphqlScheduledActionTrigger::Cron(GraphqlScheduledActionCronTrigger {
+ schedule: schedule.as_str().to_owned(),
+ timezone: timezone.to_string(),
+ next_run_at,
+ })
+ }
+ ActionTrigger::Events { filters } => {
+ GraphqlScheduledActionTrigger::Events(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(),
+ })
+ }
+ }
+}
+
+fn agent_task(kind: &ActionKind, task: &Value) -> Option<GraphqlScheduledActionAgentTask> {
+ match kind {
+ ActionKind::Agent => {
+ let task = serde_json::from_value::<AgentTask>(task.clone()).ok()?;
+ task.resolve_target().ok()?;
+ Some(GraphqlScheduledActionAgentTask {
+ model: task.model.map(|model| model.as_str().to_owned()),
+ agent: task.agent.map(|agent| GraphqlScheduledActionAgent {
+ bot_id: ID(agent.bot_id.to_string()),
+ }),
+ prompt: task.prompt,
+ user_prompt: task.user_prompt,
+ })
+ }
+ }
+}
diff --git a/crates/graphql_scheduled_action/src/query.rs b/crates/graphql_scheduled_action/src/query.rs
new file mode 100644
index 0000000000..a720658e18
--- /dev/null
+++ b/crates/graphql_scheduled_action/src/query.rs
@@ -0,0 +1,27 @@
+use async_graphql::Context;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::context::ScheduledActionGraphqlContext;
+use super::objects::{GraphqlScheduledAction, scheduled_action};
+use super::unavailable;
+
+#[cfg(test)]
+mod test;
+
+/// List routines owned by `user_id`.
+pub async fn resolve_scheduled_actions(
+ ctx: &Context<'_>,
+ user_id: MacroUserIdStr<'static>,
+) -> async_graphql::Result<Vec<GraphqlScheduledAction>> {
+ let actions = ctx
+ .data::<ScheduledActionGraphqlContext>()?
+ .0
+ .list_owned(user_id)
+ .await
+ .map_err(unavailable)?;
+ actions
+ .into_iter()
+ .map(scheduled_action)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(unavailable)
+}
diff --git a/crates/graphql_scheduled_action/src/query/test.rs b/crates/graphql_scheduled_action/src/query/test.rs
new file mode 100644
index 0000000000..ab7d0cf95d
--- /dev/null
+++ b/crates/graphql_scheduled_action/src/query/test.rs
@@ -0,0 +1,343 @@
+use std::sync::{Arc, Mutex};
+
+use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use model_owner::Owner;
+use rootcause::Report;
+use scheduled_action::domain::{
+ event_runs::ConfigurationRevision,
+ event_trigger::{ActionTrigger, EventFilter, EventFilters, EventName},
+ models::{ActionKind, ScheduledAction},
+ ports::ScheduledActionReadService,
+};
+use serde_json::{Value, json};
+
+use super::resolve_scheduled_actions;
+use crate::ScheduledActionGraphqlContext;
+
+const VIEWER: &str = "macro|[email protected]";
+const SECRET: &str = "hidden-prompt-value";
+const QUERY: &str = r#"
+{
+ user {
+ scheduledActions {
+ id
+ name
+ enabled
+ trigger {
+ __typename
+ ... on GraphqlScheduledActionCronTrigger {
+ schedule
+ timezone
+ nextRunAt
+ }
+ ... on GraphqlScheduledActionEventsTrigger {
+ filters { events entityIds }
+ }
+ }
+ agentTask { model agent { botId } prompt userPrompt }
+ claimExpiresAt
+ createdAt
+ updatedAt
+ }
+ }
+}
+"#;
+
+struct FakeReader {
+ calls: Mutex<Vec<MacroUserIdStr<'static>>>,
+ actions: Vec<ScheduledAction>,
+ error: Option<String>,
+}
+
+impl ScheduledActionReadService for FakeReader {
+ async fn list_owned(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>, Report> {
+ self.calls.lock().unwrap().push(user_id);
+ if let Some(message) = &self.error {
+ return Err(rootcause::report!("{message}"));
+ }
+ Ok(self.actions.clone())
+ }
+}
+
+struct QueryRoot {
+ user_id: MacroUserIdStr<'static>,
+}
+
+struct Viewer(MacroUserIdStr<'static>);
+
+#[Object]
+impl QueryRoot {
+ async fn user(&self) -> Viewer {
+ Viewer(self.user_id.clone())
+ }
+}
+
+#[Object]
+impl Viewer {
+ async fn id(&self) -> async_graphql::ID {
+ async_graphql::ID(self.0.to_string())
+ }
+
+ async fn scheduled_actions(
+ &self,
+ ctx: &Context<'_>,
+ ) -> async_graphql::Result<Vec<crate::GraphqlScheduledAction>> {
+ resolve_scheduled_actions(ctx, self.0.clone()).await
+ }
+}
+
+fn viewer() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(VIEWER.to_owned()).unwrap()
+}
+
+fn utc(value: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(value)
+ .unwrap()
+ .with_timezone(&Utc)
+}
+
+fn uuid(value: &str) -> Uuid {
+ Uuid::parse_str(value).unwrap()
+}
+
+fn routine(
+ id: Option<&str>,
+ name: &str,
+ enabled: bool,
+ trigger: ActionTrigger,
+ task: Value,
+ claimed: Option<DateTime<Utc>>,
+ next_run_at: Option<DateTime<Utc>>,
+ created_at: &str,
+ updated_at: &str,
+) -> ScheduledAction {
+ let event_activated_at =
+ matches!(&trigger, ActionTrigger::Events { .. }).then(|| utc("2026-01-15T00:00:00Z"));
+ ScheduledAction {
+ id: id.map(uuid),
+ owner: Owner::User(viewer()),
+ name: name.to_owned(),
+ trigger,
+ kind: ActionKind::Agent,
+ created_at: utc(created_at),
+ updated_at: utc(updated_at),
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at,
+ task,
+ claimed,
+ next_run_at,
+ enabled,
+ }
+}
+
+fn cron(schedule: &str, timezone: &str) -> ActionTrigger {
+ serde_json::from_value(json!({
+ "type": "cron",
+ "schedule": schedule,
+ "timezone": timezone
+ }))
+ .unwrap()
+}
+
+fn schema(reader: Arc<FakeReader>) -> Schema<QueryRoot, EmptyMutation, EmptySubscription> {
+ Schema::build(
+ QueryRoot { user_id: viewer() },
+ EmptyMutation,
+ EmptySubscription,
+ )
+ .data(ScheduledActionGraphqlContext::new(reader))
+ .finish()
+}
+
+#[tokio::test]
+async fn lists_cron_and_event_routines_for_the_authenticated_user() {
+ let sample = utc("2026-02-01T00:00:00Z");
+ assert_eq!(sample.to_rfc3339(), "2026-02-01T00:00:00+00:00");
+ let claimed = utc("2020-01-01T00:00:00Z");
+ let entity_id = "11111111-1111-4111-8111-111111111111";
+ let agent_id = "22222222-2222-4222-8222-222222222222";
+ let filters = EventFilters::try_from(vec![
+ EventFilter::new(vec![EventName::DocumentCreated], None).unwrap(),
+ EventFilter::new(vec![EventName::DocumentUpdated], Some(vec![])).unwrap(),
+ EventFilter::new(vec![EventName::ChannelCreated], Some(vec![uuid(entity_id)])).unwrap(),
+ ])
+ .unwrap();
+ let reader = Arc::new(FakeReader {
+ calls: Mutex::new(Vec::new()),
+ error: None,
+ actions: vec![
+ routine(
+ Some("00000000-0000-4000-8000-000000000001"),
+ "Morning",
+ true,
+ cron("0 0 9 * * *", "UTC"),
+ json!({
+ "model": "good",
+ "prompt": "summarize the inbox",
+ "user_prompt": "please summarize"
+ }),
+ Some(claimed),
+ Some(utc("2026-04-01T09:00:00Z")),
+ "2026-02-01T00:00:00Z",
+ "2026-02-02T00:00:00Z",
+ ),
+ routine(
+ Some("00000000-0000-4000-8000-000000000002"),
+ "On create",
+ true,
+ ActionTrigger::Events { filters },
+ json!({"prompt": "only-a-prompt"}),
+ None,
+ None,
+ "2026-02-03T00:00:00Z",
+ "2026-02-04T00:00:00Z",
+ ),
+ routine(
+ Some("00000000-0000-4000-8000-000000000003"),
+ "Paused",
+ false,
+ cron("0 0 10 * * *", "UTC"),
+ json!({
+ "agent": {"bot_id": agent_id},
+ "prompt": "paused prompt",
+ "user_prompt": "paused user"
+ }),
+ None,
+ Some(utc("2026-05-01T10:00:00Z")),
+ "2026-02-05T00:00:00Z",
+ "2026-02-06T00:00:00Z",
+ ),
+ ],
+ });
+ let schema = schema(Arc::clone(&reader));
+
+ let id_only = schema.execute("{ user { id } }").await;
+ assert!(id_only.errors.is_empty(), "{:?}", id_only.errors);
+ assert_eq!(id_only.data.into_json().unwrap()["user"]["id"], VIEWER);
+ assert!(reader.calls.lock().unwrap().is_empty());
+
+ let response = schema.execute(QUERY).await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data.into_json().unwrap(),
+ json!({
+ "user": {
+ "scheduledActions": [
+ {
+ "id": "00000000-0000-4000-8000-000000000001",
+ "name": "Morning",
+ "enabled": true,
+ "trigger": {
+ "__typename": "GraphqlScheduledActionCronTrigger",
+ "schedule": "0 0 9 * * *",
+ "timezone": "UTC",
+ "nextRunAt": "2026-04-01T09:00:00+00:00"
+ },
+ "agentTask": {
+ "model": "good",
+ "agent": null,
+ "prompt": "summarize the inbox",
+ "userPrompt": "please summarize"
+ },
+ "claimExpiresAt": "2020-01-01T00:20:00+00:00",
+ "createdAt": "2026-02-01T00:00:00+00:00",
+ "updatedAt": "2026-02-02T00:00:00+00:00"
+ },
+ {
+ "id": "00000000-0000-4000-8000-000000000002",
+ "name": "On create",
+ "enabled": true,
+ "trigger": {
+ "__typename": "GraphqlScheduledActionEventsTrigger",
+ "filters": [
+ {"events": ["DOCUMENT_CREATED"], "entityIds": null},
+ {"events": ["DOCUMENT_UPDATED"], "entityIds": []},
+ {"events": ["CHANNEL_CREATED"], "entityIds": [entity_id]}
+ ]
+ },
+ "agentTask": null,
+ "claimExpiresAt": null,
+ "createdAt": "2026-02-03T00:00:00+00:00",
+ "updatedAt": "2026-02-04T00:00:00+00:00"
+ },
+ {
+ "id": "00000000-0000-4000-8000-000000000003",
+ "name": "Paused",
+ "enabled": false,
+ "trigger": {
+ "__typename": "GraphqlScheduledActionCronTrigger",
+ "schedule": "0 0 10 * * *",
+ "timezone": "UTC",
+ "nextRunAt": null
+ },
+ "agentTask": {
+ "model": null,
+ "agent": {"botId": agent_id},
+ "prompt": "paused prompt",
+ "userPrompt": "paused user"
+ },
+ "claimExpiresAt": null,
+ "createdAt": "2026-02-05T00:00:00+00:00",
+ "updatedAt": "2026-02-06T00:00:00+00:00"
+ }
+ ]
+ }
+ })
+ );
+ let calls = reader.calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].as_ref(), VIEWER);
+}
+
+#[tokio::test]
+async fn read_failures_are_redacted() {
+ let reader = Arc::new(FakeReader {
+ calls: Mutex::new(Vec::new()),
+ actions: Vec::new(),
+ error: Some(format!("database read failed: {SECRET}")),
+ });
+ let response = schema(Arc::clone(&reader)).execute(QUERY).await;
+ assert_redacted(response);
+ assert_eq!(reader.calls.lock().unwrap()[0].as_ref(), VIEWER);
+}
+
+#[tokio::test]
+async fn a_listed_action_without_an_id_is_a_redacted_internal_error() {
+ let reader = Arc::new(FakeReader {
+ calls: Mutex::new(Vec::new()),
+ error: None,
+ actions: vec![routine(
+ None,
+ "Broken",
+ true,
+ cron("0 0 9 * * *", "UTC"),
+ json!({"model": "m", "prompt": SECRET, "user_prompt": "u"}),
+ None,
+ None,
+ "2026-02-01T00:00:00Z",
+ "2026-02-01T00:00:00Z",
+ )],
+ });
+ let response = schema(reader).execute(QUERY).await;
+ assert_redacted(response);
+}
+
+fn assert_redacted(response: async_graphql::Response) {
+ assert_eq!(response.errors.len(), 1, "{:?}", response.errors);
+ assert_eq!(
+ response.errors[0].message,
+ "scheduled actions are unavailable"
+ );
+ assert!(!format!("{response:?}").contains(SECRET));
+ assert_eq!(
+ response.errors[0].extensions.as_ref().unwrap().get("code"),
+ Some(&async_graphql::Value::from("INTERNAL_SERVER_ERROR"))
+ );
+ assert_eq!(response.data.into_json().unwrap(), json!({ "user": null }));
+}
diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml
index b80c55d838..2cc04deace 100644
--- a/crates/workspace-hack/Cargo.toml
+++ b/crates/workspace-hack/Cargo.toml
@@ -19,6 +19,7 @@ aes-gcm = { version = "0.10", features = ["zeroize"] }
ahash = { version = "0.8" }
aho-corasick = { version = "1" }
anyhow = { version = "1" }
+async-graphql = { version = "7", features = ["dataloader"] }
async-openai = { version = "0.36", features = ["audio", "byot", "chat-completion", "completions", "embedding"] }
aws-config = { version = "1", features = ["behavior-version-latest"] }
aws-credential-types = { version = "1", default-features = false, features = ["hardcoded-credentials", "test-util"] }
@@ -162,6 +163,7 @@ aes-gcm = { version = "0.10", features = ["zeroize"] }
ahash = { version = "0.8" }
aho-corasick = { version = "1" }
anyhow = { version = "1" }
+async-graphql = { version = "7", features = ["dataloader"] }
async-openai = { version = "0.36", features = ["audio", "byot", "chat-completion", "completions", "embedding"] }
aws-config = { version = "1", features = ["behavior-version-latest"] }
aws-credential-types = { version = "1", default-features = false, features = ["hardcoded-credentials", "test-util"] }
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index 547d5c1aa9..baf40a00a6 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -123,6 +123,7 @@ github = { path = "../../crates/github", default-features = false, features = [
] }
graphql_soup = { path = "../../crates/graphql_soup" }
graphql_initiative = { path = "../../crates/graphql_initiative" }
+graphql_scheduled_action = { path = "../../crates/graphql_scheduled_action" }
harnesses = { path = "../../crates/harnesses" }
hex = { workspace = true }
http-body-util = { workspace = true }
@@ -196,6 +197,7 @@ reqwest = { workspace = true }
rootcause = { workspace = true }
s3_key = { path = "../../crates/s3_key" }
saved_views = { path = "../../crates/saved_views" }
+scheduled_action = { path = "../scheduled_action" }
schemars = { workspace = true }
search_service = { path = "../../crates/search_service" }
secretsmanager_client = { path = "../../crates/secretsmanager_client" }
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 5e5eef970b..3a4e8be3e4 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -600,6 +600,7 @@ pub(crate) struct ApiContext {
pub reminders_state: DssRemindersState,
pub initiative_state: DssInitiativeState,
pub graphql_initiative_context: graphql_initiative::InitiativeGraphqlContext,
+ pub graphql_scheduled_action_context: graphql_scheduled_action::ScheduledActionGraphqlContext,
pub graphql_initiative_entity_loader: graphql_initiative::InitiativeEntityLoader,
pub collab_surface_state: DssCollabSurfaceState,
pub foreign_entity_state: DssForeignEntityState,
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index e16aed5107..6688a1f3c4 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -166,6 +166,7 @@ fn insert_graphql_context_data(
data.insert(state.favorites_service.clone());
data.insert(state.channel_service.clone());
data.insert(state.graphql_initiative_context.clone());
+ data.insert(state.graphql_scheduled_action_context.clone());
data.insert(state.graphql_initiative_entity_loader.clone());
data.insert(graphql_initiative::initiative_detail_loader(
state.graphql_initiative_context.clone(),
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 20e6c4dafc..790d7df8e2 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -93,6 +93,7 @@ use github::domain::service::{GithubSyncConfig, GithubSyncServiceImpl};
use github::outbound::connection_gateway_realtime::ConnectionGatewayGithubRealtime;
use github::outbound::github_sync_client::GithubSyncClientImpl;
use github::outbound::pg_github_sync_repo::PgGithubSyncRepo;
+use graphql_scheduled_action::ScheduledActionGraphqlContext;
use harnesses::outbound::pg_harness_repo::PgHarnessRepo;
use initiative::{
domain::service::InitiativeServiceImpl, inbound::axum_router::InitiativeRouterState,
@@ -140,6 +141,8 @@ use reminders::{
sqs_dispatch_queue::SqsDispatchQueue,
},
};
+use scheduled_action::domain::read_service::ScheduledActionReadServiceImpl;
+use scheduled_action::outbound::pg_scheduled_action_repo::PgScheduledActionRepo;
use secretsmanager_client::SecretManager;
use soup::{
domain::service::SoupImpl, inbound::axum_router::SoupRouterState,
@@ -1586,6 +1589,13 @@ async fn run() -> anyhow::Result<()> {
)),
));
+ // Routine writes still use the scheduled-action service. Read from the
+ // primary pool here so the GraphQL list cannot restore stale state after
+ // a REST write.
+ let scheduled_action_read_service = Arc::new(ScheduledActionReadServiceImpl::new(Arc::new(
+ PgScheduledActionRepo::new(db.clone()),
+ )));
+
let api_context = ApiContext {
dictation_state,
contacts_ingress: contacts_ingress.clone(),
@@ -1628,6 +1638,9 @@ async fn run() -> anyhow::Result<()> {
initiative_service.clone(),
entity_access_service.clone(),
),
+ graphql_scheduled_action_context: ScheduledActionGraphqlContext::new(
+ scheduled_action_read_service,
+ ),
initiative_state: InitiativeRouterState::new(
initiative_service,
entity_access_service.clone(),
diff --git a/services/scheduled_action/src/domain.rs b/services/scheduled_action/src/domain.rs
index 911dfcf5d3..9c2304ba27 100644
--- a/services/scheduled_action/src/domain.rs
+++ b/services/scheduled_action/src/domain.rs
@@ -3,6 +3,7 @@ pub mod event_trigger;
pub mod execution;
pub mod models;
pub mod ports;
+pub mod read_service;
pub mod service;
pub mod target_runner;
pub mod target_validation;
diff --git a/services/scheduled_action/src/domain/models.rs b/services/scheduled_action/src/domain/models.rs
index 050698650a..5635e5b7d7 100644
--- a/services/scheduled_action/src/domain/models.rs
+++ b/services/scheduled_action/src/domain/models.rs
@@ -290,6 +290,10 @@ impl ScheduledAction {
owner_type: self.owner.owner_type(),
})
}
+
+ pub fn claim_expires_at(&self) -> Option<DateTime<Utc>> {
+ self.claimed.map(|claimed| claimed + MAX_ACTION_TIME)
+ }
}
/// Transcript resource created by a run. Never infer this from current task configuration.
diff --git a/services/scheduled_action/src/domain/models/test.rs b/services/scheduled_action/src/domain/models/test.rs
index 79c0294542..5d340d991f 100644
--- a/services/scheduled_action/src/domain/models/test.rs
+++ b/services/scheduled_action/src/domain/models/test.rs
@@ -1,11 +1,12 @@
-use chrono::Utc;
+use chrono::{DateTime, Utc};
use macro_uuid::{Uuid, generate_uuid_v7};
use model_owner::{Owner, OwnerType};
use serde_json::json;
use super::{
- ActionConfiguration, ActionKind, AgentTask, CreateScheduledAction, ResolvedTaskTarget,
- RoutineModelId, Schedule, ScheduledAction, TaskTargetError, UpdateScheduledAction,
+ ActionConfiguration, ActionKind, AgentTask, CreateScheduledAction, MAX_ACTION_TIME,
+ ResolvedTaskTarget, RoutineModelId, Schedule, ScheduledAction, TaskTargetError,
+ UpdateScheduledAction,
};
use crate::domain::event_runs::ConfigurationRevision;
use crate::domain::event_trigger::ActionTrigger;
@@ -286,3 +287,16 @@ fn event_action_round_trips_without_cron_fields() {
ConfigurationRevision::INITIAL
);
}
+
+#[test]
+fn claim_expires_at_is_claimed_plus_the_maximum_run_time() {
+ let mut action =
+ action_owned_by(Owner::from_principal_str(USER_PRINCIPAL).expect("user principal"));
+ assert_eq!(action.claim_expires_at(), None);
+
+ let claimed = DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
+ .expect("timestamp")
+ .with_timezone(&Utc);
+ action.claimed = Some(claimed);
+ assert_eq!(action.claim_expires_at(), Some(claimed + MAX_ACTION_TIME));
+}
diff --git a/services/scheduled_action/src/domain/ports.rs b/services/scheduled_action/src/domain/ports.rs
index 9414534a49..9949379185 100644
--- a/services/scheduled_action/src/domain/ports.rs
+++ b/services/scheduled_action/src/domain/ports.rs
@@ -9,6 +9,7 @@ use anyhow::Result;
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use rootcause::Report;
use tokio::sync::mpsc::{Receiver, Sender};
/// Validate configuration syntax and authorize its target before persistence.
@@ -96,6 +97,18 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<()>> + Send;
}
+/// Lists one user's routines for read-only clients.
+///
+/// The list includes cron and event triggers, keeps only actions whose owner
+/// is that user, and orders them by `(created_at, id)`.
+pub trait ScheduledActionReadService: Send + Sync + 'static {
+ /// Routines owned by `user_id` in stable `(created_at, id)` order.
+ fn list_owned(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = std::result::Result<Vec<ScheduledAction>, Report>> + Send;
+}
+
pub trait ScheduledActionService: Send + Sync + 'static {
/// Delete all of a user's actions before account deletion, including disabled
/// and claimed actions. Repeating a completed cleanup succeeds.
diff --git a/services/scheduled_action/src/domain/read_service.rs b/services/scheduled_action/src/domain/read_service.rs
new file mode 100644
index 0000000000..0dfb7870f5
--- /dev/null
+++ b/services/scheduled_action/src/domain/read_service.rs
@@ -0,0 +1,29 @@
+use std::sync::Arc;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+
+use super::models::ScheduledAction;
+use super::ports::{ScheduledActionReadService, ScheduledActionRepo};
+use super::service::list_owned_actions;
+
+pub struct ScheduledActionReadServiceImpl<R> {
+ repo: Arc<R>,
+}
+
+impl<R> ScheduledActionReadServiceImpl<R> {
+ pub fn new(repo: Arc<R>) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R: ScheduledActionRepo> ScheduledActionReadService for ScheduledActionReadServiceImpl<R> {
+ async fn list_owned(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> Result<Vec<ScheduledAction>, Report> {
+ list_owned_actions(self.repo.as_ref(), &user_id)
+ .await
+ .map_err(|error| rootcause::report!(error).into_dynamic())
+ }
+}
diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rs
index d56cb4ec57..94f67b6b68 100644
--- a/services/scheduled_action/src/domain/service.rs
+++ b/services/scheduled_action/src/domain/service.rs
@@ -11,7 +11,7 @@ use super::event_runs::ConfigurationRevision;
use super::event_trigger::ActionTrigger;
use super::models::{
ActionConfiguration, ActionExecutionRecord, ActionPolicyError, CreateScheduledAction,
- DispatchEvent, InProgressExecution, MAX_ACTION_TIME, ScheduledAction, UpdateScheduledAction,
+ DispatchEvent, InProgressExecution, ScheduledAction, UpdateScheduledAction,
};
use super::ports::{
ScheduledActionExecutor, ScheduledActionRepo, ScheduledActionService, TaskTargetValidator,
@@ -102,11 +102,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Targets> ScheduledActionServiceImpl<Rpo, Exe
self.check_event_management(&input.trigger)?;
}
let now = Utc::now();
- if action
- .claimed
- .is_some_and(|claimed| claimed >= now - MAX_ACTION_TIME)
- && !disable_only
- {
+ if claim_blocks_replacement(&action, now) && !disable_only {
return Err(ActionPolicyError::UpdateConflict.into());
}
if !disable_only {
@@ -151,6 +147,30 @@ fn next_run(trigger: &ActionTrigger) -> Result<Option<DateTime<Utc>>> {
}
}
+pub(crate) async fn list_owned_actions<R: ScheduledActionRepo>(
+ repo: &R,
+ user_id: &MacroUserIdStr<'static>,
+) -> Result<Vec<ScheduledAction>> {
+ let mut actions = repo
+ .get_actions(user_id.clone())
+ .await?
+ .into_iter()
+ .filter(|action| action.owner.is_user(user_id))
+ .collect::<Vec<_>>();
+ actions.sort_by(|left, right| {
+ left.created_at
+ .cmp(&right.created_at)
+ .then(left.id.cmp(&right.id))
+ });
+ Ok(actions)
+}
+
+fn claim_blocks_replacement(action: &ScheduledAction, now: DateTime<Utc>) -> bool {
+ action
+ .claim_expires_at()
+ .is_some_and(|expires_at| now <= expires_at)
+}
+
fn same_trigger(left: &ActionTrigger, right: &ActionTrigger) -> bool {
match (left, right) {
(
@@ -237,12 +257,9 @@ where
user_id: MacroUserIdStr<'static>,
include_events: bool,
) -> Result<Vec<ScheduledAction>> {
- Ok(self
- .repo
- .get_actions(user_id.clone())
+ Ok(list_owned_actions(self.repo.as_ref(), &user_id)
.await?
.into_iter()
- .filter(|action| action.owner.is_user(&user_id))
.filter(|action| include_events || matches!(action.trigger, ActionTrigger::Cron { .. }))
.collect())
}
diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rs
index a98acb461c..44d597e211 100644
--- a/services/scheduled_action/src/domain/service/test.rs
+++ b/services/scheduled_action/src/domain/service/test.rs
@@ -4,11 +4,13 @@ use super::*;
use crate::domain::event_runs::ClaimToken;
use crate::domain::models::{
ActionConfigurationUpdate, ActionKind, ExecutionResource, ExecutionResourceType,
+ MAX_ACTION_TIME,
};
use crate::domain::{
event_trigger::EventReference,
execution::ExecutionHandle,
- ports::ScheduledAgentRunner,
+ ports::{ScheduledActionReadService, ScheduledAgentRunner},
+ read_service::ScheduledActionReadServiceImpl,
target_runner::TargetRunner,
target_validation::{
TargetValidation, TargetValidationError,
@@ -687,6 +689,94 @@ async fn active_execution_blocks_replacement_but_allows_disabling_even_with_gate
assert_eq!(disabled.event_activated_at, action.event_activated_at);
}
+#[test]
+fn claim_expiry_instant_still_blocks_replacement() {
+ let config = configuration(false);
+ let claimed = DateTime::parse_from_rfc3339("2026-01-01T00:00:00Z")
+ .expect("timestamp")
+ .with_timezone(&Utc);
+ let mut action = ScheduledAction {
+ id: Some(Uuid::from_u128(1)),
+ owner: Owner::User(user()),
+ name: config.name,
+ trigger: config.trigger,
+ kind: config.kind,
+ created_at: claimed,
+ updated_at: claimed,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at: None,
+ task: config.task,
+ claimed: Some(claimed),
+ next_run_at: None,
+ enabled: true,
+ };
+ let expires_at = action
+ .claim_expires_at()
+ .expect("claimed action has an expiry");
+ assert_eq!(expires_at, claimed + MAX_ACTION_TIME);
+ assert!(super::claim_blocks_replacement(
+ &action,
+ expires_at - chrono::Duration::nanoseconds(1)
+ ));
+ assert!(super::claim_blocks_replacement(&action, expires_at));
+ assert!(!super::claim_blocks_replacement(
+ &action,
+ expires_at + chrono::Duration::nanoseconds(1)
+ ));
+ action.claimed = None;
+ assert_eq!(action.claim_expires_at(), None);
+ assert!(!super::claim_blocks_replacement(&action, expires_at));
+}
+
+#[tokio::test]
+async fn expired_claim_allows_configuration_replacement() {
+ let svc = service(true);
+ let mut config = configuration(false);
+ let action = svc
+ .create_action(CreateScheduledAction::Canonical(config.clone()), user())
+ .await
+ .unwrap();
+ let id = action.id.unwrap();
+ svc.repo.actions.lock().unwrap()[0].claimed =
+ Some(Utc::now() - MAX_ACTION_TIME - chrono::Duration::seconds(1));
+ config.name = "renamed".into();
+ let updated = svc
+ .update_action(&id, update(config), user())
+ .await
+ .unwrap();
+ assert_eq!(updated.name, "renamed");
+ assert!(updated.claimed.is_some());
+}
+
+fn at(seconds: i64) -> DateTime<Utc> {
+ DateTime::UNIX_EPOCH + chrono::Duration::seconds(seconds)
+}
+
+fn seeded(
+ id: u128,
+ owner: Owner,
+ created_at: DateTime<Utc>,
+ events: bool,
+ name: &str,
+) -> ScheduledAction {
+ let config = configuration(events);
+ ScheduledAction {
+ id: Some(Uuid::from_u128(id)),
+ owner,
+ name: name.to_owned(),
+ trigger: config.trigger,
+ kind: config.kind,
+ created_at,
+ updated_at: created_at,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at: None,
+ task: config.task,
+ claimed: None,
+ next_run_at: None,
+ enabled: true,
+ }
+}
+
#[tokio::test]
async fn activation_changes_are_idempotent_and_keep_configuration() {
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
@@ -741,6 +831,77 @@ async fn activation_changes_are_idempotent_and_keep_configuration() {
}
}
+#[tokio::test]
+async fn read_service_keeps_both_triggers_for_the_owner_in_stable_order() {
+ let early = at(10);
+ let later = at(20);
+ let repo = Arc::new(FakeRepo::default());
+ *repo.actions.lock().unwrap() = vec![
+ seeded(9, Owner::User(user()), later, true, "event"),
+ seeded(
+ 1,
+ Owner::from_principal_str(FOREIGN_USER).unwrap(),
+ early,
+ false,
+ "foreign",
+ ),
+ seeded(4, Owner::User(user()), later, false, "first-equal"),
+ seeded(9, Owner::User(user()), early, false, "early-cron"),
+ seeded(
+ 2,
+ Owner::from_principal_str(&format!("bot|{}", Uuid::from_u128(50))).unwrap(),
+ early,
+ false,
+ "bot",
+ ),
+ seeded(
+ 8,
+ Owner::from_principal_str(&Uuid::from_u128(77).hyphenated().to_string()).unwrap(),
+ early,
+ false,
+ "team",
+ ),
+ seeded(4, Owner::User(user()), later, false, "second-equal"),
+ seeded(3, Owner::User(user()), later, false, "low-id"),
+ ];
+ let (tx, _rx) = tokio::sync::mpsc::channel(1);
+ let svc = TestService::new(repo.clone(), Arc::new(FakeExecutor::default()), tx);
+ let reader = ScheduledActionReadServiceImpl::new(repo);
+
+ let expected = vec![
+ "early-cron",
+ "low-id",
+ "first-equal",
+ "second-equal",
+ "event",
+ ];
+ let read = reader.list_owned(user()).await.unwrap();
+ let names = |actions: &[ScheduledAction]| {
+ actions
+ .iter()
+ .map(|action| action.name.clone())
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(names(&read), expected);
+ assert!(read.iter().all(|action| action.owner.is_user(&user())));
+ assert!(
+ read.iter()
+ .any(|action| matches!(action.trigger, ActionTrigger::Cron { .. }))
+ );
+ assert!(
+ read.iter()
+ .any(|action| matches!(action.trigger, ActionTrigger::Events { .. }))
+ );
+ assert_eq!(
+ names(&svc.get_actions(user(), true).await.unwrap()),
+ expected
+ );
+ assert_eq!(
+ names(&svc.get_actions(user(), false).await.unwrap()),
+ vec!["early-cron", "low-id", "first-equal", "second-equal"]
+ );
+}
+
#[tokio::test]
async fn gate_off_allows_pausing_an_event_action_but_not_resuming_it() {
let enabled = service(true);
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 1e368e6f84..880f612f15 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -4294,6 +4294,158 @@ type GraphqlRepliedToDocumentCommentThreadMetadata {
senderDisplayName: String
}
+"""
+An AI routine owned by the authenticated user.
+"""
+type GraphqlScheduledAction {
+ """
+ Stable identifier of the routine.
+ """
+ id: ID!
+ """
+ Name shown for the routine.
+ """
+ name: String!
+ """
+ Whether automatic dispatch runs this routine.
+ """
+ enabled: Boolean!
+ """
+ What starts a run of this routine.
+ """
+ trigger: GraphqlScheduledActionTrigger!
+ """
+ Agent task for this routine. Null when the stored task is not an agent task.
+ """
+ agentTask: GraphqlScheduledActionAgentTask
+ """
+ When the current execution claim stops blocking configuration changes.
+ The timestamp stays present after that instant so clients can compare it themselves.
+ """
+ claimExpiresAt: String
+ """
+ When the routine was created, as RFC 3339.
+ """
+ createdAt: String!
+ """
+ When the routine row last changed, including execution bookkeeping, as RFC 3339.
+ """
+ updatedAt: String!
+}
+
+"""
+An agent selected to run a routine.
+"""
+type GraphqlScheduledActionAgent {
+ """
+ Stable identifier of the selected agent.
+ """
+ botId: ID!
+}
+
+"""
+The agent task a routine runs.
+"""
+type GraphqlScheduledActionAgentTask {
+ """
+ Model the task runs. Null when the selected agent uses its default model.
+ """
+ model: String
+ """
+ Selected agent. Null for model-only tasks.
+ """
+ agent: GraphqlScheduledActionAgent
+ """
+ System prompt for the agent.
+ """
+ prompt: String!
+ """
+ User prompt for the agent.
+ """
+ userPrompt: String!
+}
+
+"""
+A routine that runs on a cron schedule.
+"""
+type GraphqlScheduledActionCronTrigger {
+ """
+ Cron expression in the six- or seven-field format the scheduler accepts.
+ """
+ schedule: String!
+ """
+ Time zone name the cron expression is evaluated in.
+ """
+ timezone: String!
+ """
+ Next cron firing, as RFC 3339. Null when the routine is disabled.
+ """
+ nextRunAt: String
+}
+
+"""
+One event filter. The event name and entity id must both match.
+"""
+type GraphqlScheduledActionEventFilter {
+ """
+ Event names that can satisfy this filter.
+ """
+ events: [GraphqlScheduledActionEventName!]!
+ """
+ Entity ids that can satisfy this filter. Null matches every id; an empty list matches nothing.
+ """
+ entityIds: [ID!]
+}
+
+"""
+Events a routine filter can name.
+"""
+enum GraphqlScheduledActionEventName {
+ """
+ A document was created.
+ """
+ DOCUMENT_CREATED
+ """
+ A document was updated.
+ """
+ DOCUMENT_UPDATED
+ """
+ A channel was created.
+ """
+ CHANNEL_CREATED
+ """
+ A channel message was posted.
+ """
+ CHANNEL_MESSAGE_POSTED
+ """
+ A user was mentioned in a channel.
+ """
+ CHANNEL_MENTIONED
+ """
+ A channel message was patched.
+ """
+ CHANNEL_MESSAGE_PATCHED
+ """
+ A channel message attachment was created.
+ """
+ CHANNEL_MESSAGE_ATTACHMENT_CREATED
+}
+
+"""
+A routine that runs when matching events are published.
+"""
+type GraphqlScheduledActionEventsTrigger {
+ """
+ Event filters. A run starts when any filter matches.
+ """
+ filters: [GraphqlScheduledActionEventFilter!]!
+}
+
+"""
+The way a routine starts.
+"""
+union GraphqlScheduledActionTrigger = GraphqlScheduledActionCronTrigger | GraphqlScheduledActionEventsTrigger
+
"""
A select-option property value.
"""
@@ -6529,6 +6681,10 @@ type GraphqlUser {
"""
taskInitiativeReferences(taskIds: [ID!]!): [TaskInitiativeReference!]!
"""
+ AI routines owned by the authenticated user.
+ """
+ scheduledActions: [GraphqlScheduledAction!]!
+ """
Authorized property definitions available to this viewer.
"""
propertyDefinitions(scope: GraphqlPropertyDefinitionScope!, forEntityType: GraphqlPropertyEntityType): [GraphqlPropertyDefinition!]!