moadim 1.4.1

Loop engine for AI agents — routines over REST, MCP, and a built-in web UI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/**
 * Top-level Routines page — composition of the filter/table/calendar/day views, the
 * create/edit form, and the history/logs/flags sub-pages.
 *
 * `RPage`/`RModal` state modeling: the Rust source (`ui/src/routines/state.rs`) models this via
 * a `RPage` enum (List/New/Logs(id)/History(id)/Flags(id)/Clone(Routine)) plus an independent
 * `RModal` overlay (None/Edit(id)/ConfirmDelete/ConfirmBulkDelete). This port keeps that same
 * shape as plain `useState` rather than nested routes: every sub-page needs the already-loaded
 * `routines` list (for title lookups, the clone source, etc.), and nested routes would need that
 * list threaded through a route loader or context for no real benefit — a query param round-trip
 * to the router buys us nothing a local discriminated-union state doesn't already give simply.
 * The one exception is the `?history=<id>` deep link from the Overview page's recent-runs panel,
 * which IS a URL param (read once on mount, then behaves like any other page transition).
 */
import { useEffect, useMemo, useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";
import {
  useAllRuns,
  useCleanupRoutines,
  useCreateRoutine,
  useDeleteRoutine,
  useLockStatus,
  useMachine,
  useMachines,
  useRoutine,
  useRoutines,
  useTriggerRoutine,
  useUnlock,
  useUpdateRoutine,
  type RoutineResponse,
} from "../../api/hooks";
import { GlobalLockBanner } from "../../components/GlobalLockBanner";
import { loadRefreshToken, RefreshControl, refreshMs, saveRefreshToken, type RefreshToken } from "../../components/RefreshControl";
import { useToasts } from "../../shell/toasts";
import { BulkBar, BulkDeleteDialog, ConfirmDeleteDialog } from "./BulkBar";
import { humanizeBytes } from "./bytes";
import { DayTimeline, type TimelineItem } from "./DayTimeline";
import {
  DUE_SOON_WINDOW_MS,
  defaultRoutineFilter,
  distinctAgents,
  distinctMachines,
  distinctRepositories,
  distinctTags,
  filterRoutines,
  isFilterActive,
  isRoutineSnoozed,
  type NamedFacet,
  type RoutineFilter,
  type RoutineMachineFacet,
  type RoutineStatusFacet,
} from "./filter";
import { FilterBar } from "./FilterBar";
import { GroupBySelector } from "./GroupBySelector";
import { RoutineCalendar } from "./RoutineCalendar";
import { RoutineFlags } from "./RoutineFlags";
import { RoutineForm, type RoutineDraft } from "./RoutineForm";
import { RoutineHistory } from "./RoutineHistory";
import { RoutineLogs } from "./RoutineLogs";
import { RoutineTable } from "./RoutineTable";
import { cloneTitle } from "./routineDraft";
import { flipDir, sortRoutines, type RCol, type RDir, type RGroupBy } from "./routineState";
import {
  captureSnapshot,
  decodeSnapshot,
  loadLastView,
  loadSavedViews,
  saveLastView,
  saveSavedViews,
  type SavedView,
  type ViewSnapshot,
} from "./savedViews";
import { SavedViewsBar } from "./SavedViewsBar";
import { groupRecentRuns, RUN_HISTORY_FETCH_LIMIT } from "./sparkline";
import { StatsBar } from "./StatsBar";
import { ViewToggle, type RView } from "./ViewToggle";

type RPage =
  | { kind: "list" }
  | { kind: "new" }
  | { kind: "clone"; source: RoutineResponse }
  | { kind: "logs"; id: string }
  | { kind: "history"; id: string }
  | { kind: "flags"; id: string };

type RModal =
  | { kind: "none" }
  | { kind: "edit"; id: string }
  | { kind: "confirmDelete"; id: string; title: string }
  | { kind: "confirmBulkDelete" };

const NEXT_RUN_TICK_MS = 30_000;

export function RoutinesPage() {
  const { addToast } = useToasts();
  const [searchParams, setSearchParams] = useSearchParams();

  // ── Persisted view state (restored from the last-used filter/sort/group-by) ──
  const initialSnapshot = useMemo(() => loadLastView(), []);
  const initialDecoded = initialSnapshot ? decodeSnapshot(initialSnapshot) : undefined;

  const [page, setPage] = useState<RPage>({ kind: "list" });
  const [modal, setModal] = useState<RModal>({ kind: "none" });
  const [view, setView] = useState<RView>("table");
  const [filter, setFilter] = useState<RoutineFilter>(initialDecoded?.filter ?? defaultRoutineFilter());
  const [sortCol, setSortCol] = useState<RCol | undefined>(initialDecoded?.sortCol);
  const [sortDir, setSortDir] = useState<RDir>(initialDecoded?.sortDir ?? "asc");
  const [groupBy, setGroupBy] = useState<RGroupBy>(initialDecoded?.groupBy ?? "none");
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [savedViewsList, setSavedViewsList] = useState<SavedView[]>(loadSavedViews);
  const [interval, setIntervalState] = useState<RefreshToken>(loadRefreshToken);
  const [now, setNow] = useState(() => new Date());
  const searchRef = useRef<HTMLInputElement>(null);

  // Deep link: `/routines?history=<id>` (e.g. from the Overview page's recent-runs panel).
  useEffect(() => {
    const id = searchParams.get("history");
    if (id) {
      setPage({ kind: "history", id });
      const next = new URLSearchParams(searchParams);
      next.delete("history");
      setSearchParams(next, { replace: true });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Live "now" clock, ticked independently of any network fetch.
  useEffect(() => {
    const id = setInterval(() => setNow(new Date()), NEXT_RUN_TICK_MS);
    return () => clearInterval(id);
  }, []);

  // Auto-persist the current filter/sort/group-by so a reload restores it.
  useEffect(() => {
    saveLastView(captureSnapshot(filter, sortCol, sortDir, groupBy));
  }, [filter, sortCol, sortDir, groupBy]);

  // Global "/" focuses search, Escape closes the open modal.
  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && modal.kind !== "none") {
        setModal({ kind: "none" });
        return;
      }
      const target = e.target as HTMLElement | null;
      const typing = target && ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName);
      if (e.key === "/" && !typing && !e.metaKey && !e.ctrlKey && !e.altKey) {
        e.preventDefault();
        searchRef.current?.focus();
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [modal.kind]);

  const refetchMs = refreshMs(interval);
  const routinesQuery = useRoutines({}, { refetchInterval: refetchMs });
  const allRunsQuery = useAllRuns(RUN_HISTORY_FETCH_LIMIT);
  const lockStatusQuery = useLockStatus();
  const currentMachineQuery = useMachine();
  const machinesQuery = useMachines();

  // Re-arm the fleet-run-history poll on the same cadence as the routines list.
  useEffect(() => {
    if (refetchMs === undefined) return;
    const id = setInterval(() => void allRunsQuery.refetch(), refetchMs);
    return () => clearInterval(id);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [refetchMs]);

  const routines = useMemo(() => routinesQuery.data ?? [], [routinesQuery.data]);
  const runHistory = useMemo(() => groupRecentRuns(allRunsQuery.data ?? []), [allRunsQuery.data]);

  // Default the machine facet to this daemon's own identity, once, unless a restored saved view
  // (or a fast operator) already picked something.
  const defaultedMachineRef = useRef(false);
  useEffect(() => {
    const name = currentMachineQuery.data?.name;
    if (!name || defaultedMachineRef.current) return;
    defaultedMachineRef.current = true;
    setFilter((f) => (f.machine.kind === "any" ? { ...f, machine: { kind: "machine", value: name } } : f));
  }, [currentMachineQuery.data]);

  // Drop selections for routines that no longer exist after a reload.
  useEffect(() => {
    const ids = new Set(routines.map((r) => r.id));
    setSelected((sel) => {
      const next = new Set([...sel].filter((id) => ids.has(id)));
      return next.size === sel.size ? sel : next;
    });
  }, [routines]);

  // ── Mutations ──────────────────────────────────────────────────────────────
  const createRoutine = useCreateRoutine();
  const updateRoutine = useUpdateRoutine();
  const deleteRoutine = useDeleteRoutine();
  const triggerRoutine = useTriggerRoutine();
  const cleanupRoutines = useCleanupRoutines();
  const unlock = useUnlock();

  const goToList = () => setPage({ kind: "list" });
  const closeModal = () => setModal({ kind: "none" });

  const onUnlockAll = () => {
    unlock.mutate("all", {
      onSuccess: () => addToast("Routines unlocked", "ok"),
      onError: (e) => addToast(`Unlock failed: ${e.message}`, "err"),
    });
  };

  const onCreate = (draft: RoutineDraft) => {
    createRoutine.mutate(
      { ...draft },
      {
        onSuccess: () => {
          goToList();
          addToast("Routine created", "ok");
        },
        onError: (e) => addToast(`Create failed: ${e.message}`, "err"),
      },
    );
  };

  const onSaveEdit = (id: string, draft: RoutineDraft) => {
    updateRoutine.mutate(
      { id, body: { ...draft } },
      {
        onSuccess: () => {
          closeModal();
          addToast("Routine updated", "ok");
        },
        onError: (e) => addToast(`Update failed: ${e.message}`, "err"),
      },
    );
  };

  const onConfirmDelete = (id: string) => {
    deleteRoutine.mutate(id, {
      onSuccess: () => {
        closeModal();
        addToast("Routine deleted", "ok");
      },
      onError: (e) => addToast(`Delete failed: ${e.message}`, "err"),
    });
  };

  const onToggle = (id: string, enabled: boolean) => {
    updateRoutine.mutate(
      { id, body: { enabled } },
      {
        onSuccess: () => addToast(enabled ? "Routine enabled" : "Routine disabled", "ok"),
        onError: (e) => addToast(`Toggle failed: ${e.message}`, "err"),
      },
    );
  };

  const onTrigger = (id: string) => {
    triggerRoutine.mutate(id, {
      onSuccess: () => addToast("Routine triggered", "ok"),
      onError: (e) => addToast(`Trigger failed: ${e.message}`, "err"),
    });
  };

  const onCleanup = () => {
    cleanupRoutines.mutate(undefined, {
      onSuccess: (res) => {
        const n = res.removed;
        addToast(
          `Cleanup removed ${n} workbench${n === 1 ? "" : "es"} (freed ${humanizeBytes(res.freed_bytes)})`,
          "ok",
        );
      },
      onError: (e) => addToast(`Cleanup failed: ${e.message}`, "err"),
    });
  };

  // ── Bulk actions (sequential, per-item — no batch endpoint) ─────────────────
  const bulkSetEnabled = async (enabled: boolean) => {
    const ids = [...selected];
    if (ids.length === 0) return;
    let ok = 0;
    let failed = 0;
    for (const id of ids) {
      try {
        await updateRoutine.mutateAsync({ id, body: { enabled } });
        ok++;
      } catch {
        failed++;
      }
    }
    const verb = enabled ? "enabled" : "disabled";
    if (failed === 0) addToast(`${ok} routine(s) ${verb}`, "ok");
    else addToast(`${ok} ${verb}, ${failed} failed`, "err");
  };

  const onConfirmBulkDelete = async () => {
    const ids = [...selected];
    let ok = 0;
    let failed = 0;
    const deleted: string[] = [];
    for (const id of ids) {
      try {
        await deleteRoutine.mutateAsync(id);
        ok++;
        deleted.push(id);
      } catch {
        failed++;
      }
    }
    setSelected((sel) => {
      const next = new Set(sel);
      for (const id of deleted) next.delete(id);
      return next;
    });
    closeModal();
    if (failed === 0) addToast(`${ok} routine(s) deleted`, "ok");
    else addToast(`${ok} deleted, ${failed} failed`, "err");
  };

  // ── Saved views ──────────────────────────────────────────────────────────────
  const onApplyView = (snapshot: ViewSnapshot) => {
    const decoded = decodeSnapshot(snapshot);
    setFilter(decoded.filter);
    setSortCol(decoded.sortCol);
    setSortDir(decoded.sortDir);
    setGroupBy(decoded.groupBy);
  };
  const onSaveView = (name: string) => {
    const snapshot = captureSnapshot(filter, sortCol, sortDir, groupBy);
    setSavedViewsList((list) => {
      const next = [...list.filter((v) => v.name !== name), { name, snapshot }];
      saveSavedViews(next);
      return next;
    });
  };
  const onDeleteView = (name: string) => {
    setSavedViewsList((list) => {
      const next = list.filter((v) => v.name !== name);
      saveSavedViews(next);
      return next;
    });
  };

  // ── Derived data ──────────────────────────────────────────────────────────────
  const agentOptions = useMemo(() => distinctAgents(routines), [routines]);
  const repositoryOptions = useMemo(() => distinctRepositories(routines), [routines]);
  const tagOptions = useMemo(() => distinctTags(routines), [routines]);
  const machineOptions = useMemo(() => {
    const opts = new Set([...distinctMachines(routines), ...(machinesQuery.data ?? [])]);
    return [...opts].sort();
  }, [routines, machinesQuery.data]);

  const filterActive = isFilterActive(filter);
  const visible = useMemo(
    () => sortRoutines(filterRoutines(routines, filter, now, DUE_SOON_WINDOW_MS), sortCol, sortDir, now),
    [routines, filter, now, sortCol, sortDir],
  );

  // List rows omit `prompt` by default (see `include_prompts`), so the edit form fetches the
  // full routine by id instead of reusing the cached list row.
  const editRoutineQuery = useRoutine(modal.kind === "edit" ? modal.id : "", modal.kind === "edit");
  const editRoutine = modal.kind === "edit" ? editRoutineQuery.data : undefined;

  const onSelect = (id: string) =>
    setSelected((sel) => {
      const next = new Set(sel);
      if (!next.delete(id)) next.add(id);
      return next;
    });
  const onSelectAll = () => {
    const visibleIds = visible.map((r) => r.id);
    const allSelected = visibleIds.length > 0 && visibleIds.every((id) => selected.has(id));
    setSelected(allSelected ? new Set() : new Set(visibleIds));
  };

  const onColSort = (col: RCol) => {
    if (sortCol === col) setSortDir((d) => flipDir(d));
    else {
      setSortCol(col);
      setSortDir("asc");
    }
  };

  const onSetInterval = (next: RefreshToken) => {
    setIntervalState(next);
    saveRefreshToken(next);
  };

  const titleOf = (id: string) => routines.find((r) => r.id === id)?.title ?? "";

  // ── Sub-pages ──────────────────────────────────────────────────────────────
  if (page.kind === "new") {
    return <RoutineForm mode="create" saving={createRoutine.isPending} onCancel={goToList} onSave={onCreate} />;
  }
  if (page.kind === "clone") {
    const pre: RoutineDraft = {
      schedule: page.source.schedule,
      title: cloneTitle(page.source.title),
      agent: page.source.agent,
      model: page.source.model ?? null,
      prompt: page.source.prompt ?? "",
      goal: page.source.goal ?? null,
      repositories: page.source.repositories ?? [],
      machines: page.source.machines ?? [],
      enabled: page.source.enabled,
      ttl_secs: page.source.ttl_secs ?? null,
      tags: page.source.tags ?? [],
    };
    return (
      <RoutineForm mode="clone" initial={pre} saving={createRoutine.isPending} onCancel={goToList} onSave={onCreate} />
    );
  }
  if (page.kind === "logs") {
    return <RoutineLogs id={page.id} title={titleOf(page.id)} onBack={goToList} />;
  }
  if (page.kind === "history") {
    return <RoutineHistory id={page.id} title={titleOf(page.id)} onBack={goToList} />;
  }
  if (page.kind === "flags") {
    return <RoutineFlags id={page.id} title={titleOf(page.id)} onBack={goToList} />;
  }

  // ── List page ──────────────────────────────────────────────────────────────
  const dayItems: TimelineItem[] = visible
    .filter((r) => r.enabled)
    .map((r) => ({
      id: r.id,
      label: r.title,
      schedule: r.schedule,
      snoozed: isRoutineSnoozed(r, now),
      flagCount: r.flag_count ?? 0,
    }));

  return (
    <div className="page">
      <h1 className="page-title">Routines</h1>
      <GlobalLockBanner status={lockStatusQuery.data} onUnlock={onUnlockAll} />
      <StatsBar
        routines={routines}
        now={now}
        active={filter.status}
        onStatus={(s: RoutineStatusFacet) => setFilter((f) => ({ ...f, status: s }))}
      />

      <div className="section-hd">
        <div className="section-label">SCHEDULED ROUTINES</div>
        <div className="section-acts">
          <RefreshControl token={interval} updatedAtMs={routinesQuery.dataUpdatedAt} onChange={onSetInterval} />
          {view === "table" && <GroupBySelector groupBy={groupBy} onChange={setGroupBy} />}
          <ViewToggle view={view} onSetView={setView} />
          <button
            type="button"
            className="btn btn-ghost btn-sm"
            title="Reap finished, expired run workbenches now"
            onClick={onCleanup}
          >
            CLEANUP NOW
          </button>
          <button type="button" className="btn btn-primary btn-sm" onClick={() => setPage({ kind: "new" })}>
            + NEW ROUTINE
          </button>
        </div>
      </div>

      <FilterBar
        filter={filter}
        agents={agentOptions}
        machines={machineOptions}
        repositories={repositoryOptions}
        tags={tagOptions}
        shown={visible.length}
        total={routines.length}
        searchRef={searchRef}
        onQuery={(q) => setFilter((f) => ({ ...f, query: q }))}
        onStatus={(s) => setFilter((f) => ({ ...f, status: s }))}
        onAgent={(a: NamedFacet) => setFilter((f) => ({ ...f, agent: a }))}
        onMachine={(m: RoutineMachineFacet) => setFilter((f) => ({ ...f, machine: m }))}
        onRepository={(r: NamedFacet) => setFilter((f) => ({ ...f, repository: r }))}
        onTag={(t: NamedFacet) => setFilter((f) => ({ ...f, tag: t }))}
        onClear={() => setFilter(defaultRoutineFilter())}
      />

      <SavedViewsBar views={savedViewsList} onApply={onApplyView} onSave={onSaveView} onDelete={onDeleteView} />

      <BulkBar
        count={selected.size}
        onEnable={() => void bulkSetEnabled(true)}
        onDisable={() => void bulkSetEnabled(false)}
        onDelete={() => setModal({ kind: "confirmBulkDelete" })}
        onClear={() => setSelected(new Set())}
      />

      {view === "table" && (
        <RoutineTable
          routines={visible}
          loading={routinesQuery.isLoading}
          filterActive={filterActive}
          now={now}
          selected={selected}
          onSelect={onSelect}
          onSelectAll={onSelectAll}
          sortCol={sortCol}
          sortDir={sortDir}
          groupBy={groupBy}
          runHistory={runHistory}
          onSort={onColSort}
          onEdit={(id) => setModal({ kind: "edit", id })}
          onClone={(id) => {
            const source = routines.find((r) => r.id === id);
            if (source) setPage({ kind: "clone", source });
          }}
          onDelete={(id, title) => setModal({ kind: "confirmDelete", id, title })}
          onToggle={onToggle}
          onTrigger={onTrigger}
          onLogs={(id) => setPage({ kind: "logs", id })}
          onHistory={(id) => setPage({ kind: "history", id })}
          onFlags={(id) => setPage({ kind: "flags", id })}
          onClearFilters={() => setFilter(defaultRoutineFilter())}
        />
      )}
      {view === "calendar" && (
        <RoutineCalendar
          routines={visible}
          loading={routinesQuery.isLoading}
          onEdit={(id) => setModal({ kind: "edit", id })}
        />
      )}
      {view === "day" && (
        <DayTimeline
          items={dayItems}
          loading={routinesQuery.isLoading}
          onClick={(id) => setModal({ kind: "edit", id })}
        />
      )}

      {modal.kind === "edit" && editRoutineQuery.isLoading && (
        <div className="empty">
          <div className="spinner" />
        </div>
      )}
      {modal.kind === "edit" && editRoutine && (
        <RoutineForm
          mode="edit"
          initial={
            editRoutine && {
              schedule: editRoutine.schedule,
              title: editRoutine.title,
              agent: editRoutine.agent,
              model: editRoutine.model ?? null,
              prompt: editRoutine.prompt ?? "",
              goal: editRoutine.goal ?? null,
              repositories: editRoutine.repositories ?? [],
              machines: editRoutine.machines ?? [],
              enabled: editRoutine.enabled,
              ttl_secs: editRoutine.ttl_secs ?? null,
              tags: editRoutine.tags ?? [],
            }
          }
          saving={updateRoutine.isPending}
          onCancel={closeModal}
          onSave={(draft) => onSaveEdit(modal.id, draft)}
        />
      )}
      {modal.kind === "confirmDelete" && (
        <ConfirmDeleteDialog title={modal.title} onCancel={closeModal} onConfirm={() => onConfirmDelete(modal.id)} />
      )}
      {modal.kind === "confirmBulkDelete" && (
        <BulkDeleteDialog count={selected.size} onCancel={closeModal} onConfirm={() => void onConfirmBulkDelete()} />
      )}
    </div>
  );
}