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.

frontend: bot-action, hire and hire-policy cards; monthly and cron routines

Lin (kwant bot)27f2ce533c1f
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d7badd08..3e7e21c0 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -8,6 +8,10 @@ import { DelegationCard } from './components/DelegationCard';
import { QuestionCard } from './components/QuestionCard';
import { McpSuggestionCard } from './components/McpSuggestionCard';
import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';
+import { ApiError, BotActionMeta, HireMeta, applyBotAction, applyHire, botActionsApi, decisionError, hiresApi } from './botActions';
+import { BotActionCard, type BotActionDecision } from './components/BotActionCard';
+import { HireCard, type HireDecision } from './components/HireCard';
+import type { RoutineFocus } from './components/RoutinesPanel';
import { AwayPage } from './components/AwayView';
import { Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
import { PendingApproval } from './components/ModernApprovalCard';
@@ -201,8 +205,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [settingsClosedCount, setSettingsClosedCount] = useState(0);
// Set when Accounts opens from a "Sign in with Claude" hint, to focus that button.
const [claudeSignInFocus, setClaudeSignInFocus] = useState(0);
+ // Set by a routine card's Edit or Pause, so Routines opens at that routine.
+ const [routineFocus, setRoutineFocus] = useState<RoutineFocus | null>(null);
const openSpaceSettings = (tab: SpaceSettingsTab = 'general') => {
setClaudeSignInFocus(0);
+ if (tab !== 'routines') setRoutineFocus(null);
setSpaceSettingsTab(tab);
playSfx('click');
};
@@ -400,6 +407,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// servers that still need the person to sign in.
const [suggestions, setSuggestions] = useState<Record<string, Suggestion>>({});
const [needsSignIn, setNeedsSignIn] = useState<Record<string, boolean>>({});
+ // Cards for changes bots made (bot_action_updated) and hire proposals (hire_updated), by id.
+ const [botActions, setBotActions] = useState<Record<string, BotActionMeta>>({});
+ const [hires, setHires] = useState<Record<string, HireMeta>>({});
// Virtual Machine & Live Browser state
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
@@ -660,6 +670,21 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (sg?.id) setSuggestions((prev) => applySuggestion(prev, sg));
break;
}
+ case 'bot_action_updated':
+ case 'BotActionUpdated': {
+ const a = event.data?.action;
+ if (a?.id) setBotActions((prev) => applyBotAction(prev, a));
+ break;
+ }
+ case 'hire_updated':
+ case 'HireUpdated': {
+ const h = event.data?.hire;
+ if (h?.id) {
+ setHires((prev) => applyHire(prev, h));
+ window.dispatchEvent(new Event('kwnt:hire-updated'));
+ }
+ break;
+ }
case 'question_updated':
case 'QuestionUpdated': {
const q: Question | undefined = event.data?.question;
@@ -1391,6 +1416,79 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
};
+ // A routine card's Edit or Pause: open Space settings → Routines at that routine.
+ const handleOpenRoutine = (id: string, mode: 'edit' | 'pause') => {
+ setRoutineFocus({ id, mode, nonce: Date.now() });
+ openSpaceSettings('routines');
+ };
+ const handleBotActionDecision = async (actionId: string, d: BotActionDecision): Promise<string | void> => {
+ try {
+ const a = d === 'undo' ? await botActionsApi.undo(actionId) : d === 'confirm' ? await botActionsApi.confirm(actionId) : await botActionsApi.decline(actionId);
+ setBotActions((prev) => applyBotAction(prev, a));
+ playSfx('click');
+ } catch (err) {
+ // Already decided elsewhere: pick up the real state so the card stops offering the button.
+ if (err instanceof ApiError && err.status === 409) {
+ botActionsApi
+ .list()
+ .then((list) => setBotActions((prev) => list.reduce((m, a) => applyBotAction(m, a), prev)))
+ .catch(() => {});
+ }
+ return decisionError(err, d === 'undo' ? 'undo it' : d === 'confirm' ? 'confirm it' : 'decline it');
+ }
+ };
+ const refreshHires = () =>
+ hiresApi
+ .list()
+ .then((list) => setHires((prev) => list.reduce((m, h) => applyHire(m, h), prev)))
+ .catch(() => {});
+ const handleHireDecision = async (hire: HireMeta, d: HireDecision): Promise<string | void> => {
+ try {
+ if (d === 'undo') {
+ if (!hire.action_id) return 'Couldn’t undo it: this hire has nothing to undo.';
+ await botActionsApi.undo(hire.action_id);
+ refreshHires();
+ } else {
+ const h = d === 'deny' ? await hiresApi.deny(hire.hire_id) : await hiresApi.accept(hire.hire_id, d === 'always_accept');
+ setHires((prev) => applyHire(prev, h));
+ }
+ window.dispatchEvent(new Event('kwnt:hire-updated'));
+ playSfx('click');
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 409) refreshHires();
+ return decisionError(err, d === 'deny' ? 'say no' : d === 'undo' ? 'undo the hire' : 'hire it');
+ }
+ };
+ const renderBotAction = (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => {
+ const owner = meta.kwant_id ?? undefined;
+ return (
+ <BotActionCard
+ meta={meta}
+ messageId={msg.id}
+ kwantName={kwantName(owner) ?? (msg.sender_id && msg.sender_id.length <= 20 ? msg.sender_id : chatTitle)}
+ kwantId={owner}
+ live={botActions[meta.action_id]}
+ onDecide={handleBotActionDecision}
+ onOpenRoutine={handleOpenRoutine}
+ flash={flash}
+ />
+ );
+ };
+ const renderHire = (msg: ChatMessage, meta: HireMeta, flash: boolean) => {
+ const owner = meta.kwant_id ?? undefined;
+ return (
+ <HireCard
+ meta={meta}
+ messageId={msg.id}
+ kwantName={meta.proposer_name || kwantName(owner) || chatTitle}
+ kwantId={owner}
+ live={hires[meta.hire_id]}
+ onDecide={handleHireDecision}
+ flash={flash}
+ />
+ );
+ };
+
const renderDelegation = (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => {
const queued = turnsIn(turns, meta.thread_id).find((t) => t.state === 'queued');
return (
@@ -2249,6 +2347,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
renderDelegation={renderDelegation}
renderQuestion={renderQuestion}
renderMcpSuggestion={renderMcpSuggestion}
+ renderBotAction={renderBotAction}
+ renderHire={renderHire}
awaitingAnswer={awaitingHere}
contextKey={openCtx}
/>
@@ -2419,6 +2519,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onManageTeam={(t) => setEditingTeam(t)}
onOpenTools={() => setIsMcpOpen(true)}
onOpenAppSettings={onOpenAppSettings}
+ routineFocus={routineFocus}
/>
)}
diff --git a/frontend/src/botActions.ts b/frontend/src/botActions.ts
new file mode 100644
index 00000000..2fc5d132
--- /dev/null
+++ b/frontend/src/botActions.ts
@@ -0,0 +1,418 @@
+// Bots changing the app (bot actions) and proposing to hire a new bot. Each shows as a card in
+// the chat; only the person can undo, confirm, decline, accept or deny.
+// Contract: docs/bot-actions.md.
+import { parseMetaObject } from './questions';
+import { Schedule, WEEKDAYS, describeSchedule, formatWhen } from './continuity';
+
+// ---------------------------------------------------------------------------
+// Bot actions
+
+export type BotActionStatus = 'applied' | 'undone' | 'pending' | 'confirmed' | 'declined';
+const ACTION_STATUSES: BotActionStatus[] = ['applied', 'undone', 'pending', 'confirmed', 'declined'];
+
+/** `meta` of a bot action card (`kind: "bot_action"`). */
+export interface BotActionMeta {
+ kind: 'bot_action';
+ action_id: string;
+ /** The tool that made it, e.g. `routine_create`. */
+ action: string;
+ kwant_id: string | null;
+ target_kind: string;
+ target_id: string | null;
+ summary: string;
+ details: Record<string, unknown>;
+ status: BotActionStatus;
+ can_undo: boolean;
+ needs_confirmation: boolean;
+ created_at: string | null;
+ resolved_at: string | null;
+}
+
+/** A bot action from the API or `bot_action_updated`; `card` is its meta. */
+export interface BotAction {
+ id: string;
+ status: string;
+ message_id?: string | null;
+ card?: unknown;
+}
+
+const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
+
+export function parseBotActionMeta(raw: unknown): BotActionMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'bot_action') return null;
+ const id = str(m.action_id);
+ if (!id) return null;
+ const status = ACTION_STATUSES.includes(m.status as BotActionStatus) ? (m.status as BotActionStatus) : 'applied';
+ return {
+ kind: 'bot_action',
+ action_id: id,
+ action: str(m.action) ?? '',
+ kwant_id: str(m.kwant_id),
+ target_kind: str(m.target_kind) ?? '',
+ target_id: str(m.target_id),
+ summary: str(m.summary) ?? '',
+ details: m.details && typeof m.details === 'object' && !Array.isArray(m.details) ? (m.details as Record<string, unknown>) : {},
+ status,
+ // A finished action never offers buttons, whatever the flags say.
+ can_undo: m.can_undo === true && status === 'applied',
+ needs_confirmation: m.needs_confirmation === true && status === 'pending',
+ created_at: str(m.created_at),
+ resolved_at: str(m.resolved_at),
+ };
+}
+
+const ACTION_RANK: Record<BotActionStatus, number> = { pending: 0, applied: 1, undone: 2, confirmed: 2, declined: 2 };
+
+/** Card state: the newer of the message's meta and the live card; a resolved card never goes back. */
+export function botActionView(meta: BotActionMeta, live?: BotActionMeta | null): BotActionMeta {
+ if (!live || live.action_id !== meta.action_id) return meta;
+ return ACTION_RANK[live.status] >= ACTION_RANK[meta.status] ? live : meta;
+}
+
+/** Keeps the latest card per action from `bot_action_updated` and route replies. */
+export function applyBotAction(map: Record<string, BotActionMeta>, a: BotAction | null | undefined): Record<string, BotActionMeta> {
+ const card = parseBotActionMeta(a?.card);
+ if (!card) return map;
+ const prev = map[card.action_id];
+ if (prev && ACTION_RANK[prev.status] > ACTION_RANK[card.status]) return map;
+ return { ...map, [card.action_id]: card };
+}
+
+const VERBS: Record<string, string> = {
+ routine_create: 'set up a routine',
+ routine_update: 'changed a routine',
+ routine_pause: 'paused a routine',
+ routine_resume: 'turned a routine back on',
+ routine_run_now: 'ran a routine',
+ routine_delete: 'deleted a routine',
+ follow_up_create: 'scheduled a check-in',
+ bot_create: 'created a bot',
+ bot_update: 'changed a bot',
+ bot_delete: 'wants to delete a bot',
+ bot_hire: 'hired a bot',
+ settings_update: 'changed a setting',
+ space_create: 'created a space',
+ space_update: 'changed this space',
+ space_archive: 'wants to archive this space',
+ channel_create: 'created a channel',
+ channel_update: 'changed a channel',
+ profile_delete: 'wants to remove an account',
+};
+
+/** "set up a routine": what the bot did, after its name. */
+export const actionVerb = (action: string) => VERBS[action] ?? 'changed something';
+
+/** "Coach set up a routine": the card's heading. */
+export const actionHeading = (botName: string, action: string) => `${botName} ${actionVerb(action)}`;
+
+/** The state line in plain words. Never "Done" once the change was undone or declined. */
+export function actionStateText(m: Pick<BotActionMeta, 'status' | 'action'>): { label: string; tone: 'ok' | 'wait' | 'off' } {
+ switch (m.status) {
+ case 'pending':
+ return { label: 'Needs your OK. Nothing changes until you confirm.', tone: 'wait' };
+ case 'undone':
+ return { label: 'Undone. It’s back the way it was.', tone: 'off' };
+ case 'confirmed':
+ return { label: 'Confirmed. It’s done.', tone: 'ok' };
+ case 'declined':
+ return { label: 'Declined. Nothing changed.', tone: 'off' };
+ default:
+ return { label: m.action === 'routine_run_now' ? 'Done. This can’t be undone.' : 'Done.', tone: 'ok' };
+ }
+}
+
+/** "created routine 'x'" → "Created routine 'x'". */
+export const sentence = (s: string) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
+
+/** A schedule from the card or the API, when the panel's helpers know its shape. */
+export function asSchedule(v: unknown): Schedule | null {
+ if (!v || typeof v !== 'object') return null;
+ const s = v as Record<string, unknown>;
+ const tz = typeof s.tz === 'string' ? s.tz : '';
+ switch (s.type) {
+ case 'once':
+ return typeof s.at === 'string' ? { type: 'once', at: s.at } : null;
+ case 'daily':
+ return typeof s.time === 'string' ? { type: 'daily', time: s.time, tz } : null;
+ case 'weekly': {
+ if (typeof s.time !== 'string' || !Array.isArray(s.weekdays)) return null;
+ const ids = WEEKDAYS.map((d) => d.id);
+ const days = s.weekdays.filter((d): d is (typeof ids)[number] => ids.includes(d as (typeof ids)[number]));
+ return { type: 'weekly', time: s.time, weekdays: days, tz };
+ }
+ case 'interval':
+ return typeof s.every_minutes === 'number' ? { type: 'interval', every_minutes: s.every_minutes } : null;
+ case 'monthly': {
+ if (typeof s.time !== 'string' || !Array.isArray(s.days)) return null;
+ const days = s.days.filter((d): d is number | 'last' => d === 'last' || (typeof d === 'number' && Number.isInteger(d) && d >= 1 && d <= 31));
+ return { type: 'monthly', time: s.time, days, tz };
+ }
+ case 'cron':
+ return typeof s.expression === 'string' ? { type: 'cron', expression: s.expression, tz } : null;
+ }
+ return null;
+}
+
+/** When a routine runs, in words: ours when we know the shape, else the server's `schedule_text`. */
+export function scheduleWords(schedule: unknown, scheduleText?: unknown): string {
+ const s = asSchedule(schedule);
+ if (s) return describeSchedule(s);
+ return typeof scheduleText === 'string' && scheduleText ? sentence(scheduleText) : 'Unknown schedule';
+}
+
+/** The facts a routine card lists: when, as whom, where, and the next run. */
+export function routineFacts(m: BotActionMeta): Array<{ label: string; value: string }> {
+ if (m.target_kind !== 'routine') return [];
+ const d = m.details;
+ const rows: Array<{ label: string; value: string }> = [];
+ if (d.schedule || d.schedule_text) rows.push({ label: 'When', value: scheduleWords(d.schedule, d.schedule_text) });
+ if (str(d.bot_name)) rows.push({ label: 'Runs as', value: d.bot_name as string });
+ if (str(d.delivers_to)) rows.push({ label: 'Posts in', value: d.delivers_to as string });
+ if (m.action === 'routine_run_now') {
+ if (str(d.run_status)) rows.push({ label: 'This run', value: RUN_WORDS[d.run_status as string] ?? (d.run_status as string) });
+ } else if (m.status === 'applied' && m.action !== 'routine_delete') {
+ const next = d.enabled === false ? 'Paused' : str(d.next_run_at) ? formatWhen(d.next_run_at as string) : null;
+ if (next) rows.push({ label: 'Next run', value: next });
+ }
+ return rows;
+}
+
+const RUN_WORDS: Record<string, string> = { running: 'Running', ok: 'Finished', error: 'Failed', skipped: 'Skipped, it was already running' };
+
+/** Edit and Pause make sense while the routine the card made or changed still exists. */
+export function routineButtons(m: BotActionMeta): { edit: boolean; pause: boolean } {
+ const live = m.target_kind === 'routine' && !!m.target_id && m.status === 'applied' && m.action !== 'routine_delete';
+ return { edit: live, pause: live && m.details.enabled !== false && m.action !== 'routine_pause' };
+}
+
+// ---------------------------------------------------------------------------
+// Hiring
+
+export type HireStatus = 'pending' | 'accepted' | 'auto_accepted' | 'denied' | 'undone';
+const HIRE_STATUSES: HireStatus[] = ['pending', 'accepted', 'auto_accepted', 'denied', 'undone'];
+
+export type HireEvidence =
+ | { basis: 'specialist'; needs: string[]; gap: string }
+ | { basis: 'repeated'; similar_requests: string[] }
+ | { basis: 'other'; text: string };
+
+/** `meta` of a hire proposal card (`kind: "hire_proposal"`). */
+export interface HireMeta {
+ kind: 'hire_proposal';
+ hire_id: string;
+ kwant_id: string | null;
+ proposer_name: string;
+ name: string;
+ role: string;
+ instructions: string;
+ model: string | null;
+ tools: Array<{ id: string; name: string | null }>;
+ team: { id: string; name: string } | null;
+ reason: string;
+ evidence: HireEvidence | null;
+ requested_by_person: boolean;
+ status: HireStatus;
+ auto: boolean;
+ choices: string[];
+ hired_kwant_id: string | null;
+ action_id: string | null;
+ can_undo: boolean;
+ policy: 'ask' | 'auto';
+ note: string | null;
+ created_at: string | null;
+ resolved_at: string | null;
+}
+
+/** A proposal from the API or `hire_updated`; `card` is its meta. */
+export interface Hire {
+ id: string;
+ status: string;
+ card?: unknown;
+}
+
+const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && !!x) : []);
+
+function parseEvidence(raw: unknown): HireEvidence | null {
+ if (typeof raw === 'string') return raw.trim() ? { basis: 'other', text: raw.trim() } : null;
+ if (!raw || typeof raw !== 'object') return null;
+ const e = raw as Record<string, unknown>;
+ if (e.basis === 'specialist') return { basis: 'specialist', needs: strs(e.needs), gap: str(e.gap) ?? '' };
+ if (e.basis === 'repeated') return { basis: 'repeated', similar_requests: strs(e.similar_requests) };
+ return null;
+}
+
+export function parseHireMeta(raw: unknown): HireMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'hire_proposal') return null;
+ const id = str(m.hire_id);
+ const name = str(m.name);
+ if (!id || !name) return null;
+ const status = HIRE_STATUSES.includes(m.status as HireStatus) ? (m.status as HireStatus) : 'pending';
+ const team = m.team && typeof m.team === 'object' ? (m.team as Record<string, unknown>) : null;
+ return {
+ kind: 'hire_proposal',
+ hire_id: id,
+ kwant_id: str(m.kwant_id),
+ proposer_name: str(m.proposer_name) ?? '',
+ name,
+ role: str(m.role) ?? '',
+ instructions: str(m.instructions) ?? '',
+ model: str(m.model),
+ tools: Array.isArray(m.tools)
+ ? m.tools.flatMap((t) => (t && typeof t === 'object' && str((t as Record<string, unknown>).id) ? [{ id: (t as Record<string, string>).id, name: str((t as Record<string, unknown>).name) }] : []))
+ : [],
+ team: team && str(team.id) ? { id: team.id as string, name: str(team.name) ?? 'a team' } : null,
+ reason: str(m.reason) ?? '',
+ evidence: parseEvidence(m.evidence),
+ requested_by_person: m.requested_by_person === true,
+ status,
+ auto: m.auto === true,
+ choices: status === 'pending' ? strs(m.choices) : [],
+ hired_kwant_id: str(m.hired_kwant_id),
+ action_id: str(m.action_id),
+ can_undo: m.can_undo === true && !!str(m.action_id) && (status === 'accepted' || status === 'auto_accepted'),
+ policy: m.policy === 'auto' ? 'auto' : 'ask',
+ note: str(m.note),
+ created_at: str(m.created_at),
+ resolved_at: str(m.resolved_at),
+ };
+}
+
+const HIRE_RANK: Record<HireStatus, number> = { pending: 0, accepted: 1, auto_accepted: 1, denied: 2, undone: 2 };
+
+export function hireView(meta: HireMeta, live?: HireMeta | null): HireMeta {
+ if (!live || live.hire_id !== meta.hire_id) return meta;
+ return HIRE_RANK[live.status] >= HIRE_RANK[meta.status] ? live : meta;
+}
+
+export function applyHire(map: Record<string, HireMeta>, h: Hire | null | undefined): Record<string, HireMeta> {
+ const card = parseHireMeta(h?.card);
+ if (!card) return map;
+ const prev = map[card.hire_id];
+ if (prev && HIRE_RANK[prev.status] > HIRE_RANK[card.status]) return map;
+ return { ...map, [card.hire_id]: card };
+}
+
+const NEEDS: Record<string, string> = { instructions: 'its own instructions', tools: 'its own tools', schedule: 'a schedule', model: 'a different model' };
+
+/** What the proposal rests on, in one sentence. */
+export function evidenceText(e: HireEvidence | null, requestedByPerson: boolean): string {
+ if (requestedByPerson) return 'You asked for this kind of bot.';
+ if (!e) return '';
+ if (e.basis === 'repeated') {
+ const n = e.similar_requests.length;
+ return `You asked for this kind of work ${n} ${n === 1 ? 'time' : 'times'} in this space.`;
+ }
+ if (e.basis === 'specialist') {
+ const needs = e.needs.map((n) => NEEDS[n] ?? n);
+ const list = needs.length > 1 ? `${needs.slice(0, -1).join(', ')} and ${needs[needs.length - 1]}` : needs[0];
+ const lead = list ? `This work needs ${list}.` : '';
+ return [lead, e.gap ? sentence(e.gap.trim()).replace(/([^.!?])$/, '$1.') : ''].filter(Boolean).join(' ');
+ }
+ return e.text;
+}
+
+/** "auto" or empty means the app picks; anything else is shown as is. */
+export const modelText = (model: string | null) => (!model || model === 'auto' ? 'Picked automatically' : model);
+
+export function hireStateText(h: Pick<HireMeta, 'status' | 'name' | 'team' | 'proposer_name'>): { label: string; tone: 'ok' | 'wait' | 'off' } {
+ switch (h.status) {
+ case 'accepted':
+ return { label: `Hired. ${h.name} ${h.team ? `joined ${h.team.name}` : 'is ready'}.`, tone: 'ok' };
+ case 'auto_accepted':
+ return { label: `Hired at once, because you chose Always accept. ${h.name} ${h.team ? `joined ${h.team.name}` : 'is ready'}.`, tone: 'ok' };
+ case 'denied':
+ return { label: `Not hired. Bots here won’t suggest this kind of bot again unless you ask.`, tone: 'off' };
+ case 'undone':
+ return { label: `Hire undone. ${h.name} was removed.`, tone: 'off' };
+ default:
+ return { label: `Waiting for you. ${h.proposer_name || 'The bot'} carries on with your request meanwhile.`, tone: 'wait' };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Hire policy (Space settings)
+
+export interface HirePolicy {
+ space_id: string;
+ policy: 'ask' | 'auto';
+ auto_hires_last_24h: number;
+ auto_hires_per_day: number;
+ denied: Array<{ hire_id: string; name: string; role: string; denied_at: string }>;
+ denials_cleared_at: string | null;
+ updated_at: string | null;
+}
+
+export function parseHirePolicy(raw: unknown): HirePolicy | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const p = raw as Record<string, unknown>;
+ const num = (v: unknown, d: number) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
+ return {
+ space_id: str(p.space_id) ?? '',
+ policy: p.policy === 'auto' ? 'auto' : 'ask',
+ auto_hires_last_24h: num(p.auto_hires_last_24h, 0),
+ auto_hires_per_day: num(p.auto_hires_per_day, 3),
+ denied: Array.isArray(p.denied)
+ ? p.denied.flatMap((d) => {
+ if (!d || typeof d !== 'object') return [];
+ const x = d as Record<string, unknown>;
+ return str(x.name) || str(x.role) ? [{ hire_id: str(x.hire_id) ?? '', name: str(x.name) ?? '', role: str(x.role) ?? '', denied_at: str(x.denied_at) ?? '' }] : [];
+ })
+ : [],
+ denials_cleared_at: str(p.denials_cleared_at),
+ updated_at: str(p.updated_at),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Routes
+
+/** An API error that keeps its HTTP status, so a 409 can read as "already decided". */
+export class ApiError extends Error {
+ constructor(message: string, readonly status: number) {
+ super(message);
+ }
+}
+
+async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
+ const res = await fetch(url, {
+ method,
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => null);
+ if (!res.ok) {
+ const fallback = res.status === 404 ? 'It no longer exists.' : `Request failed (HTTP ${res.status}).`;
+ throw new ApiError(typeof data?.error === 'string' && data.error ? data.error : fallback, res.status);
+ }
+ return data as T;
+}
+
+/** A failed button in plain words; a 409 means someone (or another tab) got there first. */
+export function decisionError(err: unknown, what: string): string {
+ if (err instanceof ApiError && err.status === 409) {
+ const why = err.message && !/^Request failed/.test(err.message) ? ` (${err.message.replace(/\.$/, '')})` : '';
+ return `Couldn’t ${what}: it was already decided or changed${why}.`;
+ }
+ if (err instanceof ApiError && err.status === 403) return `Couldn’t ${what}: only you can do this, from your own browser.`;
+ return `Couldn’t ${what}: ${err instanceof Error ? err.message : 'something went wrong.'}`;
+}
+
+const enc = encodeURIComponent;
+
+export const botActionsApi = {
+ list: () => call<BotAction[]>('GET', '/api/bot-actions'),
+ undo: (id: string) => call<BotAction>('POST', `/api/bot-actions/${enc(id)}/undo`),
+ confirm: (id: string) => call<BotAction>('POST', `/api/bot-actions/${enc(id)}/confirm`),
+ decline: (id: string) => call<BotAction>('POST', `/api/bot-actions/${enc(id)}/decline`),
+};
+
+export const hiresApi = {
+ list: () => call<Hire[]>('GET', '/api/hires'),
+ accept: (id: string, always = false) => call<Hire>('POST', `/api/hires/${enc(id)}/accept`, always ? { always: true } : {}),
+ deny: (id: string) => call<Hire>('POST', `/api/hires/${enc(id)}/deny`),
+ policy: (spaceId: string) => call<unknown>('GET', `/api/spaces/${enc(spaceId)}/hire-policy`),
+ setPolicy: (spaceId: string, body: { policy?: 'ask' | 'auto'; clear_denials?: boolean }) =>
+ call<unknown>('PUT', `/api/spaces/${enc(spaceId)}/hire-policy`, body),
+};
diff --git a/frontend/src/components/BotActionCard.tsx b/frontend/src/components/BotActionCard.tsx
new file mode 100644
index 00000000..b44bc799
--- /dev/null
+++ b/frontend/src/components/BotActionCard.tsx
@@ -0,0 +1,156 @@
+import React, { useState } from 'react';
+import { AlertTriangle, CalendarClock, CheckCircle2, Loader2, MinusCircle, Pause, Pencil, ShieldQuestion, Undo2, Wrench } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { BotActionMeta, actionStateText, actionVerb, botActionView, routineButtons, routineFacts, sentence } from '../botActions';
+
+export type BotActionDecision = 'undo' | 'confirm' | 'decline';
+
+export interface BotActionCardProps {
+ meta: BotActionMeta;
+ messageId: string;
+ kwantName: string;
+ kwantId?: string;
+ /** Newer card from `bot_action_updated` or a button's reply; wins over `meta` unless older. */
+ live?: BotActionMeta | null;
+ /** Resolves to an error message on failure. */
+ onDecide: (actionId: string, decision: BotActionDecision) => Promise<string | void>;
+ /** Opens Space settings → Routines at this routine. */
+ onOpenRoutine?: (routineId: string, mode: 'edit' | 'pause') => void;
+ flash?: boolean;
+}
+
+const btn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[32px] px-3 rounded-xl text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2';
+const quiet = `${btn} text-zinc-200 border border-zinc-700 hover:bg-zinc-800 focus-visible:outline-zinc-500`;
+
+/**
+ * A change a bot made in the app (or wants to make), in the chat: what it did in one sentence,
+ * the routine's facts when it's a routine, and the person's buttons (Undo, or Confirm/Decline).
+ * Once resolved it says so plainly, so an undone change never still reads "Done".
+ */
+export const BotActionCard: React.FC<BotActionCardProps> = ({ meta, messageId, kwantName, kwantId, live, onDecide, onOpenRoutine, flash }) => {
+ const view = botActionView(meta, live);
+ const [busy, setBusy] = useState<BotActionDecision | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const decide = async (d: BotActionDecision) => {
+ if (busy) return;
+ setBusy(d);
+ setError(null);
+ const err = await onDecide(view.action_id, d);
+ setBusy(null);
+ if (err) setError(err);
+ };
+
+ const headingId = `bot-action-${messageId}`;
+ const state = actionStateText(view);
+ const facts = routineFacts(view);
+ const { edit, pause } = routineButtons(view);
+ const reason = view.status === 'pending' && typeof view.details.reason === 'string' ? view.details.reason : '';
+ const isRoutine = view.target_kind === 'routine';
+ const resolved = view.status === 'undone' || view.status === 'declined';
+ const border = view.status === 'pending' ? 'border-amber-500/40' : resolved ? 'border-zinc-800' : 'border-emerald-500/25';
+ const Icon = view.status === 'pending' ? ShieldQuestion : isRoutine ? CalendarClock : Wrench;
+
+ return (
+ <section data-message-id={messageId} aria-labelledby={headingId} className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}>
+ <ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} />
+ <div className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${border}`}>
+ <div className="px-4 pt-3 pb-2 space-y-1.5">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
+ <Icon size={12} className={view.status === 'pending' ? 'text-amber-300' : 'text-sky-300'} aria-hidden="true" />
+ <span id={headingId}>
+ <span className="text-zinc-200">{kwantName}</span>
+ {` ${actionVerb(view.action)}`}
+ </span>
+ </span>
+ <p className={`text-sm break-words leading-relaxed ${resolved ? 'text-zinc-400 line-through decoration-zinc-600' : 'text-zinc-100'}`}>
+ {sentence(view.summary) || 'A change in the app.'}
+ </p>
+ {reason && (
+ <p className="text-sm text-zinc-300 break-words leading-relaxed">
+ <span className="text-zinc-500">Why: </span>
+ {reason}
+ </p>
+ )}
+ </div>
+
+ {facts.length > 0 && (
+ <dl className="mx-4 mb-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 text-xs">
+ {facts.map((f) => (
+ <React.Fragment key={f.label}>
+ <dt className="text-zinc-500">{f.label}</dt>
+ <dd className={`min-w-0 break-words ${resolved ? 'text-zinc-500' : 'text-zinc-200'}`}>{f.value}</dd>
+ </React.Fragment>
+ ))}
+ </dl>
+ )}
+
+ <div className="px-4 pb-3 pt-0.5 space-y-2">
+ <p role="status" aria-live="polite" className="text-[11px]">
+ <span
+ className={`inline-flex items-center gap-1.5 ${state.tone === 'ok' ? 'text-emerald-300' : state.tone === 'wait' ? 'text-amber-200' : 'text-zinc-400'}`}
+ >
+ {state.tone === 'ok' ? (
+ <CheckCircle2 size={13} aria-hidden="true" />
+ ) : state.tone === 'wait' ? (
+ <ShieldQuestion size={13} aria-hidden="true" />
+ ) : (
+ <MinusCircle size={13} aria-hidden="true" />
+ )}
+ {state.label}
+ </span>
+ </p>
+
+ {(view.can_undo || view.needs_confirmation || edit || pause) && (
+ <div className="flex flex-wrap items-center gap-2">
+ {view.needs_confirmation && (
+ <>
+ <button
+ type="button"
+ onClick={() => decide('confirm')}
+ disabled={busy !== null}
+ className={`${btn} bg-amber-500 text-zinc-950 hover:bg-amber-400 focus-visible:outline-amber-400`}
+ >
+ {busy === 'confirm' && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {busy === 'confirm' ? 'Confirming…' : 'Confirm'}
+ </button>
+ <button type="button" onClick={() => decide('decline')} disabled={busy !== null} className={quiet}>
+ {busy === 'decline' ? 'Declining…' : 'Decline'}
+ </button>
+ </>
+ )}
+ {view.can_undo && (
+ <button type="button" onClick={() => decide('undo')} disabled={busy !== null} className={quiet}>
+ {busy === 'undo' ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : (
+ <Undo2 size={13} aria-hidden="true" />
+ )}
+ {busy === 'undo' ? 'Undoing…' : 'Undo'}
+ </button>
+ )}
+ {edit && onOpenRoutine && view.target_id && (
+ <button type="button" onClick={() => onOpenRoutine(view.target_id!, 'edit')} disabled={busy !== null} className={quiet}>
+ <Pencil size={12} aria-hidden="true" /> Edit
+ </button>
+ )}
+ {pause && onOpenRoutine && view.target_id && (
+ <button type="button" onClick={() => onOpenRoutine(view.target_id!, 'pause')} disabled={busy !== null} className={quiet}>
+ <Pause size={12} aria-hidden="true" /> Pause
+ </button>
+ )}
+ </div>
+ )}
+
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 rounded-lg border border-rose-500/30 bg-rose-500/10 px-2.5 py-1.5 text-xs text-rose-200 break-words">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{error}</span>
+ </p>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 78a42557..e822fb0c 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -12,6 +12,7 @@ import { PinnedInstructions, PinnedItem } from './Instructions';
import { DelegationMeta, parseDelegationMeta } from '../threads';
import { QuestionMeta, parseQuestionMeta } from '../questions';
import { SuggestionMeta, parseSuggestionMeta } from '../mcpSuggestions';
+import { BotActionMeta, HireMeta, parseBotActionMeta, parseHireMeta } from '../botActions';
import {
AttachmentRef,
MAX_ATTACHMENTS,
@@ -155,6 +156,10 @@ export interface ChatViewProps {
renderQuestion?: (msg: ChatMessage, meta: QuestionMeta, flash: boolean) => React.ReactNode;
/** Draws a bot's tool suggestion card (messages with `mcp_suggestion` meta). */
renderMcpSuggestion?: (msg: ChatMessage, meta: SuggestionMeta, flash: boolean) => React.ReactNode;
+ /** A change a bot made in the app (message meta kind "bot_action"). */
+ renderBotAction?: (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => React.ReactNode;
+ /** A bot's proposal to hire a new bot (message meta kind "hire_proposal"). */
+ renderHire?: (msg: ChatMessage, meta: HireMeta, flash: boolean) => React.ReactNode;
/** The open chat's turn is paused on a question: it is waiting for the person, not working. */
awaitingAnswer?: boolean;
/** Changes when another chat opens, so the view jumps to its bottom. */
@@ -303,6 +308,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
renderDelegation,
renderQuestion,
renderMcpSuggestion,
+ renderBotAction,
+ renderHire,
awaitingAnswer,
contextKey,
}) => {
@@ -641,6 +648,10 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, flashId === msg.id)}</React.Fragment>;
const suggestion = msg.meta && renderMcpSuggestion ? parseSuggestionMeta(msg.meta) : null;
if (suggestion && renderMcpSuggestion) return <React.Fragment key={msg.id}>{renderMcpSuggestion(msg, suggestion, flashId === msg.id)}</React.Fragment>;
+ const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;
+ if (botAction && renderBotAction) return <React.Fragment key={msg.id}>{renderBotAction(msg, botAction, flashId === msg.id)}</React.Fragment>;
+ const hire = msg.meta && renderHire ? parseHireMeta(msg.meta) : null;
+ if (hire && renderHire) return <React.Fragment key={msg.id}>{renderHire(msg, hire, flashId === msg.id)}</React.Fragment>;
const isUser = msg.sender_role === 'user';
const files = msg.meta ? parseAttachments(msg.meta) : [];
// A bot's share_file note: the file tiles say it all.
diff --git a/frontend/src/components/HireCard.tsx b/frontend/src/components/HireCard.tsx
new file mode 100644
index 00000000..d36b0535
--- /dev/null
+++ b/frontend/src/components/HireCard.tsx
@@ -0,0 +1,185 @@
+import React, { useId, useState } from 'react';
+import { AlertTriangle, CheckCircle2, ChevronDown, ChevronRight, Loader2, MinusCircle, Undo2, UserPlus } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { HireMeta, evidenceText, hireStateText, hireView, modelText } from '../botActions';
+
+export type HireDecision = 'deny' | 'accept_once' | 'always_accept' | 'undo';
+
+export interface HireCardProps {
+ meta: HireMeta;
+ messageId: string;
+ kwantName: string;
+ kwantId?: string;
+ /** Newer card from `hire_updated` or a button's reply; wins over `meta` unless older. */
+ live?: HireMeta | null;
+ /** Resolves to an error message on failure. */
+ onDecide: (hire: HireMeta, decision: HireDecision) => Promise<string | void>;
+ flash?: boolean;
+}
+
+const btn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[32px] px-3 rounded-xl text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2';
+const quiet = `${btn} text-zinc-200 border border-zinc-700 hover:bg-zinc-800 focus-visible:outline-zinc-500`;
+const spin = <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />;
+
+/**
+ * A bot's proposal to hire a new bot: who it would be, which team it joins, why, and what that
+ * rests on. The person denies, accepts once or always accepts; an accepted hire can be undone.
+ */
+export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName, kwantId, live, onDecide, flash }) => {
+ const view = hireView(meta, live);
+ const [busy, setBusy] = useState<HireDecision | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [showInstructions, setShowInstructions] = useState(false);
+ const instructionsId = useId();
+
+ const decide = async (d: HireDecision) => {
+ if (busy) return;
+ setBusy(d);
+ setError(null);
+ const err = await onDecide(view, d);
+ setBusy(null);
+ if (err) setError(err);
+ };
+
+ const headingId = `hire-${messageId}`;
+ const proposer = view.proposer_name || kwantName;
+ const state = hireStateText({ ...view, proposer_name: proposer });
+ const pending = view.status === 'pending';
+ const done = view.status === 'denied' || view.status === 'undone';
+ const evidence = evidenceText(view.evidence, view.requested_by_person);
+ const border = pending ? 'border-violet-500/40' : done ? 'border-zinc-800' : 'border-emerald-500/25';
+ const can = (c: string) => pending && view.choices.includes(c);
+
+ return (
+ <section data-message-id={messageId} aria-labelledby={headingId} className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}>
+ <ModernAvatar role={kwantName} name={kwantName} size={34} kwantId={kwantId} />
+ <div className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${border}`}>
+ <div className="px-4 pt-3 pb-2 space-y-1.5">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
+ <UserPlus size={12} className="text-violet-300" aria-hidden="true" />
+ <span>
+ <span className="text-zinc-200">{proposer}</span>
+ {view.status === 'auto_accepted' ? ' hired a new bot' : pending ? ' proposes hiring a new bot' : ' proposed hiring a new bot'}
+ </span>
+ </span>
+ <div className="flex items-center gap-2.5 min-w-0">
+ <ModernAvatar role={view.role || view.name} name={view.name} size={28} kwantId={view.hired_kwant_id ?? undefined} />
+ <div className="min-w-0">
+ <h3 id={headingId} className={`text-sm font-semibold break-words leading-snug ${done ? 'text-zinc-400' : 'text-zinc-100'}`}>
+ {view.name}
+ </h3>
+ {view.role && <p className="text-xs text-zinc-400 break-words">{view.role}</p>}
+ </div>
+ </div>
+ {view.reason && (
+ <p className="text-sm text-zinc-300 break-words leading-relaxed">
+ <span className="text-zinc-500">Why: </span>
+ {view.reason}
+ </p>
+ )}
+ {evidence && (
+ <p className="text-sm text-zinc-300 break-words leading-relaxed">
+ <span className="text-zinc-500">Based on: </span>
+ {evidence}
+ </p>
+ )}
+ </div>
+
+ <dl className="mx-4 mb-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 text-xs">
+ <dt className="text-zinc-500">Team</dt>
+ <dd className="min-w-0 break-words text-zinc-200">{view.team ? view.team.name : 'No team'}</dd>
+ <dt className="text-zinc-500">Model</dt>
+ <dd className="min-w-0 break-words text-zinc-200">{modelText(view.model)}</dd>
+ <dt className="text-zinc-500">Tools</dt>
+ <dd className="min-w-0 break-words text-zinc-200">{view.tools.length ? view.tools.map((t) => t.name || 'Unknown tool').join(', ') : 'None'}</dd>
+ </dl>
+
+ {view.instructions && (
+ <div className="mx-4 mb-2">
+ <button
+ type="button"
+ onClick={() => setShowInstructions((v) => !v)}
+ aria-expanded={showInstructions}
+ aria-controls={instructionsId}
+ className="inline-flex items-center gap-1 min-h-[32px] text-xs text-zinc-300 hover:text-zinc-100 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"
+ >
+ {showInstructions ? <ChevronDown size={13} aria-hidden="true" /> : <ChevronRight size={13} aria-hidden="true" />}
+ {showInstructions ? 'Hide its instructions' : 'Show its instructions'}
+ </button>
+ {showInstructions && (
+ <p
+ id={instructionsId}
+ className="mt-1 max-h-64 overflow-y-auto rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2 text-xs text-zinc-300 whitespace-pre-wrap break-words leading-relaxed"
+ >
+ {view.instructions}
+ </p>
+ )}
+ </div>
+ )}
+
+ <div className="px-4 pb-3 pt-0.5 space-y-2">
+ <p role="status" aria-live="polite" className="text-[11px]">
+ <span className={`inline-flex items-start gap-1.5 ${state.tone === 'ok' ? 'text-emerald-300' : state.tone === 'wait' ? 'text-violet-200' : 'text-zinc-400'}`}>
+ {state.tone === 'ok' ? (
+ <CheckCircle2 size={13} className="mt-px shrink-0" aria-hidden="true" />
+ ) : state.tone === 'off' ? (
+ <MinusCircle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ ) : (
+ <UserPlus size={13} className="mt-px shrink-0" aria-hidden="true" />
+ )}
+ <span>{state.label}</span>
+ </span>
+ </p>
+ {view.note && <p className="text-[11px] text-amber-200 break-words">{view.note}</p>}
+
+ {pending && (
+ <div className="flex flex-wrap items-center gap-2">
+ {can('accept_once') && (
+ <button
+ type="button"
+ onClick={() => decide('accept_once')}
+ disabled={busy !== null}
+ className={`${btn} bg-violet-500 text-white hover:bg-violet-400 focus-visible:outline-violet-400`}
+ >
+ {busy === 'accept_once' && spin}
+ {busy === 'accept_once' ? 'Hiring…' : 'Accept once'}
+ </button>
+ )}
+ {can('always_accept') && (
+ <button type="button" onClick={() => decide('always_accept')} disabled={busy !== null} className={quiet}>
+ {busy === 'always_accept' && spin}
+ {busy === 'always_accept' ? 'Hiring…' : 'Always accept'}
+ </button>
+ )}
+ {can('deny') && (
+ <button type="button" onClick={() => decide('deny')} disabled={busy !== null} className={quiet}>
+ {busy === 'deny' ? 'Saying no…' : 'Deny'}
+ </button>
+ )}
+ </div>
+ )}
+ {pending && can('always_accept') && (
+ <p className="text-[11px] text-zinc-500">
+ Always accept hires later proposals in this space at once, up to 3 a day, each with Undo. You can change this in Space settings.
+ </p>
+ )}
+
+ {view.can_undo && (
+ <button type="button" onClick={() => decide('undo')} disabled={busy !== null} className={quiet}>
+ {busy === 'undo' ? spin : <Undo2 size={13} aria-hidden="true" />}
+ {busy === 'undo' ? 'Undoing…' : 'Undo'}
+ </button>
+ )}
+
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 rounded-lg border border-rose-500/30 bg-rose-500/10 px-2.5 py-1.5 text-xs text-rose-200 break-words">
+ <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />
+ <span>{error}</span>
+ </p>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/components/HirePolicyPanel.tsx b/frontend/src/components/HirePolicyPanel.tsx
new file mode 100644
index 00000000..055b5b10
--- /dev/null
+++ b/frontend/src/components/HirePolicyPanel.tsx
@@ -0,0 +1,173 @@
+import React, { useCallback, useEffect, useState } from 'react';
+import { AlertTriangle, Loader2, RefreshCw, UserPlus } from 'lucide-react';
+import { HirePolicy, decisionError, hiresApi, parseHirePolicy } from '../botActions';
+import { formatWhen } from '../continuity';
+
+const smallBtn =
+ 'inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[30px] px-2.5 rounded-lg text-xs 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`;
+
+/**
+ * Space settings: whether bots here may hire new bots without asking, how many automatic hires
+ * are left today, and the kinds of bot the person said no to (which they can clear).
+ */
+export const HirePolicyPanel: React.FC<{ spaceId: string; spaceName: string }> = ({ spaceId, spaceName }) => {
+ const [policy, setPolicy] = useState<HirePolicy | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<'policy' | 'clear' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ try {
+ const p = parseHirePolicy(await hiresApi.policy(spaceId));
+ if (!p) throw new Error('The answer made no sense.');
+ setPolicy(p);
+ setLoadError(null);
+ } catch (e) {
+ setLoadError(`Couldn’t load the hiring setting: ${e instanceof Error ? e.message : 'something went wrong.'}`);
+ }
+ }, [spaceId]);
+
+ useEffect(() => {
+ load();
+ // A hire decided in the chat changes the count and the denials.
+ const onHire = () => load();
+ window.addEventListener('kwnt:hire-updated', onHire);
+ return () => window.removeEventListener('kwnt:hire-updated', onHire);
+ }, [load]);
+
+ const save = async (body: { policy?: 'ask' | 'auto'; clear_denials?: boolean }, what: 'policy' | 'clear') => {
+ setBusy(what);
+ setError(null);
+ setNotice(null);
+ try {
+ const p = parseHirePolicy(await hiresApi.setPolicy(spaceId, body));
+ if (p) setPolicy(p);
+ setNotice(what === 'clear' ? 'Cleared. Bots may suggest those kinds of bot again.' : 'Saved.');
+ } catch (e) {
+ setError(decisionError(e, what === 'clear' ? 'clear the list' : 'save it'));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const name = `hire-policy-${spaceId}`;
+ const left = policy ? Math.max(0, policy.auto_hires_per_day - policy.auto_hires_last_24h) : 0;
+
+ return (
+ <section aria-labelledby={`${name}-title`} className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-4 space-y-3">
+ <div className="flex items-start gap-2">
+ <UserPlus size={15} className="mt-0.5 text-violet-300 shrink-0" aria-hidden="true" />
+ <div className="min-w-0">
+ <h4 id={`${name}-title`} className="text-sm font-semibold text-zinc-100">
+ Hiring new bots
+ </h4>
+ <p className="text-[11px] text-zinc-500 leading-relaxed">
+ A bot here may propose a new bot when a specialist would clearly do better, or when you keep asking for the same kind of work. Bots
+ can read this setting but can't change it.
+ </p>
+ </div>
+ </div>
+
+ {loadError && (
+ <div className="flex flex-wrap 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 className="min-w-0 break-words">{loadError}</span>
+ <button type="button" onClick={load} className={quietBtn}>
+ <RefreshCw size={12} aria-hidden="true" /> Try again
+ </button>
+ </div>
+ )}
+ {!policy && !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" aria-hidden="true" /> Loading…
+ </p>
+ )}
+
+ {policy && (
+ <>
+ <fieldset className="space-y-1.5" disabled={busy !== null}>
+ <legend className="sr-only">When a bot proposes a new bot in {spaceName}</legend>
+ {(
+ [
+ { id: 'ask', label: 'Ask me each time', hint: 'You choose Deny, Accept once or Always accept on each proposal.' },
+ {
+ id: 'auto',
+ label: 'Hire at once',
+ hint: `Proposals are hired straight away, each with Undo, up to ${policy.auto_hires_per_day} in 24 hours. After that it asks you again.`,
+ },
+ ] as const
+ ).map((o) => (
+ <label
+ key={o.id}
+ className={`flex items-start gap-2.5 rounded-lg border px-3 py-2 cursor-pointer transition-colors ${
+ policy.policy === o.id ? 'border-violet-500/50 bg-violet-500/10' : 'border-zinc-800 hover:border-zinc-700'
+ }`}
+ >
+ <input
+ type="radio"
+ name={name}
+ value={o.id}
+ checked={policy.policy === o.id}
+ onChange={() => save({ policy: o.id }, 'policy')}
+ className="mt-0.5 accent-violet-500"
+ />
+ <span className="min-w-0">
+ <span className="block text-xs font-medium text-zinc-100">{o.label}</span>
+ <span className="block text-[11px] text-zinc-500 leading-relaxed">{o.hint}</span>
+ </span>
+ </label>
+ ))}
+ </fieldset>
+
+ <p className="text-[11px] text-zinc-400">
+ Hired automatically in the last 24 hours:{' '}
+ <span className="text-zinc-100 font-medium">
+ {policy.auto_hires_last_24h} of {policy.auto_hires_per_day}
+ </span>
+ {policy.policy === 'auto' && <span className="text-zinc-500"> · {left === 0 ? 'the next one will ask you' : `${left} left`}</span>}
+ </p>
+
+ <div className="space-y-1.5">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h5 className="text-xs font-medium text-zinc-300">You said no to</h5>
+ {policy.denied.length > 0 && (
+ <button type="button" onClick={() => save({ clear_denials: true }, 'clear')} disabled={busy !== null} className={quietBtn}>
+ {busy === 'clear' && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ Clear denials
+ </button>
+ )}
+ </div>
+ {policy.denied.length === 0 ? (
+ <p className="text-[11px] text-zinc-500">Nothing. Bots here may propose any kind of bot.</p>
+ ) : (
+ <ul className="space-y-1" aria-label="Denied bots">
+ {policy.denied.map((d) => (
+ <li key={d.hire_id || `${d.name}-${d.denied_at}`} className="flex flex-wrap items-baseline gap-x-2 text-[11px] rounded-lg border border-zinc-800 px-2.5 py-1.5">
+ <span className="text-zinc-100 font-medium break-words">{d.name || 'A bot'}</span>
+ {d.role && <span className="text-zinc-400 break-words">{d.role}</span>}
+ {d.denied_at && <span className="text-zinc-600 ml-auto">{formatWhen(d.denied_at)}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {policy.denied.length > 0 && (
+ <p className="text-[11px] text-zinc-500">Bots here won't propose these kinds of bot again unless you ask for one.</p>
+ )}
+ </div>
+
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 text-[11px] text-rose-300 break-words">
+ <AlertTriangle size={12} className="mt-px shrink-0" aria-hidden="true" /> {error}
+ </p>
+ )}
+ {notice && !error && (
+ <p role="status" className="text-[11px] text-emerald-300">
+ {notice}
+ </p>
+ )}
+ </>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsx
index 8d644516..86fad274 100644
--- a/frontend/src/components/RoutinesPanel.tsx
+++ b/frontend/src/components/RoutinesPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useEffect, useId, useState } from 'react';
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Trash2 } from 'lucide-react';
import {
Routine,
@@ -9,14 +9,15 @@ import {
channelLabel,
continuityApi,
defaultTimeZone,
- describeSchedule,
emptyScheduleForm,
formFromSchedule,
formatWhen,
+ sortMonthDays,
onContinuity,
scheduleFromForm,
timeZoneOptions,
} from '../continuity';
+import { asSchedule, scheduleWords } from '../botActions';
import type { Channel, Kwant } from './Sidebar';
import { playSfx } from '../audio/chiptune';
@@ -27,6 +28,27 @@ 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;
+}
+
const STATUS: Record<RunStatus, { label: string; cls: string }> = {
running: { label: 'Running', cls: 'bg-sky-500/10 text-sky-300 border-sky-500/20' },
ok: { label: 'OK', cls: 'bg-emerald-500/10 text-emerald-300 border-emerald-500/20' },
@@ -59,13 +81,15 @@ const RoutineForm: React.FC<{
onSaved: () => void;
}> = ({ initial, fixedKwantId, kwants, channels, onCancel, onSaved }) => {
const uid = useId();
+ const initialChannel = initial?.thread_id ? IN_THREAD : initial?.channel_id ?? '';
+ const initialSchedule = initial ? asSchedule(initial.schedule) : null;
const [f, setF] = useState<FormState>(() => ({
kwantId: initial?.kwant_id ?? fixedKwantId ?? kwants[0]?.id ?? '',
- channelId: initial?.channel_id ?? '',
+ channelId: initialChannel,
name: initial?.name ?? '',
instructions: initial?.instructions ?? '',
enabled: initial?.enabled ?? true,
- schedule: initial ? formFromSchedule(initial.schedule) : emptyScheduleForm(),
+ schedule: initialSchedule ? formFromSchedule(initialSchedule) : emptyScheduleForm(),
}));
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -83,15 +107,19 @@ const RoutineForm: React.FC<{
setError(null);
const body = {
kwant_id: f.kwantId,
- channel_id: f.channelId || null,
+ 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 (initial) await continuityApi.updateRoutine(initial.id, body);
- else await continuityApi.createRoutine(body);
+ 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) {
@@ -122,6 +150,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>}
<option value="">Direct chat with the bot</option>
{channels.map((c) => (
<option key={c.id} value={c.id}>{channelLabel(c.name)}</option>
@@ -144,17 +173,17 @@ const RoutineForm: React.FC<{
<fieldset className="space-y-2">
<legend className={labelClass}>When</legend>
- <div className="grid grid-cols-4 gap-1 p-1 bg-zinc-950 rounded-lg border border-zinc-800" role="radiogroup" aria-label="Repeat">
- {(['once', 'daily', 'weekly', 'interval'] as const).map((t) => (
+ <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}
+ key={t.id}
type="button"
role="radio"
- aria-checked={s.type === t}
- onClick={() => setS({ type: t })}
- className={`py-1 rounded-md text-[11px] font-medium transition-colors ${s.type === t ? 'bg-sky-500/15 text-sky-200' : 'text-zinc-500 hover:text-zinc-300'}`}
+ aria-checked={s.type === t.id}
+ onClick={() => setS({ type: t.id })}
+ className={`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 === 'once' ? 'Once' : t === 'daily' ? 'Daily' : t === 'weekly' ? 'Weekly' : 'Every…'}
+ {t.label}
</button>
))}
</div>
@@ -167,12 +196,34 @@ const RoutineForm: React.FC<{
</div>
)}
- {(s.type === 'daily' || s.type === 'weekly') && (
+ {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">
- <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>
+ {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>
+ )}
<div>
<label htmlFor={id('tz')} className="text-[11px] text-zinc-500">Time zone</label>
<input id={id('tz')} list={id('tzs')} value={s.tz} onChange={(e) => setS({ tz: e.target.value })} className={inputClass} spellCheck={false} />
@@ -206,6 +257,42 @@ const RoutineForm: React.FC<{
</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>
@@ -281,9 +368,20 @@ const RoutineRow: React.FC<{
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;
onChanged: () => void;
-}> = ({ routine, kwantName, placeLabel, tick, onEdit, onChanged }) => {
+}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onChanged }) => {
+ 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 [confirm, setConfirm] = useState(false);
@@ -313,12 +411,13 @@ const RoutineRow: React.FC<{
});
return (
- <li className="rounded-xl border border-zinc-800 bg-zinc-950/60 p-3 space-y-2">
+ <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}
@@ -335,7 +434,7 @@ const RoutineRow: React.FC<{
</div>
<p className="text-[11px] text-zinc-500 break-words">
{kwantName ? `${kwantName} · ` : ''}
- {placeLabel} · {describeSchedule(routine.schedule)}
+ {placeLabel} · <span title={routine.schedule_text || undefined}>{scheduleWords(routine.schedule, routine.schedule_text)}</span>
</p>
<p className="text-[11px] text-zinc-400">
Next run: <span className="text-zinc-200">{routine.enabled ? formatWhen(routine.next_run_at) : 'off'}</span>
@@ -363,6 +462,9 @@ const RoutineRow: React.FC<{
<Trash2 size={11} /> {confirm ? 'Delete?' : 'Delete'}
</button>
{notice && <span className="text-[11px] text-zinc-400" role="status">{notice}</span>}
+ {highlight && routine.enabled && !notice && (
+ <span className="text-[11px] text-sky-200" role="status">Turn the switch off to pause it.</span>
+ )}
</div>
{error && <p className="pl-9 text-[11px] text-rose-400" role="alert">{error}</p>}
{open && (
@@ -375,7 +477,12 @@ 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[] }> = ({ kwantId, kwants, channels }) => {
+export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channels: Channel[]; focus?: RoutineFocus | null }> = ({
+ kwantId,
+ kwants,
+ channels,
+ focus,
+}) => {
const [routines, setRoutines] = useState<Routine[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [editing, setEditing] = useState<Routine | 'new' | null>(null);
@@ -399,8 +506,20 @@ export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channe
});
}, [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';
@@ -445,6 +564,11 @@ export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channe
<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>
+ )}
{routines && routines.length === 0 && editing !== 'new' && (
<div className="text-xs text-zinc-500 border border-dashed border-zinc-800 rounded-lg p-4 text-center space-y-1">
<CalendarClock size={18} className="mx-auto text-zinc-600" aria-hidden="true" />
@@ -465,6 +589,7 @@ export const RoutinesPanel: React.FC<{ kwantId?: string; kwants: Kwant[]; channe
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)}
onChanged={reload}
/>
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index 0e96d932..25fe4ac5 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -23,7 +23,8 @@ import { useEngines } from '../useEngines';
import { useProfiles } from '../useProfiles';
import type { Profile } from '../profiles';
import { EnginesPanel } from './EnginesPanel';
-import { RoutinesPanel } from './RoutinesPanel';
+import { RoutinesPanel, type RoutineFocus } from './RoutinesPanel';
+import { HirePolicyPanel } from './HirePolicyPanel';
import { ModernAvatar } from './ModernAvatar';
import { SpaceTile } from './Spaces';
import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';
@@ -63,6 +64,8 @@ interface Props {
onManageTeam: (t: Team) => void;
onOpenTools: () => void;
onOpenAppSettings: () => void;
+ /** Set by a routine card's Edit or Pause: opens that routine in Routines. */
+ routineFocus?: RoutineFocus | null;
}
const card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';
@@ -155,7 +158,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {
</div>
)}
{tab === 'skills' && <SkillsTab {...p} />}
- {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} />}
+ {tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} />}
<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">
<Settings size={14} /> App settings (every space)
@@ -357,6 +360,7 @@ const BotsTab: React.FC<Props> = ({ space, kwants, onNewBot, onEditBot }) => (
))}
</ul>
{kwants.length === 0 && <p className="text-xs text-zinc-500">No bots yet. New spaces start empty.</p>}
+ <HirePolicyPanel key={space.id} spaceId={space.id} spaceName={space.name} />
</div>
);
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index cf88b470..66788569 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -42,7 +42,13 @@ export type Schedule =
| { type: 'once'; at: string }
| { type: 'daily'; time: string; tz: string }
| { type: 'weekly'; time: string; weekdays: Weekday[]; tz: string }
- | { type: 'interval'; every_minutes: number };
+ | { type: 'interval'; every_minutes: number }
+ /** Days of the month (1-31, or `'last'`); a day a month lacks runs on its last day. */
+ | { type: 'monthly'; time: string; days: MonthDay[]; tz: string }
+ /** Five fields: minute hour day-of-month month weekday. The server checks the rest. */
+ | { type: 'cron'; expression: string; tz: string };
+
+export type MonthDay = number | 'last';
export type RunStatus = 'running' | 'ok' | 'error' | 'skipped';
@@ -59,6 +65,12 @@ export interface Routine {
last_run_at: string | null;
last_status: RunStatus | null;
created_at: string;
+ /** The schedule in the server's words, e.g. "monthly on day 1 at 09:00 Europe/Berlin". */
+ schedule_text?: string;
+ /** Set when it delivers into one of its bot's threads. */
+ thread_id?: string | null;
+ /** The message a follow-up checks back on. */
+ context_message_id?: string | null;
}
export interface RoutineRun {
@@ -193,6 +205,9 @@ export interface ScheduleForm {
weekdays: Weekday[];
tz: string;
everyMinutes: string;
+ monthDays: MonthDay[];
+ /** A raw five-field rule, for the "Custom" choice. */
+ cron: string;
}
/**
@@ -243,7 +258,16 @@ export function toLocalInput(d: Date): string {
export function emptyScheduleForm(now = new Date(), tz = defaultTimeZone()): ScheduleForm {
const soon = new Date(now.getTime() + 60 * 60 * 1000);
soon.setMinutes(0, 0, 0);
- return { type: 'daily', onceAt: toLocalInput(soon), time: '09:00', weekdays: ['mon', 'tue', 'wed', 'thu', 'fri'], tz, everyMinutes: '60' };
+ return {
+ type: 'daily',
+ onceAt: toLocalInput(soon),
+ time: '09:00',
+ weekdays: ['mon', 'tue', 'wed', 'thu', 'fri'],
+ tz,
+ everyMinutes: '60',
+ monthDays: [1],
+ cron: '0 9 * * 1-5',
+ };
}
export function formFromSchedule(s: Schedule, now = new Date()): ScheduleForm {
@@ -259,9 +283,19 @@ export function formFromSchedule(s: Schedule, now = new Date()): ScheduleForm {
return { ...base, type: 'weekly', time: s.time, weekdays: s.weekdays };
case 'interval':
return { ...base, type: 'interval', everyMinutes: String(s.every_minutes) };
+ case 'monthly':
+ return { ...base, type: 'monthly', time: s.time, monthDays: s.days.length ? sortMonthDays(s.days) : base.monthDays };
+ case 'cron':
+ return { ...base, type: 'cron', cron: s.expression };
+ default:
+ return base;
}
}
+/** 1, 2, … 31, then "last". */
+export const sortMonthDays = (days: MonthDay[]): MonthDay[] =>
+ Array.from(new Set(days)).sort((a, b) => (a === 'last' ? 32 : a) - (b === 'last' ? 32 : b));
+
/** The JSON the API takes, or a message for the first thing to fix. Mirrors the server's checks. */
export function scheduleFromForm(f: ScheduleForm, now = Date.now()): { schedule: Schedule } | { error: string } {
switch (f.type) {
@@ -272,11 +306,17 @@ export function scheduleFromForm(f: ScheduleForm, now = Date.now()): { schedule:
return { schedule: { type: 'once', at: at.toISOString() } };
}
case 'daily':
- case 'weekly': {
+ case 'weekly':
+ case 'monthly': {
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(f.time)) return { error: 'Use a time like 09:00.' };
const tz = canonicalTimeZone(f.tz.trim());
if (!tz) return { error: 'Pick a time zone.' };
if (f.type === 'daily') return { schedule: { type: 'daily', time: f.time, tz } };
+ if (f.type === 'monthly') {
+ const days = sortMonthDays(f.monthDays.filter((d) => d === 'last' || (Number.isInteger(d) && d >= 1 && d <= 31)));
+ if (days.length === 0) return { error: 'Pick at least one day of the month.' };
+ return { schedule: { type: 'monthly', time: f.time, days, tz } };
+ }
if (f.weekdays.length === 0) return { error: 'Pick at least one day.' };
const days = WEEKDAYS.map((d) => d.id).filter((d) => f.weekdays.includes(d));
return { schedule: { type: 'weekly', time: f.time, weekdays: days, tz } };
@@ -286,9 +326,32 @@ export function scheduleFromForm(f: ScheduleForm, now = Date.now()): { schedule:
if (!Number.isInteger(n) || n < 5 || n > 10080) return { error: 'Repeat every 5 to 10080 minutes.' };
return { schedule: { type: 'interval', every_minutes: n } };
}
+ case 'cron': {
+ const expression = f.cron.trim().replace(/\s+/g, ' ');
+ if (!expression) return { error: 'Type a rule, like 0 9 * * MON#2.' };
+ if (expression.startsWith('@')) return { error: 'Shortcuts like @daily aren’t supported. Write the five parts instead.' };
+ if (expression.split(' ').length !== 5) return { error: 'A rule has five parts: minute, hour, day of month, month and weekday.' };
+ const tz = canonicalTimeZone(f.tz.trim());
+ if (!tz) return { error: 'Pick a time zone.' };
+ return { schedule: { type: 'cron', expression, tz } };
+ }
}
}
+const ordinal = (n: number) => {
+ const t = n % 100;
+ if (t >= 11 && t <= 13) return `${n}th`;
+ return `${n}${['th', 'st', 'nd', 'rd'][n % 10] ?? 'th'}`;
+};
+
+/** "the 1st, 15th and last day". */
+export function monthDaysText(days: MonthDay[]): string {
+ const words = sortMonthDays(days).map((d) => (d === 'last' ? 'last day' : ordinal(d)));
+ if (words.length === 0) return 'no day';
+ const list = words.length > 1 ? `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}` : words[0];
+ return `the ${list}`;
+}
+
export function describeSchedule(s: Schedule): string {
switch (s.type) {
case 'once':
@@ -303,6 +366,12 @@ export function describeSchedule(s: Schedule): string {
return s.every_minutes % 60 === 0
? `Every ${s.every_minutes / 60} h`
: `Every ${s.every_minutes} min`;
+ case 'monthly':
+ return `Every month on ${monthDaysText(s.days)} at ${s.time} (${s.tz})`;
+ case 'cron':
+ return `Custom rule ${s.expression} (${s.tz})`;
+ default:
+ return 'Unknown schedule';
}
}
diff --git a/frontend/tests/botActions.test.mjs b/frontend/tests/botActions.test.mjs
new file mode 100644
index 00000000..4409db40
--- /dev/null
+++ b/frontend/tests/botActions.test.mjs
@@ -0,0 +1,278 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const b = await loadBundled(`export * from './src/botActions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { BotActionCard } from './src/components/BotActionCard';
+ import { HireCard } from './src/components/HireCard';
+ export const action = (props) => renderToStaticMarkup(React.createElement(BotActionCard, props));
+ export const hire = (props) => renderToStaticMarkup(React.createElement(HireCard, props));
+`);
+
+// Visible text only, so assertions don't match class names or ids.
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g)].map((m) => text(m[1]));
+
+const routineMeta = (over = {}) => ({
+ kind: 'bot_action', action_id: 'a1', action: 'routine_create', kwant_id: 'k1', target_kind: 'routine', target_id: 'r1',
+ summary: "created routine 'Morning motivation', daily 07:00 Europe/Berlin, delivering to #general",
+ details: {
+ routine_id: 'r1', name: 'Morning motivation', kwant_id: 'k1', bot_name: 'Coach',
+ schedule: { type: 'daily', time: '07:00', tz: 'Europe/Berlin' }, schedule_text: 'daily 07:00 Europe/Berlin', enabled: true,
+ next_run_at: '2026-10-19T05:00:00Z', channel_id: 'c1', delivers_to: '#general',
+ },
+ status: 'applied', can_undo: true, needs_confirmation: false, created_at: '2026-10-18T10:00:00Z', resolved_at: null, ...over,
+});
+const actionProps = (meta, over = {}) => ({
+ meta: b.parseBotActionMeta(meta), messageId: 'm1', kwantName: 'Coach', kwantId: 'k1',
+ onDecide: async () => {}, onOpenRoutine: () => {}, ...over,
+});
+
+test('bot action meta parses and finished actions never offer buttons', () => {
+ const m = b.parseBotActionMeta(JSON.stringify(routineMeta()));
+ assert.equal(m.action_id, 'a1');
+ assert.equal(m.can_undo, true);
+ assert.equal(b.parseBotActionMeta(routineMeta({ status: 'undone', can_undo: true })).can_undo, false);
+ assert.equal(b.parseBotActionMeta(routineMeta({ status: 'confirmed', needs_confirmation: true })).needs_confirmation, false);
+ assert.equal(b.parseBotActionMeta({ kind: 'hire_proposal', hire_id: 'h' }), null);
+ assert.equal(b.parseBotActionMeta({ kind: 'bot_action' }), null);
+ assert.equal(b.parseBotActionMeta('nope'), null);
+});
+
+test('applied routine card: summary, routine facts, Undo, Edit and Pause', () => {
+ const html = ui.action(actionProps(routineMeta()));
+ const t = text(html);
+ assert.match(t, /Coach set up a routine/);
+ assert.match(t, /Created routine 'Morning motivation'/);
+ assert.match(t, /When Every day at 07:00 \(Europe\/Berlin\)/);
+ assert.match(t, /Runs as Coach/);
+ assert.match(t, /Posts in #general/);
+ assert.match(t, /Next run/);
+ assert.match(t, /Done\./);
+ assert.deepEqual(buttons(html), ['Undo', 'Edit', 'Pause']);
+});
+
+test('undone card says Undone, not Done, and offers nothing', () => {
+ const html = ui.action(actionProps(routineMeta({ status: 'undone', can_undo: false, resolved_at: '2026-10-18T10:05:00Z' })));
+ const t = text(html);
+ assert.match(t, /Undone\. It's back the way it was\./);
+ assert.doesNotMatch(t, /\bDone\./);
+ assert.doesNotMatch(t, /Next run/);
+ assert.match(html, /line-through/);
+ assert.deepEqual(buttons(html), []);
+});
+
+test('a live update wins over the message meta, and a resolved card never goes back', () => {
+ const applied = b.parseBotActionMeta(routineMeta());
+ const undone = b.parseBotActionMeta(routineMeta({ status: 'undone', can_undo: false }));
+ assert.equal(b.botActionView(applied, undone).status, 'undone');
+ assert.equal(b.botActionView(undone, applied).status, 'undone');
+ assert.equal(b.botActionView(applied, b.parseBotActionMeta(routineMeta({ action_id: 'other', status: 'undone' }))).status, 'applied');
+
+ let map = b.applyBotAction({}, { id: 'a1', status: 'undone', card: routineMeta({ status: 'undone' }) });
+ map = b.applyBotAction(map, { id: 'a1', status: 'applied', card: routineMeta() });
+ assert.equal(map.a1.status, 'undone');
+ assert.equal(b.applyBotAction(map, { id: 'x', card: null }), map);
+
+ const html = ui.action(actionProps(routineMeta(), { live: undone }));
+ assert.match(text(html), /Undone\./);
+ assert.deepEqual(buttons(html), []);
+});
+
+test('pending action: reason, Confirm and Decline; then Confirmed or Declined', () => {
+ const pending = routineMeta({
+ action: 'routine_delete', status: 'pending', can_undo: false, needs_confirmation: true,
+ summary: "delete routine 'Morning motivation'", details: { ...routineMeta().details, reason: 'You said you no longer need it.' },
+ });
+ const html = ui.action(actionProps(pending));
+ const t = text(html);
+ assert.match(t, /Needs your OK\. Nothing changes until you confirm\./);
+ assert.match(t, /Why: You said you no longer need it\./);
+ assert.deepEqual(buttons(html), ['Confirm', 'Decline']);
+
+ const confirmed = ui.action(actionProps({ ...pending, status: 'confirmed', needs_confirmation: false }));
+ assert.match(text(confirmed), /Confirmed\. It's done\./);
+ assert.doesNotMatch(text(confirmed), /Why:/);
+ assert.deepEqual(buttons(confirmed), []);
+
+ const declined = ui.action(actionProps({ ...pending, status: 'declined', needs_confirmation: false }));
+ assert.match(text(declined), /Declined\. Nothing changed\./);
+ assert.deepEqual(buttons(declined), []);
+});
+
+test('run now cannot be undone and shows the run, not the next run', () => {
+ const html = ui.action(
+ actionProps(routineMeta({ action: 'routine_run_now', can_undo: false, details: { ...routineMeta().details, run_id: 'run1', run_status: 'ok' } })),
+ );
+ const t = text(html);
+ assert.match(t, /Done\. This can't be undone\./);
+ assert.match(t, /This run Finished/);
+ assert.doesNotMatch(t, /Next run/);
+ assert.deepEqual(buttons(html), ['Edit', 'Pause']);
+});
+
+test('Edit and Pause only while the routine exists; Pause hides when it is paused', () => {
+ const r = (over) => b.routineButtons(b.parseBotActionMeta(routineMeta(over)));
+ assert.deepEqual(r({}), { edit: true, pause: true });
+ assert.deepEqual(r({ details: { ...routineMeta().details, enabled: false } }), { edit: true, pause: false });
+ assert.deepEqual(r({ action: 'routine_pause' }), { edit: true, pause: false });
+ assert.deepEqual(r({ action: 'routine_delete' }), { edit: false, pause: false });
+ assert.deepEqual(r({ status: 'undone' }), { edit: false, pause: false });
+ assert.deepEqual(r({ target_kind: 'bot' }), { edit: false, pause: false });
+ const paused = text(ui.action(actionProps(routineMeta({ action: 'routine_pause', details: { ...routineMeta().details, enabled: false } }))));
+ assert.match(paused, /Next run Paused/);
+});
+
+test('non-routine actions: no routine facts, verb fallback', () => {
+ const html = ui.action(
+ actionProps(routineMeta({ action: 'bot_update', target_kind: 'bot', target_id: 'k2', summary: 'renamed Scout to Finder', details: { name: 'Finder' } })),
+ );
+ const t = text(html);
+ assert.match(t, /Renamed Scout to Finder/);
+ assert.doesNotMatch(t, /Runs as|When/);
+ assert.deepEqual(buttons(html), ['Undo']);
+ assert.equal(b.actionVerb('something_new'), 'changed something');
+});
+
+test('schedules in words: ours for known shapes, the server text otherwise', () => {
+ assert.equal(b.scheduleWords({ type: 'monthly', time: '09:00', days: [1, 'last'], tz: 'UTC' }), 'Every month on the 1st and last day at 09:00 (UTC)');
+ assert.equal(b.scheduleWords({ type: 'cron', expression: '0 9 * * MON#2', tz: 'UTC' }), 'Custom rule 0 9 * * MON#2 (UTC)');
+ assert.equal(b.scheduleWords({ type: 'lunar' }, 'when the moon is full'), 'When the moon is full');
+ assert.equal(b.scheduleWords(null, ''), 'Unknown schedule');
+ assert.equal(b.asSchedule({ type: 'monthly', time: '09:00', days: [0, 5, 'last', 'x'], tz: 'UTC' }).days.join(), '5,last');
+ assert.equal(b.asSchedule({ type: 'weekly', time: '09:00', weekdays: ['mon', 'xyz'], tz: 'UTC' }).weekdays.join(), 'mon');
+ assert.equal(b.asSchedule({ type: 'cron' }), null);
+});
+
+// ---------------------------------------------------------------------------
+// Hiring
+
+const hireMeta = (over = {}) => ({
+ kind: 'hire_proposal', hire_id: 'h1', kwant_id: 'k1', proposer_name: 'Ada', name: 'Ledger', role: 'Bookkeeper',
+ instructions: 'Keep the books.\nReconcile weekly.', model: 'auto', tools: [{ id: 's1', name: 'Sheets' }, { id: 's2', name: null }],
+ team: { id: 't1', name: 'Finance' }, reason: 'You keep asking for invoices.',
+ evidence: { basis: 'repeated', similar_requests: ['m1', 'm2', 'm3'] }, requested_by_person: false,
+ status: 'pending', auto: false, choices: ['deny', 'accept_once', 'always_accept'],
+ hired_kwant_id: null, action_id: null, can_undo: false, policy: 'ask', note: null, created_at: '2026-10-18T10:00:00Z', resolved_at: null, ...over,
+});
+const hireProps = (meta, over = {}) => ({ meta: b.parseHireMeta(meta), messageId: 'm9', kwantName: 'Ada', kwantId: 'k1', onDecide: async () => {}, ...over });
+
+test('pending hire: who proposes, the bot, why, evidence, and the three choices', () => {
+ const html = ui.hire(hireProps(hireMeta()));
+ const t = text(html);
+ assert.match(t, /Ada proposes hiring a new bot/);
+ assert.match(t, /Ledger Bookkeeper/);
+ assert.match(t, /Why: You keep asking for invoices\./);
+ assert.match(t, /Based on: You asked for this kind of work 3 times in this space\./);
+ assert.match(t, /Team Finance/);
+ assert.match(t, /Model Picked automatically/);
+ assert.match(t, /Tools Sheets, Unknown tool/);
+ assert.match(t, /Waiting for you\. Ada carries on with your request meanwhile\./);
+ assert.match(t, /up to 3 a day, each with Undo/);
+ assert.deepEqual(buttons(html), ['Show its instructions', 'Accept once', 'Always accept', 'Deny']);
+ // Instructions start collapsed.
+ assert.doesNotMatch(t, /Keep the books/);
+ assert.match(html, /aria-expanded="false"/);
+});
+
+test('accepted hire: Hired, joined the team, with Undo', () => {
+ const html = ui.hire(hireProps(hireMeta({ status: 'accepted', choices: [], hired_kwant_id: 'k9', action_id: 'a9', can_undo: true })));
+ assert.match(text(html), /Hired\. Ledger joined Finance\./);
+ assert.deepEqual(buttons(html), ['Show its instructions', 'Undo']);
+ // can_undo without an action id can't be honoured.
+ assert.equal(b.parseHireMeta(hireMeta({ status: 'accepted', can_undo: true })).can_undo, false);
+});
+
+test('auto-accepted hire shows why it happened at once, the note, and Undo', () => {
+ const html = ui.hire(
+ hireProps(hireMeta({ status: 'auto_accepted', auto: true, choices: [], action_id: 'a9', can_undo: true, policy: 'auto', note: '2 of 3 automatic hires used today.' })),
+ );
+ const t = text(html);
+ assert.match(t, /Ada hired a new bot/);
+ assert.match(t, /Hired at once, because you chose Always accept\./);
+ assert.match(t, /2 of 3 automatic hires used today\./);
+ assert.ok(buttons(html).includes('Undo'));
+});
+
+test('denied and undone hires offer nothing more', () => {
+ const denied = ui.hire(hireProps(hireMeta({ status: 'denied', choices: ['deny'] })));
+ assert.match(text(denied), /Not hired\. Bots here won't suggest this kind of bot again unless you ask\./);
+ assert.deepEqual(buttons(denied), ['Show its instructions']);
+ const undone = ui.hire(hireProps(hireMeta({ status: 'undone', action_id: 'a9', can_undo: true })));
+ assert.match(text(undone), /Hire undone\. Ledger was removed\./);
+ assert.deepEqual(buttons(undone), ['Show its instructions']);
+});
+
+test('a hire live update wins unless it is older', () => {
+ const pending = b.parseHireMeta(hireMeta());
+ const accepted = b.parseHireMeta(hireMeta({ status: 'accepted', action_id: 'a9', can_undo: true }));
+ const undone = b.parseHireMeta(hireMeta({ status: 'undone' }));
+ assert.equal(b.hireView(pending, accepted).status, 'accepted');
+ assert.equal(b.hireView(accepted, pending).status, 'accepted');
+ assert.equal(b.hireView(accepted, undone).status, 'undone');
+ let map = b.applyHire({}, { id: 'h1', status: 'undone', card: hireMeta({ status: 'undone' }) });
+ map = b.applyHire(map, { id: 'h1', status: 'accepted', card: hireMeta({ status: 'accepted' }) });
+ assert.equal(map.h1.status, 'undone');
+ const html = ui.hire(hireProps(hireMeta(), { live: accepted }));
+ assert.match(text(html), /Hired\./);
+});
+
+test('evidence in plain words', () => {
+ assert.equal(b.evidenceText({ basis: 'specialist', needs: ['tools', 'schedule'], gap: 'no bot here can read invoices' }, false),
+ 'This work needs its own tools and a schedule. No bot here can read invoices.');
+ assert.equal(b.evidenceText({ basis: 'repeated', similar_requests: ['m1'] }, false), 'You asked for this kind of work 1 time in this space.');
+ assert.equal(b.evidenceText(null, true), 'You asked for this kind of bot.');
+ assert.equal(b.parseHireMeta(hireMeta({ evidence: 'Plain text reason' })).evidence.text, 'Plain text reason');
+ assert.equal(b.modelText('claude-sonnet-5-5'), 'claude-sonnet-5-5');
+ assert.equal(b.parseHireMeta(hireMeta({ team: null })).team, null);
+ assert.equal(b.parseHireMeta(hireMeta({ name: '' })), null);
+});
+
+test('409 and 403 read as plain words', () => {
+ assert.equal(b.decisionError(new b.ApiError('hire is not pending', 409), 'hire it'), 'Couldn’t hire it: it was already decided or changed (hire is not pending).');
+ assert.equal(b.decisionError(new b.ApiError('Request failed (HTTP 409).', 409), 'undo it'), 'Couldn’t undo it: it was already decided or changed.');
+ assert.match(b.decisionError(new b.ApiError('nope', 403), 'deny it'), /only you can do this/);
+ assert.equal(b.decisionError(new Error('Network down'), 'deny it'), 'Couldn’t deny it: Network down');
+});
+
+test('hire routes send {} for Accept once and {always:true} for Always accept', async () => {
+ const calls = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async (url, init) => {
+ calls.push([init.method, url, init.body]);
+ if (url.endsWith('/deny')) return new Response(JSON.stringify({ error: 'hire is not pending' }), { status: 409 });
+ return new Response(JSON.stringify({ id: 'h1', status: 'accepted' }), { status: 200 });
+ };
+ try {
+ await b.hiresApi.accept('h1');
+ await b.hiresApi.accept('h1', true);
+ await b.hiresApi.setPolicy('sp 1', { clear_denials: true });
+ await assert.rejects(b.hiresApi.deny('h1'), (e) => e instanceof b.ApiError && e.status === 409 && e.message === 'hire is not pending');
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ assert.deepEqual(calls, [
+ ['POST', '/api/hires/h1/accept', '{}'],
+ ['POST', '/api/hires/h1/accept', '{"always":true}'],
+ ['PUT', '/api/spaces/sp%201/hire-policy', '{"clear_denials":true}'],
+ ['POST', '/api/hires/h1/deny', undefined],
+ ]);
+});
+
+test('hire policy parses with safe defaults', () => {
+ const p = b.parseHirePolicy({
+ space_id: 's1', policy: 'auto', auto_hires_last_24h: 2, auto_hires_per_day: 3,
+ denied: [{ hire_id: 'h2', name: 'Spammer', role: 'Outreach', denied_at: '2026-10-17T10:00:00Z' }, { hire_id: 'h3' }, null],
+ });
+ assert.equal(p.policy, 'auto');
+ assert.equal(p.auto_hires_last_24h, 2);
+ assert.deepEqual(p.denied.map((d) => d.name), ['Spammer']);
+ const d = b.parseHirePolicy({ policy: 'sometimes' });
+ assert.equal(d.policy, 'ask');
+ assert.equal(d.auto_hires_per_day, 3);
+ assert.deepEqual(d.denied, []);
+ assert.equal(b.parseHirePolicy(null), null);
+});
diff --git a/frontend/tests/continuity.test.mjs b/frontend/tests/continuity.test.mjs
index a0278f6c..d8625f7a 100644
--- a/frontend/tests/continuity.test.mjs
+++ b/frontend/tests/continuity.test.mjs
@@ -156,3 +156,47 @@ test('continuity bus delivers to subscribers until they unsubscribe', () => {
c.emitContinuity({ type: 'memory_changed', data: { kwant_id: 'k2' } });
assert.deepEqual(seen, ['k1']);
});
+
+test('monthly schedules: days sort with "last" at the end, and need at least one day', () => {
+ assert.deepEqual(c.scheduleFromForm(form({ type: 'monthly', time: '09:00', monthDays: ['last', 15, 1, 15] }), NOW), {
+ schedule: { type: 'monthly', time: '09:00', days: [1, 15, 'last'], tz: 'Europe/Kyiv' },
+ });
+ assert.ok(c.scheduleFromForm(form({ type: 'monthly', monthDays: [] }), NOW).error);
+ assert.ok(c.scheduleFromForm(form({ type: 'monthly', monthDays: [0, 32] }), NOW).error);
+ assert.ok(c.scheduleFromForm(form({ type: 'monthly', time: '9:00' }), NOW).error);
+});
+
+test('cron schedules: five parts and a time zone; shortcuts are refused', () => {
+ assert.deepEqual(c.scheduleFromForm(form({ type: 'cron', cron: ' 0 9 * * MON#2 ' }), NOW), {
+ schedule: { type: 'cron', expression: '0 9 * * MON#2', tz: 'Europe/Kyiv' },
+ });
+ const err = (cron, over = {}) => c.scheduleFromForm(form({ type: 'cron', cron, ...over }), NOW).error;
+ assert.match(err('@daily'), /aren’t supported/);
+ assert.match(err('0 9 * *'), /five parts/);
+ assert.ok(err(''));
+ assert.ok(err('0 9 L * *', { tz: ' ' }));
+ assert.equal(err('0 9 L * *'), undefined);
+});
+
+test('monthly and cron schedules round-trip through the form', () => {
+ for (const s of [
+ { type: 'monthly', time: '07:30', days: [1, 'last'], tz: 'Europe/Kyiv' },
+ { type: 'monthly', time: '23:59', days: ['last'], tz: 'UTC' },
+ { type: 'cron', expression: '0 9 1 * *', tz: 'Asia/Kolkata' },
+ ]) {
+ const f = c.formFromSchedule(s);
+ assert.equal(f.type, s.type);
+ assert.deepEqual(c.scheduleFromForm(f, NOW).schedule, s);
+ }
+ // An unknown type opens as a plain daily form instead of crashing the editor.
+ assert.equal(c.formFromSchedule({ type: 'lunar', tz: 'UTC' }).type, 'daily');
+});
+
+test('monthly and cron schedules in plain words', () => {
+ assert.equal(c.monthDaysText([15, 'last', 1]), 'the 1st, 15th and last day');
+ assert.equal(c.monthDaysText([2, 3, 11, 12, 13, 21, 22, 23]), 'the 2nd, 3rd, 11th, 12th, 13th, 21st, 22nd and 23rd');
+ assert.equal(c.monthDaysText(['last']), 'the last day');
+ assert.equal(c.describeSchedule({ type: 'monthly', time: '09:00', days: [1], tz: 'UTC' }), 'Every month on the 1st at 09:00 (UTC)');
+ assert.equal(c.describeSchedule({ type: 'cron', expression: '0 9 * * MON#2', tz: 'UTC' }), 'Custom rule 0 9 * * MON#2 (UTC)');
+ assert.equal(c.describeSchedule({ type: 'lunar' }), 'Unknown schedule');
+});