Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

39.5 KB
Raw Blame
import React, { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
import { routineRunNote } from '../spendStop';
import { liveWaitOf, runRowState, runWaitsNow, subscribeRunWaits, type RunTone, type RunWait } from '../routineRow';
import type { NotifiedChat } from '../chatTarget';
import { useUndoableDelete } from '../undoDelete';
import { UndoNotice } from './UndoNotice';
import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Sparkles, Trash2 } from 'lucide-react';
import {
  Routine,
  RoutineInput,
  RoutineRun,
  ScheduleForm,
  WEEKDAYS,
  WORK_WEEK,
  channelLabel,
  continuityApi,
  defaultTimeZone,
  emptyScheduleForm,
  firstLine,
  formFromSchedule,
  formatWhen,
  sortMonthDays,
  onContinuity,
  sameDays,
  scheduleFromForm,
  timeZoneOptions,
  zoneLabel,
  zoneOffset,
} from '../continuity';
import { asSchedule, scheduleWords } from '../botActions';
import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
import { SuggestedRoutines } from './SuggestedRoutines';
import { editorProps } from '../escape';
import type { MessageTarget } from './DoneDetail';

const smallBtn =
  'inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
const quietBtn = `${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700`;
const rowSmallBtn = smallBtn.replace('text-[11px]', 'text-xs sm:text-[11px]');
const rowQuietBtn = quietBtn.replace('text-[11px]', 'text-xs sm:text-[11px]');
const inputClass =
  'w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-xs text-zinc-100 placeholder-zinc-600 focus:border-sky-500 focus:outline-none transition-colors';
const labelClass = 'block text-xs font-medium text-zinc-400 mb-1';

/** The "Posts in" choice that keeps a routine in the thread it was set up in. */
const IN_THREAD = '__thread__';

const REPEAT: Array<{ id: ScheduleForm['type']; label: string }> = [
  { id: 'once', label: 'Once' },
  { id: 'daily', label: 'Daily' },
  { id: 'weekly', label: 'Weekly' },
  { id: 'monthly', label: 'Monthly' },
  { id: 'interval', label: 'Every…' },
  { id: 'cron', label: 'Custom' },
];
const MONTH_DAYS = Array.from({ length: 31 }, (_, i) => i + 1);

/** Which routine to show when Space settings opens from a card, and why. */
export interface RoutineFocus {
  id: string;
  mode: 'edit' | 'pause';
  /** Changes each time a card asks, so the same routine can be opened twice. */
  nonce: number;
}

// 26d: `waiting` and `needs_you` take the amber the steps list already uses for an ask; no new colours.
const TONE: Record<RunTone, string> = {
  running: 'bg-sky-500/10 text-sky-300 border-sky-500/20',
  ok: 'bg-teal-400/10 text-ok border-teal-400/20',
  error: 'bg-rose-500/10 text-rose-300 border-rose-500/20',
  skipped: 'bg-zinc-700/30 text-zinc-400 border-zinc-700',
  waiting: 'bg-amber-500/10 text-amber-300 border-amber-500/20',
  needs_you: 'bg-amber-500/10 text-amber-300 border-amber-500/20',
  // 28f: the person's own no is grey, as 28a's "You said no" mark in the chat.
  said_no: 'bg-zinc-700/30 text-zinc-300 border-zinc-500/40',
};

/**
 * 31f: `inHistory` is a History row's badge. While that run is going the card's header badge already says "Running",
 * so the row keeps the box and spinner and says the word to screen readers only. Every other tone keeps its word.
 */
const StatusBadge: React.FC<{ status: string; error?: string | null; wait?: RunWait | null; inHistory?: boolean }> = ({ status, error, wait, inHistory = false }) => {
  const st = runRowState({ status, error }, wait);
  const quiet = inHistory && st.tone === 'running';
  return (
    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${TONE[st.tone]}`} data-run-badge={st.tone}>
      {st.tone === 'running' && <Loader2 size={9} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
      {quiet ? <span className="sr-only">{st.label}</span> : st.label}
    </span>
  );
};

/** On a routine added from one kwant suggested (Automation Discovery). */
export const SuggestedBadge: React.FC = () => (
  <span
    className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border bg-sky-500/10 text-sky-200 border-sky-500/25"
    title="You added this from a suggestion, after you asked for it on a regular rhythm."
  >
    <Sparkles size={9} aria-hidden="true" />
    Suggested for you
  </span>
);

interface FormState {
  kwantId: string;
  channelId: string;
  name: string;
  instructions: string;
  enabled: boolean;
  schedule: ScheduleForm;
}

/** What a routine form starts from when it isn't editing a saved routine (an Accept with edits). */
export type RoutineSeed = Pick<Routine, 'kwant_id' | 'channel_id' | 'name' | 'instructions' | 'schedule'> & { thread_id?: string | null };

export const RoutineForm: React.FC<{
  initial?: Routine;
  /** Prefills a new routine; ignored with `initial`. */
  seed?: RoutineSeed;
  fixedKwantId?: string;
  kwants: Kwant[];
  channels: Channel[];
  onCancel: () => void;
  onSaved: () => void;
  /** Saves instead of creating or updating; `placeChanged` says whether the person picked another place. */
  onSubmit?: (body: RoutineInput, placeChanged: boolean) => Promise<void>;
  submitLabel?: string;
  label?: string;
  /** Hides Enabled (an accepted suggestion starts on). */
  hideEnabled?: boolean;
  /** Shown above the error and buttons. */
  children?: React.ReactNode;
}> = ({ initial, seed, fixedKwantId, kwants, channels, onCancel, onSaved, onSubmit, submitLabel, label, hideEnabled = false, children }) => {
  const uid = useId();
  const base = initial ?? seed;
  const initialChannel = base?.thread_id ? IN_THREAD : base?.channel_id ?? '';
  const initialSchedule = base ? asSchedule(base.schedule) : null;
  const [start] = useState<FormState>(() => ({
    kwantId: base?.kwant_id ?? fixedKwantId ?? kwants[0]?.id ?? '',
    channelId: initialChannel,
    name: base?.name ?? '',
    instructions: base?.instructions ?? '',
    enabled: initial?.enabled ?? true,
    schedule: initialSchedule ? formFromSchedule(initialSchedule) : emptyScheduleForm(),
  }));
  const [f, setF] = useState<FormState>(start);
  // Escape closes an untouched form and keeps one with changes (and Settings around it) open.
  const unsaved = JSON.stringify(f) !== JSON.stringify(start);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const s = f.schedule;
  // Routines setup D: the zone shows as a city with Change; a zone Intl doesn't know starts open, so what's saved shows.
  const [tzOpen, setTzOpen] = useState(() => !s.tz.trim() || zoneOffset(s.tz) === null);
  const tzRef = useRef<HTMLInputElement>(null);
  const openTz = () => {
    setTzOpen(true);
    // Focus on a frame, not after render (kept): only Change (a click) calls this, and React renders that update before the next frame
    requestAnimationFrame(() => tzRef.current?.focus());
  };
  const setS = (patch: Partial<ScheduleForm>) => setF((prev) => ({ ...prev, schedule: { ...prev.schedule, ...patch } }));

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!f.name.trim()) return setError('Give the routine a name.');
    if (!f.instructions.trim()) return setError('Say what the bot should do.');
    if (!f.kwantId) return setError('Pick a bot.');
    const built = scheduleFromForm(s);
    if ('error' in built) return setError(built.error);
    setSaving(true);
    setError(null);
    const body = {
      kwant_id: f.kwantId,
      channel_id: f.channelId === IN_THREAD ? null : f.channelId || null,
      name: f.name.trim(),
      instructions: f.instructions.trim(),
      schedule: built.schedule,
      enabled: f.enabled,
    };
    try {
      if (onSubmit) await onSubmit(body, f.channelId !== initialChannel);
      else if (initial) {
        // Sending the place again would move a follow-up out of its thread and forget what it
        // checks back on, so it only goes when the person picked another one.
        const { channel_id, ...rest } = body;
        await continuityApi.updateRoutine(initial.id, f.channelId === initialChannel ? rest : { ...rest, channel_id });
      } else await continuityApi.createRoutine(body);
      playSfx('coin');
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Saving failed.');
      setSaving(false);
    }
  };

  const id = (k: string) => `${uid}-${k}`;

  return (
    <form onSubmit={submit} noValidate {...editorProps(unsaved, onCancel)} className="p-3 rounded-xl border border-sky-500/30 bg-zinc-950/70 space-y-3" aria-label={label ?? (initial ? `Edit ${initial.name}` : 'New routine')}>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <div>
          <label htmlFor={id('name')} className={labelClass}>Name</label>
          <input id={id('name')} value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} placeholder="Competitor prices" className={inputClass} autoFocus />
        </div>
        {!fixedKwantId && (
          <div>
            <label htmlFor={id('kwant')} className={labelClass}>Bot</label>
            <select id={id('kwant')} value={f.kwantId} onChange={(e) => setF({ ...f, kwantId: e.target.value })} className={inputClass}>
              {kwants.map((k) => (
                <option key={k.id} value={k.id}>{k.name}</option>
              ))}
            </select>
          </div>
        )}
        <div>
          <label htmlFor={id('channel')} className={labelClass}>Posts in</label>
          <select id={id('channel')} value={f.channelId} onChange={(e) => setF({ ...f, channelId: e.target.value })} className={inputClass}>
            {base?.thread_id && <option value={IN_THREAD}>The thread it was set up in</option>}
            <option value="">Direct chat with the bot</option>
            {channels.map((c) => (
              <option key={c.id} value={c.id}>{channelLabel(c.name)}</option>
            ))}
          </select>
        </div>
      </div>

      <div>
        <label htmlFor={id('instr')} className={labelClass}>What to do</label>
        <textarea
          id={id('instr')}
          rows={3}
          value={f.instructions}
          onChange={(e) => setF({ ...f, instructions: e.target.value })}
          placeholder="Check our 3 competitors' prices and tell me what changed since last time."
          className={`${inputClass} resize-y`}
        />
      </div>

      <fieldset className="space-y-2">
        <legend className={labelClass}>When</legend>
        <div className="grid grid-cols-3 sm:grid-cols-6 gap-1 p-1 bg-zinc-950 rounded-lg border border-zinc-800" role="radiogroup" aria-label="Repeat">
          {REPEAT.map((t) => (
            <button
              key={t.id}
              type="button"
              role="radio"
              aria-checked={s.type === t.id}
              onClick={() => setS({ type: t.id })}
              className={`min-h-10 sm:min-h-0 py-1.5 sm:py-1 rounded-md text-[11px] font-medium transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${s.type === t.id ? 'bg-sky-500/15 text-sky-200' : 'text-zinc-500 hover:text-zinc-300'}`}
            >
              {t.label}
            </button>
          ))}
        </div>

        {s.type === 'once' && (
          <div>
            <label htmlFor={id('at')} className="sr-only">Date and time</label>
            <input id={id('at')} type="datetime-local" value={s.onceAt} onChange={(e) => setS({ onceAt: e.target.value })} className={inputClass} />
            <p className="mt-1 text-[11px] text-zinc-500">In your time zone ({zoneLabel(defaultTimeZone())}). Turns itself off after it runs.</p>
          </div>
        )}

        {s.type === 'cron' && (
          <div>
            <label htmlFor={id('cron')} className="text-[11px] text-zinc-500">Rule</label>
            <input
              id={id('cron')}
              value={s.cron}
              onChange={(e) => setS({ cron: e.target.value })}
              placeholder="0 9 * * MON#2"
              spellCheck={false}
              autoCapitalize="off"
              aria-describedby={id('cron-hint')}
              className={`${inputClass} font-mono`}
            />
            <p id={id('cron-hint')} className="mt-1 text-[11px] text-zinc-500 leading-relaxed">
              Five parts: minute, hour, day of month, month, weekday. <span className="font-mono text-zinc-400">0 9 * * MON#2</span> is 09:00 on the
              second Monday; <span className="font-mono text-zinc-400">0 18 L * *</span> is 18:00 on the last day of the month.
            </p>
          </div>
        )}

        {(s.type === 'daily' || s.type === 'weekly' || s.type === 'monthly' || s.type === 'cron') && (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {s.type !== 'cron' && (
              <div>
                <label htmlFor={id('time')} className="text-[11px] text-zinc-500">At</label>
                <input id={id('time')} type="time" value={s.time} onChange={(e) => setS({ time: e.target.value })} className={inputClass} />
              </div>
            )}
            {tzOpen ? (
              <div>
                <label htmlFor={id('tz')} className="text-[11px] text-zinc-500">Time zone</label>
                <input ref={tzRef} id={id('tz')} list={id('tzs')} value={s.tz} onChange={(e) => setS({ tz: e.target.value })} className={inputClass} spellCheck={false} />
                <datalist id={id('tzs')}>
                  {timeZoneOptions(s.tz).map((z) => (
                    <option key={z} value={z} />
                  ))}
                </datalist>
              </div>
            ) : (
              <div>
                <span id={id('tz-label')} className="text-[11px] text-zinc-500">Time zone</span>
                <div className="min-h-11 sm:min-h-[34px] flex items-center gap-2 text-sm sm:text-xs" title={s.tz} role="group" aria-labelledby={id('tz-label')} data-tz-row>
                  <span className="text-zinc-100">{zoneLabel(s.tz)}</span>
                  {zoneOffset(s.tz) && <span className="text-zinc-400">{zoneOffset(s.tz)}</span>}
                  <button
                    type="button"
                    onClick={openTz}
                    aria-label={`Change time zone, now ${zoneLabel(s.tz)}`}
                    className="ml-auto rounded font-medium text-sky-300 hover:text-sky-200 kw-focus kw-hit"
                    data-tz-change
                  >
                    Change
                  </button>
                </div>
              </div>
            )}
          </div>
        )}

        {s.type === 'weekly' && (
          <div className="flex flex-col gap-1 sm:flex-row sm:flex-wrap sm:items-center" role="group" aria-label="Days">
            <div className="grid grid-cols-7 gap-1 sm:flex sm:flex-wrap">
              {WEEKDAYS.map((d) => {
                const on = s.weekdays.includes(d.id);
                return (
                  <button
                    key={d.id}
                    type="button"
                    aria-pressed={on}
                    onClick={() => setS({ weekdays: on ? s.weekdays.filter((w) => w !== d.id) : [...s.weekdays, d.id] })}
                    className={`min-h-11 sm:min-h-0 px-1 sm:px-2 py-1 rounded-md text-[11px] font-medium border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
                      on ? 'border-sky-500/50 bg-sky-500/15 text-sky-200' : 'border-zinc-800 text-zinc-500 hover:text-zinc-300'
                    }`}
                  >
                    {d.label}
                  </button>
                );
              })}
            </div>
            <span className="hidden sm:block w-px h-[18px] mx-1 bg-white/[0.14]" aria-hidden="true" />
            {(() => {
              const on = sameDays(s.weekdays, WORK_WEEK);
              return (
                <button
                  type="button"
                  aria-pressed={on}
                  aria-label="Weekdays, Monday to Friday"
                  onClick={() => !on && setS({ weekdays: [...WORK_WEEK] })}
                  className={`self-start min-h-11 sm:min-h-0 px-3.5 sm:px-2 py-1 rounded-md text-[11px] font-medium border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
                    on ? 'border-sky-500/50 bg-sky-500/15 text-sky-200' : 'border-dashed border-zinc-700 text-zinc-300 hover:text-zinc-100'
                  }`}
                  data-weekdays-chip
                >
                  Weekdays<span className="sm:hidden"> (Mon–Fri)</span>
                </button>
              );
            })()}
          </div>
        )}

        {s.type === 'monthly' && (
          <div className="space-y-1">
            <div className="grid grid-cols-7 gap-1" role="group" aria-label="Days of the month">
              {MONTH_DAYS.map((d) => {
                const on = s.monthDays.includes(d);
                return (
                  <button
                    key={d}
                    type="button"
                    aria-pressed={on}
                    onClick={() => setS({ monthDays: on ? s.monthDays.filter((x) => x !== d) : sortMonthDays([...s.monthDays, d]) })}
                    className={`min-h-[32px] rounded-md text-[11px] font-medium border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
                      on ? 'border-sky-500/50 bg-sky-500/15 text-sky-200' : 'border-zinc-800 text-zinc-500 hover:text-zinc-300'
                    }`}
                  >
                    {d}
                  </button>
                );
              })}
              <button
                type="button"
                aria-pressed={s.monthDays.includes('last')}
                onClick={() =>
                  setS({ monthDays: s.monthDays.includes('last') ? s.monthDays.filter((x) => x !== 'last') : sortMonthDays([...s.monthDays, 'last']) })
                }
                className={`col-span-4 min-h-[32px] rounded-md text-[11px] font-medium border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 ${
                  s.monthDays.includes('last') ? 'border-sky-500/50 bg-sky-500/15 text-sky-200' : 'border-zinc-800 text-zinc-500 hover:text-zinc-300'
                }`}
              >
                Last day
              </button>
            </div>
            <p className="text-[11px] text-zinc-500">A day a month doesn't have, like the 31st in April, runs on that month's last day.</p>
          </div>
        )}

        {s.type === 'interval' && (
          <div className="flex items-center gap-2">
            <label htmlFor={id('every')} className="text-[11px] text-zinc-500 shrink-0">Every</label>
            <input
              id={id('every')}
              type="number"
              min={5}
              max={10080}
              step={5}
              value={s.everyMinutes}
              onChange={(e) => setS({ everyMinutes: e.target.value })}
              className={`${inputClass} w-24`}
            />
            <span className="text-[11px] text-zinc-500">minutes (5 to 10080)</span>
          </div>
        )}
      </fieldset>

      {!hideEnabled && (
        <label className="flex items-center gap-2 text-[11px] text-zinc-300">
          <input type="checkbox" checked={f.enabled} onChange={(e) => setF({ ...f, enabled: e.target.checked })} className="accent-sky-500" />
          Enabled
        </label>
      )}

      {children}

      {error && (
        <p className="text-[11px] text-rose-400 flex items-center gap-1.5" role="alert">
          <AlertTriangle size={12} /> {error}
        </p>
      )}
      <div className="flex justify-end gap-2">
        <button type="button" onClick={onCancel} className="px-3 py-1.5 rounded-lg text-xs font-medium text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 transition-colors">
          Cancel
        </button>
        <button type="submit" disabled={saving} className="px-3.5 py-1.5 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-700 transition-colors disabled:opacity-50">
          {saving ? 'Saving…' : submitLabel ?? (initial ? 'Save routine' : 'Create routine')}
        </button>
      </div>
    </form>
  );
};

/** Phone: 44 px, centred, one line each, so the four buttons share one row at 390 px. */
const rowBtn = 'min-h-11 sm:min-h-0 justify-center whitespace-nowrap';

/** "Mon, Nov 9": the card's last run, date only; the time is in History. */
const lastRanDate = (iso: string | null | undefined): string | null => {
  if (!iso) return null;
  const d = new Date(iso);
  return Number.isNaN(d.getTime()) ? null : d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
};

/** 0.9.5 F: where a run's result message lives, for its History row's link. */
export const runResultTarget = (routine: Routine, run: RoutineRun): MessageTarget | null =>
  run.message_id ? { message_id: run.message_id, channel_id: routine.channel_id, kwant_id: routine.kwant_id, thread_id: routine.thread_id ?? null } : null;

/** 26d: a run's card, for "Open the card" on a run that waits (or waited) on it. */
export const runCardTarget = (routine: Routine, cardId: string): NotifiedChat => ({
  channel_id: routine.channel_id,
  kwant_id: routine.kwant_id,
  thread_id: routine.thread_id ?? null,
  card_id: cardId,
});

/** One run in History: badge, when, how it started, Open the card (26d), Open result and the run's note. */
export const RunRow: React.FC<{
  routine: Routine;
  run: RoutineRun;
  wait?: RunWait | null;
  onOpenRunResult?: (t: MessageTarget) => void;
  onOpenRunCard?: (t: NotifiedChat) => void;
}> = ({ routine, run: r, wait, onOpenRunResult, onOpenRunCard }) => {
  const st = runRowState(r, wait);
  const t = onOpenRunResult ? runResultTarget(routine, r) : null;
  const card = onOpenRunCard && st.cardId ? st.cardId : null;
  const note = routineRunNote(r);
  const link = 'kw-focus kw-hit inline-flex items-center gap-0.5 rounded font-semibold text-info hover:text-sky-200';
  return (
    <li className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-zinc-400" data-run-row={r.id} data-run-state={st.tone}>
      <StatusBadge status={r.status} error={r.error} wait={wait} inHistory />
      <span>{formatWhen(r.started_at)}</span>
      <span className="text-zinc-400">{r.trigger === 'manual' ? 'Run now' : 'Scheduled'}</span>
      {/* Mira re-check 6: on a phone the links always sit on their own line under the badge. */}
      {(t || card) && <span className="basis-full h-0 sm:hidden" aria-hidden="true" />}
      {card && (
        <button
          type="button"
          onClick={() => onOpenRunCard!(runCardTarget(routine, card))}
          className={link}
          aria-label={`Open the approval card the run on ${formatWhen(r.started_at)} ${st.tone === 'waiting' ? 'waits on' : 'waited on'}`}
          data-compact
          data-run-card={card}
        >
          Open the card <ChevronRight size={11} aria-hidden="true" />
        </button>
      )}
      {t && (
        <button
          type="button"
          onClick={() => onOpenRunResult!(t)}
          className={link}
          aria-label={`Open the result of the run on ${formatWhen(r.started_at)}`}
          data-compact
          data-run-result={r.id}
        >
          Open result <ChevronRight size={11} aria-hidden="true" />
        </button>
      )}
      {note && <span className={`basis-full min-w-0 [overflow-wrap:anywhere] ${note.quiet ? 'text-zinc-400' : 'text-rose-300/90'}`}>{note.text}</span>}
    </li>
  );
};

const RunHistory: React.FC<{
  routine: Routine;
  tick: number;
  waits: Record<string, RunWait>;
  onOpenRunResult?: (t: MessageTarget) => void;
  onOpenRunCard?: (t: NotifiedChat) => void;
}> = ({ routine, tick, waits, onOpenRunResult, onOpenRunCard }) => {
  const routineId = routine.id;
  const [runs, setRuns] = useState<RoutineRun[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    let cancelled = false;
    continuityApi.routineRuns(routineId).then(
      (r) => !cancelled && (setRuns(r), setError(null)),
      (e) => !cancelled && setError(e instanceof Error ? e.message : 'Could not load runs.'),
    );
    return () => {
      cancelled = true;
    };
  }, [routineId, tick]);
  if (error) return <p className="text-[11px] text-rose-400" role="alert">{error}</p>;
  if (!runs) return <p className="text-[11px] text-zinc-500" role="status">Loading runs…</p>;
  if (runs.length === 0) return <p className="text-[11px] text-zinc-500">No runs yet.</p>;
  return (
    <ol className="space-y-1" aria-label="Run history">
      {runs.map((r) => (
        <RunRow key={r.id} routine={routine} run={r} wait={waits[r.id]} onOpenRunResult={onOpenRunResult} onOpenRunCard={onOpenRunCard} />
      ))}
    </ol>
  );
};

const NO_WAITS: Record<string, RunWait> = {};

export const RoutineRow: React.FC<{
  routine: Routine;
  kwantName?: string;
  placeLabel: string;
  tick: number;
  /** Opened from a card's Pause: scrolls here, focuses the switch and says how to pause. */
  focusPause?: number;
  onEdit: () => void;
  /** 0.9.5 F: History rows link to each run's result message. */
  onOpenRunResult?: (t: MessageTarget) => void;
  /** 26d: live waits by run id, and where "Open the card" goes. */
  waits?: Record<string, RunWait>;
  onOpenRunCard?: (t: NotifiedChat) => void;
  onChanged: () => void;
  /** Tests: start in the Undo window. */
  initialPending?: boolean;
}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onOpenRunResult, waits = NO_WAITS, onOpenRunCard, onChanged, initialPending = false }) => {
  const rowRef = useRef<HTMLLIElement>(null);
  const switchRef = useRef<HTMLInputElement>(null);
  const [highlight, setHighlight] = useState(false);
  useEffect(() => {
    if (!focusPause) return;
    rowRef.current?.scrollIntoView({ block: 'center', behavior: 'smooth' });
    switchRef.current?.focus({ preventScroll: true });
    setHighlight(true);
  }, [focusPause]);
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [notice, setNotice] = useState<string | null>(null);
  const historyId = useId();
  const removal = useUndoableDelete(onChanged, initialPending);

  const act = async (fn: () => Promise<unknown>) => {
    setBusy(true);
    setError(null);
    try {
      await fn();
      onChanged();
    } catch (e) {
      setError(e instanceof Error ? e.message : 'That failed.');
    } finally {
      setBusy(false);
    }
  };

  const runNow = () =>
    act(async () => {
      const run = await continuityApi.runRoutine(routine.id);
      setNotice(run.status === 'skipped' ? 'Already running; this one was skipped.' : 'Started.');
      setOpen(true);
      playSfx('click');
    });

  const what = firstLine(routine.instructions);
  const lastRan = lastRanDate(routine.last_run_at);

  if (removal.pending) return <UndoNotice as="li" text={`Deleted “${routine.name}”. It won’t run again.`} onUndo={removal.undo} />;

  return (
    <li ref={rowRef} className={`rounded-xl border bg-zinc-950/60 p-3 space-y-2 ${highlight ? 'border-sky-500/60 ring-1 ring-sky-500/30' : 'border-zinc-800'}`}>
      <div className="flex items-start gap-2.5">
        <label className="relative inline-flex items-center p-1 -m-1 mt-0 cursor-pointer" title={routine.enabled ? 'Turn off' : 'Turn on'}>
          <input
            type="checkbox"
            role="switch"
            ref={switchRef}
            className="sr-only peer"
            checked={routine.enabled}
            disabled={busy}
            aria-label={`${routine.name} enabled`}
            onChange={(e) => act(() => continuityApi.updateRoutine(routine.id, { enabled: e.target.checked }))}
          />
          <span className="w-7 h-4 rounded-full bg-zinc-700 peer-checked:bg-sky-600 peer-focus-visible:outline peer-focus-visible:outline-2 peer-focus-visible:outline-sky-500 transition-colors" />
          <span className="absolute left-1.5 top-1.5 w-3 h-3 rounded-full bg-white transition-transform motion-reduce:transition-none peer-checked:translate-x-3" />
        </label>
        <div className="flex-1 min-w-0">
          <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
            <span className={`text-xs font-medium break-words ${routine.enabled ? 'text-zinc-100' : 'text-zinc-400'}`}>{routine.name}</span>
            {routine.origin === 'discovery' && <SuggestedBadge />}
            {routine.last_status && <StatusBadge status={routine.last_status} error={routine.last_error ?? null} wait={liveWaitOf(waits, routine.id)} />}
          </div>
          {/* Routines setup F: what it does, then when it runs next, then the schedule, bot and place. */}
          {what.line && (
            <p className={`text-xs leading-[18px] truncate ${routine.enabled ? 'text-zinc-200' : 'text-zinc-400'}`} title={routine.instructions} data-routine-what>
              {what.line}
              {what.more ? ' …' : ''}
            </p>
          )}
          <p className="text-[11px] text-zinc-400" data-routine-next>
            {routine.enabled ? (
              <>
                Next <span className="text-zinc-100 font-medium">{formatWhen(routine.next_run_at)}</span>
              </>
            ) : (
              <span className="text-zinc-300 font-medium">Paused</span>
            )}
            {lastRan && <span className="hidden sm:inline"> · last ran {lastRan}</span>}
          </p>
          <p className="text-[11px] text-zinc-500 break-words">
            <span title={routine.schedule_text || undefined}>{scheduleWords(routine.schedule, routine.schedule_text)}</span>
            {kwantName ? ` · ${kwantName}` : ''} · {placeLabel}
            {lastRan && <span className="sm:hidden"> · last ran {lastRan}</span>}
          </p>
        </div>
      </div>
      {/* Phone: four 44 px buttons in one row, no indent, so Delete never wraps. Desktop is as before. */}
      <div className="grid grid-cols-4 gap-1.5 sm:flex sm:flex-wrap sm:items-center sm:pl-9">
        <button type="button" onClick={runNow} disabled={busy} className={`${rowSmallBtn} ${rowBtn} border-sky-500/40 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20`}>
          <Play size={11} aria-hidden="true" /> Run now
        </button>
        <button type="button" onClick={() => setOpen((v) => !v)} aria-expanded={open} aria-controls={historyId} className={`${rowQuietBtn} ${rowBtn}`}>
          <span className="hidden sm:inline-flex" aria-hidden="true">{open ? <ChevronDown size={11} /> : <ChevronRight size={11} />}</span> <History size={11} aria-hidden="true" /> History
        </button>
        <button type="button" onClick={onEdit} className={`${rowQuietBtn} ${rowBtn}`} data-routine-edit={routine.id}>
          <Pencil size={11} aria-hidden="true" /> Edit
        </button>
        <button
          type="button"
          disabled={busy}
          onClick={() => removal.start(() => continuityApi.removeRoutine(routine.id))}
          className={`${rowSmallBtn} ${rowBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200`}
        >
          <Trash2 size={11} aria-hidden="true" /> Delete
        </button>
        {notice && <span className="col-span-4 text-[11px] text-zinc-400" role="status">{notice}</span>}
        {highlight && routine.enabled && !notice && (
          <span className="col-span-4 text-[11px] text-sky-200" role="status">Turn the switch off to pause it.</span>
        )}
      </div>
      {(error ?? removal.error) && <p className="pl-9 text-[11px] text-rose-400" role="alert">{error ?? `Couldn’t delete it: ${removal.error}`}</p>}
      {open && (
        <div id={historyId} className="pl-9 pt-1">
          <RunHistory routine={routine} tick={tick} waits={waits} onOpenRunResult={onOpenRunResult} onOpenRunCard={onOpenRunCard} />
        </div>
      )}
    </li>
  );
};

/**
 * Routines for one kwant (`kwantId`) or for everyone. Live: refetches on `routine_run`. The
 * everyone list also shows the routines kwant suggests (Automation Discovery) on top.
 */
export const RoutinesPanel: React.FC<{
  kwantId?: string;
  kwants: Kwant[];
  channels: Channel[];
  focus?: RoutineFocus | null;
  /** Opens app Settings, where suggestions are turned on. */
  onOpenSettings?: () => void;
  /** 0.9.5 F: a History row's Open result. */
  onOpenRunResult?: (t: MessageTarget) => void;
  /** 26d: a waiting run's "Open the card": the routine's chat at its approval card. */
  onOpenRunCard?: (t: NotifiedChat) => void;
}> = ({ kwantId, kwants, channels, focus, onOpenSettings, onOpenRunResult, onOpenRunCard }) => {
  const [routines, setRoutines] = useState<Routine[] | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [editing, setEditing] = useState<Routine | 'new' | null>(null);
  const [tick, setTick] = useState(0);
  // 26d: which runs wait on an approval card right now, by run id. App records the live `routine_run` events even
  // while this panel is closed (routineRow.recordRunWait), so a wait that began earlier still shows.
  const waits = useSyncExternalStore(subscribeRunWaits, runWaitsNow, runWaitsNow);

  const reload = useCallback(async () => {
    try {
      const all = await continuityApi.routines();
      setRoutines(kwantId ? all.filter((r) => r.kwant_id === kwantId) : all);
      setLoadError(null);
    } catch (e) {
      setLoadError(e instanceof Error ? e.message : 'Could not load routines.');
    }
  }, [kwantId]);

  useEffect(() => {
    reload();
    return onContinuity('routine_run', () => {
      reload();
      setTick((t) => t + 1);
    });
  }, [reload]);

  // A card's Edit opens that routine's form; Pause points at its switch.
  const [missing, setMissing] = useState(false);
  const handled = useRef<number | null>(null);
  useEffect(() => {
    if (!focus || !routines || handled.current === focus.nonce) return;
    handled.current = focus.nonce;
    const r = routines.find((x) => x.id === focus.id);
    setMissing(!r);
    if (r && focus.mode === 'edit') setEditing(r);
  }, [focus, routines]);

  const kwantName = (id: string) => kwants.find((k) => k.id === id)?.name;
  const place = (r: Routine) => {
    if (r.thread_id) return 'a thread';
    if (!r.channel_id) return 'direct chat';
    const c = channels.find((ch) => ch.id === r.channel_id);
    return c ? channelLabel(c.name) : 'a deleted channel';
  };
  const saved = () => {
    setEditing(null);
    reload();
  };
  // A form that closes (Escape, Cancel, Save) gives focus back to New routine or the routine's Edit.
  const wrapRef = useRef<HTMLDivElement>(null);
  const wasEditing = useRef<Routine | 'new' | null>(null);
  useEffect(() => {
    const was = wasEditing.current;
    wasEditing.current = editing;
    const a = document.activeElement;
    if (editing || !was || (a && a !== document.body && a.isConnected)) return;
    wrapRef.current?.querySelector<HTMLElement>(was === 'new' ? '[data-routine-new]' : `[data-routine-edit="${was.id}"]`)?.focus();
  }, [editing]);

  // The empty card only once routines loaded; a load error keeps today's rose box instead.
  const empty = !!routines && routines.length === 0 && !loadError;
  // Over a list, or after a load error (so New routine stays reachable); not while loading, so it never flickers away.
  const showTop = (!!routines && routines.length > 0) || !!loadError;

  return (
    <div ref={wrapRef} className="space-y-3">
      {/* Routines setup B: with nothing saved, the empty card below leads; the top row only shows over a list. */}
      {showTop && (
        <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <p className="text-[11px] text-zinc-500 leading-relaxed">A routine has a bot do something on a schedule. Its answer lands where you chose.</p>
          {editing !== 'new' && (
            <button
              type="button"
              onClick={() => setEditing('new')}
              disabled={kwants.length === 0}
              data-routine-new
              className={`${smallBtn} shrink-0 justify-center min-h-11 sm:min-h-0 border-sky-500/50 bg-sky-600 text-white hover:bg-sky-700`}
            >
              <Plus size={11} aria-hidden="true" /> New routine
            </button>
          )}
        </div>
      )}

      {editing === 'new' && (
        <RoutineForm fixedKwantId={kwantId} kwants={kwants} channels={channels} onCancel={() => setEditing(null)} onSaved={saved} />
      )}

      {loadError && (
        <div className="flex items-center justify-between gap-2 bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs" role="alert">
          <span>{loadError}</span>
          <button type="button" onClick={reload} className={quietBtn}>
            <RefreshCw size={12} /> Retry
          </button>
        </div>
      )}
      {!routines && !loadError && (
        <p className="flex items-center gap-2 text-xs text-zinc-400" role="status">
          <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading routines…
        </p>
      )}
      {missing && (
        <p className="text-[11px] text-amber-200 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2" role="status">
          That routine no longer exists. It may have been undone or deleted.
        </p>
      )}
      {empty && editing !== 'new' && (
        <div className="rounded-2xl border border-dashed border-white/[0.12] px-6 py-7 flex flex-col items-center text-center gap-3" data-routines-empty>
          <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-accent-soft text-sky-200" aria-hidden="true">
            <CalendarClock size={20} />
          </span>
          <p className="text-sm leading-[21px] text-zinc-200 max-w-[420px]">
            A routine has a bot do something for you on a schedule, like checking competitors' prices every Monday.
          </p>
          <button
            type="button"
            onClick={() => setEditing('new')}
            disabled={kwants.length === 0}
            data-routine-new
            className="inline-flex h-11 w-full items-center justify-center gap-1.5 rounded-xl bg-accent-gradient kw-hover-deepen px-4 text-sm font-semibold text-white disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300 focus-visible:ring-offset-2 focus-visible:ring-offset-[#120e26] sm:h-9 sm:w-auto"
          >
            <Plus size={15} aria-hidden="true" /> New routine
          </button>
        </div>
      )}
      {routines && routines.length > 0 && (
        <ul className="space-y-2" aria-label="Routines">
          {routines.map((r) =>
            editing !== 'new' && editing?.id === r.id ? (
              <li key={r.id}>
                <RoutineForm initial={r} fixedKwantId={kwantId} kwants={kwants} channels={channels} onCancel={() => setEditing(null)} onSaved={saved} />
              </li>
            ) : (
              <RoutineRow
                key={r.id}
                routine={r}
                kwantName={kwantId ? undefined : kwantName(r.kwant_id) ?? 'deleted bot'}
                placeLabel={place(r)}
                tick={tick}
                focusPause={focus?.mode === 'pause' && focus.id === r.id ? focus.nonce : undefined}
                onEdit={() => setEditing(r)}
                onOpenRunResult={onOpenRunResult}
                waits={waits}
                onOpenRunCard={onOpenRunCard}
                onChanged={reload}
              />
            ),
          )}
        </ul>
      )}

      {/* Suggestions come after what's saved (B3). */}
      {!kwantId && (
        <div className="mt-3">
          <SuggestedRoutines kwants={kwants} channels={channels} onAccepted={reload} onOpenSettings={onOpenSettings} />
        </div>
      )}
    </div>
  );
};