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.

Accounts: failover order across engines and a quiet switch line in chat (#236)

Oleksandr Ivanchenkoe118b3e4c6b9
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index f9b6a839..269d474f 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -77,7 +77,9 @@ import {
turnsIn,
upsertThread,
} from './threads';
-import { Profile, describeProfileSwitch, profilesApi } from './profiles';
+import { Profile, profilesApi } from './profiles';
+import { FailoverEvent, createOutageLog, failoverNotice, outageKey } from './failover';
+import type { SwitchNote } from './failoverNotes';
import {
NotifyEvent,
NotifyKind,
@@ -325,6 +327,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [historyWindow, setHistoryWindow] = useState<{ ctx: string; messages: ChatMessage[] } | null>(null);
const [profiles, setProfiles] = useState<Profile[]>([]);
const [toasts, setToasts] = useState<Toast[]>([]);
+ const [switchNotes, setSwitchNotes] = useState<SwitchNote[]>([]);
+ const switchLogRef = useRef(createOutageLog());
// What fills the main pane instead of a chat: the Inbox (New or Loose ends), the Mission board
// or Parallel Universe. The Inbox's unseen count is the sidebar badge.
const [page, setPage] = useState<'chat' | 'inbox' | 'board' | 'parallel'>(() =>
@@ -905,11 +909,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
case 'profile_switched':
case 'ProfileSwitched': {
- const kwantName = kwantsRef.current.find((k) => k.id === event.data?.kwant_id)?.name;
- const { title, detail } = describeProfileSwitch(event.data, kwantName);
- const id = ++toastIdRef.current;
- setToasts((prev) => [...prev.slice(-2), { id, title, detail }]);
- playSfx('alert');
+ // A quiet line under the bot's name, once per chat per outage; no toast and no sound.
+ const sw = event.data as FailoverEvent | undefined;
+ const botName = kwantName(sw?.kwant_id);
+ if (sw && botName && switchLogRef.current.first(outageKey(sw, sw.context_id))) {
+ const note: SwitchNote = { name: botName, text: failoverNotice(sw), at: Date.now() };
+ setSwitchNotes((prev) => [...prev.filter((n) => Date.now() - n.at < 24 * 3600_000).slice(-19), note]);
+ }
refreshProfiles();
break;
}
@@ -3041,6 +3047,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
queued={queuedHere}
renderDelegation={renderDelegation}
+ switchNotes={switchNotes}
renderQuestion={renderQuestion}
renderMcpSuggestion={renderMcpSuggestion}
renderConnectionSuggestion={renderConnectionSuggestion}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index ae099ac0..28d2a12b 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -105,6 +105,14 @@ export function itemLabel(item: Pick<AwayItem, 'kind' | 'status'>): { label: str
return { label: item.status, tone: 'zinc' };
}
+/** A provider's own limit message ("You've hit your session limit · resets 3am"): never a result. The server
+ * keeps these out of replies and summaries; this is the second guard on the card. */
+const LIMIT_LINE = /\b(?:hit|reached|exceeded)\s+your\b[^.\n]{0,24}\blimit\b|\b(?:session|weekly|usage|opus)\s+limit\b|\blimit\b[^.\n]{0,12}\bresets?\b/i;
+export const isLimitLine = (text: string | null | undefined): boolean => !!text && LIMIT_LINE.test(text);
+
+/** The summary line a card shows: empty for a limit message, so the card shows its title alone. */
+export const awaySummary = (item: Pick<AwayItem, 'summary' | 'title'>): string => (isLimitLine(item.summary) ? '' : item.summary);
+
/** Sidebar badge text: nothing at 0, "99+" past 99. */
export const badgeText = (n: number): string => (n <= 0 ? '' : n > 99 ? '99+' : String(n));
diff --git a/frontend/src/components/AccountPriority.tsx b/frontend/src/components/AccountPriority.tsx
new file mode 100644
index 00000000..3a05b30b
--- /dev/null
+++ b/frontend/src/components/AccountPriority.tsx
@@ -0,0 +1,179 @@
+import React, { useEffect, useMemo, useRef, useState } from 'react';
+import { ArrowDown, ArrowUp, GripVertical } from 'lucide-react';
+import { playSfx } from '../audio/chiptune';
+import type { EngineInfo } from '../engines';
+import {
+ FAILOVER_CAPTION,
+ engineLabel,
+ failoverOrder,
+ moveAccount,
+ moveAnnouncement,
+ priorityStatus,
+ priorityUpdates,
+} from '../failover';
+import { Profile, cardOf, profilesApi } from '../profiles';
+import { StatusPill } from './EngineAccounts';
+
+const arrowBtn =
+ 'inline-flex items-center justify-center w-8 h-8 sm:w-7 sm:h-7 rounded-md border border-zinc-700/70 bg-zinc-800/70 text-zinc-200 hover:bg-zinc-700 transition-colors disabled:opacity-35 disabled:hover:bg-zinc-800/70 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400';
+
+/**
+ * One list across engines, in the order turns try them. The order is the failover priority: it is
+ * saved as each account's `priority` (PATCH /api/profiles/:id), so the server needs nothing new.
+ * Drag a row, or use its up and down buttons (they work from the keyboard and on a phone).
+ */
+export const AccountPriority: React.FC<{
+ profiles: Profile[];
+ engines: EngineInfo[] | null;
+ onChanged: () => Promise<void>;
+ now?: number;
+}> = ({ profiles, engines, onChanged, now = Date.now() }) => {
+ // The order shown while a save is in flight; null means "what the server last said".
+ const [pending, setPending] = useState<Profile[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [announce, setAnnounce] = useState('');
+ const [dragId, setDragId] = useState<string | null>(null);
+ const [overId, setOverId] = useState<string | null>(null);
+ const [focusKey, setFocusKey] = useState<string | null>(null);
+ const listRef = useRef<HTMLOListElement>(null);
+
+ const served = useMemo(() => failoverOrder(profiles), [profiles]);
+ const order = pending ?? served;
+
+ // Put keyboard focus back on the button that was used, once the row has moved.
+ useEffect(() => {
+ if (!focusKey) return;
+ const el = listRef.current?.querySelector<HTMLButtonElement>(`[data-focus-key="${CSS.escape(focusKey)}"]`);
+ if (el && !el.disabled) el.focus();
+ setFocusKey(null);
+ }, [focusKey, order]);
+
+ const save = async (next: Profile[], moved: Profile, to: number) => {
+ const updates = priorityUpdates(next);
+ if (updates.length === 0) return;
+ setError(null);
+ // Show the new order at once, with the numbers it will have, so a late reload can't flip it back.
+ const numbered = next.map((p) => ({ ...p, priority: updates.find((u) => u.id === p.id)?.priority ?? p.priority }));
+ setPending(numbered);
+ setAnnounce(moveAnnouncement(moved.kind === 'system' ? `${engineLabel(moved)} on this machine` : moved.name, to, next.length));
+ try {
+ await Promise.all(updates.map((u) => profilesApi.update(u.id, { priority: u.priority })));
+ await onChanged();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : 'Could not save the order.');
+ setAnnounce('Could not save the order. It is back as it was.');
+ await onChanged().catch(() => undefined);
+ } finally {
+ setPending(null);
+ }
+ };
+
+ const move = (index: number, to: number, key?: string) => {
+ const next = moveAccount(order, index, to);
+ if (!next) return;
+ playSfx('click');
+ if (key) setFocusKey(key);
+ void save(next, order[index], to);
+ };
+
+ const nameOf = (p: Profile) => (p.kind === 'system' ? 'This machine' : p.name);
+
+ return (
+ <section aria-labelledby="account-priority-title" className="rounded-xl border border-zinc-800 bg-zinc-900/90 p-3 text-xs">
+ <h3 id="account-priority-title" className="font-semibold text-zinc-100">
+ Order to use
+ </h3>
+ <p id="account-priority-caption" className="mt-0.5 text-[11px] text-zinc-400">
+ {FAILOVER_CAPTION}
+ </p>
+ {order.length === 0 ? (
+ <p className="mt-2 text-zinc-500">No accounts yet. Add one below.</p>
+ ) : (
+ <ol ref={listRef} aria-describedby="account-priority-caption" className="mt-2.5 space-y-1.5">
+ {order.map((p, i) => {
+ const engine = engines?.find((e) => e.id === cardOf(p));
+ const status = priorityStatus(p, engine, now);
+ const dragging = dragId === p.id;
+ const over = overId === p.id && dragId !== p.id;
+ return (
+ <li
+ key={p.id}
+ data-account={p.id}
+ draggable
+ onDragStart={(e) => {
+ setDragId(p.id);
+ e.dataTransfer.effectAllowed = 'move';
+ e.dataTransfer.setData('text/plain', p.id);
+ }}
+ onDragOver={(e) => {
+ if (!dragId) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'move';
+ if (overId !== p.id) setOverId(p.id);
+ }}
+ onDrop={(e) => {
+ e.preventDefault();
+ const from = order.findIndex((x) => x.id === dragId);
+ setDragId(null);
+ setOverId(null);
+ move(from, i);
+ }}
+ onDragEnd={() => {
+ setDragId(null);
+ setOverId(null);
+ }}
+ className={`flex items-center gap-2 rounded-lg border px-2 py-2 transition-colors ${
+ over ? 'border-sky-500/60 bg-sky-500/5' : 'border-zinc-800 bg-zinc-950/40'
+ } ${dragging ? 'opacity-50' : ''} ${p.enabled ? '' : 'opacity-75'}`}
+ >
+ <GripVertical size={14} className="shrink-0 text-zinc-600 cursor-grab hidden sm:block" aria-hidden="true" />
+ <span className="shrink-0 w-4 text-center text-[11px] tabular-nums text-zinc-500" aria-hidden="true">
+ {i + 1}
+ </span>
+ <div className="flex-1 min-w-0">
+ <p className="text-zinc-100 font-medium truncate">{nameOf(p)}</p>
+ <div className="mt-0.5 flex items-center gap-x-1.5 gap-y-1 flex-wrap">
+ <span className="text-[11px] text-zinc-500">{engineLabel(p)}</span>
+ <StatusPill tone={status.tone}>{status.label}</StatusPill>
+ </div>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <button
+ type="button"
+ data-focus-key={`${p.id}:up`}
+ className={arrowBtn}
+ disabled={i === 0}
+ aria-label={`Move ${nameOf(p)} (${engineLabel(p)}) up`}
+ title="Use it earlier"
+ onClick={() => move(i, i - 1, i - 1 === 0 ? `${p.id}:down` : `${p.id}:up`)}
+ >
+ <ArrowUp size={13} aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ data-focus-key={`${p.id}:down`}
+ className={arrowBtn}
+ disabled={i === order.length - 1}
+ aria-label={`Move ${nameOf(p)} (${engineLabel(p)}) down`}
+ title="Use it later"
+ onClick={() => move(i, i + 1, i + 1 === order.length - 1 ? `${p.id}:up` : `${p.id}:down`)}
+ >
+ <ArrowDown size={13} aria-hidden="true" />
+ </button>
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+ )}
+ <p role="status" aria-live="polite" className="sr-only">
+ {announce}
+ </p>
+ {error && (
+ <p role="alert" className="mt-2 text-[11px] text-rose-300">
+ {error}
+ </p>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/components/AwayView.tsx b/frontend/src/components/AwayView.tsx
index 8e0dbc12..0dacf9fc 100644
--- a/frontend/src/components/AwayView.tsx
+++ b/frontend/src/components/AwayView.tsx
@@ -13,6 +13,7 @@ import {
AwaySection,
Tone,
actionFailureNotice,
+ awaySummary,
awayApi,
isAwayEmpty,
itemLabel,
@@ -80,7 +81,7 @@ export const AwayView: React.FC<AwayViewProps> = ({ data, loading, error, notice
</div>
<p className="mt-0.5 text-sm font-medium text-zinc-100 truncate">{item.title}</p>
{/* A question's summary just lists its choices, which are buttons below. */}
- {item.summary && item.kind !== 'approval' && !(item.kind === 'question' && item.choices?.length) && <p className="text-xs text-zinc-400 truncate">{item.summary}</p>}
+ {awaySummary(item) && item.kind !== 'approval' && !(item.kind === 'question' && item.choices?.length) && <p className="text-xs text-zinc-400 truncate">{awaySummary(item)}</p>}
</div>
</button>
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index c00a6e8b..b4a8cf6e 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -14,7 +14,9 @@ import { QuestionMeta, parseQuestionMeta } from '../questions';
import { HumanStep, HumanStepMeta, parseHumanStepMeta } from '../humanSteps';
import { LiveActivity, hasThinkingText, parseActivityMeta } from '../activity';
import { LiveActivityList, SavedActivityList } from './ActivityList';
-import { ReplyMeta } from './ReplyMeta';
+import { FailoverNote, ReplyMeta } from './ReplyMeta';
+import { assignSwitchNotes, liveSwitchNote, type SwitchNote } from '../failoverNotes';
+import { savedFailoverNotice } from '../failover';
import { SuggestionMeta, parseSuggestionMeta } from '../mcpSuggestions';
import { BotActionMeta, HireMeta, parseBotActionMeta, parseHireMeta } from '../botActions';
import {
@@ -250,6 +252,8 @@ export interface ChatViewProps {
deciding?: { botName: string; consulted: string[] } | null;
/** Change on a decision chip; resolves to an error message on failure. */
onChangeDecision?: (msg: ChatMessage, index: number, picked: string) => Promise<string | void>;
+ /** Quiet "answered on another account" lines, one per outage; each shows under that bot's name. */
+ switchNotes?: SwitchNote[];
}
export const renderFormattedText = (text: string): React.ReactNode => {
@@ -524,6 +528,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
queued,
renderDelegation,
renderQuestion,
+ switchNotes,
renderMcpSuggestion,
renderConnectionSuggestion,
renderBotAction,
@@ -942,6 +947,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
if ((await onSendMessage(target.text, target.attachments)) === false) throw new Error('not sent');
};
+ const switchNoteFor = useMemo(
+ () => assignSwitchNotes(switchNotes ?? [], messages, (m) => (m.sender_id && m.sender_id.length > 20 ? title : m.sender_id)),
+ [switchNotes, messages, title],
+ );
+ const liveNote = isStreaming ? liveSwitchNote(switchNotes ?? [], switchNoteFor, streamingSpeakerName || title) : null;
+
const renderMessage = (msg: ChatMessage) => {
const interruption = parseInterruption(msg);
if (interruption)
@@ -1064,6 +1075,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
account={account}
tokens={tokens}
failed={!!savedActivity?.steps.some((s) => s.status === 'failed')}
+ note={savedFailoverNotice(msg.meta) ?? switchNoteFor.get(msg.id)}
>
{/* What the reply did: "12 steps · 41s", opening to the steps (tool calls go inside) */}
{savedActivity && (
@@ -1457,6 +1469,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
</div>
+ {liveNote && <FailoverNote text={liveNote} />}
+
{liveActivity && <LiveActivityList live={liveActivity} idBase={`live-${liveActivity.turnId}`} />}
{streamingThinking && (
diff --git a/frontend/src/components/ReplyMeta.tsx b/frontend/src/components/ReplyMeta.tsx
index a39c2fbb..7bf2a26f 100644
--- a/frontend/src/components/ReplyMeta.tsx
+++ b/frontend/src/components/ReplyMeta.tsx
@@ -17,15 +17,24 @@ export interface ReplyMetaProps extends ReplyFacts {
avatar?: React.ReactNode;
/** Whether a step failed: the Details toggle says so while it's folded. */
failed?: boolean;
+ /** One muted line under the name, e.g. "Claude is out until 03:00 · answered on Codex (GPT-6.1)". */
+ note?: string | null;
now?: number;
/** Steps and the reasoning item; shown with the facts when Details is open. */
children?: React.ReactNode;
}
+/** The quiet line for a reply that ran on another account. It wraps rather than clips, so it fits at 390 px. */
+export const FailoverNote: React.FC<{ text: string }> = ({ text }) => (
+ <p data-failover-note="" className="-mt-0.5 mb-1.5 max-w-full text-[11px] leading-snug text-zinc-500 break-words">
+ {text}
+ </p>
+);
+
const hasContent = (n: React.ReactNode) => React.Children.toArray(n).length > 0;
/** A bot reply's header: one line, "Name · 3:42 PM", and a Details toggle holding the rest. */
-export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, account, tokens, failed = false, now, children }) => {
+export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, account, tokens, failed = false, note, now, children }) => {
const [open, setOpen] = useState(false);
const panelId = useId();
const time = localClock(at, now);
@@ -60,6 +69,7 @@ export const ReplyMeta: React.FC<ReplyMetaProps> = ({ name, at, avatar, ranOn, a
</button>
)}
</div>
+ {note && <FailoverNote text={note} />}
{open && hasDetails && (
<div id={panelId} className="mb-2 w-full max-w-2xl">
{facts.length > 0 && (
diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsx
index 6e462266..bd8c9f68 100644
--- a/frontend/src/components/SpaceSettings.tsx
+++ b/frontend/src/components/SpaceSettings.tsx
@@ -25,6 +25,7 @@ import { SPACE_COLORS, SPACE_ICONS, Space, spaceColor, spaceNameError, spacesApi
import { useEngines } from '../useEngines';
import { useProfiles } from '../useProfiles';
import type { Profile } from '../profiles';
+import { AccountPriority } from './AccountPriority';
import { EnginesPanel } from './EnginesPanel';
import { ApiKeysPanel } from './ApiKeysPanel';
import { RoutinesPanel, type RoutineFocus } from './RoutinesPanel';
@@ -527,6 +528,9 @@ const AccountsTab: React.FC<Props> = ({ space, focusClaudeSignIn, onProfilesChan
return (
<div className="space-y-3">
<p className="text-xs text-zinc-400">What runs your kwant bots in {space.name}: the accounts here, and This machine when it’s on.</p>
+ {accounts.profiles && accounts.profiles.length > 1 && (
+ <AccountPriority profiles={accounts.profiles} engines={engines.engines} onChanged={accounts.reload} />
+ )}
<EnginesPanel api={engines} accounts={accounts} focusClaudeSignIn={focusClaudeSignIn} />
<ApiKeysPanel
onSaved={() => {
diff --git a/frontend/src/failover.ts b/frontend/src/failover.ts
new file mode 100644
index 00000000..1e8c1431
--- /dev/null
+++ b/frontend/src/failover.ts
@@ -0,0 +1,172 @@
+// Failover order (Settings › This space › Accounts) and the switch notice in chat. Pure helpers, so the
+// components and the node tests share them. Every word and time shown comes from the server's data;
+// nothing here makes up a number.
+
+import type { EngineInfo } from './engines';
+import { accountStatus } from './components/EngineAccounts';
+import { Engine, Profile, ProfileSwitchedEvent, accountState, activeLimit } from './profiles';
+import { parseMetaObject } from './questions';
+
+export const FAILOVER_CAPTION = 'When one runs out, kwant bots move to the next that still works, in this order.';
+
+export const ENGINE_NAMES: Record<Engine, string> = { claude: 'Claude', codex: 'Codex', grok: 'Grok', custom: 'Custom API' };
+
+/** The engine and kind in plain words: "Claude", "Claude API key", "Custom API". */
+export function engineLabel(p: Pick<Profile, 'engine' | 'kind'>): string {
+ const base = ENGINE_NAMES[p.engine] ?? p.engine;
+ return p.kind === 'api_key' ? `${base} API key` : base;
+}
+
+/** The accounts in the order turns try them: lowest priority number first; ties keep "This machine"
+ * first, then the name, so the list never jumps around between loads. */
+export function failoverOrder(profiles: Profile[]): Profile[] {
+ return [...profiles].sort(
+ (a, b) =>
+ a.priority - b.priority ||
+ Number(b.kind === 'system') - Number(a.kind === 'system') ||
+ a.engine.localeCompare(b.engine) ||
+ a.name.localeCompare(b.name) ||
+ a.id.localeCompare(b.id),
+ );
+}
+
+/** A clock time in the person's own zone: "03:00", with the weekday or date when it isn't today. */
+export function clockTime(at: Date, now = Date.now()): string {
+ const time = at.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hour12: false });
+ const today = new Date(now);
+ if (at.toDateString() === today.toDateString()) return time;
+ const days = (at.getTime() - now) / 86400_000;
+ const day = days < 6 ? at.toLocaleDateString(undefined, { weekday: 'short' }) : at.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+ return `${day} ${time}`;
+}
+
+export interface PriorityStatus {
+ tone: 'ok' | 'warn' | 'error' | 'muted' | 'busy' | 'info';
+ /** "Ready", "Out until 03:00", "Signed out", else the account's own state word. */
+ label: string;
+}
+
+/** The status on a priority row. `engine` is the card the account sits on, for "This machine". */
+export function priorityStatus(p: Profile, engine: EngineInfo | undefined, now = Date.now()): PriorityStatus {
+ const limit = activeLimit(p.limited_until, now);
+ // Off outranks a stale limit: a switched-off account is skipped either way.
+ if (p.enabled && limit) return { tone: 'warn', label: `Out until ${clockTime(limit, now)}` };
+ const s = engine ? accountStatus(p, engine, now) : accountState(p, now);
+ return { tone: s.tone, label: s.label === 'Needs sign-in' ? 'Signed out' : s.label };
+}
+
+/** Where a drag or an arrow press puts an account: the new order, or null when nothing moves. */
+export function moveAccount(order: Profile[], from: number, to: number): Profile[] | null {
+ if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return null;
+ const next = [...order];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item);
+ return next;
+}
+
+export const PRIORITY_STEP = 10;
+
+/** The priority updates that make `order` the failover order: ranks 10, 20, 30…, only for accounts
+ * whose number changes. Uses the existing PATCH /api/profiles/:id `priority` field (0 to 10000). */
+export function priorityUpdates(order: Profile[]): Array<{ id: string; priority: number }> {
+ const out: Array<{ id: string; priority: number }> = [];
+ order.forEach((p, i) => {
+ const priority = Math.min(10_000, (i + 1) * PRIORITY_STEP);
+ if (p.priority !== priority) out.push({ id: p.id, priority });
+ });
+ return out;
+}
+
+/** What a screen reader hears after a move: "Codex moved to position 2 of 5." */
+export const moveAnnouncement = (name: string, index: number, total: number) => `${name} moved to position ${index + 1} of ${total}.`;
+
+// ---- The switch notice in chat ----
+
+/** `profile_switched` as Vega's backend extends it; the engine and model fields are absent on older servers. */
+export type FailoverEvent = ProfileSwitchedEvent & {
+ from_engine?: string | null;
+ from_model?: string | null;
+ to_engine?: string | null;
+ to_model?: string | null;
+ /** The model as people read it ("GPT-6.1"), when the server sends one. */
+ to_model_label?: string | null;
+ /** Set when the server scopes the switch to one chat. */
+ context_id?: string | null;
+};
+
+const engineName = (engine: string | null | undefined, fallback: string): string => {
+ if (engine && engine in ENGINE_NAMES) return ENGINE_NAMES[engine as Engine];
+ return fallback;
+};
+
+/** "Claude is out until 03:00 · answered on Codex (GPT-6.1)". Kept to one short line. */
+export function failoverNotice(e: FailoverEvent, now = Date.now()): string {
+ const from = engineName(e.from_engine, e.from_name);
+ const to = engineName(e.to_engine, e.to_name);
+ const limit = activeLimit(e.retry_at ?? null, now);
+ const why = e.class === 'auth' ? `${from} is signed out` : limit ? `${from} is out until ${clockTime(limit, now)}` : `${from} is out of usage`;
+ const model = e.to_model_label || e.to_model;
+ return `${why} · answered on ${to}${model ? ` (${model})` : ''}`;
+}
+
+/** One outage, for "once per chat": the same chat, the same account that ran out, the same reset. */
+export function outageKey(e: Pick<FailoverEvent, 'kwant_id' | 'from_profile_id' | 'class' | 'retry_at'>, chat?: string | null): string {
+ return [chat || e.kwant_id, e.from_profile_id, e.class, e.retry_at ?? ''].join('|');
+}
+
+/** Remembers which outages a chat has already been told about. */
+export function createOutageLog() {
+ const seen = new Set<string>();
+ return {
+ /** True the first time this outage is seen in this chat. */
+ first(key: string): boolean {
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ },
+ size: () => seen.size,
+ };
+}
+
+// ---- The saved notice (survives a reload) ----
+
+const text = (v: unknown): string | null => (typeof v === 'string' && v.trim() ? v : null);
+
+/** One saved switch, tolerant of anything else in the array. */
+function savedSwitch(v: unknown): FailoverEvent | null {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return null;
+ const r = v as Record<string, unknown>;
+ const from_name = text(r.from_name);
+ const to_name = text(r.to_name);
+ if (!from_name && !text(r.from_engine)) return null;
+ if (!to_name && !text(r.to_engine)) return null;
+ return {
+ kwant_id: text(r.kwant_id) ?? '',
+ from_profile_id: text(r.from_profile_id) ?? '',
+ from_name: from_name ?? '',
+ to_profile_id: text(r.to_profile_id) ?? '',
+ to_name: to_name ?? '',
+ class: text(r.class) ?? 'quota',
+ retry_at: text(r.retry_at) ?? undefined,
+ from_engine: text(r.from_engine),
+ from_model: text(r.from_model),
+ to_engine: text(r.to_engine),
+ to_model: text(r.to_model),
+ to_model_label: text(r.to_model_label),
+ };
+}
+
+/**
+ * The notice a saved reply carries in `meta.failover` (an array of switches, or one object), as one
+ * line. A reply that moved twice reads from the first account that ran out to the one that answered.
+ * Null for anything missing or malformed, so the reply simply shows no notice.
+ */
+export function savedFailoverNotice(meta: unknown, now = Date.now()): string | null {
+ const m = parseMetaObject(meta);
+ const raw = m?.failover;
+ const list = (Array.isArray(raw) ? raw : raw ? [raw] : []).map(savedSwitch).filter((s): s is FailoverEvent => !!s);
+ if (list.length === 0) return null;
+ const first = list[0];
+ const last = list[list.length - 1];
+ return failoverNotice({ ...first, to_name: last.to_name, to_engine: last.to_engine, to_model: last.to_model, to_model_label: last.to_model_label }, now);
+}
diff --git a/frontend/src/failoverNotes.ts b/frontend/src/failoverNotes.ts
new file mode 100644
index 00000000..e2c366bd
--- /dev/null
+++ b/frontend/src/failoverNotes.ts
@@ -0,0 +1,46 @@
+// Which reply carries a failover notice. Pure, so the chat and the node tests share it.
+
+/** One "answered on another account" line, for the bot that was switched. */
+export interface SwitchNote {
+ /** The bot's name, as the chat shows it. */
+ name: string;
+ text: string;
+ /** When the switch happened (ms). */
+ at: number;
+}
+
+interface Msg {
+ id: string;
+ sender_role: string;
+ sender_id: string;
+ created_at?: string | null;
+}
+
+/** The notes come first, then the replies: a note goes under the first reply by its bot written at or
+ * after it. Returns message id → text; notes with no reply yet are left for the live bubble. */
+export function assignSwitchNotes(
+ notes: SwitchNote[],
+ messages: Msg[],
+ nameOf: (m: Msg) => string,
+ skewMs = 5000,
+): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const note of [...notes].sort((a, b) => a.at - b.at)) {
+ const hit = messages.find((m) => {
+ if (m.sender_role === 'user' || out.has(m.id)) return false;
+ const t = Date.parse(m.created_at ?? '');
+ return nameOf(m) === note.name && !Number.isNaN(t) && t >= note.at - skewMs;
+ });
+ if (hit) out.set(hit.id, note.text);
+ }
+ return out;
+}
+
+/** The note for the reply that is streaming now: the newest for that bot that no saved reply carries. */
+export function liveSwitchNote(notes: SwitchNote[], assigned: Map<string, string>, speaker: string, now = Date.now(), maxAgeMs = 15 * 60_000): string | null {
+ const taken = new Set(assigned.values());
+ const open = notes
+ .filter((n) => n.name === speaker && !taken.has(n.text) && now - n.at < maxAgeMs)
+ .sort((a, b) => b.at - a.at);
+ return open[0]?.text ?? null;
+}
diff --git a/frontend/tests/away.test.mjs b/frontend/tests/away.test.mjs
index c47bd8f6..1291f2b0 100644
--- a/frontend/tests/away.test.mjs
+++ b/frontend/tests/away.test.mjs
@@ -162,3 +162,22 @@ test('sidebar entry shows the unseen badge only when there is something new', ()
assert.doesNotMatch(ui.sidebar({ ...base, inboxCount: 0 }), /sr-only"> new/);
assert.match(ui.sidebar({ ...base, inboxCount: 3, inboxActive: true }), /aria-current="page"/);
});
+
+test('a limit message is never shown as a card summary', () => {
+ for (const line of [
+ "You've hit your session limit · resets 3am (Europe/Berlin)",
+ 'You have hit your weekly limit',
+ 'Claude usage limit reached',
+ "You've reached your Opus limit · resets 5pm",
+ '5-hour limit reached · resets 02:00',
+ ]) {
+ assert.equal(a.isLimitLine(line), true, line);
+ const html = view({ data: resp({ failed: [item({ id: 'd9', status: 'failed', title: 'Review PR', summary: line })] }) });
+ assert.match(html, /Review PR/);
+ assert.doesNotMatch(html, /limit/i, `"${line}" must not reach the card`);
+ }
+ // Ordinary summaries, including ones that mention limits, stay.
+ for (const ok of ['Brief', 'Finished', 'Raised the rate-limit config to 100', 'Failed']) assert.equal(a.isLimitLine(ok), false, ok);
+ assert.equal(a.awaySummary({ title: 't', summary: 'Brief' }), 'Brief');
+ assert.equal(a.awaySummary({ title: 't', summary: "You've hit your session limit · resets 3am" }), '');
+});
diff --git a/frontend/tests/failover.test.mjs b/frontend/tests/failover.test.mjs
new file mode 100644
index 00000000..79caa8c7
--- /dev/null
+++ b/frontend/tests/failover.test.mjs
@@ -0,0 +1,159 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+// The sound module reads its mute flag on load; the list plays a click on a move.
+const m = await loadBundled(`
+ export * from './src/failover';
+ export * from './src/failoverNotes';
+ export { AccountPriority } from './src/components/AccountPriority';
+ export { ReplyMeta } from './src/components/ReplyMeta';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+const h = m.createElement;
+
+const NOW = Date.parse('2026-11-02T20:00:00');
+const profile = (over) => ({
+ id: 'p', engine: 'claude', name: 'Work', kind: 'cli_home', enabled: true, is_default: false, priority: 100,
+ home_dir: null, has_key: false, signed_in: true, account_label: null, limited_until: null, last_error: null, ...over,
+});
+const engine = (id, over = {}) => ({ id, name: id, kind: 'cli', status: 'ready', detail: null, version: '1', models: [], checked_at: null, enabled: true, ready: true, uses: null, ...over });
+const list = [
+ profile({ id: 'c1', name: 'Work', priority: 10, limited_until: '2026-11-03T03:00:00' }),
+ profile({ id: 'x1', engine: 'codex', name: 'Personal', priority: 20 }),
+ profile({ id: 'k1', engine: 'claude', name: 'API', kind: 'api_key', has_key: true, priority: 30 }),
+ profile({ id: 'g1', engine: 'grok', name: 'Grok', priority: 40, signed_in: false }),
+ profile({ id: 'u1', engine: 'custom', name: 'Copilot', kind: 'custom_api', priority: 50, custom: { status: 'ready', models: [], protocol: 'openai-chat', base_url: 'x', model: null, detail: null, checked_at: null, supports_tools: true } }),
+];
+
+test('one list across engines, ordered by priority with stable ties', () => {
+ const shuffled = [list[3], list[0], list[4], list[2], list[1]];
+ assert.deepEqual(m.failoverOrder(shuffled).map((p) => p.id), ['c1', 'x1', 'k1', 'g1', 'u1']);
+ const tie = [profile({ id: 'b', name: 'B' }), profile({ id: 'a', name: 'A' }), profile({ id: 'sys', kind: 'system', name: 'This machine' })];
+ assert.deepEqual(m.failoverOrder(tie).map((p) => p.id), ['sys', 'a', 'b']);
+});
+
+test('status words: Ready, Out until a local time, Signed out', () => {
+ assert.deepEqual(m.priorityStatus(list[1], engine('codex'), NOW), { tone: 'ok', label: 'Ready' });
+ const out = m.priorityStatus(list[0], engine('claude'), NOW);
+ assert.equal(out.tone, 'warn');
+ assert.match(out.label, /^Out until /);
+ assert.match(out.label, /03:00/);
+ assert.match(out.label, /^Out until \w{3} 03:00$/, 'a reset on another day names the day');
+ assert.equal(m.priorityStatus(list[3], engine('grok'), NOW).label, 'Signed out');
+ assert.equal(m.priorityStatus(profile({ last_error: 'auth' }), engine('claude'), NOW).label, 'Signed out');
+ assert.equal(m.priorityStatus(profile({ enabled: false, limited_until: '2026-11-03T03:00:00' }), engine('claude'), NOW).label, 'Off');
+ assert.equal(m.priorityStatus(list[4], undefined, NOW).label, 'Ready');
+ // A limit that has passed is Ready again, with no action.
+ assert.equal(m.priorityStatus(profile({ limited_until: '2026-11-02T19:00:00' }), engine('claude'), NOW).label, 'Ready');
+ // Same-day reset is the bare time.
+ assert.equal(m.priorityStatus(profile({ limited_until: '2026-11-02T23:30:00' }), engine('claude'), NOW).label, 'Out until 23:30');
+});
+
+test('moving rewrites only the priorities that change', () => {
+ const order = m.failoverOrder(list);
+ const next = m.moveAccount(order, 3, 1);
+ assert.deepEqual(next.map((p) => p.id), ['c1', 'g1', 'x1', 'k1', 'u1']);
+ assert.deepEqual(m.priorityUpdates(next), [
+ { id: 'g1', priority: 20 },
+ { id: 'x1', priority: 30 },
+ { id: 'k1', priority: 40 },
+ ]);
+ assert.equal(m.moveAccount(order, 2, 2), null);
+ assert.equal(m.moveAccount(order, 0, -1), null);
+ assert.equal(m.moveAccount(order, 4, 5), null);
+ // Equal priorities get distinct ranks once one moves.
+ const ties = [profile({ id: 'a', priority: 100 }), profile({ id: 'b', priority: 100 })];
+ assert.deepEqual(m.priorityUpdates([ties[1], ties[0]]), [{ id: 'b', priority: 10 }, { id: 'a', priority: 20 }]);
+ assert.equal(m.moveAnnouncement('Codex', 1, 5), 'Codex moved to position 2 of 5.');
+});
+
+const markup = (props) => m.renderToStaticMarkup(h(m.AccountPriority, { profiles: list, engines: [engine('claude'), engine('codex'), engine('grok')], onChanged: async () => {}, now: NOW, ...props }));
+
+test('the list is an ordered list with the caption, a status per row and labelled arrow buttons', () => {
+ const html = markup();
+ assert.match(html, /When one runs out, kwant bots move to the next that still works, in this order\./);
+ assert.equal((html.match(/<li /g) ?? []).length, 5);
+ assert.match(html, /<ol /);
+ assert.match(html, /Claude API key/);
+ assert.match(html, /Custom API/);
+ assert.match(html, /Out until/);
+ assert.match(html, /Signed out/);
+ assert.match(html, /disabled="" aria-label="Move Work \(Claude\) up"/, 'the first row can not go up');
+ assert.match(html, /disabled="" aria-label="Move Copilot \(Custom API\) down"/, 'the last row can not go down');
+ assert.doesNotMatch(html, /disabled="" aria-label="Move Personal \(Codex\) up"/);
+ assert.match(html, /role="status"/);
+ assert.doesNotMatch(html, /[\u{1F300}-\u{1FAFF}]/u, 'no emoji');
+});
+
+test('the failover notice is one short line, naming the limit time and the model', () => {
+ const e = { kwant_id: 'k', from_profile_id: 'c1', from_name: 'Work', to_profile_id: 'x1', to_name: 'Personal', class: 'quota',
+ retry_at: '2026-11-02T23:30:00', from_engine: 'claude', to_engine: 'codex', to_model: 'GPT-6.1' };
+ assert.equal(m.failoverNotice(e, NOW), 'Claude is out until 23:30 · answered on Codex (GPT-6.1)');
+ assert.equal(m.failoverNotice({ ...e, class: 'auth', retry_at: undefined }, NOW), 'Claude is signed out · answered on Codex (GPT-6.1)');
+ assert.equal(m.failoverNotice({ ...e, retry_at: undefined }, NOW), 'Claude is out of usage · answered on Codex (GPT-6.1)');
+ // An older server sends no engine or model: the account names stand in.
+ assert.equal(m.failoverNotice({ ...e, from_engine: undefined, to_engine: undefined, to_model: undefined, retry_at: undefined }, NOW), 'Work is out of usage · answered on Personal');
+ assert.equal(m.failoverNotice({ ...e, to_model: undefined, to_model_label: 'GPT-6.1' }, NOW), 'Claude is out until 23:30 · answered on Codex (GPT-6.1)');
+});
+
+test('a chat is told once per outage', () => {
+ const log = m.createOutageLog();
+ const e = { kwant_id: 'k', from_profile_id: 'c1', class: 'quota', retry_at: '2026-11-03T03:00:00Z' };
+ assert.equal(log.first(m.outageKey(e)), true);
+ assert.equal(log.first(m.outageKey(e)), false, 'the next turn in the same outage');
+ assert.equal(log.first(m.outageKey(e, 'thread-2')), true, 'another chat is told once too');
+ assert.equal(log.first(m.outageKey({ ...e, retry_at: '2026-11-04T03:00:00Z' })), true, 'a new outage is a new line');
+ assert.equal(log.first(m.outageKey({ ...e, class: 'auth' })), true);
+});
+
+test('a note goes under the first reply by its bot after the switch, and the live bubble until then', () => {
+ const msgs = [
+ { id: 'u1', sender_role: 'user', sender_id: 'me', created_at: '2026-11-02T19:59:00Z' },
+ { id: 'm0', sender_role: 'kwant', sender_id: 'Architect', created_at: '2026-11-02T19:00:00Z' },
+ { id: 'm1', sender_role: 'kwant', sender_id: 'Architect', created_at: '2026-11-02T20:00:30Z' },
+ { id: 'm2', sender_role: 'kwant', sender_id: 'Architect', created_at: '2026-11-02T20:05:00Z' },
+ ];
+ const at = Date.parse('2026-11-02T20:00:10Z');
+ const notes = [{ name: 'Architect', text: 'Claude is out until 03:00 · answered on Codex (GPT-6.1)', at }];
+ const got = m.assignSwitchNotes(notes, msgs, (x) => x.sender_id);
+ assert.deepEqual([...got.entries()], [['m1', notes[0].text]]);
+ // No reply yet: the live bubble carries it.
+ const none = m.assignSwitchNotes(notes, msgs.slice(0, 2), (x) => x.sender_id);
+ assert.equal(none.size, 0);
+ assert.equal(m.liveSwitchNote(notes, none, 'Architect', at + 1000), notes[0].text);
+ assert.equal(m.liveSwitchNote(notes, got, 'Architect', at + 1000), null, 'not twice');
+ assert.equal(m.liveSwitchNote(notes, none, 'Other', at + 1000), null);
+});
+
+test('the notice sits under the name and wraps, so it fits at 390 px', () => {
+ const html = m.renderToStaticMarkup(h(m.ReplyMeta, { name: 'Architect', at: '2026-11-02T20:00:30Z', note: 'Claude is out until 03:00 · answered on Codex (GPT-6.1)' }));
+ assert.match(html, /data-failover-note/);
+ assert.match(html, /break-words/);
+ assert.doesNotMatch(html, /truncate[^"]*"[^>]*data-failover-note/);
+ assert.ok(html.indexOf('Architect') < html.indexOf('data-failover-note'));
+ assert.doesNotMatch(m.renderToStaticMarkup(h(m.ReplyMeta, { name: 'Architect' })), /data-failover-note/);
+});
+
+test('a saved reply reads its notice from meta.failover, so it survives a reload', () => {
+ const sw = { kwant_id: 'k', from_profile_id: 'c1', to_profile_id: 'x1', from_name: 'Work', to_name: 'Personal', class: 'quota', retry_at: '2026-11-03T02:00:00Z', from_engine: 'claude', to_engine: 'codex', to_model: 'gpt-6.1' };
+ const now = Date.parse('2026-11-02T20:00:00Z');
+ const line = m.savedFailoverNotice(JSON.stringify({ failover: [sw] }), now);
+ assert.match(line, /^Claude is out until .*\d\d:\d\d · answered on Codex \(gpt-6\.1\)$/);
+ // Already parsed, and a single object, read the same.
+ assert.equal(m.savedFailoverNotice({ failover: sw }, now), line);
+ // Two switches in one reply: first account out, last one answered.
+ const two = m.savedFailoverNotice({ failover: [sw, { ...sw, from_engine: 'codex', to_engine: 'grok', to_model: 'grok-4.7' }] }, now);
+ assert.match(two, /^Claude is out until .* · answered on Grok \(grok-4\.7\)$/);
+ // Auth, and a reset already past.
+ assert.equal(m.savedFailoverNotice({ failover: [{ ...sw, class: 'auth' }] }, now), 'Claude is signed out · answered on Codex (gpt-6.1)');
+ assert.equal(m.savedFailoverNotice({ failover: [{ ...sw, retry_at: '2026-11-01T00:00:00Z' }] }, now), 'Claude is out of usage · answered on Codex (gpt-6.1)');
+});
+
+test('a reply with no or malformed failover meta shows no notice', () => {
+ for (const meta of [null, undefined, '', 'not json', '{"ran_on":{}}', { failover: [] }, { failover: 'x' }, { failover: [null, 3, {}] }, { failover: [{ from_name: 'A' }] }]) {
+ assert.equal(m.savedFailoverNotice(meta), null);
+ }
+});