返回 CodeWhale
send_later.rs
根目录 / crates / engine / src / tools / send_later.rs
1 //! Model-callable one-shot delayed continuation tool (`send_later`).
2 //!
3 //! Lets the agent schedule a future message into the current workspace. When
4 //! the trigger fires the scheduler enqueues a normal durable task with the
5 //! specified message, just like an automation run.
6 //!
7 //! # Actions
8 //!
9 //! | action | description |
10 //! |------------|-----------------------------------------------------------|
11 //! | `schedule` | Create a pending trigger; returns `trigger_id`+`fire_at` |
12 //! | `list` | List recent triggers (default: 50 newest) |
13 //! | `read` | Read a single trigger by `trigger_id` |
14 //! | `cancel` | Cancel a pending trigger before it fires |
15
16 use std::path::PathBuf;
17
18 use async_trait::async_trait;
19 use chrono::{DateTime, Duration, Utc};
20 use serde_json::{Value, json};
21
22 use crate::automation_manager::{
23 CreateDelayedTriggerRequest, DelayedTriggerStatus, SharedAutomationManager,
24 };
25 use crate::tools::spec::{
26 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
27 optional_str, optional_u64,
28 };
29
30 const ALL_ACTIONS: &[&str] = &["schedule", "list", "read", "cancel"];
31 const READ_ACTIONS: &[&str] = &["list", "read"];
32
33 /// One-shot delayed-continuation tool.
34 pub struct SendLaterTool {
35 name: &'static str,
36 read_only: bool,
37 }
38
39 impl SendLaterTool {
40 pub const fn new(name: &'static str) -> Self {
41 Self {
42 name,
43 read_only: false,
44 }
45 }
46
47 /// Plan-mode variant: only the read-only actions are advertised.
48 pub const fn read_only(name: &'static str) -> Self {
49 Self {
50 name,
51 read_only: true,
52 }
53 }
54
55 fn allowed_actions(&self) -> &'static [&'static str] {
56 if self.read_only {
57 READ_ACTIONS
58 } else {
59 ALL_ACTIONS
60 }
61 }
62
63 fn resolve_action<'a>(&self, input: &'a Value) -> Result<&'a str, ToolError> {
64 let action = input.get("action").and_then(Value::as_str).ok_or_else(|| {
65 ToolError::invalid_input(format!(
66 "send_later: missing `action` (one of: {})",
67 self.allowed_actions().join(", ")
68 ))
69 })?;
70 if self.allowed_actions().contains(&action) {
71 Ok(action)
72 } else {
73 Err(ToolError::invalid_input(format!(
74 "send_later: invalid action `{action}` (one of: {})",
75 self.allowed_actions().join(", ")
76 )))
77 }
78 }
79
80 fn automations_from_context(
81 context: &ToolContext,
82 ) -> Result<SharedAutomationManager, ToolError> {
83 context
84 .runtime
85 .automations
86 .as_ref()
87 .cloned()
88 .ok_or_else(|| ToolError::not_available("send_later: automation manager not available"))
89 }
90 }
91
92 #[async_trait]
93 impl ToolSpec for SendLaterTool {
94 fn name(&self) -> &'static str {
95 self.name
96 }
97
98 fn description(&self) -> &'static str {
99 if self.read_only {
100 "Inspect pending one-shot delayed continuations. Actions: \"list\" (newest triggers), \"read\" (one trigger by trigger_id)."
101 } else {
102 "Schedule a one-shot delayed message. By default it arrives as a new turn in this thread. \
103 Actions: \"schedule\" (create a pending trigger; requires approval), \
104 \"list\" (recent triggers), \"read\" (one trigger by trigger_id), \
105 \"cancel\" (cancel a pending trigger before it fires; requires approval). \
106 Specify exactly one of delay_seconds, delay_minutes, or fire_at (ISO 8601 UTC). \
107 Returns trigger_id and resolved fire_at."
108 }
109 }
110
111 fn input_schema(&self) -> Value {
112 let actions: Vec<&str> = self.allowed_actions().to_vec();
113 let mut properties = serde_json::Map::new();
114 properties.insert(
115 "action".to_string(),
116 json!({
117 "type": "string",
118 "enum": actions,
119 "description": "Action to perform."
120 }),
121 );
122 if !self.read_only {
123 properties.insert(
124 "delay_seconds".to_string(),
125 json!({
126 "type": "integer",
127 "minimum": 1,
128 "description": "Seconds from now to fire (minimum 1). Mutually exclusive with delay_minutes and fire_at. (action=schedule)"
129 }),
130 );
131 properties.insert(
132 "delay_minutes".to_string(),
133 json!({
134 "type": "integer",
135 "minimum": 1,
136 "description": "Minutes from now to fire. Mutually exclusive with delay_seconds and fire_at. (action=schedule)"
137 }),
138 );
139 properties.insert(
140 "fire_at".to_string(),
141 json!({
142 "type": "string",
143 "description": "Absolute UTC fire time as an ISO 8601 string, e.g. \"2026-07-08T00:43:00Z\". Mutually exclusive with delay_seconds and delay_minutes. (action=schedule)"
144 }),
145 );
146 properties.insert(
147 "message".to_string(),
148 json!({
149 "type": "string",
150 "description": "The message to inject as a new task when the trigger fires. (action=schedule)"
151 }),
152 );
153 properties.insert(
154 "workspace".to_string(),
155 json!({
156 "type": "string",
157 "description": "Optional working directory for the fired task; defaults to the current workspace. (action=schedule)"
158 }),
159 );
160 properties.insert(
161 "thread_id".to_string(),
162 json!({
163 "type": "string",
164 "description": "Thread the message is delivered into as a new turn. Defaults to the calling thread, so the reminder comes back to this conversation; \"current\" names it explicitly and \"\" starts a new background task thread instead. (action=schedule)"
165 }),
166 );
167 properties.insert(
168 "parent_trigger_id".to_string(),
169 json!({
170 "type": "string",
171 "description": "Optional id of the trigger that re-armed this one, for lineage tracking. (action=schedule)"
172 }),
173 );
174 }
175 properties.insert(
176 "trigger_id".to_string(),
177 json!({
178 "type": "string",
179 "description": "Target trigger id. (action=read/cancel)"
180 }),
181 );
182 properties.insert(
183 "limit".to_string(),
184 json!({
185 "type": "integer",
186 "minimum": 1,
187 "maximum": 200,
188 "default": 50,
189 "description": "Maximum number of results to return. (action=list)"
190 }),
191 );
192 properties.insert(
193 "status".to_string(),
194 json!({
195 "type": "string",
196 "enum": ["pending", "dispatching", "fired", "canceled", "failed"],
197 "description": "Filter by trigger status. (action=list)"
198 }),
199 );
200 json!({
201 "type": "object",
202 "properties": properties,
203 "required": ["action"]
204 })
205 }
206
207 fn capabilities(&self) -> Vec<ToolCapability> {
208 if self.read_only {
209 vec![ToolCapability::ReadOnly]
210 } else {
211 vec![
212 ToolCapability::ExecutesCode,
213 ToolCapability::RequiresApproval,
214 ]
215 }
216 }
217
218 fn approval_requirement(&self) -> ApprovalRequirement {
219 if self.read_only {
220 ApprovalRequirement::Auto
221 } else {
222 ApprovalRequirement::Required
223 }
224 }
225
226 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
227 match input.get("action").and_then(Value::as_str) {
228 Some("list") | Some("read") => ApprovalRequirement::Auto,
229 _ if self.read_only => ApprovalRequirement::Auto,
230 _ => ApprovalRequirement::Required,
231 }
232 }
233
234 fn is_read_only_for(&self, input: &Value) -> bool {
235 match input.get("action").and_then(Value::as_str) {
236 Some("list") | Some("read") => true,
237 _ => self.read_only,
238 }
239 }
240
241 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
242 let action = self.resolve_action(&input)?;
243
244 match action {
245 "schedule" => execute_schedule(&input, context).await,
246 "list" => execute_list(&input, context).await,
247 "read" => execute_read(&input, context).await,
248 "cancel" => execute_cancel(&input, context).await,
249 _ => Err(ToolError::invalid_input(format!(
250 "send_later: unhandled action `{action}`"
251 ))),
252 }
253 }
254 }
255
256 // ── Action handlers ────────────────────────────────────────────────────────
257
258 fn optional_delay_arg(input: &Value, key: &str) -> Result<Option<i64>, ToolError> {
259 let Some(raw) = input.get(key) else {
260 return Ok(None);
261 };
262 if raw.is_null() {
263 return Ok(None);
264 }
265 let value = codewhale_tools::json_nonnegative_integer(raw).ok_or_else(|| {
266 ToolError::invalid_input(format!(
267 "send_later schedule: `{key}` must be a positive integer"
268 ))
269 })?;
270 if value == 0 {
271 return Err(ToolError::invalid_input(format!(
272 "send_later schedule: `{key}` must be >= 1"
273 )));
274 }
275 i64::try_from(value)
276 .map(Some)
277 .map_err(|_| ToolError::invalid_input(format!("send_later schedule: `{key}` is too large")))
278 }
279
280 fn checked_delay_fire_at(delta: Option<Duration>, key: &str) -> Result<DateTime<Utc>, ToolError> {
281 let delta = delta.ok_or_else(|| {
282 ToolError::invalid_input(format!("send_later schedule: `{key}` is too large"))
283 })?;
284 Utc::now().checked_add_signed(delta).ok_or_else(|| {
285 ToolError::invalid_input(format!("send_later schedule: `{key}` is too large"))
286 })
287 }
288
289 async fn execute_schedule(input: &Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
290 let automations = SendLaterTool::automations_from_context(context)?;
291
292 let delay_seconds = optional_delay_arg(input, "delay_seconds")?;
293 let delay_minutes = optional_delay_arg(input, "delay_minutes")?;
294 let fire_at_str = optional_str(input, "fire_at")?;
295 let message = input
296 .get("message")
297 .and_then(Value::as_str)
298 .ok_or_else(|| ToolError::invalid_input("send_later schedule: `message` is required"))?;
299
300 if message.trim().is_empty() {
301 return Err(ToolError::invalid_input(
302 "send_later schedule: `message` must not be empty",
303 ));
304 }
305
306 let fire_at: DateTime<Utc> = match (delay_seconds, delay_minutes, fire_at_str) {
307 (Some(seconds), None, None) => {
308 checked_delay_fire_at(Duration::try_seconds(seconds), "delay_seconds")?
309 }
310 (None, Some(minutes), None) => {
311 checked_delay_fire_at(Duration::try_minutes(minutes), "delay_minutes")?
312 }
313 (None, None, Some(fire_at_s)) => fire_at_s.parse::<DateTime<Utc>>().map_err(|err| {
314 ToolError::invalid_input(format!(
315 "send_later schedule: invalid `fire_at` — expected ISO 8601 UTC, e.g. \
316 \"2026-07-08T00:43:00Z\": {err}"
317 ))
318 })?,
319 (None, None, None) => {
320 return Err(ToolError::invalid_input(
321 "send_later schedule: exactly one of `delay_seconds`, `delay_minutes`, or `fire_at` is required",
322 ));
323 }
324 _ => {
325 return Err(ToolError::invalid_input(
326 "send_later schedule: `delay_seconds`, `delay_minutes`, and `fire_at` are mutually exclusive",
327 ));
328 }
329 };
330
331 let workspace: Option<PathBuf> = match optional_str(input, "workspace")? {
332 Some(raw) => Some(context.resolve_path(raw)?),
333 None => {
334 let ws = &context.workspace;
335 if ws == std::path::Path::new(".") {
336 None
337 } else {
338 Some(ws.clone())
339 }
340 }
341 };
342
343 let parent_trigger_id = optional_str(input, "parent_trigger_id")?.map(String::from);
344
345 let destination_thread_id = crate::tools::automation::destination_thread(
346 input,
347 context,
348 context.runtime.active_thread_id.clone(),
349 )?;
350
351 let req = CreateDelayedTriggerRequest {
352 destination_thread_id,
353 fire_at,
354 message: message.to_string(),
355 workspace,
356 owner_session_id: Some(context.state_namespace.clone()),
357 parent_trigger_id,
358 disallowed_tools: context.disallowed_tools.clone(),
359 };
360
361 let record = {
362 let manager = automations.lock().await;
363 // A pending trigger is fired only by the scope that owns it
364 // (`fire_due_triggers`), and a trigger has no paused state to fall
365 // back to, so an unbound host must refuse rather than store a delayed
366 // message that never arrives.
367 crate::tools::automation::require_dispatch_owner(&manager, "schedule a delayed message")?;
368 manager.create_trigger(req).map_err(|err| {
369 ToolError::execution_failed(format!("send_later schedule failed: {err}"))
370 })?
371 };
372
373 Ok(ToolResult::success(
374 serde_json::to_string_pretty(&json!({
375 "trigger_id": record.trigger_id,
376 "fire_at": record.fire_at.to_rfc3339(),
377 "status": "pending",
378 "thread_id": record.destination_thread_id,
379 }))
380 .unwrap_or_default(),
381 ))
382 }
383
384 async fn execute_list(input: &Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
385 let automations = SendLaterTool::automations_from_context(context)?;
386
387 let limit = Some(optional_u64(input, "limit", 50)? as usize);
388 let status_filter = optional_str(input, "status")?
389 .map(parse_trigger_status)
390 .transpose()
391 .map_err(ToolError::invalid_input)?;
392
393 let records = {
394 let manager = automations.lock().await;
395 manager
396 .list_triggers_for_owner(status_filter, limit, &context.state_namespace)
397 .map_err(|err| ToolError::execution_failed(format!("send_later list failed: {err}")))?
398 };
399
400 let items: Vec<Value> = records
401 .iter()
402 .map(|r| {
403 json!({
404 "trigger_id": r.trigger_id,
405 "fire_at": r.fire_at.to_rfc3339(),
406 "status": trigger_status_str(r.status),
407 "created_at": r.created_at.to_rfc3339(),
408 "message_preview": r.message.chars().take(120).collect::<String>(),
409 "workspace": r.workspace,
410 "parent_trigger_id": r.parent_trigger_id,
411 "destination_thread_id": r.destination_thread_id,
412 "task_id": r.task_id,
413 "error": r.error,
414 })
415 })
416 .collect();
417
418 let count = items.len();
419 Ok(ToolResult::success(
420 serde_json::to_string_pretty(&json!({ "triggers": items, "count": count }))
421 .unwrap_or_default(),
422 ))
423 }
424
425 async fn execute_read(input: &Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
426 let automations = SendLaterTool::automations_from_context(context)?;
427
428 let trigger_id = input
429 .get("trigger_id")
430 .and_then(Value::as_str)
431 .ok_or_else(|| ToolError::invalid_input("send_later read: `trigger_id` is required"))?;
432
433 let record = {
434 let manager = automations.lock().await;
435 manager
436 .get_trigger_for_owner(trigger_id, &context.state_namespace)
437 .map_err(|err| ToolError::execution_failed(format!("send_later read failed: {err}")))?
438 };
439
440 Ok(ToolResult::success(
441 serde_json::to_string_pretty(&json!({
442 "trigger_id": record.trigger_id,
443 "fire_at": record.fire_at.to_rfc3339(),
444 "status": trigger_status_str(record.status),
445 "created_at": record.created_at.to_rfc3339(),
446 "fired_at": record.fired_at.map(|t| t.to_rfc3339()),
447 "message": record.message,
448 "workspace": record.workspace,
449 "parent_trigger_id": record.parent_trigger_id,
450 "destination_thread_id": record.destination_thread_id,
451 "task_id": record.task_id,
452 "thread_id": record.thread_id,
453 "error": record.error,
454 }))
455 .unwrap_or_default(),
456 ))
457 }
458
459 async fn execute_cancel(input: &Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
460 let automations = SendLaterTool::automations_from_context(context)?;
461
462 let trigger_id = input
463 .get("trigger_id")
464 .and_then(Value::as_str)
465 .ok_or_else(|| ToolError::invalid_input("send_later cancel: `trigger_id` is required"))?;
466
467 let record = {
468 let manager = automations.lock().await;
469 manager
470 .cancel_trigger_for_owner(trigger_id, &context.state_namespace)
471 .map_err(|err| {
472 ToolError::execution_failed(format!("send_later cancel failed: {err}"))
473 })?
474 };
475
476 Ok(ToolResult::success(
477 serde_json::to_string_pretty(&json!({
478 "trigger_id": record.trigger_id,
479 "status": "canceled",
480 "fire_at": record.fire_at.to_rfc3339(),
481 }))
482 .unwrap_or_default(),
483 ))
484 }
485
486 fn parse_trigger_status(s: &str) -> Result<DelayedTriggerStatus, String> {
487 match s {
488 "pending" => Ok(DelayedTriggerStatus::Pending),
489 "dispatching" => Ok(DelayedTriggerStatus::Dispatching),
490 "fired" => Ok(DelayedTriggerStatus::Fired),
491 "canceled" => Ok(DelayedTriggerStatus::Canceled),
492 "failed" => Ok(DelayedTriggerStatus::Failed),
493 other => Err(format!(
494 "unknown trigger status '{other}'; expected one of: pending, dispatching, fired, canceled, failed"
495 )),
496 }
497 }
498
499 fn trigger_status_str(status: DelayedTriggerStatus) -> &'static str {
500 match status {
501 DelayedTriggerStatus::Pending => "pending",
502 DelayedTriggerStatus::Dispatching => "dispatching",
503 DelayedTriggerStatus::Fired => "fired",
504 DelayedTriggerStatus::Canceled => "canceled",
505 DelayedTriggerStatus::Failed => "failed",
506 }
507 }
508
509 // ── Tests ──────────────────────────────────────────────────────────────────
510
511 #[cfg(test)]
512 mod tests {
513 use std::sync::Arc;
514
515 use chrono::Duration;
516 use serde_json::json;
517 use tempfile::TempDir;
518 use tokio::sync::Mutex;
519
520 use crate::automation_manager::{AutomationManager, DelayedTriggerStatus};
521 use crate::tools::spec::{RuntimeToolServices, ToolContext, ToolSpec};
522
523 use super::SendLaterTool;
524
525 fn make_context(tmp: &TempDir) -> ToolContext {
526 make_context_for_session(tmp, "test-session")
527 }
528
529 fn make_context_for_session(tmp: &TempDir, session_id: &str) -> ToolContext {
530 let manager = AutomationManager::open_for_test(tmp.path().to_path_buf()).unwrap();
531 let shared = Arc::new(Mutex::new(manager));
532 ToolContext::new(".")
533 .with_state_namespace(session_id)
534 .with_runtime_services(RuntimeToolServices {
535 automations: Some(shared),
536 ..Default::default()
537 })
538 }
539
540 fn make_context_in_workspace(tmp: &TempDir, workspace: &std::path::Path) -> ToolContext {
541 let manager = AutomationManager::open_for_test(tmp.path().to_path_buf()).unwrap();
542 ToolContext::new(workspace)
543 .with_state_namespace("test-session")
544 .with_runtime_services(RuntimeToolServices {
545 automations: Some(Arc::new(Mutex::new(manager))),
546 ..Default::default()
547 })
548 }
549
550 fn stored_triggers(tmp: &TempDir) -> Vec<crate::automation_manager::DelayedTriggerRecord> {
551 AutomationManager::open_for_test(tmp.path().to_path_buf())
552 .unwrap()
553 .list_triggers(None, None)
554 .unwrap()
555 }
556
557 #[tokio::test]
558 async fn schedule_refuses_a_workspace_the_session_cannot_reach() {
559 let store = TempDir::new().unwrap();
560 let workspace = TempDir::new().unwrap();
561 let outside = TempDir::new().unwrap();
562 let ctx = make_context_in_workspace(&store, workspace.path());
563 let tool = SendLaterTool::new("send_later");
564
565 let result = tool
566 .execute(
567 json!({
568 "action": "schedule",
569 "delay_minutes": 5,
570 "message": "look around",
571 "workspace": outside.path().to_string_lossy()
572 }),
573 &ctx,
574 )
575 .await;
576
577 assert!(
578 result.is_err(),
579 "a directory outside the session workspace must be refused"
580 );
581 assert!(stored_triggers(&store).is_empty(), "nothing is scheduled");
582 }
583
584 #[tokio::test]
585 async fn schedule_stores_a_reachable_workspace_resolved() {
586 let store = TempDir::new().unwrap();
587 let workspace = TempDir::new().unwrap();
588 std::fs::create_dir(workspace.path().join("sub")).unwrap();
589 let ctx = make_context_in_workspace(&store, workspace.path());
590 let tool = SendLaterTool::new("send_later");
591
592 tool.execute(
593 json!({
594 "action": "schedule",
595 "delay_minutes": 5,
596 "message": "work in sub",
597 "workspace": "sub"
598 }),
599 &ctx,
600 )
601 .await
602 .unwrap();
603
604 let triggers = stored_triggers(&store);
605 assert_eq!(triggers.len(), 1);
606 assert_eq!(
607 triggers[0]
608 .workspace
609 .as_deref()
610 .map(|p| p.canonicalize().unwrap()),
611 Some(workspace.path().join("sub").canonicalize().unwrap())
612 );
613 }
614
615 #[tokio::test]
616 async fn schedule_allows_any_workspace_in_trust_mode() {
617 let store = TempDir::new().unwrap();
618 let workspace = TempDir::new().unwrap();
619 let elsewhere = TempDir::new().unwrap();
620 let ctx = make_context_in_workspace(&store, workspace.path()).with_trust_mode(true);
621 let tool = SendLaterTool::new("send_later");
622
623 tool.execute(
624 json!({
625 "action": "schedule",
626 "delay_minutes": 5,
627 "message": "trusted",
628 "workspace": elsewhere.path().to_string_lossy()
629 }),
630 &ctx,
631 )
632 .await
633 .unwrap();
634
635 assert_eq!(stored_triggers(&store).len(), 1);
636 }
637
638 #[tokio::test]
639 async fn schedule_with_delay_minutes_succeeds() {
640 let tmp = TempDir::new().unwrap();
641 let ctx = make_context(&tmp);
642 let tool = SendLaterTool::new("send_later");
643
644 let result = tool
645 .execute(
646 json!({
647 "action": "schedule",
648 "delay_minutes": 60,
649 "message": "Check CI status on open PRs."
650 }),
651 &ctx,
652 )
653 .await
654 .unwrap();
655
656 assert!(result.content.contains("trigger_id"));
657 assert!(result.content.contains("fire_at"));
658 assert!(result.content.contains("pending"));
659 }
660
661 #[tokio::test]
662 async fn schedule_with_absolute_fire_at_succeeds() {
663 let tmp = TempDir::new().unwrap();
664 let ctx = make_context(&tmp);
665 let tool = SendLaterTool::new("send_later");
666
667 let fire_at = (chrono::Utc::now() + Duration::minutes(30)).to_rfc3339();
668 let result = tool
669 .execute(
670 json!({
671 "action": "schedule",
672 "fire_at": fire_at,
673 "message": "Check PR mergeability."
674 }),
675 &ctx,
676 )
677 .await
678 .unwrap();
679
680 assert!(result.content.contains("trig_"));
681 }
682
683 #[tokio::test]
684 async fn schedule_rejects_mutually_exclusive_inputs() {
685 let tmp = TempDir::new().unwrap();
686 let ctx = make_context(&tmp);
687 let tool = SendLaterTool::new("send_later");
688
689 let fire_at = (chrono::Utc::now() + Duration::minutes(30)).to_rfc3339();
690 let err = tool
691 .execute(
692 json!({
693 "action": "schedule",
694 "delay_minutes": 60,
695 "fire_at": fire_at,
696 "message": "Should fail."
697 }),
698 &ctx,
699 )
700 .await
701 .unwrap_err();
702
703 assert!(err.to_string().contains("mutually exclusive"));
704 }
705
706 #[tokio::test]
707 async fn schedule_rejects_missing_timing_input() {
708 let tmp = TempDir::new().unwrap();
709 let ctx = make_context(&tmp);
710 let tool = SendLaterTool::new("send_later");
711
712 let err = tool
713 .execute(
714 json!({
715 "action": "schedule",
716 "message": "No timing provided."
717 }),
718 &ctx,
719 )
720 .await
721 .unwrap_err();
722
723 assert!(
724 err.to_string().contains("required"),
725 "expected required-timing error, got: {err}"
726 );
727 }
728
729 #[tokio::test]
730 async fn schedule_rejects_past_fire_at() {
731 let tmp = TempDir::new().unwrap();
732 let ctx = make_context(&tmp);
733 let tool = SendLaterTool::new("send_later");
734
735 let fire_at = (chrono::Utc::now() - Duration::minutes(5)).to_rfc3339();
736 let err = tool
737 .execute(
738 json!({
739 "action": "schedule",
740 "fire_at": fire_at,
741 "message": "This is in the past."
742 }),
743 &ctx,
744 )
745 .await
746 .unwrap_err();
747
748 assert!(
749 err.to_string().contains("future"),
750 "expected future-time error, got: {err}"
751 );
752 }
753
754 #[tokio::test]
755 async fn schedule_rejects_malformed_fire_at() {
756 let tmp = TempDir::new().unwrap();
757 let ctx = make_context(&tmp);
758 let tool = SendLaterTool::new("send_later");
759
760 let err = tool
761 .execute(
762 json!({
763 "action": "schedule",
764 "fire_at": "not-a-timestamp",
765 "message": "Bad time."
766 }),
767 &ctx,
768 )
769 .await
770 .unwrap_err();
771
772 assert!(
773 err.to_string().contains("invalid `fire_at`"),
774 "expected parse error, got: {err}"
775 );
776 }
777
778 #[tokio::test]
779 async fn list_and_read_round_trip() {
780 let tmp = TempDir::new().unwrap();
781 let ctx = make_context(&tmp);
782 let tool = SendLaterTool::new("send_later");
783
784 // Schedule a trigger.
785 let sched_result = tool
786 .execute(
787 json!({
788 "action": "schedule",
789 "delay_minutes": 15,
790 "message": "PR watcher check-in."
791 }),
792 &ctx,
793 )
794 .await
795 .unwrap();
796
797 let sched_val: serde_json::Value = serde_json::from_str(&sched_result.content).unwrap();
798 let trigger_id = sched_val["trigger_id"].as_str().unwrap();
799
800 // List should include it.
801 let list_result = tool
802 .execute(json!({ "action": "list" }), &ctx)
803 .await
804 .unwrap();
805 assert!(list_result.content.contains(trigger_id));
806
807 // Read should return full detail.
808 let read_result = tool
809 .execute(json!({ "action": "read", "trigger_id": trigger_id }), &ctx)
810 .await
811 .unwrap();
812 assert!(read_result.content.contains("PR watcher check-in."));
813 }
814
815 #[tokio::test]
816 async fn cancel_pending_trigger() {
817 let tmp = TempDir::new().unwrap();
818 let ctx = make_context(&tmp);
819 let tool = SendLaterTool::new("send_later");
820
821 let sched_result = tool
822 .execute(
823 json!({
824 "action": "schedule",
825 "delay_minutes": 30,
826 "message": "Will be canceled."
827 }),
828 &ctx,
829 )
830 .await
831 .unwrap();
832
833 let trigger_id = serde_json::from_str::<serde_json::Value>(&sched_result.content).unwrap()
834 ["trigger_id"]
835 .as_str()
836 .unwrap()
837 .to_string();
838
839 let cancel_result = tool
840 .execute(
841 json!({ "action": "cancel", "trigger_id": &trigger_id }),
842 &ctx,
843 )
844 .await
845 .unwrap();
846
847 assert!(cancel_result.content.contains("canceled"));
848
849 // Canceling again should fail.
850 let err = tool
851 .execute(
852 json!({ "action": "cancel", "trigger_id": &trigger_id }),
853 &ctx,
854 )
855 .await
856 .unwrap_err();
857 assert!(err.to_string().contains("canceled"));
858 }
859
860 #[tokio::test]
861 async fn list_with_status_filter() {
862 let tmp = TempDir::new().unwrap();
863 let ctx = make_context(&tmp);
864 let tool = SendLaterTool::new("send_later");
865
866 // Schedule one trigger.
867 let sched_result = tool
868 .execute(
869 json!({
870 "action": "schedule",
871 "delay_minutes": 10,
872 "message": "Pending trigger."
873 }),
874 &ctx,
875 )
876 .await
877 .unwrap();
878 let trigger_id = serde_json::from_str::<serde_json::Value>(&sched_result.content).unwrap()
879 ["trigger_id"]
880 .as_str()
881 .unwrap()
882 .to_string();
883
884 // Cancel it.
885 tool.execute(
886 json!({ "action": "cancel", "trigger_id": &trigger_id }),
887 &ctx,
888 )
889 .await
890 .unwrap();
891
892 // List pending: should be empty.
893 let pending_list = tool
894 .execute(json!({ "action": "list", "status": "pending" }), &ctx)
895 .await
896 .unwrap();
897 let pending_val: serde_json::Value = serde_json::from_str(&pending_list.content).unwrap();
898 assert_eq!(pending_val["count"].as_u64().unwrap(), 0);
899
900 // List canceled: should contain our trigger.
901 let canceled_list = tool
902 .execute(json!({ "action": "list", "status": "canceled" }), &ctx)
903 .await
904 .unwrap();
905 assert!(canceled_list.content.contains(&trigger_id));
906 }
907
908 #[tokio::test]
909 async fn parent_trigger_id_is_preserved() {
910 let tmp = TempDir::new().unwrap();
911 let ctx = make_context(&tmp);
912 let tool = SendLaterTool::new("send_later");
913
914 // First trigger (the "parent").
915 let parent_result = tool
916 .execute(
917 json!({
918 "action": "schedule",
919 "delay_minutes": 60,
920 "message": "First check-in."
921 }),
922 &ctx,
923 )
924 .await
925 .unwrap();
926 let parent_id = serde_json::from_str::<serde_json::Value>(&parent_result.content).unwrap()
927 ["trigger_id"]
928 .as_str()
929 .unwrap()
930 .to_string();
931
932 // Re-armed trigger referencing the parent.
933 let child_result = tool
934 .execute(
935 json!({
936 "action": "schedule",
937 "delay_minutes": 60,
938 "message": "Second check-in (re-arm).",
939 "parent_trigger_id": &parent_id,
940 }),
941 &ctx,
942 )
943 .await
944 .unwrap();
945 let child_id =
946 serde_json::from_str::<serde_json::Value>(&child_result.content).unwrap()["trigger_id"]
947 .as_str()
948 .unwrap()
949 .to_string();
950
951 let read_result = tool
952 .execute(json!({ "action": "read", "trigger_id": &child_id }), &ctx)
953 .await
954 .unwrap();
955 assert!(read_result.content.contains(&parent_id));
956 }
957
958 #[tokio::test]
959 async fn persistence_survives_manager_reload() {
960 let tmp = TempDir::new().unwrap();
961 let ctx = make_context(&tmp);
962 let tool = SendLaterTool::new("send_later");
963
964 let sched_result = tool
965 .execute(
966 json!({
967 "action": "schedule",
968 "delay_minutes": 45,
969 "message": "Persisted trigger."
970 }),
971 &ctx,
972 )
973 .await
974 .unwrap();
975 let trigger_id = serde_json::from_str::<serde_json::Value>(&sched_result.content).unwrap()
976 ["trigger_id"]
977 .as_str()
978 .unwrap()
979 .to_string();
980
981 // Open a fresh manager over the same directory to simulate restart.
982 let ctx2 = make_context(&tmp);
983 let read_result = tool
984 .execute(
985 json!({ "action": "read", "trigger_id": &trigger_id }),
986 &ctx2,
987 )
988 .await
989 .unwrap();
990 assert!(read_result.content.contains("Persisted trigger."));
991 }
992
993 #[tokio::test]
994 async fn trigger_controls_are_session_owned_and_legacy_records_fail_closed() {
995 let tmp = TempDir::new().unwrap();
996 let session_a = make_context_for_session(&tmp, "session-a");
997 let session_b = make_context_for_session(&tmp, "session-b");
998 let tool = SendLaterTool::new("send_later");
999
1000 let session_b_result = tool
1001 .execute(
1002 json!({
1003 "action": "schedule",
1004 "delay_minutes": 30,
1005 "message": "session B continuation"
1006 }),
1007 &session_b,
1008 )
1009 .await
1010 .unwrap();
1011 let session_b_id = serde_json::from_str::<serde_json::Value>(&session_b_result.content)
1012 .unwrap()["trigger_id"]
1013 .as_str()
1014 .unwrap()
1015 .to_string();
1016
1017 let session_a_result = tool
1018 .execute(
1019 json!({
1020 "action": "schedule",
1021 "delay_minutes": 30,
1022 "message": "session A continuation"
1023 }),
1024 &session_a,
1025 )
1026 .await
1027 .unwrap();
1028 let session_a_id = serde_json::from_str::<serde_json::Value>(&session_a_result.content)
1029 .unwrap()["trigger_id"]
1030 .as_str()
1031 .unwrap()
1032 .to_string();
1033
1034 let manager = AutomationManager::open_for_test(tmp.path().to_path_buf()).unwrap();
1035 let mut legacy = manager
1036 .create_trigger(crate::automation_manager::CreateDelayedTriggerRequest {
1037 destination_thread_id: None,
1038 fire_at: chrono::Utc::now() + Duration::hours(1),
1039 message: "ownerless legacy continuation".to_string(),
1040 workspace: None,
1041 owner_session_id: None,
1042 parent_trigger_id: None,
1043 disallowed_tools: Vec::new(),
1044 })
1045 .unwrap();
1046
1047 let session_b_list = tool
1048 .execute(json!({ "action": "list", "limit": 1 }), &session_b)
1049 .await
1050 .unwrap();
1051 assert!(session_b_list.content.contains(&session_b_id));
1052 assert!(!session_b_list.content.contains(&session_a_id));
1053 assert!(!session_b_list.content.contains(&legacy.trigger_id));
1054
1055 for action in ["read", "cancel"] {
1056 let error = tool
1057 .execute(
1058 json!({ "action": action, "trigger_id": &session_a_id }),
1059 &session_b,
1060 )
1061 .await
1062 .unwrap_err();
1063 assert!(error.to_string().contains("not found"), "{error}");
1064 }
1065 let still_pending = manager.get_trigger(&session_a_id).unwrap();
1066 assert_eq!(still_pending.status, DelayedTriggerStatus::Pending);
1067
1068 let legacy_error = tool
1069 .execute(
1070 json!({ "action": "read", "trigger_id": &legacy.trigger_id }),
1071 &session_a,
1072 )
1073 .await
1074 .unwrap_err();
1075 assert!(legacy_error.to_string().contains("not found"));
1076
1077 let restored_a = tool
1078 .execute(
1079 json!({ "action": "read", "trigger_id": &session_a_id }),
1080 &session_a,
1081 )
1082 .await
1083 .unwrap();
1084 assert!(
1085 restored_a.content.contains("session A continuation"),
1086 "switching A to B and back must restore A's controls"
1087 );
1088
1089 let own_cancel = tool
1090 .execute(
1091 json!({ "action": "cancel", "trigger_id": &session_b_id }),
1092 &session_b,
1093 )
1094 .await
1095 .unwrap();
1096 assert!(own_cancel.content.contains("canceled"));
1097
1098 legacy.fire_at = chrono::Utc::now() - Duration::minutes(1);
1099 manager.save_trigger(&legacy).unwrap();
1100 assert!(
1101 manager
1102 .collect_due_triggers(chrono::Utc::now())
1103 .unwrap()
1104 .iter()
1105 .all(|record| record.trigger_id != legacy.trigger_id),
1106 "ownerless legacy triggers must never fire"
1107 );
1108 }
1109
1110 #[tokio::test]
1111 async fn collect_due_triggers_returns_past_pending() {
1112 let tmp = TempDir::new().unwrap();
1113 let manager = AutomationManager::open_for_test(tmp.path().to_path_buf()).unwrap();
1114
1115 // Create a trigger with fire_at one hour from now — not due yet.
1116 let req = crate::automation_manager::CreateDelayedTriggerRequest {
1117 destination_thread_id: None,
1118 fire_at: chrono::Utc::now() + Duration::hours(1),
1119 message: "Not due yet.".to_string(),
1120 workspace: None,
1121 owner_session_id: Some("session-a".to_string()),
1122 parent_trigger_id: None,
1123 disallowed_tools: Vec::new(),
1124 };
1125 let record = manager.create_trigger(req).unwrap();
1126 let due = manager.collect_due_triggers(chrono::Utc::now()).unwrap();
1127 assert!(due.is_empty(), "should not fire a future trigger");
1128
1129 // Back-date the fire_at to the past and re-save.
1130 let mut past_record = record;
1131 past_record.fire_at = chrono::Utc::now() - Duration::minutes(5);
1132 manager.save_trigger(&past_record).unwrap();
1133
1134 let due = manager.collect_due_triggers(chrono::Utc::now()).unwrap();
1135 assert_eq!(due.len(), 1, "should fire a past-due trigger");
1136 }
1137
1138 /// A pending trigger is fired only by the scope that owns it, and a
1139 /// trigger has no paused state, so a one-shot host that attaches the
1140 /// store for inspection must refuse to schedule rather than store a
1141 /// delayed message that never arrives.
1142 #[tokio::test]
1143 async fn scheduling_requires_a_dispatch_owner() {
1144 let tmp = TempDir::new().unwrap();
1145 let manager = AutomationManager::open(tmp.path().to_path_buf()).unwrap();
1146 assert!(
1147 manager.execution_scope().is_none(),
1148 "fixture must model the unbound one-shot host"
1149 );
1150 let ctx = ToolContext::new(".").with_runtime_services(RuntimeToolServices {
1151 automations: Some(Arc::new(Mutex::new(manager))),
1152 ..Default::default()
1153 });
1154 let tool = SendLaterTool::new("send_later");
1155
1156 let err = tool
1157 .execute(
1158 json!({"action": "schedule", "delay_minutes": 60, "message": "Check CI."}),
1159 &ctx,
1160 )
1161 .await
1162 .expect_err("must refuse without a dispatch owner");
1163 assert!(
1164 err.to_string().contains("persistent execution owner"),
1165 "{err}"
1166 );
1167
1168 // Inspection still works against the attached store, and nothing was
1169 // persisted by the refused schedule.
1170 let listed = tool
1171 .execute(json!({"action": "list"}), &ctx)
1172 .await
1173 .expect("list must serve an attached store");
1174 assert!(
1175 AutomationManager::open(tmp.path().to_path_buf())
1176 .unwrap()
1177 .list_triggers(None, None)
1178 .unwrap()
1179 .is_empty(),
1180 "a refused schedule must not leave a trigger behind: {}",
1181 listed.content
1182 );
1183 }
1184
1185 #[tokio::test]
1186 async fn schedule_with_delay_seconds_succeeds() {
1187 let tmp = TempDir::new().unwrap();
1188 let ctx = make_context(&tmp);
1189 let tool = SendLaterTool::new("send_later");
1190
1191 let before = chrono::Utc::now();
1192 let result = tool
1193 .execute(
1194 json!({
1195 "action": "schedule",
1196 "delay_seconds": 15,
1197 "message": "Sub-minute check."
1198 }),
1199 &ctx,
1200 )
1201 .await
1202 .unwrap();
1203 let after = chrono::Utc::now();
1204
1205 let parsed: serde_json::Value = serde_json::from_str(&result.content).unwrap();
1206 assert!(parsed["trigger_id"].as_str().unwrap().starts_with("trig_"));
1207 let fire_at: chrono::DateTime<chrono::Utc> =
1208 parsed["fire_at"].as_str().unwrap().parse().unwrap();
1209 assert!(fire_at >= before + Duration::seconds(14));
1210 assert!(fire_at <= after + Duration::seconds(16));
1211 }
1212
1213 #[tokio::test]
1214 async fn schedule_rejects_invalid_and_overflow_delay_seconds() {
1215 let tmp = TempDir::new().unwrap();
1216 let ctx = make_context(&tmp);
1217 let tool = SendLaterTool::new("send_later");
1218
1219 for bad in [
1220 json!(0),
1221 json!(-5),
1222 json!(1.5),
1223 json!("10"),
1224 json!(u64::MAX),
1225 json!(i64::MAX),
1226 ] {
1227 let err = tool
1228 .execute(
1229 json!({
1230 "action": "schedule",
1231 "delay_seconds": bad,
1232 "message": "Invalid delay."
1233 }),
1234 &ctx,
1235 )
1236 .await
1237 .unwrap_err();
1238 assert!(
1239 err.to_string().contains("delay_seconds"),
1240 "unexpected error for {bad}: {err}"
1241 );
1242 }
1243 }
1244
1245 #[tokio::test]
1246 async fn schedule_enforces_three_way_timing_mutual_exclusion() {
1247 let tmp = TempDir::new().unwrap();
1248 let ctx = make_context(&tmp);
1249 let tool = SendLaterTool::new("send_later");
1250 let fire_at = (chrono::Utc::now() + Duration::minutes(10)).to_rfc3339();
1251
1252 for payload in [
1253 json!({
1254 "action": "schedule",
1255 "delay_seconds": 30,
1256 "delay_minutes": 1,
1257 "message": "Conflict"
1258 }),
1259 json!({
1260 "action": "schedule",
1261 "delay_seconds": 30,
1262 "fire_at": fire_at,
1263 "message": "Conflict"
1264 }),
1265 json!({
1266 "action": "schedule",
1267 "delay_minutes": 1,
1268 "fire_at": fire_at,
1269 "message": "Conflict"
1270 }),
1271 json!({
1272 "action": "schedule",
1273 "delay_seconds": 30,
1274 "delay_minutes": 1,
1275 "fire_at": fire_at,
1276 "message": "Conflict"
1277 }),
1278 ] {
1279 let err = tool.execute(payload, &ctx).await.unwrap_err();
1280 assert!(
1281 err.to_string().contains("mutually exclusive"),
1282 "unexpected error: {err}"
1283 );
1284 }
1285 }
1286
1287 #[test]
1288 fn schema_and_description_expose_delay_seconds_when_writable() {
1289 let writable = SendLaterTool::new("send_later");
1290 let schema = writable.input_schema();
1291 let prop = &schema["properties"]["delay_seconds"];
1292 assert_eq!(prop["type"], "integer");
1293 assert_eq!(prop["minimum"], 1);
1294 assert!(writable.description().contains("delay_seconds"));
1295
1296 let readonly = SendLaterTool::read_only("send_later_read");
1297 assert!(readonly.input_schema()["properties"]["delay_seconds"].is_null());
1298 }
1299 }
1300
1300 lines RUST