1mod ai;
2mod chat;
3mod http;
4mod schedule;
5mod secrets;
6mod tasks;
7
8use std::collections::{BTreeMap, HashSet};
9use std::path::{Path, PathBuf};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{mpsc, Arc, Mutex};
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use serde::{Deserialize, Serialize};
15use tauri::{
16 menu::{Menu, MenuItem},
17 path::BaseDirectory,
18 tray::TrayIconBuilder,
19 AppHandle, Emitter, Manager, State, WindowEvent,
20};
21use tauri_plugin_notification::{NotificationExt, PermissionState};
22use tauri_plugin_store::StoreExt;
23
24use crate::schedule::{parse_schedule, resolve_tz, Schedule};
25use crate::secrets::SecretsService;
26use crate::tasks::{
27 classify_due, expand_trigger, needs_expansion, reconcile, Disposition, ExpansionState, Task,
28 TaskOrigin, TaskStore, TriggerRuntimeState, TriggerSpecView,
29};
30
31const TICK_INTERVAL_PROD: Duration = Duration::from_secs(60);
38const TICK_INTERVAL_DEV: Duration = Duration::from_secs(10);
39
40const SCHEDULE_GRACE_TICKS: u32 = 2;
53
54const STATE_STORE_FILE: &str = "triggers-state.json";
55
56const TASKS_STORE_FILE: &str = "tasks.json";
61const TASKS_KEY: &str = "tasks";
62const EXPANSION_KEY: &str = "expansion";
63
64const META_NAMESPACE: &str = "__meta__";
67
68const LEGACY_META_FIRE_TIMES_KEY: &str = "fire_times";
72
73fn dev_mode_enabled() -> bool {
75 matches!(std::env::var("CHAMBERLAIN_DEV").ok().as_deref(), Some("1"))
76}
77
78#[derive(Clone, Serialize)]
84struct ActivityEvent {
85 ts: u64,
86 source: String,
87 message: String,
88}
89
90#[derive(Deserialize)]
91struct NotifyPayload {
92 #[serde(default)]
94 title: Option<String>,
95 body: String,
96}
97
98#[derive(Deserialize, Default)]
99struct TickResult {
100 #[serde(default)]
101 notify: Option<NotifyPayload>,
102 #[serde(default)]
103 state: Option<serde_json::Value>,
104}
105
106#[derive(Clone, Deserialize)]
107struct TriggerManifest {
108 id: String,
109 name: String,
110 #[serde(default)]
111 description: Option<String>,
112 entry: String,
113 #[serde(default, rename = "requiredSecrets")]
117 required_secrets: Vec<String>,
118 schedule: String,
124 #[serde(default)]
128 tz: Option<String>,
129}
130
131struct TriggerInfo {
132 manifest: TriggerManifest,
133 dir: PathBuf,
134 paused: Arc<AtomicBool>,
135 schedule: Schedule,
139 tz: chrono_tz::Tz,
142 schedule_error: Option<String>,
147}
148
149type TriggersRef = Arc<Vec<TriggerInfo>>;
150
151type TaskStoreRef = Arc<Mutex<TaskStore>>;
155
156struct TickSignal(Mutex<mpsc::Sender<()>>);
159
160impl TickSignal {
161 fn poke(&self) {
164 if let Ok(tx) = self.0.lock() {
165 let _ = tx.send(());
166 }
167 }
168}
169
170#[derive(Serialize)]
176struct TriggerListItem {
177 id: String,
178 name: String,
179 description: Option<String>,
180 paused: bool,
181 schedule: String,
183 #[serde(rename = "nextFireAt")]
187 next_fire_at: Option<u64>,
188 error: Option<String>,
191}
192
193#[derive(Serialize)]
196struct TaskListItem {
197 id: String,
198 origin: &'static str,
201 #[serde(rename = "triggerId")]
202 trigger_id: Option<String>,
203 #[serde(rename = "triggerName")]
205 trigger_name: Option<String>,
206 #[serde(rename = "scheduledAt")]
207 scheduled_at: u64,
208 #[serde(rename = "createdAt")]
209 created_at: u64,
210}
211
212#[derive(Serialize)]
215struct DeclaredSecretItem {
216 name: String,
217 #[serde(rename = "requiredBy")]
218 required_by: Vec<String>,
219}
220
221fn show_main_window(app: &AppHandle) {
222 if let Some(window) = app.get_webview_window("main") {
223 let _ = window.show();
224 let _ = window.unminimize();
225 let _ = window.set_focus();
226 }
227}
228
229#[cfg(windows)]
230fn register_aumid(app_id: &str, display_name: &str) {
231 use windows_registry::CURRENT_USER;
232 if let Ok(key) = CURRENT_USER.create(format!(r"SOFTWARE\Classes\AppUserModelId\{app_id}")) {
233 let _ = key.set_string("DisplayName", display_name);
234 }
235}
236
237fn send_notification(app: &AppHandle, title: &str, body: &str) {
238 let notification = app.notification();
239
240 match notification.permission_state() {
246 Ok(PermissionState::Granted) => {
247 let _ = notification.builder().title(title).body(body).show();
248 }
249 _ => {
250 eprintln!("notification permission not granted; skipping");
251 }
252 }
253}
254
255pub(crate) fn now_millis() -> u64 {
256 SystemTime::now()
257 .duration_since(UNIX_EPOCH)
258 .map(|d| d.as_millis() as u64)
259 .unwrap_or(0)
260}
261
262fn emit_activity(app: &AppHandle, source: &str, message: String) {
263 let _ = app.emit(
264 "activity",
265 ActivityEvent {
266 ts: now_millis(),
267 source: source.into(),
268 message,
269 },
270 );
271}
272
273fn fire_trigger(
276 app: &AppHandle,
277 trigger_id: &str,
278 trigger_name: &str,
279 title: Option<String>,
280 body: String,
281) {
282 let effective_title = title.unwrap_or_else(|| trigger_name.to_string());
283 send_notification(app, &effective_title, &body);
284 emit_activity(app, trigger_id, body);
285}
286
287fn read_trigger_state(app: &AppHandle, trigger_id: &str) -> serde_json::Value {
288 match app.store(STATE_STORE_FILE) {
289 Ok(store) => store
290 .get(trigger_id)
291 .unwrap_or_else(|| serde_json::json!({})),
292 Err(e) => {
293 eprintln!("failed to open state store: {e}");
294 serde_json::json!({})
295 }
296 }
297}
298
299fn write_trigger_state(app: &AppHandle, trigger_id: &str, state: serde_json::Value) {
300 match app.store(STATE_STORE_FILE) {
301 Ok(store) => {
302 store.set(trigger_id, state);
303 if let Err(e) = store.save() {
304 eprintln!("failed to persist state for {trigger_id}: {e}");
305 }
306 }
307 Err(e) => eprintln!("failed to open state store for write: {e}"),
308 }
309}
310
311fn drop_legacy_fire_times(app: &AppHandle) {
316 let store = match app.store(STATE_STORE_FILE) {
317 Ok(s) => s,
318 Err(e) => {
319 eprintln!("failed to open state store for legacy cleanup: {e}");
320 return;
321 }
322 };
323 let Some(mut meta) = store.get(META_NAMESPACE) else {
324 return;
325 };
326 let Some(map) = meta.as_object_mut() else {
327 return;
328 };
329 if map.remove(LEGACY_META_FIRE_TIMES_KEY).is_none() {
330 return;
331 }
332 eprintln!("migrating: dropped legacy __meta__.fire_times (superseded by the task list)");
333 store.set(META_NAMESPACE, meta);
334 if let Err(e) = store.save() {
335 eprintln!("failed to persist legacy cleanup: {e}");
336 }
337}
338
339fn load_task_store(app: &AppHandle) -> TaskStore {
344 let store = match app.store(TASKS_STORE_FILE) {
345 Ok(s) => s,
346 Err(e) => {
347 eprintln!("failed to open task store: {e}");
348 return TaskStore::default();
349 }
350 };
351 let tasks = store
352 .get(TASKS_KEY)
353 .and_then(|v| match serde_json::from_value::<Vec<Task>>(v) {
354 Ok(t) => Some(t),
355 Err(e) => {
356 eprintln!("tasks.json: unreadable task list, starting empty: {e}");
357 None
358 }
359 })
360 .unwrap_or_default();
361 let expansion = store
362 .get(EXPANSION_KEY)
363 .and_then(
364 |v| match serde_json::from_value::<BTreeMap<String, ExpansionState>>(v) {
365 Ok(e) => Some(e),
366 Err(e) => {
367 eprintln!("tasks.json: unreadable expansion state, starting empty: {e}");
368 None
369 }
370 },
371 )
372 .unwrap_or_default();
373
374 let mut loaded = TaskStore { tasks, expansion };
375 loaded.normalize();
378 loaded
379}
380
381fn save_task_store(app: &AppHandle, state: &TaskStore) {
384 let store = match app.store(TASKS_STORE_FILE) {
385 Ok(s) => s,
386 Err(e) => {
387 eprintln!("failed to open task store for write: {e}");
388 return;
389 }
390 };
391 match serde_json::to_value(&state.tasks) {
392 Ok(v) => store.set(TASKS_KEY, v),
393 Err(e) => {
394 eprintln!("failed to serialize task list: {e}");
395 return;
396 }
397 }
398 match serde_json::to_value(&state.expansion) {
399 Ok(v) => store.set(EXPANSION_KEY, v),
400 Err(e) => {
401 eprintln!("failed to serialize expansion state: {e}");
402 return;
403 }
404 }
405 if let Err(e) = store.save() {
406 eprintln!("failed to persist task store: {e}");
407 }
408}
409
410fn discover_triggers(app: &AppHandle, triggers_dir: &Path) -> Vec<TriggerInfo> {
422 let entries = match std::fs::read_dir(triggers_dir) {
423 Ok(e) => e,
424 Err(e) => {
425 eprintln!("failed to read triggers dir {triggers_dir:?}: {e}");
426 return Vec::new();
427 }
428 };
429
430 let mut result: Vec<TriggerInfo> = Vec::new();
431 for entry in entries.flatten() {
432 let path = entry.path();
433 if !path.is_dir() {
434 continue;
435 }
436 let manifest_path = path.join("manifest.json");
437 if !manifest_path.exists() {
438 continue;
439 }
440 let text = match std::fs::read_to_string(&manifest_path) {
441 Ok(t) => t,
442 Err(e) => {
443 eprintln!("failed to read {manifest_path:?}: {e}");
444 continue;
445 }
446 };
447 let manifest: TriggerManifest = match serde_json::from_str(&text) {
448 Ok(m) => m,
449 Err(e) => {
450 eprintln!("invalid manifest {manifest_path:?}: {e}");
451 continue;
452 }
453 };
454
455 if manifest.id == META_NAMESPACE {
456 eprintln!(
457 "trigger id '{META_NAMESPACE}' is reserved by framework, skipping {manifest_path:?}"
458 );
459 continue;
460 }
461
462 let (schedule, schedule_error) = match parse_schedule(&manifest.schedule) {
467 Ok(spec) => (spec, None),
468 Err(e) => {
469 eprintln!(
470 "invalid schedule for trigger '{}': {e} ({manifest_path:?})",
471 manifest.id
472 );
473 emit_activity(app, &manifest.id, format!("[schedule error] {e}"));
474 (Schedule::Hourly { minutes: vec![0] }, Some(e))
476 }
477 };
478
479 let (tz, schedule_error) = match resolve_tz(manifest.tz.as_deref()) {
481 Ok(t) => (t, schedule_error),
482 Err(e) => {
483 eprintln!("trigger '{}' tz error: {e}", manifest.id);
484 emit_activity(app, &manifest.id, format!("[schedule error] {e}"));
485 let combined = match schedule_error {
486 Some(prev) => Some(format!("{prev}; {e}")),
487 None => Some(e),
488 };
489 (chrono_tz::UTC, combined)
490 }
491 };
492
493 result.push(TriggerInfo {
494 manifest,
495 dir: path,
496 paused: Arc::new(AtomicBool::new(false)),
497 schedule,
498 tz,
499 schedule_error,
500 });
501 }
502
503 result.sort_by(|a, b| a.manifest.id.cmp(&b.manifest.id));
509
510 let mut seen = HashSet::new();
511 let mut deduped: Vec<TriggerInfo> = Vec::new();
512 for t in result {
513 if seen.insert(t.manifest.id.clone()) {
514 deduped.push(t);
515 } else {
516 eprintln!("duplicate trigger id '{}', skipping", t.manifest.id);
517 }
518 }
519 deduped
520}
521
522fn lock_tasks(store: &Mutex<TaskStore>) -> std::sync::MutexGuard<'_, TaskStore> {
527 store
528 .lock()
529 .unwrap_or_else(|poisoned| poisoned.into_inner())
530}
531
532fn find_trigger<'a>(triggers: &'a [TriggerInfo], id: &str) -> Option<&'a TriggerInfo> {
533 triggers.iter().find(|t| t.manifest.id == id)
534}
535
536fn fmt_utc(ms: u64) -> String {
543 match i64::try_from(ms)
544 .ok()
545 .and_then(chrono::DateTime::from_timestamp_millis)
546 {
547 Some(dt) => dt.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
548 None => format!("<invalid ts {ms}>"),
549 }
550}
551
552fn fmt_delay(ms: u64) -> String {
554 let secs = ms / 1000;
555 if secs < 60 {
556 return format!("{secs}s");
557 }
558 let mins = secs / 60;
559 if mins < 60 {
560 return format!("{mins}m");
561 }
562 format!("{}h{}m", mins / 60, mins % 60)
563}
564
565fn expand_pending_triggers(
572 app: &AppHandle,
573 triggers: &[TriggerInfo],
574 loaded: &BTreeMap<String, rustyscript::ModuleHandle>,
575 task_store: &Mutex<TaskStore>,
576 now: u64,
577) -> bool {
578 let mut store = lock_tasks(task_store);
579 let mut dirty = false;
580
581 for t in triggers {
582 let id = &t.manifest.id;
583 if t.schedule_error.is_some() || !loaded.contains_key(id) {
584 continue;
585 }
586 let boundary = store
588 .expansion
589 .get(id)
590 .map(|s| s.expanded_until)
591 .unwrap_or(now);
592 if !needs_expansion(boundary, now) {
593 continue;
594 }
595
596 let (generated, new_boundary) = expand_trigger(id, &t.schedule, &t.tz, boundary, now);
597 let added = store.extend(generated);
598
599 store
602 .expansion
603 .entry(id.clone())
604 .and_modify(|s| s.expanded_until = new_boundary)
605 .or_insert_with(|| ExpansionState {
606 expanded_until: new_boundary,
607 schedule: t.manifest.schedule.clone(),
608 tz: t.manifest.tz.clone(),
609 });
610 dirty = true;
611
612 if added > 0 {
613 emit_activity(
614 app,
615 id,
616 format!(
617 "[expanded] {added} 件のタスクを積みました (〜{})",
618 fmt_utc(new_boundary)
619 ),
620 );
621 }
622 }
623 dirty
624}
625
626fn reconcile_at_startup(
633 app: &AppHandle,
634 triggers: &[TriggerInfo],
635 task_store: &Mutex<TaskStore>,
636 now: u64,
637) {
638 let views: Vec<TriggerSpecView<'_>> = triggers
639 .iter()
640 .map(|t| TriggerSpecView {
641 id: &t.manifest.id,
642 schedule: &t.manifest.schedule,
643 tz: t.manifest.tz.as_deref(),
644 })
645 .collect();
646
647 let mut store = lock_tasks(task_store);
648 let report = reconcile(&mut store, &views, now);
649
650 for (task_id, trigger_id) in &report.orphaned {
651 eprintln!("dropped task '{task_id}': trigger '{trigger_id}' no longer exists");
652 emit_activity(
653 app,
654 trigger_id,
655 format!("[orphaned] トリガーが存在しないため予定を破棄しました ({task_id})"),
656 );
657 }
658 for trigger_id in &report.rescheduled {
659 eprintln!("trigger '{trigger_id}': schedule changed, re-expanding");
660 emit_activity(
661 app,
662 trigger_id,
663 "[rescheduled] schedule が変更されたため未実行の予定を破棄して再展開します".to_string(),
664 );
665 }
666 save_task_store(app, &store);
667}
668
669fn spawn_trigger_worker(
694 app: AppHandle,
695 triggers: TriggersRef,
696 task_store: TaskStoreRef,
697 secrets_service: SecretsService,
698 tick_interval: Duration,
699) -> mpsc::Sender<()> {
700 let (tick_tx, tick_rx) = mpsc::channel::<()>();
701 let app_for_worker = app.clone();
702 let timer_tx = tick_tx.clone();
703 let schedule_grace = tick_interval * SCHEDULE_GRACE_TICKS;
706
707 std::thread::spawn(move || {
708 let mut runtime = match rustyscript::Runtime::new(rustyscript::RuntimeOptions {
709 extensions: vec![secrets::chamberlain_ops::init()],
710 ..Default::default()
711 }) {
712 Ok(r) => r,
713 Err(e) => {
714 eprintln!("failed to init JS runtime: {e}");
715 return;
716 }
717 };
718
719 runtime
722 .deno_runtime()
723 .op_state()
724 .borrow_mut()
725 .put(secrets_service);
726
727 let mut loaded: BTreeMap<String, rustyscript::ModuleHandle> = BTreeMap::new();
731 for t in triggers.iter() {
732 if t.schedule_error.is_some() {
733 continue;
734 }
735 let entry_path = t.dir.join(&t.manifest.entry);
736 let module = match rustyscript::Module::load(&entry_path) {
737 Ok(m) => m,
738 Err(e) => {
739 eprintln!(
740 "failed to load trigger '{}' at {:?}: {e}",
741 t.manifest.id, entry_path
742 );
743 emit_activity(&app_for_worker, &t.manifest.id, format!("[load error] {e}"));
744 continue;
745 }
746 };
747 let handle = match runtime.load_module(&module) {
748 Ok(h) => h,
749 Err(e) => {
750 eprintln!("failed to instantiate trigger '{}': {e}", t.manifest.id);
751 emit_activity(
752 &app_for_worker,
753 &t.manifest.id,
754 format!("[instantiate error] {e}"),
755 );
756 continue;
757 }
758 };
759 loaded.insert(t.manifest.id.clone(), handle);
760 }
761
762 drop_legacy_fire_times(&app_for_worker);
764 reconcile_at_startup(&app_for_worker, &triggers, &task_store, now_millis());
765
766 while tick_rx.recv().is_ok() {
767 let now = now_millis();
768
769 let dirty =
771 expand_pending_triggers(&app_for_worker, &triggers, &loaded, &task_store, now);
772
773 let due = lock_tasks(&task_store).due(now);
776
777 let mut handled: Vec<String> = Vec::new();
779 for task in due {
780 let trigger = task
781 .trigger_id
782 .as_deref()
783 .and_then(|tid| find_trigger(&triggers, tid));
784 let handle = task.trigger_id.as_deref().and_then(|tid| loaded.get(tid));
785 let runtime_state = match (trigger, handle) {
788 (Some(t), Some(_)) => Some(TriggerRuntimeState {
789 paused: t.paused.load(Ordering::Relaxed),
790 }),
791 _ => None,
792 };
793
794 let source = task.trigger_id.clone().unwrap_or_else(|| "__task__".into());
795 match classify_due(&task, now, runtime_state, schedule_grace) {
796 Disposition::Run { delay_ms } => {
797 let (Some(t), Some(handle)) = (trigger, handle) else {
799 emit_activity(
802 &app_for_worker,
803 &source,
804 "[unsupported] 実行対象のトリガーが無いタスクは Phase 1 では実行できません"
805 .to_string(),
806 );
807 handled.push(task.id.clone());
808 continue;
809 };
810 let id = &t.manifest.id;
811 let current_state = read_trigger_state(&app_for_worker, id);
812 let ctx = serde_json::json!({
815 "now": now,
816 "state": current_state,
817 "scheduledAt": task.scheduled_at,
818 "delayMs": delay_ms,
819 });
820 let result: Result<Option<TickResult>, _> = runtime.call_function(
821 Some(handle),
822 "tick",
823 rustyscript::json_args!(ctx),
824 );
825 match result {
826 Ok(Some(res)) => {
827 if let Some(notify) = res.notify {
828 fire_trigger(
829 &app_for_worker,
830 id,
831 &t.manifest.name,
832 notify.title,
833 notify.body,
834 );
835 }
836 if let Some(new_state) = res.state {
837 write_trigger_state(&app_for_worker, id, new_state);
838 }
839 }
840 Ok(None) => {}
841 Err(e) => {
842 eprintln!("trigger '{id}' tick() error: {e}");
843 emit_activity(&app_for_worker, id, format!("[error] {e}"));
844 }
845 }
846 }
847 Disposition::Orphaned => {
848 let message = if trigger.is_some() {
851 "[unavailable] トリガーが実行できない状態 (構成エラー / ロード失敗) \
852 のため予定を破棄しました"
853 .to_string()
854 } else {
855 "[orphaned] トリガーが存在しないため予定を破棄しました".to_string()
856 };
857 emit_activity(&app_for_worker, &source, message);
858 }
859 Disposition::Paused => {
860 emit_activity(
861 &app_for_worker,
862 &source,
863 format!(
864 "[paused] 停止中のため {} の予定を破棄しました",
865 fmt_utc(task.scheduled_at)
866 ),
867 );
868 }
869 Disposition::SkippedLate { delay_ms } => {
870 emit_activity(
871 &app_for_worker,
872 &source,
873 format!(
874 "[skipped] {} の予定に {} 遅れているため実行しませんでした",
875 fmt_utc(task.scheduled_at),
876 fmt_delay(delay_ms)
877 ),
878 );
879 }
880 Disposition::Expired { delay_ms } => {
881 emit_activity(
882 &app_for_worker,
883 &source,
884 format!(
885 "[expired] {} の予定が猶予を超えた ({} 遅れ) ため未実行のまま破棄しました",
886 fmt_utc(task.scheduled_at),
887 fmt_delay(delay_ms)
888 ),
889 );
890 }
891 }
892 handled.push(task.id.clone());
893 }
894
895 if !handled.is_empty() || dirty {
898 let mut store = lock_tasks(&task_store);
899 for id in &handled {
900 store.remove(id);
901 }
902 save_task_store(&app_for_worker, &store);
903 }
904 }
905 });
906
907 tauri::async_runtime::spawn(async move {
908 if timer_tx.send(()).is_err() {
912 return;
913 }
914 loop {
915 tokio::time::sleep(tick_interval).await;
916 if timer_tx.send(()).is_err() {
917 break;
918 }
919 }
920 });
921
922 tick_tx
923}
924
925#[tauri::command]
928fn list_triggers(
929 triggers: State<'_, TriggersRef>,
930 task_store: State<'_, TaskStoreRef>,
931) -> Vec<TriggerListItem> {
932 let store = lock_tasks(&task_store);
933 triggers
934 .iter()
935 .map(|t| TriggerListItem {
936 id: t.manifest.id.clone(),
937 name: t.manifest.name.clone(),
938 description: t.manifest.description.clone(),
939 paused: t.paused.load(Ordering::Relaxed),
940 schedule: t.manifest.schedule.clone(),
941 next_fire_at: store.next_scheduled_for(&t.manifest.id),
942 error: t.schedule_error.clone(),
943 })
944 .collect()
945}
946
947#[tauri::command]
950fn list_tasks(
951 triggers: State<'_, TriggersRef>,
952 task_store: State<'_, TaskStoreRef>,
953) -> Vec<TaskListItem> {
954 let store = lock_tasks(&task_store);
955 store
956 .tasks
957 .iter()
958 .map(|t| TaskListItem {
959 id: t.id.clone(),
960 origin: match t.origin {
961 TaskOrigin::Schedule => "schedule",
962 TaskOrigin::Adhoc => "adhoc",
963 },
964 trigger_id: t.trigger_id.clone(),
965 trigger_name: t
966 .trigger_id
967 .as_deref()
968 .and_then(|tid| find_trigger(&triggers, tid))
969 .map(|t| t.manifest.name.clone()),
970 scheduled_at: t.scheduled_at,
971 created_at: t.created_at,
972 })
973 .collect()
974}
975
976#[tauri::command]
981fn delete_task(
982 app: AppHandle,
983 id: String,
984 task_store: State<'_, TaskStoreRef>,
985) -> Result<(), String> {
986 let mut store = lock_tasks(&task_store);
987 if !store.remove(&id) {
988 return Err(format!("unknown task: {id}"));
989 }
990 save_task_store(&app, &store);
991 drop(store);
992 emit_activity(
993 &app,
994 "__task__",
995 format!("[deleted] 予定を削除しました ({id})"),
996 );
997 Ok(())
998}
999
1000#[tauri::command]
1011fn run_trigger_now(
1012 app: AppHandle,
1013 id: String,
1014 triggers: State<'_, TriggersRef>,
1015 task_store: State<'_, TaskStoreRef>,
1016 tick: State<'_, TickSignal>,
1017) -> Result<(), String> {
1018 let trigger = find_trigger(&triggers, &id).ok_or_else(|| format!("unknown trigger: {id}"))?;
1019 if let Some(err) = &trigger.schedule_error {
1020 return Err(format!("trigger '{id}' has a configuration error: {err}"));
1021 }
1022
1023 let now = now_millis();
1024 {
1025 let mut store = lock_tasks(&task_store);
1026 store.insert(Task {
1027 id: format!("manual-{id}-{now}"),
1028 origin: TaskOrigin::Adhoc,
1029 trigger_id: Some(id.clone()),
1030 scheduled_at: now,
1031 created_at: now,
1032 });
1033 save_task_store(&app, &store);
1034 }
1035 emit_activity(&app, &id, "[manual] 手動実行を予約しました".to_string());
1036 tick.poke();
1038 Ok(())
1039}
1040
1041#[tauri::command]
1042fn pause_trigger(id: String, triggers: State<'_, TriggersRef>) -> Result<(), String> {
1043 match triggers.iter().find(|t| t.manifest.id == id) {
1044 Some(t) => {
1045 t.paused.store(true, Ordering::Relaxed);
1046 Ok(())
1047 }
1048 None => Err(format!("unknown trigger: {id}")),
1049 }
1050}
1051
1052#[tauri::command]
1053fn resume_trigger(id: String, triggers: State<'_, TriggersRef>) -> Result<(), String> {
1054 match triggers.iter().find(|t| t.manifest.id == id) {
1055 Some(t) => {
1056 t.paused.store(false, Ordering::Relaxed);
1057 Ok(())
1058 }
1059 None => Err(format!("unknown trigger: {id}")),
1060 }
1061}
1062
1063#[tauri::command]
1068fn list_declared_secrets(triggers: State<'_, TriggersRef>) -> Vec<DeclaredSecretItem> {
1069 let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
1070
1071 map.entry(secrets::ANTHROPIC_API_KEY_NAME.to_string())
1073 .or_default()
1074 .push("Chamberlain".to_string());
1075
1076 for t in triggers.iter() {
1077 for name in &t.manifest.required_secrets {
1078 map.entry(name.clone())
1079 .or_default()
1080 .push(t.manifest.id.clone());
1081 }
1082 }
1083 map.into_iter()
1084 .map(|(name, required_by)| DeclaredSecretItem { name, required_by })
1085 .collect()
1086}
1087
1088pub fn builder() -> tauri::Builder<tauri::Wry> {
1099 let _ = dotenvy::dotenv();
1103
1104 tauri::Builder::default()
1105 .plugin(tauri_plugin_notification::init())
1106 .plugin(tauri_plugin_store::Builder::default().build())
1107 .invoke_handler(tauri::generate_handler![
1108 list_triggers,
1109 pause_trigger,
1110 resume_trigger,
1111 run_trigger_now,
1112 list_tasks,
1113 delete_task,
1114 list_declared_secrets,
1115 secrets::set_secret,
1116 secrets::has_secret,
1117 secrets::delete_secret,
1118 chat::chat_history,
1119 chat::chat_send,
1120 chat::chat_clear,
1121 ])
1122 .on_window_event(|window, event| {
1123 if let WindowEvent::CloseRequested { api, .. } = event {
1124 let _ = window.hide();
1125 api.prevent_close();
1126 }
1127 })
1128 .setup(move |app| {
1129 #[cfg(windows)]
1130 {
1131 let identifier = app.config().identifier.clone();
1132 let display_name = app
1133 .config()
1134 .product_name
1135 .clone()
1136 .unwrap_or_else(|| identifier.clone());
1137 register_aumid(&identifier, &display_name);
1138 }
1139
1140 {
1145 let notification = app.notification();
1146 if !matches!(
1147 notification.permission_state(),
1148 Ok(PermissionState::Granted)
1149 ) {
1150 let _ = notification.request_permission();
1151 }
1152 }
1153
1154 let open_item = MenuItem::with_id(app, "open", "Open Chamberlain", true, None::<&str>)?;
1155 let notify_item =
1156 MenuItem::with_id(app, "notify", "Send test notification", true, None::<&str>)?;
1157 let quit_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
1158 let menu = Menu::with_items(app, &[&open_item, ¬ify_item, &quit_item])?;
1159
1160 TrayIconBuilder::new()
1161 .icon(app.default_window_icon().unwrap().clone())
1162 .menu(&menu)
1163 .show_menu_on_left_click(true)
1164 .on_menu_event(|app, event| match event.id.as_ref() {
1165 "open" => show_main_window(app),
1166 "notify" => send_notification(app, "Chamberlain", "テスト通知です"),
1167 "quit" => app.exit(0),
1168 _ => {}
1169 })
1170 .build(app)?;
1171
1172 let dev_mode = dev_mode_enabled();
1177 let tick_interval = if dev_mode {
1178 TICK_INTERVAL_DEV
1179 } else {
1180 TICK_INTERVAL_PROD
1181 };
1182 if dev_mode {
1183 eprintln!(
1184 "CHAMBERLAIN_DEV=1: heartbeat is 10s (use the manual-run button to \
1185 iterate on a trigger; schedule floors are enforced by the DSL now)"
1186 );
1187 }
1188
1189 let triggers_dir = match app.path().resolve("triggers", BaseDirectory::Resource) {
1194 Ok(p) => p,
1195 Err(e) => {
1196 eprintln!("failed to resolve triggers resource dir: {e}");
1197 PathBuf::new()
1198 }
1199 };
1200 let triggers: TriggersRef = Arc::new(discover_triggers(app.handle(), &triggers_dir));
1201 for t in triggers.iter() {
1202 eprintln!(
1203 "discovered trigger: {} ({}) — entry {}, schedule '{}' tz={:?}",
1204 t.manifest.id, t.manifest.name, t.manifest.entry, t.manifest.schedule, t.tz
1205 );
1206 }
1207
1208 let secrets_service = SecretsService(app.config().identifier.clone());
1211 app.manage(secrets_service.clone());
1212
1213 let task_store: TaskStoreRef = Arc::new(Mutex::new(load_task_store(app.handle())));
1216
1217 app.manage(triggers.clone());
1218 app.manage(task_store.clone());
1219 let tick_tx = spawn_trigger_worker(
1220 app.handle().clone(),
1221 triggers,
1222 task_store,
1223 secrets_service,
1224 tick_interval,
1225 );
1226 app.manage(TickSignal(Mutex::new(tick_tx)));
1227
1228 Ok(())
1229 })
1230}