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: runs never stop silently (#541)

Oleksandr Ivanchenko010a9e376911
diff --git a/frontend/src/away.ts b/frontend/src/away.ts
index 123a1631..fd2af8fa 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' | 'connection';
+export type AwayKind = 'question' | 'approval' | 'delegation' | 'routine_run' | 'watch' | 'stopped' | 'connection';
export type AwaySection = 'waiting' | 'finished' | 'failed';
export type ApprovalDecision = 'allow_once' | 'always_allow' | 'deny';
@@ -36,6 +36,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, stopped items only: the chat notice that carries Retry or Continue, what resumes the work
+ * (null: Retry in the chat resends the person's message), and the browser step it waits on. */
+ message_id?: string | null;
+ retry?: { type: 'continue' } | { type: 'approval'; approval_id: string } | null;
+ human_step_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. */
@@ -122,6 +127,9 @@ export function itemLabel(item: Pick<AwayItem, 'kind' | 'status' | 'cause'>): {
return item.status === 'waiting' ? { label: 'Still open', tone: 'sky' } : { label: 'Needs approval', tone: 'amber' };
case 'watch':
return { label: 'Watch', tone: 'amber' };
+ case 'stopped':
+ // 0.9.5: a bot's work stopped and waits for the person; the title says why and what resumes it.
+ return { label: 'Stopped', 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' };
@@ -254,8 +262,22 @@ export const awayApi = {
resolve: (id: string, decision: ApprovalDecision) => call<unknown>('POST', `/api/approvals/${enc(id)}/resolve`, { decision }),
/** Approval records with this stored status, newest first (`answered_via` says where). */
approvals: (status: string) => call<unknown>('GET', `/api/approvals?status=${enc(status)}`),
+ /** 0.9.5: ask again for an approval that expired unanswered (starts a new turn; grants nothing). */
+ retryApproval: (approvalId: string) => call<unknown>('POST', `/api/approvals/${enc(approvalId)}/retry`),
};
+/**
+ * 0.9.5: the one action a stopped item offers in place. An expired approval is retried from the Inbox
+ * itself; every other stop resumes in its chat (the notice there has Retry or Continue, a browser step
+ * its Done), so the row opens the chat.
+ */
+export function stoppedAction(item: Pick<AwayItem, 'kind' | 'retry'>): { kind: 'retry_approval'; approvalId: string } | { kind: 'open_chat' } | null {
+ if (item.kind !== 'stopped') return null;
+ const r = item.retry;
+ if (r && r.type === 'approval' && r.approval_id) return { kind: 'retry_approval', approvalId: r.approval_id };
+ return { kind: 'open_chat' };
+}
+
/** SSE events that can change what the page shows, so the badge re-counts. */
const AWAY_EVENTS = new Set([
'question_updated', 'QuestionUpdated',
diff --git a/frontend/src/chatsTab.ts b/frontend/src/chatsTab.ts
index 7043e744..4ce2c559 100644
--- a/frontend/src/chatsTab.ts
+++ b/frontend/src/chatsTab.ts
@@ -55,6 +55,8 @@ export function needsYouRows(waiting: AwayItem[], openSteps: Record<string, numb
for (const item of waiting) {
if (item.kind === 'approval') put({ kwant_id: item.kwant_id, line: approvalLine(item.tool_name), item });
else if (item.kind === 'question') put({ kwant_id: item.kwant_id, line: 'Asked you a question', item });
+ // 0.9.5: work that stopped and waits on the person, in its own words ("Ben needs you to sign in to …")
+ else if (item.kind === 'stopped') put({ kwant_id: item.kwant_id, line: item.title || 'Stopped: needs you to carry on', item });
}
for (const [id, n] of Object.entries(openSteps)) if (n > 0) put({ kwant_id: id, line: 'Needs you in the browser' });
const last = Number.POSITIVE_INFINITY;
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index c0ab0489..2687aadf 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -72,13 +72,14 @@ import { parseRoutingMeta, ranOnAccount, routingLine } from '../spaces';
import { SetupNeededCard, parseSetupMeta } from './SetupNeededCard';
import { ConnectionSuggestionMeta, parseConnectionMeta } from '../connectionSuggestions';
import { routeChipLabel, routeReasonText } from '../routeReason';
-import { BudgetPausedNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
+import { BudgetPausedNotice, ExpiredApprovalNotice, HandoffCappedNotice, InterruptedNotice, SystemNotice } from './SystemNotice';
import { chainBudgetApi, parseBudgetPaused, parseHandoffCapped } from '../chainBudget';
import { parseSpendStopped } from '../spendStop';
import { SpendStoppedNotice } from './SpendStop';
+import { awayApi } from '../away';
import { parseBudgetNotice } from '../botBudget';
import { BudgetNotice, BudgetPausedBanner, useBudgets } from './BotBudget';
-import { isSystemNotice, parseInterruption, retryTargets } from '../interruptions';
+import { isSystemNotice, parseExpiredApproval, parseInterruption, retryTargets } from '../interruptions';
import { parseIsolationFailed, parseRequestLimit } from '../isolationNotice';
import { IsolationNotice, RequestLimitNotice } from './IsolationNotice';
import { IDEA_MAX, isIdeaCommand } from '../ideas';
@@ -1417,6 +1418,18 @@ export const ChatView: React.FC<ChatViewProps> = ({
flash={flashId === msg.id}
/>
);
+ const expired = parseExpiredApproval(msg);
+ if (expired)
+ return (
+ <ExpiredApprovalNotice
+ key={msg.id}
+ messageId={msg.id}
+ text={msg.text}
+ expired={expired}
+ onRetry={canRun === false ? undefined : awayApi.retryApproval}
+ flash={flashId === msg.id}
+ />
+ );
if (isSystemNotice(msg) && !parseAttachments(msg.meta).length)
return <SystemNotice key={msg.id} messageId={msg.id} text={msg.text} flash={flashId === msg.id} />;
const isUser = msg.sender_role === 'user';
diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsx
index adf746db..8dfae87e 100644
--- a/frontend/src/components/InboxNew.tsx
+++ b/frontend/src/components/InboxNew.tsx
@@ -30,7 +30,7 @@ import { type DoneApi, type DoneDetailData, type MessageTarget, DoneChips, DoneI
import { DONE_EMPTY, DONE_FOOTER, changedState, doneTitle, isDoneGroup, isRoutineItem, isUnread, metaLine, rowKicker, sectionItems, teamSize, unreadLine } from '../doneAway';
import { usePhoneLayout } from '../usePhoneLayout';
import { approvalFromAway, awayTitle, lateAnswerText } from '../approvals';
-import { ApprovalDecision, AwayError, AwayItem, actionFailureNotice, awayApi, awaySummary, itemLabel, windowLabel } from '../away';
+import { ApprovalDecision, AwayError, AwayItem, actionFailureNotice, awayApi, awaySummary, itemLabel, stoppedAction, windowLabel } from '../away';
import { InboxGroup, InboxItem, ReviewItem, isBeingChecked, isReview, pendingHeld, reviewWord } from '../api/inbox';
import {
BatchRow,
@@ -186,7 +186,7 @@ const AwaySubline: React.FC<{ item: InboxItem }> = ({ item }) => {
const { label, tone } = itemLabel(item as AwayItem);
const toneText = tone === 'amber' ? 'text-amber-300' : tone === 'rose' ? 'text-rose-300' : tone === 'emerald' ? 'text-teal-300' : tone === 'sky' ? 'text-sky-300' : 'text-zinc-400';
const sum = awaySummary(item as AwayItem);
- const showSum = sum && item.kind !== 'approval' && !(item.kind === 'question' && item.choices?.length);
+ const showSum = sum && item.kind !== 'approval' && item.kind !== 'stopped' && !(item.kind === 'question' && item.choices?.length);
// F6: an approval titled with its own question still says what the bot wants to use: "Needs approval · use gmail".
const asked = item.kind === 'approval' && typeof item.question === 'string' && !!item.question.trim();
const use = asked ? awayTitle(item as AwayItem) : '';
@@ -212,6 +212,8 @@ interface RowProps {
onPick: (i: InboxItem) => void;
onAnswer: (i: InboxItem, choice: number) => void;
onResolve: (i: InboxItem, d: ApprovalDecision) => void;
+ /** 0.9.5: Retry on a stopped item whose approval expired unanswered. */
+ onRetry?: (i: InboxItem, approvalId: string) => void;
/** A routine's review task in Done: its run's first line, as the run's own row would show it. */
doneSummary?: string | null;
/** The conversation it happened in ("@Spring launch"), said before the bot's name like the mockup. */
@@ -220,7 +222,8 @@ interface RowProps {
onOpenConnections?: () => void;
}
-const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve, doneSummary, place, onOpenConnections }) => {
+const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve, onRetry, doneSummary, place, onOpenConnections }) => {
+ const stopped = isReview(item) ? null : stoppedAction(item as AwayItem);
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.
@@ -331,6 +334,21 @@ const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, o
</div>
)}
+ {stopped?.kind === 'retry_approval' && onRetry && (
+ <div className="px-3 pb-3 pl-[54px]">
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => onRetry(item, stopped.approvalId)}
+ className={`${plainBtn} px-3 text-xs ${wide ? 'h-7' : 'h-11'}`}
+ data-stopped-retry={item.id}
+ >
+ <RotateCcw size={12} aria-hidden="true" />
+ Retry
+ </button>
+ </div>
+ )}
+
{item.kind === 'approval' && (
<div className="px-3 pb-1 pl-[54px] [&>div]:my-0 [&>div]:mb-2">
<ModernApprovalCard approval={approvalFromAway(item as AwayItem)} disabled={disabled} onResolve={(_, d) => onResolve(item, d)} />
@@ -794,6 +812,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({
};
const onAnswer = (item: InboxItem, choice: number) => act(item, () => awayApi.answer(item.id, choice));
+ const onRetry = (item: InboxItem, approvalId: string) => act(item, () => awayApi.retryApproval(approvalId));
const onResolve = (item: InboxItem, decision: ApprovalDecision) =>
act(
item,
@@ -922,6 +941,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({
onPick={pick}
onAnswer={onAnswer}
onResolve={onResolve}
+ onRetry={onRetry}
doneSummary={sections.runFor[i.id]?.summary || null}
place={i.link?.channel_id ? (placeName?.(i.link.channel_id) ?? null) : null}
onOpenConnections={onOpenConnections}
diff --git a/frontend/src/components/SystemNotice.tsx b/frontend/src/components/SystemNotice.tsx
index a9ca4ff7..aaad1aca 100644
--- a/frontend/src/components/SystemNotice.tsx
+++ b/frontend/src/components/SystemNotice.tsx
@@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from 'react';
import { AlertTriangle, Check, Gauge, Info, Loader2, PauseCircle, Play, RotateCcw } from 'lucide-react';
import { BudgetPausedMeta, HandoffCappedMeta, handoffCappedText, isAlreadyContinued, isChainGone } from '../chainBudget';
import { compactTokens } from '../modelUsage';
-import { Interruption, RetryState, RetryTarget, interruptionText, runRetryOnce } from '../interruptions';
+import { ExpiredApproval, Interruption, RetryState, RetryTarget, interruptionText, runRetryOnce } from '../interruptions';
/** A note kwnt itself wrote (e.g. "Growth wasn't asked: …"): a quiet line, not a bot's reply. */
export const SystemNotice: React.FC<{ messageId: string; text: string; flash?: boolean }> = ({ messageId, text, flash }) => (
@@ -53,7 +53,7 @@ export const InterruptedNotice: React.FC<InterruptedNoticeProps> = ({ messageId,
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<p id={headingId} className="flex items-start gap-2 min-w-0 flex-1 basis-56 text-sm text-amber-200 break-words">
<AlertTriangle size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />
- <span className="min-w-0">
+ <span className="min-w-0 whitespace-pre-line">
{interruptionText(interruption)}
{canRetry && state !== 'sent' && <span className="text-amber-200/70"> Retry sends your message again.</span>}
</span>
@@ -244,3 +244,74 @@ export const HandoffCappedNotice: React.FC<HandoffCappedNoticeProps> = ({ messag
</section>
);
};
+
+export interface ExpiredApprovalNoticeProps {
+ messageId: string;
+ text: string;
+ expired: ExpiredApproval;
+ /** Asks again (POST /api/approvals/:id/retry); without it (a read-only view) there's no button. */
+ onRetry?: (approvalId: string) => Promise<unknown>;
+ flash?: boolean;
+}
+
+/** 0.9.5: an approval nobody answered in time, so its step didn't run. Retry starts a turn that asks again. */
+export const ExpiredApprovalNotice: React.FC<ExpiredApprovalNoticeProps> = ({ messageId, text, expired, onRetry, flash }) => {
+ const [state, setState] = useState<'idle' | 'sending' | 'sent' | 'already' | 'error'>('idle');
+ const lock = useRef(false);
+ const headingId = `expired-${messageId}`;
+ const run = async () => {
+ if (!onRetry || lock.current) return;
+ lock.current = true;
+ setState('sending');
+ try {
+ await onRetry(expired.approvalId);
+ setState('sent');
+ } catch (e) {
+ // 409: Retry already ran (here, another tab or the Inbox)
+ if ((e as { status?: number } | null)?.status === 409) return setState('already');
+ lock.current = false;
+ setState('error');
+ }
+ };
+ const done = state === 'sent' || state === 'already';
+ return (
+ <section
+ data-message-id={messageId}
+ data-approval-expired={expired.approvalId}
+ data-state={state}
+ aria-labelledby={headingId}
+ className={`w-full max-w-5xl rounded-xl border border-amber-500/30 bg-amber-950/20 px-3.5 py-2.5 sm:px-4 ${flash ? 'kw-flash' : ''}`}
+ >
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
+ <p id={headingId} className="flex items-start gap-2 min-w-0 flex-1 basis-56 text-sm text-amber-200 break-words">
+ <AlertTriangle size={15} className="mt-0.5 shrink-0 text-amber-400" aria-hidden="true" />
+ <span className="min-w-0">{text}</span>
+ </p>
+ {onRetry && (
+ <button
+ type="button"
+ onClick={run}
+ disabled={state === 'sending' || done}
+ aria-describedby={headingId}
+ data-approval-retry
+ className="shrink-0 inline-flex items-center justify-center gap-1.5 min-h-[36px] px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors cursor-pointer disabled:cursor-default text-amber-100 bg-amber-500/15 border-amber-500/40 hover:bg-amber-500/25 disabled:opacity-70 disabled:hover:bg-amber-500/15 focus-visible:outline focus-visible:outline-2 focus-visible:outline-amber-400"
+ >
+ {state === 'sending' ? (
+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : done ? (
+ <Check size={13} aria-hidden="true" />
+ ) : (
+ <RotateCcw size={13} aria-hidden="true" />
+ )}
+ <span>{state === 'sending' ? 'Asking again…' : state === 'sent' ? 'Asked again' : state === 'already' ? 'Already retried' : 'Retry'}</span>
+ </button>
+ )}
+ </div>
+ {state === 'error' && (
+ <p role="alert" className="mt-2 pl-[23px] text-[11px] text-rose-300">
+ Couldn't retry. Try again.
+ </p>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/interruptions.ts b/frontend/src/interruptions.ts
index df39bbb9..3ee709c2 100644
--- a/frontend/src/interruptions.ts
+++ b/frontend/src/interruptions.ts
@@ -1,16 +1,32 @@
// Replies that ended without an answer: cut off by a restart (system note with
-// `turn_interrupted` meta) or stopped by the stall watchdog (the bot's own message with
-// `turn_stalled` meta). Both get a notice with Retry, which resends the person's message.
+// `turn_interrupted` meta), stopped by the stall watchdog (the bot's own message with
+// `turn_stalled` meta) or failed (the bot's own message with `turn_failed` meta, 0.9.5). Each gets
+// a notice with Retry, which resends the person's message.
import type { ChatMessage } from './components/ChatView';
import { AttachmentRef, parseAttachments } from './attachments';
import { parseMetaObject } from './questions';
import { isIsolationNotice } from './isolationNotice';
export interface Interruption {
- kind: 'restart' | 'stall';
+ kind: 'restart' | 'stall' | 'failed';
botName: string;
/** Seconds of silence before the watchdog stopped the reply (stall only). */
secs?: number;
+ /** What went wrong, in the saved message's own words without its "⚠️ [Bot]" tag (failed, and a restart mid outward step). */
+ detail?: string;
+ /**
+ * 0.9.5: the restart cut off a step that reaches outside (a send, a post, a push, a payment). It may
+ * already have gone out, so there's no Retry (that resends the whole request): the notice asks the
+ * person to tell the bot in the chat whether to do it again.
+ */
+ outwardStep?: string;
+}
+
+/** A failed reply's text without its leading "⚠️ [Bot] " tag. */
+export function failedDetail(text: string, botName: string): string {
+ const t = text.trim().replace(/^⚠️\s*/u, '');
+ const tag = `[${botName}] `;
+ return (t.startsWith(tag) ? t.slice(tag.length) : t.replace(/^\[[^\]\n]{1,80}\] /, '')).trim();
}
// Rows saved before the watchdog tagged its message with `turn_stalled` meta carry only this text.
@@ -21,6 +37,9 @@ export function parseInterruption(msg: ChatMessage): Interruption | null {
const m = parseMetaObject(msg.meta);
if (m?.kind !== 'turn_interrupted' || m.interrupted !== true) return null;
const name = typeof m.kwant_name === 'string' && m.kwant_name.trim() ? m.kwant_name : 'The bot';
+ if (typeof m.outward_step === 'string' && m.outward_step) {
+ return { kind: 'restart', botName: name, outwardStep: m.outward_step, detail: msg.text.trim() || undefined };
+ }
return { kind: 'restart', botName: name };
}
if (msg.sender_role === 'kwant') {
@@ -31,6 +50,12 @@ export function parseInterruption(msg: ChatMessage): Interruption | null {
const secs = typeof m.stall_secs === 'number' && m.stall_secs > 0 ? m.stall_secs : undefined;
return { kind: 'stall', botName: name, secs };
}
+ // 0.9.5: a reply that failed (a driver error, the model gave up): Retry like the others
+ if (m?.kind === 'turn_failed') {
+ const name = typeof m.kwant_name === 'string' && m.kwant_name.trim() ? m.kwant_name : msg.sender_id || 'The bot';
+ const detail = failedDetail(msg.text, name);
+ return { kind: 'failed', botName: name, detail: detail || undefined };
+ }
const s = STALL_RE.exec(msg.text.trim());
if (s) return { kind: 'stall', botName: s[1], secs: Number(s[2]) };
}
@@ -38,6 +63,8 @@ export function parseInterruption(msg: ChatMessage): Interruption | null {
}
export function interruptionText(i: Interruption): string {
+ if (i.kind === 'failed') return i.detail || `${i.botName} couldn't finish this reply.`;
+ if (i.outwardStep) return i.detail || `${i.botName}'s reply was cut off when the app restarted, in the middle of a step that may already have gone out. Tell ${i.botName} in the chat whether to do it again.`;
return i.kind === 'restart'
? `${i.botName}'s reply was cut off when the app restarted.`
: i.secs
@@ -60,7 +87,10 @@ export function retryTargets(messages: ChatMessage[]): Map<string, RetryTarget>
const msg = messages[i];
if (msg.sender_role === 'user') return out;
// Isolation refusals and the request limit end a reply too (agents-in-vm notices 1–7).
- if (!parseInterruption(msg) && !isIsolationNotice(msg)) continue;
+ const parsed = parseInterruption(msg);
+ if (!parsed && !isIsolationNotice(msg)) continue;
+ // A step that may already have gone out is never resent blindly: no Retry (0.9.5)
+ if (parsed?.outwardStep) return out;
for (let j = i - 1; j >= 0; j--) {
const prev = messages[j];
if (prev.sender_role !== 'user') continue;
@@ -100,5 +130,20 @@ export async function runRetryOnce(
}
}
+/** 0.9.5: an approval card that expired unanswered, so its step didn't run; Retry asks again. */
+export interface ExpiredApproval {
+ approvalId: string;
+ botName: string;
+ toolName: string | null;
+}
+
+export function parseExpiredApproval(msg: ChatMessage): ExpiredApproval | null {
+ if (msg.sender_role !== 'system') return null;
+ const m = parseMetaObject(msg.meta);
+ if (m?.kind !== 'approval_expired' || typeof m.approval_id !== 'string' || !m.approval_id) return null;
+ const name = typeof m.kwant_name === 'string' && m.kwant_name.trim() ? m.kwant_name : 'The bot';
+ return { approvalId: m.approval_id, botName: name, toolName: typeof m.tool_name === 'string' ? m.tool_name : null };
+}
+
/** kwnt's own notes (sender "system"): drawn as a notice line, never as a bot's reply. */
export const isSystemNotice = (msg: ChatMessage) => msg.sender_role === 'system';
diff --git a/frontend/tests/noSilentStops.test.mjs b/frontend/tests/noSilentStops.test.mjs
new file mode 100644
index 00000000..8a7d8267
--- /dev/null
+++ b/frontend/tests/noSilentStops.test.mjs
@@ -0,0 +1,147 @@
+// 0.9.5 "Runs never stop silently": stopped items in Needs you and the Inbox, Retry on a failed
+// reply, and Retry on an approval that expired unanswered.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ export { parseInterruption, retryTargets, interruptionText, failedDetail, parseExpiredApproval } from './src/interruptions';
+ export { itemLabel, stoppedAction, normalizeAwayItem } from './src/away';
+ export { needsYouRows } from './src/chatsTab';
+ export { ExpiredApprovalNotice, InterruptedNotice } from './src/components/SystemNotice';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createElement } from 'react';
+`);
+
+// Shaped like away::stopped_items in src/server/away.rs.
+const stopped = (id, kwant_id, title, extra = {}) => ({
+ kind: 'stopped',
+ id,
+ kwant_id,
+ kwant_name: 'Ben',
+ title,
+ summary: title,
+ status: 'open',
+ timestamp: '2026-11-12T10:00:00Z',
+ message_id: 'm1',
+ retry: null,
+ link: { thread_id: null, channel_id: null, direct_kwant_id: kwant_id },
+ ...extra,
+});
+
+test('a stopped item is labelled Stopped and keeps its own words', () => {
+ assert.deepEqual(m.itemLabel({ kind: 'stopped', status: 'open' }), { label: 'Stopped', tone: 'amber' });
+ const item = stopped('w1', 'k1', 'Ben needs you to sign in to tiktok.com in the browser panel, then it continues.');
+ assert.equal(m.normalizeAwayItem(item), item, 'passes through untouched');
+});
+
+test('Needs you lists a stopped bot with the line that says what resumes it', () => {
+ const line = "Ben's reply was cut off when kwant restarted. Retry in the chat sends your message again.";
+ const rows = m.needsYouRows([stopped('w1', 'k1', line)], {}, new Set(['k1']));
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0].line, line);
+ assert.equal(rows[0].item.id, 'w1');
+});
+
+test('an approval outranks a stopped item for the same bot; a browser step alone ranks below it', () => {
+ const approval = { kind: 'approval', id: 'a1', kwant_id: 'k1', kwant_name: 'Ben', title: 't', summary: '', status: 'pending', timestamp: '2026-11-12T11:00:00Z', link: {}, tool_name: 'bash' };
+ const rows = m.needsYouRows([stopped('w1', 'k1', 'Stopped'), approval], {}, new Set(['k1']));
+ assert.equal(rows[0].line, 'Wants to run a command');
+ // The oldest ask's time stays (the stopped item came first)
+ assert.equal(rows[0].at, Date.parse('2026-11-12T10:00:00Z'));
+ const withStep = m.needsYouRows([stopped('w1', 'k1', 'Ben needs you to sign in to x.com in the browser panel, then it continues.')], { k1: 1 }, new Set(['k1']));
+ assert.match(withStep[0].line, /sign in to x\.com/, 'the specific ask wins over "Needs you in the browser"');
+});
+
+test('a stopped item offers Retry in place only for an expired approval', () => {
+ assert.equal(m.stoppedAction({ kind: 'approval', retry: null }), null);
+ assert.deepEqual(m.stoppedAction({ kind: 'stopped', retry: null }), { kind: 'open_chat' });
+ assert.deepEqual(m.stoppedAction({ kind: 'stopped', retry: { type: 'continue' } }), { kind: 'open_chat' });
+ assert.deepEqual(m.stoppedAction({ kind: 'stopped', retry: { type: 'approval', approval_id: 'ap1' } }), { kind: 'retry_approval', approvalId: 'ap1' });
+});
+
+// The failed reply saved by run_kwant_turn_inner (meta from stopped::gave_up_meta or turn_failed_text).
+const failed = (id, text, meta = { kind: 'turn_failed', gave_up: true }) => ({ id, sender_role: 'kwant', sender_id: 'Ben', text, meta: JSON.stringify(meta) });
+const user = (id, text) => ({ id, sender_role: 'user', sender_id: 'me', text, meta: null });
+
+test('a failed reply is an interruption with its own words and gets Retry', () => {
+ const msg = failed('f1', "⚠️ [Ben] Couldn't finish this reply: the model returned an error.\nDetails: 529");
+ const i = m.parseInterruption(msg);
+ assert.equal(i.kind, 'failed');
+ assert.equal(i.botName, 'Ben');
+ assert.equal(m.interruptionText(i), "Couldn't finish this reply: the model returned an error.\nDetails: 529");
+ const targets = m.retryTargets([user('u1', 'make the report'), msg]);
+ assert.deepEqual(targets.get('f1'), { text: 'make the report', attachments: [] });
+ // Once the person writes again, the old notice has no Retry
+ assert.equal(m.retryTargets([user('u1', 'a'), msg, user('u2', 'b')]).size, 0);
+ // turn_failed without gave_up (a driver error) is the same
+ assert.equal(m.parseInterruption(failed('f2', '⚠️ [Ben] boom', { kind: 'turn_failed' })).kind, 'failed');
+ assert.equal(m.interruptionText({ kind: 'failed', botName: 'Ben' }), "Ben couldn't finish this reply.");
+});
+
+test('failedDetail drops only the bot tag', () => {
+ assert.equal(m.failedDetail('⚠️ [Ben] boom', 'Ben'), 'boom');
+ assert.equal(m.failedDetail('⚠️ [Other bot] boom', 'Ben'), 'boom');
+ assert.equal(m.failedDetail('[draft] kept', 'Ben'), 'kept');
+ assert.equal(m.failedDetail('no tag at all', 'Ben'), 'no tag at all');
+});
+
+test('the failed notice shows every line and a Retry button', () => {
+ const html = m.renderToStaticMarkup(
+ m.createElement(m.InterruptedNotice, { messageId: 'f1', interruption: { kind: 'failed', botName: 'Ben', detail: 'line one\nline two' }, retry: { text: 'x', attachments: [] }, onRetry: () => {} }),
+ );
+ assert.match(html, /data-interrupted="failed"/);
+ assert.match(html, /whitespace-pre-line/);
+ assert.match(html, />Retry</);
+});
+
+// The note mcp_runtime::expire_unanswered posts.
+const expiredNote = (id, approval_id = 'ap1') => ({
+ id,
+ sender_role: 'system',
+ sender_id: 'kwnt',
+ text: "Ben stopped waiting for your OK to use bash (no answer in 24 h), so that step didn't run. Retry asks you again.",
+ meta: JSON.stringify({ kind: 'approval_expired', approval_id, kwant_id: 'k1', kwant_name: 'Ben', tool_name: 'bash' }),
+});
+
+test('an expired approval note is parsed; other notes are not', () => {
+ assert.deepEqual(m.parseExpiredApproval(expiredNote('n1')), { approvalId: 'ap1', botName: 'Ben', toolName: 'bash' });
+ assert.equal(m.parseExpiredApproval({ ...expiredNote('n1'), sender_role: 'kwant' }), null);
+ assert.equal(m.parseExpiredApproval({ ...expiredNote('n1'), meta: JSON.stringify({ kind: 'approval_expired' }) }), null);
+ assert.equal(m.parseInterruption(expiredNote('n1')), null, 'not a resend-your-message Retry');
+});
+
+test('the expired approval notice has Retry, and none in a read-only view', () => {
+ const props = { messageId: 'n1', text: 'Ben stopped waiting…', expired: { approvalId: 'ap1', botName: 'Ben', toolName: 'bash' } };
+ const withRetry = m.renderToStaticMarkup(m.createElement(m.ExpiredApprovalNotice, { ...props, onRetry: async () => ({}) }));
+ assert.match(withRetry, /data-approval-expired="ap1"/);
+ assert.match(withRetry, /data-approval-retry/);
+ assert.match(withRetry, />Retry</);
+ const readOnly = m.renderToStaticMarkup(m.createElement(m.ExpiredApprovalNotice, props));
+ assert.doesNotMatch(readOnly, /data-approval-retry/);
+});
+
+test('a restart cut off mid send: the notice says so in its own words and offers no Retry', () => {
+ const user = { id: 'u1', sender_role: 'user', sender_id: 'user', text: 'post the launch note', meta: null };
+ const text = "Ben's reply was cut off when kwant restarted, in the middle of `mcp__slack__send_message`, which may already have gone out. kwant won't run it again by itself. Check whether it went out, then tell Ben in the chat whether to do it again.";
+ const note = {
+ id: 'n1',
+ sender_role: 'system',
+ sender_id: 'kwnt',
+ text,
+ meta: JSON.stringify({ kind: 'turn_interrupted', interrupted: true, kwant_name: 'Ben', outward_step: 'mcp__slack__send_message' }),
+ };
+ const i = m.parseInterruption(note);
+ assert.equal(i.kind, 'restart');
+ assert.equal(i.outwardStep, 'mcp__slack__send_message');
+ assert.equal(m.interruptionText(i), text);
+ assert.equal(m.retryTargets([user, note]).size, 0, 'never resent blindly');
+ const html = m.renderToStaticMarkup(m.createElement(m.InterruptedNotice, { messageId: 'n1', interruption: i, retry: null, onRetry: () => {} }));
+ assert.ok(html.includes('may already have gone out'), html);
+ assert.ok(!html.includes('Retry'), html);
+ // A plain restart keeps its Retry
+ const plain = { ...note, text: 'This reply from Ben was interrupted by a restart.', meta: JSON.stringify({ kind: 'turn_interrupted', interrupted: true, kwant_name: 'Ben' }) };
+ assert.equal(m.retryTargets([user, plain]).get('n1').text, 'post the launch note');
+});
diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rs
index c98d2ac1..a97d23bc 100644
--- a/src/db/approval_modes.rs
+++ b/src/db/approval_modes.rs
@@ -268,34 +268,72 @@ impl Database {
Ok(done.rows_affected())
}
+ /// Whether a card of that turn is still `waiting` for an answer (its Allow resumes the work).
+ pub async fn turn_has_waiting_approval(&self, turn_id: &str) -> Result<bool, DbError> {
+ let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM approvals WHERE turn_id = ?1 AND status = 'waiting'")
+ .bind(turn_id)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n > 0)
+ }
+
/// Answers a `waiting` card once: sets `status` and returns the ticket with its chat. `None`
- /// when it isn't waiting (answered, or never parked) or is older than [`WAITING_APPROVAL_HOURS`],
- /// which is then marked `expired`. Two answers at once: only one gets the ticket.
+ /// when it isn't waiting (answered, or never parked) or is older than [`WAITING_APPROVAL_HOURS`]
+ /// (it stays `waiting` until [`Self::expire_waiting_approvals`] marks it `expired` and the
+ /// person is told). Two answers at once: only one gets the ticket.
pub async fn claim_waiting_approval(
&self,
id: &str,
status: &str,
) -> Result<Option<(super::models::Approval, serde_json::Value)>, DbError> {
let window = format!("-{WAITING_APPROVAL_HOURS} hours");
- sqlx::query("UPDATE approvals SET status = 'expired' WHERE id = ? AND status = 'waiting' AND created_at <= datetime('now', ?)")
- .bind(id)
- .bind(&window)
- .execute(&self.pool)
- .await?;
- let done = sqlx::query("UPDATE approvals SET status = ? WHERE id = ? AND status = 'waiting'")
+ let done = sqlx::query("UPDATE approvals SET status = ? WHERE id = ? AND status = 'waiting' AND created_at > datetime('now', ?)")
.bind(status)
.bind(id)
+ .bind(&window)
.execute(&self.pool)
.await?;
if done.rows_affected() != 1 {
return Ok(None);
}
+ let chat = self.resume_of(id).await?;
+ Ok(self.get_approval(id).await?.map(|a| (a, chat)))
+ }
+
+ async fn resume_of(&self, id: &str) -> Result<serde_json::Value, DbError> {
let resume: Option<(Option<String>,)> =
sqlx::query_as("SELECT resume FROM approvals WHERE id = ?").bind(id).fetch_optional(&self.pool).await?;
- let chat = resume
- .and_then(|r| r.0)
- .and_then(|r| serde_json::from_str(&r).ok())
- .unwrap_or(serde_json::Value::Null);
+ Ok(resume.and_then(|r| r.0).and_then(|r| serde_json::from_str(&r).ok()).unwrap_or(serde_json::Value::Null))
+ }
+
+ /// Cards that waited [`WAITING_APPROVAL_HOURS`] without an answer become `expired`, each once
+ /// (whoever else sweeps), returned with the chat they were in so the person can be told.
+ pub async fn expire_waiting_approvals(&self) -> Result<Vec<(super::models::Approval, serde_json::Value)>, DbError> {
+ let window = format!("-{WAITING_APPROVAL_HOURS} hours");
+ let ids: Vec<(String,)> = sqlx::query_as("SELECT id FROM approvals WHERE status = 'waiting' AND created_at <= datetime('now', ?) ORDER BY created_at")
+ .bind(&window)
+ .fetch_all(&self.pool)
+ .await?;
+ let mut out = Vec::new();
+ for (id,) in ids {
+ let done = sqlx::query("UPDATE approvals SET status = 'expired' WHERE id = ? AND status = 'waiting'").bind(&id).execute(&self.pool).await?;
+ if done.rows_affected() == 1 {
+ if let Some(a) = self.get_approval(&id).await? {
+ out.push((a, self.resume_of(&id).await?));
+ }
+ }
+ }
+ Ok(out)
+ }
+
+ /// The person pressed Retry on an expired card: `expired` → `retried`, once. Returns the
+ /// ticket with its chat; `None` when it isn't expired (already retried, or never expired).
+ pub async fn claim_expired_approval(&self, id: &str) -> Result<Option<(super::models::Approval, serde_json::Value)>, DbError> {
+ let done = sqlx::query("UPDATE approvals SET status = 'retried' WHERE id = ? AND status = 'expired'").bind(id).execute(&self.pool).await?;
+ if done.rows_affected() != 1 {
+ return Ok(None);
+ }
+ let chat = self.resume_of(id).await?;
Ok(self.get_approval(id).await?.map(|a| (a, chat)))
}
diff --git a/src/db/continuity.rs b/src/db/continuity.rs
index f2da5185..3aaea1ea 100644
--- a/src/db/continuity.rs
+++ b/src/db/continuity.rs
@@ -71,7 +71,7 @@ pub struct PinChange {
}
/// A chat turn in progress: where its reply would go.
-#[derive(Debug, Clone, FromRow, PartialEq)]
+#[derive(Debug, Clone, FromRow, PartialEq, Default)]
pub struct RunningTurn {
pub turn_id: String,
pub kwant_id: String,
@@ -80,6 +80,21 @@ pub struct RunningTurn {
pub direct_kwant_id: Option<String>,
pub thread_id: Option<String>,
pub started_at: DateTime<Utc>,
+ /// Whether a stop of this turn asks the person to resume it in Needs you (a person's own
+ /// chat, see `server::stopped`). `None`: written by a kwnt before 0.9.5.
+ #[sqlx(default)]
+ pub asks: Option<bool>,
+ /// The message the turn answers, so a restart can continue it (0.9.5). `None`: an older kwnt.
+ #[sqlx(default)]
+ pub prompt: Option<String>,
+ /// The turn's tool steps so far, newest last, as `server::restart_resume::Step` JSON: what a
+ /// restart cut off mid-call, and what already ran.
+ #[sqlx(default)]
+ pub steps: Option<String>,
+ /// The turn is itself the continuation of one a restart cut off: a second restart asks the
+ /// person instead of continuing again.
+ #[sqlx(default)]
+ pub resumed: Option<bool>,
}
#[derive(Debug, PartialEq)]
@@ -285,6 +300,23 @@ impl Database {
)
.execute(&self.pool)
.await?;
+ // 0.9.5 (additive): whether a restart that cuts it off asks the person in Needs you
+ let has_asks: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pragma_table_info('running_turns') WHERE name = 'asks'")
+ .fetch_one(&self.pool)
+ .await?;
+ if has_asks == 0 {
+ sqlx::query("ALTER TABLE running_turns ADD COLUMN asks INTEGER").execute(&self.pool).await?;
+ }
+ // 0.9.5 (additive): what a restart needs to continue the turn by itself
+ for (col, ty) in [("prompt", "TEXT"), ("steps", "TEXT"), ("resumed", "INTEGER")] {
+ let has: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pragma_table_info('running_turns') WHERE name = ?1")
+ .bind(col)
+ .fetch_one(&self.pool)
+ .await?;
+ if has == 0 {
+ sqlx::query(&format!("ALTER TABLE running_turns ADD COLUMN {col} {ty}")).execute(&self.pool).await?;
+ }
+ }
let had_index: Option<(String,)> = sqlx::query_as(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'",
@@ -1000,8 +1032,8 @@ impl Database {
pub async fn add_running_turn(&self, turn: &RunningTurn) -> Result<(), DbError> {
sqlx::query(
- "INSERT OR REPLACE INTO running_turns (turn_id, kwant_id, kwant_name, channel_id, direct_kwant_id, thread_id, started_at) \
- VALUES (?, ?, ?, ?, ?, ?, ?)",
+ "INSERT OR REPLACE INTO running_turns (turn_id, kwant_id, kwant_name, channel_id, direct_kwant_id, thread_id, started_at, asks, \
+ prompt, steps, resumed) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
)
.bind(&turn.turn_id)
.bind(&turn.kwant_id)
@@ -1010,11 +1042,21 @@ impl Database {
.bind(&turn.direct_kwant_id)
.bind(&turn.thread_id)
.bind(turn.started_at)
+ .bind(turn.asks)
+ .bind(&turn.prompt)
+ .bind(&turn.steps)
+ .bind(turn.resumed)
.execute(&self.pool)
.await?;
Ok(())
}
+ /// Records a running turn's tool steps so far (see [`RunningTurn::steps`]).
+ pub async fn set_running_steps(&self, turn_id: &str, steps: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE running_turns SET steps = ?1 WHERE turn_id = ?2").bind(steps).bind(turn_id).execute(&self.pool).await?;
+ Ok(())
+ }
+
pub async fn remove_running_turn(&self, turn_id: &str) -> Result<(), DbError> {
sqlx::query("DELETE FROM running_turns WHERE turn_id = ?").bind(turn_id).execute(&self.pool).await?;
Ok(())
diff --git a/src/db/human_steps.rs b/src/db/human_steps.rs
index 58a13f7d..a661231b 100644
--- a/src/db/human_steps.rs
+++ b/src/db/human_steps.rs
@@ -336,6 +336,28 @@ impl Database {
.await?)
}
+ /// Whether the turn asked the person for any step (open or answered).
+ pub async fn turn_asked_human_step(&self, turn_id: &str) -> Result<bool, DbError> {
+ let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM human_steps WHERE turn_id = ?").bind(turn_id).fetch_one(&self.pool).await?;
+ Ok(n > 0)
+ }
+
+ /// Whether the person was already asked to sign in (or for a code) on `site` in this browser
+ /// page since `since`, whatever they answered: kwnt asks for a wall it finds once, not every turn.
+ pub async fn sign_in_asked_since(&self, page: &str, site: &str, since: DateTime<Utc>) -> Result<bool, DbError> {
+ let n: i64 = sqlx::query_scalar(
+ // Numbered throughout: sqlx gives a bare `?` after `?2` the next unnumbered argument (the 2nd)
+ "SELECT COUNT(*) FROM human_steps WHERE kind IN ('sign_in', 'two_factor') AND COALESCE(page_key, sandbox_target) = ?1 \
+ AND substr(url, 1, length(?2)) = ?2 AND created_at >= ?3",
+ )
+ .bind(page)
+ .bind(site)
+ .bind(since)
+ .fetch_one(&self.pool)
+ .await?;
+ Ok(n > 0)
+ }
+
/// The open steps of one turn.
pub async fn open_human_steps_for_turn(&self, turn_id: &str) -> Result<Vec<HumanStep>, DbError> {
Ok(sqlx::query_as::<_, HumanStep>("SELECT * FROM human_steps WHERE status = 'open' AND turn_id = ?")
@@ -382,6 +404,37 @@ impl Database {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn a_sign_in_wall_is_asked_once_per_page_and_site() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let place = HumanStepPlace {
+ kwant_id: "k".into(),
+ direct_kwant_id: Some("k".into()),
+ turn_id: Some("t1".into()),
+ sandbox_target: Some("k".into()),
+ page_key: Some("k#job1".into()),
+ ..Default::default()
+ };
+ let hour_ago = Utc::now() - chrono::Duration::hours(1);
+ assert!(!db.turn_asked_human_step("t1").await.unwrap());
+ assert!(!db.sign_in_asked_since("k#job1", "https://www.tiktok.com/", hour_ago).await.unwrap());
+ let (s, _, _) = db
+ .create_human_step_with_card(&place, "sign_in", "Ben needs you to sign in", Some("https://www.tiktok.com/login"), None, "auto", |_| None)
+ .await
+ .unwrap();
+ assert!(db.turn_asked_human_step("t1").await.unwrap());
+ assert!(!db.turn_asked_human_step("t2").await.unwrap());
+ assert!(db.sign_in_asked_since("k#job1", "https://www.tiktok.com/", hour_ago).await.unwrap());
+ // Whatever they answered: a declined ask isn't repeated within the window either
+ assert!(db.close_human_step(&s.id, "declined").await.unwrap());
+ assert!(db.sign_in_asked_since("k#job1", "https://www.tiktok.com/", hour_ago).await.unwrap());
+ // Another page, another site, or outside the window: ask
+ assert!(!db.sign_in_asked_since("k", "https://www.tiktok.com/", hour_ago).await.unwrap());
+ assert!(!db.sign_in_asked_since("k#job1", "https://x.com/", hour_ago).await.unwrap());
+ assert!(!db.sign_in_asked_since("k#job1", "https://www.tiktok.com/", Utc::now() + chrono::Duration::hours(1)).await.unwrap());
+ }
+
#[test]
fn requests_are_checked_and_urls_lose_their_secrets() {
assert!(clean_request("sign_in", "Log in to GitHub", None).is_ok());
diff --git a/src/db/waiting.rs b/src/db/waiting.rs
index dfe7c3a0..f62da47e 100644
--- a/src/db/waiting.rs
+++ b/src/db/waiting.rs
@@ -26,8 +26,20 @@ pub struct WaitingItem {
pub status: String,
pub created_at: DateTime<Utc>,
pub reminded_at: Option<DateTime<Utc>>,
+ /// `None`: a question or a reply that asked. `"stopped"`: the bot's work stopped without
+ /// finishing and `question` says what stopped, why and what resumes it (0.9.5, see
+ /// `server::stopped`). Never reminded (`due_at` is `None`).
+ #[sqlx(default)]
+ pub kind: Option<String>,
+ /// Stopped items only: what Retry does, as JSON (`{"type":"approval","approval_id":…}`);
+ /// `None` when the chat's own Retry (resending the person's message) resumes it.
+ #[sqlx(default)]
+ pub retry: Option<String>,
}
+/// The `kind` of an item that says a bot's work stopped.
+pub const STOPPED: &str = "stopped";
+
pub struct NewWaitingItem {
pub kwant_id: String,
pub channel_id: Option<String>,
@@ -66,6 +78,16 @@ impl Database {
] {
sqlx::query(stmt).execute(&self.pool).await?;
}
+ // 0.9.5: stopped items (additive; an older kwnt reads them as plain replies)
+ for (col, ty) in [("kind", "TEXT"), ("retry", "TEXT")] {
+ let has: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM pragma_table_info('waiting_on_person') WHERE name = ?")
+ .bind(col)
+ .fetch_one(&self.pool)
+ .await?;
+ if has == 0 {
+ sqlx::query(&format!("ALTER TABLE waiting_on_person ADD COLUMN {col} {ty}")).execute(&self.pool).await?;
+ }
+ }
Ok(())
}
@@ -78,7 +100,7 @@ impl Database {
Some(q) => sqlx::query_as("SELECT id FROM waiting_on_person WHERE question_id = ?").bind(q).fetch_optional(&mut *tx).await?,
None => {
sqlx::query_as(&format!(
- "SELECT id FROM waiting_on_person WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT}"
+ "SELECT id FROM waiting_on_person WHERE question_id IS NULL AND kind IS NULL AND status != 'closed' AND {SAME_CHAT}"
))
.bind(&w.kwant_id)
.bind(w.channel_id.as_deref().unwrap_or(""))
@@ -176,7 +198,9 @@ impl Database {
direct_kwant_id: Option<&str>,
thread_id: Option<&str>,
) -> Result<u64, DbError> {
- let res = sqlx::query(&format!("UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT}"))
+ let res = sqlx::query(&format!(
+ "UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND kind IS NULL AND status != 'closed' AND {SAME_CHAT}"
+ ))
.bind(kwant_id)
.bind(channel_id.unwrap_or(""))
.bind(direct_kwant_id.unwrap_or(""))
@@ -186,6 +210,89 @@ impl Database {
Ok(res.rows_affected())
}
+ /// Records that a bot's work stopped in one chat: its earlier stopped item and its "waiting
+ /// on a reply" item there close (this says more), and one new item opens. Never reminded.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn add_stopped(
+ &self,
+ kwant_id: &str,
+ channel_id: Option<&str>,
+ direct_kwant_id: Option<&str>,
+ thread_id: Option<&str>,
+ message_id: Option<&str>,
+ line: &str,
+ retry: Option<&str>,
+ ) -> Result<WaitingItem, DbError> {
+ let mut tx = self.begin_write().await?;
+ sqlx::query(&format!("UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT}"))
+ .bind(kwant_id)
+ .bind(channel_id.unwrap_or(""))
+ .bind(direct_kwant_id.unwrap_or(""))
+ .bind(thread_id.unwrap_or(""))
+ .execute(&mut *tx)
+ .await?;
+ let row = sqlx::query_as::<_, WaitingItem>(
+ "INSERT INTO waiting_on_person (id, kwant_id, channel_id, direct_kwant_id, thread_id, message_id, question, status, created_at, kind, retry) \
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?) RETURNING *",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(kwant_id)
+ .bind(channel_id)
+ .bind(direct_kwant_id)
+ .bind(thread_id)
+ .bind(message_id)
+ .bind(line)
+ .bind(Utc::now())
+ .bind(STOPPED)
+ .bind(retry)
+ .fetch_one(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(row)
+ }
+
+ /// The bot's work in that chat went on (a later reply finished): its stopped items there close.
+ pub async fn close_stopped(
+ &self,
+ kwant_id: &str,
+ channel_id: Option<&str>,
+ direct_kwant_id: Option<&str>,
+ thread_id: Option<&str>,
+ ) -> Result<u64, DbError> {
+ let res = sqlx::query(&format!("UPDATE waiting_on_person SET status = 'closed' WHERE kind = 'stopped' AND status != 'closed' AND {SAME_CHAT}"))
+ .bind(kwant_id)
+ .bind(channel_id.unwrap_or(""))
+ .bind(direct_kwant_id.unwrap_or(""))
+ .bind(thread_id.unwrap_or(""))
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+
+ /// Closes one item if it is still open; `false` when it was already closed (a second Retry).
+ pub async fn claim_waiting(&self, id: &str) -> Result<bool, DbError> {
+ let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE id = ? AND status != 'closed'").bind(id).execute(&self.pool).await?;
+ Ok(res.rows_affected() > 0)
+ }
+
+ /// Stopped items still open whose notice is `message_id` (a chain notice's Continue).
+ pub async fn close_waiting_for_message(&self, message_id: &str) -> Result<u64, DbError> {
+ let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE message_id = ? AND kind = 'stopped' AND status != 'closed'")
+ .bind(message_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+
+ /// The stopped item whose Retry asks again for approval card `approval_id`.
+ pub async fn close_stopped_for_approval(&self, approval_id: &str) -> Result<u64, DbError> {
+ let res = sqlx::query("UPDATE waiting_on_person SET status = 'closed' WHERE kind = 'stopped' AND status != 'closed' AND json_extract(retry, '$.approval_id') = ?")
+ .bind(approval_id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+
/// The entries whose reminder is due by `now`, each claimed (`open` → `reminded`) so it goes
/// out once, whoever else is looking.
pub async fn take_due_waiting(&self, now: DateTime<Utc>) -> Result<Vec<WaitingItem>, DbError> {
@@ -282,4 +389,47 @@ mod tests {
assert_eq!(db.clear_waiting_due().await.unwrap(), 1);
assert!(db.take_due_waiting(Utc::now()).await.unwrap().is_empty());
}
+
+ #[tokio::test]
+ async fn a_stopped_item_replaces_the_chats_ask_and_closes_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ // A "waiting on your reply" item in the chat, then the work stops there
+ db.add_waiting(&item("k", None, Some("k"), None, None)).await.unwrap();
+ let a = db.add_stopped("k", None, Some("k"), None, Some("m1"), "Stopped. Retry in the chat sends your message again.", None).await.unwrap();
+ assert_eq!(a.kind.as_deref(), Some(STOPPED));
+ let open = db.list_waiting(None).await.unwrap();
+ assert_eq!(open.len(), 1, "the stop says more than the plain ask: {open:?}");
+ // A second stop in the same chat replaces the first: one ask per chat
+ let b = db.add_stopped("k", None, Some("k"), None, Some("m2"), "Again", None).await.unwrap();
+ let open = db.list_waiting(None).await.unwrap();
+ assert_eq!(open.iter().map(|w| w.id.as_str()).collect::<Vec<_>>(), vec![b.id.as_str()]);
+ // Never reminded
+ assert!(db.take_due_waiting(Utc::now() + Duration::days(30)).await.unwrap().is_empty());
+ // A stop elsewhere is untouched; a later reply of the bot there closes only that chat's
+ db.add_stopped("k", Some("c1"), None, None, None, "In the channel", None).await.unwrap();
+ assert_eq!(db.close_stopped("k", None, Some("k"), None).await.unwrap(), 1);
+ assert_eq!(db.list_waiting(None).await.unwrap().len(), 1);
+ // Plain closes don't take a stopped item with them, a write does
+ db.add_waiting(&item("k", Some("c1"), None, None, None)).await.unwrap();
+ assert_eq!(db.close_waiting_in_chat(Some("c1"), None, None).await.unwrap(), 2);
+ assert!(db.list_waiting(None).await.unwrap().is_empty());
+ }
+
+ #[tokio::test]
+ async fn a_stopped_item_closes_by_its_notice_or_its_approval_once() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let cont = db.add_stopped("k", Some("c1"), None, None, Some("notice1"), "Paused", Some(r#"{"type":"continue"}"#)).await.unwrap();
+ assert_eq!(cont.retry.as_deref(), Some(r#"{"type":"continue"}"#));
+ db.add_stopped("k", Some("c2"), None, None, Some("notice2"), "Expired", Some(r#"{"type":"approval","approval_id":"ap1"}"#)).await.unwrap();
+ assert_eq!(db.close_waiting_for_message("notice1").await.unwrap(), 1);
+ assert_eq!(db.close_waiting_for_message("notice1").await.unwrap(), 0);
+ assert_eq!(db.close_stopped_for_approval("ap2").await.unwrap(), 0);
+ assert_eq!(db.close_stopped_for_approval("ap1").await.unwrap(), 1);
+ assert!(db.list_waiting(None).await.unwrap().is_empty());
+ let c = db.add_stopped("k", Some("c3"), None, None, None, "x", None).await.unwrap();
+ assert!(db.claim_waiting(&c.id).await.unwrap());
+ assert!(!db.claim_waiting(&c.id).await.unwrap(), "a second Retry gets nothing");
+ }
}
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index a343e110..2e51a735 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -774,6 +774,39 @@ pub(crate) const FOCUSED_EDITABLE_JS: &str = r#"(() => {
/// Look-alikes are skipped: a reCAPTCHA v2 checkbox only counts while its challenge (bframe) is
/// open or the page is otherwise a wall (no field to fill, little text), and phrases like
/// "press and hold" only count inside an element whose id or class looks like a CAPTCHA.
+/// Whether the page is a sign-in wall (0.9.5): a visible one-time-code field is `"two_factor"`,
+/// a visible password field `"sign_in"`, else `null`. Only fields a person can see count, so a
+/// hidden login form in a page's header or a modal that isn't open doesn't.
+pub const SIGN_IN_PROBE_JS: &str = r##"(function () {
+ function shown(el) {
+ if (!el || el.disabled || el.type === 'hidden') return false;
+ var r = el.getBoundingClientRect();
+ if (r.width < 4 || r.height < 4) return false;
+ var s = window.getComputedStyle(el);
+ return s.visibility !== 'hidden' && s.display !== 'none' && Number(s.opacity) > 0.05;
+ }
+ var inputs = Array.prototype.slice.call(document.querySelectorAll('input'));
+ var otp = inputs.some(function (el) {
+ if (!shown(el)) return false;
+ var ac = (el.getAttribute('autocomplete') || '').toLowerCase();
+ if (ac === 'one-time-code') return true;
+ var hint = ((el.name || '') + ' ' + (el.id || '')).toLowerCase();
+ return /(^|[^a-z])(otp|totp|2fa|mfa)([^a-z]|$)|verification.?code|one.?time/.test(hint);
+ });
+ if (otp) return 'two_factor';
+ if (inputs.some(function (el) { return el.type === 'password' && shown(el); })) return 'sign_in';
+ return null;
+})()"##;
+
+/// The kind of sign-in wall a page shows ([`SIGN_IN_PROBE_JS`]): `"sign_in"` or `"two_factor"`.
+pub fn sign_in_kind(value: &Value) -> Option<&'static str> {
+ match value.as_str() {
+ Some("sign_in") => Some("sign_in"),
+ Some("two_factor") => Some("two_factor"),
+ _ => None,
+ }
+}
+
pub const CAPTCHA_PROBE_JS: &str = r##"(function () {
var VENDORS = [
['recaptcha', /(^|\.)google\.com\/recaptcha\/|recaptcha\.net\/recaptcha\//i],
@@ -2176,6 +2209,17 @@ impl BrowserController {
Ok(CaptchaHit::parse(&res["result"]["value"]))
}
+ /// The sign-in wall the page shows, if any (see [`SIGN_IN_PROBE_JS`]).
+ pub async fn probe_sign_in(&self) -> Result<Option<&'static str>, BrowserError> {
+ let res = self.send_cdp_command("Runtime.evaluate", json!({
+ "expression": SIGN_IN_PROBE_JS, "returnByValue": true
+ })).await?;
+ if res.get("exceptionDetails").is_some() {
+ return Err(BrowserError::Protocol("sign-in probe failed".into()));
+ }
+ Ok(sign_in_kind(&res["result"]["value"]))
+ }
+
/// Declines optional cookies on a known consent banner. Never accepts.
pub async fn reject_consent(&self) -> Option<String> {
// Consent managers often render a moment after load: look twice
@@ -2659,6 +2703,24 @@ mod view_claim_tests {
}
}
+#[cfg(test)]
+mod sign_in_probe_tests {
+ use super::{sign_in_kind, SIGN_IN_PROBE_JS};
+ use serde_json::json;
+
+ #[test]
+ fn only_the_two_wall_kinds_count() {
+ assert_eq!(sign_in_kind(&json!("sign_in")), Some("sign_in"));
+ assert_eq!(sign_in_kind(&json!("two_factor")), Some("two_factor"));
+ assert_eq!(sign_in_kind(&json!(null)), None);
+ assert_eq!(sign_in_kind(&json!("captcha")), None);
+ assert_eq!(sign_in_kind(&json!({"kind": "sign_in"})), None);
+ // The probe looks only at visible fields, and a code field wins over a password field
+ assert!(SIGN_IN_PROBE_JS.contains("one-time-code"));
+ assert!(SIGN_IN_PROBE_JS.find("'two_factor'").unwrap() < SIGN_IN_PROBE_JS.find("'sign_in'").unwrap());
+ }
+}
+
#[cfg(test)]
mod outage_tests {
use super::{outage, BrowserError, Outage};
diff --git a/src/serve.rs b/src/serve.rs
index 9ca10bf5..244a2999 100644
--- a/src/serve.rs
+++ b/src/serve.rs
@@ -62,6 +62,8 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(
// chats say which replies it cut off
crate::server::mcp_runtime::keep_cards_after_restart(&state).await;
crate::server::routes::interrupt_running_turns(&state).await;
+ // Cards that ran out of time while kwant was down tell their chat (0.9.5)
+ crate::server::mcp_runtime::expire_unanswered(&state).await;
// Audits that were waiting their turn when kwant stopped run now (the cut-off ones ended)
crate::server::missions::auditor::resume_after_restart(&state).await;
crate::server::missions::watch::resume_after_restart(&state).await;
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 89e582c2..bfe2ee22 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -404,6 +404,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
// person's; the status stays readable
["", "api", "app", "update", ..] => *method != Method::GET && *method != Method::HEAD,
["", "api", "approvals", _, "resolve"] => *method == Method::POST,
+ // Retry on a card that expired unanswered asks the person again: theirs to press (0.9.5)
+ ["", "api", "approvals", _, "retry"] => *method == Method::POST,
// Dev mode (0.7): the watched repo, its cards, Fix it and Dismiss, release notes and the
// backup command are the person's; bots never read the desk either (D3)
["", "api", "spaces", _, "dev_mode" | "dev", ..] => true,
@@ -1085,6 +1087,7 @@ mod tests {
assert!(person_only(&post, "/api/documents"));
assert!(person_only(&get, "/api/documents/d1"));
assert!(person_only(&post, "/api/approvals/a1/resolve"));
+ assert!(person_only(&post, "/api/approvals/a1/retry"));
assert!(person_only(&put, "/api/spaces/s1/approvals"));
assert!(person_only(&put, "/api/kwants/k1/approvals"));
assert!(!person_only(&get, "/api/kwants/k1/approvals"));
diff --git a/src/server/away.rs b/src/server/away.rs
index f5daeaee..72f4d89b 100644
--- a/src/server/away.rs
+++ b/src/server/away.rs
@@ -315,6 +315,58 @@ pub(super) async fn waiting_approvals(state: &AppState, space: &SpaceId) -> Resu
Ok(rows)
}
+/// The space's open stopped items, as Needs-you cards: `title` is what stopped and what resumes
+/// it, `message_id` the chat notice that carries Retry or Continue, `retry` set when Retry is
+/// `POST /api/waiting/:id/retry` rather than the chat's own.
+pub(super) async fn stopped_items(state: &AppState, space: &SpaceId) -> Vec<Value> {
+ let rows = state.db.list_waiting(Some(space)).await.unwrap_or_default();
+ let mut out = Vec::new();
+ for w in rows.into_iter().filter(|w| w.kind.as_deref() == Some(crate::db::waiting::STOPPED)) {
+ let name = state.db.get_kwant(&w.kwant_id).await.ok().flatten().map(|k| k.name);
+ out.push(json!({
+ "kind": "stopped",
+ "id": w.id,
+ "kwant_id": w.kwant_id,
+ "kwant_name": name.unwrap_or_else(|| "A bot".into()),
+ "title": super::stopped::title(&w.question, TITLE_CHARS),
+ "summary": w.question,
+ "status": "open",
+ "timestamp": rfc3339(w.created_at),
+ "message_id": w.message_id,
+ "retry": w.retry.as_deref().and_then(|r| serde_json::from_str::<Value>(r).ok()),
+ "link": {
+ "thread_id": w.thread_id,
+ "channel_id": w.channel_id,
+ "direct_kwant_id": w.direct_kwant_id,
+ },
+ }));
+ }
+ // A sign-in, code or CAPTCHA step the person hasn't done: the bot's work waits on it (0.9.5,
+ // #9), so it is in Needs you too, not only a card in its chat
+ for s in state.db.list_human_steps(Some("open"), None, Some(space)).await.unwrap_or_default() {
+ let name = state.db.get_kwant(&s.kwant_id).await.ok().flatten().map(|k| k.name);
+ out.push(json!({
+ "kind": "stopped",
+ "id": s.id,
+ "human_step_id": s.id,
+ "kwant_id": s.kwant_id,
+ "kwant_name": name.unwrap_or_else(|| "A bot".into()),
+ "title": super::stopped::title(&s.reason, TITLE_CHARS),
+ "summary": s.reason,
+ "status": "open",
+ "timestamp": rfc3339(s.created_at),
+ "message_id": s.message_id,
+ "retry": Value::Null,
+ "link": {
+ "thread_id": s.thread_id,
+ "channel_id": s.channel_id,
+ "direct_kwant_id": s.direct_kwant_id,
+ },
+ }));
+ }
+ out
+}
+
#[derive(Debug, Deserialize)]
pub struct AwayQuery {
pub since: Option<String>,
@@ -356,9 +408,12 @@ pub async fn get(State(state): State<AppState>, Scope(space): Scope, Query(q): Q
};
// What a mission watcher left for the person (P1)
let watch = crate::server::missions::watch::waiting_items(&state, &space).await;
- let waiting_count = waiting_count + watch.len() as i64;
+ // Work that stopped without finishing and waits for the person to resume it (0.9.5)
+ let stopped = stopped_items(&state, &space).await;
+ let waiting_count = waiting_count + watch.len() as i64 + stopped.len() as i64;
let mut waiting: Vec<Value> = waiting.into_iter().map(item).collect();
waiting.extend(watch);
+ waiting.extend(stopped);
waiting.sort_by(|a, b| b["timestamp"].as_str().unwrap_or("").cmp(a["timestamp"].as_str().unwrap_or("")));
waiting.truncate(MAX_ITEMS as usize);
Json(json!({
diff --git a/src/server/bot_status.rs b/src/server/bot_status.rs
index 3bc4f9be..8d960b23 100644
--- a/src/server/bot_status.rs
+++ b/src/server/bot_status.rs
@@ -222,6 +222,24 @@ impl Board {
self.nudged.insert(kwant_id.to_string());
}
+ /// 0.9.5 (no silent stops): the person writing to `kwant_id` in the chat where it gave up after
+ /// a stall is that stop's Retry (the notice's Retry button resends their message; the notice
+ /// says "Send your message again to retry"). It ends the gave-up Stuck like "Try again" does,
+ /// so the one press runs it now instead of holding it until "Try again" is pressed as well.
+ /// True when it ended one. The gave-up mark is a status hold, not a safety guard: failure
+ /// streaks, budget and spending stops live elsewhere and keep their own one resume button.
+ pub fn person_retries_in(&mut self, kwant_id: &str, context_id: &str) -> bool {
+ let Some(m) = self.marks.get_mut(kwant_id) else {
+ return false;
+ };
+ if !m.gave_up.as_ref().is_some_and(|g| g.context_id == context_id || g.thread_id.as_deref() == Some(context_id)) {
+ return false;
+ }
+ m.gave_up = None;
+ self.nudge(kwant_id);
+ true
+ }
+
pub fn take_nudged(&mut self) -> HashSet<String> {
std::mem::take(&mut self.nudged)
}
@@ -788,6 +806,22 @@ pub async fn status_of(state: &AppState, kwant_id: &str) -> Option<Status> {
/// stuck or waits on the person elsewhere; the `held` object the response carries, or `None`
/// to send it now. Run its turn after [`wait_released`].
pub async fn hold(state: &AppState, kwant: &crate::db::models::Kwant, context_id: &str, kind: &'static str, item_id: &str) -> Option<Value> {
+ hold_from(state, kwant, context_id, kind, item_id, false).await
+}
+
+/// [`hold`] for a send that may be the person's own: their message in the chat where the bot gave
+/// up after a stall is its Retry and goes now ([`Board::person_retries_in`]).
+pub async fn hold_from(
+ state: &AppState,
+ kwant: &crate::db::models::Kwant,
+ context_id: &str,
+ kind: &'static str,
+ item_id: &str,
+ from_person: bool,
+) -> Option<Value> {
+ if from_person && kind == "message" && state.turns.board(|b| b.person_retries_in(&kwant.id, context_id)) {
+ tracing::info!(kwant = %kwant.id, "the person retried in the chat where the bot stalled: it runs now");
+ }
let input = inputs(state, &SpaceId::new(&kwant.space_id), std::slice::from_ref(&kwant.id)).await.pop()?;
let r = hold_reason(&input, context_id, Utc::now())?;
state.turns.board(|b| {
@@ -1326,6 +1360,29 @@ mod tests {
assert!(hold_reason(&b, "c1", at(30)).is_none(), "the gave-up window ended");
}
+ /// 0.9.5: after a stall gave up, the person's Retry in that chat (their message sent again)
+ /// resumes it in one press; anywhere else, or a second time, it changes nothing.
+ #[test]
+ fn the_persons_retry_in_the_stalled_chat_ends_the_gave_up_hold() {
+ let gave_up = |thread: Option<&str>| GaveUp { at: at(0), tries: 2, secs: 120, turn_id: "t1".into(), context_id: "c1".into(), thread_id: thread.map(str::to_string) };
+ let mut board = Board::default();
+ board.marks.entry("k1".into()).or_default().gave_up = Some(gave_up(None));
+ assert!(!board.person_retries_in("k1", "c2"), "another chat isn't this stop's Retry");
+ assert!(!board.person_retries_in("k2", "c1"), "nor another bot");
+ assert!(board.marks["k1"].gave_up.is_some());
+ assert!(board.take_nudged().is_empty());
+ assert!(board.person_retries_in("k1", "c1"));
+ assert!(board.marks["k1"].gave_up.is_none());
+ assert!(board.take_nudged().contains("k1"), "the status is pushed again");
+ let mut b = bot(Vec::new());
+ b.marks = board.marks["k1"].clone();
+ assert!(hold_reason(&b, "c1", at(1)).is_none(), "so the resent message isn't held");
+ assert!(!board.person_retries_in("k1", "c1"), "nothing left to end");
+ // A thread's stop: its thread id is the chat
+ board.marks.entry("k1".into()).or_default().gave_up = Some(gave_up(Some("th1")));
+ assert!(board.person_retries_in("k1", "th1"));
+ }
+
#[test]
fn a_send_to_a_bot_waiting_on_the_person_is_held_unless_it_is_the_answer() {
let mut t = running("t1", at(0));
diff --git a/src/server/budget.rs b/src/server/budget.rs
index 3435e09a..3043258f 100644
--- a/src/server/budget.rs
+++ b/src/server/budget.rs
@@ -93,7 +93,13 @@ pub(super) async fn pause_if_over(scope: &TurnScope, spoken: &[String], replies:
"resumed": false,
});
let msg = scope.message("system", "kwant", text);
- scope.save(&msg, Some(meta)).await;
+ let saved = scope.save(&msg, Some(meta)).await;
+ // …and in Needs you, with the same Continue (0.9.5). The chain is the last bot's that spoke
+ let by = replies.last().and_then(|(from, _)| scope.teammates.iter().find(|k| &k.name == from)).or(scope.teammates.first());
+ if let (Some(by), Some(m)) = (by, &saved) {
+ let line = format!("Paused before handing on to {}: over this request's token budget. Continue in the chat carries on.", waiting.join(", "));
+ super::stopped::ask(&scope.state, &super::stopped::Place::of_turn(scope, &by.id), Some(&m.id), &line, super::stopped::Resume::Continue).await;
+ }
true
}
@@ -120,6 +126,9 @@ pub(super) async fn pause_capped(scope: &TurnScope, lead: &Kwant, capped: &[&Kwa
});
if let Some(saved) = scope.save(&scope.message("system", "kwnt", line), Some(meta)).await {
let _ = scope.state.event_sender.send(crate::drivers::events::RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });
+ // …and in Needs you, with the same Continue (0.9.5)
+ let ask = format!("{} paused after {} hand-offs: {} not sent yet. Continue in the chat carries on.", lead.name, super::routes::MAX_DELEGATIONS_PER_REQUEST, names.join(", "));
+ super::stopped::ask(&scope.state, &super::stopped::Place::of_turn(scope, &lead.id), Some(&saved.id), &ask, super::stopped::Resume::Continue).await;
}
}
@@ -145,6 +154,8 @@ async fn resume(state: &AppState, notice_id: &str) -> Result<(), (StatusCode, &'
if meta["resumed"] == true {
return Err((StatusCode::CONFLICT, "this chain was already continued"));
}
+ // Its Needs-you item is answered either way
+ let _ = state.db.close_waiting_for_message(notice_id).await;
let channel_id = notice.channel_id.clone().ok_or((StatusCode::BAD_REQUEST, "not a channel message"))?;
if meta["kind"] == CAPPED_KIND {
return resume_capped(state, notice_id, meta, channel_id).await;
diff --git a/src/server/busy_retry.rs b/src/server/busy_retry.rs
new file mode 100644
index 00000000..11f2290e
--- /dev/null
+++ b/src/server/busy_retry.rs
@@ -0,0 +1,524 @@
+//! 0.9.5 no-silent-stops: a browser step that failed because the VM browser was busy is retried
+//! by kwnt itself, a bounded number of times, instead of the reply ending on it.
+//!
+//! The browser recovery work (#544) retries a busy browser for about 45 s inside each call; when
+//! it still doesn't answer, the call fails with HTTP 503 and
+//! `{"code": "BROWSER_BUSY", "retryable": true, "is_running": true}`. That is temporary, not a
+//! give-up: when a reply ends with its last browser step failed that way, kwnt parks the turn and
+//! runs it again after a cooldown, told to retry that same step ([`MAX_RETRIES`] times per
+//! message, [`cooldown`] apart). After that the person is asked once (a stopped item).
+//!
+//! Matched on the `code` only, never on the wording, and only from what kwnt's own browser
+//! handlers answered (`continuity::call_browser_tool`), never from the bot's text or tool output
+//! it could echo. A step that may reach outside (a click on "Send", "Pay"…, see
+//! [`super::restart_resume::outward`]) is never run again by itself: the person is asked.
+//!
+//! Turns nobody watches (a routine run, a hand-off) get the same bounds through [`unwatched`]: the
+//! turn leaves its busy step in a [`Slot`] instead of parking a retry in a chat, its caller waits
+//! the cooldown and runs it again, and when the retries run out (or the step looks outward) the
+//! run fails the way it fails today: a routine run to the Inbox, a hand-off back to its lead.
+
+use serde_json::Value;
+use std::collections::HashMap;
+use std::future::Future;
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+
+/// The `code` of a browser call that failed because the browser is there but overloaded.
+// TODO(#544): use `crate::sandbox::service::BROWSER_BUSY_CODE` once #544 is on main.
+pub const BROWSER_BUSY_CODE: &str = "BROWSER_BUSY";
+
+/// How many times kwnt runs a reply again by itself after it ended on a busy browser step.
+pub const MAX_RETRIES: u8 = 2;
+
+/// Parked-turn reasons, one per retry, so the count survives a restart and a new message from
+/// the person starts again from zero.
+pub const REASON_1: &str = "browser_busy_1";
+pub const REASON_2: &str = "browser_busy_2";
+
+/// The header the retry's prompt starts with (stripped again if that retry ends busy too).
+const PROMPT_HEAD: &str = "[kwnt: the browser was busy";
+
+/// Longest step arguments kept, in characters (as the restart record does).
+const MAX_ARGS_CHARS: usize = 200;
+
+/// Whether a browser handler's answer means "busy, retry the same step": its `code` is
+/// [`BROWSER_BUSY_CODE`] (and it doesn't say `retryable: false`). The text is never looked at.
+pub fn is_busy(body: &Value) -> bool {
+ body.get("code").and_then(Value::as_str) == Some(BROWSER_BUSY_CODE) && body.get("retryable") != Some(&Value::Bool(false))
+}
+
+/// The browser step that last failed busy in a turn.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Step {
+ pub tool: String,
+ pub args: String,
+}
+
+fn busy_steps() -> &'static Mutex<HashMap<String, Step>> {
+ static STEPS: OnceLock<Mutex<HashMap<String, Step>>> = OnceLock::new();
+ STEPS.get_or_init(Default::default)
+}
+
+/// Records how a turn's browser step ended: busy keeps it as the turn's last busy step, anything
+/// else (the browser answered) clears it, so only a turn that *ended* on a busy step is retried.
+pub fn note(turn_id: &str, tool: &str, args: &Value, busy: bool) {
+ if turn_id.is_empty() {
+ return;
+ }
+ let mut steps = busy_steps().lock().unwrap_or_else(|e| e.into_inner());
+ if busy {
+ let args: String = args.to_string().chars().take(MAX_ARGS_CHARS).collect();
+ steps.insert(turn_id.to_string(), Step { tool: tool.to_string(), args });
+ } else {
+ steps.remove(turn_id);
+ }
+}
+
+/// The turn's last browser step, if it failed busy and nothing answered after it. Forgets it.
+pub fn take(turn_id: &str) -> Option<Step> {
+ busy_steps().lock().unwrap_or_else(|e| e.into_inner()).remove(turn_id)
+}
+
+/// How long the `attempt`th retry (1-based) waits: 1 min, then 2 min.
+pub fn cooldown(attempt: u8) -> Duration {
+ Duration::from_secs(60 * u64::from(attempt.max(1)))
+}
+
+/// The parked reason for the `attempt`th retry.
+pub fn reason(attempt: u8) -> &'static str {
+ if attempt <= 1 { REASON_1 } else { REASON_2 }
+}
+
+/// How many busy retries a parked turn's reason stands for, if it is one.
+pub fn retries_of(reason: &str) -> Option<u8> {
+ match reason {
+ REASON_1 => Some(1),
+ REASON_2 => Some(2),
+ _ => None,
+ }
+}
+
+/// What happens to a reply that ended on a busy browser step.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Exit {
+ /// Run it again by itself: the `attempt`th retry, after `after`.
+ Retry { attempt: u8, after: Duration },
+ /// The retries are used up: ask the person once.
+ Exhausted,
+ /// The step may reach outside: never run again by itself, ask the person.
+ Outward,
+}
+
+/// The rule: retried by itself up to [`MAX_RETRIES`] times (`done` already happened for this
+/// message), except a step that may reach outside.
+pub fn decide(step: &Step, done: u8) -> Exit {
+ if super::restart_resume::outward(&step.tool, &step.args) {
+ return Exit::Outward;
+ }
+ if done >= MAX_RETRIES {
+ return Exit::Exhausted;
+ }
+ let attempt = done + 1;
+ Exit::Retry { attempt, after: cooldown(attempt) }
+}
+
+fn step_line(step: &Step) -> String {
+ if step.args.is_empty() || step.args == "{}" || step.args == "null" {
+ format!("`{}`", step.tool)
+ } else {
+ format!("`{}` with {}", step.tool, step.args)
+ }
+}
+
+/// The retry's prompt: the same step again, then the original request. A request that is
+/// already a busy retry keeps only its original part.
+pub fn prompt(step: &Step, original: &str) -> String {
+ let original = match original.strip_prefix(PROMPT_HEAD) {
+ Some(rest) => rest.split_once("]\n\n").map_or(original, |(_, o)| o),
+ None => original,
+ };
+ format!(
+ "{PROMPT_HEAD} (overloaded, not gone) when you ran {step}, so that step didn't happen. \
+ Run that same step again now, then carry on with the request below. If the browser is \
+ still busy, say so in one line]\n\n{original}",
+ step = step_line(step),
+ )
+}
+
+/// The chat note when a retry is set.
+pub fn retry_note(name: &str, step: &Step, attempt: u8, at: chrono::DateTime<chrono::Utc>) -> String {
+ format!(
+ "The browser was busy when {name} ran `{tool}` (it is overloaded, not gone), so {name} tries that same step again at {at} UTC (retry {attempt} of {MAX_RETRIES}).",
+ tool = step.tool,
+ at = at.format("%H:%M"),
+ )
+}
+
+/// The one ask (chat note and Needs-you line) when kwnt doesn't retry by itself.
+pub fn ask_line(name: &str, step: &Step, exit: &Exit) -> String {
+ match exit {
+ Exit::Outward => format!(
+ "{name}'s browser step `{tool}` failed because the browser was busy, and it may reach outside (a send, a post, a payment), \
+ so kwant won't run it again by itself. Check whether it went through, then tell {name} in the chat whether to do it again.",
+ tool = step.tool,
+ ),
+ _ => format!(
+ "{name} couldn't finish: the browser stayed busy after {MAX_RETRIES} automatic retries of `{tool}`. Retry in the chat sends your message again.",
+ tool = step.tool,
+ ),
+ }
+}
+
+/// Called when a reply in a person's own chat ended with its last browser step failed busy:
+/// parks a retry of it, or asks the person once (see [`decide`]). `done` is how many busy
+/// retries this message already had.
+pub(super) async fn after_turn(
+ scope: &super::routes::TurnScope,
+ kwant: &crate::db::models::Kwant,
+ original: &str,
+ step: &Step,
+ done: u8,
+) {
+ let state = &scope.state;
+ let exit = decide(step, done);
+ if let Exit::Retry { attempt, after } = &exit {
+ let at = chrono::Utc::now() + chrono::Duration::from_std(*after).unwrap_or_else(|_| chrono::Duration::seconds(60));
+ let parked = state
+ .db
+ .park_turn(&crate::db::parked::NewParkedTurn {
+ kwant_id: kwant.id.clone(),
+ channel_id: scope.channel_id.clone(),
+ direct_kwant_id: scope.kwant_id.clone(),
+ thread_id: scope.thread_id.clone(),
+ delegation_id: None,
+ depth: scope.delegation_depth,
+ prompt: prompt(step, original),
+ retry_at: at,
+ reason: reason(*attempt),
+ })
+ .await;
+ match parked {
+ Ok(Some(_)) => {
+ let note = scope.message("system", "kwnt", retry_note(&kwant.name, step, *attempt, at));
+ scope.save(&note, Some(serde_json::json!({"kind": "browser_busy_retry", "attempt": attempt}))).await;
+ tracing::info!(kwant = %kwant.id, attempt, tool = %step.tool, "the browser was busy: retrying the step by itself");
+ state.scheduler_wake.notify_one();
+ }
+ // Another retry already waits in this chat (a usage limit): that one runs it again
+ Ok(None) => {}
+ Err(e) => tracing::warn!(kwant = %kwant.id, "couldn't park a busy-browser retry: {e}"),
+ }
+ return;
+ }
+ let line = ask_line(&kwant.name, step, &exit);
+ let note = scope.message("system", "kwnt", line.clone());
+ let saved = scope.save(&note, Some(serde_json::json!({"kind": "browser_busy_stopped", "outward": exit == Exit::Outward}))).await;
+ let place = super::stopped::Place::of_turn(scope, &kwant.id);
+ super::stopped::ask(state, &place, saved.as_ref().map(|m| m.id.as_str()), &line, super::stopped::Resume::ResendMessage).await;
+}
+
+/// Where a turn nobody watches (a routine run, a hand-off) leaves the busy browser step it ended
+/// on, for its caller to retry (see [`unwatched`]), instead of parking a retry in a chat.
+#[derive(Debug, Clone, Default)]
+pub struct Slot(Arc<Mutex<Option<Step>>>);
+
+impl Slot {
+ pub fn put(&self, step: Step) {
+ *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(step);
+ }
+
+ /// The step a turn ended on, if it ended busy. Forgets it.
+ pub fn take(&self) -> Option<Step> {
+ self.0.lock().unwrap_or_else(|e| e.into_inner()).take()
+ }
+}
+
+/// Why an unwatched run failed when kwnt didn't (or no longer) retry its busy step: the run's
+/// error, which goes where a failed run goes today (a routine's Inbox item, a hand-off's lead).
+pub fn unwatched_failure(step: &Step, exit: &Exit) -> String {
+ match exit {
+ Exit::Outward => format!(
+ "the browser was busy at `{tool}`, a step that may reach outside (a send, a post, a payment), so it wasn't run again \
+ by itself. Check whether it went through before running it again",
+ tool = step.tool,
+ ),
+ _ => format!("the browser stayed busy after {MAX_RETRIES} automatic retries of `{tool}`", tool = step.tool),
+ }
+}
+
+/// The bounded retry for a turn nobody watches. `run` runs the turn with a prompt and the
+/// [`Slot`] it leaves a busy end in; `wait` says the retry in its chat, waits the cooldown and
+/// answers `false` if the run was stopped meanwhile. A turn that ended on a busy step runs again
+/// (the `attempt`th retry, told to retry that step) up to [`MAX_RETRIES`] times; then, or at once
+/// for an outward step, it fails with [`unwatched_failure`]. A turn that failed, or didn't end
+/// busy, is returned as it is.
+pub async fn retry_loop<R, RF, W, WF>(original: &str, mut run: R, mut wait: W) -> Result<String, String>
+where
+ R: FnMut(String, Slot) -> RF,
+ RF: Future<Output = Result<String, String>>,
+ W: FnMut(Step, u8, Duration) -> WF,
+ WF: Future<Output = bool>,
+{
+ let mut done = 0u8;
+ let mut next = original.to_string();
+ loop {
+ let slot = Slot::default();
+ let outcome = run(next, slot.clone()).await;
+ let step = slot.take();
+ let (Ok(_), Some(step)) = (&outcome, step) else {
+ return outcome;
+ };
+ match decide(&step, done) {
+ Exit::Retry { attempt, after } => {
+ if !wait(step.clone(), attempt, after).await {
+ return Err("stopped".into());
+ }
+ done = attempt;
+ next = prompt(&step, original);
+ }
+ exit => return Err(unwatched_failure(&step, &exit)),
+ }
+ }
+}
+
+/// [`retry_loop`] for a turn in `scope` (a routine run's chat, a hand-off's thread): each retry is
+/// said there in one line, and the wait ends early, as stopped, when the run is stopped.
+pub(super) async fn unwatched<R, RF>(scope: &super::routes::TurnScope, name: &str, original: &str, run: R) -> Result<String, String>
+where
+ R: FnMut(String, Slot) -> RF,
+ RF: Future<Output = Result<String, String>>,
+{
+ retry_loop(original, run, |step, attempt, after| async move {
+ let at = chrono::Utc::now() + chrono::Duration::from_std(after).unwrap_or_else(|_| chrono::Duration::seconds(60));
+ let note = scope.message("system", "kwnt", retry_note(name, &step, attempt, at));
+ scope.save(&note, Some(serde_json::json!({"kind": "browser_busy_retry", "attempt": attempt}))).await;
+ tracing::info!(bot = name, attempt, tool = %step.tool, "the browser was busy in an unwatched run: retrying the step by itself");
+ tokio::select! {
+ _ = tokio::time::sleep(after) => !scope.cancel_token.is_cancelled(),
+ _ = scope.cancel_token.cancelled() => false,
+ }
+ })
+ .await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn act(args: Value) -> Step {
+ Step { tool: "browser_act".into(), args: args.to_string() }
+ }
+
+ #[test]
+ fn busy_is_matched_on_the_code_never_the_text() {
+ // #544's 503 body
+ let busy = json!({"error": "The browser isn't responding right now (it is overloaded, not gone). This is temporary: retry the same step in a minute.",
+ "code": "BROWSER_BUSY", "retryable": true, "is_running": true});
+ assert!(is_busy(&busy));
+ assert!(is_busy(&json!({"error": "anything else entirely", "code": "BROWSER_BUSY", "retryable": true})), "any wording");
+ // The same wording without the code is not busy (a bot or a page could echo it)
+ assert!(!is_busy(&json!({"error": busy["error"], "retryable": true})));
+ assert!(!is_busy(&json!(busy["error"])));
+ // Truly unreachable (Docker), pages full, or an explicit opt-out
+ assert!(!is_busy(&json!({"error": "Sandbox browser is unavailable. Check that Docker is running, then restart the browser.", "is_running": false})));
+ assert!(!is_busy(&json!({"error": "pages full", "code": "PAGES_FULL"})));
+ assert!(!is_busy(&json!({"code": "BROWSER_BUSY", "retryable": false})));
+ assert!(!is_busy(&json!({"code": "browser_busy"})), "the code is exact");
+ }
+
+ #[test]
+ fn the_code_matches_the_browser_recovery_constant() {
+ // TODO(#544): assert_eq!(BROWSER_BUSY_CODE, crate::sandbox::service::BROWSER_BUSY_CODE)
+ assert_eq!(BROWSER_BUSY_CODE, "BROWSER_BUSY");
+ }
+
+ #[test]
+ fn a_busy_step_is_retried_by_itself_twice_then_the_person_is_asked() {
+ let step = act(json!({"action": "scroll", "delta_y": 400}));
+ assert_eq!(decide(&step, 0), Exit::Retry { attempt: 1, after: Duration::from_secs(60) });
+ assert_eq!(decide(&step, 1), Exit::Retry { attempt: 2, after: Duration::from_secs(120) });
+ assert_eq!(decide(&step, 2), Exit::Exhausted);
+ assert_eq!(decide(&step, 9), Exit::Exhausted);
+ // the count rides on the parked reason, so it survives a restart
+ assert_eq!(retries_of(reason(1)), Some(1));
+ assert_eq!(retries_of(reason(2)), Some(2));
+ assert_eq!(retries_of("usage_limit"), None);
+ assert_eq!(retries_of("restart"), None);
+ let reads = Step { tool: "browser_page".into(), args: "{}".into() };
+ assert!(matches!(decide(&reads, 0), Exit::Retry { .. }));
+ }
+
+ #[test]
+ fn a_busy_step_that_may_reach_outside_is_never_run_again_by_itself() {
+ // a click whose arguments name a "Send" button, or a tool named for a payment
+ assert_eq!(decide(&act(json!({"action": "type", "ref": "e4", "text": "Send"})), 0), Exit::Outward);
+ let pay = Step { tool: "pay_invoice".into(), args: "{}".into() };
+ assert_eq!(decide(&pay, 0), Exit::Outward);
+ // ...even with retries left, and before the cap
+ assert_eq!(decide(&pay, 1), Exit::Outward);
+ assert!(ask_line("Ben", &pay, &Exit::Outward).contains("won't run it again by itself"));
+ assert!(ask_line("Ben", &pay, &Exit::Exhausted).contains("Retry in the chat"));
+ }
+
+ #[test]
+ fn only_a_turn_that_ended_on_a_busy_step_is_retried() {
+ let turn = format!("t-{}", uuid::Uuid::new_v4());
+ note(&turn, "browser_open", &json!({"url": "https://example.com"}), true);
+ // the browser answered a later step: nothing to retry
+ note(&turn, "browser_page", &json!({}), false);
+ assert_eq!(take(&turn), None);
+ note(&turn, "browser_page", &json!({}), false);
+ note(&turn, "browser_act", &json!({"action": "click", "ref": "e9"}), true);
+ let step = take(&turn).expect("ended busy");
+ assert_eq!(step.tool, "browser_act");
+ assert!(step.args.contains("e9"));
+ assert_eq!(take(&turn), None, "taken once");
+ // a turn without an id records nothing
+ note("", "browser_act", &json!({}), true);
+ assert_eq!(take(""), None);
+ // long arguments are clipped
+ note(&turn, "browser_act", &json!({"text": "x".repeat(1000)}), true);
+ assert_eq!(take(&turn).unwrap().args.chars().count(), MAX_ARGS_CHARS);
+ }
+
+ #[test]
+ fn the_retry_prompt_names_the_step_and_keeps_one_copy_of_the_request() {
+ let step = act(json!({"action": "click", "ref": "e9"}));
+ let first = prompt(&step, "Find the price on example.com");
+ assert!(first.starts_with(PROMPT_HEAD));
+ assert!(first.contains("`browser_act` with {\"action\":\"click\",\"ref\":\"e9\"}"));
+ assert!(first.ends_with("\n\nFind the price on example.com"));
+ let second = prompt(&Step { tool: "browser_open".into(), args: "{}".into() }, &first);
+ assert_eq!(second.matches(PROMPT_HEAD).count(), 1);
+ assert!(second.contains("`browser_open`"));
+ assert!(second.ends_with("\n\nFind the price on example.com"));
+ let at = chrono::DateTime::parse_from_rfc3339("2026-11-12T22:30:00Z").unwrap().with_timezone(&chrono::Utc);
+ assert_eq!(
+ retry_note("Ben", &step, 1, at),
+ "The browser was busy when Ben ran `browser_act` (it is overloaded, not gone), so Ben tries that same step again at 22:30 UTC (retry 1 of 2)."
+ );
+ }
+
+ /// A fake unwatched run: each turn answers `replies[n]` and, where `busy[n]`, ends on `step`.
+ /// Returns the outcome, the prompts each turn got and the waits (attempt, cooldown).
+ async fn drive(step: Step, busy: &[bool], stop_at: Option<u8>) -> (Result<String, String>, Vec<String>, Vec<(u8, Duration)>) {
+ let prompts = Mutex::new(Vec::new());
+ let waits = Mutex::new(Vec::new());
+ let outcome = retry_loop(
+ "Check the price on example.com",
+ |p, slot| {
+ let n = {
+ let mut ps = prompts.lock().unwrap();
+ ps.push(p);
+ ps.len() - 1
+ };
+ if busy.get(n).copied().unwrap_or(false) {
+ slot.put(step.clone());
+ }
+ async move { Ok::<String, String>(format!("reply {n}")) }
+ },
+ |s, attempt, after| {
+ assert_eq!(s, step, "the retry is for the same step");
+ waits.lock().unwrap().push((attempt, after));
+ let go_on = stop_at != Some(attempt);
+ async move { go_on }
+ },
+ )
+ .await;
+ (outcome, prompts.into_inner().unwrap(), waits.into_inner().unwrap())
+ }
+
+ fn busy_retries_of(prompts: &[String], step: &Step) {
+ assert_eq!(prompts[0], "Check the price on example.com", "the first run gets the request as it is");
+ for p in &prompts[1..] {
+ assert!(p.starts_with(PROMPT_HEAD), "each retry is told the browser was busy");
+ assert!(p.contains(&format!("`{}`", step.tool)), "and to retry the same step");
+ assert_eq!(p.matches("Check the price on example.com").count(), 1);
+ }
+ }
+
+ #[tokio::test]
+ async fn a_routine_run_that_ends_busy_is_retried_twice_then_fails_to_the_inbox() {
+ let step = act(json!({"action": "scroll", "delta_y": 400}));
+ let (outcome, prompts, waits) = drive(step.clone(), &[true, true, true], None).await;
+ assert_eq!(prompts.len(), 3, "the run, then 2 retries, never a third");
+ busy_retries_of(&prompts, &step);
+ assert_eq!(waits, vec![(1, Duration::from_secs(60)), (2, Duration::from_secs(120))]);
+ // The run fails, so it is recorded as failed and the Inbox gets today's routine_failed item
+ let err = outcome.expect_err("the run fails once the retries are used up");
+ assert_eq!(err, "the browser stayed busy after 2 automatic retries of `browser_act`");
+ let recorded = super::super::routes::routine_turn_error(&err);
+ assert_eq!(
+ super::super::scheduler::failed_body("Morning prices", Some(&recorded)),
+ "The routine \"Morning prices\" did not finish: the bot's turn failed: the browser stayed busy after 2 automatic \
+ retries of `browser_act`. Open the routine to see the run or run it again."
+ );
+ }
+
+ #[tokio::test]
+ async fn a_hand_off_that_ends_busy_is_retried_twice_then_fails_back_to_its_lead() {
+ let step = Step { tool: "browser_open".into(), args: json!({"url": "https://example.com"}).to_string() };
+ let (outcome, prompts, waits) = drive(step.clone(), &[true, true, true], None).await;
+ assert_eq!(prompts.len(), 3);
+ busy_retries_of(&prompts, &step);
+ assert_eq!(waits.iter().map(|w| w.0).collect::<Vec<_>>(), vec![1, 2]);
+ // Reported the way a failed hand-off is today: failed, with the why, to the origin chat and its lead
+ let (status, error) = super::super::delegation::ended_as(&outcome);
+ assert_eq!(status, "failed");
+ assert_eq!(error.as_deref(), Some("the browser stayed busy after 2 automatic retries of `browser_open`"));
+ assert_eq!(
+ super::super::delegation::report_text("Find the price", &outcome),
+ "Couldn't finish “Find the price”: the browser stayed busy after 2 automatic retries of `browser_open`"
+ );
+ }
+
+ #[tokio::test]
+ async fn an_unwatched_run_that_gets_through_on_a_retry_ends_with_that_reply() {
+ let step = act(json!({"action": "click", "ref": "e9"}));
+ let (outcome, prompts, waits) = drive(step, &[true, false], None).await;
+ assert_eq!(outcome, Ok("reply 1".into()));
+ assert_eq!(prompts.len(), 2);
+ assert_eq!(waits, vec![(1, Duration::from_secs(60))]);
+ // a run that never ended busy runs once
+ let (outcome, prompts, waits) = drive(act(json!({})), &[false], None).await;
+ assert_eq!((outcome, prompts.len(), waits.len()), (Ok("reply 0".into()), 1, 0));
+ }
+
+ #[tokio::test]
+ async fn an_unwatched_outward_step_is_never_run_again_by_itself() {
+ let send = act(json!({"action": "click", "ref": "e4", "name": "Send"}));
+ let (outcome, prompts, waits) = drive(send, &[true, true, true], None).await;
+ assert_eq!((prompts.len(), waits.len()), (1, 0), "straight to the one failure, no retry");
+ let err = outcome.unwrap_err();
+ assert!(err.contains("may reach outside") && err.contains("wasn't run again by itself"), "{err}");
+ assert_eq!(super::super::delegation::ended_as(&Err(err)).0, "failed");
+ }
+
+ #[tokio::test]
+ async fn an_unwatched_run_stopped_while_it_waits_ends_stopped() {
+ let (outcome, prompts, _) = drive(act(json!({"action": "scroll"})), &[true, true, true], Some(1)).await;
+ assert_eq!(prompts.len(), 1, "nothing runs after the stop");
+ assert_eq!(outcome, Err("stopped".into()));
+ assert_eq!(super::super::delegation::ended_as(&outcome).0, "cancelled");
+ }
+
+ #[tokio::test]
+ async fn an_unwatched_turn_that_failed_is_returned_as_it_is() {
+ let step = act(json!({}));
+ let mut runs = 0;
+ let outcome = retry_loop(
+ "x",
+ |_, slot| {
+ runs += 1;
+ slot.put(step.clone());
+ async { Err::<String, String>("the claude driver failed: boom".into()) }
+ },
+ |_, _, _| async { true },
+ )
+ .await;
+ assert_eq!(runs, 1);
+ assert_eq!(outcome, Err("the claude driver failed: boom".into()));
+ }
+}
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index b7afffce..67fa66b5 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -835,14 +835,22 @@ async fn call_browser_tool(state: &AppState, scope: &SelfScope, target: &str, na
// finds it open
// A browser that doesn't answer is retried here for up to a minute (VM mode), so the tool
// below doesn't wait all over again
- match super::routes::open_page_steady(state, target, state.job_pages.wait()).await {
+ let opened = super::routes::open_page_steady(state, target, state.job_pages.wait()).await;
+ // 0.9.5: a page still refused because the browser is busy (its answer's `code`, see
+ // [`super::busy_retry`]) is a step kwnt retries by itself if the reply ends on it
+ if let Err(refusal) = &opened {
+ let (_, Json(body)) = super::routes::page_refused(state, *refusal);
+ super::busy_retry::note(&reader, name, args, super::busy_retry::is_busy(&body));
+ }
+ match opened {
Ok(ctrl) => ctrl.site_guard.set_driver(&scope.kwant_id),
Err(refusal @ (super::routes::PageRefusal::PagesFull | super::routes::PageRefusal::Busy)) => {
return (page_refusal_text(state, refusal), true)
}
Err(super::routes::PageRefusal::Unavailable) => {}
}
- let (text, is_error) = run_browser_tool(state, target, &reader, name, args).await;
+ let (text, is_error, busy) = run_browser_tool_coded(state, target, &reader, name, args).await;
+ super::busy_retry::note(&reader, name, args, busy);
// A CAPTCHA wall: ask the person to solve it, then show the agent the page they left. Also
// when the call itself failed: a click that stalled, was covered or timed out because a
// check slid over the page is still a check for the person
@@ -888,6 +896,13 @@ fn page_refusal_text(state: &AppState, refusal: super::routes::PageRefusal) -> S
/// `reader` names who reads (empty: nobody known), for `browser_page` to answer "unchanged" when
/// that reader's last page (from any browser tool) still reads the same.
async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool) {
+ let (text, is_error, _) = run_browser_tool_coded(state, target, reader, name, args).await;
+ (text, is_error)
+}
+
+/// [`run_browser_tool`], plus whether the handler answered that the browser is busy (matched on
+/// the answer's `code`, see [`super::busy_retry::is_busy`]).
+async fn run_browser_tool_coded(state: &AppState, target: &str, reader: &str, name: &str, args: &Value) -> (String, bool, bool) {
use super::routes::{
act_sandbox_allowed, cite_sandbox, get_sandbox_page, navigate_sandbox, unchanged_read, CitePayload, InteractPayload, NavigatePayload,
PageQuery,
@@ -901,7 +916,7 @@ async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &s
let result = match name {
BROWSER_OPEN => {
let Some(url) = args["url"].as_str().map(str::trim).filter(|u| !u.is_empty()) else {
- return ("url is required".into(), true);
+ return ("url is required".into(), true, false);
};
navigate_sandbox(state, target, Json(NavigatePayload { url: url.to_string() })).await
}
@@ -916,7 +931,7 @@ async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &s
}
_ => {
let Some(action) = args["action"].as_str() else {
- return ("action is required: click, type, key or scroll".into(), true);
+ return ("action is required: click, type, key or scroll".into(), true, false);
};
let payload = InteractPayload {
action: action.to_string(),
@@ -944,15 +959,18 @@ async fn run_browser_tool(state: &AppState, target: &str, reader: &str, name: &s
}
}
let is_error = page.get("error").is_some();
- (page.to_string(), is_error)
+ let busy = super::busy_retry::is_busy(&page);
+ (page.to_string(), is_error, busy)
}
Err((StatusCode::CONFLICT, _)) => (
"The user has taken control of the browser. Stop browser actions and wait until they hand it back.".into(),
true,
+ false,
),
Err((status, Json(body))) => (
body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("Browser error (HTTP {}).", status.as_u16())),
true,
+ super::busy_retry::is_busy(&body),
),
}
}
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 94c13b80..12eae277 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -2,7 +2,7 @@
//! specialist that runs in its own thread in the background and reports back to the chat it came
//! from. See `design-A.md` (batch 2) for the API and SSE contract.
-use super::routes::{continue_once_if_capped, scope_for, try_kwant_turn, TurnOpts};
+use super::routes::{continue_once_if_capped, continue_once_if_capped_into, scope_for, try_kwant_turn, TurnOpts};
use super::AppState;
use crate::db::models::{Kwant, MessageExtra, NewMessage};
use crate::db::spaces::SpaceId;
@@ -556,13 +556,25 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
origin = origin_brief(&state, &d).await,
again = if after_restart { RESTARTED_NOTE } else { "" },
);
- let mut opts = TurnOpts::default();
- opts.on_started = Some(on_started);
- opts.retried = retried;
- opts.delegation_id = Some(d.id.clone());
- opts.source = Some(super::bot_status::TurnSource::bot(&lead.name));
- let outcome = try_kwant_turn(&scope, &specialist, prompt, opts).await;
- let outcome = continue_once_if_capped(&scope, &specialist, outcome, false).await;
+ // 0.9.5: nobody watches a hand-off, so a busy browser step it ends on is retried here, bounded
+ // (see [`super::busy_retry::unwatched`]); one that still ends busy fails back to its lead
+ let mut on_started: Option<futures::future::BoxFuture<'static, ()>> = Some(on_started);
+ let outcome = super::busy_retry::unwatched(&scope, &specialist.name, &prompt, |p, slot| {
+ let mut opts = TurnOpts::default();
+ // marks the hand-off running once, when its first turn gets its slot
+ opts.on_started = on_started.take();
+ opts.retried = retried;
+ opts.delegation_id = Some(d.id.clone());
+ opts.source = Some(super::bot_status::TurnSource::bot(&lead.name));
+ opts.busy_slot = Some(slot.clone());
+ let (scope, specialist) = (&scope, &specialist);
+ // boxed, so the retry loop around the turn adds no stack to it
+ async move {
+ let outcome = Box::pin(try_kwant_turn(scope, specialist, p, opts)).await;
+ Box::pin(continue_once_if_capped_into(scope, specialist, outcome, false, Some(&slot))).await
+ }
+ })
+ .await;
let outcome = match outcome {
Err(_) if job.token.is_cancelled() => Err("stopped".to_string()),
other => other,
@@ -684,14 +696,28 @@ pub const RESTARTED_NOTE: &str = "\n\n[kwnt restarted while an earlier run of th
files may already be written, messages sent or settings changed. Check what is already done before redoing anything, \
and don't repeat a step that can't be undone (sending, posting, deleting, paying) unless you've confirmed it didn't happen.]";
-/// Ends `d` with `outcome`: the result in the origin chat, then the lead (with its batch, or on
-/// its own when the person sent the task back: `carried_on`).
-async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Result<String, String>, carried_on: bool) {
- let (status, error) = match &outcome {
+/// A delegation's status, and its error, for how its run ended.
+pub(super) fn ended_as(outcome: &Result<String, String>) -> (&'static str, Option<String>) {
+ match outcome {
Ok(_) => ("completed", None),
Err(e) if e == "stopped" => ("cancelled", Some("stopped by the user".to_string())),
Err(e) => ("failed", Some(clip(e, 500))),
- };
+ }
+}
+
+/// What the origin chat (and so the lead) reads for how the delegation `title` ended.
+pub(super) fn report_text(title: &str, outcome: &Result<String, String>) -> String {
+ match outcome {
+ Ok(reply) => result_text(reply),
+ Err(e) if e == "stopped" => format!("Stopped work on “{title}”."),
+ Err(e) => format!("Couldn't finish “{title}”: {}", clip(e, 500)),
+ }
+}
+
+/// Ends `d` with `outcome`: the result in the origin chat, then the lead (with its batch, or on
+/// its own when the person sent the task back: `carried_on`).
+async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: Result<String, String>, carried_on: bool) {
+ let (status, error) = ended_as(&outcome);
// Someone may have cancelled it meanwhile; then the cancel already reported it
if !state.db.finish_delegation(&d.id, status, error.as_deref(), None).await.unwrap_or(false) {
return;
@@ -699,11 +725,7 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R
let Ok(Some(done)) = state.db.get_delegation(&d.id).await else {
return;
};
- let text = match &outcome {
- Ok(reply) => result_text(reply),
- Err(_) if status == "cancelled" => format!("Stopped work on “{}”.", done.title),
- Err(e) => format!("Couldn't finish “{}”: {}", done.title, clip(e, 500)),
- };
+ let text = report_text(&done.title, &outcome);
let result_id = post_to_origin(state, &done, "kwant", &specialist.name, text, meta("delegation_result", &done, &specialist.name)).await;
if let Some(id) = &result_id {
let _ = state.db.set_delegation_result_message(&done.id, id).await;
diff --git a/src/server/human_steps.rs b/src/server/human_steps.rs
index 221ea7a0..0c760125 100644
--- a/src/server/human_steps.rs
+++ b/src/server/human_steps.rs
@@ -632,6 +632,53 @@ pub async fn ask_for_bot_wall(state: &AppState, scope: &SelfScope, on: &str, pag
}
}
+/// How long kwnt waits before asking again about a sign-in wall it already asked about on a page.
+pub const SIGN_IN_REASK_HOURS: i64 = 12;
+
+/// The step's line for a sign-in wall kwnt found: who needs what, where, and what happens next.
+pub fn sign_in_reason(kwant_name: &str, kind: &str, host: &str) -> String {
+ let reason = match kind {
+ "two_factor" => format!("{kwant_name} needs you to enter the sign-in code for {host} in the browser panel, then it continues."),
+ _ => format!("{kwant_name} needs you to sign in to {host} in the browser panel, then it continues."),
+ };
+ reason.chars().take(300).collect()
+}
+
+/// 0.9.5 (#9): a turn in a person's chat ended with its browser page on a sign-in form it didn't
+/// get past, and it asked the person nothing. Instead of the bot's work stopping there quietly,
+/// the person gets one sign-in step for that site on that page, whose Done starts the bot again.
+/// Asked once per site and page every [`SIGN_IN_REASK_HOURS`] (whatever they answered). Returns
+/// the step's reason when it asked.
+pub async fn ask_for_sign_in_wall(state: &AppState, scope: &SelfScope, page: &str) -> Option<String> {
+ scope.origin.as_ref()?;
+ let turn_id = scope.turn_id.as_deref()?;
+ if browser_is_held(state, page).await || state.db.turn_asked_human_step(turn_id).await.unwrap_or(true) {
+ return None;
+ }
+ let ctrl = state.browser_controllers.lock().await.get(page).cloned()?;
+ let kind = ctrl.probe_sign_in().await.ok().flatten()?;
+ let _ = ctrl.sync_location().await;
+ let raw = ctrl.current_url.lock().await.clone()?;
+ let url = crate::db::human_steps::clean_url(&raw)?;
+ let site = crate::db::human_steps::sign_in_site(&url)?;
+ let host = url::Url::parse(&url).ok()?.host_str()?.trim_start_matches("www.").to_string();
+ let since = chrono::Utc::now() - chrono::Duration::hours(SIGN_IN_REASK_HOURS);
+ if state.db.sign_in_asked_since(page, &site, since).await.unwrap_or(true) {
+ return None;
+ }
+ let reason = sign_in_reason(&scope.kwant_name, kind, &host);
+ match raise_step(state, scope, Some(page.to_string()), kind, &reason, Some(&url), None, "auto", false).await {
+ Ok(_) => {
+ tracing::info!(kwant_id = %scope.kwant_id, page, kind, "a turn ended on a sign-in wall: asked the person");
+ Some(reason)
+ }
+ Err(e) => {
+ tracing::warn!(kwant_id = %scope.kwant_id, error = %e, "couldn't ask the person to sign in");
+ None
+ }
+ }
+}
+
/// The step to ask for on a blocked page: reason, address and the widget's box.
fn wall_request(page: &Value) -> (String, Option<String>, Option<CaptchaHit>) {
let target = CaptchaHit::parse(&page["captcha"]).and_then(CaptchaHit::on_screen);
@@ -857,6 +904,16 @@ pub async fn cancel_for_turn(state: &AppState, turn_id: &str) {
mod tests {
use super::*;
+ #[test]
+ fn a_sign_in_wall_asks_for_one_specific_thing() {
+ assert_eq!(sign_in_reason("Ben", "sign_in", "tiktok.com"), "Ben needs you to sign in to tiktok.com in the browser panel, then it continues.");
+ assert_eq!(
+ sign_in_reason("Ben", "two_factor", "github.com"),
+ "Ben needs you to enter the sign-in code for github.com in the browser panel, then it continues."
+ );
+ assert!(sign_in_reason(&"B".repeat(400), "sign_in", "x.com").chars().count() <= 300);
+ }
+
#[tokio::test]
async fn the_hub_wakes_the_waiting_turn_once() {
let hub = HumanStepHub::default();
diff --git a/src/server/inbox.rs b/src/server/inbox.rs
index da953857..e372ea17 100644
--- a/src/server/inbox.rs
+++ b/src/server/inbox.rs
@@ -529,7 +529,8 @@ pub fn current_verdict(v: &TaskVerdict, in_review_since: DateTime<Utc>) -> Optio
serde_json::to_value(v).ok()
}
-/// A watcher's open item (`watch::waiting_items`) in Waiting on you, keyed like the away items.
+/// A watcher's open item (`watch::waiting_items`) or a stopped item (`away::stopped_items`) in
+/// Waiting on you, keyed like the away items.
fn watch_item(mut v: Value, last_seen: Option<DateTime<Utc>>) -> Value {
let at = v["timestamp"].as_str().and_then(|t| DateTime::parse_from_rfc3339(t).ok()).map(|t| t.with_timezone(&Utc));
let at_ms = at.map(|t| t.timestamp_millis()).unwrap_or(0);
@@ -841,16 +842,19 @@ 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;
+ // Work that stopped and waits for the person to resume it (0.9.5), as on /api/away
+ let stopped = away::stopped_items(&state, &space).await;
// 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 unseen_total = unseen_total + watch.len() as i64 + stopped.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(stopped.into_iter().map(|v| watch_item(v, seen)));
items.extend(connections.into_iter().map(|(at, v)| connection_item(at, &v, seen)));
// An approval's title is its own question when the call names what it is about (Iris's #539).
// `question` is sent only then, so the Inbox can tell it from today's tool title, which stays
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 148a0f51..6aa22505 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -497,6 +497,126 @@ pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: A
Some(json!({"ticket_id": ticket_id, "resolved": true, "status": status, "resumed": "new_turn"}))
}
+/// Cards nobody answered within [`crate::db::approval_modes::WAITING_APPROVAL_HOURS`] expire
+/// (0.9.5): each once, with a notice in the card's chat and a Needs-you item whose Retry
+/// (`POST /api/approvals/:id/retry`) asks the bot to make the call again, so the person gets a
+/// fresh card. Audit cards just close (their stage is over). Returns how many expired.
+pub async fn expire_unanswered(state: &AppState) -> usize {
+ let Ok(expired) = state.db.expire_waiting_approvals().await else {
+ return 0;
+ };
+ let n = expired.len();
+ for (approval, chat) in expired {
+ let _ = state.event_sender.send(RuntimeEvent::approval_withdrawn(&approval.id, "expired", None));
+ if super::missions::auditor::is_audit_card(&chat, &approval.tool_name) {
+ continue;
+ }
+ let Ok(Some(kwant)) = state.db.get_kwant(&approval.kwant_id).await else {
+ continue;
+ };
+ let place = expired_place(&chat, &kwant.id);
+ let text = expired_text(&kwant.name, &approval.tool_name, crate::db::approval_modes::WAITING_APPROVAL_HOURS);
+ let msg = crate::db::models::NewMessage {
+ channel_id: place.channel_id.clone(),
+ direct_kwant_id: place.direct_kwant_id.clone(),
+ sender_role: "system".into(),
+ sender_id: "kwnt".into(),
+ text: text.clone(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let meta = json!({
+ "kind": "approval_expired",
+ "approval_id": approval.id,
+ "kwant_id": kwant.id,
+ "kwant_name": kwant.name,
+ "tool_name": approval.tool_name,
+ });
+ let extra = crate::db::models::MessageExtra { thread_id: place.thread_id.clone(), meta: Some(meta) };
+ let saved = state.db.insert_message_with(&msg, &extra).await.ok();
+ if let Some(t) = &place.thread_id {
+ let _ = state.db.touch_thread(t).await;
+ }
+ if let Some(m) = &saved {
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(m).unwrap_or_default() });
+ }
+ super::stopped::ask(state, &place, saved.as_ref().map(|m| m.id.as_str()), &text, super::stopped::Resume::Approval { approval_id: approval.id.clone() }).await;
+ tracing::info!(ticket_id = %approval.id, kwant = %kwant.id, tool = %approval.tool_name, "an approval card expired unanswered: told the person");
+ }
+ if n > 0 {
+ super::missions::listener::refresh_needs_you(state).await;
+ }
+ n
+}
+
+/// Where an expired card's notice goes: its chat as recorded on the card, else the bot's DM.
+fn expired_place(chat: &Value, kwant_id: &str) -> super::stopped::Place {
+ let thread_id = chat["thread_id"].as_str().map(str::to_string);
+ let channel_id = chat["channel_id"].as_str().map(str::to_string);
+ let direct = chat["direct_kwant_id"].as_str().map(str::to_string);
+ let direct_kwant_id = match (&thread_id, &channel_id, direct) {
+ (None, None, None) => Some(kwant_id.to_string()),
+ (_, _, d) => d,
+ };
+ super::stopped::Place { kwant_id: kwant_id.to_string(), channel_id, direct_kwant_id, thread_id }
+}
+
+/// The chat notice (and Needs-you line) for a card that expired unanswered.
+pub fn expired_text(kwant_name: &str, tool_name: &str, hours: i64) -> String {
+ format!("{kwant_name} stopped waiting for your OK to use {tool_name} (no answer in {hours} h), so that step didn't run. Retry asks you again.")
+}
+
+/// Retry on a card that expired unanswered: starts a turn in its chat telling the bot to make the
+/// call again. Nothing is granted: the call asks for a fresh card. `None` when the card isn't
+/// expired (never, or Retry already ran).
+pub async fn retry_expired(state: &AppState, ticket_id: &str) -> Option<Value> {
+ let (approval, chat) = state.db.claim_expired_approval(ticket_id).await.ok().flatten()?;
+ let _ = state.db.close_stopped_for_approval(ticket_id).await;
+ let not_resumed = |why: &str| Some(json!({"ticket_id": ticket_id, "status": "retried", "resumed": false, "reason": why}));
+ let Ok(Some(kwant)) = state.db.get_kwant(&approval.kwant_id).await else {
+ return not_resumed("the bot no longer exists");
+ };
+ if super::spaces::ensure_active(state, &crate::db::spaces::SpaceId::new(&kwant.space_id)).await.is_err() {
+ return not_resumed("the bot's space is archived");
+ }
+ let details: Value = serde_json::from_str(&approval.parameters).unwrap_or(Value::Null);
+ let arguments = details.get("arguments").cloned().unwrap_or_else(|| json!({}));
+ let place = expired_place(&chat, &kwant.id);
+ let thread_id = place.thread_id.clone();
+ // A DM's scope is the bot's own chat (no channel, no thread)
+ let channel_id = place.channel_id.clone();
+ let conversation = thread_id.clone().or_else(|| channel_id.clone()).unwrap_or_else(|| kwant.id.clone());
+ let depth = match &thread_id {
+ Some(t) => state.db.delegation_for_thread(t).await.ok().flatten().map(|d| d.depth).unwrap_or(0),
+ None => 0,
+ };
+ let job = state.turns.start_job([conversation.clone(), ticket_id.to_string()]);
+ let scope = match super::routes::scope_for(state, &kwant, channel_id, thread_id, &job, depth).await {
+ Ok(s) => s,
+ Err(why) => return not_resumed(&why),
+ };
+ let prompt = expired_retry_prompt(&approval.tool_name, &arguments);
+ let target = kwant.clone();
+ let opts = super::routes::TurnOpts::routed_as(chat["agent"].as_str(), chat["effort"].as_str());
+ tokio::spawn(async move {
+ let _job = job;
+ let _ = super::routes::try_kwant_turn(&scope, &target, prompt, opts).await;
+ });
+ Some(json!({"ticket_id": ticket_id, "status": "retried", "resumed": "new_turn"}))
+}
+
+/// The turn Retry starts on an expired card.
+pub fn expired_retry_prompt(tool_name: &str, arguments: &Value) -> String {
+ let args = serde_json::to_string_pretty(arguments).unwrap_or_default();
+ let args: String = args.chars().take(2000).collect();
+ format!(
+ "[The person pressed Retry on a tool call that waited too long for their OK]\nTool: {tool_name}\nArguments: {args}\n\n\
+Nobody answered the approval card in time, so this call never ran. Make the same call again now; \
+the person gets a fresh card to answer. Then continue the task from where you stopped."
+ )
+}
+
/// The resumed turn's prompt after a late Allow.
pub fn late_approval_prompt(tool_name: &str, arguments: &Value) -> String {
let args = serde_json::to_string_pretty(arguments).unwrap_or_default();
@@ -1101,3 +1221,30 @@ async fn gateway_rpc(
_ => rpc_error(id, -32601, "method not found"),
}
}
+
+#[cfg(test)]
+mod expired_tests {
+ use super::*;
+
+ #[test]
+ fn an_expired_card_says_what_didnt_run_and_what_resumes_it() {
+ assert_eq!(
+ expired_text("Ben", "Bash", 24),
+ "Ben stopped waiting for your OK to use Bash (no answer in 24 h), so that step didn't run. Retry asks you again."
+ );
+ let p = expired_retry_prompt("Bash", &json!({"command": "ls"}));
+ assert!(p.starts_with("[The person pressed Retry on a tool call that waited too long for their OK]\nTool: Bash"), "{p}");
+ assert!(p.contains("\"command\": \"ls\""), "{p}");
+ assert!(p.contains("fresh card"), "Retry grants nothing: {p}");
+ }
+
+ #[test]
+ fn an_expired_card_with_no_chat_tells_the_bots_own_chat() {
+ let p = expired_place(&Value::Null, "k1");
+ assert_eq!((p.direct_kwant_id.as_deref(), p.channel_id, p.thread_id), (Some("k1"), None, None));
+ let p = expired_place(&json!({"thread_id": "t1"}), "k1");
+ assert_eq!((p.direct_kwant_id, p.thread_id.as_deref()), (None, Some("t1")));
+ let p = expired_place(&json!({"channel_id": "c1"}), "k1");
+ assert_eq!((p.direct_kwant_id, p.channel_id.as_deref()), (None, Some("c1")));
+ }
+}
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index 12d347b4..1400d071 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -244,11 +244,11 @@ pub async fn transition(
if matches!(from, "working" | "needs_you") && !matches!(to, "working" | "needs_you") {
checkpoints::after_run(state, &task).await;
}
- after_move(state, &task, to).await;
+ after_move(state, &task, to, actor).await;
Ok(task)
}
-async fn after_move(state: &AppState, task: &Task, to: &str) {
+async fn after_move(state: &AppState, task: &Task, to: &str, actor: Actor) {
// The Performance Market observes a settled task in the background (report-only, D1)
if crate::db::performance::result_of(to).is_some() {
performance::record_soon(state, &task.id);
@@ -267,8 +267,11 @@ async fn after_move(state: &AppState, task: &Task, to: &str) {
autofix::settle(state, task, to).await;
// A task parked for AutoFix isn't done failing: no "failed" line until it is
let to = if to == "failed" && autofix::parked(state, task).await { "parked" } else { to };
+ // 0.9.5: a task kwnt stopped (budget, failure streak) says so in its chat, not only on the
+ // board; one the person blocked needs no telling
+ let to = if to == "blocked" && matches!(actor, Actor::Person) { "blocked_by_person" } else { to };
let Some(mid) = task.mission_id.clone() else {
- if matches!(to, "verified" | "failed") {
+ if matches!(to, "verified" | "failed" | "blocked") {
task_chat_line(state, task, None).await;
}
if to == "verified" {
@@ -279,7 +282,7 @@ async fn after_move(state: &AppState, task: &Task, to: &str) {
return;
};
let mission = state.db.get_mission(&mid).await.ok().flatten();
- if matches!(to, "verified" | "failed") {
+ if matches!(to, "verified" | "failed" | "blocked") {
task_chat_line(state, task, mission.as_ref()).await;
}
if to == "verified" || to == "cancelled" {
@@ -779,10 +782,19 @@ pub async fn mission_chat_line(state: &AppState, m: &Mission, text: String) {
post_line(state, m.channel_id.clone(), m.direct_kwant_id.clone(), m.thread_id.clone(), &m.lead_kwant_id, text, meta).await;
}
+/// The chat line for a task kwnt stopped: what, why, and what carries it on.
+pub fn blocked_line(title: &str, reason: Option<&str>) -> String {
+ match reason.map(str::trim).filter(|r| !r.is_empty()) {
+ Some(r) => format!("Blocked: \"{title}\" stopped ({r}). Move it back to the backlog on the board to carry on."),
+ None => format!("Blocked: \"{title}\" stopped. Move it back to the backlog on the board to carry on."),
+ }
+}
+
async fn task_chat_line(state: &AppState, t: &Task, m: Option<&Mission>) {
let text = match t.state.as_str() {
"verified" => format!("Verified: \"{}\" passed its checks.", t.title),
"failed" => format!("Failed: \"{}\" didn't pass its checks after {} attempts. Retry it on the board.", t.title, t.attempts),
+ "blocked" => blocked_line(&t.title, t.blocked_reason.as_deref()),
_ => return,
};
let meta = json!({"kind": "mission", "task_id": t.id, "mission_id": t.mission_id, "state": t.state});
@@ -1120,6 +1132,16 @@ mod tests {
use super::*;
use chrono::Utc;
+ #[test]
+ fn a_blocked_task_says_what_stopped_and_how_to_carry_on() {
+ assert_eq!(
+ blocked_line("Ship the page", Some("the build failed")),
+ "Blocked: \"Ship the page\" stopped (the build failed). Move it back to the backlog on the board to carry on."
+ );
+ assert_eq!(blocked_line("T", Some(" ")), blocked_line("T", None));
+ assert!(blocked_line("T", None).ends_with("Move it back to the backlog on the board to carry on."));
+ }
+
#[test]
fn transitions_follow_the_contract() {
use Actor::*;
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 4e072196..af315555 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -63,6 +63,9 @@ pub mod connections;
pub mod setup_routes;
pub mod push;
pub mod waiting;
+pub mod stopped;
+pub mod restart_resume;
+pub mod busy_retry;
pub mod decide;
pub mod reactions;
pub mod work_ahead;
@@ -298,6 +301,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/chat/cancel", post(routes::cancel_chat))
.route("/api/approvals", get(approval_modes::list))
.route("/api/approvals/:id/resolve", post(routes::resolve_approval))
+ .route("/api/approvals/:id/retry", post(routes::retry_expired_approval))
.route("/api/spaces/:id/approvals", get(approval_modes::get_space).put(approval_modes::put_space))
.route("/api/spaces/:id/dev_mode", get(dev::routes::get_mode).put(dev::routes::put_mode))
.route("/api/spaces/:id/dev_mode/check", post(dev::routes::check))
diff --git a/src/server/parked.rs b/src/server/parked.rs
index 87251457..3d863e31 100644
--- a/src/server/parked.rs
+++ b/src/server/parked.rs
@@ -83,6 +83,10 @@ pub(super) async fn park_for(
Some(retry_line(at, Utc::now()))
}
+/// The reason a reply a restart cut off waits to run again (see [`super::restart_resume`]); its
+/// parked prompt already says what was cut off.
+pub const RESTART: &str = "restart";
+
/// The prompt a held turn gets once its bot can start new work again (G2).
pub fn budget_retry_prompt(original: &str) -> String {
format!(
@@ -137,19 +141,33 @@ async fn retry(state: &AppState, p: &ParkedTurn) -> bool {
return false;
};
let budget = p.reason == "bot_budget";
- let text = if budget {
- format!("{} can start new work again: running the message it held.", kwant.name)
+ let restart = p.reason == RESTART;
+ // 0.9.5: a busy-browser retry (see [`super::busy_retry`]); its count rides on the reason
+ let busy = super::busy_retry::retries_of(&p.reason);
+ // A restart's continuation and a busy-browser retry said so in the chat when they were parked
+ if !restart && busy.is_none() {
+ let text = if budget {
+ format!("{} can start new work again: running the message it held.", kwant.name)
+ } else {
+ format!("The usage limit has reset: retrying {}'s turn once.", kwant.name)
+ };
+ let note = scope.message("system", "kwnt", text);
+ scope.save(&note, None).await;
+ }
+ let prompt = if budget {
+ budget_retry_prompt(&p.prompt)
+ } else if restart || busy.is_some() {
+ p.prompt.clone()
} else {
- format!("The usage limit has reset: retrying {}'s turn once.", kwant.name)
+ retry_prompt(&p.prompt)
};
- let note = scope.message("system", "kwnt", text);
- scope.save(&note, None).await;
- let prompt = if budget { budget_retry_prompt(&p.prompt) } else { retry_prompt(&p.prompt) };
- tracing::info!(kwant = %kwant.id, parked = %p.id, "retrying a parked turn");
+ tracing::info!(kwant = %kwant.id, parked = %p.id, reason = %p.reason, "retrying a parked turn");
tokio::spawn(async move {
let _job = job;
let mut opts = TurnOpts::default();
opts.retried = true;
+ opts.resumed_after_restart = restart;
+ opts.busy_retries = busy.unwrap_or(0);
let _ = try_kwant_turn(&scope, &kwant, prompt, opts).await;
});
true
diff --git a/src/server/restart_resume.rs b/src/server/restart_resume.rs
new file mode 100644
index 00000000..ac67dbe5
--- /dev/null
+++ b/src/server/restart_resume.rs
@@ -0,0 +1,339 @@
+//! 0.9.5 "Runs never stop silently": a reply that a kwnt restart cut off continues by itself,
+//! once. A running turn records its tool steps as they start and finish
+//! ([`crate::db::continuity::RunningTurn::steps`]); at the next start the turn runs again with
+//! a note saying what was cut off. A step that only reads may simply run again. A step that acted
+//! locally (a shell command, an edit, a click) is never re-run blindly: the bot is told it was cut
+//! off mid-call, checks whether it took effect, and only then retries; if it can't tell, it asks
+//! the person once. A step that reaches outside (send, post, push, pay, publish, merge, deploy;
+//! see [`outward`]) isn't continued at all: kwant asks the person instead ([`outward_line`]), with
+//! no Retry, since Retry would resend the whole request and could do it twice.
+//!
+//! Bounded: the continuation is itself marked ([`crate::db::continuity::RunningTurn::resumed`]),
+//! so a second restart asks the person instead (the notice with Retry and a Needs-you item). A
+//! turn with a card or a browser step still waiting on the person isn't continued: answering
+//! that resumes the work. The exact in-flight call isn't resumed (that needs a durable record per
+//! call); the model makes it again or not, after checking.
+
+use crate::db::continuity::RunningTurn;
+use crate::drivers::RuntimeEvent;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// Steps kept per turn (the newest).
+pub const MAX_STEPS: usize = 12;
+/// A step's arguments are kept this short.
+const MAX_ARGS_CHARS: usize = 200;
+
+/// One tool step of a running turn.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Step {
+ pub id: String,
+ pub name: String,
+ /// Its arguments as JSON, clipped.
+ #[serde(default)]
+ pub args: String,
+ /// It only reads (see [`read_only`]).
+ pub read_only: bool,
+ /// It finished before the turn ended.
+ pub done: bool,
+}
+
+/// A turn's steps as they happen.
+#[derive(Debug, Default)]
+pub struct Steps(Vec<Step>);
+
+impl Steps {
+ /// Notes a step starting or finishing; true when the record changed.
+ pub fn saw(&mut self, e: &RuntimeEvent) -> bool {
+ match e {
+ RuntimeEvent::ToolCallPending { id, name, args } => {
+ let args = clip(&args.to_string(), MAX_ARGS_CHARS);
+ self.0.push(Step { id: id.clone(), read_only: read_only(name), name: name.clone(), args, done: false });
+ if self.0.len() > MAX_STEPS {
+ self.0.remove(0);
+ }
+ true
+ }
+ RuntimeEvent::ToolCallCompleted { id, .. } => match self.0.iter_mut().rev().find(|s| &s.id == id && !s.done) {
+ Some(s) => {
+ s.done = true;
+ true
+ }
+ None => false,
+ },
+ _ => false,
+ }
+ }
+
+ pub fn json(&self) -> String {
+ serde_json::to_string(&self.0).unwrap_or_else(|_| "[]".into())
+ }
+}
+
+fn clip(s: &str, max: usize) -> String {
+ if s.chars().count() <= max {
+ return s.to_string();
+ }
+ let cut: String = s.chars().take(max).collect();
+ format!("{cut}…")
+}
+
+/// Tool names (after any `mcp__<server>__` prefix) that only read.
+const READ_ONLY_TOOLS: &[&str] = &[
+ "read", "grep", "glob", "ls", "websearch", "webfetch", "notebookread", "todowrite", "todoread", "bashoutput",
+ "view_image", "web_search",
+];
+/// Name prefixes and parts that only read (a browser look, a lookup).
+const READ_ONLY_PREFIXES: &[&str] = &["get_", "list_", "read_", "search_", "find_", "view_", "describe_", "fetch_"];
+const READ_ONLY_PARTS: &[&str] = &["snapshot", "screenshot", "get_text", "get_url", "get_title", "wait_for", "tab_list"];
+
+/// Whether a step only reads, so running it again is harmless. Anything not known to read (a
+/// shell command, a click, a send) counts as able to change something.
+pub fn read_only(name: &str) -> bool {
+ let tool = name.rsplit("__").next().unwrap_or(name);
+ let lower = tool.to_ascii_lowercase();
+ if crate::server::continuity::READ_ONLY_SELF_TOOLS.contains(&tool) || READ_ONLY_TOOLS.contains(&lower.as_str()) {
+ return true;
+ }
+ // A browser tool's own name follows its prefix (agent_browser_snapshot, browser_get_text)
+ let bare = lower.trim_start_matches("agent_").trim_start_matches("browser_");
+ READ_ONLY_PREFIXES.iter().any(|p| bare.starts_with(p)) || READ_ONLY_PARTS.iter().any(|p| bare.contains(p))
+}
+
+/// Words in a tool's own name that mean it reaches outside: a message, a post, a push, a payment.
+const OUTWARD_NAME_PARTS: &[&str] = &[
+ "send", "post", "publish", "tweet", "reply", "comment", "email", "mail", "message", "push", "merge", "deploy", "release",
+ "pay", "charge", "checkout", "purchase", "buy", "order", "transfer", "invoice", "refund", "submit", "invite", "share",
+ "upload", "create_pull_request", "create_issue", "dm",
+];
+/// What a shell command or a click's arguments say when the step reaches outside.
+const OUTWARD_ARG_PARTS: &[&str] = &[
+ "git push", "gh pr merge", "gh pr create", "gh release", "npm publish", "cargo publish", "docker push", "twine upload",
+ "kubectl apply", "wrangler deploy", "fly deploy", "vercel deploy", "vercel --prod", "sendmail", "mailx ", "curl -x post", "curl -x put",
+ "curl -x delete", "curl --data", "curl -d ", "\"send\"", "\"post\"", "\"publish\"", "\"pay", "\"buy", "\"submit\"", "\"tweet\"",
+ "\"reply\"",
+];
+
+/// Whether a step reaches outside, so it may already have gone out and must not run again without
+/// the person: its name says so, or (a shell command, a click) its arguments do. Unknown names
+/// that don't say so count as local (checked first, see [`prompt`]); reads are never outward.
+pub fn outward(name: &str, args: &str) -> bool {
+ if read_only(name) {
+ return false;
+ }
+ let tool = name.rsplit("__").next().unwrap_or(name).to_ascii_lowercase();
+ let bare = tool.trim_start_matches("agent_").trim_start_matches("browser_");
+ let words: Vec<&str> = bare.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()).collect();
+ let named = OUTWARD_NAME_PARTS.iter().any(|p| if p.contains('_') { bare.contains(p) } else { words.contains(p) });
+ let args = args.to_ascii_lowercase();
+ named || OUTWARD_ARG_PARTS.iter().any(|p| args.contains(p))
+}
+
+/// The step a restart cut off mid-call that reaches outside, if any: then the reply isn't
+/// continued and the person is asked instead.
+pub fn cut_off_outward(t: &RunningTurn) -> Option<Step> {
+ steps_of(t).into_iter().rev().find(|s| !s.done && outward(&s.name, &s.args))
+}
+
+/// The chat notice and Needs-you line when the cut-off step reaches outside: what stopped, why
+/// it isn't continued, and the one action (tell the bot in the chat).
+pub fn outward_line(t: &RunningTurn, step: &Step) -> String {
+ format!(
+ "{name}'s reply was cut off when kwant restarted, in the middle of `{step}`, which may already have gone out. \
+ kwant won't run it again by itself. Check whether it went out, then tell {name} in the chat whether to do it again.",
+ name = t.kwant_name,
+ step = step.name,
+ )
+}
+
+fn steps_of(t: &RunningTurn) -> Vec<Step> {
+ t.steps.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default()
+}
+
+fn step_line(s: &Step) -> String {
+ if s.args.is_empty() || s.args == "{}" || s.args == "null" {
+ format!("`{}`", s.name)
+ } else {
+ format!("`{}` with {}", s.name, s.args)
+ }
+}
+
+/// The prompt that continues `t` after a restart; `None` when it isn't continued (no message
+/// recorded, already a continuation, or the cut-off step reaches outside: [`cut_off_outward`]).
+pub fn prompt(t: &RunningTurn) -> Option<String> {
+ let original = t.prompt.as_deref().filter(|p| !p.trim().is_empty())?;
+ if t.resumed == Some(true) || cut_off_outward(t).is_some() {
+ return None;
+ }
+ let steps = steps_of(t);
+ let mut note = String::from(
+ "[kwnt restarted while you were working on the message below, which cut your turn off; kwnt is continuing it once, now. \
+ What you did before the restart isn't in this conversation.",
+ );
+ let done_acting: Vec<String> = steps.iter().filter(|s| s.done && !s.read_only).map(step_line).collect();
+ if !done_acting.is_empty() {
+ note.push_str(&format!(
+ "\n- These steps finished before the restart and may have changed something: {}. Don't do them again; check their result instead if you need it.",
+ done_acting.join("; ")
+ ));
+ }
+ for s in steps.iter().filter(|s| !s.done) {
+ if s.read_only {
+ note.push_str(&format!(
+ "\n- The step {} was cut off mid-call. It only reads, so run it again if you still need it.",
+ step_line(s)
+ ));
+ } else {
+ note.push_str(&format!(
+ "\n- The step {} was cut off mid-call, so it may or may not have taken effect. Check first whether it took effect \
+ (look for the sent message, the post, the push, the payment or the changed file). Run it again only if it clearly \
+ didn't. If you can't tell, don't run it again: ask the person once, in one short question, whether to.",
+ step_line(s)
+ ));
+ }
+ }
+ note.push_str("\nThen finish the person's request.]");
+ Some(format!("{note}\n\n{original}"))
+}
+
+/// The step that was cut off mid-call, for the chat's note.
+pub fn cut_off_step(t: &RunningTurn) -> Option<String> {
+ steps_of(t).into_iter().rev().find(|s| !s.done).map(|s| s.name)
+}
+
+/// The chat's note when the reply continues by itself.
+pub fn note_text(t: &RunningTurn) -> String {
+ match cut_off_step(t) {
+ Some(step) => format!(
+ "kwant restarted while {} was replying (in the middle of `{step}`), so {} is continuing it now and checks first whether that step already took effect.",
+ t.kwant_name, t.kwant_name
+ ),
+ None => format!("kwant restarted while {} was replying, so {} is continuing it now.", t.kwant_name, t.kwant_name),
+ }
+}
+
+/// The meta that note is saved with.
+pub fn note_meta(t: &RunningTurn) -> Value {
+ serde_json::json!({
+ "kind": "turn_resumed_after_restart",
+ "kwant_id": t.kwant_id,
+ "kwant_name": t.kwant_name,
+ "turn_id": t.turn_id,
+ "started_at": t.started_at,
+ "cut_off_step": cut_off_step(t),
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn turn(steps: &[Step], resumed: Option<bool>) -> RunningTurn {
+ RunningTurn {
+ turn_id: "t1".into(),
+ kwant_id: "k1".into(),
+ kwant_name: "Ben".into(),
+ prompt: Some("post the launch note".into()),
+ steps: Some(serde_json::to_string(steps).unwrap()),
+ resumed,
+ ..Default::default()
+ }
+ }
+
+ fn step(name: &str, done: bool) -> Step {
+ Step { id: format!("id-{name}"), name: name.into(), args: r#"{"x":1}"#.into(), read_only: read_only(name), done }
+ }
+
+ #[test]
+ fn reads_are_told_apart_from_steps_that_act() {
+ for name in ["Read", "Grep", "WebFetch", "mcp__browser__agent_browser_snapshot", "mcp__kwnt_tools__memory_search", "mcp__x__list_issues", "mcp__browser__agent_browser_get_text", "mcp__gh__get_file"] {
+ assert!(read_only(name), "{name}");
+ }
+ for name in ["Bash", "Write", "Edit", "mcp__browser__agent_browser_click", "mcp__slack__send_message", "mcp__gh__create_pull_request", "mcp__stripe__charge", "shell", "apply_patch", "mcp__browser__agent_browser_open", "Task"] {
+ assert!(!read_only(name), "{name}");
+ }
+ }
+
+ #[test]
+ fn steps_are_recorded_as_they_start_and_finish() {
+ let mut s = Steps::default();
+ assert!(s.saw(&RuntimeEvent::ToolCallPending { id: "a".into(), name: "Bash".into(), args: json!({"command": "x".repeat(500)}) }));
+ assert!(!s.saw(&RuntimeEvent::Progress));
+ assert!(s.saw(&RuntimeEvent::ToolCallCompleted { id: "a".into(), result: json!({}) }));
+ assert!(!s.saw(&RuntimeEvent::ToolCallCompleted { id: "zz".into(), result: json!({}) }));
+ let v: Vec<Step> = serde_json::from_str(&s.json()).unwrap();
+ assert_eq!(v.len(), 1);
+ assert!(v[0].done && !v[0].read_only);
+ assert!(v[0].args.chars().count() <= MAX_ARGS_CHARS + 1, "args are clipped");
+ for i in 0..20 {
+ s.saw(&RuntimeEvent::ToolCallPending { id: i.to_string(), name: "Read".into(), args: json!({}) });
+ }
+ let v: Vec<Step> = serde_json::from_str(&s.json()).unwrap();
+ assert_eq!(v.len(), MAX_STEPS, "only the newest are kept");
+ assert_eq!(v.last().unwrap().id, "19");
+ }
+
+ #[test]
+ fn a_step_that_acts_locally_is_checked_before_it_runs_again() {
+ let p = prompt(&turn(&[step("Read", true), step("Edit", false)], None)).unwrap();
+ assert!(p.contains("`Edit` with {\"x\":1} was cut off mid-call"), "{p}");
+ assert!(p.contains("Check first whether it took effect"), "{p}");
+ assert!(p.contains("If you can't tell, don't run it again: ask the person once"), "{p}");
+ assert!(!p.contains("Don't do them again"), "a finished read isn't listed: {p}");
+ assert!(p.ends_with("\n\npost the launch note"), "{p}");
+ }
+
+ /// deer-flow row (Ada): a step that reaches outside, cut off mid-call, is never run again by
+ /// kwant or the bot on its own: the reply isn't continued and the person is asked instead.
+ #[test]
+ fn a_cut_off_step_that_reaches_outside_is_not_continued_and_the_person_is_asked() {
+ for name in ["mcp__slack__send_message", "mcp__x__create_post", "mcp__gmail__send_email", "mcp__stripe__charge", "mcp__gh__merge_pull_request", "mcp__gh__create_pull_request", "mcp__shop__checkout", "mcp__tg__send"] {
+ assert!(outward(name, "{}"), "{name}");
+ let t = turn(&[step("Read", true), step(name, false)], None);
+ assert!(prompt(&t).is_none(), "{name} is not continued");
+ let line = outward_line(&t, &cut_off_outward(&t).unwrap());
+ assert!(line.contains(&format!("in the middle of `{name}`, which may already have gone out")), "{line}");
+ assert!(line.ends_with("then tell Ben in the chat whether to do it again."), "{line}");
+ }
+ // A shell command or a click is outward when its arguments say so
+ assert!(outward("Bash", r#"{"command":"git push origin main"}"#));
+ assert!(outward("Bash", r#"{"command":"curl -X POST https://api.example.com/pay"}"#));
+ assert!(outward("mcp__browser__agent_browser_click", r#"{"element":"Post","ref":"\"post\""}"#));
+ assert!(!outward("Bash", r#"{"command":"cargo test"}"#));
+ assert!(!outward("mcp__browser__agent_browser_click", r#"{"ref":"e12"}"#));
+ // Reads and local edits never are, even when a word matches
+ for name in ["Read", "mcp__gmail__list_messages", "mcp__slack__get_message", "Edit", "Write", "mcp__x__search_posts", "mcp__gh__get_pull_request"] {
+ assert!(!outward(name, "{}"), "{name}");
+ }
+ // A finished outward step isn't cut off: it's listed as done, never repeated
+ let t = turn(&[step("mcp__slack__send_message", true), step("Read", false)], None);
+ assert!(cut_off_outward(&t).is_none());
+ assert!(prompt(&t).unwrap().contains("Don't do them again"));
+ }
+
+ #[test]
+ fn a_read_is_simply_run_again_and_finished_actions_are_not_repeated() {
+ let p = prompt(&turn(&[step("Bash", true), step("mcp__browser__agent_browser_snapshot", false)], None)).unwrap();
+ assert!(p.contains("It only reads, so run it again if you still need it."), "{p}");
+ assert!(!p.contains("Check first whether it took effect"), "{p}");
+ assert!(p.contains("These steps finished before the restart and may have changed something: `Bash`"), "{p}");
+ }
+
+ #[test]
+ fn a_continuation_is_not_continued_again_and_an_old_row_is_not_continued() {
+ assert!(prompt(&turn(&[], Some(true))).is_none());
+ assert!(prompt(&RunningTurn { prompt: None, ..turn(&[], None) }).is_none());
+ // No steps at all: still continued, with no step lines
+ let p = prompt(&turn(&[], None)).unwrap();
+ assert!(!p.contains("mid-call"), "{p}");
+ }
+
+ #[test]
+ fn the_chat_note_names_the_step_that_was_cut_off() {
+ let t = turn(&[step("mcp__slack__send_message", false)], None);
+ assert!(note_text(&t).contains("in the middle of `mcp__slack__send_message`"), "{}", note_text(&t));
+ assert_eq!(note_meta(&t)["cut_off_step"], "mcp__slack__send_message");
+ assert_eq!(note_text(&turn(&[], None)), "kwant restarted while Ben was replying, so Ben is continuing it now.");
+ }
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index e2b1d923..0e163915 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -756,6 +756,19 @@ fn with_failure_meta(meta: Option<serde_json::Value>, extra: &Option<serde_json:
Some(meta)
}
+/// A stopped reply in this turn's chat asks the person to resume it in Needs you (0.9.5): only a
+/// person's own chat; hand-offs, routine runs and missions are reported where they belong.
+fn stop_asks(scope: &TurnScope, opts: &TurnOpts) -> bool {
+ super::stopped::for_turn(
+ scope.delegation_depth,
+ opts.quiet_failure,
+ opts.unsaved,
+ opts.discussion.is_some(),
+ opts.rehearse.is_some(),
+ opts.source.as_ref().is_some_and(|s| s.kind == "routine"),
+ )
+}
+
/// Longest driver error kept in a saved `turn_failed` message, in bytes.
const MAX_SAVED_ERROR_BYTES: usize = 600;
@@ -1039,8 +1052,10 @@ pub(super) async fn run_routine_turn(
prompt: String,
routine_name: &str,
) -> Result<Option<String>, String> {
- let opts = TurnOpts { source: Some(super::bot_status::TurnSource::routine(routine_name)), ..TurnOpts::default() };
- run_turn_with(state, kwant, channel_id, thread_id, prompt, opts, Vec::new()).await
+ // 0.9.5: nobody watches a routine run, so a busy browser step it ends on is retried here,
+ // bounded (see [`super::busy_retry::unwatched`]); a run that still ends busy fails to the Inbox
+ let opts = || TurnOpts { source: Some(super::bot_status::TurnSource::routine(routine_name)), ..TurnOpts::default() };
+ run_turn_with(state, kwant, channel_id, thread_id, prompt, opts, true, Vec::new()).await
}
/// [`run_routine_turn`] with the routing card for the reply (`meta.routing`) and extra stop keys
@@ -1055,24 +1070,43 @@ pub(super) async fn run_routed_turn(
routing: Option<serde_json::Value>,
stop_keys: Vec<String>,
) -> Result<Option<String>, String> {
- run_turn_with(state, kwant, channel_id, thread_id, prompt, TurnOpts { routing, ..TurnOpts::default() }, stop_keys).await
+ let mut routing = Some(routing);
+ let opts = move || TurnOpts { routing: routing.take().flatten(), ..TurnOpts::default() };
+ run_turn_with(state, kwant, channel_id, thread_id, prompt, opts, false, stop_keys).await
}
-/// [`run_routed_turn`] with any turn options.
+/// [`run_routed_turn`] with any turn options (`opts` makes them; called again for each busy
+/// retry of an `unwatched` turn, see [`super::busy_retry::unwatched`]).
+#[allow(clippy::too_many_arguments)]
async fn run_turn_with(
state: &AppState,
kwant: &Kwant,
channel_id: Option<String>,
thread_id: Option<String>,
prompt: String,
- opts: TurnOpts,
+ mut opts: impl FnMut() -> TurnOpts,
+ unwatched: bool,
stop_keys: Vec<String>,
) -> Result<Option<String>, String> {
let context_key = thread_id.clone().or_else(|| channel_id.clone()).unwrap_or_else(|| kwant.id.clone());
let job = state.turns.start_job(std::iter::once(context_key.clone()).chain(stop_keys));
let scope = scope_for(state, kwant, channel_id, thread_id, &job, 0).await?;
- let reply = try_kwant_turn(&scope, kwant, prompt.clone(), opts).await;
- let reply = continue_once_if_capped(&scope, kwant, reply, false).await;
+ let reply = if unwatched {
+ let scope = &scope;
+ super::busy_retry::unwatched(scope, &kwant.name, &prompt, |p, slot| {
+ let mut o = opts();
+ o.busy_slot = Some(slot.clone());
+ // boxed, so the retry loop around the turn adds no stack to it
+ async move {
+ let reply = Box::pin(try_kwant_turn(scope, kwant, p, o)).await;
+ Box::pin(continue_once_if_capped_into(scope, kwant, reply, false, Some(&slot))).await
+ }
+ })
+ .await
+ } else {
+ let reply = try_kwant_turn(&scope, kwant, prompt.clone(), opts()).await;
+ continue_once_if_capped(&scope, kwant, reply, false).await
+ };
match reply {
Ok(text) => {
let reply_id = state
@@ -1090,10 +1124,15 @@ async fn run_turn_with(
Err(_) if job.token.is_cancelled() => Err("stopped by the user".into()),
// Today's spending stop held the turn: it never ran, so the caller records a skip
Err(why) if super::spend_stop::is_stop_error(&why) => Err(why),
- Err(why) => Err(format!("the bot's turn failed: {why}")),
+ Err(why) => Err(routine_turn_error(&why)),
}
}
+/// The error a routine run (or routed turn) records when its bot's turn failed with `why`.
+pub(super) fn routine_turn_error(why: &str) -> String {
+ format!("the bot's turn failed: {why}")
+}
+
/// The prompt of the one automatic continuation a routine's or delegation's turn gets when it ran
/// out of model calls (see [`continue_once_if_capped`]).
pub const CONTINUE_PROMPT: &str = "[kwnt: your last turn stopped at the limit of model calls before you finished. \
@@ -1108,6 +1147,18 @@ pub(super) async fn continue_once_if_capped(
kwant: &Kwant,
first: Result<String, String>,
always_ask: bool,
+) -> Result<String, String> {
+ continue_once_if_capped_into(scope, kwant, first, always_ask, None).await
+}
+
+/// [`continue_once_if_capped`] for an unwatched turn: the continuation, when there is one, is the
+/// turn that ended last, so only its busy step (if any) is left in `busy_slot`.
+pub(super) async fn continue_once_if_capped_into(
+ scope: &TurnScope,
+ kwant: &Kwant,
+ first: Result<String, String>,
+ always_ask: bool,
+ busy_slot: Option<&super::busy_retry::Slot>,
) -> Result<String, String> {
let Ok(text) = &first else {
return first;
@@ -1116,9 +1167,13 @@ pub(super) async fn continue_once_if_capped(
return first;
}
tracing::info!(kwant = %kwant.id, "turn hit the model-call cap: one automatic continuation");
+ if let Some(slot) = busy_slot {
+ let _ = slot.take();
+ }
let opts = TurnOpts {
label: Some("Automatic continuation (once): the last turn ran out of model calls".into()),
always_ask,
+ busy_slot: busy_slot.cloned(),
..Default::default()
};
match try_kwant_turn(scope, kwant, CONTINUE_PROMPT.to_string(), opts).await {
@@ -1949,6 +2004,15 @@ pub(super) struct TurnOpts {
pub(super) on_started: Option<futures::future::BoxFuture<'static, ()>>,
/// The retry of a turn a usage limit stopped (see [`super::parked`]): it never parks again.
pub(super) retried: bool,
+ /// The continuation of a reply a restart cut off (see [`super::restart_resume`]): a second
+ /// restart asks the person instead of continuing it again.
+ pub(super) resumed_after_restart: bool,
+ /// How many times kwnt already ran this message again because the browser was busy (see
+ /// [`super::busy_retry`]); at [`super::busy_retry::MAX_RETRIES`] the person is asked instead.
+ pub(super) busy_retries: u8,
+ /// A turn nobody watches (a routine run, a hand-off): a busy browser step it ends on is left
+ /// here for its caller to retry (see [`super::busy_retry::unwatched`]), never parked in a chat.
+ pub(super) busy_slot: Option<super::busy_retry::Slot>,
/// The delegation this turn works on; a parked retry restarts the delegation.
pub(super) delegation_id: Option<String>,
/// (agent, effort) to run on instead of asking Laya: a turn resumed after a late Allow
@@ -2387,6 +2451,11 @@ pub(super) async fn turn_once(
direct_kwant_id: scope.kwant_id.clone(),
thread_id: scope.thread_id.clone(),
started_at: chrono::Utc::now(),
+ asks: Some(stop_asks(scope, &opts)),
+ // What a restart needs to continue it (0.9.5); steps are added as they run
+ prompt: Some(truncate_chars(&prompt, 64 * 1024).to_string()),
+ steps: None,
+ resumed: Some(opts.resumed_after_restart),
};
if scope.state.db.add_running_turn(&running).await.is_ok() {
ended.running_row = Some(scope.state.db.clone());
@@ -2433,23 +2502,36 @@ pub(super) async fn turn_once(
/// Says in each chat which reply a previous run of kwnt cut off by stopping mid-turn. Runs once at
/// startup, before any new turn can start. The note's meta is
-/// `{"kind":"turn_interrupted","interrupted":true,"kwant_id","kwant_name","turn_id","started_at"}`.
+/// `{"kind":"turn_interrupted","interrupted":true,"kwant_id","kwant_name","turn_id","started_at"}`,
+/// plus `outward_step` (the tool name) when the cut-off step reached outside: no Retry then.
pub async fn interrupt_running_turns(state: &AppState) -> usize {
let Ok(turns) = state.db.take_running_turns().await else {
return 0;
};
for t in &turns {
+ // A reply in a person's own chat continues by itself, once (0.9.5)
+ if continue_after_restart(state, t).await {
+ continue;
+ }
+ // Cut off in the middle of a step that reaches outside (a send, a post, a push, a payment):
+ // it may already have gone out, so nothing runs it again by itself and the notice has no
+ // Retry (that resends the whole request); the person says whether to (0.9.5, deer-flow row)
+ let outward = super::restart_resume::cut_off_outward(t);
+ let text = match &outward {
+ Some(step) => super::restart_resume::outward_line(t, step),
+ None => format!("This reply from {} was interrupted by a restart. Send your message again to retry.", t.kwant_name),
+ };
let msg = NewMessage {
channel_id: t.channel_id.clone(),
direct_kwant_id: t.direct_kwant_id.clone(),
sender_role: "system".into(),
sender_id: "kwnt".into(),
- text: format!("This reply from {} was interrupted by a restart. Send your message again to retry.", t.kwant_name),
+ text: text.clone(),
reasoning_content: None,
tool_calls: None,
tokens_used: 0,
};
- let meta = json!({
+ let mut meta = json!({
"kind": "turn_interrupted",
"interrupted": true,
"kwant_id": t.kwant_id,
@@ -2457,10 +2539,27 @@ pub async fn interrupt_running_turns(state: &AppState) -> usize {
"turn_id": t.turn_id,
"started_at": t.started_at,
});
- let _ = state.db.insert_message_with(&msg, &MessageExtra { thread_id: t.thread_id.clone(), meta: Some(meta) }).await;
+ if let Some(step) = &outward {
+ meta["outward_step"] = json!(step.name);
+ }
+ let saved = state.db.insert_message_with(&msg, &MessageExtra { thread_id: t.thread_id.clone(), meta: Some(meta) }).await.ok();
if let Some(tid) = &t.thread_id {
let _ = state.db.touch_thread(tid).await;
}
+ // …and in Needs you, for a person's own chat (0.9.5)
+ if restart_asks(state, t).await {
+ let place = super::stopped::Place {
+ kwant_id: t.kwant_id.clone(),
+ channel_id: t.channel_id.clone(),
+ direct_kwant_id: t.direct_kwant_id.clone(),
+ thread_id: t.thread_id.clone(),
+ };
+ let line = match &outward {
+ Some(_) => text.clone(),
+ None => format!("{}'s reply was cut off when kwant restarted. Retry in the chat sends your message again.", t.kwant_name),
+ };
+ super::stopped::ask(state, &place, saved.as_ref().map(|m| m.id.as_str()), &line, super::stopped::Resume::ResendMessage).await;
+ }
}
if !turns.is_empty() {
tracing::info!(count = turns.len(), "marked chat replies cut short by a restart as interrupted");
@@ -2470,6 +2569,70 @@ pub async fn interrupt_running_turns(state: &AppState) -> usize {
turns.len()
}
+/// Whether a turn a restart cut off asks the person in Needs you: a person's own chat. A row from
+/// an older kwnt doesn't say: every chat but a hand-off's thread, which the Inbox reports.
+async fn restart_asks(state: &AppState, t: &crate::db::continuity::RunningTurn) -> bool {
+ match (t.asks, &t.thread_id) {
+ (Some(a), _) => a,
+ (None, Some(tid)) => state.db.delegation_for_thread(tid).await.ok().flatten().is_none(),
+ (None, None) => true,
+ }
+}
+
+/// Continues a reply in a person's own chat that a restart cut off, once, by parking it to run
+/// right away with a note on what was cut off (see [`super::restart_resume`]). False when it
+/// isn't continued: not a person's chat, already a continuation, no message recorded, or a card
+/// or browser step of that turn still waits on the person (answering it resumes the work).
+async fn continue_after_restart(state: &AppState, t: &crate::db::continuity::RunningTurn) -> bool {
+ if !restart_asks(state, t).await {
+ return false;
+ }
+ let Some(prompt) = super::restart_resume::prompt(t) else {
+ return false;
+ };
+ if state.db.turn_has_waiting_approval(&t.turn_id).await.unwrap_or(true)
+ || !state.db.open_human_steps_for_turn(&t.turn_id).await.map(|s| s.is_empty()).unwrap_or(false)
+ {
+ return false;
+ }
+ let parked = state
+ .db
+ .park_turn(&crate::db::parked::NewParkedTurn {
+ kwant_id: t.kwant_id.clone(),
+ channel_id: t.channel_id.clone(),
+ direct_kwant_id: t.direct_kwant_id.clone(),
+ thread_id: t.thread_id.clone(),
+ delegation_id: None,
+ depth: 0,
+ prompt,
+ retry_at: chrono::Utc::now(),
+ reason: super::parked::RESTART,
+ })
+ .await;
+ // One already waits in that chat (a usage-limit retry): the person is asked instead
+ let Ok(Some(_)) = parked else {
+ return false;
+ };
+ let msg = NewMessage {
+ channel_id: t.channel_id.clone(),
+ direct_kwant_id: t.direct_kwant_id.clone(),
+ sender_role: "system".into(),
+ sender_id: "kwnt".into(),
+ text: super::restart_resume::note_text(t),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let extra = MessageExtra { thread_id: t.thread_id.clone(), meta: Some(super::restart_resume::note_meta(t)) };
+ let _ = state.db.insert_message_with(&msg, &extra).await;
+ if let Some(tid) = &t.thread_id {
+ let _ = state.db.touch_thread(tid).await;
+ }
+ tracing::info!(kwant = %t.kwant_id, turn = %t.turn_id, "continuing a reply a restart cut off");
+ state.scheduler_wake.notify_one();
+ true
+}
+
/// `text` with every URL cut to scheme and host, so a failure reason that names a custom
/// endpoint can be stored without the credentials some endpoints carry in the userinfo,
/// path or query.
@@ -2509,6 +2672,8 @@ struct TurnEndedGuard {
impl Drop for TurnEndedGuard {
fn drop(&mut self) {
self.turns.end_turn(&self.tag.turn_id);
+ // a busy browser step a failed or stopped turn left behind is never retried
+ let _ = super::busy_retry::take(&self.tag.turn_id);
// However it ended (reply, error, stop, panic), the lead hears the hand-offs this turn started
super::delegation::release_held(&self.state, &self.tag.turn_id, self.turns.end_hold(&self.tag.turn_id));
if let (Some(db), Ok(rt)) = (self.running_row.take(), tokio::runtime::Handle::try_current()) {
@@ -3076,6 +3241,9 @@ async fn run_kwant_turn_inner(
let mut gave_up: Option<String> = None;
// Saved with the gave-up reply, so a client can offer Retry without reading its wording
let mut gave_up_meta: Option<serde_json::Value> = None;
+ // Set when the turn was parked behind a usage limit: it retries by itself at the reset, so
+ // its note asks nothing of the person (0.9.5, see `super::stopped`)
+ let mut resumes_itself = false;
let mut ran_on: Option<RanOn> = None;
// Only Claude's permission hook holds every call of a replay to the scratch folder. A
// Dev mode brief (J7) runs on Claude, whose hook holds every call to reading, or on Codex,
@@ -3103,6 +3271,7 @@ async fn run_kwant_turn_inner(
let at = super::profile_turn::clock_text(state, until).await;
let mut text = super::profile_turn::all_out_line(&at);
let parked = super::parked::park(scope, target_kwant, &park_prompt, opts.no_park(), opts.delegation_id.clone(), Some(until)).await;
+ resumes_itself = parked.is_some();
if parked.is_none() {
text = format!("Every model is out until {at}.");
}
@@ -3153,6 +3322,8 @@ async fn run_kwant_turn_inner(
}
// A stalled attempt is run once more as it was (P7, 2026-11-09): `Some(secs)` once it was
let mut stall_retried: Option<u64> = None;
+ // Its tool steps, kept with its running record so a restart knows what it cut off (0.9.5)
+ let mut restart_steps = super::restart_resume::Steps::default();
let mut next_attempt = 0;
while next_attempt < attempts.len() {
let i = next_attempt;
@@ -3342,6 +3513,9 @@ async fn run_kwant_turn_inner(
if let Some(e) = &event_opt {
stall_clock.saw(e, tokio::time::Instant::now());
state.turns.saw_step(&tag.turn_id, e);
+ if restart_steps.saw(e) {
+ let _ = state.db.set_running_steps(&tag.turn_id, &restart_steps.json()).await;
+ }
}
match event_opt {
Some(RuntimeEvent::TurnComplete { tokens, duration_ms, .. }) => {
@@ -3505,6 +3679,7 @@ async fn run_kwant_turn_inner(
if let Some(until) = again.all_out_until {
let at = super::profile_turn::clock_text(state, until).await;
let parked = super::parked::park(scope, target_kwant, &park_prompt, opts.no_park(), opts.delegation_id.clone(), Some(until)).await;
+ resumes_itself = parked.is_some();
let text = if parked.is_some() { super::profile_turn::all_out_line(&at) } else { format!("Every model is out until {at}.") };
event_broadcast.send(RuntimeEvent::TextDelta(text.clone()));
event_broadcast.send(RuntimeEvent::TurnComplete {
@@ -3531,6 +3706,7 @@ async fn run_kwant_turn_inner(
let mut text = text;
if failure.class == crate::profiles::classify::FailClass::Quota && !side_effects {
if let Some(line) = super::parked::park(scope, target_kwant, &park_prompt, opts.no_park(), opts.delegation_id.clone(), failure.retry_at).await {
+ resumes_itself = true;
text = format!("{text}\n\n{line}");
}
}
@@ -3613,8 +3789,13 @@ async fn run_kwant_turn_inner(
reasoning_content: with_notices(opts.label.clone()),
..scope.message("kwant", &target_kwant.name, text.clone())
};
- let meta = with_failure_meta(gave_up_meta, &opts.failure_meta);
- scope.save(&msg, super::activity::with_activity(meta, activity)).await;
+ let meta = with_failure_meta(super::stopped::gave_up_meta(gave_up_meta, resumes_itself), &opts.failure_meta);
+ let saved = scope.save(&msg, super::activity::with_activity(meta, activity)).await;
+ if !resumes_itself && stop_asks(scope, &opts) {
+ let place = super::stopped::Place::of_turn(scope, &target_kwant.id);
+ let line = super::stopped::reply_line(&text);
+ super::stopped::ask(state, &place, saved.as_ref().map(|m| m.id.as_str()), &line, super::stopped::Resume::ResendMessage).await;
+ }
}
return Err(text);
} else if let Some(Ok(Ok(output))) = driver_result {
@@ -3815,6 +3996,21 @@ async fn run_kwant_turn_inner(
}
}
}
+ // 0.9.5 (#9): the reply ended with its page on a sign-in form it asked nobody about
+ // (and no continuation of it is coming): the person gets one sign-in step for it
+ let continues = opts.delivery_next.as_ref().is_some_and(|n| n.lock().is_ok_and(|n| n.is_some()));
+ // 0.9.5: the reply ended with its last browser step refused because the browser was
+ // busy (by code): kwnt runs that step again by itself, bounded, or asks once
+ let busy_step = super::busy_retry::take(&tag.turn_id);
+ if let (Some(step), false, false, Some(slot)) = (&busy_step, continues, opts.no_tools, &opts.busy_slot) {
+ slot.put(step.clone());
+ } else if let (Some(step), false, false, true) = (&busy_step, continues, opts.no_tools, stop_asks(scope, &opts)) {
+ // boxed: inline, its state made this turn's future overflow a test thread's stack
+ Box::pin(super::busy_retry::after_turn(scope, target_kwant, &park_prompt, step, opts.busy_retries)).await;
+ } else if !continues && !opts.no_tools && stop_asks(scope, &opts) {
+ let probe = super::human_steps::ask_for_sign_in_wall(state, &turn_scope, &turn_page);
+ let _ = tokio::time::timeout(std::time::Duration::from_secs(10), probe).await;
+ }
return Ok(reply_text);
}
let why = match driver_result {
@@ -3829,7 +4025,11 @@ async fn run_kwant_turn_inner(
..scope.message("kwant", &target_kwant.name, turn_failed_text(&target_kwant.name, &why, &event_broadcast.activity))
};
let meta = with_failure_meta(Some(json!({"kind": "turn_failed"})), &opts.failure_meta);
- scope.save(&msg, super::activity::with_activity(meta, activity)).await;
+ let saved = scope.save(&msg, super::activity::with_activity(meta, activity)).await;
+ if let (Some(m), true) = (&saved, stop_asks(scope, &opts)) {
+ let place = super::stopped::Place::of_turn(scope, &target_kwant.id);
+ super::stopped::ask(state, &place, Some(&m.id), &super::stopped::reply_line(&m.text), super::stopped::Resume::ResendMessage).await;
+ }
}
if let Some(e) = driver_error {
event_broadcast.send(e);
@@ -4321,7 +4521,7 @@ async fn send_chat_routed(
target_kwant.name, target_kwant.title, reason
)));
- let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id).await;
+ let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id, from_person).await;
execute_single_turn(
state.clone(),
target_kwant.clone(),
@@ -4556,7 +4756,7 @@ async fn send_chat_routed(
return Ok(Json(v));
}
let team_keys = active_team.as_ref().map(|t| (t.id.clone(), t.name.clone()));
- let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id).await;
+ let held = held_send(&state, &target_kwant, &payload, &saved_user_msg.id, from_person).await;
execute_single_turn(
state.clone(),
target_kwant.clone(),
@@ -4679,7 +4879,7 @@ async fn send_to_thread(
let prompt = payload.prompt + &note;
let target = kwant.clone();
// H3: the message is saved and shows; its turn waits while the bot is stuck or waits on the person
- let held = super::bot_status::hold(&state, &kwant, &thread.id, "message", &saved.id).await;
+ let held = super::bot_status::hold_from(&state, &kwant, &thread.id, "message", &saved.id, from_person).await;
let held_id = held.as_ref().map(|_| saved.id.clone());
tokio::spawn(async move {
let _job = job;
@@ -4701,9 +4901,11 @@ async fn send_to_thread(
}
/// Holds a chat or 1:1 message to `kwant` while it is stuck or waits on the person elsewhere (H3).
-async fn held_send(state: &AppState, kwant: &Kwant, payload: &SendChatPayload, message_id: &str) -> Option<serde_json::Value> {
+/// The person's own message in the chat where the bot gave up after a stall is its Retry and goes
+/// now (0.9.5).
+async fn held_send(state: &AppState, kwant: &Kwant, payload: &SendChatPayload, message_id: &str, from_person: bool) -> Option<serde_json::Value> {
let context = payload.channel_id.clone().or_else(|| payload.kwant_id.clone()).unwrap_or_else(|| kwant.id.clone());
- super::bot_status::hold(state, kwant, &context, "message", message_id).await
+ super::bot_status::hold_from(state, kwant, &context, "message", message_id, from_person).await
}
/// A held send answers `status: "held"` with why (`release-090/h4-contract.md` §7a).
@@ -4733,6 +4935,23 @@ pub async fn resolve_approval(
Ok((status, Json(body)).into_response())
}
+/// `POST /api/approvals/:id/retry`: Retry on a card that expired unanswered (0.9.5). Starts a
+/// turn in the card's chat that makes the call again, so a fresh card asks the person. 409 when
+/// the card isn't expired (still waiting, answered, or Retry already ran).
+pub async fn retry_expired_approval(State(state): State<AppState>, Path(ticket_id): Path<String>) -> Response {
+ match super::mcp_runtime::retry_expired(&state, &ticket_id).await {
+ Some(body) => {
+ super::missions::listener::refresh_needs_you(&state).await;
+ (StatusCode::OK, Json(body)).into_response()
+ }
+ None => (
+ StatusCode::CONFLICT,
+ Json(json!({"ticket_id": ticket_id, "resumed": false, "error": "This card can't be retried: it isn't expired, or Retry already ran."})),
+ )
+ .into_response(),
+ }
+}
+
/// Answers an approval card: the app's route, and Telegram's Allow once (`via: "telegram"`, which
/// is recorded as the card's `answered_via`). Same checks either way: the production floor, and
/// only a card still waiting (or one kwant kept over a restart) can be answered.
@@ -4775,6 +4994,10 @@ pub(crate) async fn resolve_approval_inner(
// A card whose turn stopped waiting (or that kwant kept over a restart): a late answer,
// and Allow resumes the work
let reply = super::mcp_runtime::resume_late_approval(state, ticket_id, decision, status_str, via).await;
+ if reply.is_none() {
+ // Too old to answer: it expires now (if the sweep hasn't yet), and the chat says so
+ super::mcp_runtime::expire_unanswered(state).await;
+ }
super::missions::listener::refresh_needs_you(state).await;
return match reply {
Some(mut reply) => {
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index ddab8098..6a3607f8 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -598,10 +598,7 @@ pub async fn start_run_noted(state: &AppState, routine: RoutineRow, trigger: &st
kwant_name,
channel_id: routine.channel_id.clone(),
title: format!("Routine \"{}\" failed", routine.name),
- body: format!(
- "The routine \"{}\" did not finish. Open kwant bots to see its run history.",
- routine.name
- ),
+ body: failed_body(&routine.name, err),
thread_id: None,
card_id: None,
},
@@ -612,6 +609,20 @@ pub async fn start_run_noted(state: &AppState, routine: RoutineRow, trigger: &st
Some(run)
}
+/// The notification for a routine run that failed (0.9.5): what stopped, why (the error's first
+/// line, clipped) and what to do about it.
+pub fn failed_body(name: &str, err: Option<&str>) -> String {
+ let why = err.map(super::stopped::short_line).filter(|w| !w.is_empty());
+ let why: Option<String> = why.map(|w| {
+ let w = w.trim_end_matches('.');
+ if w.chars().count() > 160 { format!("{}…", w.chars().take(160).collect::<String>().trim_end()) } else { w.to_string() }
+ });
+ match why {
+ Some(why) => format!("The routine \"{name}\" did not finish: {why}. Open the routine to see the run or run it again."),
+ None => format!("The routine \"{name}\" did not finish. Open the routine to see the run or run it again."),
+ }
+}
+
fn send_run_event(state: &AppState, run: &RoutineRun) {
let _ = state.event_sender.send(RuntimeEvent::RoutineRun {
routine_id: run.routine_id.clone(),
@@ -838,6 +849,8 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) -> tokio::task::JoinH
// G2: bots whose budget pause ended on its own (a new month) start what they held
super::bot_budget::release_due(&state).await;
super::parked::run_due(&state, Utc::now()).await;
+ // 0.9.5: an approval card nobody answered in time tells its chat, with Retry
+ super::mcp_runtime::expire_unanswered(&state).await;
super::waiting::run_due(&state, Utc::now()).await;
super::work_ahead::scan(&state, Utc::now(), false).await;
super::idea_jar::scan(&state, Utc::now(), false).await;
@@ -885,3 +898,20 @@ pub fn spawn_background(state: AppState, shutdown: CancellationToken) {
super::telegram::spawn(state.clone(), shutdown.clone());
spawn(state, shutdown);
}
+
+#[cfg(test)]
+mod no_silent_stop_tests {
+ use super::failed_body;
+
+ #[test]
+ fn a_failed_routine_says_why_and_what_to_do() {
+ assert_eq!(
+ failed_body("Daily digest", Some("⚠️ [Ben] The model sent nothing for 300 s, so this reply was stopped.\nmore")),
+ "The routine \"Daily digest\" did not finish: The model sent nothing for 300 s, so this reply was stopped. Open the routine to see the run or run it again."
+ );
+ assert_eq!(failed_body("D", None), "The routine \"D\" did not finish. Open the routine to see the run or run it again.");
+ assert_eq!(failed_body("D", Some(" \n ")), failed_body("D", None));
+ let long = failed_body("D", Some(&"x".repeat(500)));
+ assert!(long.contains(&format!("{}…", "x".repeat(160))) && !long.contains(&"x".repeat(161)), "{long}");
+ }
+}
diff --git a/src/server/stopped.rs b/src/server/stopped.rs
new file mode 100644
index 00000000..c2536155
--- /dev/null
+++ b/src/server/stopped.rs
@@ -0,0 +1,227 @@
+//! 0.9.5 "Runs never stop silently": when a bot's work in a person's chat stops without finishing
+//! and nothing will pick it up by itself, the person gets exactly one ask. It goes in the chat (the
+//! notice the stop already posts, which carries Retry or Continue) and in Needs you, as a
+//! `waiting_on_person` item of kind `stopped` whose line says what stopped, why, and the one action
+//! that resumes it. The item closes when the person writes in that chat (Retry resends their
+//! message), when a later reply of that bot there finishes, when its Continue or Retry runs, or
+//! when the stop resolves itself.
+//!
+//! Stops that already resume by themselves get no item: a turn parked behind a usage limit (it
+//! retries at the reset), a stall's one automatic retry, the delivery check's one continuation.
+//! Hand-offs, routine runs and mission tasks have their own Inbox and board entries, so their
+//! turns add none here (see [`for_turn`]).
+
+use super::AppState;
+use crate::db::waiting::WaitingItem;
+use serde_json::{json, Value};
+
+/// Longest line a stopped item keeps (it is shown on one row).
+pub const MAX_LINE_CHARS: usize = 200;
+
+/// The chat a stop happened in.
+#[derive(Debug, Clone, Default)]
+pub struct Place {
+ pub kwant_id: String,
+ pub channel_id: Option<String>,
+ pub direct_kwant_id: Option<String>,
+ pub thread_id: Option<String>,
+}
+
+impl Place {
+ /// `kwant`'s place in a turn's chat; a thread keeps only its thread id (as messages do).
+ pub(super) fn of_turn(scope: &super::routes::TurnScope, kwant_id: &str) -> Self {
+ Self {
+ kwant_id: kwant_id.to_string(),
+ channel_id: scope.channel_id.clone(),
+ direct_kwant_id: scope.kwant_id.clone(),
+ thread_id: scope.thread_id.clone(),
+ }
+ }
+}
+
+/// What resumes a stop when it isn't the chat's own Retry.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Resume {
+ /// Retry resends the person's last message in that chat (the notice's Retry button).
+ ResendMessage,
+ /// The notice's Continue button (a chain paused at its budget or hand-off cap).
+ Continue,
+ /// `POST /api/approvals/:id/retry` asks again for an approval that expired unanswered.
+ Approval { approval_id: String },
+}
+
+impl Resume {
+ fn json(&self) -> Option<String> {
+ match self {
+ Resume::ResendMessage => None,
+ Resume::Continue => Some(json!({"type": "continue"}).to_string()),
+ Resume::Approval { approval_id } => Some(json!({"type": "approval", "approval_id": approval_id}).to_string()),
+ }
+ }
+}
+
+/// One short line: the text with a leading "⚠️ [Bot] " cut, its first non-empty line, clipped.
+pub fn short_line(text: &str) -> String {
+ let t = text.trim_start();
+ let t = t.strip_prefix("⚠️").map(str::trim_start).unwrap_or(t);
+ let t = match t.strip_prefix('[').and_then(|r| r.split_once("] ")) {
+ Some((name, rest)) if !name.contains('\n') && name.chars().count() <= 80 => rest,
+ _ => t,
+ };
+ let first = t.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
+ let clipped: String = first.chars().take(MAX_LINE_CHARS).collect();
+ if clipped.chars().count() < first.chars().count() {
+ format!("{}…", clipped.trim_end())
+ } else {
+ clipped
+ }
+}
+
+/// The Needs-you line for a reply that stopped: what stopped (in the bot's notice's own words, so
+/// the why is there) and what resumes it.
+pub fn reply_line(notice: &str) -> String {
+ let what = short_line(notice);
+ // The notice's own "send it again" advice is replaced by the one action below, not repeated
+ let what = what.trim_end().strip_suffix(OWN_RETRY_ADVICE).unwrap_or(what.trim_end()).trim_end();
+ let what = what.trim_end_matches('.');
+ if what.is_empty() {
+ "The reply stopped before it finished. Retry in the chat sends your message again.".into()
+ } else {
+ format!("{what}. Retry in the chat sends your message again.")
+ }
+}
+
+/// The advice a stall notice ends with (`turns::stall_stop_line`), which the item's action replaces.
+const OWN_RETRY_ADVICE: &str = "Send your message again to retry.";
+
+/// An item's one-row title, at most `max` characters: when it's too long, what stopped is clipped
+/// and its last sentence (the action that resumes it) is kept whole.
+pub fn title(text: &str, max: usize) -> String {
+ let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ if line.chars().count() <= max {
+ return line;
+ }
+ if let Some(i) = line.trim_end_matches('.').rfind(". ") {
+ let action = &line[i + 2..];
+ let room = max.saturating_sub(action.chars().count() + 2);
+ if room >= 24 {
+ let what: String = line[..i].chars().take(room).collect();
+ return format!("{}… {action}", what.trim_end());
+ }
+ }
+ let cut: String = line.chars().take(max.saturating_sub(1)).collect();
+ format!("{}…", cut.trim_end())
+}
+
+/// Records the ask (clients refresh Needs you on the notice's message, posted with it).
+pub async fn ask(state: &AppState, place: &Place, message_id: Option<&str>, line: &str, resume: Resume) -> Option<WaitingItem> {
+ let line: String = line.chars().take(MAX_LINE_CHARS + 120).collect();
+ let item = state
+ .db
+ .add_stopped(
+ &place.kwant_id,
+ place.channel_id.as_deref(),
+ place.direct_kwant_id.as_deref(),
+ place.thread_id.as_deref(),
+ message_id,
+ &line,
+ resume.json().as_deref(),
+ )
+ .await
+ .ok()?;
+ tracing::info!(waiting_id = %item.id, kwant_id = %place.kwant_id, "a bot's work stopped: asked the person to resume it");
+ Some(item)
+}
+
+/// A reply of the bot in that chat finished: whatever stopped there before has moved on.
+pub async fn recovered(state: &AppState, place: &Place) {
+ let _ = state
+ .db
+ .close_stopped(&place.kwant_id, place.channel_id.as_deref(), place.direct_kwant_id.as_deref(), place.thread_id.as_deref())
+ .await;
+}
+
+/// Whether a turn that stopped gets a Needs-you item of its own: only a person's chat (depth 0)
+/// whose stop notice was saved. A hand-off, a routine run, a mission task, a discussion round, a
+/// replay or an unsaved view is reported where it belongs (Inbox, board, its caller).
+pub(super) fn for_turn(depth: i64, quiet_failure: bool, unsaved: bool, discussion: bool, rehearse: bool, routine: bool) -> bool {
+ depth == 0 && !quiet_failure && !unsaved && !discussion && !rehearse && !routine
+}
+
+/// The meta a gave-up reply is saved with when it has none of its own: marks it as a failure the
+/// chat offers Retry on. `None` for a turn that resumes by itself (parked behind a limit).
+pub fn gave_up_meta(meta: Option<Value>, resumes_itself: bool) -> Option<Value> {
+ match (meta, resumes_itself) {
+ (Some(m), _) => Some(m),
+ (None, true) => None,
+ (None, false) => Some(json!({"kind": "turn_failed", "gave_up": true})),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn lines_are_short_and_drop_the_bot_tag() {
+ assert_eq!(short_line("⚠️ [Ben] Couldn't finish this reply: boom\nmore"), "Couldn't finish this reply: boom");
+ assert_eq!(short_line("\n plain line \n"), "plain line");
+ let long = short_line(&format!("⚠️ [B] {}", "x".repeat(400)));
+ assert!(long.ends_with('…') && long.chars().count() == MAX_LINE_CHARS + 1, "{long}");
+ // A bracket that isn't a bot tag stays
+ assert_eq!(short_line("[draft without close"), "[draft without close");
+ }
+
+ #[test]
+ fn reply_lines_say_what_resumes_it() {
+ assert_eq!(
+ reply_line("⚠️ [Ben] The model sent nothing for 300 s, so this reply was stopped."),
+ "The model sent nothing for 300 s, so this reply was stopped. Retry in the chat sends your message again."
+ );
+ assert!(reply_line("").starts_with("The reply stopped before it finished."));
+ // A stall notice's own advice isn't repeated next to the action
+ assert_eq!(
+ reply_line(&super::super::turns::stall_stop_line("Ben", 2, true)),
+ "The model sent nothing for 2 s, twice (it was retried once), so this reply was stopped. Retry in the chat sends your message again."
+ );
+ }
+
+ #[test]
+ fn a_long_title_keeps_the_action_that_resumes_it() {
+ let action = "Retry in the chat sends your message again.";
+ let long = format!("Couldn't finish this reply: {}. {action}", "the driver failed with a long error ".repeat(5));
+ let t = title(&long, 120);
+ assert!(t.chars().count() <= 120 && t.ends_with(&format!("… {action}")) && t.starts_with("Couldn't finish this reply:"), "{t}");
+ assert_eq!(title(" Short. Retry here. ", 120), "Short. Retry here.");
+ // No sentence to keep: plain clip
+ let one = "x".repeat(300);
+ assert_eq!(title(&one, 120).chars().count(), 120);
+ assert!(title(&one, 120).ends_with('…'));
+ }
+
+ #[test]
+ fn only_a_persons_own_chat_gets_an_item() {
+ assert!(for_turn(0, false, false, false, false, false));
+ assert!(!for_turn(1, false, false, false, false, false), "hand-offs are in the Inbox");
+ assert!(!for_turn(0, true, false, false, false, false), "quiet failures: the caller reports");
+ assert!(!for_turn(0, false, true, false, false, false));
+ assert!(!for_turn(0, false, false, true, false, false));
+ assert!(!for_turn(0, false, false, false, true, false));
+ assert!(!for_turn(0, false, false, false, false, true), "routine runs are in the Inbox");
+ }
+
+ #[test]
+ fn a_parked_turn_gets_no_retry_meta() {
+ assert_eq!(gave_up_meta(None, true), None);
+ assert_eq!(gave_up_meta(None, false), Some(json!({"kind": "turn_failed", "gave_up": true})));
+ let stall = json!({"kind": "turn_stalled"});
+ assert_eq!(gave_up_meta(Some(stall.clone()), false), Some(stall));
+ }
+
+ #[test]
+ fn resume_kinds_serialize() {
+ assert_eq!(Resume::ResendMessage.json(), None);
+ let a = Resume::Approval { approval_id: "ap1".into() }.json().unwrap();
+ assert_eq!(serde_json::from_str::<Value>(&a).unwrap(), json!({"type": "approval", "approval_id": "ap1"}));
+ }
+}
diff --git a/src/server/waiting.rs b/src/server/waiting.rs
index 94261329..bf7798d6 100644
--- a/src/server/waiting.rs
+++ b/src/server/waiting.rs
@@ -49,6 +49,8 @@ fn last_line(text: &str) -> &str {
/// delegation) a reply that ends by asking the person something without handing on to a teammate.
pub(super) async fn turn_ended(scope: &TurnScope, kwant: &Kwant, turn_id: &str, reply: &str) {
let state = &scope.state;
+ // A reply finished here: what stopped in this chat before has moved on (0.9.5)
+ super::stopped::recovered(state, &super::stopped::Place::of_turn(scope, &kwant.id)).await;
let hours = follow_up_hours(state).await;
let due_at = (hours > 0).then(|| Utc::now() + Duration::hours(hours));
let open = state.db.list_questions(Some("open"), None, None).await.unwrap_or_default();
@@ -196,8 +198,15 @@ pub async fn list(State(state): State<AppState>, super::spaces::Scope(space): su
}
seen.insert(q.clone());
}
+ let kind = match (&w.question_id, w.kind.as_deref()) {
+ (Some(_), _) => "question",
+ (None, Some(crate::db::waiting::STOPPED)) => "stopped",
+ _ => "reply",
+ };
items.push((w.created_at, json!({
- "kind": if w.question_id.is_some() { "question" } else { "reply" },
+ "kind": kind,
+ "id": w.id,
+ "retry": w.retry.as_deref().and_then(|r| serde_json::from_str::<Value>(r).ok()),
"kwant_id": w.kwant_id,
"kwant_name": name(&w.kwant_id),
"channel_id": w.channel_id,
diff --git a/tests/chain_budget_test.rs b/tests/chain_budget_test.rs
index 9648237d..8bcb277d 100644
--- a/tests/chain_budget_test.rs
+++ b/tests/chain_budget_test.rs
@@ -224,8 +224,17 @@ async fn the_continue_button_carries_a_paused_chain_on() {
env.say("@Ann look at this MENTION:Bob").await;
env.wait_for("the notice", || async { !env.notices().await.is_empty() }).await;
let notice = env.notices().await.remove(0);
+ // 0.9.5: the pause is in Needs you too, once, with the notice's Continue
+ let stopped = |away: Value| -> Vec<Value> { away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").cloned().collect() };
+ let items = stopped(ok(&env.app, "GET", "/api/away", None).await);
+ assert_eq!(items.len(), 1, "{items:?}");
+ assert_eq!(items[0]["message_id"], notice.id.as_str());
+ assert_eq!(items[0]["retry"], json!({"type": "continue"}));
+ let title = items[0]["title"].as_str().unwrap();
+ assert!(title.contains("Bob") && title.ends_with("Continue in the chat carries on."), "{title}");
ok(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
env.wait_for("Bob's turn", || async { env.replies_from("Bob").await == 1 }).await;
+ assert!(stopped(ok(&env.app, "GET", "/api/away", None).await).is_empty(), "Continue answered it");
assert!(env.messages().await.iter().any(|m| m.sender_role == "user" && m.text == "continue"), "the person's continue is in the chat");
// Not a notice: refused
let first = env.messages().await.remove(0);
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 0cae31db..f4524ffd 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -1808,6 +1808,8 @@ async fn a_result_reported_after_the_next_hand_off_started_still_reaches_the_lea
direct_kwant_id: None,
thread_id: None,
started_at: chrono::Utc::now(),
+ asks: None,
+ ..Default::default()
};
delegation::release_cut_short(&env.state, &[turn]).await;
wait_or_dump(&env, &channel, "the lead's turn with the first result", || async {
diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rs
index 6a44e6b6..82198f3d 100644
--- a/tests/late_approval_test.rs
+++ b/tests/late_approval_test.rs
@@ -219,3 +219,64 @@ async fn a_late_allow_on_an_audit_card_runs_nothing() {
assert!(!env.state.broker.drop_grant(&env.a, &env.a, tool, &json!({"command": "ls AUDIT_LATE_MARK", "description": "list"})).await, "no grant left");
}
}
+
+/// 0.9.5: a card nobody answered in 24 h expires with one ask. The chat gets a notice that says
+/// what didn't run and why, Needs you gets one stopped item, and Retry starts a turn that makes the
+/// call again (granting nothing, so a fresh card asks). Retry runs once.
+#[tokio::test]
+async fn an_expired_card_says_so_once_and_retry_asks_again() {
+ let env = setup().await;
+ let args = json!({"command": "ls EXPIRED_RETRY_MARK", "description": "list"});
+ let ticket = unanswered(&env, args.clone()).await;
+ env.state.db.backdate_approval_for_test(&ticket, 25).await.unwrap();
+ assert_eq!(kwnt::server::mcp_runtime::expire_unanswered(&env.state).await, 1);
+ assert_eq!(kwnt::server::mcp_runtime::expire_unanswered(&env.state).await, 0, "each card expires once");
+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "expired");
+
+ // One notice in the chat it was asked in
+ let msgs = env.state.db.list_messages(&env.a, 50).await.unwrap();
+ let notices: Vec<_> = msgs.iter().filter(|m| m.meta.as_deref().is_some_and(|x| x.contains("approval_expired"))).collect();
+ assert_eq!(notices.len(), 1, "{msgs:?}");
+ let note = notices[0];
+ assert_eq!(note.sender_role, "system");
+ assert!(note.text.contains("stopped waiting for your OK to use Bash"), "{}", note.text);
+ assert!(note.text.contains("Retry asks you again"), "{}", note.text);
+ let meta: Value = serde_json::from_str(note.meta.as_deref().unwrap()).unwrap();
+ assert_eq!(meta["approval_id"], ticket.as_str());
+
+ // One stopped item in Needs you, whose Retry is the card's; the expired card itself is gone
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ let waiting = away["waiting"].as_array().unwrap();
+ assert!(!waiting.iter().any(|i| i["id"] == ticket.as_str() && i["kind"] == "approval"));
+ let items: Vec<_> = waiting.iter().filter(|i| i["kind"] == "stopped").collect();
+ assert_eq!(items.len(), 1, "{away}");
+ assert_eq!(items[0]["retry"], json!({"type": "approval", "approval_id": ticket}));
+ assert_eq!(items[0]["message_id"], note.id.as_str());
+ assert_eq!(items[0]["link"]["direct_kwant_id"], env.a.as_str());
+ let (_, inbox) = call(&env.app, "GET", "/api/inbox", None).await;
+ assert!(inbox["items"].as_array().unwrap().iter().any(|i| i["kind"] == "stopped" && i["group"] == "waiting_on_you"), "{inbox}");
+
+ // A late answer can't run it
+ let (s, _) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "allow_once"}))).await;
+ assert_eq!(s.as_u16(), 409);
+
+ // Retry: a new turn makes the call again, nothing is granted, the item closes
+ let (s, v) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/retry"), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(v["resumed"], "new_turn");
+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "retried");
+ wait_for("the retry turn", || async { !invocations_with("ls EXPIRED_RETRY_MARK").is_empty() }).await;
+ let prompt = invocations_with("ls EXPIRED_RETRY_MARK").pop().unwrap();
+ assert!(prompt.contains("[The person pressed Retry on a tool call that waited too long for their OK]"), "{prompt}");
+ assert!(!env.state.broker.drop_grant(&env.a, &env.a, "Bash", &args).await, "Retry grants nothing");
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert!(!away["waiting"].as_array().unwrap().iter().any(|i| i["kind"] == "stopped"), "{away}");
+
+ // Retry runs once; a card that never expired can't be retried
+ let (s, _) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/retry"), None).await;
+ assert_eq!(s.as_u16(), 409);
+ let fresh = unanswered(&env, json!({"command": "ls NOT_EXPIRED_MARK"})).await;
+ let (s, _) = call(&env.app, "POST", &format!("/api/approvals/{fresh}/retry"), None).await;
+ assert_eq!(s.as_u16(), 409);
+ assert_eq!(env.state.db.get_approval(&fresh).await.unwrap().unwrap().status, "waiting");
+}
diff --git a/tests/mission_autofix_test.rs b/tests/mission_autofix_test.rs
index ce40af3c..14712393 100644
--- a/tests/mission_autofix_test.rs
+++ b/tests/mission_autofix_test.rs
@@ -641,6 +641,10 @@ async fn auth_budget_and_denied_are_never_retried_and_ask_the_person() {
assert_eq!(t["last_failure"]["class"], "budget", "{t}");
assert!(kinds(&t["needs_you"]).contains(&"fix_needed".to_string()), "{t}");
assert!(attempts(&e, &budget).await.iter().all(|a| a.status == "skipped"));
+ // 0.9.5: kwant stopped it, so the owner's chat says so once: what, why, what carries it on
+ let lines: Vec<_> = e.state.db.list_messages(&e.bot.id, 50).await.unwrap().into_iter().filter(|m| m.text.starts_with("Blocked: \"Small\"")).collect();
+ assert_eq!(lines.len(), 1, "{lines:?}");
+ assert!(lines[0].text.ends_with("Move it back to the backlog on the board to carry on."), "{}", lines[0].text);
let (status, v) = send(&e.app, "POST", &format!("/api/tasks/{budget}/autofix"), None, None).await;
assert_eq!((status, v["code"].as_str()), (StatusCode::CONFLICT, Some("not_retryable")), "{v}");
kwnt::server::missions::autofix::run_due(&e.state).await;
diff --git a/tests/restart_cards_test.rs b/tests/restart_cards_test.rs
index bffdc101..c0d183b2 100644
--- a/tests/restart_cards_test.rs
+++ b/tests/restart_cards_test.rs
@@ -124,6 +124,8 @@ async fn a_card_with_no_chat_resumes_where_its_turn_was_running() {
direct_kwant_id: None,
thread_id: Some(thread.id.clone()),
started_at: chrono::Utc::now(),
+ asks: None,
+ ..Default::default()
};
env.state.db.add_running_turn(&turn).await.unwrap();
// And one from a turn nobody recorded lands in the bot's direct chat
diff --git a/tests/sign_in_wall_test.rs b/tests/sign_in_wall_test.rs
new file mode 100644
index 00000000..e09fbb85
--- /dev/null
+++ b/tests/sign_in_wall_test.rs
@@ -0,0 +1,250 @@
+//! 0.9.5 (#9) "Runs never stop silently": a bot's turn that ends with its browser page on a
+//! sign-in form it didn't get past, and that asked the person nothing, leaves one specific ask:
+//! "<Bot> needs you to sign in to <site> in the browser panel, then it continues." It is a sign-in
+//! step on that turn's own job page (0.9.3 per-job pages), listed in Needs you, and its Done
+//! starts the bot again. The same site on the same page is asked about once per 12 h, so a bot
+//! that keeps landing on the form doesn't pile up asks. A fake claude CLI on PATH drives the
+//! browser through the shell API (curl) like a bot without kwnt's tools. Its own test binary: it
+//! changes PATH. Skipped when no Chrome or Chromium is installed.
+
+#[path = "common/exe.rs"]
+mod exe;
+#[path = "support/chrome_guard.rs"]
+mod chrome_guard;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use chrome_guard::ChromeGuard;
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{human_steps::HumanStep, Database},
+ router::LayaRouter,
+ sandbox::computer,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tower::ServiceExt;
+
+/// Records its arguments to `$KWNT_TEST_BEHAVE/<bot>.prompt`; with `<bot>.curl` holding a page
+/// address, opens it through the browser API from the system prompt (saving the HTTP status to
+/// `<bot>.status`), then ends its turn without asking anyone anything.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+me=$(printf '%s\n' "$@" | sed -n 's/.*You are \([A-Za-z0-9]*\), .*/\1/p' | head -n 1)
+dir="$KWNT_TEST_BEHAVE"
+printf '%s\n' "$@" > "$dir/$me.prompt"
+if [ -f "$dir/$me.curl" ]; then
+ api=$(printf '%s\n' "$@" | sed -n 's/^Browser API: \(http[^ ]*\).*/\1/p' | head -n 1)
+ url=$(cat "$dir/$me.curl")
+ curl -sS -o /dev/null -w '%{http_code}' -X POST "$api/navigate" -H 'Content-Type: application/json' -d "{\"url\":\"$url\"}" > "$dir/$me.status"
+fi
+echo '{"type":"result","is_error":false,"num_turns":1,"result":"The page wants a login, so I stopped there."}'
+"#;
+
+const LOGIN_PAGE: &str = r#"<!doctype html><html><head><title>Log in</title></head><body>
+<form><label>Email <input type="email" name="email"></label>
+<label>Password <input type="password" name="password"></label><button>Log in</button></form>
+</body></html>"#;
+
+const PLAIN_PAGE: &str = r#"<!doctype html><html><head><title>Prices</title></head><body>
+<h1>Prices</h1><p>Plain page, no form.</p><input type="password" style="display:none"></body></html>"#;
+
+fn behave_dir() -> &'static PathBuf {
+ static DIR: OnceLock<PathBuf> = OnceLock::new();
+ DIR.get_or_init(|| {
+ let root = tempfile::tempdir().unwrap().keep();
+ let (bin, behave) = (root.join("bin"), root.join("behave"));
+ for d in [&bin, &behave] {
+ std::fs::create_dir_all(d).unwrap();
+ }
+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);
+ std::env::set_var("KWNT_TEST_BEHAVE", &behave);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ behave
+ })
+}
+
+fn read(bot: &str, what: &str) -> String {
+ std::fs::read_to_string(behave_dir().join(format!("{bot}.{what}"))).unwrap_or_default()
+}
+
+/// Serves `/login` and `/plain` on 127.0.0.1.
+async fn serve_pages() -> String {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ tokio::spawn(async move {
+ while let Ok((mut stream, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 4096];
+ let n = stream.read(&mut buf).await.unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..n]);
+ let path = request.split_whitespace().nth(1).unwrap_or("/").to_string();
+ let (status, body) = match path.as_str() {
+ "/login" => ("200 OK", LOGIN_PAGE),
+ "/plain" => ("200 OK", PLAIN_PAGE),
+ _ => ("404 Not Found", ""),
+ };
+ let reply = format!("HTTP/1.1 {status}\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
+ let _ = stream.write_all(reply.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://127.0.0.1:{port}")
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ site: String,
+ _chrome: ChromeGuard,
+ _tmp: tempfile::TempDir,
+}
+
+/// kwnt on a real port (the shell API is curled), with a windowless Chrome as the VM browser and
+/// kwnt's own agent tools off (the bot only has curl).
+async fn setup() -> Option<Env> {
+ behave_dir();
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return None;
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let profile = tmp.path().join("chrome");
+ let (endpoint, _) = computer::ensure_local_chrome(&profile, true).await.expect("Chrome starts");
+ let chrome = ChromeGuard(profile);
+ std::env::set_var("KWNT_COMPUTER_MODE", "vm");
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let config = Config {
+ data_dir: data.clone(),
+ port: listener.local_addr().unwrap().port(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some(endpoint),
+ ..Config::default()
+ };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let app = create_router(state.clone());
+ let served = app.clone();
+ tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });
+ let env = Env { app, state, site: serve_pages().await, _chrome: chrome, _tmp: tmp };
+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"agent_tools": false}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ Some(env)
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let resp = app.clone().oneshot(req.body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+async fn add_bot(env: &Env, name: &str) -> String {
+ let (s, v) = call(&env.app, "POST", "/api/kwants", Some(json!({"name": name, "title": "Researcher", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ v["id"].as_str().or(v["kwant"]["id"].as_str()).unwrap().to_string()
+}
+
+/// Waits until no turn runs (for a while).
+async fn settle(env: &Env) {
+ let mut quiet = 0;
+ for _ in 0..600 {
+ quiet = if env.state.turns.active_turns().is_empty() { quiet + 1 } else { 0 };
+ if quiet >= 10 {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("the turn never ended");
+}
+
+async fn steps_of(env: &Env, bot: &str, status: Option<&str>) -> Vec<HumanStep> {
+ env.state.db.list_human_steps(status, None, None).await.unwrap().into_iter().filter(|s| s.kwant_id == bot).collect()
+}
+
+async fn send(env: &Env, bot: &str, prompt: &str) {
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": bot, "prompt": prompt, "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ settle(env).await;
+}
+
+#[tokio::test]
+async fn a_turn_that_ends_on_a_sign_in_form_asks_the_person_once_to_sign_in() {
+ let Some(env) = setup().await else { return };
+ let bot = add_bot(&env, "Ben").await;
+ let login = format!("{}/login", env.site);
+ std::fs::write(behave_dir().join("Ben.curl"), &login).unwrap();
+ send(&env, &bot, "check my orders on the shop").await;
+ assert_eq!(read("Ben", "status"), "200", "the bot opened the page");
+ assert!(read("Ben", "prompt").contains(&format!("/api/sandbox/{bot}/bot/{bot}/chat/{bot}")), "its own job page: {}", read("Ben", "prompt"));
+
+ // One specific ask: who, which site, where, and what happens next
+ let open = steps_of(&env, &bot, Some("open")).await;
+ assert_eq!(open.len(), 1, "{open:?}");
+ let step = &open[0];
+ assert_eq!((step.kind.as_str(), step.source.as_str()), ("sign_in", "auto"));
+ assert_eq!(step.reason, "Ben needs you to sign in to 127.0.0.1 in the browser panel, then it continues.");
+ assert_eq!(step.url.as_deref(), Some(login.as_str()));
+ assert!(step.turn_id.is_some(), "the step belongs to the turn that ended on the form");
+ // On the turn's own page (0.9.3): the team page stays free for other jobs
+ let page = kwnt::server::browser_pages::job_page_key(&bot, &bot, &bot).unwrap();
+ assert_eq!(step.page_key.as_deref(), Some(page.as_str()));
+ assert_eq!(step.sandbox_target.as_deref(), Some(bot.as_str()));
+ // Its card is in the chat
+ let card = env.state.db.get_message(step.message_id.as_deref().unwrap()).await.unwrap().unwrap();
+ assert!(env.state.db.list_messages(&bot, 50).await.unwrap().iter().any(|m| m.id == card.id));
+ // And in Needs you, in the same words
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ let items: Vec<_> = away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").cloned().collect();
+ assert_eq!(items.len(), 1, "{away}");
+ assert_eq!(items[0]["human_step_id"], step.id.as_str());
+ assert_eq!(items[0]["summary"], step.reason.as_str());
+ assert_eq!(items[0]["link"]["direct_kwant_id"], bot.as_str());
+
+ // The person signs in and presses Done: a new turn picks the task up, ends on the same form
+ // again (still logged out), and is not asked about it a second time within 12 h
+ std::fs::remove_file(behave_dir().join("Ben.prompt")).unwrap();
+ let (s, v) = call(&env.app, "POST", &format!("/api/human-steps/{}/done", step.id), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["resumed"], "new_turn");
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ settle(&env).await;
+ assert!(read("Ben", "prompt").contains("The person did the browser step you asked for earlier"));
+ let all = steps_of(&env, &bot, None).await;
+ let seen: Vec<_> = all.iter().map(|s| (&s.kind, &s.status, &s.source, &s.url, &s.page_key, &s.sandbox_target, &s.turn_id, s.created_at)).collect();
+ assert!(all.iter().all(|s| s.status != "open"), "no second ask for the same site and page: {seen:?}");
+ assert_eq!(all.len(), 1, "{seen:?}");
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert!(!away["waiting"].as_array().unwrap().iter().any(|i| i["kind"] == "stopped"), "{away}");
+}
+
+#[tokio::test]
+async fn a_turn_that_ends_on_a_page_without_a_sign_in_form_asks_nothing() {
+ let Some(env) = setup().await else { return };
+ let bot = add_bot(&env, "Cleo").await;
+ std::fs::write(behave_dir().join("Cleo.curl"), format!("{}/plain", env.site)).unwrap();
+ send(&env, &bot, "read the prices page").await;
+ assert_eq!(read("Cleo", "status"), "200");
+ assert!(steps_of(&env, &bot, None).await.is_empty(), "a hidden password field is no wall");
+}
+
+#[tokio::test]
+async fn a_turn_that_never_opened_the_browser_asks_nothing() {
+ let Some(env) = setup().await else { return };
+ let bot = add_bot(&env, "Dora").await;
+ send(&env, &bot, "just say hi").await;
+ assert!(steps_of(&env, &bot, None).await.is_empty());
+}
diff --git a/tests/turn_recovery_test.rs b/tests/turn_recovery_test.rs
index eea3d899..52ba775a 100644
--- a/tests/turn_recovery_test.rs
+++ b/tests/turn_recovery_test.rs
@@ -33,8 +33,20 @@ case "$1" in
auth) echo '{"loggedIn":true}'; exit 0 ;;
esac
echo '{"type":"system","subtype":"init"}'
-case "$*" in
+# Only the person's own words choose (the last line of -p): earlier chat lines may ride along
+prompt=""; prev=""
+for a in "$@"; do [ "$prev" = "-p" ] && prompt="$a"; prev="$a"; done
+[ -n "$prompt" ] || prompt="$*"
+last=$(printf '%s\n' "$prompt" | awk 'NF { l = $0 } END { print l }')
+[ -n "$FAKE_ARGS_LOG" ] && printf '%s\n=====\n' "$*" >> "$FAKE_ARGS_LOG"
+# A reply a restart cut off, continued with kwnt's note on what was cut off
+case "$prompt" in
+ *"Check first whether it took effect"*) echo '{"type":"result","is_error":false,"num_turns":1,"result":"RESUMED: checked first"}'; exit 0 ;;
+ *"It only reads, so run it again"*) echo '{"type":"result","is_error":false,"num_turns":1,"result":"RESUMED: read again"}'; exit 0 ;;
+esac
+case "$last" in
*GO_SILENT*) exec sleep 3600 ;;
+ *CRASH_NOW*) echo 'the engine crashed' >&2; exit 3 ;;
*LONG_TOOL*)
echo '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tu_1","name":"Bash","input":{"command":"sleep 5"}}]}}'
sleep 5
@@ -247,6 +259,65 @@ async fn a_silent_claude_is_stopped_with_a_visible_reason() {
assert_eq!(meta["stall_secs"], 2);
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(env.state.db.take_running_turns().await.unwrap().is_empty(), "the running row is cleared");
+
+ // 0.9.5: one ask in Needs you, in the notice's own words, pointing at it
+ let stopped_items = |away: &Value| -> Vec<Value> { away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").cloned().collect() };
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ let items = stopped_items(&away);
+ assert_eq!(items.len(), 1, "{away}");
+ assert_eq!(items[0]["message_id"], stopped["id"]);
+ assert_eq!(items[0]["retry"], Value::Null);
+ let title = items[0]["title"].as_str().unwrap();
+ assert!(title.contains("sent nothing for 2 s") && title.ends_with("Retry in the chat sends your message again."), "{title}");
+ // The bot is Stuck (gave up): the dot says so until something resumes it
+ let (_, st) = call(&env.app, "GET", "/api/bots/status", None).await;
+ let mine = |st: &Value| st["bots"].as_array().unwrap().iter().find(|b| b["kwant_id"] == kid.as_str()).cloned().unwrap_or_else(|| panic!("{st}"));
+ assert_eq!((mine(&st)["status"].as_str(), mine(&st)["reason_code"].as_str()), (Some("stuck"), Some("stalled_gave_up")), "{st}");
+ // The person writes again (what the notice's Retry does): one press runs it now, not held
+ // until "Try again" is pressed too, and the reply finishes: the ask is gone
+ let mut rx = env.state.event_sender.subscribe();
+ let (s, sent) = call(&env.app, "POST", "/api/chat/send", Some(json!({"kwant_id": kid, "prompt": "hi again", "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{sent}");
+ assert_eq!(sent["status"], "dispatched", "the Retry must not be held behind the stall: {sent}");
+ assert!(sent.get("held").is_none(), "{sent}");
+ let ended = tokio::time::timeout(Duration::from_secs(30), async {
+ let mut text = String::new();
+ while let Ok(e) = rx.recv().await {
+ if let RuntimeEvent::TextDelta(t) = e.unscoped() {
+ text.push_str(t);
+ }
+ if matches!(e.unscoped(), RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == &kid) {
+ return text;
+ }
+ }
+ text
+ })
+ .await
+ .expect("the retried reply did not run");
+ assert!(ended.contains("answer ok"), "{ended}");
+ let (_, st) = call(&env.app, "GET", "/api/bots/status", None).await;
+ assert_ne!(mine(&st)["status"], "stuck", "{st}");
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert!(stopped_items(&away).is_empty(), "{away}");
+}
+
+/// 0.9.5: an engine that crashes mid-reply leaves the failed reply in the chat (with Retry) and
+/// one ask in Needs you; a hand-off's turn would be reported in the Inbox instead.
+#[tokio::test]
+async fn a_reply_whose_engine_crashed_asks_the_person_once() {
+ let env = setup().await;
+ let kid = env.claude_bot().await;
+ env.turn_with(&kid, "please CRASH_NOW", Duration::from_secs(60)).await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let (_, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;
+ let failed = msgs.as_array().unwrap().iter().rev().find(|m| m["sender_role"] == "kwant").cloned().unwrap_or_else(|| panic!("{msgs}"));
+ let meta: Value = serde_json::from_str(failed["meta"].as_str().unwrap_or("null")).unwrap();
+ assert!(matches!(meta["kind"].as_str(), Some("turn_failed")), "the chat offers Retry on it: {failed}");
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ let items: Vec<&Value> = away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").collect();
+ assert_eq!(items.len(), 1, "{away}");
+ assert_eq!(items[0]["message_id"], failed["id"]);
+ assert!(items[0]["title"].as_str().unwrap().ends_with("Retry in the chat sends your message again."), "{away}");
}
#[tokio::test]
@@ -340,6 +411,8 @@ async fn replies_cut_short_by_a_restart_are_marked_interrupted() {
direct_kwant_id: Some(kid.clone()),
thread_id: None,
started_at: chrono::Utc::now(),
+ asks: None,
+ ..Default::default()
})
.await
.unwrap();
@@ -363,4 +436,199 @@ async fn replies_cut_short_by_a_restart_are_marked_interrupted() {
assert_eq!(meta["interrupted"], true);
assert_eq!(meta["kwant_id"], kid.as_str());
assert_eq!(meta["turn_id"], "turn-1");
+
+ // 0.9.5: and one ask in Needs you, pointing at that notice (its Retry resends the message)
+ let (s, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert_eq!(s, StatusCode::OK, "{away}");
+ let stopped: Vec<&Value> = away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").collect();
+ assert_eq!(stopped.len(), 1, "{away}");
+ assert_eq!(stopped[0]["message_id"], marked[0]["id"]);
+ assert_eq!(stopped[0]["kwant_id"], kid.as_str());
+ assert_eq!(stopped[0]["retry"], Value::Null, "the chat's own Retry resumes it");
+ assert_eq!(
+ stopped[0]["title"].as_str().map(|t| t.starts_with("Ivy's reply was cut off when kwant restarted.")),
+ Some(true),
+ "{away}"
+ );
+ let (_, waiting) = call(&env.app, "GET", "/api/waiting", None).await;
+ assert!(waiting.to_string().contains("\"stopped\""), "{waiting}");
+
+ // A turn that said it asks nothing (a hand-off, a routine run) gets no item
+ env.state
+ .db
+ .add_running_turn(&RunningTurn {
+ turn_id: "turn-2".into(),
+ kwant_id: kid.clone(),
+ kwant_name: "Ivy".into(),
+ channel_id: Some("some-channel".into()),
+ direct_kwant_id: None,
+ thread_id: None,
+ started_at: chrono::Utc::now(),
+ asks: Some(false),
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert_eq!(away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").count(), 1, "{away}");
+
+ // The person writes in that chat (or presses Retry, which sends): the ask closes
+ env.state.db.close_waiting_in_chat(None, Some(&kid), None).await.unwrap();
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert!(!away["waiting"].as_array().unwrap().iter().any(|i| i["kind"] == "stopped"), "{away}");
+}
+
+/// The steps a running turn recorded, as `server::restart_resume::Step` JSON.
+fn steps_json(cut_off: &str, read_only: bool) -> String {
+ json!([
+ {"id": "s1", "name": "Read", "args": "{\"file_path\":\"notes.md\"}", "read_only": true, "done": true},
+ {"id": "s2", "name": cut_off, "args": "{\"text\":\"We launched\"}", "read_only": read_only, "done": false},
+ ])
+ .to_string()
+}
+
+fn cut_off_turn(turn_id: &str, kid: &str, steps: String, resumed: bool) -> RunningTurn {
+ RunningTurn {
+ turn_id: turn_id.into(),
+ kwant_id: kid.into(),
+ kwant_name: "Clio".into(),
+ direct_kwant_id: Some(kid.into()),
+ started_at: chrono::Utc::now(),
+ asks: Some(true),
+ prompt: Some("post the launch note".into()),
+ steps: Some(steps),
+ resumed: Some(resumed),
+ ..Default::default()
+ }
+}
+
+async fn wait_turn_end(rx: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>, kid: &str) -> Vec<RuntimeEvent> {
+ let mut events = Vec::new();
+ tokio::time::timeout(Duration::from_secs(60), async {
+ while let Ok(e) = rx.recv().await {
+ let end = matches!(&e, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kid);
+ events.push(e.unscoped().clone());
+ if end {
+ break;
+ }
+ }
+ })
+ .await
+ .unwrap_or_else(|_| panic!("the continued turn did not end: {events:?}"));
+ events
+}
+
+/// 0.9.5: kwnt restarted while a reply was in the middle of a step that could change something
+/// locally (a shell command). The reply continues by itself, once, and the bot is told that step was cut off
+/// mid-call and to check whether it took effect before running it again. A second restart of
+/// that continuation asks the person instead of continuing again.
+#[tokio::test]
+async fn a_reply_cut_off_mid_step_by_a_restart_continues_by_itself_once() {
+ let env = setup().await;
+ let kid = env.claude_bot().await;
+ env.state.db.add_running_turn(&cut_off_turn("turn-mid", &kid, steps_json("Bash", false), false)).await.unwrap();
+ let mut rx = env.state.event_sender.subscribe();
+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);
+
+ // The chat says it continues, naming the step; nobody is asked
+ let (_, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;
+ let notes: Vec<&Value> = msgs.as_array().unwrap().iter().filter(|m| m["sender_role"] == "system").collect();
+ assert_eq!(notes.len(), 1, "{msgs}");
+ let text = notes[0]["text"].as_str().unwrap();
+ assert!(text.contains("in the middle of `Bash`") && text.contains("continuing it now"), "{text}");
+ assert!(!text.contains("Send your message again"), "{text}");
+ let meta: Value = serde_json::from_str(notes[0]["meta"].as_str().unwrap()).unwrap();
+ assert_eq!(meta["kind"], "turn_resumed_after_restart");
+ assert_eq!(meta["cut_off_step"], "Bash");
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert!(!away["waiting"].as_array().unwrap().iter().any(|i| i["kind"] == "stopped"), "{away}");
+
+ // The scheduler's next tick runs it, and the bot is told to check before running it again
+ assert_eq!(kwnt::server::parked::run_due(&env.state, chrono::Utc::now()).await, 1);
+ let events = wait_turn_end(&mut rx, &kid).await;
+ // The ended turn's own running record is removed in the background after TurnEnded; clear it
+ // now so the next "restart" sees only the record this test adds
+ let _ = env.state.db.take_running_turns().await;
+ assert!(shown(&events).contains("RESUMED: checked first"), "{}", shown(&events));
+ assert_eq!(kwnt::server::parked::run_due(&env.state, chrono::Utc::now()).await, 0, "once");
+
+ // kwnt restarts again during that continuation: this time the person is asked
+ env.state.db.add_running_turn(&cut_off_turn("turn-mid-2", &kid, steps_json("Bash", false), true)).await.unwrap();
+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);
+ assert_eq!(kwnt::server::parked::run_due(&env.state, chrono::Utc::now()).await, 0, "not continued twice");
+ let (_, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;
+ assert!(msgs.to_string().contains("This reply from Clio was interrupted by a restart. Send your message again to retry."), "{msgs}");
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert_eq!(away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").count(), 1, "{away}");
+}
+
+/// 0.9.5 (deer-flow row): kwnt restarted in the middle of a step that reaches outside (a Slack
+/// send). It may already have gone out, so nothing runs it again by itself: the reply isn't
+/// continued, the chat says what stopped and why with no Retry (that would resend the whole
+/// request), and Needs you has one item whose action is telling the bot in the chat.
+#[tokio::test]
+async fn a_reply_cut_off_mid_send_by_a_restart_asks_the_person_instead_of_continuing() {
+ let env = setup().await;
+ let kid = env.claude_bot().await;
+ env.state.db.add_running_turn(&cut_off_turn("turn-send", &kid, steps_json("mcp__slack__send_message", false), false)).await.unwrap();
+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);
+ assert_eq!(kwnt::server::parked::run_due(&env.state, chrono::Utc::now()).await, 0, "never continued by itself");
+
+ let (_, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;
+ let notes: Vec<&Value> = msgs.as_array().unwrap().iter().filter(|m| m["sender_role"] == "system").collect();
+ assert_eq!(notes.len(), 1, "{msgs}");
+ let text = notes[0]["text"].as_str().unwrap();
+ assert!(text.contains("in the middle of `mcp__slack__send_message`, which may already have gone out"), "{text}");
+ assert!(text.contains("kwant won't run it again by itself"), "{text}");
+ assert!(text.ends_with("tell Clio in the chat whether to do it again."), "{text}");
+ assert!(!text.contains("Send your message again"), "no blind resend is offered: {text}");
+ let meta: Value = serde_json::from_str(notes[0]["meta"].as_str().unwrap()).unwrap();
+ assert_eq!(meta["kind"], "turn_interrupted");
+ assert_eq!(meta["outward_step"], "mcp__slack__send_message", "the chat hides Retry on it");
+
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ let items: Vec<&Value> = away["waiting"].as_array().unwrap().iter().filter(|i| i["kind"] == "stopped").collect();
+ assert_eq!(items.len(), 1, "{away}");
+ assert_eq!(items[0]["message_id"], notes[0]["id"]);
+ assert_eq!(items[0]["retry"], Value::Null, "its action opens the chat");
+ assert!(items[0]["title"].as_str().unwrap().ends_with("whether to do it again."), "{away}");
+
+ // The person answers in the chat: the bot runs with that, and the ask is gone
+ let events = env.turn_with(&kid, "it didn't go out, send it", Duration::from_secs(30)).await;
+ assert!(shown(&events).contains("answer ok"), "{}", shown(&events));
+ let (_, away) = call(&env.app, "GET", "/api/away", None).await;
+ assert!(!away["waiting"].as_array().unwrap().iter().any(|i| i["kind"] == "stopped"), "{away}");
+}
+
+/// 0.9.5: a step that only reads, cut off by a restart, is simply run again; a reply whose card
+/// still waits on the person isn't continued (answering the card resumes the work).
+#[tokio::test]
+async fn a_read_cut_off_by_a_restart_runs_again_and_a_waiting_card_is_left_to_the_person() {
+ let env = setup().await;
+ let kid = env.claude_bot().await;
+ env.state.db.add_running_turn(&cut_off_turn("turn-read", &kid, steps_json("mcp__browser__agent_browser_snapshot", true), false)).await.unwrap();
+ let mut rx = env.state.event_sender.subscribe();
+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);
+ assert_eq!(kwnt::server::parked::run_due(&env.state, chrono::Utc::now()).await, 1);
+ let events = wait_turn_end(&mut rx, &kid).await;
+ // The ended turn's own running record is removed in the background after TurnEnded; clear it
+ // now so the next "restart" sees only the record this test adds
+ let _ = env.state.db.take_running_turns().await;
+ assert!(shown(&events).contains("RESUMED: read again"), "{}", shown(&events));
+
+ // A card of the cut-off turn is still waiting: not continued, the old notice and ask stand
+ let card = env
+ .state
+ .db
+ .save_approval(&kwnt::db::models::NewApproval { turn_id: "turn-card".into(), kwant_id: kid.clone(), tool_name: "Bash".into(), parameters: json!({}) })
+ .await
+ .unwrap();
+ env.state.db.add_running_turn(&cut_off_turn("turn-card", &kid, steps_json("Bash", false), false)).await.unwrap();
+ assert_eq!(kwnt::server::mcp_runtime::keep_cards_after_restart(&env.state).await, 1);
+ assert_eq!(env.state.db.get_approval(&card.id).await.unwrap().unwrap().status, "waiting");
+ assert_eq!(routes::interrupt_running_turns(&env.state).await, 1);
+ assert_eq!(kwnt::server::parked::run_due(&env.state, chrono::Utc::now()).await, 0, "the card's Allow resumes it");
+ let (_, msgs) = call(&env.app, "GET", &format!("/api/channels/{kid}/messages"), None).await;
+ assert!(msgs.to_string().contains("interrupted by a restart"), "{msgs}");
}