@bridgebrew/scheduler 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1327 @@
1
+ // The scheduled tasks (research-040, revision): every task of the workspace, its list beside its card, and a draft for
2
+ // a new one. A task is a schedule and an action chosen among the types the plugins register; the action's fields are
3
+ // the type's JSON Schema, drawn by the settings form (./scheduled-screen.tsx uses @bridge/plugin-manager/form).
4
+ import * as React from 'react';
5
+ import {
6
+ Button,
7
+ Card,
8
+ CardHeader,
9
+ Detail,
10
+ DetailHeader,
11
+ DetailTitle,
12
+ Dialog,
13
+ DialogBody,
14
+ DialogClose,
15
+ DialogContent,
16
+ DialogDescription,
17
+ DialogFooter,
18
+ DialogHeader,
19
+ DialogTitle,
20
+ DropdownMenu,
21
+ DropdownMenuContent,
22
+ DropdownMenuItem,
23
+ DropdownMenuTrigger,
24
+ EditableField,
25
+ EmptyState,
26
+ Icon,
27
+ Input,
28
+ List,
29
+ ListItem,
30
+ Pane,
31
+ PaneBody,
32
+ PaneFooter,
33
+ PaneHeader,
34
+ Properties,
35
+ PropertyRow,
36
+ SegmentGroup,
37
+ Select,
38
+ SelectContent,
39
+ Tabs,
40
+ TabsContent,
41
+ TabsList,
42
+ TabsTrigger,
43
+ SelectItem,
44
+ SelectTrigger,
45
+ SelectValue,
46
+ MultiPane,
47
+ StatusIcon,
48
+ Toggle,
49
+ ToggleGroup,
50
+ Tooltip,
51
+ TooltipContent,
52
+ TooltipTrigger,
53
+ isRecord,
54
+ readJson,
55
+ useToast,
56
+ useFollow,
57
+ gestureOf,
58
+ formatDate,
59
+ isComposing,
60
+ } from '@bridge/ui';
61
+ import { ObjectFields, type FormContext, type Path } from '@bridge/plugin-manager/form';
62
+ import { LogView } from '@bridge/plugin-manager/logs';
63
+ import type { Context } from 'cordis';
64
+
65
+ import {
66
+ everyMsOf,
67
+ intervalParts,
68
+ nextLabel,
69
+ type IntervalUnit,
70
+ type Schedule,
71
+ type TaskState,
72
+ } from '../view.ts';
73
+
74
+ /** A type of action the scheduler lists (`GET /scheduler/actions`). */
75
+ interface ActionMeta {
76
+ type: string;
77
+ title: string;
78
+ description?: string;
79
+ icon?: string;
80
+ input: Record<string, unknown>;
81
+ }
82
+
83
+ /** A choice of an action field (`GET /scheduler/actions/options`). */
84
+ interface ActionOption {
85
+ value: string;
86
+ label: string;
87
+ }
88
+
89
+ /** A task as `GET /scheduler/tasks` answers it. */
90
+ interface ScheduledTaskView {
91
+ scheduledTaskId: string;
92
+ title: string;
93
+ enabled: boolean;
94
+ schedule: Schedule;
95
+ scheduleText: string;
96
+ action: { type: string; input: unknown };
97
+ actionTitle: string;
98
+ available: boolean;
99
+ subject?: { domain: string; id: string };
100
+ state: TaskState;
101
+ runningSince?: string;
102
+ pastDeadline?: boolean;
103
+ suspendedReason?: string;
104
+ failures: number;
105
+ nextRunAt: string | null;
106
+ lastRunStatus: 'never' | 'succeeded' | 'failed' | 'timed_out';
107
+ lastRunAt?: string;
108
+ lastRunError?: string;
109
+ lastRunSummary?: string;
110
+ runCount: number;
111
+ createdBy: string;
112
+ }
113
+
114
+ interface UpdateBody {
115
+ scheduledTaskId: string;
116
+ title?: string;
117
+ schedule?: Schedule;
118
+ enabled?: boolean;
119
+ action?: { type: string; input: unknown };
120
+ }
121
+
122
+ interface CreateBody {
123
+ title?: string;
124
+ schedule: Schedule;
125
+ action: { type: string; input: unknown };
126
+ enabled: boolean;
127
+ }
128
+
129
+ interface ScheduleDraft {
130
+ mode: 'fixed_time' | 'interval';
131
+ time: string;
132
+ weekdays: string[];
133
+ count: string;
134
+ unit: IntervalUnit;
135
+ }
136
+
137
+ /** An action refused by the server, anchored under the field it concerns. */
138
+ interface ActionError {
139
+ path: Path;
140
+ message: string;
141
+ }
142
+
143
+ const WEEKDAYS = [
144
+ { value: '1', label: 'M', title: 'Monday' },
145
+ { value: '2', label: 'T', title: 'Tuesday' },
146
+ { value: '3', label: 'W', title: 'Wednesday' },
147
+ { value: '4', label: 'T', title: 'Thursday' },
148
+ { value: '5', label: 'F', title: 'Friday' },
149
+ { value: '6', label: 'S', title: 'Saturday' },
150
+ { value: '0', label: 'S', title: 'Sunday' },
151
+ ];
152
+
153
+ const UNIT_ITEMS = [
154
+ { value: 'minutes', label: 'minutes' },
155
+ { value: 'hours', label: 'hours' },
156
+ { value: 'days', label: 'days' },
157
+ ];
158
+
159
+ const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
160
+
161
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
162
+
163
+ /** How long ago `iso` was, as a person reads it: "just now", "5 min ago", "3 h ago", "2 d ago", then a date. */
164
+ /** A task's state as a status disc: waiting open, running half-filled, suspended a warning, paused grey. */
165
+ const STATE_ICON = {
166
+ waiting: 'todo',
167
+ running: 'in-progress',
168
+ suspended: 'warning',
169
+ off: 'cancelled',
170
+ } as const;
171
+ const STATE_WORD: Record<TaskState, string> = {
172
+ waiting: 'Waiting',
173
+ running: 'Running',
174
+ suspended: 'Suspended',
175
+ off: 'Paused',
176
+ };
177
+ const LAST_RUN_WORD = { failed: 'Failed', timed_out: 'Timed out', succeeded: 'Succeeded' } as const;
178
+
179
+ const relativeTime = (iso: string): string => {
180
+ const at = Date.parse(iso);
181
+ if (!Number.isFinite(at)) return iso;
182
+ const past = Date.now() - at;
183
+ if (past < 60_000) return 'just now';
184
+ const minutes = Math.floor(past / 60_000);
185
+ if (minutes < 60) return `${minutes} min ago`;
186
+ const hours = Math.floor(minutes / 60);
187
+ if (hours < 24) return `${hours} h ago`;
188
+ const days = Math.floor(hours / 24);
189
+ if (days < 30) return `${days} d ago`;
190
+ return formatDate(at, {
191
+ day: 'numeric',
192
+ month: 'short',
193
+ year: 'numeric',
194
+ });
195
+ };
196
+
197
+ /** The form's fields for a task's schedule, keeping what the other mode would need as the mode changes. */
198
+ const draftOf = (schedule: Schedule): ScheduleDraft => {
199
+ if (schedule.type === 'fixed_time') {
200
+ const days = schedule.weekdays ?? [];
201
+ return {
202
+ mode: 'fixed_time',
203
+ time: schedule.timeOfDay,
204
+ weekdays: days.length === 7 ? [] : days.map(String),
205
+ count: '1',
206
+ unit: 'hours',
207
+ };
208
+ }
209
+ const parts = intervalParts(schedule.everyMs);
210
+ return {
211
+ mode: 'interval',
212
+ time: '09:00',
213
+ weekdays: [],
214
+ count: String(parts.count),
215
+ unit: parts.unit,
216
+ };
217
+ };
218
+
219
+ /** A schedule from the form's fields, or the line that refuses them. */
220
+ const scheduleOf = (draft: ScheduleDraft): { schedule?: Schedule; error?: string } => {
221
+ if (draft.mode === 'fixed_time') {
222
+ if (!TIME.test(draft.time)) return { error: 'Choose a time of day.' };
223
+ const days = [...new Set(draft.weekdays.map(Number))]
224
+ .filter((day) => Number.isInteger(day) && day >= 0 && day <= 6)
225
+ .sort((a, b) => a - b);
226
+ return {
227
+ schedule: {
228
+ type: 'fixed_time',
229
+ timeOfDay: draft.time,
230
+ ...(days.length > 0 && days.length < 7 && { weekdays: days }),
231
+ },
232
+ };
233
+ }
234
+ const count = Number(draft.count);
235
+ if (!Number.isInteger(count) || count < 1)
236
+ return { error: 'Every needs a whole number of at least 1.' };
237
+ const everyMs = everyMsOf({ count, unit: draft.unit });
238
+ if (everyMs < 60_000) return { error: 'An interval is at least 1 minute.' };
239
+ return { schedule: { type: 'interval', everyMs } };
240
+ };
241
+
242
+ /** Every `x-bridge-options` kind below a schema (a property, an item, a map's values). */
243
+ const optionKinds = (schema: unknown): string[] => {
244
+ const found = new Set<string>();
245
+ const visit = (value: unknown) => {
246
+ if (!isRecord(value)) return;
247
+ const kind = value['x-bridge-options'];
248
+ if (typeof kind === 'string') found.add(kind);
249
+ if (isRecord(value.properties)) for (const each of Object.values(value.properties)) visit(each);
250
+ if (isRecord(value.items)) visit(value.items);
251
+ if (isRecord(value.additionalProperties)) visit(value.additionalProperties);
252
+ };
253
+ visit(schema);
254
+ return [...found];
255
+ };
256
+
257
+ /** Whether `path` is the error's anchor or below it. */
258
+ const under = (anchor: Path, path: Path) =>
259
+ anchor.length <= path.length && anchor.every((step, at) => path[at] === step);
260
+
261
+ /** The field a refused action input shows under: its first property, else the action itself. */
262
+ /** Where a refusal of the action's input goes: under the field it names (`prompt: is required`), else the first. */
263
+ const anchorOf = (
264
+ action: { type: string; input: unknown },
265
+ actions: ActionMeta[],
266
+ message = '',
267
+ ): Path => {
268
+ const type = actions.find((each) => each.type === action.type);
269
+ const properties = isRecord(type?.input.properties) ? type.input.properties : {};
270
+ const named = /^(\w+): /.exec(message)?.[1];
271
+ if (named !== undefined && named in properties) return ['input', named];
272
+ const first = Object.keys(properties)[0];
273
+ return first === undefined ? ['input'] : ['input', first];
274
+ };
275
+ /** The required fields of the action's input still empty. */
276
+ const missingOf = (action: { type: string; input: unknown }, actions: ActionMeta[]) => {
277
+ const type = actions.find((each) => each.type === action.type);
278
+ const required = Array.isArray(type?.input.required) ? type.input.required : [];
279
+ const input = isRecord(action.input) ? action.input : {};
280
+ return required.filter(
281
+ (key): key is string =>
282
+ typeof key === 'string' && (input[key] === undefined || String(input[key]).trim() === ''),
283
+ );
284
+ };
285
+
286
+ /** The schedule's fields: "At a time" or "Every", each change committed as it is made. */
287
+ function ScheduleFields({
288
+ draft,
289
+ error,
290
+ onDraft,
291
+ onCommit,
292
+ }: {
293
+ draft: ScheduleDraft;
294
+ error: string | undefined;
295
+ onDraft: (draft: ScheduleDraft) => void;
296
+ onCommit: (draft: ScheduleDraft) => void;
297
+ }) {
298
+ const fixed = draft.mode === 'fixed_time';
299
+ const chooseMode = (mode: string) => {
300
+ if (mode !== 'fixed_time' && mode !== 'interval') return;
301
+ const next: ScheduleDraft = {
302
+ ...draft,
303
+ mode: mode === 'interval' ? 'interval' : 'fixed_time',
304
+ };
305
+ onDraft(next);
306
+ onCommit(next);
307
+ };
308
+ return (
309
+ <div className="flex flex-col gap-2">
310
+ <SegmentGroup
311
+ items={[
312
+ { value: 'fixed_time', label: 'At a time' },
313
+ { value: 'interval', label: 'Every' },
314
+ ]}
315
+ value={draft.mode}
316
+ onValueChange={chooseMode}
317
+ aria-label="Kind of schedule"
318
+ />
319
+ {fixed ? (
320
+ <div className="flex flex-wrap items-center gap-2">
321
+ <div className="w-[120px]">
322
+ <Input
323
+ type="time"
324
+ aria-label="Time of day"
325
+ value={draft.time}
326
+ onChange={(event) => onDraft({ ...draft, time: event.currentTarget.value })}
327
+ onBlur={(event) => onCommit({ ...draft, time: event.currentTarget.value })}
328
+ onKeyDown={(event) => {
329
+ if (event.key === 'Enter' && !isComposing(event)) event.currentTarget.blur();
330
+ }}
331
+ />
332
+ </div>
333
+ <ToggleGroup
334
+ aria-label="Days"
335
+ items={WEEKDAYS}
336
+ value={draft.weekdays}
337
+ onValueChange={(weekdays) => {
338
+ const next = { ...draft, weekdays };
339
+ onDraft(next);
340
+ onCommit(next);
341
+ }}
342
+ />
343
+ {draft.weekdays.length === 0 && <span className="text-xs text-muted">Every day</span>}
344
+ </div>
345
+ ) : (
346
+ <div className="flex flex-wrap items-center gap-2">
347
+ <div className="w-[72px]">
348
+ <Input
349
+ type="number"
350
+ min={1}
351
+ step={1}
352
+ aria-label="Every how many"
353
+ value={draft.count}
354
+ onChange={(event) => onDraft({ ...draft, count: event.currentTarget.value })}
355
+ onBlur={(event) => onCommit({ ...draft, count: event.currentTarget.value })}
356
+ onKeyDown={(event) => {
357
+ if (event.key === 'Enter' && !isComposing(event)) event.currentTarget.blur();
358
+ }}
359
+ />
360
+ </div>
361
+ <div className="w-[120px]">
362
+ <Select<IntervalUnit>
363
+ items={Object.fromEntries(UNIT_ITEMS.map((item) => [item.value, item.label]))}
364
+ value={draft.unit}
365
+ onValueChange={(unit) => {
366
+ if (!unit) return;
367
+ const next = { ...draft, unit };
368
+ onDraft(next);
369
+ onCommit(next);
370
+ }}
371
+ >
372
+ <SelectTrigger aria-label="Interval unit">
373
+ <SelectValue />
374
+ </SelectTrigger>
375
+ <SelectContent>
376
+ {UNIT_ITEMS.map((item) => (
377
+ <SelectItem key={item.value} value={item.value}>
378
+ {item.label}
379
+ </SelectItem>
380
+ ))}
381
+ </SelectContent>
382
+ </Select>
383
+ </div>
384
+ </div>
385
+ )}
386
+ {error !== undefined && (
387
+ <p role="alert" className="text-xs text-destructive">
388
+ {error}
389
+ </p>
390
+ )}
391
+ </div>
392
+ );
393
+ }
394
+
395
+ /** The action's type, its description and the fields of its input schema. */
396
+ function ActionFields({
397
+ actions,
398
+ action,
399
+ actionTitle,
400
+ disabled,
401
+ error,
402
+ onType,
403
+ onInput,
404
+ fetchOptions,
405
+ id,
406
+ }: {
407
+ actions: ActionMeta[];
408
+ action: { type: string; input: unknown };
409
+ actionTitle: string;
410
+ disabled: boolean;
411
+ error: ActionError | undefined;
412
+ onType: (type: string) => void;
413
+ onInput: (input: unknown) => void;
414
+ fetchOptions: (type: string, kind: string, input: string) => Promise<ActionOption[]>;
415
+ id: string;
416
+ }) {
417
+ const selected = actions.find((each) => each.type === action.type);
418
+ const byType = React.useMemo(() => new Map(actions.map((each) => [each.type, each])), [actions]);
419
+ const items = React.useMemo(() => {
420
+ const known = Object.fromEntries(actions.map((each) => [each.type, each.title]));
421
+ // The type of a task whose plugin is gone stays named, and can be replaced.
422
+ if (action.type !== '' && known[action.type] === undefined) known[action.type] = actionTitle;
423
+ return known;
424
+ }, [actions, action.type, actionTitle]);
425
+ const kinds = React.useMemo(() => optionKinds(selected?.input), [selected]);
426
+ const key = kinds.join('\n');
427
+ // The input the choices may follow, as text, so a new object with the same fields does not refetch.
428
+ const input = React.useMemo(() => JSON.stringify(action.input ?? {}), [action.input]);
429
+ const [options, setOptions] = React.useState<Record<string, ActionOption[]>>({});
430
+ React.useEffect(() => {
431
+ if (!selected) {
432
+ setOptions({});
433
+ return;
434
+ }
435
+ let live = true;
436
+ // The choices follow what the form holds (the profile, then the model): let the typing rest, latest answer wins.
437
+ const timer = setTimeout(() => {
438
+ void Promise.all(
439
+ kinds.map(async (kind) => [kind, await fetchOptions(selected.type, kind, input)] as const),
440
+ ).then(
441
+ (entries) => {
442
+ if (live) setOptions(Object.fromEntries(entries));
443
+ },
444
+ () => {},
445
+ );
446
+ }, 300);
447
+ return () => {
448
+ live = false;
449
+ clearTimeout(timer);
450
+ };
451
+ }, [selected, key, fetchOptions, input]);
452
+ const formContext: FormContext = {
453
+ disabled,
454
+ errorAt: (path) => (error !== undefined && under(error.path, path) ? error.message : undefined),
455
+ options: (kind) => (options[kind] ?? []).map((each) => each.value),
456
+ optionLabel: (kind, value) => options[kind]?.find((each) => each.value === value)?.label,
457
+ needle: '',
458
+ id,
459
+ };
460
+ return (
461
+ <div className="flex w-full flex-col gap-2">
462
+ <Select<string>
463
+ items={items}
464
+ value={action.type === '' ? null : action.type}
465
+ disabled={disabled}
466
+ onValueChange={(type) => {
467
+ if (type) onType(type);
468
+ }}
469
+ >
470
+ <SelectTrigger aria-label="Action type" className="w-full max-w-[420px]">
471
+ <SelectValue placeholder="Choose an action" />
472
+ </SelectTrigger>
473
+ <SelectContent>
474
+ {Object.entries(items).map(([type, title]) => {
475
+ const icon = byType.get(type)?.icon;
476
+ return (
477
+ <SelectItem key={type} value={type}>
478
+ <span className="flex min-w-0 items-center gap-1.5">
479
+ {icon !== undefined && <Icon name={icon} size={14} />}
480
+ <span className="truncate">{title}</span>
481
+ </span>
482
+ </SelectItem>
483
+ );
484
+ })}
485
+ </SelectContent>
486
+ </Select>
487
+ {action.type !== '' && selected === undefined && (
488
+ <p role="note" className="text-xs text-warning-text">
489
+ Action unavailable: the plugin that provides it is not installed.
490
+ </p>
491
+ )}
492
+ {selected !== undefined ? (
493
+ // The action's own fields, as its plugin declares them (its JSON Schema): boxed apart from the task's.
494
+ <Card aria-label={`${selected.title} settings`} className="w-full">
495
+ <CardHeader className="justify-start gap-1.5">
496
+ {selected.icon !== undefined && (
497
+ <Icon name={selected.icon} size={14} className="text-muted" />
498
+ )}
499
+ <span className="text-sm font-medium">{selected.title}</span>
500
+ </CardHeader>
501
+ {selected.description !== undefined && (
502
+ <p className="mb-3 text-xs leading-[18px] text-muted">{selected.description}</p>
503
+ )}
504
+ <ObjectFields
505
+ schema={selected.input}
506
+ value={action.input}
507
+ onChange={onInput}
508
+ ctx={formContext}
509
+ path={['input']}
510
+ />
511
+ </Card>
512
+ ) : (
513
+ <p className="text-xs text-muted">Choose an action to fill its fields.</p>
514
+ )}
515
+ </div>
516
+ );
517
+ }
518
+
519
+ /** The card of an existing scheduled task, edited in place. */
520
+ function TaskCard({
521
+ task,
522
+ actions,
523
+ update,
524
+ fetchOptions,
525
+ onToggle,
526
+ onRun,
527
+ onResume,
528
+ onDelete,
529
+ logs,
530
+ }: {
531
+ task: ScheduledTaskView;
532
+ /** Where the task's history is read (bridge#209): its workspace's file of the scheduler. */
533
+ logs?:
534
+ | {
535
+ stream: Parameters<typeof LogView>[0]['stream'];
536
+ fetch: (path: string) => Promise<Response>;
537
+ slug: string;
538
+ plugin: string;
539
+ }
540
+ | undefined;
541
+ actions: ActionMeta[];
542
+ update: (body: UpdateBody) => Promise<ScheduledTaskView>;
543
+ fetchOptions: (type: string, kind: string, input: string) => Promise<ActionOption[]>;
544
+ onToggle: (task: ScheduledTaskView, enabled: boolean) => void;
545
+ onRun: (task: ScheduledTaskView) => void;
546
+ onResume: (task: ScheduledTaskView) => void;
547
+ onDelete: () => void;
548
+ }) {
549
+ const { toast } = useToast();
550
+ const [title, setTitle] = React.useState(task.title);
551
+ const [action, setAction] = React.useState(task.action);
552
+ const [draft, setDraft] = React.useState<ScheduleDraft>(() => draftOf(task.schedule));
553
+ const [scheduleError, setScheduleError] = React.useState<string>();
554
+ const [actionError, setActionError] = React.useState<ActionError>();
555
+ const [confirming, setConfirming] = React.useState(false);
556
+ const timer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
557
+
558
+ React.useEffect(
559
+ () => () => {
560
+ if (timer.current !== undefined) clearTimeout(timer.current);
561
+ },
562
+ [],
563
+ );
564
+
565
+ const report = (what: string) => (cause: unknown) =>
566
+ toast({ title: what, description: messageOf(cause), variant: 'error' });
567
+
568
+ const commitTitle = () => {
569
+ const next = title.trim();
570
+ if (next === task.title) {
571
+ setTitle(task.title);
572
+ return;
573
+ }
574
+ if (!next) {
575
+ setTitle(task.title);
576
+ return;
577
+ }
578
+ void update({ scheduledTaskId: task.scheduledTaskId, title: next })
579
+ .then((updated) => setTitle(updated.title))
580
+ .catch((cause) => {
581
+ setTitle(task.title);
582
+ report('Could not rename the scheduled task')(cause);
583
+ });
584
+ };
585
+
586
+ const commitSchedule = (next: ScheduleDraft) => {
587
+ setDraft(next);
588
+ const built = scheduleOf(next);
589
+ if (built.schedule === undefined) {
590
+ setScheduleError(built.error ?? 'Choose when it runs.');
591
+ return;
592
+ }
593
+ setScheduleError(undefined);
594
+ void update({ scheduledTaskId: task.scheduledTaskId, schedule: built.schedule })
595
+ .then((updated) => setDraft(draftOf(updated.schedule)))
596
+ .catch((cause) => setScheduleError(messageOf(cause)));
597
+ };
598
+
599
+ /** Saves the action after the fields rest (600 ms), so typing does not send one request per key. */
600
+ const commitAction = (next: { type: string; input: unknown }) => {
601
+ setAction(next);
602
+ setActionError(undefined);
603
+ if (timer.current !== undefined) clearTimeout(timer.current);
604
+ // A required field left empty is said under it, and nothing is sent until it is filled.
605
+ const missing = missingOf(next, actions)[0];
606
+ if (missing !== undefined) {
607
+ setActionError({ path: ['input', missing], message: 'Required' });
608
+ return;
609
+ }
610
+ timer.current = setTimeout(() => {
611
+ timer.current = undefined;
612
+ void update({ scheduledTaskId: task.scheduledTaskId, action: next })
613
+ .then((updated) => {
614
+ setAction(updated.action);
615
+ setActionError(undefined);
616
+ })
617
+ .catch((cause) =>
618
+ setActionError({
619
+ path: anchorOf(next, actions, messageOf(cause)),
620
+ message: messageOf(cause),
621
+ }),
622
+ );
623
+ }, 600);
624
+ };
625
+
626
+ const lastRun =
627
+ task.lastRunStatus === 'never' || task.lastRunAt === undefined
628
+ ? 'Never run'
629
+ : `${LAST_RUN_WORD[task.lastRunStatus]} · ${relativeTime(task.lastRunAt)}`;
630
+ const creator = task.createdBy === 'person' ? 'You' : 'An agent';
631
+ const [tab, setTab] = React.useState<'details' | 'logs'>('details');
632
+
633
+ return (
634
+ <Detail aria-label={task.title}>
635
+ <DetailHeader>
636
+ <DetailTitle>
637
+ <EditableField
638
+ variant="title"
639
+ aria-label="Scheduled task title"
640
+ placeholder="Scheduled task"
641
+ value={title}
642
+ onChange={setTitle}
643
+ onCommit={commitTitle}
644
+ />
645
+ </DetailTitle>
646
+ <div className="flex shrink-0 items-center gap-1">
647
+ <Button variant="outline" size="sm" onClick={() => onRun(task)}>
648
+ Run now
649
+ </Button>
650
+ <DropdownMenu>
651
+ <DropdownMenuTrigger
652
+ render={<Button variant="ghost" size="icon" aria-label="More actions" />}
653
+ >
654
+ <Icon name="ellipsis" size={16} />
655
+ </DropdownMenuTrigger>
656
+ <DropdownMenuContent align="end">
657
+ <DropdownMenuItem variant="destructive" onSelect={() => setConfirming(true)}>
658
+ <Icon name="trash" size={14} />
659
+ Delete
660
+ </DropdownMenuItem>
661
+ </DropdownMenuContent>
662
+ </DropdownMenu>
663
+ </div>
664
+ </DetailHeader>
665
+ <Tabs value={tab} onValueChange={(value) => setTab(value as 'details' | 'logs')}>
666
+ <TabsList aria-label={`${task.title} views`}>
667
+ <TabsTrigger value="details">Details</TabsTrigger>
668
+ <TabsTrigger value="logs" disabled={!logs}>
669
+ Logs
670
+ </TabsTrigger>
671
+ </TabsList>
672
+ <TabsContent value="logs">
673
+ {logs && tab === 'logs' && (
674
+ <LogView
675
+ stream={logs.stream}
676
+ fetch={logs.fetch}
677
+ params={{
678
+ workspace: logs.slug,
679
+ plugin: logs.plugin,
680
+ subject: `task:${task.scheduledTaskId}`,
681
+ }}
682
+ title={task.title}
683
+ empty="No run yet: each run, and what the scheduler decides for this task, shows here."
684
+ />
685
+ )}
686
+ </TabsContent>
687
+ <TabsContent value="details">
688
+ <Properties>
689
+ <PropertyRow label="Enabled">
690
+ <div className="flex items-center gap-2">
691
+ <Toggle
692
+ checked={task.enabled}
693
+ aria-label={task.enabled ? 'Pause' : 'Resume'}
694
+ onCheckedChange={(enabled) => onToggle(task, enabled)}
695
+ />
696
+ <span className="text-sm text-secondary">{task.enabled ? 'On' : 'Paused'}</span>
697
+ </div>
698
+ </PropertyRow>
699
+ <PropertyRow label="State" tall={task.state === 'suspended'}>
700
+ <div className="flex min-w-0 flex-col gap-1">
701
+ <span className="flex items-center gap-2 text-sm text-secondary">
702
+ <StatusIcon status={STATE_ICON[task.state]} aria-label={STATE_WORD[task.state]} />
703
+ {nextLabel(task)}
704
+ </span>
705
+ {task.state === 'suspended' && (
706
+ <>
707
+ <span className="text-xs text-warning-text">
708
+ {`Stopped after ${task.failures >= 3 ? `${task.failures} failed runs in a row` : 'a failed run'}: ${task.suspendedReason ?? 'its action failed'}`}
709
+ </span>
710
+ <span>
711
+ <Button variant="outline" size="sm" onClick={() => onResume(task)}>
712
+ Resume
713
+ </Button>
714
+ </span>
715
+ </>
716
+ )}
717
+ {task.state === 'off' && task.suspendedReason !== undefined && (
718
+ <span className="text-xs text-warning-text">{`Suspended: ${task.suspendedReason}`}</span>
719
+ )}
720
+ </div>
721
+ </PropertyRow>
722
+ <PropertyRow label="Schedule" tall>
723
+ <ScheduleFields
724
+ draft={draft}
725
+ error={scheduleError}
726
+ onDraft={setDraft}
727
+ onCommit={commitSchedule}
728
+ />
729
+ </PropertyRow>
730
+ <PropertyRow label="Action" tall>
731
+ <ActionFields
732
+ actions={actions}
733
+ action={action}
734
+ actionTitle={task.actionTitle}
735
+ disabled={false}
736
+ error={actionError}
737
+ onType={(type) => {
738
+ if (type !== action.type) commitAction({ type, input: {} });
739
+ }}
740
+ onInput={(input) => commitAction({ type: action.type, input })}
741
+ fetchOptions={fetchOptions}
742
+ id={`scheduler-task-${task.scheduledTaskId}`}
743
+ />
744
+ </PropertyRow>
745
+ <PropertyRow label="Last run" tall>
746
+ <div className="flex flex-col gap-0.5">
747
+ <span className="text-sm text-secondary">{lastRun}</span>
748
+ {task.lastRunError !== undefined && (
749
+ <span className="text-xs text-warning-text">{task.lastRunError}</span>
750
+ )}
751
+ {task.lastRunSummary !== undefined && (
752
+ <span className="text-xs text-muted">{task.lastRunSummary}</span>
753
+ )}
754
+ {task.runCount > 0 && (
755
+ <span className="text-xs text-muted">
756
+ {`Ran ${task.runCount} ${task.runCount === 1 ? 'time' : 'times'}`}
757
+ </span>
758
+ )}
759
+ </div>
760
+ </PropertyRow>
761
+ <PropertyRow label="Created by">
762
+ <span className="text-sm text-secondary">{creator}</span>
763
+ </PropertyRow>
764
+ </Properties>
765
+ </TabsContent>
766
+ </Tabs>
767
+ <Dialog open={confirming} onOpenChange={setConfirming}>
768
+ <DialogContent aria-label="Delete scheduled task" className="w-[440px]">
769
+ <DialogHeader className="px-5 pt-4">
770
+ <DialogTitle className="text-[15px] font-semibold">
771
+ Delete this scheduled task?
772
+ </DialogTitle>
773
+ </DialogHeader>
774
+ <DialogBody className="pb-5">
775
+ <DialogDescription className="m-0 leading-5">It will not run again.</DialogDescription>
776
+ </DialogBody>
777
+ <DialogFooter className="justify-end gap-2 px-5 py-3">
778
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
779
+ <Button
780
+ variant="destructive"
781
+ onClick={() => {
782
+ setConfirming(false);
783
+ onDelete();
784
+ }}
785
+ >
786
+ Delete
787
+ </Button>
788
+ </DialogFooter>
789
+ </DialogContent>
790
+ </Dialog>
791
+ </Detail>
792
+ );
793
+ }
794
+
795
+ /** The card of a scheduled task not made yet: the same fields, a Create button once it is valid. */
796
+ function DraftCard({
797
+ actions,
798
+ onCreate,
799
+ fetchOptions,
800
+ }: {
801
+ actions: ActionMeta[];
802
+ onCreate: (body: CreateBody) => Promise<void>;
803
+ fetchOptions: (type: string, kind: string, input: string) => Promise<ActionOption[]>;
804
+ }) {
805
+ const [title, setTitle] = React.useState('');
806
+ const [enabled, setEnabled] = React.useState(true);
807
+ const [draft, setDraft] = React.useState<ScheduleDraft>({
808
+ mode: 'fixed_time',
809
+ time: '09:00',
810
+ weekdays: ['1', '2', '3', '4', '5'],
811
+ count: '1',
812
+ unit: 'hours',
813
+ });
814
+ const [action, setAction] = React.useState<{ type: string; input: unknown }>({
815
+ type: '',
816
+ input: {},
817
+ });
818
+ const [scheduleError, setScheduleError] = React.useState<string>();
819
+ const [formError, setFormError] = React.useState<string>();
820
+ const [saving, setSaving] = React.useState(false);
821
+
822
+ const commitSchedule = (next: ScheduleDraft) => {
823
+ setDraft(next);
824
+ const built = scheduleOf(next);
825
+ setScheduleError(
826
+ built.schedule === undefined ? (built.error ?? 'Choose when it runs.') : undefined,
827
+ );
828
+ };
829
+
830
+ const built = scheduleOf(draft);
831
+ const valid =
832
+ action.type !== '' && built.schedule !== undefined && missingOf(action, actions).length === 0;
833
+ const [draftError, setDraftError] = React.useState<ActionError>();
834
+
835
+ const create = () => {
836
+ setFormError(undefined);
837
+ const schedule = scheduleOf(draft);
838
+ if (schedule.schedule === undefined) {
839
+ setScheduleError(schedule.error ?? 'Choose when it runs.');
840
+ return;
841
+ }
842
+ if (action.type === '') {
843
+ setFormError('Choose an action.');
844
+ return;
845
+ }
846
+ setSaving(true);
847
+ void onCreate({
848
+ ...(title.trim() !== '' && { title: title.trim() }),
849
+ schedule: schedule.schedule,
850
+ action,
851
+ enabled,
852
+ })
853
+ .catch((cause) => {
854
+ const message = messageOf(cause);
855
+ // A refusal of the action's input goes under its field; anything else under the card.
856
+ if (/^\w+: /.test(message))
857
+ setDraftError({ path: anchorOf(action, actions, message), message });
858
+ else setFormError(message);
859
+ })
860
+ .finally(() => setSaving(false));
861
+ };
862
+
863
+ return (
864
+ <Detail aria-label="New scheduled task">
865
+ <DetailHeader>
866
+ <DetailTitle>
867
+ <EditableField
868
+ variant="title"
869
+ aria-label="Scheduled task title"
870
+ placeholder="New scheduled task"
871
+ value={title}
872
+ onChange={setTitle}
873
+ />
874
+ </DetailTitle>
875
+ <div className="flex shrink-0 items-center gap-1">
876
+ <Button variant="primary" size="sm" disabled={!valid || saving} onClick={create}>
877
+ Create
878
+ </Button>
879
+ </div>
880
+ </DetailHeader>
881
+ <Properties>
882
+ <PropertyRow label="Enabled">
883
+ <div className="flex items-center gap-2">
884
+ <Toggle
885
+ checked={enabled}
886
+ aria-label={enabled ? 'Pause' : 'Resume'}
887
+ onCheckedChange={setEnabled}
888
+ />
889
+ <span className="text-sm text-secondary">{enabled ? 'On' : 'Paused'}</span>
890
+ </div>
891
+ </PropertyRow>
892
+ <PropertyRow label="Schedule" tall>
893
+ <ScheduleFields
894
+ draft={draft}
895
+ error={scheduleError}
896
+ onDraft={setDraft}
897
+ onCommit={commitSchedule}
898
+ />
899
+ </PropertyRow>
900
+ <PropertyRow label="Action" tall>
901
+ <ActionFields
902
+ actions={actions}
903
+ action={action}
904
+ actionTitle={action.type}
905
+ disabled={saving}
906
+ error={draftError}
907
+ onType={(type) => {
908
+ if (type !== action.type) setAction({ type, input: {} });
909
+ setDraftError(undefined);
910
+ }}
911
+ onInput={(input) => {
912
+ setAction({ type: action.type, input });
913
+ setDraftError(undefined);
914
+ }}
915
+ fetchOptions={fetchOptions}
916
+ id="scheduler-task-new"
917
+ />
918
+ </PropertyRow>
919
+ </Properties>
920
+ {formError !== undefined && (
921
+ <p role="alert" className="text-xs text-destructive">
922
+ {formError}
923
+ </p>
924
+ )}
925
+ </Detail>
926
+ );
927
+ }
928
+
929
+ /** Every scheduled task of the workspace: its list, its card, and a draft. */
930
+ export function ScheduledScreen({
931
+ ctx,
932
+ node,
933
+ item,
934
+ }: {
935
+ ctx: Context;
936
+ node: string;
937
+ item: string | undefined;
938
+ }) {
939
+ const { workspace } = ctx;
940
+ const { toast } = useToast();
941
+ // New by Bridge's click rule (research-048): ⌘ beside, ⌥ on a new desk; outside a shell, here.
942
+ const follow = useFollow();
943
+ const openNew = (event: React.MouseEvent) =>
944
+ follow
945
+ ? follow.follow({ item: 'new' }, event)
946
+ : gestureOf(event) === 'here' && ctx.screen.open('new');
947
+ const api = `/${workspace.slug}/api/scheduler`;
948
+ const headers = { 'x-bridge-node': node };
949
+ const postHeaders = { 'content-type': 'application/json', 'x-bridge-node': node };
950
+ const [tasks, setTasks] = React.useState<ScheduledTaskView[]>();
951
+ const [actions, setActions] = React.useState<ActionMeta[]>([]);
952
+ /** The scheduler's key, which names its log file (from `/scheduler/tasks`). */
953
+ const [logPlugin, setLogPlugin] = React.useState<string>();
954
+ const [error, setError] = React.useState<string>();
955
+ // The windows and the breadcrumb name a task by its title, not its id.
956
+ React.useEffect(() => {
957
+ ctx.screen.title?.('new', 'New scheduled task');
958
+ for (const task of tasks ?? []) ctx.screen.title?.(task.scheduledTaskId, task.title);
959
+ }, [ctx, tasks]);
960
+
961
+ const report = React.useCallback(
962
+ (what: string) => (cause: unknown) =>
963
+ toast({ title: what, description: messageOf(cause), variant: 'error' }),
964
+ [toast],
965
+ );
966
+
967
+ const load = React.useCallback(async () => {
968
+ const [tasksRes, actionsRes] = await Promise.all([
969
+ workspace.fetch(`${api}/scheduler/tasks`, { headers }),
970
+ workspace.fetch(`${api}/scheduler/actions`, { headers }),
971
+ ]);
972
+ const taskBody = (await readJson(tasksRes)) as {
973
+ tasks: ScheduledTaskView[];
974
+ logs?: { plugin: string };
975
+ };
976
+ setLogPlugin(taskBody.logs?.plugin);
977
+ const actionBody = (await readJson(actionsRes)) as { actions: ActionMeta[] };
978
+ setTasks(taskBody.tasks);
979
+ setActions(actionBody.actions);
980
+ setError(undefined);
981
+ }, [workspace, api, node]);
982
+
983
+ const fetchOptions = React.useCallback(
984
+ async (type: string, kind: string, input: string): Promise<ActionOption[]> => {
985
+ // `input`: the held input as JSON text already.
986
+ const held = encodeURIComponent(input);
987
+ const res = await workspace.fetch(
988
+ `${api}/scheduler/actions/options?type=${encodeURIComponent(type)}&kind=${encodeURIComponent(kind)}&input=${held}`,
989
+ { headers },
990
+ );
991
+ const body = (await readJson(res)) as { options: ActionOption[] };
992
+ return body.options;
993
+ },
994
+ [workspace, api, node],
995
+ );
996
+
997
+ // Every 15 s, every 2 s while a task runs: its end shows soon after.
998
+ const busy = tasks?.some((task) => task.state === 'running') ?? false;
999
+ React.useEffect(() => {
1000
+ let live = true;
1001
+ const tick = () => {
1002
+ void load().catch((cause) => {
1003
+ if (live) setError(messageOf(cause));
1004
+ });
1005
+ };
1006
+ tick();
1007
+ const every = window.setInterval(tick, busy ? 2_000 : 15_000);
1008
+ window.addEventListener('focus', tick);
1009
+ return () => {
1010
+ live = false;
1011
+ window.clearInterval(every);
1012
+ window.removeEventListener('focus', tick);
1013
+ };
1014
+ }, [load, busy]);
1015
+ // And a second after the earliest planned run (bridge#208): its outcome (or, still running, the 2 s polling) and the
1016
+ // next run show then, not at the next 15 s poll. A timer waits 2³¹−1 ms at most.
1017
+ const due = Math.min(
1018
+ ...(tasks ?? []).map((task) => (task.nextRunAt ? Date.parse(task.nextRunAt) : Infinity)),
1019
+ );
1020
+ React.useEffect(() => {
1021
+ if (!Number.isFinite(due)) return;
1022
+ let live = true;
1023
+ const wait = Math.min(Math.max(0, due - Date.now()) + 1_000, 2_147_483_647);
1024
+ const timer = window.setTimeout(() => {
1025
+ void load().catch((cause) => {
1026
+ if (live) setError(messageOf(cause));
1027
+ });
1028
+ }, wait);
1029
+ return () => {
1030
+ live = false;
1031
+ window.clearTimeout(timer);
1032
+ };
1033
+ }, [load, due]);
1034
+
1035
+ const apply = (updated: ScheduledTaskView) =>
1036
+ setTasks((was) =>
1037
+ was?.map((task) => (task.scheduledTaskId === updated.scheduledTaskId ? updated : task)),
1038
+ );
1039
+
1040
+ const update = async (body: UpdateBody): Promise<ScheduledTaskView> => {
1041
+ const res = await workspace.fetch(`${api}/scheduler/tasks/update`, {
1042
+ method: 'POST',
1043
+ headers: postHeaders,
1044
+ body: JSON.stringify(body),
1045
+ });
1046
+ const updated = (await readJson(res)) as ScheduledTaskView;
1047
+ apply(updated);
1048
+ void load().catch(report('Could not list the scheduled tasks again'));
1049
+ return updated;
1050
+ };
1051
+
1052
+ const toggle = (task: ScheduledTaskView, enabled: boolean) => {
1053
+ const was = { enabled: task.enabled, nextRunAt: task.nextRunAt };
1054
+ setTasks((current) =>
1055
+ current?.map((each) =>
1056
+ each.scheduledTaskId === task.scheduledTaskId
1057
+ ? { ...each, enabled, nextRunAt: enabled ? each.nextRunAt : null }
1058
+ : each,
1059
+ ),
1060
+ );
1061
+ void update({ scheduledTaskId: task.scheduledTaskId, enabled }).catch((cause) => {
1062
+ setTasks((current) =>
1063
+ current?.map((each) =>
1064
+ each.scheduledTaskId === task.scheduledTaskId ? { ...each, ...was } : each,
1065
+ ),
1066
+ );
1067
+ report(
1068
+ enabled ? 'Could not resume the scheduled task' : 'Could not pause the scheduled task',
1069
+ )(cause);
1070
+ });
1071
+ };
1072
+
1073
+ const run = (task: ScheduledTaskView) => {
1074
+ void (async () => {
1075
+ const res = await workspace.fetch(`${api}/scheduler/tasks/run`, {
1076
+ method: 'POST',
1077
+ headers: postHeaders,
1078
+ body: JSON.stringify({ scheduledTaskId: task.scheduledTaskId }),
1079
+ });
1080
+ // The run starts; its outcome shows on the card when it ends.
1081
+ apply((await readJson(res)) as ScheduledTaskView);
1082
+ toast({ title: 'Scheduled task started' });
1083
+ })().catch(report('Could not run the scheduled task'));
1084
+ };
1085
+
1086
+ const resume = (task: ScheduledTaskView) => {
1087
+ void (async () => {
1088
+ const res = await workspace.fetch(`${api}/scheduler/tasks/resume`, {
1089
+ method: 'POST',
1090
+ headers: postHeaders,
1091
+ body: JSON.stringify({ scheduledTaskId: task.scheduledTaskId }),
1092
+ });
1093
+ apply((await readJson(res)) as ScheduledTaskView);
1094
+ })().catch(report('Could not resume the scheduled task'));
1095
+ };
1096
+
1097
+ const remove = (task: ScheduledTaskView) => {
1098
+ void (async () => {
1099
+ const res = await workspace.fetch(`${api}/scheduler/tasks/delete`, {
1100
+ method: 'POST',
1101
+ headers: postHeaders,
1102
+ body: JSON.stringify({ scheduledTaskId: task.scheduledTaskId }),
1103
+ });
1104
+ await readJson(res);
1105
+ setTasks((was) => was?.filter((each) => each.scheduledTaskId !== task.scheduledTaskId));
1106
+ toast({ title: 'Scheduled task deleted' });
1107
+ ctx.screen.open();
1108
+ void load().catch(report('Could not list the scheduled tasks again'));
1109
+ })().catch(report('Could not delete the scheduled task'));
1110
+ };
1111
+
1112
+ const create = async (body: CreateBody) => {
1113
+ const res = await workspace.fetch(`${api}/scheduler/tasks`, {
1114
+ method: 'POST',
1115
+ headers: postHeaders,
1116
+ body: JSON.stringify(body),
1117
+ });
1118
+ const created = (await readJson(res)) as ScheduledTaskView;
1119
+ setTasks((was) => [...(was ?? []), created]);
1120
+ ctx.screen.open(created.scheduledTaskId);
1121
+ void load().catch(report('Could not list the scheduled tasks again'));
1122
+ };
1123
+
1124
+ const selected =
1125
+ item === undefined || item === 'new'
1126
+ ? undefined
1127
+ : tasks?.find((task) => task.scheduledTaskId === item);
1128
+
1129
+ let card: React.ReactNode;
1130
+ if (item === 'new') {
1131
+ card = <DraftCard actions={actions} onCreate={create} fetchOptions={fetchOptions} />;
1132
+ } else if (item === undefined) {
1133
+ card = (
1134
+ <EmptyState fill icon={<Icon name="alarm-clock" size={24} />} title="Select a scheduled task">
1135
+ <p>Choose one from the list, or create a new one with New.</p>
1136
+ </EmptyState>
1137
+ );
1138
+ } else if (tasks === undefined) {
1139
+ card = <EmptyState fill icon={<Icon name="alarm-clock" size={24} />} title="Loading…" />;
1140
+ } else if (selected === undefined) {
1141
+ card = (
1142
+ <EmptyState
1143
+ fill
1144
+ icon={<Icon name="alarm-clock" size={24} />}
1145
+ title="This scheduled task no longer exists"
1146
+ >
1147
+ <p>It was deleted in another window.</p>
1148
+ </EmptyState>
1149
+ );
1150
+ } else {
1151
+ card = (
1152
+ <TaskCard
1153
+ key={selected.scheduledTaskId}
1154
+ task={selected}
1155
+ actions={actions}
1156
+ update={update}
1157
+ fetchOptions={fetchOptions}
1158
+ onToggle={toggle}
1159
+ onRun={run}
1160
+ onResume={resume}
1161
+ onDelete={() => remove(selected)}
1162
+ logs={
1163
+ logPlugin === undefined
1164
+ ? undefined
1165
+ : {
1166
+ stream: workspace.stream as Parameters<typeof LogView>[0]['stream'],
1167
+ fetch: (path) => workspace.fetch(path, { cache: 'no-store' }),
1168
+ slug: workspace.slug,
1169
+ plugin: logPlugin,
1170
+ }
1171
+ }
1172
+ />
1173
+ );
1174
+ }
1175
+
1176
+ const empty = (
1177
+ <EmptyState icon={<Icon name="alarm-clock" size={24} />} title="No scheduled tasks">
1178
+ <p>A task runs an action on a schedule. Ask an agent to schedule one, or create one here.</p>
1179
+ <Button
1180
+ variant="outline"
1181
+ onClick={openNew}
1182
+ onAuxClick={(event) => event.button === 1 && openNew(event)}
1183
+ >
1184
+ <Icon name="plus" size={14} />
1185
+ New
1186
+ </Button>
1187
+ </EmptyState>
1188
+ );
1189
+
1190
+ let body: React.ReactNode;
1191
+ if (error !== undefined && tasks === undefined) {
1192
+ body = (
1193
+ <EmptyState role="alert" icon={<Icon name="alarm-clock" size={24} />} title="Could not load">
1194
+ <p>{error}</p>
1195
+ <Button variant="outline" onClick={() => void load().catch(report('Could not load'))}>
1196
+ Retry
1197
+ </Button>
1198
+ </EmptyState>
1199
+ );
1200
+ } else if (tasks === undefined) {
1201
+ body = <p className="px-4 py-3 text-xs text-muted">Loading…</p>;
1202
+ } else if (tasks.length === 0) {
1203
+ body = empty;
1204
+ } else {
1205
+ body = (
1206
+ <List
1207
+ aria-label="Scheduled tasks"
1208
+ selectionMode="single"
1209
+ selectionFollowsFocus
1210
+ selectedKey={item !== undefined && item !== 'new' ? item : undefined}
1211
+ onSelectionChange={(keys) => {
1212
+ const next = keys[0];
1213
+ if (next !== undefined && next !== item) ctx.screen.open(next);
1214
+ }}
1215
+ >
1216
+ {tasks.map((task) => {
1217
+ const meta = actions.find((each) => each.type === task.action.type);
1218
+ return (
1219
+ <ListItem
1220
+ key={task.scheduledTaskId}
1221
+ value={task.scheduledTaskId}
1222
+ textValue={task.title}
1223
+ size="auto"
1224
+ description={
1225
+ <span className="flex min-w-0 flex-col gap-0.5">
1226
+ <span className="flex min-w-0 items-center gap-1.5">
1227
+ <StatusIcon
1228
+ size="sm"
1229
+ status={STATE_ICON[task.state]}
1230
+ aria-label={STATE_WORD[task.state]}
1231
+ />
1232
+ <span className="truncate">{`${task.scheduleText} · ${nextLabel(task)}`}</span>
1233
+ </span>
1234
+ <span
1235
+ className={
1236
+ task.available
1237
+ ? 'flex min-w-0 items-center gap-1'
1238
+ : 'flex min-w-0 items-center gap-1 text-warning-text'
1239
+ }
1240
+ >
1241
+ {meta?.icon !== undefined && <Icon name={meta.icon} size={12} />}
1242
+ <span className="truncate">
1243
+ {task.available ? task.actionTitle : 'Action unavailable'}
1244
+ </span>
1245
+ </span>
1246
+ </span>
1247
+ }
1248
+ trailing={
1249
+ <span
1250
+ className="flex items-center gap-1"
1251
+ onClick={(event) => event.stopPropagation()}
1252
+ >
1253
+ {(task.state === 'suspended' ||
1254
+ task.lastRunStatus === 'failed' ||
1255
+ task.lastRunStatus === 'timed_out') && (
1256
+ <Tooltip>
1257
+ <TooltipTrigger
1258
+ render={
1259
+ <Button
1260
+ variant="ghost"
1261
+ size="icon-sm"
1262
+ aria-label={
1263
+ task.state === 'suspended' ? 'Suspended' : 'The last run failed'
1264
+ }
1265
+ onClick={(event) => event.stopPropagation()}
1266
+ />
1267
+ }
1268
+ >
1269
+ <Icon name="triangle-alert" size={14} className="text-warning-text" />
1270
+ </TooltipTrigger>
1271
+ <TooltipContent>
1272
+ {task.state === 'suspended'
1273
+ ? `Suspended: ${task.suspendedReason ?? 'its action failed'}`
1274
+ : (task.lastRunError ?? 'The last run failed')}
1275
+ </TooltipContent>
1276
+ </Tooltip>
1277
+ )}
1278
+ <Toggle
1279
+ checked={task.enabled}
1280
+ aria-label={task.enabled ? `Pause ${task.title}` : `Resume ${task.title}`}
1281
+ onClick={(event) => event.stopPropagation()}
1282
+ onCheckedChange={(enabled) => toggle(task, enabled)}
1283
+ />
1284
+ </span>
1285
+ }
1286
+ >
1287
+ <span className="block truncate font-medium">{task.title}</span>
1288
+ </ListItem>
1289
+ );
1290
+ })}
1291
+ </List>
1292
+ );
1293
+ }
1294
+
1295
+ return (
1296
+ <MultiPane
1297
+ storageKey="scheduler/scheduled/list@v1"
1298
+ defaultNavSize="320px"
1299
+ nav={
1300
+ <Pane aria-label="Scheduled tasks">
1301
+ <PaneHeader>
1302
+ <h2 className="min-w-0 flex-1 truncate text-sm font-semibold">Scheduled</h2>
1303
+ <Button
1304
+ variant="ghost"
1305
+ size="sm"
1306
+ onClick={openNew}
1307
+ onAuxClick={(event) => event.button === 1 && openNew(event)}
1308
+ >
1309
+ <Icon name="plus" size={14} />
1310
+ New
1311
+ </Button>
1312
+ </PaneHeader>
1313
+ {/* The rows fit the pane (their titles cut), as the sessions list does. */}
1314
+ <PaneBody viewportClassName="[&>[data-slot=scroll-area-content]]:min-w-0!">
1315
+ {body}
1316
+ </PaneBody>
1317
+ <PaneFooter>
1318
+ {tasks === undefined
1319
+ ? ''
1320
+ : `${tasks.length} ${tasks.length === 1 ? 'scheduled task' : 'scheduled tasks'}`}
1321
+ </PaneFooter>
1322
+ </Pane>
1323
+ }
1324
+ main={card}
1325
+ />
1326
+ );
1327
+ }