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.

0.9.5: say in the chat when a bot's connection fails (#537)

Oleksandr Ivanchenkoe0edc3944e7c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index ddc4d597..25c64028 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -3980,6 +3980,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onOpen={openAwayItem}
onCounts={setAwayCount}
onApprovalResolved={dropApproval}
+ onOpenConnections={openConnections}
onCrumb={(c) => showPage(c === 'board' ? 'board' : 'dev')}
top={
<>
@@ -4206,6 +4207,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
renderConnectionSuggestion={renderConnectionSuggestion}
renderBotAction={renderBotAction}
onOpenToolNote={openToolNote}
+ onOpenConnections={openConnections}
renderWatchReport={renderWatchReport}
renderHire={renderHire}
renderRouteChoice={renderRouteChoice}
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index 13f6e7c5..ab34814b 100644
--- a/frontend/src/away.ts
+++ b/frontend/src/away.ts
@@ -1,7 +1,7 @@
// "While you were away" (batch 3): what agents need from you, finished and failed since you last
// looked. Pure helpers, so the page and the node tests share them; the API calls are at the bottom.
-export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run' | 'watch';
+export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run' | 'watch' | 'connection';
export type AwaySection = 'waiting' | 'finished' | 'failed';
export type ApprovalDecision = 'allow_once' | 'always_allow' | 'deny';
@@ -31,6 +31,11 @@ export interface AwayItem {
/** 0.9.0 P1, watch items only: the watched mission and the first task that needs the person. */
mission_id?: string | null;
task_id?: string | null;
+ /** 0.9.5, connection items only (Inbox): a sign-in only the person can redo, and its fix button. */
+ connection?: string;
+ /** "sign_in" or "reconnect" (an app to connect again); older servers may leave it out. */
+ cause?: string;
+ fix?: { label: string; opens?: string } | null;
}
export interface AwayCounts {
@@ -103,7 +108,7 @@ export function windowLabel(since: string, now: number = Date.now()): string {
export type Tone = 'amber' | 'emerald' | 'rose' | 'sky' | 'zinc';
/** Short label and colour for an item's kind and status. */
-export function itemLabel(item: Pick<AwayItem, 'kind' | 'status'>): { label: string; tone: Tone } {
+export function itemLabel(item: Pick<AwayItem, 'kind' | 'status' | 'cause'>): { label: string; tone: Tone } {
switch (item.kind) {
case 'question':
return { label: 'Question', tone: 'amber' };
@@ -112,6 +117,9 @@ export function itemLabel(item: Pick<AwayItem, 'kind' | 'status'>): { label: str
return item.status === 'waiting' ? { label: 'Still open', tone: 'sky' } : { label: 'Needs approval', tone: 'amber' };
case 'watch':
return { label: 'Watch', tone: 'amber' };
+ case 'connection':
+ // The chat line's cause: an app to connect again (Composio, no active account), else a sign-in.
+ return item.cause === 'reconnect' ? { label: 'Connect again', tone: 'amber' } : { label: 'Sign in again', tone: 'amber' };
case 'routine_run':
return item.status === 'ok' ? { label: 'Routine ran', tone: 'emerald' } : { label: 'Routine failed', tone: 'rose' };
case 'delegation':
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index a3e82024..c0ab0489 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -63,6 +63,8 @@ import { DropBot, DropLayer, DropPhase } from './DropLayer';
import { EarlierCopies, FileTiles, PointChip, UploadChip } from './Attachments';
import { arrangeSharedFiles, botDisplayName, botOf, shareInfo } from '../sharedFiles';
import { parseToolNoteMeta } from '../toolNotes';
+import { ToolFailureLine } from './ToolFailureLine';
+import { parseToolFailureMeta } from '../toolFailures';
import { ToolNoteLine } from './ToolNoteLine';
import { ranOnLabel } from '../engines';
import { replyTokens } from '../modelUsage';
@@ -303,6 +305,8 @@ export interface ChatViewProps {
renderBotAction?: (msg: ChatMessage, meta: BotActionMeta, flash: boolean) => React.ReactNode;
/** 0.9.0 P5: a bot's tool-note line (meta kind "tool_note"); "See the note" opens it on Connections. */
onOpenToolNote?: (noteId: string) => void;
+ /** 0.9.5: a connection-failure line's fix button (meta kind "tool_failure") opens Connections. */
+ onOpenConnections?: () => void;
/** A mission watcher's check report (message meta kind "watch"). */
renderWatchReport?: (msg: ChatMessage, meta: WatchMeta, flash: boolean) => React.ReactNode;
/** A bot's proposal to hire a new bot (message meta kind "hire_proposal"). */
@@ -532,6 +536,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
renderConnectionSuggestion,
renderBotAction,
onOpenToolNote,
+ onOpenConnections,
renderWatchReport,
renderHire,
renderRouteChoice,
@@ -1258,7 +1263,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
useEffect(() => onContinuity('trial_ended', (t) => setEndedTrials((prev) => (prev.has(t.skill_id) ? prev : new Set(prev).add(t.skill_id)))), []);
const trialCards = useMemo(() => trialCardsAfter(messages, endedTrials), [messages, endedTrials]);
- const renderMessage = (msg: ChatMessage) => {
+ // `prev`: the message shown just above, so a kwant line under another sits close to it (0.9.5 F5)
+ const renderMessage = (msg: ChatMessage, prev?: ChatMessage) => {
const interruption = parseInterruption(msg);
if (interruption)
return (
@@ -1318,6 +1324,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (watch && renderWatchReport) return <React.Fragment key={msg.id}>{renderWatchReport(msg, watch, flashId === msg.id)}</React.Fragment>;
const botAction = msg.meta && renderBotAction ? parseBotActionMeta(msg.meta) : null;
if (botAction && renderBotAction) return <React.Fragment key={msg.id}>{renderBotAction(msg, botAction, flashId === msg.id)}</React.Fragment>;
+ const toolFailure = msg.meta ? parseToolFailureMeta(msg.meta) : null;
+ if (toolFailure)
+ return (
+ <ToolFailureLine
+ key={msg.id}
+ meta={toolFailure}
+ messageId={msg.id}
+ flash={flashId === msg.id}
+ tight={!!prev?.meta && !!(parseToolFailureMeta(prev.meta) || parseToolNoteMeta(prev.meta))}
+ onFix={onOpenConnections}
+ />
+ );
const toolNote = msg.meta ? parseToolNoteMeta(msg.meta) : null;
if (toolNote)
return (
@@ -2037,13 +2055,15 @@ export const ChatView: React.FC<ChatViewProps> = ({
<BotHome home={home} spaceName={spaceName} team={activeKwants} prompts={suggestions} canRun={canRun} onPick={handlePromptSuggestion} />
</div>
)}
- {groupDiscussionThreads(arranged.messages).map((item) => {
+ {groupDiscussionThreads(arranged.messages).map((item, n, items) => {
if (item.kind === 'message') {
const trial = trialCards.get(item.message.id);
- if (!trial) return renderMessage(item.message);
+ const above = items[n - 1];
+ const prev = above?.kind === 'message' && !trialCards.has(above.message.id) ? above.message : undefined;
+ if (!trial) return renderMessage(item.message, prev);
return (
<Fragment key={item.message.id}>
- {renderMessage(item.message)}
+ {renderMessage(item.message, prev)}
<TrialWaitsCard key={`trial:${trial.skill_id}`} skillId={trial.skill_id} kwantId={item.message.sender_role === 'kwant' ? item.message.sender_id : (item.message.direct_kwant_id ?? item.message.sender_id)} onOpenSkills={onOpenSkills} />
</Fragment>
);
@@ -2069,7 +2089,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
</button>
{isThreadOpen && (
<div className="mt-4 ml-2 pl-3 sm:ml-[30px] sm:pl-4 border-l border-zinc-800 space-y-6">
- {item.turns.map(renderMessage)}
+ {item.turns.map((t, i, all) => renderMessage(t, all[i - 1]))}
</div>
)}
</div>
@@ -2182,7 +2202,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
{/* P4: the running bot's shares, already in the place its saved reply will give them */}
- {liveRowShown && arranged.live.map(renderMessage)}
+ {liveRowShown && arranged.live.map((m) => renderMessage(m))}
{/* Approvals allowed in Telegram (G4): "✓ Allowed once from Telegram", live and after a reload */}
{settledApprovals.map((approval) => (
diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsx
index 4e183d21..df1b0011 100644
--- a/frontend/src/components/InboxNew.tsx
+++ b/frontend/src/components/InboxNew.tsx
@@ -16,6 +16,7 @@ import {
List,
Loader2,
MinusCircle,
+ Plug,
RefreshCw,
RotateCcw,
ShieldCheck,
@@ -163,9 +164,11 @@ interface RowProps {
onPick: (i: InboxItem) => void;
onAnswer: (i: InboxItem, choice: number) => void;
onResolve: (i: InboxItem, d: ApprovalDecision) => void;
+ /** 0.9.5: a connection row's Reconnect opens Settings › Connections. */
+ onOpenConnections?: () => void;
}
-const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve }) => {
+const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve, onOpenConnections }) => {
const review = isReview(item) ? item : null;
const title = rowTitle(item);
// The server decides one_tap; an item with no verdict (Not checked yet, Being checked) never gets inline Approve.
@@ -249,6 +252,15 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o
</div>
)}
+ {item.kind === 'connection' && onOpenConnections && (
+ <div className="px-3 pb-3 pl-[54px]">
+ <button type="button" onClick={onOpenConnections} className={`${plainBtn} px-3 text-xs ${wide ? 'h-7' : 'h-11'}`} data-reconnect={item.id}>
+ <Plug size={12} aria-hidden="true" />
+ {item.fix?.label || 'Reconnect'}
+ </button>
+ </div>
+ )}
+
{busy === item.id && !review && (
<p className="px-3 pb-3 pl-[54px] inline-flex items-center gap-1.5 text-[11px] text-zinc-400">
<Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Sending…
@@ -492,6 +504,8 @@ export interface InboxNewProps {
onApprovalResolved?: (id: string) => void;
/** Phone: back to the chat list. */
onBack?: () => void;
+ /** 0.9.5: a connection row's Reconnect opens Settings › Connections. */
+ onOpenConnections?: () => void;
/** The back crumb: return to the page the item was opened from. */
onCrumb?: (c: Exclude<Crumb, null>) => void;
top?: React.ReactNode;
@@ -515,7 +529,7 @@ function writeItemParam(id: string | null) {
}, 0);
}
-export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApprovalResolved, onBack, onCrumb, top, now = Date.now(), noLoad = false, wide: forceWide }) => {
+export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApprovalResolved, onBack, onOpenConnections, onCrumb, top, now = Date.now(), noLoad = false, wide: forceWide }) => {
const st = useInbox();
const mqWide = useWide();
const wide = forceWide ?? mqWide;
@@ -734,6 +748,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
onPick={pick}
onAnswer={onAnswer}
onResolve={onResolve}
+ onOpenConnections={onOpenConnections}
/>
))}
{withBatch && <BatchCard items={bItems} selected={wide && selectedId === 'batch'} focusable={firstFocusable === 'batch'} wide={wide} onPick={() => select('batch')} />}
diff --git a/frontend/src/components/ToolFailureLine.tsx b/frontend/src/components/ToolFailureLine.tsx
new file mode 100644
index 00000000..80479395
--- /dev/null
+++ b/frontend/src/components/ToolFailureLine.tsx
@@ -0,0 +1,51 @@
+// 0.9.5: the plain line a chat shows when one of a bot's connections fails (meta kind
+// "tool_failure"): "Gmail stopped working for Ben: it needs to be connected again. Reconnect".
+// Quiet like a tool note; the fix button opens Connections. Once the connection works again the
+// line stays, says so in green with a plugged icon, and loses its button. Mira's design check
+// (release-095/tool-failure-line/design-check.md F3–F6): a needs-you line is brighter with an
+// amber button and tells a screen reader; lines of one turn sit 4 px apart; the button has a
+// 44 px hit area on a phone. That area is the invisible ::before, so the button opts out of the
+// phones' 44 px min-height (data-compact), which would make its line of text twice as tall.
+import React from 'react';
+import { Plug, Unplug } from 'lucide-react';
+import { ToolFailureMeta } from '../toolFailures';
+
+export const ToolFailureLine: React.FC<{
+ meta: ToolFailureMeta;
+ messageId?: string;
+ flash?: boolean;
+ /** The message before is also a kwant line (a tool failure or tool note): sit 4 px under it (F5). */
+ tight?: boolean;
+ onFix?: () => void;
+}> = ({ meta, messageId, flash = false, tight = false, onFix }) => {
+ const open = !meta.resolved_at;
+ const urgent = open && meta.needs_you;
+ const Icon = open ? Unplug : Plug;
+ return (
+ <div
+ data-message-id={messageId}
+ data-tool-failure-line={meta.cause}
+ className={`flex items-start gap-2 pl-11 pr-4 py-1 rounded-lg text-[12.5px] leading-snug ${urgent ? 'text-zinc-300' : 'text-zinc-400'} ${tight ? '!mt-1' : ''} ${flash ? 'bg-sky-500/10' : ''}`}
+ >
+ <Icon size={13} className={`mt-[3px] shrink-0 ${urgent ? 'text-amber-400' : 'text-zinc-500'}`} aria-hidden="true" />
+ <p className="min-w-0 break-words">
+ {urgent && <span className="sr-only">Needs you: </span>}
+ {meta.line}
+ {!open && <span className="text-emerald-400"> It works again.</span>}
+ {open && meta.fix && onFix && (
+ <>
+ {' '}
+ <button
+ type="button"
+ data-compact
+ onClick={onFix}
+ className={`relative before:absolute before:content-[''] before:-inset-x-2 before:-inset-y-[14px] font-medium ${urgent ? 'text-amber-200' : 'text-zinc-200'} underline-offset-2 hover:underline rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500`}
+ >
+ {meta.fix.label}
+ </button>
+ </>
+ )}
+ </p>
+ </div>
+ );
+};
diff --git a/frontend/src/toolFailures.ts b/frontend/src/toolFailures.ts
new file mode 100644
index 00000000..48fb0453
--- /dev/null
+++ b/frontend/src/toolFailures.ts
@@ -0,0 +1,45 @@
+// 0.9.5: the line kwnt posts in a chat when one of a bot's connections fails (meta kind
+// "tool_failure", see src/server/tool_failures.rs): "Gmail stopped working for Ben: it needs to be
+// connected again. Reconnect". One per connection per turn; nothing when a retry fixed it.
+import { parseMetaObject } from './questions';
+
+export type ToolFailureCause = 'sign_in' | 'reconnect' | 'not_started' | 'down';
+
+export interface ToolFailureMeta {
+ kind: 'tool_failure';
+ kwant_id: string | null;
+ /** The connection's name, e.g. "Gmail". */
+ connection: string;
+ cause: ToolFailureCause;
+ /** The line's words, without the fix link. */
+ line: string;
+ /** Only the person can fix it (a sign-in or a reconnect). */
+ needs_you: boolean;
+ /** Where to fix it; null for kwant's own tools. */
+ fix: { label: string; connection_id: string | null } | null;
+ /** Set once a later call through the connection worked. */
+ resolved_at: string | null;
+}
+
+const CAUSES: readonly ToolFailureCause[] = ['sign_in', 'reconnect', 'not_started', 'down'];
+const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
+
+export function parseToolFailureMeta(raw: unknown): ToolFailureMeta | null {
+ const m = parseMetaObject(raw);
+ if (!m || m.kind !== 'tool_failure') return null;
+ const line = str(m.line);
+ const connection = str(m.connection);
+ if (!line || !connection) return null;
+ const fix = m.fix && typeof m.fix === 'object' ? (m.fix as Record<string, unknown>) : null;
+ const label = fix ? str(fix.label) : null;
+ return {
+ kind: 'tool_failure',
+ kwant_id: str(m.kwant_id),
+ connection,
+ cause: CAUSES.includes(m.cause as ToolFailureCause) ? (m.cause as ToolFailureCause) : 'down',
+ line,
+ needs_you: m.needs_you === true,
+ fix: label ? { label, connection_id: str(fix?.connection_id) } : null,
+ resolved_at: str(m.resolved_at),
+ };
+}
diff --git a/frontend/tests/inboxConnection.test.mjs b/frontend/tests/inboxConnection.test.mjs
new file mode 100644
index 00000000..0a4417d1
--- /dev/null
+++ b/frontend/tests/inboxConnection.test.mjs
@@ -0,0 +1,78 @@
+// 0.9.5 F8 (release-095/tool-failure-line/design-check.md): a connection only the person can fix is a
+// Waiting-on-you row in the Inbox, "Gmail needs you to sign in again for Ben", with Reconnect.
+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', 'DOMParser', 'localStorage', 'sessionStorage', 'getComputedStyle']) {
+ if (k in dom.window) Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export * as store from './src/inboxStore';
+ export { INBOX_FIXTURE_EMPTY } from './src/api/inbox';
+ export { InboxNew } from './src/components/InboxNew';
+ export { itemLabel } from './src/away';
+`);
+const { React, store: s } = m;
+
+// Shaped like src/server/inbox.rs connection_item.
+const row = {
+ kind: 'connection', id: 'msg1', kwant_id: 'k1', kwant_name: 'Ben', title: 'Gmail needs you to sign in again for Ben', summary: '',
+ status: 'open', timestamp: '2026-11-12T18:00:00Z', link: { thread_id: null, channel_id: null, direct_kwant_id: 'k1' },
+ connection: 'Gmail', cause: 'sign_in', fix: { label: 'Reconnect', opens: 'connections', connection_id: 'mcp:s1' },
+ group: 'waiting_on_you', sort_key: [0, 0, 0, 'Ben', 'msg1'],
+};
+
+const render = (props) => {
+ const data = JSON.parse(JSON.stringify(m.INBOX_FIXTURE_EMPTY));
+ data.items = [row];
+ data.counts.waiting_on_you = 1;
+ s.inboxStore.reset();
+ s.inboxStore.patch({ data });
+ const html = m.renderToStaticMarkup(React.createElement(m.InboxNew, { noLoad: true, wide: false, onOpen: () => {}, ...props }));
+ return new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html');
+};
+
+test('a connection row says who needs what, with Reconnect, in Waiting on you', () => {
+ const d = render({ onOpenConnections: () => {} });
+ const li = d.querySelector('[data-row="msg1"]');
+ assert.ok(li, 'the row is listed');
+ assert.equal(li.getAttribute('data-group'), 'waiting_on_you');
+ assert.match(li.textContent, /Gmail needs you to sign in again for Ben/);
+ assert.match(li.textContent, /Sign in again/);
+ const btn = li.querySelector('[data-reconnect="msg1"]');
+ assert.ok(btn);
+ assert.equal(btn.textContent, 'Reconnect');
+ assert.match(btn.className, /h-11/, '44 px on a phone');
+ assert.deepEqual(m.itemLabel({ kind: 'connection', status: 'open' }), { label: 'Sign in again', tone: 'amber' });
+ assert.deepEqual(m.itemLabel({ kind: 'connection', status: 'open', cause: 'sign_in' }), { label: 'Sign in again', tone: 'amber' });
+});
+
+test('a Composio app with no active account says Connect again, still with Reconnect', () => {
+ const composio = {
+ ...row, id: 'msg2', kwant_name: 'TechLead', title: 'Google Calendar needs to be connected again for TechLead',
+ connection: 'Google Calendar', cause: 'reconnect', sort_key: [0, 0, 0, 'TechLead', 'msg2'],
+ };
+ const data = JSON.parse(JSON.stringify(m.INBOX_FIXTURE_EMPTY));
+ data.items = [composio];
+ data.counts.waiting_on_you = 1;
+ s.inboxStore.reset();
+ s.inboxStore.patch({ data });
+ const html = m.renderToStaticMarkup(React.createElement(m.InboxNew, { noLoad: true, wide: false, onOpen: () => {}, onOpenConnections: () => {} }));
+ const li = new DOMParser().parseFromString(`<body>${html}</body>`, 'text/html').querySelector('[data-row="msg2"]');
+ assert.ok(li, 'the row is listed');
+ assert.match(li.textContent, /Google Calendar needs to be connected again for TechLead/);
+ assert.match(li.textContent, /Connect again/);
+ assert.doesNotMatch(li.textContent, /Sign in again/);
+ assert.equal(li.querySelector('[data-reconnect="msg2"]').textContent, 'Reconnect');
+ assert.deepEqual(m.itemLabel({ kind: 'connection', status: 'open', cause: 'reconnect' }), { label: 'Connect again', tone: 'amber' });
+});
+
+test('without a way to open Connections there is no button', () => {
+ assert.equal(render({}).querySelector('[data-reconnect]'), null);
+});
diff --git a/frontend/tests/toolFailures.test.mjs b/frontend/tests/toolFailures.test.mjs
new file mode 100644
index 00000000..7ca901d9
--- /dev/null
+++ b/frontend/tests/toolFailures.test.mjs
@@ -0,0 +1,94 @@
+// 0.9.5: the chat line when a bot's connection fails (release-095/tool-failure-line/brief.md).
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const m = await loadBundled(`export * from './src/toolFailures';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { ToolFailureLine } from './src/components/ToolFailureLine';
+ export const line = (props) => renderToStaticMarkup(React.createElement(ToolFailureLine, props));
+`);
+
+// Shaped like the meta src/server/tool_failures.rs writes.
+const meta = (over = {}) => ({
+ kind: 'tool_failure', kwant_id: 'k1', turn_id: 't1', connection: 'Gmail', key: 'composio:gmail', server_id: 's1',
+ cause: 'reconnect', tool: 'composio · GMAIL_SEND_EMAIL', detail: 'Connected account not found',
+ line: 'Gmail stopped working for Ben: it needs to be connected again.', needs_you: true,
+ fix: { label: 'Reconnect', opens: 'connections', connection_id: 'mcp:s1' }, resolved_at: null, ...over,
+});
+
+test('the meta is read from the saved string, and defensively', () => {
+ const v = m.parseToolFailureMeta(JSON.stringify(meta()));
+ assert.equal(v.connection, 'Gmail');
+ assert.equal(v.cause, 'reconnect');
+ assert.deepEqual(v.fix, { label: 'Reconnect', connection_id: 'mcp:s1' });
+ assert.equal(v.needs_you, true);
+ assert.equal(m.parseToolFailureMeta(meta({ cause: 'weird' })).cause, 'down');
+ assert.equal(m.parseToolFailureMeta(meta({ fix: null })).fix, null);
+ assert.equal(m.parseToolFailureMeta(meta({ line: '' })), null);
+ assert.equal(m.parseToolFailureMeta({ ...meta(), kind: 'tool_note' }), null);
+ assert.equal(m.parseToolFailureMeta('not json'), null);
+});
+
+test('the line says what broke and has a fix button that opens Connections', () => {
+ const html = ui.line({ meta: m.parseToolFailureMeta(meta()), messageId: 'm1', onFix: () => {} });
+ assert.match(html, /Gmail stopped working for Ben: it needs to be connected again\./);
+ assert.match(html, /<button[^>]*>Reconnect<\/button>/);
+ assert.match(html, /data-tool-failure-line="reconnect"/);
+ assert.match(html, /text-amber-400/);
+ // F2: an MCP server that refused its sign-in says who acts.
+ const signIn = meta({ connection: 'Notion', key: 'mcp:s1', cause: 'sign_in', tool: 'Notion · search', detail: '401 Unauthorized', line: 'Notion stopped working for Ben: it needs you to sign in again.' });
+ const html2 = ui.line({ meta: m.parseToolFailureMeta(signIn), messageId: 'm2', onFix: () => {} });
+ assert.match(html2, /Notion stopped working for Ben: it needs you to sign in again\./);
+ assert.match(html2, /data-tool-failure-line="sign_in"/);
+ assert.match(html2, /<button[^>]*>Reconnect<\/button>/);
+});
+
+test('F3: a needs-you line is brighter, its button amber, and a screen reader hears "Needs you"', () => {
+ const urgent = ui.line({ meta: m.parseToolFailureMeta(meta()), onFix: () => {} });
+ assert.match(urgent, /^<div[^>]*text-zinc-300/);
+ assert.match(urgent, /<p[^>]*><span class="sr-only">Needs you: <\/span>Gmail stopped/);
+ assert.match(urgent, /<button[^>]*text-amber-200[^>]*>Reconnect<\/button>/);
+ assert.match(urgent, /<button[^>]*font-medium/);
+ assert.match(urgent, /<button[^>]*focus-visible:outline-sky-500/);
+ const grey = ui.line({
+ meta: m.parseToolFailureMeta(meta({ cause: 'down', needs_you: false, fix: { label: 'Check it', connection_id: 'mcp:s1' }, line: 'GitHub stopped responding for Ben.' })),
+ onFix: () => {},
+ });
+ assert.match(grey, /^<div[^>]*text-zinc-400/);
+ assert.doesNotMatch(grey, /sr-only|text-amber/);
+ assert.match(grey, /<button[^>]*text-zinc-200[^>]*>Check it<\/button>/);
+});
+
+test('F4: a resolved line ends in a green "It works again." with a plugged icon, never amber', () => {
+ const fixed = ui.line({ meta: m.parseToolFailureMeta(meta({ resolved_at: '2026-11-12T18:00:00Z' })), onFix: () => {} });
+ assert.match(fixed, /^<div[^>]*text-zinc-400/);
+ assert.match(fixed, /<span class="text-emerald-400"> It works again\.<\/span>/);
+ assert.match(fixed, /lucide-plug[^-]/);
+ assert.doesNotMatch(fixed, /lucide-unplug/);
+ assert.match(fixed, /<svg[^>]*text-zinc-500/);
+ assert.doesNotMatch(fixed, /amber|sr-only/);
+});
+
+test('F5 and F6: a line under another sits 4 px close; the button has an invisible 44 px hit area', () => {
+ const props = { meta: m.parseToolFailureMeta(meta()), onFix: () => {} };
+ assert.match(ui.line({ ...props, tight: true }), /^<div[^>]*!mt-1/);
+ assert.doesNotMatch(ui.line(props), /!mt-1/);
+ assert.match(ui.line(props), /<button[^>]*relative before:absolute before:content-\[(?:''|&#x27;&#x27;)\] before:-inset-x-2 before:-inset-y-\[14px\]/);
+ // The phones' 44 px min-height would make the button's line of text twice as tall: it opts out
+ assert.match(ui.line(props), /<button[^>]*data-compact/);
+});
+
+test('no button without a place to fix it; a fixed connection says it works again', () => {
+ const own = m.parseToolFailureMeta(meta({ connection: 'kwant’s own tools', cause: 'down', fix: null, needs_you: false, line: 'kwant’s own tools stopped responding for Ben.' }));
+ assert.doesNotMatch(ui.line({ meta: own, onFix: () => {} }), /<button/);
+ assert.doesNotMatch(ui.line({ meta: m.parseToolFailureMeta(meta()) }), /<button/, 'no handler, no button');
+ const fixed = ui.line({ meta: m.parseToolFailureMeta(meta({ resolved_at: '2026-11-12T18:00:00Z' })), onFix: () => {} });
+ assert.match(fixed, /It works again\./);
+ assert.doesNotMatch(fixed, /<button/);
+ assert.doesNotMatch(fixed, /text-amber-400/);
+});
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 608b34e0..8bc5dca8 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -3,6 +3,7 @@ pub mod profiles;
pub mod browser_sites;
pub mod continuity;
pub mod threads;
+pub mod tool_failures;
pub mod zombie;
pub mod parallel;
pub mod documents;
@@ -229,6 +230,8 @@ impl Database {
db.migrate_tool_notes().await?;
// 0.9.0 P1: mission watches and their checks (add-only)
db.migrate_mission_watch().await?;
+ // 0.9.5: an index for the chat's connection-failure lines (add-only)
+ db.migrate_tool_failures().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/db/tool_failures.rs b/src/db/tool_failures.rs
new file mode 100644
index 00000000..36b1d3d4
--- /dev/null
+++ b/src/db/tool_failures.rs
@@ -0,0 +1,59 @@
+//! 0.9.5: the chat lines kwnt posts when a bot's connection fails (`server::tool_failures`).
+//! They are ordinary messages with `meta.kind = "tool_failure"`; this adds one index so "Needs
+//! you" can find the open ones without scanning every message, and the reads it needs.
+
+use super::{Database, DbError};
+use crate::db::models::Message;
+
+/// The meta kind of a failure line (`server::tool_failures::KIND`).
+pub const KIND: &str = "tool_failure";
+/// Most failure lines one read returns, newest first.
+pub const MAX_LINES: i64 = 200;
+
+impl Database {
+ /// Additive: an index on the meta kind of messages kwnt writes itself. An old binary ignores it.
+ pub(super) async fn migrate_tool_failures(&self) -> Result<(), DbError> {
+ sqlx::query(
+ "CREATE INDEX IF NOT EXISTS messages_by_meta_kind ON messages (json_extract(meta, '$.kind'), created_at) \
+ WHERE meta IS NOT NULL AND json_valid(meta)",
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ /// The newest failure lines (at most [`MAX_LINES`]), newest first.
+ pub async fn list_tool_failure_lines(&self) -> Result<Vec<Message>, DbError> {
+ Ok(sqlx::query_as::<_, Message>(
+ "SELECT * FROM messages WHERE meta IS NOT NULL AND json_valid(meta) AND json_extract(meta, '$.kind') = ? \
+ ORDER BY created_at DESC LIMIT ?",
+ )
+ .bind(KIND)
+ .bind(MAX_LINES)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The read uses the index rather than scanning all messages.
+ #[tokio::test]
+ async fn failure_lines_use_the_meta_kind_index() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let plan: Vec<(i64, i64, i64, String)> = sqlx::query_as(
+ "EXPLAIN QUERY PLAN SELECT * FROM messages WHERE meta IS NOT NULL AND json_valid(meta) AND json_extract(meta, '$.kind') = ? \
+ ORDER BY created_at DESC LIMIT ?",
+ )
+ .bind(KIND)
+ .bind(MAX_LINES)
+ .fetch_all(&db.pool)
+ .await
+ .unwrap();
+ let detail: Vec<&str> = plan.iter().map(|p| p.3.as_str()).collect();
+ assert!(detail.iter().any(|d| d.contains("messages_by_meta_kind")), "index unused: {detail:?}");
+ }
+}
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index e1688229..ef2c7a8a 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -194,16 +194,11 @@ impl ActivityLog {
RuntimeEvent::ToolCallCompleted { id, result } => {
changed.extend(self.close_thinking());
if let Some(i) = self.tools.remove(id) {
- let failed = matches!(result["status"].as_str(), Some("error" | "failed" | "denied" | "cancelled"));
- if failed {
- let why = ["error", "content", "message"]
- .iter()
- .find_map(|k| result[*k].as_str().filter(|s| !s.trim().is_empty()));
- if let Some(why) = why {
- self.steps[i].detail = Some(cut(&self.redact(why.trim()), MAX_DETAIL));
- }
+ let failed = failed_reason(result);
+ if let Some(Some(why)) = failed {
+ self.steps[i].detail = Some(cut(&self.redact(why), MAX_DETAIL));
}
- changed.push(self.end(i, if failed { "failed" } else { "ok" }));
+ changed.push(self.end(i, if failed.is_some() { "failed" } else { "ok" }));
}
}
_ => {}
@@ -502,6 +497,23 @@ const TOKEN_PREFIXES: [&str; 12] = [
/// Masks secrets in text shown to people: the exact `secrets`, then credentials written as
/// `key=value`, `Bearer …`, URL passwords and provider-looking tokens.
+/// A finished tool call's result: `None` when it went fine, `Some(why)` when its step is
+/// `failed` (error, failed, denied or cancelled), with the reason it gave, trimmed, if any. The
+/// one rule for "a tool failed", shared with the chat's failure line (`server::tool_failures`).
+pub fn failed_reason(result: &Value) -> Option<Option<&str>> {
+ if !matches!(
+ result["status"].as_str(),
+ Some("error" | "failed" | "denied" | "cancelled")
+ ) {
+ return None;
+ }
+ Some(
+ ["error", "content", "message"]
+ .iter()
+ .find_map(|k| result[*k].as_str().map(str::trim).filter(|s| !s.is_empty())),
+ )
+}
+
pub fn redact(text: &str, secrets: &[String]) -> String {
let text = crate::mcp::redact(text, secrets);
let text = crate::profiles::classify::mask_credentials(&text);
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index db2b2ecf..f6e74439 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -1280,7 +1280,7 @@ impl Driver for ApiDriver {
let own = format!("{}:", crate::mcp::SELF_SERVER_NAME);
for problem in problems {
self_failed |= problem.starts_with(&own);
- let _ = event_tx.send(RuntimeEvent::ThinkingDelta(format!("MCP server unavailable: {problem}"))).await;
+ let _ = event_tx.send(RuntimeEvent::ThinkingDelta(format!("{}{problem}", crate::mcp::UNAVAILABLE_PREFIX))).await;
}
Some(session)
}
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rs
index d5ab7505..ce702e5f 100644
--- a/src/drivers/cli.rs
+++ b/src/drivers/cli.rs
@@ -1107,6 +1107,22 @@ struct ClaudeStream {
offered: Option<Vec<String>>,
}
+/// Longest reason kept from a failed tool result.
+const CLAUDE_ERROR_MAX: usize = 600;
+
+/// A `tool_result`'s text: a string, or the text blocks of an array.
+fn tool_result_text(content: &serde_json::Value) -> String {
+ match content {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Array(parts) => parts
+ .iter()
+ .filter_map(|p| p["text"].as_str())
+ .collect::<Vec<_>>()
+ .join("\n"),
+ _ => String::new(),
+ }
+}
+
impl ClaudeStream {
fn line(&mut self, line: &str, now: Instant) -> Vec<RuntimeEvent> {
let line = line.trim();
@@ -1131,6 +1147,27 @@ impl ClaudeStream {
offered.push(item.as_str().or_else(|| item["name"].as_str()).map_or_else(|| item.to_string(), str::to_string));
}
}
+ // A server claude couldn't start, or that wants a sign-in: said like the API
+ // driver says it, so the chat gets its failure line (`server::tool_failures`)
+ for s in v["mcp_servers"]
+ .as_array()
+ .map(Vec::as_slice)
+ .unwrap_or_default()
+ {
+ let (Some(name), Some(status)) = (s["name"].as_str(), s["status"].as_str())
+ else {
+ continue;
+ };
+ let why = match status {
+ "failed" => "it failed to start",
+ "needs-auth" | "needs_auth" => "authentication required",
+ _ => continue,
+ };
+ events.push(RuntimeEvent::ThinkingDelta(format!(
+ "{}{name}: {why}\n",
+ crate::mcp::UNAVAILABLE_PREFIX
+ )));
+ }
}
Some("stream_event") => {
match v["event"]["type"].as_str() {
@@ -1179,8 +1216,13 @@ impl ClaudeStream {
let Some(id) = b["tool_use_id"].as_str().filter(|id| self.running.remove(*id)) else {
continue;
};
- let status = if b["is_error"] == true { "error" } else { "ok" };
- events.push(RuntimeEvent::ToolCallCompleted { id: id.to_string(), result: serde_json::json!({ "status": status }) });
+ let result = if b["is_error"] == true {
+ // Why it failed, cut short: the activity step's detail and the failure line read it
+ serde_json::json!({ "status": "error", "error": crate::mcp::truncate_text(&tool_result_text(&b["content"]), CLAUDE_ERROR_MAX) })
+ } else {
+ serde_json::json!({ "status": "ok" })
+ };
+ events.push(RuntimeEvent::ToolCallCompleted { id: id.to_string(), result });
}
}
_ => {}
@@ -2180,6 +2222,41 @@ endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & \"%_prog%\" \"%dp0%\\n
assert_eq!(parsed.tokens(), Some(7));
}
+ /// 0.9.5: claude's init line names servers that failed or want a sign-in (said like the API
+ /// driver says them), and a failed tool result keeps why it failed.
+ #[test]
+ fn claude_stream_says_which_servers_failed_and_why_a_call_failed() {
+ let t0 = Instant::now();
+ let mut s = ClaudeStream::default();
+ let init = r#"{"type":"system","subtype":"init","tools":[],"mcp_servers":[{"name":"gmail","status":"needs-auth"},{"name":"notion","status":"failed"},{"name":"kwnt_tools","status":"connected"}]}"#;
+ let said: Vec<String> = s
+ .line(init, t0)
+ .into_iter()
+ .filter_map(|e| match e {
+ RuntimeEvent::ThinkingDelta(t) => Some(t),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ said,
+ [
+ "MCP server unavailable: gmail: authentication required\n",
+ "MCP server unavailable: notion: it failed to start\n"
+ ]
+ );
+ s.line(r#"{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tu_9","name":"mcp__gmail__send","input":{}}]}}"#, t0);
+ let done = r#"{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tu_9","is_error":true,"content":[{"type":"text","text":"HTTP 401 Unauthorized"}]}]}}"#;
+ match s.line(done, t0).as_slice() {
+ [RuntimeEvent::ToolCallCompleted { result, .. }] => {
+ assert_eq!(
+ (result["status"].as_str(), result["error"].as_str()),
+ (Some("error"), Some("HTTP 401 Unauthorized"))
+ );
+ }
+ other => panic!("{other:?}"),
+ }
+ }
+
#[test]
fn claude_stream_progress_is_sent_at_most_once_a_second() {
let t0 = Instant::now();
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index b64e5bba..c39cc73d 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -30,6 +30,9 @@ use std::sync::{Arc, Mutex};
pub const SECRET_MASK: &str = "********";
/// Server name kwnt uses for its own permission endpoint in agent CLI configs.
pub const RESERVED_SERVER_NAME: &str = "kwnt";
+/// What a driver says (as a thinking line) when one of the turn's servers could not be reached
+/// at the start: `"MCP server unavailable: <server>: <why>"` (read by `server::tool_failures`).
+pub const UNAVAILABLE_PREFIX: &str = "MCP server unavailable: ";
/// Server name of the agents' own continuity tools (`mcp__kwnt_tools__memory_add`, …).
pub const SELF_SERVER_NAME: &str = "kwnt_tools";
pub const DEFAULT_TIMEOUT_SECS: i64 = 30;
diff --git a/src/server/bot_status.rs b/src/server/bot_status.rs
index 359c903c..3bc4f9be 100644
--- a/src/server/bot_status.rs
+++ b/src/server/bot_status.rs
@@ -158,10 +158,29 @@ pub struct GaveUp {
pub thread_id: Option<String>,
}
+/// One of the bot's connections failed in a way only the person can fix (its sign-in expired or
+/// was refused, a Composio app needs connecting again), see `tool_failures`. Cleared when a later
+/// call through that connection works.
+#[derive(Debug, Clone, PartialEq)]
+pub struct SignInMark {
+ pub at: DateTime<Utc>,
+ /// The connection's key (`mcp:<id>`, `composio:<toolkit>`).
+ pub key: String,
+ /// Its name, e.g. "Gmail".
+ pub connection: String,
+ pub context_id: String,
+ pub thread_id: Option<String>,
+}
+
+/// Most sign-in marks kept per bot (the newest).
+const MAX_SIGN_IN_MARKS: usize = 8;
+
#[derive(Debug, Clone, Default, PartialEq)]
pub struct BotMarks {
pub gave_up: Option<GaveUp>,
pub last_finished_at: Option<DateTime<Utc>>,
+ /// Connections waiting for the person to sign in again, oldest first.
+ pub sign_in: Vec<SignInMark>,
}
/// A send that waits for its bot (H3): the person's message, or a bot's hand-off.
@@ -207,6 +226,31 @@ impl Board {
std::mem::take(&mut self.nudged)
}
+ /// Marks the bot as needing the person to sign in to a connection again (one mark per connection).
+ pub fn mark_sign_in(&mut self, kwant_id: &str, mark: SignInMark) {
+ let marks = &mut self.marks.entry(kwant_id.to_string()).or_default().sign_in;
+ marks.retain(|m| m.key != mark.key);
+ marks.push(mark);
+ if marks.len() > MAX_SIGN_IN_MARKS {
+ marks.remove(0);
+ }
+ self.nudge(kwant_id);
+ }
+
+ /// The connection works again: its mark goes. True when there was one.
+ pub fn clear_sign_in(&mut self, kwant_id: &str, key: &str) -> bool {
+ let Some(m) = self.marks.get_mut(kwant_id) else {
+ return false;
+ };
+ let before = m.sign_in.len();
+ m.sign_in.retain(|s| s.key != key);
+ let cleared = m.sign_in.len() != before;
+ if cleared {
+ self.nudge(kwant_id);
+ }
+ cleared
+ }
+
/// Reserves `key` (chat + client message id) for one send, whose message will be saved as
/// `message_id`. `Err` with the first send when it was seen within [`DEDUPE_MIN`].
pub fn reserve_send(&mut self, key: &str, now: DateTime<Utc>, message_id: &str) -> Result<(), Sent> {
@@ -558,6 +602,25 @@ pub fn compute(b: &BotInput, now: DateTime<Utc>) -> Status {
parts.push(s);
}
}
+ // A connection only the person can fix (0.9.5): the bot needs them until it works again
+ if !parts.iter().any(|p| p.status == "needs_you") {
+ let shows = Span::days(super::tool_failures::NEEDS_YOU_DAYS);
+ if let Some(m) = b
+ .marks
+ .sign_in
+ .iter()
+ .filter(|m| now - m.at < shows)
+ .max_by_key(|m| m.at)
+ {
+ let mut s = Status::new(&b.kwant_id, "needs_you", "needs_sign_in", Some(m.at));
+ s.reason_text = Some(m.connection.clone());
+ s.waits_on = Some(WaitsOn {
+ kind: "person",
+ label: Some(m.connection.clone()),
+ });
+ parts.push(s);
+ }
+ }
if parts.is_empty() {
if let Some(g) = b.marks.gave_up.as_ref().filter(|g| now - g.at < Span::minutes(GAVE_UP_SHOWS_MIN)) {
let mut s = Status::new(&b.kwant_id, "stuck", "stalled_gave_up", Some(g.at));
@@ -1120,6 +1183,74 @@ mod tests {
assert_eq!((s.reason_code, s.since), ("needs_browser", Some(at(4))));
}
+ fn sign_in(key: &str, conn: &str, at: DateTime<Utc>) -> SignInMark {
+ SignInMark {
+ at,
+ key: key.into(),
+ connection: conn.into(),
+ context_id: "c1".into(),
+ thread_id: None,
+ }
+ }
+
+ /// 0.9.5: a connection only the person can fix keeps an idle bot in "needs you", naming it,
+ /// until it works again (or a week passes); a question asked outranks it.
+ #[test]
+ fn a_failed_sign_in_needs_you_until_the_connection_works() {
+ let mut board = Board::default();
+ board.mark_sign_in("k1", sign_in("mcp:s1", "Gmail", at(1)));
+ board.mark_sign_in("k1", sign_in("mcp:s1", "Gmail", at(2)));
+ assert_eq!(
+ board.marks["k1"].sign_in.len(),
+ 1,
+ "one mark per connection"
+ );
+ assert!(board.take_nudged().contains("k1"));
+ let mut b = bot(Vec::new());
+ b.marks = board.marks["k1"].clone();
+ let s = compute(&b, at(3));
+ assert_eq!(
+ (s.status, s.reason_code, s.since),
+ ("needs_you", "needs_sign_in", Some(at(2)))
+ );
+ assert_eq!(s.reason_text.as_deref(), Some("Gmail"));
+ assert_eq!(
+ s.waits_on.as_ref().and_then(|w| w.label.as_deref()),
+ Some("Gmail")
+ );
+ // Still needs you while it works on something else
+ let busy = compute(
+ &BotInput {
+ turns: vec![running("t1", at(3))],
+ ..b.clone()
+ },
+ at(4),
+ );
+ assert_eq!(
+ (busy.status, busy.reason_code),
+ ("needs_you", "needs_sign_in")
+ );
+ assert_eq!(busy.also.first().map(|a| a.status), Some("working"));
+ // A question it asked comes first
+ let mut asked = b.clone();
+ asked.questions = vec![question("q1", "c9", at(3), None)];
+ assert_eq!(compute(&asked, at(4)).reason_code, "asked_question");
+ // A week later it's gone
+ assert_eq!(
+ compute(
+ &b,
+ at(2) + Span::days(super::super::tool_failures::NEEDS_YOU_DAYS)
+ )
+ .status,
+ "available"
+ );
+ // Working again clears it
+ assert!(!board.clear_sign_in("k1", "mcp:other"));
+ assert!(board.clear_sign_in("k1", "mcp:s1"));
+ b.marks = board.marks["k1"].clone();
+ assert_eq!(compute(&b, at(4)).status, "available");
+ }
+
#[test]
fn an_open_question_of_an_ended_turn_still_needs_you() {
let mut b = bot(Vec::new());
diff --git a/src/server/inbox.rs b/src/server/inbox.rs
index d27a5206..2d7f6cc3 100644
--- a/src/server/inbox.rs
+++ b/src/server/inbox.rs
@@ -539,6 +539,33 @@ fn watch_item(mut v: Value, last_seen: Option<DateTime<Utc>>) -> Value {
v
}
+/// 0.9.5: a connection only the person can fix (`tool_failures::needs_you`) as a Waiting-on-you
+/// row, "Gmail needs you to sign in again for Ben" or, for `cause` "reconnect", "Google Calendar
+/// needs to be connected again for TechLead"; the row's Reconnect opens Settings › Connections
+/// and the row itself opens the chat with the line. Its id is the line's message id.
+pub fn connection_item(at: DateTime<Utc>, v: &Value, last_seen: Option<DateTime<Utc>>) -> Value {
+ let unread = last_seen.is_none_or(|s| at > s);
+ let name = v["kwant_name"].as_str().unwrap_or("").to_string();
+ let id = v["message_id"].as_str().unwrap_or("").to_string();
+ let title = super::tool_failures::inbox_title(v["connection"].as_str().unwrap_or("A connection"), v["cause"].as_str().unwrap_or(""), &name);
+ json!({
+ "kind": "connection",
+ "id": id,
+ "kwant_id": v["kwant_id"],
+ "kwant_name": name,
+ "title": title,
+ "summary": "",
+ "status": "open",
+ "timestamp": rfc3339(at),
+ "link": {"thread_id": v["thread_id"], "channel_id": v["channel_id"], "direct_kwant_id": v["direct_kwant_id"]},
+ "connection": v["connection"],
+ "cause": v["cause"],
+ "fix": v["fix"],
+ "group": Group::WaitingOnYou.key(),
+ "sort_key": sort_key(Group::WaitingOnYou, None, at.timestamp_millis(), unread, &name, &id),
+ })
+}
+
/// A review item, and the facts its group and buttons came from; `None` when it isn't listed.
pub fn review_item(r: &ReviewInput, last_seen: Option<DateTime<Utc>>) -> Option<(Value, ReviewFacts)> {
let t = &r.task;
@@ -791,11 +818,17 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
};
// What a mission watcher left for the person (P1), listed and counted as on /api/away
let watch = super::missions::watch::waiting_items(&state, &space).await;
- let unseen_total = unseen_total + watch.len() as i64;
+ // A connection only the person can fix (0.9.5), as listed on /api/waiting
+ let connections = match state.db.list_kwants(&space).await {
+ Ok(kwants) => super::tool_failures::needs_you(&state, &kwants).await,
+ Err(_) => Vec::new(),
+ };
+ let unseen_total = unseen_total + watch.len() as i64 + connections.len() as i64;
let mut items: Vec<Value> = Vec::new();
items.extend(waiting.into_iter().map(|r| away_item(r, Group::WaitingOnYou, seen)));
items.extend(watch.into_iter().map(|v| watch_item(v, seen)));
+ items.extend(connections.into_iter().map(|(at, v)| connection_item(at, &v, seen)));
items.extend(failed.into_iter().map(|r| away_item(r, Group::FailedOrStuck, seen)));
items.extend(finished.into_iter().map(|r| away_item(r, Group::Finished, seen)));
items.extend(reviews.iter().filter_map(|r| review_item(r, seen)).map(|(v, _)| v));
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 030c01db..148a0f51 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -72,8 +72,13 @@ impl PermissionSession {
}
let cwd = self.cwd.as_deref().filter(|d| d.exists());
let (session, problems) = McpToolSession::open(&self.ctx, cwd).await;
+ let watch = super::tool_failures::TurnWatch::find(&self.turn_id);
for problem in problems {
tracing::warn!(kwant = %self.kwant_name, %problem, "MCP gateway could not reach a server");
+ // The chat says so (0.9.5)
+ if let Some(w) = &watch {
+ w.server_problem(&problem).await;
+ }
}
let session = Arc::new(session);
*slot = Some(session.clone());
@@ -1080,6 +1085,14 @@ async fn gateway_rpc(
return rpc_result(id, json!({"content": [{"type": "text", "text": "The turn ended before the call finished."}], "isError": true}));
}
};
+ // The chat's failure line (0.9.5): codex and grok calls are reported here, by their real server
+ if let Some(w) = super::tool_failures::TurnWatch::find(&session.turn_id) {
+ match outcome.status {
+ "ok" => w.call_done(&tool_name, &arguments, None).await,
+ "error" => w.call_done(&tool_name, &arguments, Some(&outcome.text)).await,
+ _ => {}
+ }
+ }
rpc_result(
id,
json!({"content": [{"type": "text", "text": outcome.text}], "isError": outcome.status != "ok"}),
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 82bbc858..0a658dce 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -42,6 +42,7 @@ pub mod away;
pub mod computer;
pub mod mcp_suggest;
pub mod page_source;
+pub mod tool_failures;
pub mod tool_notes;
pub mod connection_suggest;
pub mod bot_actions;
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 938104a3..2da1c3d0 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2959,6 +2959,16 @@ async fn run_kwant_turn_inner(
if let Some(ctx) = &mcp_ctx {
event_broadcast.activity.add_secrets(ctx.secret_values());
}
+ // 0.9.5: a connection that fails says so in this chat, once per connection (see `tool_failures`)
+ let failure_watch = mcp_ctx.as_ref().map(|ctx| {
+ let place = super::tool_failures::Place {
+ channel_id: channel_id.clone(),
+ direct_kwant_id: kwant_id.clone(),
+ thread_id: scope.thread_id.clone(),
+ context_id: tag.context_id.clone(),
+ };
+ super::tool_failures::TurnWatch::start(state, place, &target_kwant.id, &target_kwant.name, &tag.turn_id, &ctx.servers, ctx.secret_values())
+ });
let with_tools = mcp_ctx
.as_ref()
.is_some_and(|c| c.servers.iter().any(|s| s.name == crate::mcp::SELF_SERVER_NAME));
@@ -3390,6 +3400,9 @@ async fn run_kwant_turn_inner(
side_effects |= visible;
acted |= matches!(event, RuntimeEvent::ToolCallPending { .. } | RuntimeEvent::ApprovalRequired { .. });
event_broadcast.activity.relay(&event);
+ if let Some(w) = &failure_watch {
+ w.0.observe(&event).await;
+ }
}
None => break,
}
@@ -3571,6 +3584,10 @@ async fn run_kwant_turn_inner(
// (and toward the bot's monthly budget, G2; usage the engine streamed is reported usage)
super::spend_stop::book_turn(state, &target_kwant.id, state.turns.usage_seen(&tag.turn_id), None, true).await;
}
+ // Failures still waiting for a retry are posted now, before the reply
+ if let Some(w) = &failure_watch {
+ w.0.finish().await;
+ }
let mcp_records = mcp_ctx.map(|c| c.take_records()).filter(|r| !r.is_empty());
// Ends what still runs; kept on the reply so the steps show after a reload
let activity = event_broadcast.activity.finish();
diff --git a/src/server/tool_failures.rs b/src/server/tool_failures.rs
new file mode 100644
index 00000000..78e130b6
--- /dev/null
+++ b/src/server/tool_failures.rs
@@ -0,0 +1,772 @@
+//! 0.9.5: a connection failing says so in the chat when it happens. When one of a bot's
+//! connections or tool servers fails during a turn (it needs the person to sign in again, a
+//! Composio app needs connecting again, the server didn't start or stopped responding), kwnt
+//! posts one plain line in the chat the turn runs in, with a link to fix it:
+//! "Gmail stopped working for Ben: it needs you to sign in again. Reconnect".
+//!
+//! Rules:
+//! - one line per connection per turn, never one per tool call;
+//! - nothing for a failure a retry through the same connection fixed: a failure waits
+//! [`GRACE`] for a retry (a second failure, or the turn ending, posts it at once);
+//! - a server that didn't start posts at once (nothing can retry it in this turn);
+//! - when only the person can fix it (a sign-in or a reconnect), the bot shows as "needs you"
+//! (`bot_status`'s `needs_sign_in`) and the line is listed in `GET /api/waiting` until a later
+//! call through that connection works, or [`NEEDS_YOU_DAYS`] pass.
+//!
+//! No new store: a failure is the activity step's `failed` status
+//! ([`crate::drivers::activity::failed_reason`]), a server that didn't start is the problem
+//! `McpToolSession::open` reports (API driver, codex gateway) or claude's own init line, and the
+//! line is an ordinary message with `meta.kind = "tool_failure"`, posted like a tool note's.
+
+use super::AppState;
+use crate::db::models::{McpServer, Message, MessageExtra, NewMessage};
+use crate::drivers::events::RuntimeEvent;
+use chrono::{DateTime, Duration as Span, Utc};
+use serde_json::{json, Value};
+use std::collections::{HashMap, HashSet};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+pub const KIND: &str = crate::db::tool_failures::KIND;
+pub use crate::mcp::UNAVAILABLE_PREFIX;
+/// How long a failure waits for a retry through the same connection before its line is posted.
+pub const GRACE: Duration = Duration::from_secs(20);
+/// How long an unfixed sign-in keeps the bot in "needs you".
+pub const NEEDS_YOU_DAYS: i64 = 7;
+/// Longest reason kept with a line.
+const MAX_DETAIL: usize = 300;
+/// Most failures one turn keeps track of (a runaway turn can't grow this without bound).
+const MAX_KEYS: usize = 32;
+
+/// Why a connection failed.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Cause {
+ /// It needs the person to sign in again (401/403, an expired or invalid token).
+ SignIn,
+ /// A Composio app has no active connected account: it needs connecting again.
+ Reconnect,
+ /// The server didn't start (or couldn't be reached) when the turn began.
+ NotStarted,
+ /// The server stopped responding mid-turn.
+ Down,
+}
+
+impl Cause {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Cause::SignIn => "sign_in",
+ Cause::Reconnect => "reconnect",
+ Cause::NotStarted => "not_started",
+ Cause::Down => "down",
+ }
+ }
+
+ /// Only the person can fix it (sign in, connect again).
+ pub fn needs_you(self) -> bool {
+ matches!(self, Cause::SignIn | Cause::Reconnect)
+ }
+
+ fn fix_label(self) -> &'static str {
+ if self.needs_you() {
+ "Reconnect"
+ } else {
+ "Check it"
+ }
+ }
+}
+
+/// One of the turn's servers, as the classifier needs it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Server {
+ pub id: String,
+ pub name: String,
+ pub composio: bool,
+}
+
+impl Server {
+ pub fn of(s: &McpServer) -> Self {
+ Self { id: s.id.clone(), name: s.name.clone(), composio: super::connections::is_composio(s) }
+ }
+}
+
+/// The connection a tool call went through: one key per connection, a name for the person and
+/// the server to fix it in (none for kwant's own tools).
+#[derive(Debug, Clone, PartialEq)]
+pub struct Connection {
+ /// `mcp:<server id>`, `composio:<toolkit>` or `kwnt`.
+ pub key: String,
+ pub label: String,
+ pub server_id: Option<String>,
+}
+
+/// A failed connection: what the line says.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Failure {
+ pub conn: Connection,
+ pub cause: Cause,
+ /// The tool that met it (`server · tool`), when a call did.
+ pub tool: Option<String>,
+ /// The reason it gave, redacted and cut.
+ pub detail: Option<String>,
+}
+
+fn is_own(server: &str) -> bool {
+ server == crate::mcp::SELF_SERVER_NAME || server == crate::mcp::RESERVED_SERVER_NAME
+}
+
+/// How well-known apps are written, as in `frontend/src/toolLabel.ts` `SERVERS` (keep the two
+/// in step): matched case-insensitively on a Composio toolkit slug or an MCP server name.
+const KNOWN_NAMES: [(&str, &str); 12] = [
+ ("github", "GitHub"),
+ ("gitlab", "GitLab"),
+ ("linear", "Linear"),
+ ("slack", "Slack"),
+ ("notion", "Notion"),
+ ("jira", "Jira"),
+ ("stripe", "Stripe"),
+ ("gmail", "Gmail"),
+ ("googlecalendar", "Google Calendar"),
+ ("google_calendar", "Google Calendar"),
+ ("googledrive", "Google Drive"),
+ ("google_drive", "Google Drive"),
+];
+
+fn known_name(name: &str) -> Option<&'static str> {
+ KNOWN_NAMES.iter().find(|(k, _)| k.eq_ignore_ascii_case(name.trim())).map(|(_, v)| *v)
+}
+
+/// A Composio app's name: `GitHub` from `github`, else `Gmail` from `gmail`, `GMAIL`.
+fn title(word: &str) -> String {
+ if let Some(known) = known_name(word) {
+ return known.to_string();
+ }
+ let lower = word.to_lowercase();
+ let mut chars = lower.chars();
+ match chars.next() {
+ Some(c) => c.to_uppercase().chain(chars).collect(),
+ None => String::new(),
+ }
+}
+
+/// An MCP server's name for the person: a well-known one written properly, any other as typed.
+fn server_label(name: &str) -> String {
+ known_name(name).map(str::to_string).unwrap_or_else(|| name.to_string())
+}
+
+/// The Composio app a call used: the prefix of its tool slug (`GMAIL_SEND_EMAIL` → `gmail`), or
+/// of the first slug a meta tool was given (`COMPOSIO_MULTI_EXECUTE_TOOL` with `tools[0].tool_slug`).
+fn composio_toolkit(tool: &str, args: &Value) -> Option<String> {
+ let slug = if tool.to_ascii_uppercase().starts_with("COMPOSIO_") {
+ args["tools"][0]["tool_slug"]
+ .as_str()
+ .or_else(|| args["tool_slug"].as_str())
+ .or_else(|| args["toolkit"].as_str())
+ .or_else(|| args["toolkits"][0].as_str())?
+ } else {
+ tool
+ };
+ let kit = slug.split('_').next().unwrap_or("").trim().to_lowercase();
+ (kit.len() >= 2 && kit.len() <= 40 && kit.chars().all(|c| c.is_ascii_alphanumeric()) && kit != "composio").then_some(kit)
+}
+
+/// The connection behind a tool name (`mcp__<server>__<tool>`), or `None` for a tool that isn't a
+/// connection's (an engine's own tool, an unknown server).
+pub fn connection_of(name: &str, args: &Value, servers: &[Server]) -> Option<Connection> {
+ let (server, tool) = crate::mcp::split_tool_name(name)?;
+ if is_own(server) {
+ return Some(Connection { key: "kwnt".into(), label: "kwant's own tools".into(), server_id: None });
+ }
+ let s = servers.iter().find(|s| s.name == server)?;
+ if s.composio {
+ if let Some(kit) = composio_toolkit(tool, args) {
+ return Some(Connection { key: format!("composio:{kit}"), label: title(&kit), server_id: Some(s.id.clone()) });
+ }
+ }
+ Some(Connection { key: format!("mcp:{}", s.id), label: server_label(&s.name), server_id: Some(s.id.clone()) })
+}
+
+/// `code` appears in `text` as a number of its own (`401`, not `14012`).
+fn has_code(text: &str, code: &str) -> bool {
+ text.match_indices(code).any(|(i, _)| {
+ let before = text[..i].chars().next_back();
+ let after = text[i + code.len()..].chars().next();
+ !before.is_some_and(|c| c.is_ascii_alphanumeric()) && !after.is_some_and(|c| c.is_ascii_alphanumeric())
+ })
+}
+
+const SIGN_IN_WORDS: [&str; 14] = [
+ "unauthorized",
+ "unauthenticated",
+ "forbidden",
+ "invalid_grant",
+ "invalid_token",
+ "invalid token",
+ "token expired",
+ "token has expired",
+ "expired token",
+ "authentication required",
+ "authentication failed",
+ "login required",
+ "re-authenticate",
+ "reauthenticate",
+];
+
+const RECONNECT_WORDS: [&str; 8] = [
+ "connected account not found",
+ "connected account is not active",
+ "connected account expired",
+ "connected account is expired",
+ "connected account is inactive",
+ "no connected account",
+ "no active connection",
+ "needs to be reconnected",
+];
+
+const DOWN_WORDS: [&str; 11] = [
+ "could not start",
+ "failed to start",
+ "connection refused",
+ "connection reset",
+ "connection closed",
+ "transport closed",
+ "failed to connect",
+ "error sending request",
+ "bad gateway",
+ "service unavailable",
+ "gateway timeout",
+];
+
+fn sign_in_text(lower: &str) -> bool {
+ has_code(lower, "401") || has_code(lower, "403") || SIGN_IN_WORDS.iter().any(|w| lower.contains(w))
+}
+
+fn down_text(lower: &str) -> bool {
+ has_code(lower, "502") || has_code(lower, "503") || has_code(lower, "504") || DOWN_WORDS.iter().any(|w| lower.contains(w))
+}
+
+/// What a failed call's reason says about its connection, or `None` when it's the tool's own
+/// error (bad arguments, not found, a rule it refused): those aren't the connection's.
+pub fn cause_of(conn: &Connection, why: &str) -> Option<Cause> {
+ let lower = why.to_lowercase();
+ // The MCP client couldn't talk to the server at all (`McpToolSession::call`)
+ let transport = lower.starts_with("tool call failed:");
+ if conn.key == "kwnt" {
+ // kwant's own tools reach the web for the bot; only their own transport failing counts
+ return (transport || lower.contains("transport closed") || lower.contains("connection closed")).then_some(Cause::Down);
+ }
+ let composio = conn.key.starts_with("composio:");
+ if composio && RECONNECT_WORDS.iter().any(|w| lower.contains(w)) {
+ return Some(Cause::Reconnect);
+ }
+ if sign_in_text(&lower) {
+ return Some(if composio { Cause::Reconnect } else { Cause::SignIn });
+ }
+ if transport || down_text(&lower) {
+ return Some(Cause::Down);
+ }
+ None
+}
+
+/// A failed call → the connection failure it is, if any.
+pub fn classify(name: &str, args: &Value, why: &str, servers: &[Server]) -> Option<Failure> {
+ let conn = connection_of(name, args, servers)?;
+ let cause = cause_of(&conn, why)?;
+ Some(Failure {
+ conn,
+ cause,
+ tool: Some(cut(&super::tool_notes::tool_name(name), 80)),
+ detail: Some(cut(why.trim(), MAX_DETAIL)).filter(|d| !d.is_empty()),
+ })
+}
+
+/// A server the turn couldn't reach at the start (`"<server>: <why>"`), as a failure.
+pub fn not_started(problem: &str, servers: &[Server]) -> Option<Failure> {
+ let (server, why) = problem.split_once(": ").unwrap_or((problem, ""));
+ let server = server.trim();
+ let conn = if is_own(server) {
+ Connection { key: "kwnt".into(), label: "kwant's own tools".into(), server_id: None }
+ } else {
+ let s = servers.iter().find(|s| s.name == server)?;
+ Connection { key: format!("mcp:{}", s.id), label: server_label(&s.name), server_id: Some(s.id.clone()) }
+ };
+ let lower = why.to_lowercase();
+ let cause = if conn.server_id.is_some() && sign_in_text(&lower) { Cause::SignIn } else { Cause::NotStarted };
+ Some(Failure { conn, cause, tool: None, detail: Some(cut(why.trim(), MAX_DETAIL)).filter(|d| !d.is_empty()) })
+}
+
+fn cut(s: &str, max: usize) -> String {
+ super::tool_notes::cut(&super::tool_notes::clean(s, false), max)
+}
+
+/// The line's words, without the fix link.
+pub fn line(f: &Failure, bot: &str) -> String {
+ let c = &f.conn.label;
+ match f.cause {
+ Cause::SignIn => {
+ format!("{c} stopped working for {bot}: it needs you to sign in again.")
+ }
+ Cause::Reconnect => {
+ format!("{c} stopped working for {bot}: it needs to be connected again.")
+ }
+ Cause::NotStarted => format!("{c} didn't start for {bot}, so its tools weren't available."),
+ Cause::Down => format!("{c} stopped responding for {bot}."),
+ }
+}
+
+/// The Inbox row's title for a connection only the person can fix, worded like the chat line:
+/// "Gmail needs you to sign in again for Ben" for a sign-in, "Google Calendar needs to be connected
+/// again for TechLead" for an app to connect again (`cause` is the line's `Cause::as_str`).
+pub fn inbox_title(connection: &str, cause: &str, bot: &str) -> String {
+ if cause == Cause::Reconnect.as_str() {
+ format!("{connection} needs to be connected again for {bot}")
+ } else {
+ format!("{connection} needs you to sign in again for {bot}")
+ }
+}
+
+/// The saved message's text: the line plus where to fix it, for clients that show text only.
+pub fn text(f: &Failure, bot: &str) -> String {
+ let mut out = line(f, bot);
+ if f.conn.server_id.is_some() {
+ out.push_str(if f.cause.needs_you() { " Reconnect it in Settings › Connections." } else { " See Settings › Connections." });
+ }
+ out
+}
+
+/// The saved message's `meta`.
+pub fn meta(f: &Failure, kwant_id: &str, bot: &str, turn_id: &str) -> Value {
+ let fix = f
+ .conn
+ .server_id
+ .as_ref()
+ .map(|id| json!({"label": f.cause.fix_label(), "opens": "connections", "connection_id": format!("mcp:{id}")}));
+ json!({
+ "kind": KIND,
+ "kwant_id": kwant_id,
+ "turn_id": turn_id,
+ "connection": f.conn.label,
+ "key": f.conn.key,
+ "server_id": f.conn.server_id,
+ "cause": f.cause.as_str(),
+ "tool": f.tool,
+ "detail": f.detail,
+ "line": line(f, bot),
+ "needs_you": f.cause.needs_you(),
+ "fix": fix,
+ "resolved_at": null,
+ })
+}
+
+// ---------------------------------------------------------------------------------------------
+// One turn's failures: which to post, which a retry fixed
+
+/// The turn's connection failures. A failure waits (pending) for a retry; a success through the
+/// same connection drops it; a second failure, its grace running out or the turn ending posts
+/// it. A connection is posted at most once per turn.
+#[derive(Debug, Default)]
+pub struct Watch {
+ pending: HashMap<String, (Failure, u64)>,
+ posted: HashSet<String>,
+ next_gen: u64,
+}
+
+/// What [`Watch::failed`] asks for.
+#[derive(Debug, PartialEq)]
+pub enum Next {
+ /// Nothing: already posted, or too many connections this turn.
+ Nothing,
+ /// Post this now.
+ Post(Failure),
+ /// Wait for a retry; post when [`Watch::due`] with this generation still finds it.
+ Wait(u64),
+}
+
+impl Watch {
+ pub fn failed(&mut self, f: Failure) -> Next {
+ let key = f.conn.key.clone();
+ if self.posted.contains(&key) {
+ return Next::Nothing;
+ }
+ if self.pending.remove(&key).is_some() || f.cause == Cause::NotStarted {
+ self.posted.insert(key);
+ return Next::Post(f);
+ }
+ if self.pending.len() + self.posted.len() >= MAX_KEYS {
+ return Next::Nothing;
+ }
+ self.next_gen += 1;
+ self.pending.insert(key, (f, self.next_gen));
+ Next::Wait(self.next_gen)
+ }
+
+ /// A call through `key` worked: a failure still waiting is dropped (the retry fixed it).
+ pub fn succeeded(&mut self, key: &str) -> bool {
+ self.pending.remove(key).is_some()
+ }
+
+ /// The grace of the failure `gen` ran out: post it if it still waits.
+ pub fn due(&mut self, key: &str, gen: u64) -> Option<Failure> {
+ match self.pending.get(key) {
+ Some((_, g)) if *g == gen => {
+ let (f, _) = self.pending.remove(key)?;
+ self.posted.insert(key.to_string());
+ Some(f)
+ }
+ _ => None,
+ }
+ }
+
+ /// The turn ended: everything still waiting is posted.
+ pub fn finish(&mut self) -> Vec<Failure> {
+ let mut out: Vec<(Failure, u64)> = self.pending.drain().map(|(_, v)| v).collect();
+ out.sort_by_key(|(_, g)| *g);
+ for (f, _) in &out {
+ self.posted.insert(f.conn.key.clone());
+ }
+ out.into_iter().map(|(f, _)| f).collect()
+ }
+
+ pub fn was_posted(&self, key: &str) -> bool {
+ self.posted.contains(key)
+ }
+}
+
+/// Where the turn's line goes.
+#[derive(Debug, Clone, Default)]
+pub struct Place {
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+ /// The chat's id as bot status names it (`TurnTag::context_id`).
+ pub context_id: String,
+}
+
+#[derive(Default)]
+struct Inner {
+ watch: Watch,
+ /// Calls still running: id → (tool name, arguments).
+ calls: HashMap<String, (String, Value)>,
+ /// Connections a success was already seen for this turn (open lines resolved once).
+ worked: HashSet<String>,
+ finished: bool,
+}
+
+/// One turn's watch, found by turn id (the codex gateway reports its calls to it).
+pub struct TurnWatch {
+ state: AppState,
+ place: Place,
+ kwant_id: String,
+ kwant_name: String,
+ turn_id: String,
+ servers: Vec<Server>,
+ secrets: Vec<String>,
+ inner: Mutex<Inner>,
+}
+
+fn registry() -> &'static Mutex<HashMap<String, Arc<TurnWatch>>> {
+ static WATCHES: OnceLock<Mutex<HashMap<String, Arc<TurnWatch>>>> = OnceLock::new();
+ WATCHES.get_or_init(Default::default)
+}
+
+/// Removes the turn's watch when the turn's run ends, however it ends; failures still waiting
+/// are posted in the background (the normal end posts them first, see [`TurnWatch::finish`]).
+pub struct WatchGuard(pub Arc<TurnWatch>);
+
+impl Drop for WatchGuard {
+ fn drop(&mut self) {
+ let w = self.0.clone();
+ registry().lock().unwrap_or_else(|e| e.into_inner()).remove(&w.turn_id);
+ let left = {
+ let mut inner = w.lock();
+ inner.finished = true;
+ inner.watch.finish()
+ };
+ if !left.is_empty() {
+ if let Ok(rt) = tokio::runtime::Handle::try_current() {
+ rt.spawn(async move {
+ for f in left {
+ w.post(f).await;
+ }
+ });
+ }
+ }
+ }
+}
+
+impl TurnWatch {
+ /// Starts watching a turn that has MCP servers.
+ pub fn start(
+ state: &AppState,
+ place: Place,
+ kwant_id: &str,
+ kwant_name: &str,
+ turn_id: &str,
+ servers: &[McpServer],
+ secrets: Vec<String>,
+ ) -> WatchGuard {
+ let watch = Arc::new(Self {
+ state: state.clone(),
+ place,
+ kwant_id: kwant_id.to_string(),
+ kwant_name: kwant_name.to_string(),
+ turn_id: turn_id.to_string(),
+ servers: servers.iter().map(Server::of).collect(),
+ secrets,
+ inner: Mutex::new(Inner::default()),
+ });
+ registry().lock().unwrap_or_else(|e| e.into_inner()).insert(turn_id.to_string(), watch.clone());
+ WatchGuard(watch)
+ }
+
+ pub fn find(turn_id: &str) -> Option<Arc<TurnWatch>> {
+ registry().lock().unwrap_or_else(|e| e.into_inner()).get(turn_id).cloned()
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
+ self.inner.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// A driver event of the turn. Calls through kwnt's gateway (`mcp__kwnt__…`) are skipped:
+ /// the gateway reports those itself, with the real server's name ([`TurnWatch::call_done`]).
+ pub async fn observe(self: &Arc<Self>, event: &RuntimeEvent) {
+ match event {
+ RuntimeEvent::ToolCallPending { id, name, args } => {
+ let Some((server, _)) = crate::mcp::split_tool_name(name) else {
+ return;
+ };
+ if server == crate::mcp::RESERVED_SERVER_NAME {
+ return;
+ }
+ let mut inner = self.lock();
+ if inner.calls.len() < 256 {
+ inner.calls.insert(id.clone(), (name.clone(), args.clone()));
+ }
+ }
+ RuntimeEvent::ToolCallCompleted { id, result } => {
+ let Some((name, args)) = self.lock().calls.remove(id) else {
+ return;
+ };
+ let status = result["status"].as_str().unwrap_or("");
+ // A card the person declined, or a call the turn's end cut off, isn't the connection's
+ if matches!(status, "denied" | "cancelled" | "unanswered") {
+ return;
+ }
+ let why = crate::drivers::activity::failed_reason(result);
+ self.call_done(&name, &args, why.map(|w| w.unwrap_or(""))).await;
+ }
+ RuntimeEvent::ThinkingDelta(t) => {
+ for problem in t.lines().filter_map(|l| l.trim().strip_prefix(UNAVAILABLE_PREFIX)) {
+ self.server_problem(problem).await;
+ }
+ }
+ _ => {}
+ }
+ }
+
+ /// A tool call finished: `failed` is `None` when it worked, else its reason.
+ pub async fn call_done(self: &Arc<Self>, name: &str, args: &Value, failed: Option<&str>) {
+ match failed {
+ None => {
+ let Some(conn) = connection_of(name, args, &self.servers) else {
+ return;
+ };
+ let (first, dropped) = {
+ let mut inner = self.lock();
+ let dropped = inner.watch.succeeded(&conn.key);
+ (inner.worked.insert(conn.key.clone()), dropped)
+ };
+ if dropped {
+ tracing::info!(kwant = %self.kwant_name, key = %conn.key, "a retry fixed a failed connection; no line");
+ }
+ if first {
+ resolve(&self.state, &self.kwant_id, &conn.key).await;
+ }
+ }
+ Some(why) => {
+ let why = crate::drivers::activity::redact(why, &self.secrets);
+ if let Some(f) = classify(name, args, &why, &self.servers) {
+ self.failed(f).await;
+ }
+ }
+ }
+ }
+
+ /// A server the turn couldn't reach (`"<server>: <why>"`).
+ pub async fn server_problem(self: &Arc<Self>, problem: &str) {
+ let problem = crate::drivers::activity::redact(problem, &self.secrets);
+ if let Some(f) = not_started(&problem, &self.servers) {
+ self.failed(f).await;
+ }
+ }
+
+ async fn failed(self: &Arc<Self>, f: Failure) {
+ let key = f.conn.key.clone();
+ let next = {
+ let mut inner = self.lock();
+ if inner.finished {
+ return;
+ }
+ inner.watch.failed(f)
+ };
+ match next {
+ Next::Nothing => {}
+ Next::Post(f) => self.post(f).await,
+ Next::Wait(gen) => {
+ let me = self.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(GRACE).await;
+ let due = me.lock().watch.due(&key, gen);
+ if let Some(f) = due {
+ me.post(f).await;
+ }
+ });
+ }
+ }
+ }
+
+ /// The turn ended: failures still waiting for a retry are posted now (before the reply).
+ pub async fn finish(&self) {
+ let left = {
+ let mut inner = self.lock();
+ inner.finished = true;
+ inner.watch.finish()
+ };
+ for f in left {
+ self.post(f).await;
+ }
+ }
+
+ async fn post(&self, f: Failure) {
+ post_line(&self.state, &self.place, &self.kwant_id, &self.kwant_name, &self.turn_id, &f).await;
+ }
+}
+
+/// Posts the line in the turn's chat, tells Connections, and marks the bot "needs you" when
+/// only the person can fix it.
+pub async fn post_line(state: &AppState, place: &Place, kwant_id: &str, bot: &str, turn_id: &str, f: &Failure) -> Option<Message> {
+ // A connection's own server: Connections shows it as signed out or failing
+ if let (Some(id), false) = (&f.conn.server_id, f.conn.key.starts_with("composio:")) {
+ super::connections::record_mcp_check(id, &json!({"ok": false, "auth_required": f.cause == Cause::SignIn, "error": f.detail}));
+ }
+ if f.cause.needs_you() {
+ let mark = super::bot_status::SignInMark {
+ at: Utc::now(),
+ key: f.conn.key.clone(),
+ connection: f.conn.label.clone(),
+ context_id: place.context_id.clone(),
+ thread_id: place.thread_id.clone(),
+ };
+ state.turns.board(|b| b.mark_sign_in(kwant_id, mark));
+ }
+ tracing::info!(kwant = %bot, key = %f.conn.key, cause = f.cause.as_str(), "a connection failed; posting a line");
+ let message = NewMessage {
+ channel_id: place.channel_id.clone(),
+ direct_kwant_id: place.direct_kwant_id.clone(),
+ sender_role: "kwant".into(),
+ sender_id: bot.to_string(),
+ text: text(f, bot),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let extra = MessageExtra { thread_id: place.thread_id.clone(), meta: Some(meta(f, kwant_id, bot, turn_id)) };
+ match state.db.insert_message_with(&message, &extra).await {
+ Ok(saved) => {
+ if let Some(t) = &place.thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });
+ Some(saved)
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "tool failure: could not post the chat line");
+ None
+ }
+ }
+}
+
+fn meta_of(m: &Message) -> Option<Value> {
+ m.meta.as_deref().and_then(|s| serde_json::from_str::<Value>(s).ok()).filter(|v| v["kind"] == KIND)
+}
+
+/// A call through `key` worked: the bot's open lines for it are resolved (out of "Needs you")
+/// and its sign-in mark is cleared.
+pub async fn resolve(state: &AppState, kwant_id: &str, key: &str) {
+ let marked = state.turns.board(|b| b.clear_sign_in(kwant_id, key));
+ let since = Utc::now() - Span::days(NEEDS_YOU_DAYS);
+ let open: Vec<(String, Value)> = match state.db.list_tool_failure_lines().await {
+ Ok(lines) => lines
+ .iter()
+ .filter(|m| m.created_at.is_some_and(|at| at >= since))
+ .filter_map(|m| meta_of(m).map(|v| (m.id.clone(), v)))
+ .filter(|(_, v)| v["kwant_id"] == kwant_id && v["key"] == key && v["needs_you"] == true && v["resolved_at"].is_null())
+ .collect(),
+ Err(_) => return,
+ };
+ if open.is_empty() && !marked {
+ return;
+ }
+ let now = Utc::now();
+ for (id, mut v) in open {
+ v["resolved_at"] = json!(now);
+ let _ = state.db.set_message_meta(&id, &v).await;
+ }
+ tracing::info!(kwant = %kwant_id, %key, "a connection works again; its line is resolved");
+}
+
+/// "Needs you" items: open sign-in lines of the space's bots from the last [`NEEDS_YOU_DAYS`],
+/// one per bot and connection (the newest), as `(asked_at, item)` for `GET /api/waiting`.
+pub async fn needs_you(state: &AppState, kwants: &[crate::db::models::Kwant]) -> Vec<(DateTime<Utc>, Value)> {
+ let Ok(lines) = state.db.list_tool_failure_lines().await else {
+ return Vec::new();
+ };
+ needs_you_items(&lines, kwants, Utc::now())
+}
+
+pub fn needs_you_items(lines: &[Message], kwants: &[crate::db::models::Kwant], now: DateTime<Utc>) -> Vec<(DateTime<Utc>, Value)> {
+ let since = now - Span::days(NEEDS_YOU_DAYS);
+ let mut seen: HashSet<(String, String)> = HashSet::new();
+ let mut out = Vec::new();
+ // Newest first, so the first line of a bot and connection is the one kept
+ for m in lines {
+ let Some(at) = m.created_at.filter(|at| *at >= since) else {
+ continue;
+ };
+ let Some(v) = meta_of(m) else { continue };
+ if v["needs_you"] != true || !v["resolved_at"].is_null() {
+ continue;
+ }
+ let (Some(kwant_id), Some(key)) = (v["kwant_id"].as_str(), v["key"].as_str()) else {
+ continue;
+ };
+ let Some(k) = kwants.iter().find(|k| k.id == kwant_id) else {
+ continue;
+ };
+ if !seen.insert((kwant_id.to_string(), key.to_string())) {
+ continue;
+ }
+ out.push((
+ at,
+ json!({
+ "kind": "connection",
+ "kwant_id": kwant_id,
+ "kwant_name": k.name,
+ "channel_id": m.channel_id,
+ "direct_kwant_id": m.direct_kwant_id,
+ "thread_id": m.thread_id,
+ "message_id": m.id,
+ "connection": v["connection"],
+ "cause": v["cause"],
+ "fix": v["fix"],
+ "text": v["line"],
+ "asked_at": at,
+ "follow_up_at": null,
+ "reminded_at": null,
+ }),
+ ));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/src/server/tool_failures/tests.rs b/src/server/tool_failures/tests.rs
new file mode 100644
index 00000000..305735f5
--- /dev/null
+++ b/src/server/tool_failures/tests.rs
@@ -0,0 +1,237 @@
+use super::*;
+
+fn servers() -> Vec<Server> {
+ vec![
+ Server { id: "s-gh".into(), name: "github".into(), composio: false },
+ Server { id: "s-co".into(), name: "composio".into(), composio: true },
+ ]
+}
+
+fn gh() -> Failure {
+ classify("mcp__github__list_issues", &json!({}), "HTTP 401 Unauthorized: bad credentials", &servers()).unwrap()
+}
+
+fn down(key: &str) -> Failure {
+ Failure {
+ conn: Connection { key: key.into(), label: key.into(), server_id: Some("s".into()) },
+ cause: Cause::Down,
+ tool: None,
+ detail: None,
+ }
+}
+
+/// A 401 is a sign-in failure of that server, and its line links to Connections.
+#[test]
+fn a_401_is_a_sign_in_with_a_fix_link() {
+ let f = gh();
+ assert_eq!(f.cause, Cause::SignIn);
+ assert_eq!(f.conn, Connection { key: "mcp:s-gh".into(), label: "GitHub".into(), server_id: Some("s-gh".into()) });
+ assert_eq!(
+ text(&f, "Ben"),
+ "GitHub stopped working for Ben: it needs you to sign in again. Reconnect it in Settings › Connections."
+ );
+ let m = meta(&f, "k1", "Ben", "t1");
+ assert_eq!(m["kind"], KIND);
+ assert_eq!(m["needs_you"], true);
+ assert_eq!(m["fix"], json!({"label": "Reconnect", "opens": "connections", "connection_id": "mcp:s-gh"}));
+ assert_eq!(m["cause"], "sign_in");
+ assert!(m["resolved_at"].is_null());
+ // 403 and an expired token too; a number that merely contains 401 doesn't count
+ for why in ["403 Forbidden", "invalid_grant: Token has expired", "error: Unauthorized"] {
+ assert_eq!(classify("mcp__github__x", &json!({}), why, &servers()).unwrap().cause, Cause::SignIn, "{why}");
+ }
+ assert!(classify("mcp__github__x", &json!({}), "issue 14012 not found", &servers()).is_none());
+}
+
+/// A tool's own error (bad arguments, not found) isn't the connection's: no line.
+#[test]
+fn a_tools_own_error_is_not_a_connection_failure() {
+ for why in ["", "invalid arguments: repo is required", "Not Found", "rate limit: try in 2 minutes"] {
+ assert!(classify("mcp__github__get_repo", &json!({}), why, &servers()).is_none(), "{why}");
+ }
+ // Engines' own tools and unknown servers aren't connections
+ assert!(classify("Bash", &json!({}), "401", &servers()).is_none());
+ assert!(classify("mcp__unknown__x", &json!({}), "401", &servers()).is_none());
+}
+
+/// A Composio app that lost its account needs connecting again, keyed by the app, not the server.
+#[test]
+fn composio_failures_are_per_app_and_need_a_reconnect() {
+ let f = classify("mcp__composio__GMAIL_SEND_EMAIL", &json!({}), "Connected account not found for toolkit gmail", &servers()).unwrap();
+ assert_eq!(f.cause, Cause::Reconnect);
+ assert_eq!(f.conn.key, "composio:gmail");
+ assert_eq!(f.conn.label, "Gmail");
+ assert_eq!(line(&f, "Ben"), "Gmail stopped working for Ben: it needs to be connected again.");
+ let args = json!({"tools": [{"tool_slug": "SLACK_SEND_MESSAGE", "arguments": {}}]});
+ let f = classify("mcp__composio__COMPOSIO_MULTI_EXECUTE_TOOL", &args, "401 Unauthorized", &servers()).unwrap();
+ assert_eq!((f.conn.key.as_str(), f.cause), ("composio:slack", Cause::Reconnect));
+ assert_eq!(meta(&f, "k", "Ben", "t")["fix"]["connection_id"], "mcp:s-co");
+ // A meta tool with no app falls back to the server
+ let f = classify("mcp__composio__COMPOSIO_SEARCH_TOOLS", &json!({}), "503 Service Unavailable", &servers()).unwrap();
+ assert_eq!((f.conn.key.as_str(), f.cause), ("mcp:s-co", Cause::Down));
+}
+
+/// Well-known apps are written as the working strip writes them (`toolLabel.ts` `SERVERS`),
+/// matched case-insensitively on the Composio app and the MCP server name; others as typed.
+#[test]
+fn well_known_apps_are_named_properly() {
+ for (slug, name) in [
+ ("GITHUB_LIST_ISSUES", "GitHub"),
+ ("GITLAB_GET_PROJECT", "GitLab"),
+ ("GOOGLECALENDAR_LIST_EVENTS", "Google Calendar"),
+ ("GOOGLEDRIVE_FIND_FILE", "Google Drive"),
+ ("GMAIL_SEND_EMAIL", "Gmail"),
+ ("TRELLO_GET_BOARD", "Trello"),
+ ] {
+ let f = classify(&format!("mcp__composio__{slug}"), &json!({}), "401 Unauthorized", &servers()).unwrap();
+ assert_eq!(f.conn.label, name, "{slug}");
+ }
+ let f = classify("mcp__composio__GOOGLECALENDAR_LIST_EVENTS", &json!({}), "Connected account not found", &servers()).unwrap();
+ assert_eq!(line(&f, "Ben"), "Google Calendar stopped working for Ben: it needs to be connected again.");
+ let servers = vec![
+ Server { id: "a".into(), name: "GitHub".into(), composio: false },
+ Server { id: "b".into(), name: "google_drive".into(), composio: false },
+ Server { id: "c".into(), name: "my-Wiki".into(), composio: false },
+ ];
+ let label = |n: &str| classify(&format!("mcp__{n}__x"), &json!({}), "503 Service Unavailable", &servers).unwrap().conn.label;
+ assert_eq!(label("GitHub"), "GitHub");
+ assert_eq!(label("google_drive"), "Google Drive");
+ assert_eq!(label("my-Wiki"), "my-Wiki", "any other server as the person typed it");
+ assert_eq!(not_started("google_drive: failed to start", &servers).unwrap().conn.label, "Google Drive");
+}
+
+/// kwant's own tools fetch the web for the bot: a page's 401 isn't kwant failing.
+#[test]
+fn kwants_own_tools_count_only_their_transport() {
+ assert!(classify("mcp__kwnt_tools__web_fetch", &json!({}), "HTTP 401 from example.com", &servers()).is_none());
+ let f = classify("mcp__kwnt_tools__web_fetch", &json!({}), "tool call failed: transport closed", &servers()).unwrap();
+ assert_eq!((f.conn.key.as_str(), f.cause, f.conn.server_id.clone()), ("kwnt", Cause::Down, None));
+ assert_eq!(text(&f, "Ben"), "kwant's own tools stopped responding for Ben.");
+ assert!(meta(&f, "k", "Ben", "t")["fix"].is_null());
+}
+
+/// A server that didn't start: auth text makes it a sign-in, anything else "didn't start".
+#[test]
+fn a_server_that_did_not_start() {
+ let f = not_started("github: it failed to start", &servers()).unwrap();
+ assert_eq!(f.cause, Cause::NotStarted);
+ assert_eq!(text(&f, "Ben"), "GitHub didn't start for Ben, so its tools weren't available. See Settings › Connections.");
+ assert_eq!(not_started("github: authentication required", &servers()).unwrap().cause, Cause::SignIn);
+ assert!(not_started("nobody: failed", &servers()).is_none());
+}
+
+/// Two failures of one connection give one line; a failure a retry fixed gives none.
+#[test]
+fn one_line_per_connection_per_turn() {
+ let mut w = Watch::default();
+ let Next::Wait(gen) = w.failed(gh()) else { panic!("first failure waits") };
+ assert_eq!(w.failed(gh()), Next::Post(gh()));
+ assert_eq!(w.failed(gh()), Next::Nothing);
+ assert_eq!(w.due("mcp:s-gh", gen), None);
+ assert!(w.finish().is_empty());
+
+ // Failure, then a retry that works: nothing
+ let mut w = Watch::default();
+ let Next::Wait(gen) = w.failed(gh()) else { panic!() };
+ assert!(w.succeeded("mcp:s-gh"));
+ assert_eq!(w.due("mcp:s-gh", gen), None);
+ assert!(w.finish().is_empty());
+ assert!(!w.was_posted("mcp:s-gh"));
+
+ // A failure, a retry fixing it, then failing again later: the new failure gets its own grace
+ let Next::Wait(gen2) = w.failed(gh()) else { panic!() };
+ assert_eq!(w.due("mcp:s-gh", gen), None, "an old timer doesn't post the new failure");
+ assert_eq!(w.due("mcp:s-gh", gen2), Some(gh()));
+ assert!(w.was_posted("mcp:s-gh"));
+}
+
+/// The turn ending posts what still waits, oldest first; a server that didn't start posts at once.
+#[test]
+fn the_end_of_the_turn_posts_what_waits() {
+ let mut w = Watch::default();
+ assert!(matches!(w.failed(down("b")), Next::Wait(_)));
+ assert!(matches!(w.failed(down("a")), Next::Wait(_)));
+ let ns = Failure { cause: Cause::NotStarted, ..down("c") };
+ assert_eq!(w.failed(ns.clone()), Next::Post(ns));
+ let keys: Vec<String> = w.finish().into_iter().map(|f| f.conn.key).collect();
+ assert_eq!(keys, ["b", "a"]);
+ assert_eq!(w.failed(down("a")), Next::Nothing);
+}
+
+/// A runaway turn can't track failures without bound.
+#[test]
+fn failures_per_turn_are_capped() {
+ let mut w = Watch::default();
+ for i in 0..MAX_KEYS {
+ assert!(matches!(w.failed(down(&format!("k{i}"))), Next::Wait(_)));
+ }
+ assert_eq!(w.failed(down("one-more")), Next::Nothing);
+}
+
+fn kwant(id: &str, name: &str) -> crate::db::models::Kwant {
+ serde_json::from_value(json!({
+ "id": id, "name": name, "title": "", "persona_prompt": "", "avatar_sprite": "", "driver_type": "claude",
+ "preferred_model": "", "temperature": 0.5, "max_tokens": 1000, "level": 1, "turns_completed": 0, "created_at": null,
+ }))
+ .unwrap()
+}
+
+fn line_msg(id: &str, kwant_id: &str, key: &str, at: DateTime<Utc>, needs_you: bool, resolved: bool) -> Message {
+ let mut v = meta(&gh(), kwant_id, "Ben", "t");
+ v["key"] = json!(key);
+ v["needs_you"] = json!(needs_you);
+ if resolved {
+ v["resolved_at"] = json!(at);
+ }
+ serde_json::from_value(json!({
+ "id": id, "channel_id": null, "direct_kwant_id": kwant_id, "sender_role": "kwant", "sender_id": "Ben",
+ "text": "x", "reasoning_content": null, "tool_calls": null, "tokens_used": 0, "created_at": at,
+ "meta": v.to_string(),
+ }))
+ .unwrap()
+}
+
+/// "Needs you" lists open sign-in lines: newest per bot and connection, not resolved, not old,
+/// not "down" lines, not bots outside the space.
+#[test]
+fn needs_you_lists_open_sign_in_lines() {
+ let now = Utc::now();
+ let kwants = [kwant("k1", "Ben"), kwant("k2", "Ann")];
+ let lines = [
+ line_msg("m1", "k1", "mcp:s-gh", now - Span::minutes(1), true, false),
+ line_msg("m2", "k1", "mcp:s-gh", now - Span::minutes(5), true, false),
+ line_msg("m3", "k2", "mcp:s-gh", now - Span::minutes(2), true, true),
+ line_msg("m4", "k2", "composio:gmail", now - Span::days(NEEDS_YOU_DAYS + 1), true, false),
+ line_msg("m5", "k2", "mcp:s-x", now - Span::minutes(3), false, false),
+ line_msg("m6", "k9", "mcp:s-gh", now - Span::minutes(3), true, false),
+ ];
+ let items = needs_you_items(&lines, &kwants, now);
+ assert_eq!(items.len(), 1, "{items:?}");
+ let item = &items[0].1;
+ assert_eq!(item["kind"], "connection");
+ assert_eq!(item["message_id"], "m1");
+ assert_eq!(item["kwant_name"], "Ben");
+ assert_eq!(item["direct_kwant_id"], "k1");
+ assert_eq!(item["fix"]["opens"], "connections");
+ assert_eq!(item["text"], "GitHub stopped working for Ben: it needs you to sign in again.");
+}
+
+/// The Inbox row is worded like the chat line: a sign-in, or an app to connect again.
+#[test]
+fn inbox_title_follows_the_cause() {
+ assert_eq!(inbox_title("Gmail", Cause::SignIn.as_str(), "Ben"), "Gmail needs you to sign in again for Ben");
+ assert_eq!(
+ inbox_title("Google Calendar", Cause::Reconnect.as_str(), "TechLead"),
+ "Google Calendar needs to be connected again for TechLead"
+ );
+ // A line saved without a cause reads as a sign-in, as before
+ assert_eq!(inbox_title("GitHub", "", "Ann"), "GitHub needs you to sign in again for Ann");
+}
+
+/// A long reason is cut before it is kept.
+#[test]
+fn reasons_are_cut() {
+ let long = format!("401 Unauthorized {}", "x".repeat(2000));
+ let f = classify("mcp__github__x", &json!({}), &long, &servers()).unwrap();
+ assert!(f.detail.unwrap().chars().count() <= MAX_DETAIL + 1);
+}
diff --git a/src/server/waiting.rs b/src/server/waiting.rs
index ee46c323..94261329 100644
--- a/src/server/waiting.rs
+++ b/src/server/waiting.rs
@@ -245,6 +245,8 @@ pub async fn list(State(state): State<AppState>, super::spaces::Scope(space): su
}
// Fix-it items past their PR's daily turn cap (dev::fix_it)
items.extend(super::dev::fix_it::needs_you(&state, space.as_str(), &kwants).await);
+ // Connections only the person can fix (0.9.5): a sign-in that expired, an app to connect again
+ items.extend(super::tool_failures::needs_you(&state, &kwants).await);
items.sort_by_key(|(at, _)| *at);
let mut items: Vec<Value> = items.into_iter().map(|(_, v)| v).collect();
// Today's spending stop holds routines, goals, missions and AutoFix: one item, first, while it
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 019797f7..93f40369 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -16,6 +16,8 @@
//! 500 test stub" as claude's error result / as plain text, once per tag.
//! - `FAILSTEP:<tag>` / `BLOCKSTEP:<tag>` in the current request (not the history): run a Bash
//! tool step that fails, then end on a plan ("I'll retry the render…") / on a `Blocked:` line.
+//! - `STREAMLINES:<base64 text>`: print that text (claude `stream-json` lines: an init line, tool
+//! calls and their results) before the reply; once per marker.
//!
//! Each test file that uses it is its own binary, because it changes PATH.
#![allow(dead_code)]
@@ -109,6 +111,15 @@ if fs:
print(json.dumps({"type": "result", "is_error": False, "num_turns": 2,
"result": "The render command was refused (" + tag + ").\n\n" + end}))
sys.exit(0)
+# STREAMLINES:<base64>: print those stream-json lines first (tool calls and results), once per marker
+sl = re.findall(r"STREAMLINES:([A-Za-z0-9+/=]+)", prompt)
+if sl:
+ import hashlib
+ sl_flag = os.path.join(os.path.dirname(out_dir), "streamed-" + hashlib.sha1(sl[-1].encode()).hexdigest())
+ if not os.path.exists(sl_flag):
+ open(sl_flag, "w").close()
+ sys.stdout.write(base64.b64decode(sl[-1]).decode())
+ sys.stdout.flush()
# REPLYTEXT:<base64>: reply exactly that text
rt = re.findall(r"REPLYTEXT:([A-Za-z0-9+/=]+)", prompt)
if rt:
@@ -185,6 +196,13 @@ pub fn call_tool_marker(tool: &str, args: Value) -> String {
format!("CALLTOOL:{tool}:{}", base64::engine::general_purpose::STANDARD.encode(args.to_string()))
}
+/// A prompt marker that makes the fake CLI print these `stream-json` lines before its reply.
+pub fn stream_lines_marker(lines: &[Value]) -> String {
+ use base64::Engine;
+ let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
+ format!("STREAMLINES:{}", base64::engine::general_purpose::STANDARD.encode(text))
+}
+
pub async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
call_with(app, method, uri, body, &[]).await
}
diff --git a/tests/tool_failures_test.rs b/tests/tool_failures_test.rs
new file mode 100644
index 00000000..631081ab
--- /dev/null
+++ b/tests/tool_failures_test.rs
@@ -0,0 +1,198 @@
+//! 0.9.5: a connection failing says so in the chat (release-095/tool-failure-line/brief.md).
+//! Full turns on the fake claude, which prints the tool calls and results each test gives it.
+
+mod common;
+
+use axum::http::StatusCode;
+use common::*;
+use kwnt::db::models::{McpServer, Message};
+use kwnt::db::spaces::SpaceId;
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+
+async fn server(env: &Env, name: &str) -> McpServer {
+ env.state
+ .db
+ .create_mcp_server(
+ &SpaceId::default_space(),
+ &McpServer {
+ id: String::new(),
+ name: name.into(),
+ transport: "stdio".into(),
+ command: Some("/usr/bin/true".into()),
+ args: vec![],
+ url: None,
+ env: BTreeMap::new(),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs: 30,
+ created_at: None,
+ },
+ )
+ .await
+ .unwrap()
+}
+
+/// A claude tool call and its result, as `stream-json` lines. `error` makes the call fail with it.
+fn call(id: &str, tool: &str, error: Option<&str>) -> [Value; 2] {
+ let result = match error {
+ Some(e) => {
+ json!({"type": "tool_result", "tool_use_id": id, "is_error": true, "content": [{"type": "text", "text": e}]})
+ }
+ None => json!({"type": "tool_result", "tool_use_id": id, "content": "ok"}),
+ };
+ [
+ json!({"type": "assistant", "message": {"content": [{"type": "tool_use", "id": id, "name": tool, "input": {}}]}}),
+ json!({"type": "user", "message": {"content": [result]}}),
+ ]
+}
+
+/// Runs one turn of bot A in its direct chat that prints `lines`, and waits for its reply.
+async fn turn(env: &Env, tag: &str, lines: &[Value]) {
+ send_direct(env, &env.a, &format!("go {} REPLYTAG:{tag}", stream_lines_marker(lines)), json!({})).await;
+ wait_reply(env, &env.a, &format!("answer {tag}")).await;
+}
+
+fn meta(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+async fn failure_lines(env: &Env) -> Vec<(Message, Value)> {
+ messages(env, &env.a)
+ .await
+ .into_iter()
+ .map(|m| (meta(&m), m))
+ .filter(|(v, _)| v["kind"] == "tool_failure")
+ .map(|(v, m)| (m, v))
+ .collect()
+}
+
+async fn waiting(env: &Env) -> Vec<Value> {
+ let (s, v) = common::call(&env.app, "GET", "/api/waiting", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v["items"].as_array().unwrap().iter().filter(|i| i["kind"] == "connection").cloned().collect()
+}
+
+/// The Inbox's Waiting-on-you rows for a connection.
+async fn inbox_rows(env: &Env) -> Vec<Value> {
+ let (s, v) = common::call(&env.app, "GET", "/api/inbox", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v["items"].as_array().unwrap().iter().filter(|i| i["kind"] == "connection").cloned().collect()
+}
+
+async fn status_of(env: &Env, kwant: &str) -> Value {
+ let (s, v) = common::call(&env.app, "GET", "/api/bots/status", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ v["bots"].as_array().unwrap().iter().find(|b| b["kwant_id"] == kwant).cloned().unwrap()
+}
+
+/// A 401 posts one line with a fix link; the bot needs the person until a call through that
+/// connection works again.
+#[tokio::test]
+async fn a_401_posts_one_line_with_a_fix_link_and_needs_you_until_it_works() {
+ let env = setup().await;
+ let gh = server(&env, "github").await;
+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap().name;
+
+ turn(&env, "tf401", &call("tf401_1", "mcp__github__list_issues", Some("HTTP 401 Unauthorized: Bad credentials"))).await;
+ let lines = failure_lines(&env).await;
+ assert_eq!(lines.len(), 1, "{lines:?}");
+ let (m, v) = &lines[0];
+ assert_eq!(m.sender_role, "kwant");
+ assert_eq!(
+ m.text,
+ format!("GitHub stopped working for {bot}: it needs you to sign in again. Reconnect it in Settings › Connections.")
+ );
+ assert_eq!(v["cause"], "sign_in");
+ assert_eq!(v["needs_you"], true);
+ assert_eq!(v["fix"], json!({"label": "Reconnect", "opens": "connections", "connection_id": format!("mcp:{}", gh.id)}));
+ assert_eq!(v["tool"], "github · list_issues");
+ // The line comes before the turn's reply
+ let all = messages(&env, &env.a).await;
+ let pos = |id: &str| all.iter().position(|x| x.id == id).unwrap();
+ let reply = all.iter().find(|x| x.text.contains("answer tf401")).unwrap();
+ assert!(pos(&m.id) < pos(&reply.id), "line after reply");
+
+ // Needs you: in the person's list and on the bot
+ let items = waiting(&env).await;
+ assert_eq!(items.len(), 1, "{items:?}");
+ assert_eq!(items[0]["message_id"], m.id.as_str());
+ assert_eq!(items[0]["kwant_id"], env.a.as_str());
+ assert_eq!(items[0]["fix"]["connection_id"], format!("mcp:{}", gh.id));
+ let st = status_of(&env, &env.a).await;
+ assert_eq!((st["status"].as_str(), st["reason_code"].as_str()), (Some("needs_you"), Some("needs_sign_in")), "{st}");
+ assert_eq!(st["waits_on"]["label"], "GitHub");
+ assert_eq!(status_of(&env, &env.b).await["status"], "available");
+ // F8: the Inbox lists it in Waiting on you, with Reconnect to Settings › Connections
+ let rows = inbox_rows(&env).await;
+ assert_eq!(rows.len(), 1, "{rows:?}");
+ assert_eq!(rows[0]["title"], format!("GitHub needs you to sign in again for {bot}"));
+ assert_eq!(rows[0]["group"], "waiting_on_you");
+ assert_eq!(rows[0]["id"], m.id.as_str());
+ assert_eq!(rows[0]["fix"]["opens"], "connections");
+ assert_eq!(rows[0]["link"]["direct_kwant_id"], env.a.as_str());
+
+ // Connected again: the next call through github works, and it no longer needs the person
+ turn(&env, "tf401ok", &call("tf401_2", "mcp__github__list_issues", None)).await;
+ assert!(waiting(&env).await.is_empty());
+ assert!(inbox_rows(&env).await.is_empty(), "the Inbox row goes once it works");
+ assert_eq!(status_of(&env, &env.a).await["status"], "available");
+ let lines = failure_lines(&env).await;
+ assert_eq!(lines.len(), 1, "a working call posts nothing");
+ assert!(lines[0].1["resolved_at"].is_string(), "{}", lines[0].1);
+}
+
+/// Two failures of one connection in a turn give one line.
+#[tokio::test]
+async fn two_failures_of_one_connection_give_one_line() {
+ let env = setup().await;
+ server(&env, "github").await;
+ server(&env, "notion").await;
+ let mut lines = Vec::new();
+ lines.extend(call("tf2_1", "mcp__github__list_issues", Some("401 Unauthorized")));
+ lines.extend(call("tf2_2", "mcp__github__get_repo", Some("401 Unauthorized")));
+ lines.extend(call("tf2_3", "mcp__github__get_repo", Some("token expired")));
+ // A tool's own error isn't the connection's
+ lines.extend(call("tf2_4", "mcp__notion__search", Some("invalid arguments: query is required")));
+ turn(&env, "tf2", &lines).await;
+ let lines = failure_lines(&env).await;
+ assert_eq!(lines.len(), 1, "{lines:?}");
+ assert_eq!(lines[0].1["connection"], "GitHub");
+ assert_eq!(waiting(&env).await.len(), 1);
+}
+
+/// A failure the bot's retry fixed posts nothing, and the bot doesn't need the person.
+#[tokio::test]
+async fn a_failure_a_retry_fixed_gives_no_line() {
+ let env = setup().await;
+ server(&env, "github").await;
+ let mut lines = Vec::new();
+ lines.extend(call("tfr_1", "mcp__github__list_issues", Some("502 Bad Gateway")));
+ lines.extend(call("tfr_2", "mcp__github__list_issues", None));
+ turn(&env, "tfr", &lines).await;
+ assert!(failure_lines(&env).await.is_empty());
+ assert!(waiting(&env).await.is_empty());
+ assert_eq!(status_of(&env, &env.a).await["status"], "available");
+}
+
+/// A server that failed to start says so once; one that needs a sign-in needs the person.
+#[tokio::test]
+async fn servers_that_did_not_start_say_so() {
+ let env = setup().await;
+ server(&env, "github").await;
+ server(&env, "notion").await;
+ let init = json!({"type": "system", "subtype": "init", "tools": [], "mcp_servers": [
+ {"name": "github", "status": "needs-auth"}, {"name": "notion", "status": "failed"}, {"name": "kwnt_tools", "status": "connected"}]});
+ let mut lines = vec![init];
+ lines.extend(call("tfs_1", "mcp__notion__search", Some("connection closed")));
+ turn(&env, "tfs", &lines).await;
+ let lines = failure_lines(&env).await;
+ let causes: Vec<(String, String)> =
+ lines.iter().map(|(_, v)| (v["connection"].as_str().unwrap().into(), v["cause"].as_str().unwrap().into())).collect();
+ assert_eq!(causes.len(), 2, "{causes:?}");
+ assert!(causes.contains(&("GitHub".into(), "sign_in".into())), "{causes:?}");
+ assert!(causes.contains(&("Notion".into(), "not_started".into())), "{causes:?}");
+ let items = waiting(&env).await;
+ assert_eq!(items.len(), 1, "{items:?}");
+ assert_eq!(items[0]["connection"], "GitHub");
+}