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.

Automation Discovery step 4: suggested routines screens

Pixel (kwant bot)ace3ed4622e9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5cab9c83..9a609806 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
suggested routine keeps it marked as suggested. Exports now carry a routine's class and acceptance,
and its checks when they hold no secrets. This is step 3 of Automation Discovery; the screens come
next.
+- **Suggested routines in Routines, and a switch in Settings.** Settings > Mission board has "Suggest
+ routines from repeated tasks" (off by default) and how many new suggestions a day (0–10). Routines
+ lists each suggestion with its bot, rhythm, first run, the tasks it learned from (with their days),
+ what the bot may do when it runs (its Flight School tier, when it asks you, what past runs changed),
+ and which checks it keeps or leaves out and why. Accept opens the routine form to edit it first,
+ then says when it first runs; checks can only be unticked, and masked check details are never
+ editable. Dismiss says the suggestion is hidden for 30 days. If it was already handled elsewhere, the
+ list refreshes and says so. Preview and Scan now show what was found and, in plain words, why other
+ repeated tasks weren't suggested. When suggestions are paused (the switch or the board is off, or no
+ time zone is set), the section says why and how to fix it. Routines added this way carry a
+ "Suggested for you" badge, a small line shows the last 30 days, and "A routine was suggested" joins
+ the notification toggles. This is step 4 of Automation Discovery.
### Changed
- **kwant.si footer says "Made in Germany with ❤️".** The line sits under the trademark note on every
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index a67bb892..653e4464 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -344,17 +344,20 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const showNotification = (n: NotifyEvent) => {
// Another space's news is the shell's to show, with a way to switch there.
if (n.space_id && n.space_id !== space.id) return;
+ if (n.kind === 'automation_suggested') emitContinuity({ type: 'automation_suggested', data: n });
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
// Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
- if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
const id = ++toastIdRef.current;
const action =
n.kind === 'routine_failed'
? undefined
: n.kind === 'skill_proposed'
? { label: 'Review', onClick: () => openSkillsRef.current(n.kwant_id) }
- : n.kind === 'question_asked'
+ : n.kind === 'automation_suggested'
+ ? { label: 'Review', onClick: () => setIsRoutinesOpen(true) }
+ : n.kind === 'question_asked'
? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openTargetRef.current(target) }
: n.kind === 'human_step'
? { label: 'Open', onClick: () => openHumanStepRef.current(n.kwant_id) || openTargetRef.current(target) }
@@ -370,6 +373,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const openNotified = (n: Pick<NotifyEvent, 'kind' | 'kwant_id' | 'channel_id'>) => {
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
if (n.kind === 'skill_proposed') openSkillsRef.current(n.kwant_id);
+ // A suggested routine is decided in Routines, not in the bot's chat
+ else if (n.kind === 'automation_suggested') setIsRoutinesOpen(true);
else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) {
setIsVmPaneOpen(true);
// A CAPTCHA lands straight in the solve view
@@ -3214,7 +3219,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}}
/>
{isSearchOpen && <SearchModal isOpen onClose={() => setIsSearchOpen(false)} kwants={kwants} onJump={handleJump} />}
- {isRoutinesOpen && <RoutinesModal isOpen onClose={() => setIsRoutinesOpen(false)} kwants={kwants} channels={channels} />}
+ {isRoutinesOpen && <RoutinesModal isOpen onClose={() => setIsRoutinesOpen(false)} kwants={kwants} channels={channels} onOpenSettings={onOpenAppSettings} />}
</Suspense>
{editingChannelInstructions && (
diff --git a/frontend/src/automationDiscovery.ts b/frontend/src/automationDiscovery.ts
new file mode 100644
index 00000000..a45cb092
--- /dev/null
+++ b/frontend/src/automationDiscovery.ts
@@ -0,0 +1,389 @@
+// Automation Discovery (Mission Control Phase D4, docs/mission-control.md §20): kwant notices a
+// board task the person asks for on a regular rhythm and suggests a routine for it. Nothing is
+// created until the person accepts; every route here is the person's only.
+
+import { PersonCancelledError, personFetch } from './auth';
+import type { Routine, RoutineInput, Schedule } from './continuity';
+import { type Check, type CheckKind, checkKindLabel, checkTarget } from './missions';
+
+export type DiscoveryBlock = 'off' | 'board_off' | 'no_timezone';
+export type SuggestionStatus = 'offered' | 'accepted' | 'dismissed' | 'expired' | 'superseded';
+export type DiscoveryPattern = 'monthly' | 'weekly' | 'weekdays' | 'daily';
+
+export interface DiscoveryCheck {
+ kind: string;
+ /** Secrets are already masked; never sent back. */
+ spec: unknown;
+ required: boolean;
+}
+
+export interface LeftOutCheck {
+ kind: string;
+ spec: unknown;
+ reason: string;
+}
+
+export interface ChainStep {
+ key: string;
+ title: string;
+ kwant_id: string | null;
+ /** Same bot: a step of the routine. Another bot: only mentioned. */
+ in_instructions: boolean;
+ after: number;
+}
+
+export interface DiscoverySource {
+ task_id: string;
+ title: string;
+ /** The person's local day and time of the ask. */
+ local_date: string;
+ local_time: string;
+ state: string;
+}
+
+export interface DiscoveryEvidence {
+ pattern: DiscoveryPattern;
+ matched: number;
+ expected: number;
+ coverage: number;
+ precision: number;
+ verified: number;
+ settled: number;
+ total: number;
+ time_spread: string;
+ time_varies: boolean;
+ last_ask_at: string;
+}
+
+export interface DiscoveryPermissions {
+ flight_school: boolean;
+ tier: 'observe' | 'sandbox' | 'act';
+ tier_from: string;
+ tier_label: string;
+ approval_mode: 'ask' | 'smart' | 'off';
+ payments_ask: boolean;
+ past: { external: number; workspace: number; needed_ok: number };
+}
+
+export interface Suggestion {
+ id: string;
+ space_id: string;
+ cluster_key: string;
+ kwant_id: string;
+ name: string;
+ instructions: string;
+ schedule: Schedule;
+ schedule_text: string;
+ first_run_at: string;
+ first_run_text: string;
+ delivery: { channel_id?: string; thread_id?: string; direct_kwant_id?: string };
+ task_class: string;
+ acceptance: string;
+ checks: DiscoveryCheck[];
+ left_out_checks: LeftOutCheck[];
+ chain: ChainStep[];
+ source_task_ids: string[];
+ sources: DiscoverySource[];
+ time_spread: string;
+ evidence: DiscoveryEvidence;
+ permissions: DiscoveryPermissions;
+ status: SuggestionStatus;
+ routine_id: string | null;
+ cooldown_until: string | null;
+ offered_at: string;
+ decided_at: string | null;
+}
+
+export interface DiscoveryStats {
+ offered_30d: number;
+ accepted_30d: number;
+ dismissed_30d: number;
+ retained: number;
+ dropped: number;
+}
+
+export interface DiscoveryList {
+ setting: 'on' | 'off';
+ daily_cap: number;
+ blocked_by: DiscoveryBlock[];
+ last_scan_at: string | null;
+ suggestions: Suggestion[];
+ stats: DiscoveryStats;
+}
+
+export interface SkippedHabit {
+ cluster_key: string;
+ title: string;
+ asks: number;
+ reason: string;
+}
+
+/** A `?preview=1` offer: what would be suggested, never stored. */
+export interface PreviewOffer {
+ cluster_key: string;
+ kwant_id: string;
+ name: string;
+ schedule: Schedule;
+ first_run_text: string;
+ evidence: DiscoveryEvidence;
+}
+
+export interface ScanResult {
+ blocked_by: DiscoveryBlock | null;
+ preview: boolean;
+ timezone?: string;
+ offered: Array<Suggestion | PreviewOffer>;
+ skipped: SkippedHabit[];
+ expired?: string[];
+ superseded?: string[];
+}
+
+/** What Accept may change; anything left out stays as suggested. Checks can only be dropped. */
+export interface AcceptEdits {
+ name?: string;
+ instructions?: string;
+ schedule?: Schedule;
+ kwant_id?: string;
+ /** `null`: the bot's direct chat. */
+ channel_id?: string | null;
+ acceptance?: string | null;
+ /** Indexes into the suggestion's checks to keep. */
+ keep_checks?: number[];
+}
+
+export interface Accepted {
+ suggestion: Suggestion;
+ routine: Routine;
+ first_run_text: string | null;
+}
+
+export class DiscoveryError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ /** On a 409: what already happened to it, and its routine when it was accepted. */
+ public current: { status: string; routine_id: string | null } | null = null,
+ ) {
+ super(message);
+ }
+}
+
+const sentence = (s: string) => {
+ const t = s.trim();
+ if (!t) return t;
+ const c = t[0].toUpperCase() + t.slice(1);
+ return /[.!?]$/.test(c) ? c : `${c}.`;
+};
+
+export function discoveryErrorFrom(status: number, answer: unknown): DiscoveryError {
+ const a = answer && typeof answer === 'object' ? (answer as Record<string, unknown>) : {};
+ const err = typeof a.error === 'string' && a.error.trim() ? sentence(a.error) : null;
+ if (status === 403) return new DiscoveryError('Only you can act on suggested routines.', 403);
+ if (status === 409) {
+ const current = { status: typeof a.status === 'string' ? a.status : '', routine_id: typeof a.routine_id === 'string' ? a.routine_id : null };
+ return new DiscoveryError(alreadyHandledText(current.status), 409, current);
+ }
+ if (status === 404) return new DiscoveryError(err && !/not found/i.test(err) ? err : 'That suggestion no longer exists.', 404);
+ return new DiscoveryError(err ?? `Something went wrong (HTTP ${status}).`, status);
+}
+
+/** The 409 in the person's words: someone (often another tab) already decided it. */
+export function alreadyHandledText(status: string): string {
+ switch (status) {
+ case 'accepted':
+ return 'Already added. It’s in your routines below.';
+ case 'dismissed':
+ return 'Already dismissed.';
+ case 'expired':
+ return 'This suggestion has expired: the habit no longer fits a schedule.';
+ case 'superseded':
+ return 'This suggestion was updated. The list now shows the new one.';
+ default:
+ return 'This suggestion was already handled.';
+ }
+}
+
+async function call<T>(url: string, method = 'GET', body?: unknown, extra?: Record<string, string>): Promise<T> {
+ let res: Response;
+ const headers = { ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...extra };
+ try {
+ res = await personFetch(url, {
+ method,
+ cache: 'no-store',
+ headers: Object.keys(headers).length ? headers : undefined,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new DiscoveryError(e.message, 401);
+ throw new DiscoveryError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const answer = await res.json().catch(() => null);
+ if (res.ok) return answer as T;
+ throw discoveryErrorFrom(res.status, answer);
+}
+
+const enc = encodeURIComponent;
+const BASE = '/api/automation-discovery';
+
+export const discoveryApi = {
+ /** The space comes from the fetch wrapper's `?space=`. */
+ list: (status: SuggestionStatus | 'all' = 'offered') => call<DiscoveryList>(`${BASE}?status=${enc(status)}`),
+ scan: (preview = false) => call<ScanResult>(`${BASE}/scan${preview ? '?preview=1' : ''}`, 'POST'),
+ /** `key` is one per Accept intent: a retry or a double press sends the same one. */
+ accept: (id: string, key: string, edits?: AcceptEdits) =>
+ call<Accepted>(`${BASE}/${enc(id)}/accept`, 'POST', edits && Object.keys(edits).length ? edits : undefined, { 'Idempotency-Key': key }),
+ dismiss: (id: string) => call<{ suggestion: Suggestion }>(`${BASE}/${enc(id)}/dismiss`, 'POST'),
+};
+
+/** Keys sorted, so the same schedule written in another order compares equal. */
+const canonical = (v: unknown): string =>
+ JSON.stringify(v, (_k, x) => (x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x));
+
+/**
+ * The Accept body for what the person changed in the form: only the fields that differ from the
+ * suggestion (an empty object accepts it as it is), and `keep_checks` only when one was unticked.
+ */
+export function acceptEdits(s: Suggestion, body: RoutineInput, placeChanged: boolean, keep: boolean[]): AcceptEdits {
+ const out: AcceptEdits = {};
+ if (body.name.trim() !== s.name) out.name = body.name.trim();
+ if (body.instructions.trim() !== s.instructions.trim()) out.instructions = body.instructions.trim();
+ if (canonical(body.schedule) !== canonical(s.schedule)) out.schedule = body.schedule;
+ if (body.kwant_id !== s.kwant_id) out.kwant_id = body.kwant_id;
+ if (placeChanged) out.channel_id = body.channel_id;
+ if (keep.length === s.checks.length && keep.some((k) => !k)) out.keep_checks = keep.flatMap((k, i) => (k ? [i] : []));
+ return out;
+}
+
+/**
+ * One Idempotency-Key per Accept intent: the same key until the server answers for good (a 2xx or a
+ * refusal it will repeat), so a retry after a dropped connection or a double press can't add a second
+ * routine. A new intent (after a refusal the person fixes, or another card) gets a new key.
+ */
+export class AcceptIntent {
+ private key: string | null = null;
+ constructor(private make: () => string) {}
+ current(): string {
+ this.key ??= this.make();
+ return this.key;
+ }
+ /** After an answer that isn't worth retrying with the same key. */
+ settle(err: unknown) {
+ // Network errors (0) and server errors (5xx) may have gone through: keep the key so the retry replays
+ const status = err instanceof DiscoveryError ? err.status : 0;
+ if (status !== 0 && status < 500) this.key = null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// In the person's words
+
+export const BLOCK_TEXT: Record<DiscoveryBlock, { title: string; fix: string }> = {
+ off: {
+ title: 'Suggestions are off.',
+ fix: 'Turn on “Suggest routines from repeated tasks” in Settings, under Mission board.',
+ },
+ board_off: {
+ title: 'Suggestions learn from tasks on the Mission board, and the board is off.',
+ fix: 'Turn on “Show the Mission board” in Settings.',
+ },
+ no_timezone: {
+ title: 'Your time zone isn’t set, so there’s no telling what time you usually ask.',
+ fix: 'Set your time zone in Settings, under Where you are.',
+ },
+};
+
+export const blockText = (b: string) => BLOCK_TEXT[b as DiscoveryBlock] ?? { title: 'Suggestions can’t run right now.', fix: 'Check Settings.' };
+
+const SKIP_TEXT: Record<string, string> = {
+ too_short: 'Not enough asks yet to see a rhythm',
+ not_regular: 'No regular rhythm',
+ stopped: 'You stopped asking for it',
+ not_verified: 'Too few of these tasks passed their checks',
+ mixed_owners: 'Different bots did it, so there’s no one bot to suggest',
+ bot_unavailable: 'The bot that did it isn’t in this space any more',
+ covered: 'A routine already does this',
+ cooling_off: 'You dismissed it, or deleted its routine, in the last 30 days',
+ already_offered: 'Already suggested',
+ in_chain: 'It’s a follow-up step of another suggestion',
+ capped: 'Waiting: today’s limit of new suggestions is reached',
+};
+
+export const skipText = (reason: string) => SKIP_TEXT[reason] ?? reason.replace(/_/g, ' ');
+
+const PATTERN_TEXT: Record<DiscoveryPattern, string> = {
+ monthly: 'once a month',
+ weekly: 'every week',
+ weekdays: 'on weekdays',
+ daily: 'every day',
+};
+
+/** "You asked for this 5 times, every week, usually around 09:10." */
+export function habitLine(e: DiscoveryEvidence | undefined | null): string {
+ if (!e) return '';
+ const times = e.matched === 1 ? 'once' : `${e.matched} times`;
+ const rhythm = PATTERN_TEXT[e.pattern] ? `, ${PATTERN_TEXT[e.pattern]}` : '';
+ const when = e.time_spread ? (e.time_spread.includes('–') ? `, usually between ${e.time_spread.replace('–', ' and ')}` : `, usually around ${e.time_spread}`) : '';
+ return `You asked for this ${times}${rhythm}${when}${e.time_varies ? ' (the time varies)' : ''}.`;
+}
+
+const APPROVAL_TEXT: Record<string, string> = {
+ ask: 'Asks you before actions that need approval',
+ smart: 'Asks you only when an action is risky',
+ off: 'Doesn’t ask before actions (approvals are off for this bot)',
+};
+export const approvalText = (m: string) => APPROVAL_TEXT[m] ?? APPROVAL_TEXT.ask;
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+/** "In past runs: 2 outside actions, 1 workspace change; needed your OK twice." */
+export function pastText(p: DiscoveryPermissions['past'] | undefined): string {
+ if (!p) return '';
+ const did = [p.external ? plural(p.external, 'outside action') : '', p.workspace ? plural(p.workspace, 'workspace change') : ''].filter(Boolean);
+ const ok = p.needed_ok ? `needed your OK ${p.needed_ok === 1 ? 'once' : p.needed_ok === 2 ? 'twice' : `${p.needed_ok} times`}` : 'never needed your OK';
+ return did.length ? `In past runs: ${did.join(', ')}; ${ok}.` : `In past runs it changed nothing outside its chat, and ${ok}.`;
+}
+
+/** A kept or left-out check on one line, from its masked spec: shown only, never editable. */
+export function checkLine(c: { kind: string; spec: unknown }): string {
+ const spec = c.spec && typeof c.spec === 'object' && !Array.isArray(c.spec) ? (c.spec as Record<string, unknown>) : {};
+ const target = checkTarget({ kind: c.kind as CheckKind, spec } as Pick<Check, 'kind' | 'spec'>);
+ return target ? `${checkKindLabel(c.kind)}: ${target}` : checkKindLabel(c.kind);
+}
+
+const LEFT_OUT_TEXT: Record<string, string> = {
+ 'needs a person or a reviewer': 'Needs you or a teammate to look, so it can’t run on a schedule',
+ 'changes every time': 'It was different every time',
+ 'passed only once': 'It passed only once',
+ 'more than 10 checks': 'A routine keeps at most 10 checks',
+};
+export const leftOutText = (reason: string) => LEFT_OUT_TEXT[reason] ?? sentence(reason).replace(/\.$/, '');
+
+/** "Last 30 days: 3 suggested, 1 added, 1 dismissed. Still on after 14 days: 1 of 2." */
+export function statsLine(s: DiscoveryStats | undefined | null): string {
+ if (!s) return '';
+ const parts = `Last 30 days: ${s.offered_30d} suggested, ${s.accepted_30d} added, ${s.dismissed_30d} dismissed.`;
+ const judged = s.retained + s.dropped;
+ return judged ? `${parts} Still on 14 days after adding: ${s.retained} of ${judged}.` : parts;
+}
+
+/** A source ask's day: "Mon 12 Oct". Local dates come as YYYY-MM-DD in the person's zone. */
+export function sourceDay(localDate: string): string {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(localDate);
+ if (!m) return localDate;
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
+ return d.toLocaleDateString(undefined, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' });
+}
+
+/** The automation_discovery settings, or null on a server without them. */
+export function parseDiscoverySettings(data: unknown): { automation_discovery: 'on' | 'off'; automation_discovery_daily_cap: number } | null {
+ if (!data || typeof data !== 'object') return null;
+ const d = data as Record<string, unknown>;
+ if (d.automation_discovery !== 'on' && d.automation_discovery !== 'off') return null;
+ const cap = typeof d.automation_discovery_daily_cap === 'number' && Number.isInteger(d.automation_discovery_daily_cap) ? d.automation_discovery_daily_cap : 2;
+ return { automation_discovery: d.automation_discovery, automation_discovery_daily_cap: Math.min(10, Math.max(0, cap)) };
+}
+
+export const DISCOVERY_CAPS = Array.from({ length: 11 }, (_, i) => i);
+
+/** Fired after Settings saves the discovery setting, so an open Routines list checks again. */
+export const DISCOVERY_SETTING_EVENT = 'kwnt:automation-discovery-setting';
diff --git a/frontend/src/components/RoutinesModal.tsx b/frontend/src/components/RoutinesModal.tsx
index 962246b0..f7050c15 100644
--- a/frontend/src/components/RoutinesModal.tsx
+++ b/frontend/src/components/RoutinesModal.tsx
@@ -5,11 +5,12 @@ import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
/** Every kwant's routines in one list. */
-export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwants: Kwant[]; channels: Channel[] }> = ({
+export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwants: Kwant[]; channels: Channel[]; onOpenSettings?: () => void }> = ({
isOpen,
onClose,
kwants,
channels,
+ onOpenSettings,
}) => {
const closeRef = useRef(onClose);
closeRef.current = onClose;
@@ -51,7 +52,7 @@ export const RoutinesModal: React.FC<{ isOpen: boolean; onClose: () => void; kwa
<X size={18} />
</button>
</div>
- <RoutinesPanel kwants={kwants} channels={channels} />
+ <RoutinesPanel kwants={kwants} channels={channels} onOpenSettings={onOpenSettings} />
</div>
</div>
);
diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsx
index b8624de2..a63bd651 100644
--- a/frontend/src/components/RoutinesPanel.tsx
+++ b/frontend/src/components/RoutinesPanel.tsx
@@ -1,9 +1,10 @@
import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
import { useUndoableDelete } from '../undoDelete';
import { UndoNotice } from './UndoNotice';
-import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Trash2 } from 'lucide-react';
+import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Sparkles, Trash2 } from 'lucide-react';
import {
Routine,
+ RoutineInput,
RoutineRun,
RunStatus,
ScheduleForm,
@@ -22,6 +23,7 @@ import {
import { asSchedule, scheduleWords } from '../botActions';
import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
+import { SuggestedRoutines } from './SuggestedRoutines';
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';
@@ -65,6 +67,17 @@ const StatusBadge: React.FC<{ status: RunStatus }> = ({ status }) => (
</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-violet-500/10 text-violet-200 border-violet-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;
@@ -74,22 +87,36 @@ interface FormState {
schedule: ScheduleForm;
}
-const RoutineForm: React.FC<{
+/** 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;
-}> = ({ initial, fixedKwantId, kwants, channels, onCancel, onSaved }) => {
+ /** 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 initialChannel = initial?.thread_id ? IN_THREAD : initial?.channel_id ?? '';
- const initialSchedule = initial ? asSchedule(initial.schedule) : null;
+ const base = initial ?? seed;
+ const initialChannel = base?.thread_id ? IN_THREAD : base?.channel_id ?? '';
+ const initialSchedule = base ? asSchedule(base.schedule) : null;
const [f, setF] = useState<FormState>(() => ({
- kwantId: initial?.kwant_id ?? fixedKwantId ?? kwants[0]?.id ?? '',
+ kwantId: base?.kwant_id ?? fixedKwantId ?? kwants[0]?.id ?? '',
channelId: initialChannel,
- name: initial?.name ?? '',
- instructions: initial?.instructions ?? '',
+ name: base?.name ?? '',
+ instructions: base?.instructions ?? '',
enabled: initial?.enabled ?? true,
schedule: initialSchedule ? formFromSchedule(initialSchedule) : emptyScheduleForm(),
}));
@@ -116,7 +143,8 @@ const RoutineForm: React.FC<{
enabled: f.enabled,
};
try {
- if (initial) {
+ 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;
@@ -133,7 +161,7 @@ const RoutineForm: React.FC<{
const id = (k: string) => `${uid}-${k}`;
return (
- <form onSubmit={submit} noValidate className="p-3 rounded-xl border border-sky-500/30 bg-zinc-950/70 space-y-3" aria-label={initial ? `Edit ${initial.name}` : 'New routine'}>
+ <form onSubmit={submit} noValidate 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>
@@ -152,7 +180,7 @@ const RoutineForm: React.FC<{
<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}>
- {initial?.thread_id && <option value={IN_THREAD}>The thread it was set up in</option>}
+ {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>
@@ -313,10 +341,14 @@ const RoutineForm: React.FC<{
)}
</fieldset>
- <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>
+ {!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">
@@ -328,7 +360,7 @@ const RoutineForm: React.FC<{
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-500 transition-colors disabled:opacity-50">
- {saving ? 'Saving…' : initial ? 'Save routine' : 'Create routine'}
+ {saving ? 'Saving…' : submitLabel ?? (initial ? 'Save routine' : 'Create routine')}
</button>
</div>
</form>
@@ -436,6 +468,7 @@ export const RoutineRow: React.FC<{
<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 text-zinc-100 break-words">{routine.name}</span>
+ {routine.origin === 'discovery' && <SuggestedBadge />}
{routine.last_status && <StatusBadge status={routine.last_status} />}
</div>
<p className="text-[11px] text-zinc-500 break-words">
@@ -481,13 +514,18 @@ export const RoutineRow: React.FC<{
);
};
-/** Routines for one kwant (`kwantId`) or for everyone. Live: refetches on `routine_run`. */
-export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channels: Channel[]; focus?: RoutineFocus | null }> = ({
- kwantId,
- kwants,
- channels,
- focus,
-}) => {
+/**
+ * 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;
+}> = ({ kwantId, kwants, channels, focus, onOpenSettings }) => {
const [routines, setRoutines] = useState<Routine[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [editing, setEditing] = useState<Routine | 'new' | null>(null);
@@ -552,6 +590,8 @@ export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channe
)}
</div>
+ {!kwantId && <SuggestedRoutines kwants={kwants} channels={channels} onAccepted={reload} onOpenSettings={onOpenSettings} />}
+
{editing === 'new' && (
<RoutineForm fixedKwantId={kwantId} kwants={kwants} channels={channels} onCancel={() => setEditing(null)} onSaved={saved} />
)}
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 20c35a32..e9f9a117 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -49,6 +49,7 @@ import {
requestLimitFrom,
} from '../missions';
import { FlightSchoolSettings, TIERS, TIER_HINTS, TIER_LABELS, Tier, parseFlightSchoolSettings } from '../flightSchool';
+import { DISCOVERY_CAPS, DISCOVERY_SETTING_EVENT, parseDiscoverySettings } from '../automationDiscovery';
const RECOVERY_PCTS = [0, 10, 25, 50, 100];
@@ -243,6 +244,48 @@ interface SettingsModalProps {
/** App settings: shared by every space (keys, Laya, limits, notifications, sounds). Accounts,
* bots and tools are per space, in Space settings. */
+type DiscoverySettings = NonNullable<ReturnType<typeof parseDiscoverySettings>>;
+
+/** Automation Discovery: off until the person turns it on; suggestions only, never a routine on its own. */
+const DiscoverySetting: React.FC<{ value: DiscoverySettings; onChange: (v: DiscoverySettings) => void }> = ({ value, onChange }) => {
+ const on = value.automation_discovery === 'on';
+ const cap = value.automation_discovery_daily_cap;
+ return (
+ <SwitchRow
+ id="automation-discovery"
+ label="Suggest routines from repeated tasks"
+ hint="When you ask for the same task on the board on a regular rhythm, you get a suggested routine for it, with the bot, the time and the checks it would keep. Nothing is set up until you accept it in Routines. It learns only from board tasks you created, never from chats."
+ checked={on}
+ onToggle={() => onChange({ ...value, automation_discovery: on ? 'off' : 'on' })}
+ >
+ {on && (
+ <div className="mt-2 flex flex-wrap items-center gap-2" data-testid="automation-discovery-options">
+ <label htmlFor="automation-discovery-cap" className="text-[11px] text-zinc-300">
+ At most
+ </label>
+ <select
+ id="automation-discovery-cap"
+ value={cap}
+ onChange={(e) => onChange({ ...value, automation_discovery_daily_cap: Number(e.target.value) })}
+ aria-describedby="automation-discovery-cap-hint"
+ className="bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none"
+ >
+ {DISCOVERY_CAPS.map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ <span className="text-[11px] text-zinc-300">new {cap === 1 ? 'suggestion' : 'suggestions'} a day</span>
+ <p id="automation-discovery-cap-hint" className="basis-full text-[11px] text-zinc-500">
+ {cap === 0 ? 'With 0, it still looks but suggests nothing new; Scan now in Routines shows what it found.' : 'More waiting suggestions come on later days.'}
+ </p>
+ </div>
+ )}
+ </SwitchRow>
+ );
+};
+
export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0 }) => {
const { authRequired, deviceLogin, signOut } = useAuth();
const computer = useComputerMode(isOpen);
@@ -271,6 +314,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
const [auditor, setAuditor] = useState<AuditorSettings | null>(null);
// null on a server without Flight School: the switch stays hidden and out of the save
const [flightSchool, setFlightSchool] = useState<FlightSchoolSettings | null>(null);
+ const [discovery, setDiscovery] = useState<DiscoverySettings | null>(null);
// null until loaded, and on a server without these settings
const [place, setPlace] = useState<{ timezone: string; location: string } | null>(null);
const [webhookUrl, setWebhookUrl] = useState('');
@@ -345,6 +389,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
setAutofix(parseAutofixSettings(data));
setAuditor(parseAuditorSettings(data));
setFlightSchool(parseFlightSchoolSettings(data));
+ setDiscovery(parseDiscoverySettings(data));
setPlace(
typeof data.timezone === 'string'
? { timezone: data.timezone || defaultTimeZone(), location: typeof data.location === 'string' ? data.location : '' }
@@ -413,7 +458,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
openai_api_key: openaiKey,
ollama_url: ollamaUrl,
notify_webhook_url: webhookUrl.trim(),
- notify_on: notifyOnToSave(notifyOn, appUpdates, !!proactive),
+ notify_on: notifyOnToSave(notifyOn, appUpdates, !!proactive, !!discovery),
...(limits
? {
max_turns_per_agent: Number(limits.max_turns_per_agent),
@@ -429,6 +474,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
...(autofix !== null ? { autofix: autofix.autofix, recovery_budget_pct: autofix.recovery_budget_pct } : {}),
...(flightSchool ?? {}),
...(auditor ?? {}),
+ ...(discovery ?? {}),
...(place ? { timezone: place.timezone.trim(), location: place.location.trim() } : {}),
}),
});
@@ -436,6 +482,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
if (res.ok) {
setSaveSuccess(true);
if (missionBoard !== null) window.dispatchEvent(new CustomEvent(MISSION_BOARD_SETTING_EVENT, { detail: missionBoard }));
+ if (discovery) window.dispatchEvent(new CustomEvent(DISCOVERY_SETTING_EVENT, { detail: discovery }));
// Saving a key or the Ollama URL re-checks engines on the server; show the result.
window.setTimeout(engines.reload, 1500);
window.setTimeout(engines.reload, 6000);
@@ -955,6 +1002,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
)}
</SwitchRow>
)}
+ {discovery !== null && <DiscoverySetting value={discovery} onChange={setDiscovery} />}
</fieldset>
)}
@@ -1039,7 +1087,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
<div className="space-y-1.5" role="group" aria-labelledby="notify-kinds-label">
<p id="notify-kinds-label" className="text-xs font-medium text-zinc-400">Tell me when</p>
- {notifyKindsFor(appUpdates, !!proactive).map((k) => (
+ {notifyKindsFor(appUpdates, !!proactive, !!discovery).map((k) => (
<label key={k.id} className="flex items-center gap-2 text-[11px] text-zinc-300">
<input
type="checkbox"
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index 86a455bb..a84c4fee 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -175,7 +175,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {
</div>
)}
{tab === 'skills' && <SkillsTab {...p} />}
- {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} />}
+ {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={p.onOpenAppSettings} />}
{tab === 'import' && <ImportTab {...tp} />}
<div className="md:hidden pt-2">
<button type="button" onClick={p.onOpenAppSettings} className="flex items-center gap-2 text-xs text-zinc-400 hover:text-zinc-100">
diff --git a/frontend/src/components/SuggestedRoutines.tsx b/frontend/src/components/SuggestedRoutines.tsx
new file mode 100644
index 00000000..76de6573
--- /dev/null
+++ b/frontend/src/components/SuggestedRoutines.tsx
@@ -0,0 +1,571 @@
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { AlertTriangle, CalendarClock, Check, ChevronDown, ChevronRight, Eye, Loader2, RefreshCw, Search, ShieldCheck, Sparkles, X } from 'lucide-react';
+import {
+ AcceptIntent,
+ DISCOVERY_SETTING_EVENT,
+ DiscoveryError,
+ DiscoveryList,
+ ScanResult,
+ Suggestion,
+ acceptEdits,
+ approvalText,
+ blockText,
+ checkLine,
+ discoveryApi,
+ habitLine,
+ leftOutText,
+ pastText,
+ skipText,
+ sourceDay,
+ statsLine,
+} from '../automationDiscovery';
+import { channelLabel, formatWhen, onContinuity } from '../continuity';
+import { newIdempotencyKey } from '../missions';
+import { scheduleWords } from '../botActions';
+import { RoutineForm } from './RoutinesPanel';
+import { ModernAvatar } from './ModernAvatar';
+import type { Channel, Kwant } from './Sidebar';
+import { playSfx } from '../audio/chiptune';
+
+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 primaryBtn = `${smallBtn} border-sky-500/50 bg-sky-600 text-white hover:bg-sky-500`;
+
+/** A card the person just decided: stays as one line so they see what happened. */
+type Done = { id: string; text: string };
+
+const errText = (e: unknown, fallback: string) => (e instanceof Error && e.message ? e.message : fallback);
+
+/** Where an offer would post, in words. */
+function placeText(s: Suggestion, channels: Channel[]): string {
+ if (s.delivery?.thread_id) return 'the thread it came from';
+ const id = s.delivery?.channel_id;
+ if (!id) return 'direct chat';
+ const c = channels.find((ch) => ch.id === id);
+ return c ? channelLabel(c.name) : 'a deleted channel';
+}
+
+const Disclosure: React.FC<{ label: string; children: React.ReactNode; defaultOpen?: boolean }> = ({ label, children, defaultOpen = false }) => {
+ const [open, setOpen] = useState(defaultOpen);
+ const id = useId();
+ return (
+ <div>
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-controls={id}
+ className="inline-flex items-center gap-1 text-[11px] font-medium text-zinc-300 hover:text-zinc-100 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ {open ? <ChevronDown size={11} aria-hidden="true" /> : <ChevronRight size={11} aria-hidden="true" />}
+ {label}
+ </button>
+ {open && (
+ <div id={id} className="mt-1 pl-4">
+ {children}
+ </div>
+ )}
+ </div>
+ );
+};
+
+/** Checks the routine keeps: each can only be unticked (dropped); its masked spec is shown, never edited. */
+const KeepChecks: React.FC<{ suggestion: Suggestion; keep: boolean[]; onChange: (keep: boolean[]) => void }> = ({ suggestion, keep, onChange }) => {
+ if (suggestion.checks.length === 0) return null;
+ return (
+ <fieldset className="space-y-1">
+ <legend className="block text-xs font-medium text-zinc-400 mb-1">Checks after each run</legend>
+ {suggestion.checks.map((c, i) => (
+ <label key={i} className="flex items-start gap-2 min-h-[28px] text-[11px] text-zinc-300 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={keep[i] ?? true}
+ onChange={(e) => onChange(keep.map((k, j) => (j === i ? e.target.checked : k)))}
+ className="mt-0.5 accent-sky-500"
+ />
+ <span className="min-w-0 [overflow-wrap:anywhere]">
+ {checkLine(c)}
+ {!c.required && <span className="text-zinc-500"> (optional)</span>}
+ </span>
+ </label>
+ ))}
+ <p className="text-[11px] text-zinc-500">Untick a check to leave it out. Checks can’t be changed here; edit the routine later for that.</p>
+ </fieldset>
+ );
+};
+
+export const SuggestionCard: React.FC<{
+ suggestion: Suggestion;
+ kwants: Kwant[];
+ channels: Channel[];
+ /** Accepted or dismissed: the line to show in its place. */
+ onDone: (done: Done, accepted: boolean) => void;
+ /** Someone else already decided it (409) or it's gone (404): reload and say so. */
+ onStale: (message: string, accepted: boolean) => void;
+ /** Tests: a fixed key maker. */
+ makeKey?: () => string;
+}> = ({ suggestion: s, kwants, channels, onDone, onStale, makeKey = newIdempotencyKey }) => {
+ const [editing, setEditing] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [keep, setKeep] = useState<boolean[]>(() => s.checks.map(() => true));
+ const intent = useRef(new AcceptIntent(makeKey)).current;
+ const titleId = useId();
+ const kwant = kwants.find((k) => k.id === s.kwant_id);
+ const botName = kwant?.name ?? 'a deleted bot';
+ const p = s.permissions;
+ const e = s.evidence;
+
+ const stale = (err: unknown): boolean => {
+ if (!(err instanceof DiscoveryError) || (err.status !== 409 && err.status !== 404)) return false;
+ onStale(err.message, err.current?.status === 'accepted');
+ return true;
+ };
+
+ const accept = async (body: Parameters<NonNullable<React.ComponentProps<typeof RoutineForm>['onSubmit']>>[0], placeChanged: boolean) => {
+ const edits = acceptEdits(s, body, placeChanged, keep);
+ try {
+ const res = await discoveryApi.accept(s.id, intent.current(), edits);
+ const when = res.first_run_text ?? s.first_run_text;
+ onDone({ id: s.id, text: `Added “${res.routine?.name ?? body.name}” for ${botName}.${when ? ` First run: ${when}.` : ''}` }, true);
+ } catch (err) {
+ intent.settle(err);
+ if (stale(err)) return;
+ throw err;
+ }
+ };
+
+ const dismiss = async () => {
+ setBusy(true);
+ setError(null);
+ playSfx('click');
+ try {
+ const res = await discoveryApi.dismiss(s.id);
+ const until = res.suggestion?.cooldown_until;
+ onDone(
+ {
+ id: s.id,
+ text: `Dismissed “${s.name}”. It won’t be suggested again for 30 days${until ? ` (until ${new Date(until).toLocaleDateString(undefined, { day: 'numeric', month: 'short' })})` : ''}.`,
+ },
+ false,
+ );
+ } catch (err) {
+ if (!stale(err)) setError(errText(err, 'Dismissing failed.'));
+ setBusy(false);
+ }
+ };
+
+ if (editing)
+ return (
+ <li>
+ <RoutineForm
+ seed={{
+ kwant_id: s.kwant_id,
+ channel_id: s.delivery?.channel_id ?? null,
+ thread_id: s.delivery?.thread_id ?? null,
+ name: s.name,
+ instructions: s.instructions,
+ schedule: s.schedule,
+ }}
+ kwants={kwants}
+ channels={channels}
+ label={`Accept ${s.name}`}
+ submitLabel="Add routine"
+ hideEnabled
+ onSubmit={accept}
+ onCancel={() => setEditing(false)}
+ onSaved={() => undefined}
+ >
+ <KeepChecks suggestion={s} keep={keep} onChange={setKeep} />
+ </RoutineForm>
+ </li>
+ );
+
+ return (
+ <li aria-labelledby={titleId} className="rounded-xl border border-violet-500/25 bg-zinc-950/60 p-3 space-y-2.5" data-testid="suggestion-card">
+ <div className="flex items-start gap-2.5">
+ {kwant ? (
+ <ModernAvatar role={kwant.avatar_sprite} name={kwant.name} size={28} kwantId={kwant.id} />
+ ) : (
+ <span className="w-7 h-7 rounded-full bg-zinc-800 shrink-0" aria-hidden="true" />
+ )}
+ <div className="flex-1 min-w-0">
+ <h4 id={titleId} className="text-xs font-medium text-zinc-100 break-words">
+ {s.name}
+ </h4>
+ <p className="text-[11px] text-zinc-400 break-words">
+ {botName} · {placeText(s, channels)} · <span title={s.schedule_text || undefined}>{scheduleWords(s.schedule, s.schedule_text)}</span>
+ </p>
+ {s.first_run_text && (
+ <p className="text-[11px] text-zinc-400">
+ First run: <span className="text-zinc-200">{s.first_run_text}</span>
+ </p>
+ )}
+ </div>
+ </div>
+
+ <div className="pl-[38px] space-y-2 text-[11px] text-zinc-400">
+ <div>
+ <p className="text-zinc-300">{habitLine(e)}</p>
+ {e && e.settled > 0 && (
+ <p>
+ {e.verified} of {e.settled} finished {e.settled === 1 ? 'task' : 'tasks'} passed {e.verified === 1 && e.settled === 1 ? 'its' : 'their'} checks.
+ </p>
+ )}
+ </div>
+
+ {s.sources.length > 0 && (
+ <Disclosure label={`Why: the ${s.sources.length === 1 ? 'task' : `${s.sources.length} tasks`} it learned from`}>
+ <ul className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5" aria-label="Tasks it learned from">
+ {s.sources.map((src) => (
+ <li key={src.task_id} className="col-span-2 grid grid-cols-subgrid [overflow-wrap:anywhere]">
+ <span className="text-zinc-500 tabular-nums whitespace-nowrap">
+ {sourceDay(src.local_date)} {src.local_time}
+ </span>
+ <span className="text-zinc-300">{src.title}</span>
+ </li>
+ ))}
+ </ul>
+ </Disclosure>
+ )}
+
+ <Disclosure label="What it would do">
+ <p className="whitespace-pre-wrap text-zinc-300 [overflow-wrap:anywhere]">{s.instructions}</p>
+ {s.acceptance && <p className="mt-1">Done when: <span className="text-zinc-300">{s.acceptance}</span></p>}
+ {s.chain.filter((c) => !c.in_instructions).length > 0 && (
+ <p className="mt-1">
+ Mentions, but leaves to other bots: {s.chain.filter((c) => !c.in_instructions).map((c) => `“${c.title}”`).join(', ')}.
+ </p>
+ )}
+ </Disclosure>
+
+ {p && (
+ <div className="flex items-start gap-1.5" data-testid="permissions-preview">
+ <ShieldCheck size={12} className="mt-0.5 shrink-0 text-emerald-300/80" aria-hidden="true" />
+ <p>
+ <span className="text-zinc-300">{p.flight_school ? p.tier_label : 'Works as this bot does today'}.</span> {approvalText(p.approval_mode)}. Payments always ask you.{' '}
+ {pastText(p.past)}
+ </p>
+ </div>
+ )}
+
+ {(s.checks.length > 0 || s.left_out_checks.length > 0) && (
+ <div>
+ {s.checks.length > 0 ? (
+ <>
+ <p className="text-zinc-300">Checks it keeps after each run:</p>
+ <ul className="list-disc pl-4 space-y-0.5" aria-label="Checks it keeps">
+ {s.checks.map((c, i) => (
+ <li key={i} className="[overflow-wrap:anywhere]">
+ {checkLine(c)}
+ {!c.required && <span className="text-zinc-500"> (optional)</span>}
+ </li>
+ ))}
+ </ul>
+ </>
+ ) : (
+ <p>No checks would run after each run.</p>
+ )}
+ {s.left_out_checks.length > 0 && (
+ <>
+ <p className="mt-1 text-zinc-300">Left out:</p>
+ <ul className="list-disc pl-4 space-y-0.5" aria-label="Checks left out">
+ {s.left_out_checks.map((c, i) => (
+ <li key={i} className="[overflow-wrap:anywhere]">
+ {checkLine(c)} <span className="text-zinc-500">— {leftOutText(c.reason)}</span>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-1.5 pl-[38px]">
+ <button
+ type="button"
+ disabled={busy || !kwant}
+ onClick={() => {
+ playSfx('click');
+ setError(null);
+ setEditing(true);
+ }}
+ aria-label={`Accept ${s.name}: review and add it`}
+ className={primaryBtn}
+ >
+ <Check size={11} aria-hidden="true" /> Accept…
+ </button>
+ <button type="button" disabled={busy} onClick={dismiss} aria-label={`Dismiss ${s.name}`} className={quietBtn}>
+ {busy ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <X size={11} aria-hidden="true" />} Dismiss
+ </button>
+ {!kwant && <span className="text-[11px] text-amber-200">Its bot is gone, so it can only be dismissed.</span>}
+ </div>
+ {error && (
+ <p className="pl-[38px] text-[11px] text-rose-400 flex items-center gap-1.5" role="alert">
+ <AlertTriangle size={12} aria-hidden="true" /> {error}
+ </p>
+ )}
+ </li>
+ );
+};
+
+/** What Scan now or Preview found: the offers, and why the other habits weren't suggested. */
+const ScanReport: React.FC<{ result: ScanResult; onClose: () => void }> = ({ result, onClose }) => {
+ const n = result.offered.length;
+ const head = result.preview
+ ? n === 0
+ ? 'Preview: nothing would be suggested now.'
+ : `Preview: ${n === 1 ? '1 routine would' : `${n} routines would`} be suggested. Nothing was saved.`
+ : n === 0
+ ? 'Looked just now: nothing new to suggest.'
+ : `Looked just now: ${n === 1 ? '1 new suggestion' : `${n} new suggestions`}.`;
+ return (
+ <div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 space-y-2 text-[11px] text-zinc-400" data-testid="scan-report">
+ <div className="flex items-start justify-between gap-2">
+ <p className="text-zinc-200" role="status">
+ {head}
+ </p>
+ <button type="button" onClick={onClose} aria-label="Close the scan results" className="p-0.5 rounded text-zinc-500 hover:text-zinc-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">
+ <X size={12} />
+ </button>
+ </div>
+ {result.preview && n > 0 && (
+ <ul className="space-y-1" aria-label="Would be suggested">
+ {result.offered.map((o) => (
+ <li key={o.cluster_key}>
+ <span className="text-zinc-200">{o.name}</span> · {scheduleWords(o.schedule)}
+ {o.first_run_text ? ` · first run ${o.first_run_text}` : ''}
+ <span className="block text-zinc-500">{habitLine(o.evidence)}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {result.skipped.length > 0 && (
+ <Disclosure label={`Not suggested (${result.skipped.length})`}>
+ <ul className="space-y-0.5" aria-label="Not suggested">
+ {result.skipped.map((k) => (
+ <li key={k.cluster_key} className="[overflow-wrap:anywhere]">
+ <span className="text-zinc-300">{k.title}</span>
+ <span className="text-zinc-500">
+ {' '}
+ ({k.asks === 1 ? 'asked once' : `asked ${k.asks} times`}): {skipText(k.reason)}.
+ </span>
+ </li>
+ ))}
+ </ul>
+ </Disclosure>
+ )}
+ </div>
+ );
+};
+
+/**
+ * "Suggested routines" on top of the Routines list (Automation Discovery, docs §20): what kwant
+ * noticed you ask for on a rhythm, to accept (with edits) or dismiss. Hidden on servers without it.
+ */
+export const SuggestedRoutines: React.FC<{
+ kwants: Kwant[];
+ channels: Channel[];
+ /** After an accept: the routine list below should show the new routine. */
+ onAccepted: () => void;
+ onOpenSettings?: () => void;
+}> = ({ kwants, channels, onAccepted, onOpenSettings }) => {
+ const [list, setList] = useState<DiscoveryList | null>(null);
+ const [unsupported, setUnsupported] = useState(false);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [done, setDone] = useState<Done[]>([]);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [scanning, setScanning] = useState<'scan' | 'preview' | null>(null);
+ const [report, setReport] = useState<ScanResult | null>(null);
+ const [scanError, setScanError] = useState<string | null>(null);
+ const headingId = useId();
+ const doneRef = useRef<HTMLParagraphElement>(null);
+
+ const reload = useCallback(async () => {
+ try {
+ setList(await discoveryApi.list());
+ setLoadError(null);
+ } catch (e) {
+ // A server without Automation Discovery: show nothing, as before
+ if (e instanceof DiscoveryError && (e.status === 404 || e.status === 405)) setUnsupported(true);
+ else setLoadError(errText(e, 'Couldn’t load suggestions.'));
+ }
+ }, []);
+
+ useEffect(() => {
+ reload();
+ const onSetting = () => reload();
+ window.addEventListener(DISCOVERY_SETTING_EVENT, onSetting);
+ const off = onContinuity('automation_suggested', () => reload());
+ return () => {
+ window.removeEventListener(DISCOVERY_SETTING_EVENT, onSetting);
+ off();
+ };
+ }, [reload]);
+
+ // The line that replaced a decided card takes focus, so a keyboard or screen reader user isn't lost
+ useEffect(() => {
+ if (done.length) doneRef.current?.focus();
+ }, [done.length]);
+
+ const decided = (d: Done, accepted: boolean) => {
+ playSfx(accepted ? 'coin' : 'click');
+ setNotice(null);
+ setDone((prev) => [...prev.filter((x) => x.id !== d.id), d]);
+ setList((l) => (l ? { ...l, suggestions: l.suggestions.filter((x) => x.id !== d.id) } : l));
+ if (accepted) onAccepted();
+ reload();
+ };
+
+ const stale = (message: string, accepted: boolean) => {
+ setNotice(message);
+ if (accepted) onAccepted();
+ reload();
+ };
+
+ const scan = async (preview: boolean) => {
+ setScanning(preview ? 'preview' : 'scan');
+ setScanError(null);
+ setReport(null);
+ try {
+ const r = await discoveryApi.scan(preview);
+ if (r.blocked_by) setScanError(`${blockText(r.blocked_by).title} ${blockText(r.blocked_by).fix}`);
+ else setReport(r);
+ if (!preview) reload();
+ } catch (e) {
+ setScanError(errText(e, 'Looking failed.'));
+ } finally {
+ setScanning(null);
+ }
+ };
+
+ if (unsupported) return null;
+
+ const blocked = list?.blocked_by ?? [];
+ const offers = list?.suggestions.filter((s) => s.status === 'offered') ?? [];
+ const onlyOff = blocked.length === 1 && blocked[0] === 'off';
+ const settingsBtn = onOpenSettings && (
+ <button type="button" onClick={onOpenSettings} className={quietBtn}>
+ Open Settings
+ </button>
+ );
+
+ return (
+ <section aria-labelledby={headingId} className="space-y-2" data-testid="suggested-routines">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h3 id={headingId} className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">
+ <Sparkles size={13} className="text-violet-300" aria-hidden="true" />
+ Suggested routines
+ {offers.length > 0 && <span className="px-1.5 rounded-full bg-violet-500/15 text-violet-200 text-[10px] font-medium">{offers.length}</span>}
+ </h3>
+ {list && blocked.length === 0 && (
+ <div className="flex items-center gap-1.5">
+ <button type="button" onClick={() => scan(true)} disabled={!!scanning} className={quietBtn} title="See what would be suggested now, without saving anything">
+ {scanning === 'preview' ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Eye size={11} aria-hidden="true" />} Preview
+ </button>
+ <button type="button" onClick={() => scan(false)} disabled={!!scanning} className={quietBtn}>
+ {scanning === 'scan' ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Search size={11} aria-hidden="true" />} Scan now
+ </button>
+ </div>
+ )}
+ </div>
+
+ {!list && !loadError && (
+ <p className="flex items-center gap-2 text-[11px] text-zinc-400" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Checking for suggestions…
+ </p>
+ )}
+
+ {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-[11px]" role="alert">
+ <span>{loadError}</span>
+ <button type="button" onClick={reload} className={quietBtn}>
+ <RefreshCw size={11} aria-hidden="true" /> Retry
+ </button>
+ </div>
+ )}
+
+ {list && onlyOff && (
+ <div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-zinc-400 border border-dashed border-zinc-800 rounded-lg px-3 py-2" data-testid="discovery-blocked">
+ <p>
+ You can get a suggested routine when you ask for the same board task on a regular rhythm. {blockText('off').title} {blockText('off').fix}
+ </p>
+ {settingsBtn}
+ </div>
+ )}
+
+ {list && blocked.length > 0 && !onlyOff && (
+ <div className="text-[11px] text-amber-100 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2 space-y-1.5" role="status" data-testid="discovery-blocked">
+ <p className="font-medium">Suggestions are paused:</p>
+ <ul className="space-y-1">
+ {blocked.map((b) => (
+ <li key={b}>
+ {blockText(b).title} <span className="text-amber-200/80">{blockText(b).fix}</span>
+ </li>
+ ))}
+ </ul>
+ <div className="flex gap-1.5">
+ {settingsBtn}
+ <button type="button" onClick={reload} className={quietBtn}>
+ <RefreshCw size={11} aria-hidden="true" /> Check again
+ </button>
+ </div>
+ </div>
+ )}
+
+ {notice && (
+ <p className="text-[11px] text-sky-100 bg-sky-500/10 border border-sky-500/20 rounded-lg px-3 py-2" role="status">
+ {notice}
+ </p>
+ )}
+ {scanError && (
+ <p className="text-[11px] text-rose-300 flex items-center gap-1.5" role="alert">
+ <AlertTriangle size={12} aria-hidden="true" /> {scanError}
+ </p>
+ )}
+ {report && <ScanReport result={report} onClose={() => setReport(null)} />}
+
+ {done.length > 0 && (
+ <div className="space-y-1" role="status">
+ {done.map((d, i) => (
+ <p
+ key={d.id}
+ ref={i === done.length - 1 ? doneRef : undefined}
+ tabIndex={-1}
+ className="flex items-start gap-1.5 text-[11px] text-emerald-200 bg-emerald-500/10 border border-emerald-500/20 rounded-lg px-3 py-2 focus:outline-none focus-visible:ring-1 focus-visible:ring-emerald-400/50"
+ >
+ <Check size={12} className="mt-0.5 shrink-0" aria-hidden="true" /> {d.text}
+ </p>
+ ))}
+ </div>
+ )}
+
+ {list && blocked.length === 0 && offers.length === 0 && (
+ <div className="text-[11px] text-zinc-500 border border-dashed border-zinc-800 rounded-lg px-3 py-2.5 flex items-start gap-2" data-testid="discovery-empty">
+ <CalendarClock size={14} className="mt-0.5 shrink-0 text-zinc-600" aria-hidden="true" />
+ <p>
+ {list.daily_cap === 0
+ ? 'No suggestions. The daily limit in Settings is 0, so nothing new is suggested; Preview shows what it would suggest.'
+ : `No suggestions right now. The board is checked every hour for tasks you ask for on a regular rhythm, with at most ${list.daily_cap} new ${list.daily_cap === 1 ? 'suggestion' : 'suggestions'} a day.`}
+ </p>
+ </div>
+ )}
+
+ {offers.length > 0 && (
+ <ul className="space-y-2" aria-label="Suggested routines">
+ {offers.map((s) => (
+ <SuggestionCard key={s.id} suggestion={s} kwants={kwants} channels={channels} onDone={decided} onStale={stale} />
+ ))}
+ </ul>
+ )}
+
+ {list && (list.setting === 'on' || list.stats.offered_30d > 0) && (
+ <p className="text-[11px] text-zinc-500" data-testid="discovery-stats">
+ {statsLine(list.stats)} {list.last_scan_at ? `Last looked ${formatWhen(list.last_scan_at)}.` : list.setting === 'on' ? 'Hasn’t looked yet.' : ''}
+ </p>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index 9f72477d..6860f54a 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -82,6 +82,9 @@ export interface Routine {
thread_id?: string | null;
/** The message a follow-up checks back on. */
context_message_id?: string | null;
+ /** `discovery`: added from a routine kwant suggested (Automation Discovery). */
+ origin?: string | null;
+ suggestion_id?: string | null;
}
export interface RoutineRun {
@@ -114,7 +117,8 @@ export type NotifyKind =
| 'question_asked'
| 'human_step'
| 'app_update'
- | 'work_ahead';
+ | 'work_ahead'
+ | 'automation_suggested';
export const NOTIFY_KINDS: Array<{ id: NotifyKind; label: string }> = [
{ id: 'turn_finished', label: 'A bot finished replying' },
{ id: 'approval_needed', label: 'A bot needs your approval' },
@@ -132,19 +136,36 @@ export const APP_UPDATE_KIND: { id: NotifyKind; label: string } = { id: 'app_upd
/** Sent by servers with the proactive-bots settings (`work_ahead` in GET /api/settings). */
export const WORK_AHEAD_KIND: { id: NotifyKind; label: string } = { id: 'work_ahead', label: 'A bot worked ahead while you were away' };
-/** The checkboxes under "Tell me when": App updates only in the Mac app, work ahead only where the server has it. */
-export const notifyKindsFor = (appUpdates: boolean, workAhead = false) => [
+/** Sent by servers with Automation Discovery (`automation_discovery` in GET /api/settings). Not a Needs-you item. */
+export const AUTOMATION_SUGGESTED_KIND: { id: NotifyKind; label: string } = { id: 'automation_suggested', label: 'A routine was suggested' };
+
+/**
+ * The checkboxes under "Tell me when": App updates only in the Mac app, work ahead and suggested
+ * routines only where the server has them.
+ */
+export const notifyKindsFor = (appUpdates: boolean, workAhead = false, discovery = false) => [
...NOTIFY_KINDS,
...(workAhead ? [WORK_AHEAD_KIND] : []),
+ ...(discovery ? [AUTOMATION_SUGGESTED_KIND] : []),
...(appUpdates ? [APP_UPDATE_KIND] : []),
];
/** What to save: never a kind the server doesn't know (it would refuse the whole list). */
-export const notifyOnToSave = (on: NotifyKind[], appUpdates: boolean, workAhead = false) =>
- on.filter((k) => (k !== APP_UPDATE_KIND.id || appUpdates) && (k !== WORK_AHEAD_KIND.id || workAhead));
+export const notifyOnToSave = (on: NotifyKind[], appUpdates: boolean, workAhead = false, discovery = false) =>
+ on.filter(
+ (k) => (k !== APP_UPDATE_KIND.id || appUpdates) && (k !== WORK_AHEAD_KIND.id || workAhead) && (k !== AUTOMATION_SUGGESTED_KIND.id || discovery),
+ );
/** Kinds also shown as an in-app toast while kwnt is visible (the others only matter in the background). */
-export const TOAST_KINDS: NotifyKind[] = ['routine_failed', 'delegation_finished', 'delegation_stalled', 'skill_proposed', 'question_asked', 'human_step'];
+export const TOAST_KINDS: NotifyKind[] = [
+ 'routine_failed',
+ 'delegation_finished',
+ 'delegation_stalled',
+ 'skill_proposed',
+ 'question_asked',
+ 'human_step',
+ 'automation_suggested',
+];
export interface NotifyEvent {
kind: NotifyKind;
@@ -493,7 +514,8 @@ export function shouldShowOsNotification(opts: {
hidden: boolean;
kind: string;
}): boolean {
- return opts.enabled && opts.permission === 'granted' && opts.hidden && (NOTIFY_KINDS.some((k) => k.id === opts.kind) || opts.kind === WORK_AHEAD_KIND.id);
+ const known = NOTIFY_KINDS.some((k) => k.id === opts.kind) || opts.kind === WORK_AHEAD_KIND.id || opts.kind === AUTOMATION_SUGGESTED_KIND.id;
+ return opts.enabled && opts.permission === 'granted' && opts.hidden && known;
}
/** Whether this browser has OS notifications switched on for kwnt (stored per browser). */
@@ -515,7 +537,9 @@ export function notificationPermission(): NotificationPermission | 'unsupported'
export type ContinuityEvent =
| { type: 'memory_changed'; data: { kwant_id: string } }
| { type: 'routine_run'; data: { routine_id: string; run_id: string; status: RunStatus } }
- | { type: 'skill_updated'; data: Skill | DeletedSkill };
+ | { type: 'skill_updated'; data: Skill | DeletedSkill }
+ /** kwant suggested a routine (re-broadcast from its notification), so an open Routines list reloads. */
+ | { type: 'automation_suggested'; data: NotifyEvent };
const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;
diff --git a/frontend/tests/appUpdate.test.mjs b/frontend/tests/appUpdate.test.mjs
index 713af1b0..86c3fdff 100644
--- a/frontend/tests/appUpdate.test.mjs
+++ b/frontend/tests/appUpdate.test.mjs
@@ -357,7 +357,7 @@ test('app_update is saved in the Mac app and never sent to a server without it',
test('App settings shows the switch only when the update API is supported', () => {
const s = src('components/SettingsModal.tsx');
assert.match(s, /const appUpdates = useAppUpdate\(\)\.model\.status !== null;/);
- assert.match(s, /notifyKindsFor\(appUpdates, !!proactive\)\.map/);
- assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates, !!proactive\)/);
+ assert.match(s, /notifyKindsFor\(appUpdates, !!proactive, !!discovery\)\.map/);
+ assert.match(s, /notify_on: notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery\)/);
assert.doesNotMatch(s, /\{NOTIFY_KINDS\.map/);
});
diff --git a/frontend/tests/automationDiscovery.test.mjs b/frontend/tests/automationDiscovery.test.mjs
new file mode 100644
index 00000000..09614f6d
--- /dev/null
+++ b/frontend/tests/automationDiscovery.test.mjs
@@ -0,0 +1,471 @@
+// Automation Discovery screens (Mission Control D4, docs/mission-control.md §20): the API client
+// (one Idempotency-Key per Accept intent, the 409 in plain words), the words for every blocked and
+// skipped reason, and the Suggested routines section rendered in a DOM against a stubbed server.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'SubmitEvent', 'HTMLFormElement', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+g.matchMedia = g.window.matchMedia;
+g.window.HTMLElement.prototype.scrollIntoView ??= () => {};
+g.window.HTMLMediaElement && (g.window.HTMLMediaElement.prototype.play = () => Promise.resolve());
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export * from './src/automationDiscovery';
+ export { SuggestedRoutines, SuggestionCard } from './src/components/SuggestedRoutines';
+ export { RoutineRow } from './src/components/RoutinesPanel';
+ export { notifyKindsFor, notifyOnToSave, shouldShowOsNotification, TOAST_KINDS } from './src/continuity';
+`);
+const { React, createRoot } = m;
+
+const settle = async () => {
+ for (let i = 0; i < 25; i++) await new Promise((r) => setTimeout(r, 2));
+};
+const act = async (fn) => {
+ await fn();
+ await settle();
+};
+
+const KWANTS = [
+ { id: 'k_ada', name: 'Ada', title: 'Lead', persona_prompt: '', avatar_sprite: 'architect', driver_type: 'claude', preferred_model: 'auto' },
+ { id: 'k_lin', name: 'Lin', title: 'Backend', persona_prompt: '', avatar_sprite: 'engineer', driver_type: 'claude', preferred_model: 'auto' },
+];
+const CHANNELS = [{ id: 'c_eng', name: 'engineering', lead_kwant_id: 'k_ada', member_kwants: ['k_ada'], routing_mode: 'lead' }];
+
+const SCHEDULE = { type: 'weekly', time: '09:00', weekdays: ['mon'], tz: 'Europe/Berlin' };
+const offer = (over = {}) => ({
+ id: 'sg_1',
+ space_id: 'sp_1',
+ cluster_key: 'weekly-report',
+ kwant_id: 'k_ada',
+ name: 'Weekly status report',
+ instructions: 'Write the weekly status report.',
+ schedule: SCHEDULE,
+ schedule_text: 'weekly on Mon at 09:00 Europe/Berlin',
+ first_run_at: '2026-11-02T08:00:00Z',
+ first_run_text: 'Mon 2 Nov at 09:00',
+ delivery: { channel_id: 'c_eng' },
+ task_class: 'report',
+ acceptance: 'The report is in reports/',
+ checks: [
+ { kind: 'file_exists', spec: { path: 'reports/week.md' }, required: true },
+ { kind: 'command', spec: { command: 'curl -H "Authorization: ••••••••" https://api.example.com' }, required: false },
+ ],
+ left_out_checks: [{ kind: 'person', spec: {}, reason: 'needs a person or a reviewer' }],
+ chain: [],
+ source_task_ids: ['t1', 't2', 't3'],
+ sources: [
+ { task_id: 't1', title: 'Weekly status report', local_date: '2026-10-12', local_time: '09:05', state: 'verified' },
+ { task_id: 't2', title: 'Weekly status report', local_date: '2026-10-19', local_time: '09:10', state: 'verified' },
+ { task_id: 't3', title: 'Status report for the week', local_date: '2026-10-26', local_time: '09:02', state: 'verified' },
+ ],
+ time_spread: '09:02–09:10',
+ evidence: { pattern: 'weekly', matched: 3, expected: 3, coverage: 1, precision: 1, verified: 3, settled: 3, total: 3, time_spread: '09:02–09:10', time_varies: false, last_ask_at: '2026-10-26T08:02:00Z' },
+ permissions: {
+ flight_school: true,
+ tier: 'sandbox',
+ tier_from: 'class',
+ tier_label: 'Sandbox: commands that can change things ask you first',
+ approval_mode: 'smart',
+ payments_ask: true,
+ past: { external: 0, workspace: 3, needed_ok: 1 },
+ },
+ status: 'offered',
+ routine_id: null,
+ cooldown_until: null,
+ offered_at: '2026-10-31T10:00:00Z',
+ decided_at: null,
+ ...over,
+});
+const STATS = { offered_30d: 2, accepted_30d: 1, dismissed_30d: 0, retained: 1, dropped: 0 };
+const listing = (over = {}) => ({ setting: 'on', daily_cap: 2, blocked_by: [], last_scan_at: '2026-10-31T10:00:00Z', suggestions: [offer()], stats: STATS, ...over });
+
+const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+
+/** A stub server: `routes` answers by "METHOD path" prefix; every call is recorded. */
+function stubServer(routes) {
+ const calls = [];
+ g.fetch = async (url, init = {}) => {
+ const u = String(url);
+ const method = init.method ?? 'GET';
+ const headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
+ calls.push({ method, url: u, headers, body: init.body === undefined ? undefined : JSON.parse(init.body) });
+ for (const [key, answer] of Object.entries(routes)) {
+ const [rm, rp] = key.split(' ');
+ if (rm !== method || !u.startsWith(rp)) continue;
+ if (typeof answer === 'function') return answer({ url: u, headers, init, calls });
+ return answer instanceof Response ? answer.clone() : json(answer);
+ }
+ return json([]);
+ };
+ g.window.fetch = g.fetch;
+ return calls;
+}
+
+function mount(el) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ return {
+ host,
+ render: (e) => act(async () => root.render(e)),
+ done: () => {
+ root.unmount();
+ host.remove();
+ },
+ button: (label) => [...host.querySelectorAll('button')].find((b) => b.textContent.trim() === label || b.getAttribute('aria-label') === label),
+ text: () => host.textContent.replace(/\s+/g, ' '),
+ };
+}
+
+const setValue = (el, v) => {
+ const proto = el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, v);
+ el.dispatchEvent(new window.Event('input', { bubbles: true }));
+};
+
+async function renderSection(routes, extra = {}) {
+ const calls = stubServer(routes);
+ const v = mount();
+ const accepted = { n: 0 };
+ await v.render(
+ React.createElement(m.SuggestedRoutines, { kwants: KWANTS, channels: CHANNELS, onAccepted: () => accepted.n++, onOpenSettings: () => {}, ...extra }),
+ );
+ await settle();
+ return { ...v, calls, accepted };
+}
+
+// ---------------------------------------------------------------------------
+// API client
+
+test('accept sends the Idempotency-Key header, and a body only when something changed', async () => {
+ const calls = stubServer({ 'POST /api/automation-discovery/sg_1/accept': json({ suggestion: offer({ status: 'accepted' }), routine: { id: 'r1', name: 'x' }, first_run_text: 'Mon 2 Nov at 09:00' }, 201) });
+ await m.discoveryApi.accept('sg_1', 'key-1');
+ await m.discoveryApi.accept('sg_1', 'key-2', {});
+ await m.discoveryApi.accept('sg_1', 'key-3', { name: 'Renamed' });
+ assert.deepEqual(
+ calls.map((c) => [c.method, c.url, c.headers['idempotency-key'], c.body]),
+ [
+ ['POST', '/api/automation-discovery/sg_1/accept', 'key-1', undefined],
+ ['POST', '/api/automation-discovery/sg_1/accept', 'key-2', undefined],
+ ['POST', '/api/automation-discovery/sg_1/accept', 'key-3', { name: 'Renamed' }],
+ ],
+ );
+});
+
+test('a 409 becomes a DiscoveryError with what already happened, in plain words', async () => {
+ stubServer({ 'POST /api/automation-discovery/sg_1/dismiss': () => json({ error: 'this suggestion was already accepted', status: 'accepted', routine_id: 'r9' }, 409) });
+ await assert.rejects(m.discoveryApi.dismiss('sg_1'), (e) => {
+ assert.ok(e instanceof m.DiscoveryError);
+ assert.equal(e.status, 409);
+ assert.deepEqual(e.current, { status: 'accepted', routine_id: 'r9' });
+ assert.equal(e.message, 'Already added. It’s in your routines below.');
+ return true;
+ });
+ for (const s of ['dismissed', 'expired', 'superseded', 'weird']) assert.ok(m.alreadyHandledText(s).length > 10, s);
+});
+
+test('a dropped connection is a status-0 error, not a crash', async () => {
+ g.fetch = async () => {
+ throw new TypeError('Failed to fetch');
+ };
+ g.window.fetch = g.fetch;
+ await assert.rejects(m.discoveryApi.list(), (e) => e instanceof m.DiscoveryError && e.status === 0 && /connection/.test(e.message));
+});
+
+test('AcceptIntent keeps one key across retries that may have gone through, and starts a new one after a refusal', () => {
+ let n = 0;
+ const intent = new m.AcceptIntent(() => `k${++n}`);
+ assert.equal(intent.current(), 'k1');
+ assert.equal(intent.current(), 'k1', 'a double press sends the same key');
+ intent.settle(new m.DiscoveryError('offline', 0));
+ assert.equal(intent.current(), 'k1', 'after a dropped connection the retry replays');
+ intent.settle(new m.DiscoveryError('boom', 502));
+ assert.equal(intent.current(), 'k1', 'after a server error the retry replays');
+ intent.settle(new TypeError('x'));
+ assert.equal(intent.current(), 'k1');
+ intent.settle(new m.DiscoveryError('bad schedule', 400));
+ assert.equal(intent.current(), 'k2', 'a refusal the person fixes is a new intent');
+ intent.settle(new m.DiscoveryError('bad index', 422));
+ assert.equal(intent.current(), 'k3');
+});
+
+test('acceptEdits sends only what changed; checks can only be dropped', () => {
+ const s = offer();
+ const body = { kwant_id: 'k_ada', channel_id: 'c_eng', name: 'Weekly status report', instructions: 'Write the weekly status report.', schedule: { tz: 'Europe/Berlin', weekdays: ['mon'], time: '09:00', type: 'weekly' }, enabled: true };
+ assert.deepEqual(m.acceptEdits(s, body, false, [true, true]), {}, 'the same schedule in another key order is no change');
+ assert.deepEqual(m.acceptEdits(s, { ...body, name: ' Monday report ' }, false, [true, true]), { name: 'Monday report' });
+ assert.deepEqual(m.acceptEdits(s, { ...body, schedule: { ...SCHEDULE, time: '08:30' } }, false, [true, true]), { schedule: { ...SCHEDULE, time: '08:30' } });
+ assert.deepEqual(m.acceptEdits(s, { ...body, channel_id: null }, true, [true, true]), { channel_id: null }, 'moving to direct chat sends null');
+ assert.deepEqual(m.acceptEdits(s, { ...body, kwant_id: 'k_lin' }, false, [true, true]), { kwant_id: 'k_lin' });
+ assert.deepEqual(m.acceptEdits(s, body, false, [false, true]), { keep_checks: [1] });
+ assert.deepEqual(m.acceptEdits(s, body, false, [false, false]), { keep_checks: [] });
+ assert.ok(!('checks' in m.acceptEdits(s, body, false, [false, true])), 'a masked spec is never sent back');
+});
+
+// ---------------------------------------------------------------------------
+// Words
+
+test('every blocked reason and every skip reason has plain words', () => {
+ for (const b of ['off', 'board_off', 'no_timezone']) {
+ const t = m.blockText(b);
+ assert.ok(t.title && t.fix && /Settings/.test(t.fix), b);
+ }
+ const reasons = ['too_short', 'not_regular', 'stopped', 'not_verified', 'mixed_owners', 'bot_unavailable', 'covered', 'cooling_off', 'already_offered', 'in_chain', 'capped'];
+ for (const r of reasons) {
+ const t = m.skipText(r);
+ assert.ok(!t.includes('_') && t !== r && /^[A-Z]/.test(t), `${r} → ${t}`);
+ }
+ assert.equal(m.skipText('something_new'), 'something new', 'an unknown reason still reads as words');
+});
+
+test('the habit, permissions and stats lines read naturally', () => {
+ assert.equal(m.habitLine(offer().evidence), 'You asked for this 3 times, every week, usually between 09:02 and 09:10.');
+ assert.equal(m.habitLine({ ...offer().evidence, pattern: 'daily', time_spread: '18:00', matched: 7, time_varies: true }), 'You asked for this 7 times, every day, usually around 18:00 (the time varies).');
+ assert.equal(m.pastText({ external: 0, workspace: 3, needed_ok: 1 }), 'In past runs: 3 workspace changes; needed your OK once.');
+ assert.equal(m.pastText({ external: 0, workspace: 0, needed_ok: 0 }), 'In past runs it changed nothing outside its chat, and never needed your OK.');
+ assert.equal(m.approvalText('smart'), 'Asks you only when an action is risky');
+ assert.equal(m.statsLine(STATS), 'Last 30 days: 2 suggested, 1 added, 0 dismissed. Still on 14 days after adding: 1 of 1.');
+ assert.equal(m.statsLine({ ...STATS, retained: 0 }), 'Last 30 days: 2 suggested, 1 added, 0 dismissed.');
+ assert.equal(m.checkLine(offer().checks[0]), 'File exists: reports/week.md');
+ assert.match(m.checkLine(offer().checks[1]), /^Command: curl -H "Authorization: ••••••••"/);
+ assert.match(m.leftOutText('needs a person or a reviewer'), /can’t run on a schedule/);
+});
+
+test('settings parse: null on an older server, the cap kept within 0–10', () => {
+ assert.equal(m.parseDiscoverySettings({}), null);
+ assert.deepEqual(m.parseDiscoverySettings({ automation_discovery: 'off', automation_discovery_daily_cap: 2 }), { automation_discovery: 'off', automation_discovery_daily_cap: 2 });
+ assert.deepEqual(m.parseDiscoverySettings({ automation_discovery: 'on', automation_discovery_daily_cap: 40 }), { automation_discovery: 'on', automation_discovery_daily_cap: 10 });
+ assert.deepEqual(m.parseDiscoverySettings({ automation_discovery: 'on' }), { automation_discovery: 'on', automation_discovery_daily_cap: 2 });
+ assert.deepEqual(m.DISCOVERY_CAPS, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
+});
+
+test('the automation_suggested notification: a toggle where the server has it, a toast, never a Needs-you item', () => {
+ const ids = (d) => m.notifyKindsFor(false, false, d).map((k) => k.id);
+ assert.ok(ids(true).includes('automation_suggested'));
+ assert.ok(!ids(false).includes('automation_suggested'), 'not offered to a server that would refuse it');
+ assert.equal(m.notifyKindsFor(false, false, true).find((k) => k.id === 'automation_suggested').label, 'A routine was suggested');
+ assert.deepEqual(m.notifyOnToSave(['turn_finished', 'automation_suggested'], false, false, false), ['turn_finished']);
+ assert.deepEqual(m.notifyOnToSave(['turn_finished', 'automation_suggested'], false, false, true), ['turn_finished', 'automation_suggested']);
+ assert.ok(m.TOAST_KINDS.includes('automation_suggested'));
+ assert.equal(m.shouldShowOsNotification({ enabled: true, permission: 'granted', hidden: true, kind: 'automation_suggested' }), true);
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /n\.kind === 'automation_suggested'\) setIsRoutinesOpen\(true\)/, 'a tapped notification opens Routines');
+ assert.doesNotMatch(readFileSync(new URL('../src/missions.ts', import.meta.url), 'utf8'), /automation_suggested/, 'not on the Needs-you list');
+ const settings = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');
+ assert.match(settings, /notifyKindsFor\(appUpdates, !!proactive, !!discovery\)/);
+ assert.match(settings, /notifyOnToSave\(notifyOn, appUpdates, !!proactive, !!discovery\)/);
+ assert.match(settings, /\.\.\.\(discovery \?\? \{\}\)/, 'the switch and cap are saved');
+});
+
+// ---------------------------------------------------------------------------
+// The section in a DOM
+
+test('an offer card shows the name, bot, rhythm, first run, why, permissions and checks', async () => {
+ const v = await renderSection({ 'GET /api/automation-discovery': listing() });
+ const card = v.host.querySelector('[data-testid="suggestion-card"]');
+ assert.ok(card);
+ const t = card.textContent.replace(/\s+/g, ' ');
+ for (const want of ['Weekly status report', 'Ada', '#engineering', 'First run: Mon 2 Nov at 09:00', 'You asked for this 3 times, every week', '3 of 3 finished tasks passed their checks', 'Sandbox: commands that can change things ask you first', 'Payments always ask you', 'File exists: reports/week.md', '(optional)', 'Left out:', 'can’t run on a schedule']) {
+ assert.ok(t.includes(want), `card shows “${want}”: ${t}`);
+ }
+ assert.equal(card.getAttribute('aria-labelledby'), card.querySelector('h4').id, 'the card is named by its title');
+ assert.ok(v.button('Accept Weekly status report: review and add it'));
+ assert.ok(v.button('Dismiss Weekly status report'));
+ // Why: the sources, with their days
+ await act(async () => v.button('Why: the 3 tasks it learned from').click());
+ assert.match(v.text(), /Mon, Oct 12 09:05 ?Weekly status report/);
+ assert.match(v.text(), /Last 30 days: 2 suggested, 1 added/);
+ v.done();
+});
+
+test('Accept → edit → Add routine sends one key, only the edits, and shows the first run it returned', async () => {
+ let answered = 0;
+ const v = await renderSection({
+ 'GET /api/automation-discovery': () => json(listing({ suggestions: answered ? [] : [offer()] })),
+ 'POST /api/automation-discovery/sg_1/accept': ({ init }) => {
+ answered++;
+ const body = JSON.parse(init.body);
+ return json({ suggestion: offer({ status: 'accepted' }), routine: { id: 'r1', name: body.name, origin: 'discovery' }, first_run_text: 'Mon 2 Nov at 09:00' }, 201);
+ },
+ });
+ await act(async () => v.button('Accept Weekly status report: review and add it').click());
+ const form = v.host.querySelector('form[aria-label="Accept Weekly status report"]');
+ assert.ok(form, 'Accept opens the edit step');
+ assert.equal(form.querySelector('input[type="checkbox"]:not([role])')?.closest('label').textContent.includes('Enabled'), false, 'no Enabled box: it starts on');
+ // Masked specs are text, never an input that could be edited back into a secret
+ for (const input of form.querySelectorAll('input, textarea')) assert.ok(!String(input.value).includes('••••'), 'no masked spec in an input');
+ const name = form.querySelector('input[placeholder="Morning digest"]');
+ assert.equal(name.value, 'Weekly status report');
+ await act(async () => setValue(name, 'Monday report'));
+ const keepBoxes = [...form.querySelectorAll('fieldset input[type="checkbox"]')];
+ assert.equal(keepBoxes.length, 2);
+ await act(async () => keepBoxes[1].click());
+ await act(async () => [...form.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Add routine').click());
+ const posts = v.calls.filter((c) => c.method === 'POST');
+ assert.equal(posts.length, 1);
+ assert.ok(posts[0].headers['idempotency-key'], 'sent with an Idempotency-Key');
+ assert.deepEqual(posts[0].body, { name: 'Monday report', keep_checks: [0] });
+ assert.match(v.text(), /Added “Monday report” for Ada\. First run: Mon 2 Nov at 09:00\./);
+ assert.equal(v.accepted.n, 1, 'the routine list reloads');
+ assert.equal(v.host.querySelectorAll('[data-testid="suggestion-card"]').length, 0);
+ assert.equal(document.activeElement?.textContent.includes('Added'), true, 'focus moves to the result line');
+ v.done();
+});
+
+test('a failed Accept retried after a dropped connection reuses the key; a fixed 400 gets a new one', async () => {
+ let n = 0;
+ const v = await renderSection({
+ 'GET /api/automation-discovery': listing(),
+ 'POST /api/automation-discovery/sg_1/accept': () => {
+ n++;
+ if (n === 1) throw new TypeError('Failed to fetch');
+ if (n === 2) return json({ error: 'that schedule is in the past' }, 400);
+ return json({ suggestion: offer({ status: 'accepted' }), routine: { id: 'r1', name: 'Weekly status report' }, first_run_text: 'Mon 2 Nov at 09:00' }, 201);
+ },
+ });
+ await act(async () => v.button('Accept Weekly status report: review and add it').click());
+ const add = () => [...v.host.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Add routine');
+ await act(async () => add().click());
+ assert.match(v.host.querySelector('[role="alert"]').textContent, /Couldn’t reach the server/);
+ await act(async () => add().click());
+ assert.match(v.host.querySelector('[role="alert"]').textContent, /That schedule is in the past\./);
+ await act(async () => add().click());
+ const keys = v.calls.filter((c) => c.method === 'POST').map((c) => c.headers['idempotency-key']);
+ assert.equal(keys.length, 3);
+ assert.equal(keys[0], keys[1], 'the retry after a dropped connection replays the same intent');
+ assert.notEqual(keys[2], keys[1], 'after a refusal, a new intent');
+ assert.match(v.text(), /Added “Weekly status report”/);
+ v.done();
+});
+
+test('Dismiss says the suggestion is hidden for 30 days', async () => {
+ let dismissed = false;
+ const v = await renderSection({
+ 'GET /api/automation-discovery': () => json(listing({ suggestions: dismissed ? [] : [offer()] })),
+ 'POST /api/automation-discovery/sg_1/dismiss': () => {
+ dismissed = true;
+ return json({ suggestion: offer({ status: 'dismissed', cooldown_until: '2026-11-30T10:00:00Z' }) });
+ },
+ });
+ await act(async () => v.button('Dismiss Weekly status report').click());
+ assert.match(v.text(), /Dismissed “Weekly status report”\. It won’t be suggested again for 30 days \(until Nov 30\)\./);
+ assert.equal(v.host.querySelectorAll('[data-testid="suggestion-card"]').length, 0);
+ assert.equal(v.accepted.n, 0);
+ v.done();
+});
+
+test('a 409 refreshes the list and says it was already handled', async () => {
+ let gets = 0;
+ const v = await renderSection({
+ 'GET /api/automation-discovery': () => json(listing({ suggestions: gets++ ? [] : [offer()] })),
+ 'POST /api/automation-discovery/sg_1/dismiss': () => json({ error: 'this suggestion was already accepted', status: 'accepted', routine_id: 'r1' }, 409),
+ });
+ await act(async () => v.button('Dismiss Weekly status report').click());
+ assert.match(v.text(), /Already added\. It’s in your routines below\./);
+ assert.ok(gets >= 2, 'the list was fetched again');
+ assert.equal(v.host.querySelectorAll('[data-testid="suggestion-card"]').length, 0);
+ assert.equal(v.accepted.n, 1, 'the routine list reloads to show the routine someone else added');
+ assert.equal(v.host.querySelector('[role="alert"]'), null, 'not shown as an error');
+ v.done();
+});
+
+test('a 409 on Accept in the edit step does the same', async () => {
+ const v = await renderSection({
+ 'GET /api/automation-discovery': listing(),
+ 'POST /api/automation-discovery/sg_1/accept': () => json({ error: 'this suggestion was already dismissed', status: 'dismissed', routine_id: null }, 409),
+ });
+ await act(async () => v.button('Accept Weekly status report: review and add it').click());
+ await act(async () => [...v.host.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Add routine').click());
+ assert.match(v.text(), /Already dismissed\./);
+ assert.equal(v.accepted.n, 0);
+ v.done();
+});
+
+test('blocked: off is one quiet line; board off and no time zone each show their fix', async () => {
+ let v = await renderSection({ 'GET /api/automation-discovery': listing({ setting: 'off', blocked_by: ['off'], suggestions: [], stats: { ...STATS, offered_30d: 0 } }) });
+ let box = v.host.querySelector('[data-testid="discovery-blocked"]');
+ assert.match(box.textContent, /Suggestions are off\..*Turn on “Suggest routines from repeated tasks” in Settings/);
+ assert.ok(v.button('Open Settings'));
+ assert.equal(v.button('Scan now'), undefined, 'no scan while blocked');
+ v.done();
+
+ v = await renderSection({ 'GET /api/automation-discovery': listing({ blocked_by: ['board_off', 'no_timezone'], suggestions: [] }) });
+ box = v.host.querySelector('[data-testid="discovery-blocked"]');
+ assert.equal(box.getAttribute('role'), 'status');
+ assert.match(box.textContent, /the board is off\..*Turn on “Show the Mission board” in Settings/);
+ assert.match(box.textContent, /time zone isn’t set.*Set your time zone in Settings, under Where you are/);
+ assert.ok(v.button('Check again'));
+ v.done();
+});
+
+test('empty, loading and error states', async () => {
+ let v = await renderSection({ 'GET /api/automation-discovery': listing({ suggestions: [] }) });
+ assert.match(v.host.querySelector('[data-testid="discovery-empty"]').textContent, /No suggestions right now\..*at most 2 new suggestions a day/);
+ v.done();
+
+ g.fetch = () => new Promise(() => {});
+ g.window.fetch = g.fetch;
+ v = mount();
+ await v.render(React.createElement(m.SuggestedRoutines, { kwants: KWANTS, channels: CHANNELS, onAccepted: () => {} }));
+ assert.match(v.host.querySelector('[role="status"]').textContent, /Checking for suggestions/);
+ v.done();
+
+ v = await renderSection({ 'GET /api/automation-discovery': () => json({ error: 'database is locked' }, 500) });
+ assert.match(v.host.querySelector('[role="alert"]').textContent, /Database is locked\./);
+ assert.ok(v.button('Retry'));
+ v.done();
+
+ v = await renderSection({ 'GET /api/automation-discovery': () => new Response('Not Found', { status: 404 }) });
+ assert.equal(v.host.querySelector('[data-testid="suggested-routines"]'), null, 'a server without it shows nothing');
+ v.done();
+});
+
+test('Scan now and Preview show what was found and why the rest was skipped', async () => {
+ const skipped = [
+ { cluster_key: 'a', title: 'Fix the build', asks: 2, reason: 'too_short' },
+ { cluster_key: 'b', title: 'Daily standup notes', asks: 9, reason: 'covered' },
+ ];
+ const v = await renderSection({
+ 'GET /api/automation-discovery': listing({ suggestions: [] }),
+ 'POST /api/automation-discovery/scan?preview=1': json({ blocked_by: null, preview: true, timezone: 'Europe/Berlin', offered: [{ cluster_key: 'c', kwant_id: 'k_ada', name: 'Invoice run', schedule: { type: 'monthly', time: '10:00', days: [1], tz: 'Europe/Berlin' }, first_run_text: 'Sun 1 Nov at 10:00', evidence: { ...offer().evidence, pattern: 'monthly', matched: 4 } }], skipped }),
+ 'POST /api/automation-discovery/scan': json({ blocked_by: null, preview: false, timezone: 'Europe/Berlin', offered: [], skipped, expired: [], superseded: [] }),
+ });
+ await act(async () => v.button('Preview').click());
+ let report = v.host.querySelector('[data-testid="scan-report"]');
+ assert.match(report.textContent, /Preview: 1 routine would be suggested\. Nothing was saved\./);
+ assert.match(report.textContent, /Invoice run/);
+ await act(async () => v.button('Not suggested (2)').click());
+ report = v.host.querySelector('[data-testid="scan-report"]');
+ assert.match(report.textContent, /Fix the build \(asked 2 times\): Not enough asks yet to see a rhythm\./);
+ assert.match(report.textContent, /Daily standup notes \(asked 9 times\): A routine already does this\./);
+
+ await act(async () => v.button('Scan now').click());
+ assert.match(v.host.querySelector('[data-testid="scan-report"]').textContent, /Looked just now: nothing new to suggest\./);
+ assert.deepEqual(
+ v.calls.filter((c) => c.method === 'POST').map((c) => c.url),
+ ['/api/automation-discovery/scan?preview=1', '/api/automation-discovery/scan'],
+ );
+ v.done();
+});
+
+test('a routine added from a suggestion carries the “Suggested for you” badge', async () => {
+ stubServer({});
+ const base = { id: 'r1', kwant_id: 'k_ada', channel_id: null, name: 'Weekly status report', instructions: 'x', schedule: SCHEDULE, enabled: true, next_run_at: null, last_run_at: null, last_status: null, created_at: '2026-10-31T10:00:00Z' };
+ const v = mount();
+ await v.render(React.createElement(m.RoutineRow, { routine: { ...base, origin: 'discovery', suggestion_id: 'sg_1' }, placeLabel: 'direct chat', tick: 0, onEdit() {}, onChanged() {} }));
+ assert.match(v.text(), /Suggested for you/);
+ await v.render(React.createElement(m.RoutineRow, { routine: { ...base, origin: 'person' }, placeLabel: 'direct chat', tick: 0, onEdit() {}, onChanged() {} }));
+ assert.doesNotMatch(v.text(), /Suggested for you/);
+ v.done();
+});