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.

Router UI: ask card, plain route reasons, covers/avoids, "Wrong bot?"

Ada (kwant bot)d2bd098c9999
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index f9a3e6ac..92cd1bed 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -34,6 +34,8 @@ import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './m
import { ApiError, BotActionMeta, HireMeta, applyBotAction, applyHire, botActionsApi, changesBots, decisionError, hiresApi } from './botActions';
import { BotActionCard, type BotActionDecision } from './components/BotActionCard';
import { HireCard, type HireDecision } from './components/HireCard';
+import { RouteChoiceCard } from './components/RouteChoiceCard';
+import { RouteChoiceMeta, applyRouteChoice, correctRoute, isAskingReply, rerouteTargetsFor, resolveRouteChoice } from './routeChoice';
import type { RoutineFocus } from './components/RoutinesPanel';
import { AwayPage } from './components/AwayView';
import { LooseEndsPage } from './components/LooseEndsView';
@@ -632,6 +634,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// 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>>({});
+ // Laya's "Who should answer this?" cards, by route_choice_id (route_choice_updated).
+ const [routeChoices, setRouteChoices] = useState<Record<string, RouteChoiceMeta>>({});
// Virtual Machine & Live Browser state
const [isVmPaneOpen, setIsVmPaneOpen] = useState(false);
@@ -929,6 +933,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (a?.id) setBotActions((prev) => applyBotAction(prev, a));
break;
}
+ case 'route_choice_updated':
+ case 'RouteChoiceUpdated': {
+ const c = event.data?.choice;
+ if (c) setRouteChoices((prev) => applyRouteChoice(prev, c));
+ break;
+ }
case 'hire_updated':
case 'HireUpdated': {
const h = event.data?.hire;
@@ -1363,6 +1373,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}
throw new Error(message);
}
+ const reply = await res.json().catch(() => null);
+ if (isAskingReply(reply)) {
+ // A close call: Laya posted "Who should answer this?" and nothing runs until the person picks.
+ if (turnsIn(turnsRef.current, targetId).length === 0) clearLive(targetId);
+ if (streamingContextIdRef.current === targetId) {
+ setRoutingState(null);
+ streamingContextIdRef.current = null;
+ }
+ }
return true;
} catch (err) {
console.error('Failed sending chat:', err);
@@ -1929,6 +1948,35 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
);
};
+ const renderRouteChoice = (msg: ChatMessage, meta: RouteChoiceMeta, flash: boolean, question?: string) => (
+ <RouteChoiceCard
+ meta={meta}
+ messageId={msg.id}
+ live={routeChoices[meta.route_choice_id]}
+ question={question}
+ flash={flash}
+ onResolve={async (id, pick) => {
+ haptic('tap');
+ const r = await resolveRouteChoice(id, pick);
+ if (r.kind === 'error') haptic('warning');
+ return r;
+ }}
+ />
+ );
+
+ /** "Wrong bot?": teach routing that this message is the other bot's, then ask that bot now. */
+ const handleSendToOtherBot = async (question: ChatMessage, kwantId: string): Promise<string | void> => {
+ haptic('tap');
+ const err = await correctRoute(question.id, kwantId);
+ if (err) {
+ haptic('warning');
+ return err;
+ }
+ const name = kwants.find((k) => k.id === kwantId)?.name;
+ if (!name) return 'That bot is gone.';
+ if (!(await handleSendMessage(`@${name} ${question.text}`))) return `Routing learned, but ${name} wasn’t asked. Send it again with @${name}.`;
+ };
+
const renderDelegation = (msg: ChatMessage, meta: DelegationMeta, flash: boolean) => {
const queued = turnsIn(turns, meta.thread_id).find((t) => t.state === 'queued');
return (
@@ -2989,6 +3037,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
renderConnectionSuggestion={renderConnectionSuggestion}
renderBotAction={renderBotAction}
renderHire={renderHire}
+ renderRouteChoice={renderRouteChoice}
+ rerouteTargets={openThreadId ? [] : rerouteTargetsFor(currentChannel, kwants)}
+ onSendToOtherBot={openThreadId ? undefined : handleSendToOtherBot}
awaitingAnswer={awaitingHere}
awaitingBrowser={awaitingBrowserHere}
liveActivity={isCurrentContextStreaming ? activityHere : null}
diff --git a/frontend/src/botActions.ts b/frontend/src/botActions.ts
index 3f0e2359..c80a83fe 100644
--- a/frontend/src/botActions.ts
+++ b/frontend/src/botActions.ts
@@ -217,9 +217,17 @@ export function routineButtons(m: BotActionMeta): { edit: boolean; pause: boolea
export type HireStatus = 'pending' | 'accepted' | 'auto_accepted' | 'denied' | 'undone';
const HIRE_STATUSES: HireStatus[] = ['pending', 'accepted', 'auto_accepted', 'denied', 'undone'];
+/** One earlier request a "repeated" hire rests on. The server stores `{message_id, at, text}`;
+ * older cards may hold bare ids. */
+export interface SimilarRequest {
+ message_id: string;
+ at: string | null;
+ text: string | null;
+}
+
export type HireEvidence =
| { basis: 'specialist'; needs: string[]; gap: string }
- | { basis: 'repeated'; similar_requests: string[] }
+ | { basis: 'repeated'; similar_requests: SimilarRequest[] }
| { basis: 'other'; text: string };
/** `meta` of a hire proposal card (`kind: "hire_proposal"`). */
@@ -273,12 +281,28 @@ export interface Hire {
const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && !!x) : []);
+function similarRequests(v: unknown): SimilarRequest[] {
+ if (!Array.isArray(v)) return [];
+ const out: SimilarRequest[] = [];
+ for (const x of v) {
+ const o = typeof x === 'string' ? { message_id: x } : x && typeof x === 'object' ? (x as Record<string, unknown>) : null;
+ const id = o && typeof o.message_id === 'string' ? o.message_id : '';
+ if (!id || out.some((r) => r.message_id === id)) continue;
+ out.push({
+ message_id: id,
+ at: typeof o!.at === 'string' && o!.at ? (o!.at as string) : null,
+ text: typeof o!.text === 'string' && (o!.text as string).trim() ? (o!.text as string).trim() : null,
+ });
+ }
+ return out;
+}
+
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) };
+ if (e.basis === 'repeated') return { basis: 'repeated', similar_requests: similarRequests(e.similar_requests) };
return null;
}
@@ -373,6 +397,14 @@ export function applyHire(map: Record<string, HireMeta>, h: Hire | null | undefi
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. */
+/** "Oct 28": when a past request was asked, short. */
+export function shortDate(at: string | null, now: Date = new Date()): string {
+ if (!at) return '';
+ const d = new Date(at);
+ if (Number.isNaN(d.getTime())) return '';
+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(d.getFullYear() !== now.getFullYear() ? { year: 'numeric' } : {}) });
+}
+
export function evidenceText(e: HireEvidence | null, requestedByPerson: boolean): string {
if (requestedByPerson) return 'You asked for this kind of bot.';
if (!e) return '';
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index bdc4ae0f..e0771123 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,5 +1,5 @@
-import React, { useState, useRef, useEffect } from 'react';
-import { ArrowDown, ArrowUp, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor } from 'lucide-react';
+import React, { useState, useRef, useEffect, useMemo } from 'react';
+import { ArrowDown, ArrowUp, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, Loader2 } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
@@ -45,6 +45,7 @@ import { isSystemNotice, parseInterruption, retryTargets } from '../interruption
import { consultedNames, hideStreamingDecisions, messageDecisions, parseWorkAhead } from '../decideFirst';
import { approvalScrollAction, fullyVisible, isNearBottom, nextFollowing } from '../approvalVisibility';
import { DecidingLine, DecisionChips, WorkAheadBody } from './Proactive';
+import { RouteChoiceMeta, parseRouteChoiceMeta, questionsOfReplies } from '../routeChoice';
/** A swipeable chip row whose right fade edge (phones only, see .kw-scroll-row) goes away once
* it is scrolled to the end, or when everything already fits. */
@@ -218,6 +219,14 @@ export interface ChatViewProps {
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;
+ /** Laya's "Who should answer this?" card (message meta kind "route_choice"); `question` is the
+ * person's message it is about, when it's loaded. */
+ renderRouteChoice?: (msg: ChatMessage, meta: RouteChoiceMeta, flash: boolean, question?: string) => React.ReactNode;
+ /** Bots a routed reply can be sent to instead ("Wrong bot? Send to…"); empty hides it. */
+ rerouteTargets?: Array<{ id: string; name: string; title: string }>;
+ /** Teaches routing that `question` should have gone to `kwantId` and asks that bot now.
+ * Resolves to an error message on failure. */
+ onSendToOtherBot?: (question: ChatMessage, kwantId: string) => Promise<string | void>;
/** Opens Space settings → Accounts; turns a "nothing can run" reply into a card with a button. */
onOpenAccounts?: () => void;
/** Whether anything can run a bot in this space now (null while unknown). */
@@ -256,28 +265,113 @@ export const renderFormattedText = (text: string): React.ReactNode => {
});
};
-/** Why Laya picked this bot. Phones show one line and open the rest on a tap. */
-const RoutingLine: React.FC<{ text: string; fallback: boolean }> = ({ text, fallback }) => {
+interface Reroute {
+ /** The reply's id, for element ids. */
+ key: string;
+ targets: Array<{ id: string; name: string; title: string }>;
+ onPick: (kwantId: string) => Promise<string | void>;
+}
+
+/** Why Laya picked this bot. Phones show one line and open the rest on a tap. With `reroute`, a
+ * "Wrong bot?" link opens the other bots here; picking one teaches routing and asks that bot. */
+const RoutingLine: React.FC<{ text: string; fallback: boolean; reroute?: Reroute }> = ({ text, fallback, reroute }) => {
const [open, setOpen] = useState(false);
+ const [picking, setPicking] = useState(false);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [sentTo, setSentTo] = useState<string | null>(null);
const tone = fallback ? 'text-amber-300/80' : 'text-violet-300/80';
const icon = <Sparkles size={10} className="inline -mt-0.5 mr-1" aria-hidden="true" />;
+ const panelId = reroute ? `reroute-${reroute.key}` : undefined;
+ const canReroute = !!reroute && reroute.targets.length > 0;
+
+ const pick = async (k: { id: string; name: string }) => {
+ if (!reroute || busy) return;
+ setBusy(k.id);
+ setError(null);
+ const err = await reroute.onPick(k.id);
+ setBusy(null);
+ if (err) setError(err);
+ else {
+ setSentTo(k.name);
+ setPicking(false);
+ }
+ };
+
+ const wrongBot = canReroute && !sentTo && (
+ <button
+ type="button"
+ onClick={() => setPicking((v) => !v)}
+ aria-expanded={picking}
+ aria-controls={panelId}
+ className="shrink-0 py-1 sm:py-0 text-[11px] text-zinc-500 hover:text-zinc-200 underline decoration-dotted underline-offset-2 rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ Wrong bot?
+ </button>
+ );
+
return (
<>
- <p className={`hidden sm:block -mt-1 mb-1.5 text-[11px] ${tone} break-words`} data-routing-line>
- {icon}
- {text}
- </p>
- <button
- type="button"
- data-compact
- onClick={() => setOpen((v) => !v)}
- aria-expanded={open}
- title={open ? undefined : text}
- className={`sm:hidden -mt-3.5 -mb-1.5 py-3.5 max-w-full text-left text-[11px] ${tone} ${open ? 'break-words' : 'truncate'} rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500`}
- >
- {icon}
- {text}
- </button>
+ <div className="hidden sm:flex items-baseline gap-2 -mt-1 mb-1.5 max-w-full min-w-0" data-routing-line>
+ <p className={`text-[11px] ${tone} break-words min-w-0`}>
+ {icon}
+ {text}
+ </p>
+ {wrongBot}
+ </div>
+ <div className="sm:hidden flex items-center gap-2 -mt-3.5 -mb-1.5 max-w-full min-w-0">
+ <button
+ type="button"
+ data-compact
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ title={open ? undefined : text}
+ className={`py-3.5 min-w-0 flex-1 text-left text-[11px] ${tone} ${open ? 'break-words' : 'truncate'} rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500`}
+ >
+ {icon}
+ {text}
+ </button>
+ {wrongBot}
+ </div>
+ {picking && reroute && (
+ <div id={panelId} role="group" aria-label="Send to another bot" className="mt-1 sm:mt-0 mb-2 max-w-full rounded-xl border border-zinc-800 bg-zinc-950/70 px-3 py-2">
+ <p className="text-[11px] text-zinc-400 mb-1.5">Send your message to:</p>
+ <div className="flex flex-wrap gap-1.5">
+ {reroute.targets.map((k) => (
+ <button
+ key={k.id}
+ type="button"
+ disabled={busy !== null}
+ onClick={() => pick(k)}
+ title={k.title}
+ className="inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[28px] px-2.5 rounded-lg border border-zinc-700 bg-zinc-900 text-xs text-zinc-100 hover:bg-zinc-800 disabled:opacity-60 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ {busy === k.id && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ <span>{k.name}</span>
+ {k.title && <span className="hidden sm:inline text-zinc-500">· {k.title}</span>}
+ </button>
+ ))}
+ <button
+ type="button"
+ onClick={() => setPicking(false)}
+ className="min-h-[36px] sm:min-h-[28px] px-2.5 rounded-lg text-xs text-zinc-400 hover:text-zinc-200 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ Cancel
+ </button>
+ </div>
+ <p className="mt-1.5 text-[11px] text-zinc-500">Messages like this will go to the bot you pick from now on.</p>
+ {error && (
+ <p role="alert" className="mt-1 text-[11px] text-rose-400 break-words">
+ {error}
+ </p>
+ )}
+ </div>
+ )}
+ {sentTo && (
+ <p role="status" className="-mt-0.5 mb-1.5 text-[11px] text-emerald-300/90">
+ Sent to {sentTo}. Messages like this will go to {sentTo} from now on.
+ </p>
+ )}
</>
);
};
@@ -429,6 +523,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
renderConnectionSuggestion,
renderBotAction,
renderHire,
+ renderRouteChoice,
+ rerouteTargets = [],
+ onSendToOtherBot,
onOpenAccounts,
canRun = null,
awaitingAnswer,
@@ -490,6 +587,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
}, [teamsProp]);
const activeKwants = kwantsProp || internalKwants;
+ // Each routed reply's question: the person's latest saved message before it ("Wrong bot?").
+ const questionOf = useMemo(() => questionsOfReplies(messages), [messages]);
const activeTeams = teamsProp || internalTeams;
const mentionItems: MentionItem[] = [
@@ -847,6 +946,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
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 routeChoice = msg.meta && renderRouteChoice ? parseRouteChoiceMeta(msg.meta) : null;
+ if (routeChoice && renderRouteChoice) {
+ const asked = messages.find((m) => m.id === routeChoice.user_message_id);
+ return <React.Fragment key={msg.id}>{renderRouteChoice(msg, routeChoice, flashId === msg.id, asked?.text)}</React.Fragment>;
+ }
const setup = msg.meta && onOpenAccounts ? parseSetupMeta(msg.meta) : null;
if (setup && onOpenAccounts)
return (
@@ -973,7 +1077,21 @@ export const ChatView: React.FC<ChatViewProps> = ({
</ReplyMeta>
)}
- {routed && <RoutingLine text={routingLine(routed, spaceName ?? 'this space')} fallback={!!routed.fallback} />}
+ {routed && (
+ <RoutingLine
+ text={routingLine(routed, spaceName ?? 'this space', (id) => activeKwants.find((k) => k.id === id)?.name)}
+ fallback={!!routed.fallback}
+ reroute={
+ onSendToOtherBot && questionOf.get(msg.id)
+ ? {
+ key: msg.id,
+ targets: rerouteTargets.filter((k) => k.id !== routed.kwant_id && k.name !== displayName),
+ onPick: (kwantId) => onSendToOtherBot(questionOf.get(msg.id)!, kwantId),
+ }
+ : undefined
+ }
+ />
+ )}
{/* Message Body Bubble */}
{!filesOnly && (text.trim() || !files.length) && (
diff --git a/frontend/src/components/HireCard.tsx b/frontend/src/components/HireCard.tsx
index 5c06776d..02e09cce 100644
--- a/frontend/src/components/HireCard.tsx
+++ b/frontend/src/components/HireCard.tsx
@@ -1,7 +1,7 @@
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, hireLeadIndex, hiredBotGone, isTeamHire, modelText } from '../botActions';
+import { HireMeta, evidenceText, hireStateText, hireView, hireLeadIndex, hiredBotGone, isTeamHire, modelText, shortDate } from '../botActions';
export type HireDecision = 'deny' | 'accept_once' | 'always_accept' | 'undo';
@@ -108,6 +108,16 @@ export const HireCard: React.FC<HireCardProps> = ({ meta, messageId, kwantName,
{evidence}
</p>
)}
+ {!view.requested_by_person && view.evidence?.basis === 'repeated' && view.evidence.similar_requests.some((r) => r.text) && (
+ <ul aria-label="Your earlier requests" className="space-y-1 border-l-2 border-zinc-700 pl-3">
+ {view.evidence.similar_requests.map((r) => (
+ <li key={r.message_id} className="text-xs text-zinc-300 break-words leading-relaxed">
+ {r.text ? <q className="italic">{r.text}</q> : <span className="text-zinc-500">An earlier message</span>}
+ {shortDate(r.at) && <span className="text-zinc-500 not-italic"> · {shortDate(r.at)}</span>}
+ </li>
+ ))}
+ </ul>
+ )}
</div>
{team ? (
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index b5d63935..108dcc83 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -1,4 +1,5 @@
import React, { useEffect, useState } from 'react';
+import { TagListInput } from './TagListInput';
import { X, Sparkles, Pencil, ChevronRight, Brain, CalendarClock, UserRound, ListChecks, Trash2, Gauge } from 'lucide-react';
import { ModernAvatar, AVATAR_STYLES } from './ModernAvatar';
import { AGENT_PRESETS, AgentPreset, PRESET_GROUPS, PresetGroup, uniqueAgentName } from '../agentPresets';
@@ -37,6 +38,9 @@ export interface AgentFormData {
/** Pinned LLM profile; null uses the engine's default. */
profile_id?: string | null;
profile_failover?: boolean;
+ /** What routing sends it ("Good for") and keeps away from it ("Not for"). */
+ covers?: string[];
+ avoids?: string[];
}
interface NewAgentModalProps {
@@ -115,6 +119,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const [mcpIds, setMcpIds] = useState<string[] | undefined>(undefined);
const [profileId, setProfileId] = useState<string | null>(null);
const [failover, setFailover] = useState(true);
+ const [covers, setCovers] = useState<string[]>([]);
+ const [avoids, setAvoids] = useState<string[]>([]);
// Follows the prop until the person changes this bot's approvals here.
const [toolsRunFree, setToolsRunFree] = useState(approvalsOff);
useEffect(() => setToolsRunFree(approvalsOff), [approvalsOff, isOpen]);
@@ -142,6 +148,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
setMcpIds(undefined);
setProfileId(initial?.profile_id ?? null);
setFailover(initial?.profile_failover ?? true);
+ setCovers(initial?.covers ?? []);
+ setAvoids(initial?.avoids ?? []);
let cancelled = false;
// If a list can't load, the picker stays hidden and nothing is saved: saving an empty
// list would switch every server off for this kwant.
@@ -201,6 +209,8 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
profile_id:
profiles.length === 0 ? undefined : engine && engineProfiles.some((p) => p.id === profileId) ? profileId : null,
profile_failover: failover,
+ // Only once loaded (edit): older servers leave them out, and a new bot has none yet.
+ ...(isEdit && initial?.covers ? { covers, avoids } : {}),
});
setSubmitting(false);
@@ -486,6 +496,26 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
/>
</div>
+ {isEdit && initial?.covers && (
+ <div className="space-y-3">
+ <TagListInput
+ label="Good for"
+ hint="what to send this bot"
+ placeholder="e.g. taxes, invoices — Enter to add"
+ value={covers}
+ onChange={setCovers}
+ />
+ <TagListInput
+ label="Not for"
+ hint="what never to send it"
+ placeholder="e.g. legal advice — Enter to add"
+ value={avoids}
+ onChange={setAvoids}
+ tone="bad"
+ />
+ </div>
+ )}
+
{isEdit && initial && name.trim() !== initial.name && (
<p className="text-[11px] text-zinc-500">
Renaming updates past messages; teammates will need to @mention the new name.
diff --git a/frontend/src/components/RouteChoiceCard.tsx b/frontend/src/components/RouteChoiceCard.tsx
new file mode 100644
index 00000000..07891430
--- /dev/null
+++ b/frontend/src/components/RouteChoiceCard.tsx
@@ -0,0 +1,141 @@
+import React, { useRef, useState } from 'react';
+import { Check, CheckCircle2, Loader2, MessagesSquare, Sparkles } from 'lucide-react';
+import { ResolvePick, ResolveResult, RouteChoiceMeta, generalHint, routeChoiceOutcome, routeChoiceView } from '../routeChoice';
+
+export interface RouteChoiceCardProps {
+ meta: RouteChoiceMeta;
+ messageId: string;
+ /** Newer card from `route_choice_updated`; wins over `meta` unless it would reopen it. */
+ live?: RouteChoiceMeta | null;
+ /** The person's message this card is about, quoted when known. */
+ question?: string;
+ onResolve: (routeChoiceId: string, pick: ResolvePick) => Promise<ResolveResult>;
+ flash?: boolean;
+}
+
+type Busy = string | 'general' | null;
+
+/**
+ * Laya's "Who should answer this?" card for a close call: two bots and "Answer generally". Nothing
+ * answers until the person taps one. A settled card keeps the pick and disables the buttons; a
+ * second tap (409) just shows it's already answered.
+ */
+export const RouteChoiceCard: React.FC<RouteChoiceCardProps> = ({ meta, messageId, live, question, onResolve, flash }) => {
+ const view = routeChoiceView(meta, live);
+ const [busy, setBusy] = useState<Busy>(null);
+ const [error, setError] = useState<string | null>(null);
+ // Shown right away; route_choice_updated confirms it with the real pick.
+ const [sent, setSent] = useState<Busy | 'already'>(null);
+ const refs = useRef<Array<HTMLButtonElement | null>>([]);
+
+ const open = view.status === 'open' && sent === null;
+ const outcome = routeChoiceOutcome(view);
+ const pickedId = view.status === 'resolved' ? (view.chose_general ? 'general' : view.chosen_kwant_id) : sent === 'already' ? null : sent;
+ const headingId = `rc-${messageId}`;
+
+ const pick = async (key: string | 'general') => {
+ if (!open || busy !== null) return;
+ setBusy(key);
+ setError(null);
+ const r = await onResolve(view.route_choice_id, key === 'general' ? { general: true } : { kwant_id: key });
+ setBusy(null);
+ if (r.kind === 'sent') setSent(key);
+ else if (r.kind === 'already') setSent('already');
+ else setError(r.message);
+ };
+
+ const options: Array<{ key: string; label: string; sub: string }> = [
+ ...view.choices.slice(0, 2).map((b) => ({ key: b.kwant_id, label: b.name, sub: b.title })),
+ { key: 'general', label: view.general.label || 'Answer generally', sub: generalHint(view) },
+ ];
+
+ const onKey = (e: React.KeyboardEvent, i: number) => {
+ const n = options.length;
+ const to = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? (i + 1) % n : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? (i - 1 + n) % n : -1;
+ if (to < 0) return;
+ e.preventDefault();
+ refs.current[to]?.focus();
+ };
+
+ const status = outcome ? (
+ <span className="inline-flex items-center gap-1.5 text-emerald-300">
+ <CheckCircle2 size={13} aria-hidden="true" /> {outcome}
+ </span>
+ ) : sent === 'already' ? (
+ <span className="inline-flex items-center gap-1.5 text-zinc-400">
+ <CheckCircle2 size={13} aria-hidden="true" /> Already answered.
+ </span>
+ ) : sent !== null ? (
+ <span className="inline-flex items-center gap-1.5 text-emerald-300">
+ <CheckCircle2 size={13} aria-hidden="true" /> {sent === 'general' ? 'Sent. A general answer is coming.' : `Sent. ${options.find((o) => o.key === sent)?.label ?? 'The bot'} is answering.`}
+ </span>
+ ) : (
+ <span className="text-zinc-400">Nothing is answered until you choose.</span>
+ );
+
+ return (
+ <section
+ data-message-id={messageId}
+ data-route-choice={view.status}
+ aria-labelledby={headingId}
+ className={`flex items-start gap-3.5 w-full max-w-5xl rounded-xl ${flash ? 'kw-flash' : ''}`}
+ >
+ <div className="w-[34px] h-[34px] flex-shrink-0 rounded-full bg-violet-500/15 border border-violet-500/40 flex items-center justify-center" aria-hidden="true">
+ <Sparkles size={16} className="text-violet-300" />
+ </div>
+ <div className={`flex-1 min-w-0 max-w-2xl rounded-2xl rounded-tl-sm border bg-zinc-900/60 shadow-sm ${open ? 'border-violet-500/40' : 'border-zinc-800'}`}>
+ <div className="px-4 pt-3 pb-2 space-y-1">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
+ <MessagesSquare size={12} className="text-violet-300" aria-hidden="true" />
+ <span className="text-zinc-200">Laya</span> · router
+ </span>
+ <h3 id={headingId} className="text-sm font-semibold text-zinc-100 leading-snug">
+ Who should answer this?
+ </h3>
+ {question && <p className="text-xs text-zinc-400 break-words line-clamp-2">“{question}”</p>}
+ </div>
+
+ <div role="group" aria-labelledby={headingId} className="px-4 pb-2 grid grid-cols-1 sm:grid-cols-3 gap-2">
+ {options.map((o, i) => {
+ const chosen = pickedId === o.key;
+ return (
+ <button
+ key={o.key}
+ ref={(el) => (refs.current[i] = el)}
+ type="button"
+ disabled={!open || busy !== null}
+ aria-pressed={chosen}
+ onClick={() => pick(o.key)}
+ onKeyDown={(e) => onKey(e, i)}
+ className={`flex items-start gap-2 min-h-[44px] px-3 py-2 rounded-xl text-left border transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-400 ${
+ chosen
+ ? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-100'
+ : open
+ ? 'bg-zinc-800/80 border-zinc-700 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600 active:scale-[0.98] disabled:opacity-60'
+ : 'bg-zinc-900 border-zinc-800 text-zinc-500'
+ }`}
+ >
+ <span className="mt-0.5 w-[13px] shrink-0" aria-hidden="true">
+ {busy === o.key ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" /> : chosen ? <Check size={13} /> : null}
+ </span>
+ <span className="min-w-0">
+ <span className="block text-sm font-medium break-words">{o.label}</span>
+ {o.sub && <span className={`block text-[11px] break-words ${chosen ? 'text-emerald-200/80' : 'text-zinc-400'}`}>{o.sub}</span>}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="px-4 pb-3 text-[11px]" role="status">
+ {status}
+ </div>
+ {error && (
+ <p role="alert" className="px-4 pb-3 -mt-1 text-[11px] text-rose-400 break-words">
+ {error}
+ </p>
+ )}
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 0fd9e190..7f4286a4 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -33,6 +33,9 @@ export interface Kwant {
/** Its own approvals setting, and what it comes to with the space's; absent on older servers. */
approvals?: 'inherit' | 'ask' | 'smart' | 'off';
approvals_effective?: 'ask' | 'smart' | 'off';
+ /** "Good for" / "Not for" phrases routing reads; absent on older servers. */
+ covers?: string[];
+ avoids?: string[];
}
export interface Channel {
diff --git a/frontend/src/components/TagListInput.tsx b/frontend/src/components/TagListInput.tsx
new file mode 100644
index 00000000..ab9db138
--- /dev/null
+++ b/frontend/src/components/TagListInput.tsx
@@ -0,0 +1,79 @@
+import React, { useId, useState } from 'react';
+import { X } from 'lucide-react';
+import { MAX_TAGS, addTags } from '../tagList';
+
+/** A list of short phrases: type and press Enter (or a comma) to add one, × or Backspace to remove. */
+export const TagListInput: React.FC<{
+ label: string;
+ hint: string;
+ placeholder: string;
+ value: string[];
+ onChange: (next: string[]) => void;
+ tone?: 'good' | 'bad';
+}> = ({ label, hint, placeholder, value, onChange, tone = 'good' }) => {
+ const id = useId();
+ const [draft, setDraft] = useState('');
+ const [error, setError] = useState<string | null>(null);
+ const chip = tone === 'good' ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-100' : 'border-amber-500/30 bg-amber-500/10 text-amber-100';
+
+ const commit = () => {
+ if (!draft.trim()) return;
+ const r = addTags(value, draft);
+ setError(r.error);
+ if (r.list.length !== value.length) onChange(r.list);
+ if (!r.error) setDraft('');
+ };
+
+ return (
+ <div>
+ <label htmlFor={id} className="block text-xs font-medium text-zinc-400 mb-1">
+ {label} <span className="text-zinc-600 font-normal">· {hint}</span>
+ </label>
+ <div className="flex flex-wrap items-center gap-1.5 w-full bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 focus-within:border-sky-500 transition-colors">
+ {value.map((t) => (
+ <span key={t} className={`inline-flex items-center gap-1 max-w-full rounded-md border pl-2 pr-0.5 text-[11px] ${chip}`}>
+ <span className="truncate">{t}</span>
+ <button
+ type="button"
+ onClick={() => onChange(value.filter((x) => x !== t))}
+ aria-label={`Remove ${t}`}
+ className="p-1 rounded text-zinc-400 hover:text-zinc-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <X size={11} aria-hidden="true" />
+ </button>
+ </span>
+ ))}
+ <input
+ id={id}
+ type="text"
+ value={draft}
+ onChange={(e) => {
+ setError(null);
+ if (e.target.value.includes(',')) {
+ const r = addTags(value, e.target.value);
+ setError(r.error);
+ onChange(r.list);
+ setDraft('');
+ } else setDraft(e.target.value);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ commit();
+ } else if (e.key === 'Backspace' && !draft && value.length) onChange(value.slice(0, -1));
+ }}
+ onBlur={commit}
+ placeholder={value.length ? '' : placeholder}
+ aria-describedby={error ? `${id}-err` : undefined}
+ disabled={value.length >= MAX_TAGS && !draft}
+ className="flex-1 min-w-[8rem] bg-transparent py-0.5 text-xs text-zinc-100 placeholder-zinc-600 focus:outline-none"
+ />
+ </div>
+ {error && (
+ <p id={`${id}-err`} role="alert" className="mt-1 text-[11px] text-rose-400">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/routeChoice.ts b/frontend/src/routeChoice.ts
new file mode 100644
index 00000000..daafd466
--- /dev/null
+++ b/frontend/src/routeChoice.ts
@@ -0,0 +1,179 @@
+import { personFetch } from './auth';
+
+// The ask card (docs/channel-routing.md, "Ask band"): when a channel message is a close call between
+// two bots, the router posts a card instead of answering, and nothing runs until the person taps who
+// answers (or "Answer generally").
+
+export interface RouteChoiceBot {
+ kwant_id: string;
+ name: string;
+ title: string;
+}
+
+export interface RouteChoiceMeta {
+ route_choice_id: string;
+ channel_id: string;
+ user_message_id: string;
+ status: 'open' | 'resolved';
+ reason: string;
+ choices: RouteChoiceBot[];
+ /** Who "Answer generally" goes to; `kwant_id` is null when the Concierge doesn't exist yet. */
+ general: { label: string; name: string; kwant_id: string | null };
+ chosen_kwant_id: string | null;
+ chose_general: boolean;
+}
+
+const str = (v: unknown) => (typeof v === 'string' ? v : '');
+
+function parseBot(raw: unknown): RouteChoiceBot | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const b = raw as Record<string, unknown>;
+ return str(b.kwant_id) && str(b.name) ? { kwant_id: str(b.kwant_id), name: str(b.name), title: str(b.title) } : null;
+}
+
+/** The card's meta from a message's `meta` (JSON text or object) or a `route_choice_updated` event. */
+export function parseRouteChoiceMeta(raw: unknown): RouteChoiceMeta | null {
+ let m: unknown = raw;
+ if (typeof raw === 'string') {
+ try {
+ m = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ }
+ if (!m || typeof m !== 'object') return null;
+ const o = m as Record<string, unknown>;
+ if (o.kind !== 'route_choice' || !str(o.route_choice_id)) return null;
+ const g = (o.general && typeof o.general === 'object' ? o.general : {}) as Record<string, unknown>;
+ return {
+ route_choice_id: str(o.route_choice_id),
+ channel_id: str(o.channel_id),
+ user_message_id: str(o.user_message_id),
+ status: o.status === 'resolved' ? 'resolved' : 'open',
+ reason: str(o.reason),
+ choices: (Array.isArray(o.choices) ? o.choices : []).map(parseBot).filter((b): b is RouteChoiceBot => !!b),
+ general: { label: str(g.label) || 'Answer generally', name: str(g.name), kwant_id: str(g.kwant_id) || null },
+ chosen_kwant_id: str(o.chosen_kwant_id) || null,
+ chose_general: o.chose_general === true,
+ };
+}
+
+/** The newest state of a card: a resolved card never goes back to open. */
+export function routeChoiceView(meta: RouteChoiceMeta, live?: RouteChoiceMeta | null): RouteChoiceMeta {
+ if (!live || live.route_choice_id !== meta.route_choice_id) return meta;
+ return meta.status === 'resolved' && live.status === 'open' ? meta : live;
+}
+
+/** Keeps the newest card per id, from `route_choice_updated`. */
+export function applyRouteChoice(map: Record<string, RouteChoiceMeta>, raw: unknown): Record<string, RouteChoiceMeta> {
+ const card = parseRouteChoiceMeta(raw);
+ if (!card) return map;
+ const prev = map[card.route_choice_id];
+ return { ...map, [card.route_choice_id]: prev ? routeChoiceView(prev, card) : card };
+}
+
+/** "You picked Nutritionist." / "You asked for a general answer." once settled, else null. */
+export function routeChoiceOutcome(c: RouteChoiceMeta): string | null {
+ if (c.status !== 'resolved') return null;
+ if (c.chose_general) return c.general.name ? `You asked for a general answer, so ${c.general.name} answers.` : 'You asked for a general answer.';
+ const bot = c.choices.find((b) => b.kwant_id === c.chosen_kwant_id);
+ return bot ? `You picked ${bot.name}.` : 'Already answered.';
+}
+
+/** What "Answer generally" will do, under its button. */
+export function generalHint(c: RouteChoiceMeta): string {
+ const { name, kwant_id } = c.general;
+ if (!name) return '';
+ return kwant_id ? `${name} answers` : `Adds ${name}, a generalist, to answer`;
+}
+
+export type ResolvePick = { kwant_id: string } | { general: true };
+
+/** How a tap ended: sent, already answered (a double tap or another device), or an error to show. */
+export type ResolveResult = { kind: 'sent' } | { kind: 'already' } | { kind: 'error'; message: string };
+
+/** Turns the resolve route's reply into a result. 409 "already chosen" is not an error: the card
+ * just shows it's settled. Other 409s (no one can answer generally) and failures are shown. */
+export async function resolveResult(res: Response): Promise<ResolveResult> {
+ if (res.ok) return { kind: 'sent' };
+ let message = '';
+ try {
+ const body = await res.json();
+ if (body && typeof body.error === 'string') message = body.error;
+ } catch {
+ // not JSON
+ }
+ if (res.status === 409 && (!message || /already/i.test(message))) return { kind: 'already' };
+ if (res.status === 409) return { kind: 'error', message: sentence(message) };
+ if (res.status === 401) return { kind: 'error', message: 'Enter your access token, then tap again.' };
+ if (res.status === 403) return { kind: 'error', message: 'Only you can choose who answers.' };
+ if (res.status === 404) return { kind: 'error', message: 'This choice is gone. Send your message again.' };
+ return { kind: 'error', message: message ? sentence(message) : `Couldn’t send your choice (HTTP ${res.status}).` };
+}
+
+const sentence = (s: string) => {
+ const t = s.trim();
+ return t ? `${t[0].toUpperCase()}${t.slice(1)}${/[.!?]$/.test(t) ? '' : '.'}` : t;
+};
+
+export async function resolveRouteChoice(id: string, pick: ResolvePick): Promise<ResolveResult> {
+ try {
+ const res = await personFetch(`/api/route-choices/${encodeURIComponent(id)}/resolve`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(pick),
+ });
+ return await resolveResult(res);
+ } catch {
+ return { kind: 'error', message: 'Could not reach the server.' };
+ }
+}
+
+/** `/api/chat/send` answered "asking": a card is waiting for the person, and no reply is coming. */
+export function isAskingReply(body: unknown): body is { status: 'asking'; route_choice_id: string; card_message_id?: string; user_message_id?: string } {
+ return !!body && typeof body === 'object' && (body as { status?: unknown }).status === 'asking';
+}
+
+/** For each bot reply, the person's latest saved channel message before it: the message "Wrong bot?"
+ * resends. Replies don't carry the message id they answer, so this is the nearest earlier one.
+ * Optimistic messages (temp ids) aren't saved yet and can't be corrected. */
+export function questionsOfReplies<M extends { id: string; sender_role: string; thread_id?: string | null }>(messages: M[]): Map<string, M> {
+ const out = new Map<string, M>();
+ let last: M | null = null;
+ for (const m of messages) {
+ if (m.sender_role === 'user') last = m.id.startsWith('temp') || m.thread_id ? null : m;
+ else if (m.sender_role === 'kwant' && last) out.set(m.id, last);
+ }
+ return out;
+}
+
+/** The bots "Wrong bot?" can send to: those that answer in the channel (every bot in #general, else
+ * the members and lead), minus the Concierge, which the server won't take as a correction. */
+export function rerouteTargetsFor<K extends { id: string; name: string; title: string }>(
+ channel: { name: string; lead_kwant_id: string; member_kwants: string[] } | null | undefined,
+ kwants: K[],
+): Array<{ id: string; name: string; title: string }> {
+ if (!channel) return [];
+ const ids = channel.name === 'general' ? null : new Set([channel.lead_kwant_id, ...channel.member_kwants]);
+ return kwants
+ .filter((k) => (ids ? ids.has(k.id) : true) && k.name !== 'Concierge')
+ .map((k) => ({ id: k.id, name: k.name, title: k.title }));
+}
+
+/** "This should have gone to X": teaches routing. Returns an error sentence, or null when learned. */
+export async function correctRoute(messageId: string, kwantId: string): Promise<string | null> {
+ try {
+ const res = await personFetch('/api/route-corrections', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ message_id: messageId, kwant_id: kwantId }),
+ });
+ if (res.ok) return null;
+ const body = await res.json().catch(() => null);
+ const msg = body && typeof body.error === 'string' ? body.error : '';
+ if (res.status === 403) return 'Only you can change who answers.';
+ return msg ? sentence(msg) : `Couldn’t change who answers (HTTP ${res.status}).`;
+ } catch {
+ return 'Could not reach the server.';
+ }
+}
diff --git a/frontend/src/routeReason.ts b/frontend/src/routeReason.ts
index 0efcbfd5..ebccf811 100644
--- a/frontend/src/routeReason.ts
+++ b/frontend/src/routeReason.ts
@@ -1,7 +1,20 @@
// The line under "Sending your question to X" on Laya's routing card: why that bot, in words that
// match how it was actually picked.
-export type RouteBasis = 'skills' | 'lead' | 'keywords' | 'only' | 'several' | 'discuss' | 'team' | 'asked' | 'last';
+export type RouteBasis =
+ | 'skills'
+ | 'lead'
+ | 'keywords'
+ | 'only'
+ | 'several'
+ | 'discuss'
+ | 'team'
+ | 'asked'
+ | 'last'
+ | 'concierge'
+ | 'ask'
+ | 'handback'
+ | 'learned';
export interface RouteReasonInput {
kwantName?: string;
@@ -9,6 +22,29 @@ export interface RouteReasonInput {
basis?: string;
fallback?: boolean;
matchedTerms?: string[];
+ /** Basis "handback": the name of the bot that said it wasn't their area. */
+ handedBackBy?: string;
+}
+
+/** "Lin handed this back (…), so Ada takes it": the server's handback sentence starts with the name. */
+const handbackName = (reason?: string) => reason?.match(/^(\S+) handed this back\b/)?.[1];
+
+/** The fixed line for the router's newer picks (Concierge, ask card, hand-back, learned), or null for
+ * any other basis. These always use the app's own wording, never the server's longer sentence. */
+export function pickedLine(r: RouteReasonInput): string | null {
+ const name = r.kwantName || 'another bot';
+ switch (r.basis) {
+ case 'concierge':
+ return 'No specialist fits, answering generally.';
+ case 'ask':
+ return `You picked ${name}.`;
+ case 'handback':
+ return `${r.handedBackBy || handbackName(r.reason) || 'The first bot'} said it’s not their area, so ${name} took it.`;
+ case 'learned':
+ return `You sent a message like this to ${name} before.`;
+ default:
+ return null;
+ }
}
/** True when the server wrote its own sentence for this pick. Older servers say "Laya picked …" for
@@ -20,6 +56,8 @@ export function serverReason(r: { reason?: string; basis?: string }): string | n
}
export function routeReasonText(r: RouteReasonInput): string | null {
+ const picked = pickedLine(r);
+ if (picked) return picked;
const own = serverReason(r);
if (own) return own;
const name = r.kwantName || 'the team lead';
diff --git a/frontend/src/spaces.ts b/frontend/src/spaces.ts
index a915f3d0..d8ad411f 100644
--- a/frontend/src/spaces.ts
+++ b/frontend/src/spaces.ts
@@ -2,7 +2,7 @@
// `/api` call as `?space=` (added by the fetch wrapper in auth.ts) and on the event stream.
import { parseView, viewSegment, type SpaceView } from './nav';
-import { serverReason } from './routeReason';
+import { pickedLine, serverReason } from './routeReason';
export interface SpaceCounts {
bots: number;
@@ -276,8 +276,16 @@ export interface RoutingMeta {
candidate_count?: number | null;
fallback?: boolean;
matched_terms?: string[];
- /** How the bot was picked: skills, keywords, only, lead, several or discuss; see routeReason.ts. */
+ /** How the bot was picked: skills, keywords, only, lead, several, discuss, concierge, ask, handback or learned; see routeReason.ts. */
basis?: string;
+ /** How well the pick fits, 0–1; absent on older messages. */
+ fit?: number;
+ /** Basis "ask": the card the person answered. */
+ route_choice_id?: string;
+ /** Basis "handback": the id of the bot that said "not my area". */
+ handed_back_by?: string;
+ /** Basis "concierge": the person's similar earlier requests (message ids). */
+ similar_requests?: string[];
}
export function parseRoutingMeta(meta: string | null | undefined): RoutingMeta | null {
@@ -291,7 +299,14 @@ export function parseRoutingMeta(meta: string | null | undefined): RoutingMeta |
}
/** The server's own reason when it sends one, else "Laya picked Lin from 6 bots in Work · matched 'migration', 'SQLite'", or the keyword-fallback line. */
-export function routingLine(r: RoutingMeta, spaceName: string): string {
+export function routingLine(r: RoutingMeta, spaceName: string, nameOf?: (kwantId: string) => string | undefined): string {
+ const picked = pickedLine({
+ kwantName: r.kwant_name,
+ basis: r.basis,
+ reason: r.reason,
+ handedBackBy: r.handed_back_by ? nameOf?.(r.handed_back_by) : undefined,
+ });
+ if (picked) return picked;
const n = typeof r.candidate_count === 'number' && r.candidate_count > 0 ? r.candidate_count : null;
const pool = n ? `from ${n} ${n === 1 ? 'bot' : 'bots'} in ${spaceName}` : `in ${spaceName}`;
const own = serverReason(r);
diff --git a/frontend/src/tagList.ts b/frontend/src/tagList.ts
new file mode 100644
index 00000000..6d0ae28f
--- /dev/null
+++ b/frontend/src/tagList.ts
@@ -0,0 +1,26 @@
+// "Good for" / "Not for" on a bot (covers / avoids): short phrases routing reads. Same rules as the
+// server (PUT /api/kwants/:id): trimmed, duplicates dropped ignoring case, at most 20 of 60 chars.
+
+export const MAX_TAGS = 20;
+export const MAX_TAG_CHARS = 60;
+
+/** Adds what was typed (commas split it) to `list`, keeping the server's rules. */
+export function addTags(list: string[], typed: string): { list: string[]; error: string | null } {
+ const out = [...list];
+ let error: string | null = null;
+ for (const raw of typed.split(',')) {
+ const t = raw.trim().replace(/\s+/g, ' ');
+ if (!t) continue;
+ if (t.length > MAX_TAG_CHARS) {
+ error = `Keep each one under ${MAX_TAG_CHARS} characters.`;
+ continue;
+ }
+ if (out.some((x) => x.toLowerCase() === t.toLowerCase())) continue;
+ if (out.length >= MAX_TAGS) {
+ error = `Up to ${MAX_TAGS}. Remove one to add another.`;
+ break;
+ }
+ out.push(t);
+ }
+ return { list: out, error };
+}
diff --git a/frontend/tests/routerUi.test.mjs b/frontend/tests/routerUi.test.mjs
new file mode 100644
index 00000000..956d6890
--- /dev/null
+++ b/frontend/tests/routerUi.test.mjs
@@ -0,0 +1,228 @@
+// The router UI on top of Lin's #197/#198/#200 (router-concierge/contract.md): plain reasons for the
+// new bases, Laya's "Who should answer this?" card (open, settled, double tap), "Wrong bot?", covers /
+// avoids in bot settings, and a "repeated" hire card that quotes the requests it rests on.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+globalThis.IS_REACT_ACT_ENVIRONMENT = false;
+
+const m = await loadBundled(`
+ export { routeReasonText } from './src/routeReason';
+ export { routingLine } from './src/spaces';
+ export * from './src/routeChoice';
+ export { addTags } from './src/tagList';
+ export { parseHireMeta, evidenceText } from './src/botActions';
+`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { flushSync } from 'react-dom';
+ import { RouteChoiceCard } from './src/components/RouteChoiceCard';
+ import { HireCard } from './src/components/HireCard';
+ export { createRoot } from 'react-dom/client';
+ export { React, flushSync, RouteChoiceCard, HireCard };
+`);
+
+const mount = (Comp, props) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = ui.createRoot(host);
+ const render = (p) => ui.flushSync(() => root.render(ui.React.createElement(Comp, p)));
+ render(props);
+ return { host, render, unmount: () => (root.unmount(), host.remove()) };
+};
+const tick = () => new Promise((r) => setTimeout(r, 0));
+const click = async (el) => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await tick();
+ await tick();
+};
+
+test('reasons: the four new bases read as one plain sentence, never a weak-match explanation', () => {
+ const server = 'Laya picked Nutritionist (Diet) as the best fit, though only weakly (fit 0.41)';
+ assert.equal(m.routeReasonText({ kwantName: 'Concierge', basis: 'concierge', reason: server }), 'No specialist fits, answering generally.');
+ assert.equal(m.routeReasonText({ kwantName: 'Nutritionist', basis: 'ask', reason: 'You chose Nutritionist (Diet) for this' }), 'You picked Nutritionist.');
+ assert.equal(
+ m.routeReasonText({ kwantName: 'Chef', basis: 'handback', reason: 'Atlas handed this back ("not SEO"), so Chef (Cook) takes it' }),
+ 'Atlas said it’s not their area, so Chef took it.',
+ );
+ assert.equal(m.routeReasonText({ kwantName: 'Chef', basis: 'learned', reason: server }), 'You sent a message like this to Chef before.');
+ for (const basis of ['concierge', 'ask', 'handback', 'learned']) {
+ assert.doesNotMatch(m.routeReasonText({ kwantName: 'X', basis, reason: server }), /weak|fit \d|0\.4|best fit/i, basis);
+ }
+});
+
+test('reasons: the routing line uses the same words, naming who handed it back from the id', () => {
+ const names = { k1: 'Atlas' };
+ const line = (r) => m.routingLine(r, 'Home', (id) => names[id]);
+ assert.equal(line({ kwant_name: 'Concierge', basis: 'concierge', reason: 'x', candidate_count: 4 }), 'No specialist fits, answering generally.');
+ assert.equal(line({ kwant_name: 'Chef', basis: 'handback', handed_back_by: 'k1', reason: 'k1 handed this back', candidate_count: 4 }), 'Atlas said it’s not their area, so Chef took it.');
+ assert.equal(line({ kwant_name: 'Chef', basis: 'learned', reason: 'x', candidate_count: 4 }), 'You sent a message like this to Chef before.');
+ assert.equal(line({ kwant_name: 'Chef', basis: 'ask', reason: 'x', candidate_count: 4 }), 'You picked Chef.');
+});
+
+const card = (over = {}) => ({
+ kind: 'route_choice',
+ route_choice_id: 'rc1',
+ channel_id: 'c1',
+ user_message_id: 'u1',
+ status: 'open',
+ reason: 'Close call between Nutritionist and Chef',
+ choices: [
+ { kwant_id: 'n', name: 'Nutritionist', title: 'Diet and meal plans' },
+ { kwant_id: 'c', name: 'Chef', title: 'Recipes' },
+ ],
+ general: { label: 'Answer generally', name: 'Concierge', kwant_id: 'g' },
+ chosen_kwant_id: null,
+ chose_general: false,
+ ...over,
+});
+
+test('ask card: parse, live updates never reopen a settled card', () => {
+ const open = m.parseRouteChoiceMeta(JSON.stringify(card()));
+ assert.equal(open.status, 'open');
+ assert.equal(m.parseRouteChoiceMeta({ kind: 'hire_proposal' }), null);
+ assert.equal(m.parseRouteChoiceMeta(card({ general: { name: 'Concierge', kwant_id: null } })).general.label, 'Answer generally');
+ const settled = m.parseRouteChoiceMeta(card({ status: 'resolved', chosen_kwant_id: 'c' }));
+ assert.equal(m.routeChoiceView(open, settled).status, 'resolved');
+ assert.equal(m.routeChoiceView(settled, open).status, 'resolved', 'a late "open" event does not reopen it');
+ let map = m.applyRouteChoice({}, card({ status: 'resolved', chose_general: true }));
+ map = m.applyRouteChoice(map, card());
+ assert.equal(map.rc1.status, 'resolved');
+ assert.equal(m.routeChoiceOutcome(map.rc1), 'You asked for a general answer, so Concierge answers.');
+ assert.equal(m.generalHint(m.parseRouteChoiceMeta(card({ general: { name: 'Concierge', kwant_id: null } }))), 'Adds Concierge, a generalist, to answer');
+});
+
+test('ask card: open shows two bots and "Answer generally"; a tap posts the pick and settles', async () => {
+ const picks = [];
+ const meta = m.parseRouteChoiceMeta(card());
+ const props = { meta, messageId: 'm1', question: 'What should I eat before a run?', onResolve: async (id, pick) => (picks.push([id, pick]), { kind: 'sent' }) };
+ const { host, render, unmount } = mount(ui.RouteChoiceCard, props);
+ const section = host.querySelector('[data-route-choice]');
+ assert.equal(section.dataset.routeChoice, 'open');
+ assert.match(host.textContent, /Who should answer this\?/);
+ assert.match(host.textContent, /“What should I eat before a run\?”/);
+ const buttons = [...host.querySelectorAll('[role=group] button')];
+ assert.deepEqual(buttons.map((b) => b.querySelector('.font-medium').textContent), ['Nutritionist', 'Chef', 'Answer generally']);
+ assert.ok(buttons.every((b) => !b.disabled && b.getAttribute('aria-pressed') === 'false'));
+ assert.match(host.querySelector('[role=status]').textContent, /Nothing is answered until you choose/);
+
+ await click(buttons[1]);
+ assert.deepEqual(picks, [['rc1', { kwant_id: 'c' }]]);
+ assert.match(host.querySelector('[role=status]').textContent, /Sent\. Chef is answering\./);
+ assert.ok([...host.querySelectorAll('[role=group] button')].every((b) => b.disabled), 'no second pick');
+
+ // route_choice_updated confirms it: the card shows the resolved state.
+ render({ ...props, live: m.parseRouteChoiceMeta(card({ status: 'resolved', chosen_kwant_id: 'c' })) });
+ assert.equal(host.querySelector('[data-route-choice]').dataset.routeChoice, 'resolved');
+ assert.match(host.querySelector('[role=status]').textContent, /You picked Chef\./);
+ assert.equal(host.querySelectorAll('[aria-pressed=true]').length, 1);
+ assert.match(host.querySelector('[aria-pressed=true]').textContent, /Chef/);
+ unmount();
+});
+
+test('ask card: a card that loads resolved shows the pick with every button off', () => {
+ const meta = m.parseRouteChoiceMeta(card({ status: 'resolved', chose_general: true }));
+ const { host, unmount } = mount(ui.RouteChoiceCard, { meta, messageId: 'm2', onResolve: async () => assert.fail('no tap') });
+ assert.equal(host.querySelector('[data-route-choice]').dataset.routeChoice, 'resolved');
+ assert.match(host.textContent, /You asked for a general answer, so Concierge answers\./);
+ assert.ok([...host.querySelectorAll('[role=group] button')].every((b) => b.disabled));
+ assert.match(host.querySelector('[aria-pressed=true]').textContent, /Answer generally/);
+ unmount();
+});
+
+test('ask card: 409 "already chosen" is not an error; other failures are shown and can be retried', async () => {
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+ assert.deepEqual(await m.resolveResult(json(409, { error: 'already chosen' })), { kind: 'already' });
+ assert.deepEqual(await m.resolveResult(json(409, { error: 'no one here can answer generally' })), { kind: 'error', message: 'No one here can answer generally.' });
+ assert.deepEqual(await m.resolveResult(json(404, { error: 'no such choice' })), { kind: 'error', message: 'This choice is gone. Send your message again.' });
+ assert.deepEqual(await m.resolveResult(json(200, { status: 'resolved' })), { kind: 'sent' });
+
+ const meta = m.parseRouteChoiceMeta(card());
+ const already = mount(ui.RouteChoiceCard, { meta, messageId: 'm3', onResolve: async () => ({ kind: 'already' }) });
+ await click(already.host.querySelector('[role=group] button'));
+ assert.match(already.host.querySelector('[role=status]').textContent, /Already answered\./);
+ assert.equal(already.host.querySelector('[role=alert]'), null, 'no error for a double tap');
+ assert.ok([...already.host.querySelectorAll('[role=group] button')].every((b) => b.disabled));
+ already.unmount();
+
+ const failing = mount(ui.RouteChoiceCard, { meta, messageId: 'm4', onResolve: async () => ({ kind: 'error', message: 'Could not reach the server.' }) });
+ await click(failing.host.querySelectorAll('[role=group] button')[2]);
+ assert.match(failing.host.querySelector('[role=alert]').textContent, /Could not reach the server/);
+ assert.ok([...failing.host.querySelectorAll('[role=group] button')].every((b) => !b.disabled), 'still open to try again');
+ failing.unmount();
+});
+
+test('send: "asking" means a card is waiting, not an error', () => {
+ assert.equal(m.isAskingReply({ status: 'asking', route_choice_id: 'rc1' }), true);
+ assert.equal(m.isAskingReply({ status: 'started' }), false);
+ assert.equal(m.isAskingReply(null), false);
+});
+
+test('wrong bot: each reply resends the person\'s latest saved message before it, not thread or unsaved ones', () => {
+ const q = m.questionsOfReplies([
+ { id: 'u1', sender_role: 'user', text: 'corn dog recipe' },
+ { id: 'r1', sender_role: 'kwant' },
+ { id: 's1', sender_role: 'system' },
+ { id: 'r2', sender_role: 'kwant' },
+ { id: 'u2', sender_role: 'user', thread_id: 't1' },
+ { id: 'r3', sender_role: 'kwant' },
+ { id: 'temp-1', sender_role: 'user' },
+ { id: 'r4', sender_role: 'kwant' },
+ ]);
+ assert.equal(q.get('r1').id, 'u1');
+ assert.equal(q.get('r2').id, 'u1');
+ assert.equal(q.has('r3'), false);
+ assert.equal(q.has('r4'), false);
+
+ const kwants = [
+ { id: 'a', name: 'Atlas', title: 'SEO' },
+ { id: 'b', name: 'Chef', title: 'Recipes' },
+ { id: 'g', name: 'Concierge', title: 'Everyday questions' },
+ ];
+ assert.deepEqual(m.rerouteTargetsFor({ name: 'general', lead_kwant_id: 'a', member_kwants: [] }, kwants).map((k) => k.name), ['Atlas', 'Chef']);
+ assert.deepEqual(m.rerouteTargetsFor({ name: 'seo', lead_kwant_id: 'a', member_kwants: [] }, kwants).map((k) => k.name), ['Atlas']);
+ assert.deepEqual(m.rerouteTargetsFor(null, kwants), []);
+});
+
+test('covers / avoids: trimmed, case-insensitive duplicates dropped, at most 20 of 60 characters', () => {
+ assert.deepEqual(m.addTags(['Taxes'], ' invoices , taxes, VAT returns ').list, ['Taxes', 'invoices', 'VAT returns']);
+ assert.match(m.addTags([], 'x'.repeat(61)).error, /60 characters/);
+ const full = Array.from({ length: 20 }, (_, i) => `t${i}`);
+ const r = m.addTags(full, 'one more');
+ assert.equal(r.list.length, 20);
+ assert.match(r.error, /Up to 20/);
+});
+
+test('hire card: "repeated" reads the server\'s {message_id, at, text} and quotes the three requests', () => {
+ const meta = m.parseHireMeta({
+ kind: 'hire_proposal', hire_id: 'h1', name: 'FoodGuide', role: 'Local food guide', reason: 'Street food keeps coming up.',
+ status: 'pending', requested_by_person: false,
+ evidence: {
+ basis: 'repeated',
+ similar_requests: [
+ { message_id: 'm1', at: '2026-10-28T09:00:00Z', text: 'Where is the best street food in Munich?' },
+ { message_id: 'm2', at: '2026-10-30T09:00:00Z', text: 'Good street food markets in Munich?' },
+ { message_id: 'm3', at: '2026-11-01T09:00:00Z', text: 'Best street food stalls in Munich this weekend?' },
+ ],
+ },
+ });
+ assert.equal(meta.evidence.similar_requests.length, 3);
+ assert.equal(m.evidenceText(meta.evidence, false), 'You asked for this kind of work 3 times in this space.');
+ assert.equal(m.parseHireMeta({ ...meta, kind: 'hire_proposal', evidence: { basis: 'repeated', similar_requests: ['a', 'b'] } }).evidence.similar_requests.length, 2, 'older cards with bare ids');
+
+ const { host, unmount } = mount(ui.HireCard, { meta, messageId: 'hm', kwantName: 'Concierge', onDecide: async () => {} });
+ const list = host.querySelector('[aria-label="Your earlier requests"]');
+ assert.ok(list, 'the requests are listed');
+ const items = [...list.querySelectorAll('li')].map((li) => li.textContent);
+ assert.equal(items.length, 3);
+ assert.match(items[0], /Where is the best street food in Munich\?/);
+ assert.match(items[2], /Nov 1|1 Nov/);
+ unmount();
+});
diff --git a/src/server/hires.rs b/src/server/hires.rs
index 66831b35..12e8e8dc 100644
--- a/src/server/hires.rs
+++ b/src/server/hires.rs
@@ -167,7 +167,9 @@ async fn check_evidence(state: &AppState, space: &SpaceId, raw: &Value) -> Resul
match state.db.message_space_and_sender(id).await {
Ok(Some((s, role))) if &s == space && role == "user" => {
let at = state.db.message_created_at(id).await.ok().flatten();
- found.push(json!({"message_id": id, "at": at}));
+ // The card quotes them, so the person sees what the proposal rests on.
+ let text = state.db.get_message(id).await.ok().flatten().map(|m| quote(&m.text));
+ found.push(json!({"message_id": id, "at": at, "text": text}));
}
Ok(Some((s, _))) if &s == space => {
return Err(format!("Message {id} isn't a request from the person; give the person's own messages."))
@@ -1015,3 +1017,13 @@ pub async fn put_policy(State(state): State<AppState>, headers: HeaderMap, Path(
Err(r) => r,
}
}
+
+/// One past request for the hire card: first line-ish, at most 160 characters.
+fn quote(text: &str) -> String {
+ let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ if flat.chars().count() <= 160 {
+ return flat;
+ }
+ let cut: String = flat.chars().take(159).collect();
+ format!("{}…", cut.trim_end())
+}
diff --git a/tests/concierge_test.rs b/tests/concierge_test.rs
index d56005bd..684d4d89 100644
--- a/tests/concierge_test.rs
+++ b/tests/concierge_test.rs
@@ -525,6 +525,11 @@ async fn the_concierge_suggests_a_hire_on_the_third_similar_request() {
assert_eq!(evidence["basis"], "repeated");
let on_card: Vec<&str> = evidence["similar_requests"].as_array().unwrap().iter().map(|r| r["message_id"].as_str().unwrap()).collect();
assert_eq!(on_card, ids.iter().map(String::as_str).collect::<Vec<_>>());
+ for r in evidence["similar_requests"].as_array().unwrap() {
+ let quoted = r["text"].as_str().unwrap_or_default();
+ assert!(!quoted.is_empty() && quoted.chars().count() <= 160, "the card quotes each past request: {r}");
+ assert!(r["at"].is_string(), "with when it was asked: {r}");
+ }
let msgs = state.db.list_messages(&general, 100).await.unwrap();
assert!(
msgs.iter().any(|m| m.meta.as_deref().is_some_and(|x| x.contains("hire_proposal") && x.contains(&card.id))),