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.

Fewer confirms: sure letter fields auto-confirm; cheap deletes use Undo

Lin (kwant bot)ea20a75e5078
diff --git a/docs/camera-to-completed.md b/docs/camera-to-completed.md
index 57f1c3ef..ce3cb577 100644
--- a/docs/camera-to-completed.md
+++ b/docs/camera-to-completed.md
@@ -51,7 +51,7 @@ Fields {
sender, request, reply_to, deadline: Field | null,
references, amounts, checklist: [Field]
}
-Field { value, quote, uncertain, confirmed, done? } // done: checklist items only
+Field { value, quote, uncertain, confirmed, auto?, done? } // done: checklist items only
```
## Reading
@@ -78,12 +78,15 @@ The model returns each field as `{value, quote, uncertain}`. kwant marks a field
- an amount has no currency, or its number is ambiguous ("1.234" could be 1234 or 1.234). Amounts are normalised to
`CUR 1234.50`.
-Nothing is `confirmed` until the person confirms it. `PATCH /api/zombie/cases/:id/fields` takes:
+A field that is **not** uncertain is confirmed as it is read, with `auto: true`; the UI shows it with an "auto" mark, and the
+person can still edit or clear it. A sure deadline therefore schedules reminders straight away. An uncertain field (and an
+uncertain deadline) stays unconfirmed until the person confirms it, so no reminders run off a date the model wasn't sure of.
+Fields stored before `auto` existed have no `auto` and keep their state. `PATCH /api/zombie/cases/:id/fields` takes:
- for a single field: `null` to clear it, `{}` to confirm it as it is (the value must still parse), or `{"value": "..."}` to set it
- (which also confirms it);
+ (which also confirms it). Either one clears `auto`: the field is now the person's;
- for a list: the whole list, as `[{"value": "...", "done"?: bool, "confirmed"?: true}]`. `done` applies to checklist items only.
- A new or changed item is confirmed. An item whose value is unchanged keeps its quote and its confirmed/uncertain state, so
+ A new or changed item is confirmed. An item whose value is unchanged keeps its quote and its confirmed/uncertain/auto state, so
ticking one checklist item confirms nothing; send `"confirmed": true` on an item to confirm it as it is.
Values are at most 500 characters and lists at most 20 items.
diff --git a/frontend/src/components/LetterView.tsx b/frontend/src/components/LetterView.tsx
index 3812c2b0..e3f9e1a4 100644
--- a/frontend/src/components/LetterView.tsx
+++ b/frontend/src/components/LetterView.tsx
@@ -32,6 +32,8 @@ import {
reminderWhen,
setBody,
stillReading,
+ isAuto,
+ needsLook,
} from '../letters';
const actionBtn =
@@ -238,11 +240,22 @@ export const AddLetterForm: React.FC<{ onCreated: (caseId: string) => void; onCa
export const StateBadge: React.FC<{ field: LetterField | null | undefined }> = ({ field }) => {
const s = fieldState(field);
+ const auto = isAuto(field);
return (
- <span className={`inline-flex items-center gap-1 px-1.5 py-px rounded-full border text-[11px] ${STATE_TONE[s]}`} data-state={s}>
+ <span
+ className={`inline-flex items-center gap-1 px-1.5 py-px rounded-full border text-[11px] ${STATE_TONE[s]}`}
+ data-state={s}
+ data-auto={auto || undefined}
+ title={auto ? 'This was clear in the letter, so it was confirmed for you. Edit or clear it if it’s wrong.' : undefined}
+ >
{s === 'uncertain' && <AlertTriangle size={11} aria-hidden="true" />}
{s === 'confirmed' && <Check size={11} aria-hidden="true" />}
{FIELD_STATE_LABEL[s]}
+ {auto && (
+ <span className="ml-0.5 px-1 rounded bg-emerald-500/15 text-[10px] font-medium uppercase tracking-wide text-emerald-300/90">
+ auto<span className="sr-only">: confirmed automatically, not by you</span>
+ </span>
+ )}
</span>
);
};
@@ -472,7 +485,7 @@ export const ListField: React.FC<{ fkey: ListKey; label: string; hint: string; e
)}
<StateBadge field={it} />
</div>
- {s !== 'confirmed' && <FieldQuote field={it} />}
+ {(s !== 'confirmed' || isAuto(it)) && <FieldQuote field={it} />}
</li>
);
})}
@@ -768,9 +781,14 @@ export const LetterDetail: React.FC<LetterDetailProps> = ({ view, loading, error
<p className="text-xs text-zinc-500">The fields appear here once the letter has been read.</p>
) : (
<>
- <p className="text-[11px] text-zinc-500">Nothing is confirmed until you confirm it. Fields marked Uncertain need a look at the page first.</p>
+ <p className="text-[11px] text-zinc-500">
+ {needsLook(fields) > 0
+ ? `${needsLook(fields) === 1 ? '1 field needs' : `${needsLook(fields)} fields need`} a look: check ${needsLook(fields) === 1 ? 'it' : 'each'} against the page and confirm. `
+ : 'Nothing needs a look. '}
+ Fields marked auto were clear in the letter and are confirmed already; edit or clear any that are wrong.
+ </p>
{SINGLE_FIELDS.map((f) => (
- <FieldRow key={`${f.key}-${fields[f.key]?.value ?? ''}-${fields[f.key]?.confirmed}`} fkey={f.key} label={f.label} hint={f.hint} field={fields[f.key]} disabled={!canEdit || acting} onSave={onSave} missing={wasRead ? undefined : 'Not filled in yet.'} />
+ <FieldRow key={`${f.key}-${fields[f.key]?.value ?? ''}-${fields[f.key]?.confirmed}-${fields[f.key]?.auto}`} fkey={f.key} label={f.label} hint={f.hint} field={fields[f.key]} disabled={!canEdit || acting} onSave={onSave} missing={wasRead ? undefined : 'Not filled in yet.'} />
))}
{LIST_FIELDS.map((f) => (
<ListField
diff --git a/frontend/src/components/MemoryPanel.tsx b/frontend/src/components/MemoryPanel.tsx
index db1a63ed..88e25cc7 100644
--- a/frontend/src/components/MemoryPanel.tsx
+++ b/frontend/src/components/MemoryPanel.tsx
@@ -1,4 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react';
+import { useUndoableDelete } from '../undoDelete';
+import { UndoNotice } from './UndoNotice';
import { Bot, Check, Loader2, Pencil, Plus, RefreshCw, Trash2, User, X } from 'lucide-react';
import { MAX_MEMORIES, MAX_MEMORY, Memory, continuityApi, formatWhen, onContinuity } from '../continuity';
import { playSfx } from '../audio/chiptune';
@@ -20,16 +22,18 @@ const SourceBadge: React.FC<{ source: Memory['source'] }> = ({ source }) =>
</span>
);
-const MemoryRow: React.FC<{
+export const MemoryRow: React.FC<{
memory: Memory;
onSave: (text: string) => Promise<string | void>;
onDelete: () => Promise<string | void>;
-}> = ({ memory, onSave, onDelete }) => {
+ /** Tests: start in the Undo window. */
+ initialPending?: boolean;
+}> = ({ memory, onSave, onDelete, initialPending = false }) => {
const [editing, setEditing] = useState(false);
const [text, setText] = useState(memory.text);
const [busy, setBusy] = useState(false);
- const [confirm, setConfirm] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const removal = useUndoableDelete(undefined, initialPending);
useEffect(() => {
if (!editing) setText(memory.text);
@@ -48,18 +52,16 @@ const MemoryRow: React.FC<{
}
};
- const remove = async () => {
- if (!confirm) {
- setConfirm(true);
- return;
- }
- setBusy(true);
- const err = await onDelete();
- setBusy(false);
- setConfirm(false);
- if (err) setError(err);
+ const remove = () => {
+ setError(null);
+ removal.start(async () => {
+ const err = await onDelete();
+ if (err) throw new Error(err);
+ });
};
+ if (removal.pending) return <UndoNotice as="li" text="Memory deleted." onUndo={removal.undo} />;
+
return (
<li className="p-2.5 rounded-lg border border-zinc-800 bg-zinc-950/60 space-y-1.5">
<div className="flex items-center gap-2 text-[10px] text-zinc-500">
@@ -77,13 +79,11 @@ const MemoryRow: React.FC<{
<button
type="button"
onClick={remove}
- onBlur={() => setConfirm(false)}
disabled={busy}
- className={`${smallBtn} ${confirm ? 'border-rose-500/50 bg-rose-500/15 text-rose-200' : 'border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200'}`}
- aria-label={confirm ? 'Confirm delete' : 'Delete memory'}
+ className={`${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200`}
+ aria-label="Delete memory"
>
<Trash2 size={11} />
- {confirm && <span>Delete?</span>}
</button>
</span>
</div>
@@ -124,9 +124,9 @@ const MemoryRow: React.FC<{
) : (
<p className="text-xs text-zinc-200 whitespace-pre-wrap break-words">{memory.text}</p>
)}
- {error && (
+ {(error ?? removal.error) && (
<p className="text-[11px] text-rose-400" role="alert">
- {error}
+ {error ?? `Couldn’t delete it: ${removal.error}`}
</p>
)}
</li>
diff --git a/frontend/src/components/ParallelUniverseView.tsx b/frontend/src/components/ParallelUniverseView.tsx
index 0e130ae2..a1865e3e 100644
--- a/frontend/src/components/ParallelUniverseView.tsx
+++ b/frontend/src/components/ParallelUniverseView.tsx
@@ -1,5 +1,7 @@
import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
-import { AlertTriangle, ChevronLeft, ExternalLink, Loader2, Pencil, Play, Plus, RefreshCw, Split, Trash2, X } from 'lucide-react';
+import { useUndoableDelete } from '../undoDelete';
+import { UndoNotice } from './UndoNotice';
+import { AlertTriangle, ChevronLeft, ExternalLink, Loader2, Pencil, Play, Plus, RefreshCw, Split, Trash2 } from 'lucide-react';
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { playSfx } from '../audio/chiptune';
import {
@@ -751,7 +753,12 @@ export const ParallelPage: React.FC<{ onBack?: () => void }> = ({ onBack }) => {
const [starting, setStarting] = useState(false);
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState<{ text: string; error: boolean } | null>(null);
- const [confirmDelete, setConfirmDelete] = useState(false);
+ // A deleted scenario leaves the list at once; the delete is sent once Undo has had its chance
+ const [removing, setRemoving] = useState<Scenario | null>(null);
+ const removal = useUndoableDelete(() => {
+ setScenarios((list) => (list ?? []).filter((x) => x.id !== removing?.id));
+ setRemoving(null);
+ });
const alive = useRef(true);
const fail = (e: unknown) => {
@@ -817,7 +824,6 @@ export const ParallelPage: React.FC<{ onBack?: () => void }> = ({ onBack }) => {
setCurrent(null);
setNotice(null);
setBusy(false);
- setConfirmDelete(false);
if (scenarioId) loadRuns(scenarioId);
}, [scenarioId, loadRuns]);
@@ -877,21 +883,27 @@ export const ParallelPage: React.FC<{ onBack?: () => void }> = ({ onBack }) => {
}
};
- const remove = async (s: Scenario) => {
- try {
- await parallelApi.remove(s.id);
- if (!alive.current) return;
- setScenarios((list) => (list ?? []).filter((x) => x.id !== s.id));
- setScreen({ kind: 'list' });
- } catch (e) {
- if (alive.current) setNotice({ text: `Couldn’t delete it: ${e instanceof Error ? e.message : 'something went wrong.'}`, error: true });
- }
+ const remove = (s: Scenario) => {
+ setRemoving(s);
+ removal.start(() => parallelApi.remove(s.id));
+ setScreen({ kind: 'list' });
};
+ const undoRemove = () => {
+ removal.undo();
+ setRemoving(null);
+ };
+ const listed = (scenarios ?? []).filter((x) => !(removal.pending && x.id === removing?.id));
const shownScenario = scenarioId ? (scenarios ?? []).find((s) => s.id === scenarioId) ?? null : null;
let body: React.ReactNode = null;
if (screen.kind === 'list') {
- body = <ScenarioList scenarios={scenarios ?? []} onOpen={(s) => setScreen({ kind: 'scenario', id: s.id })} onNew={() => (setSaveError(null), setScreen({ kind: 'edit', scenario: null }))} />;
+ body = (
+ <>
+ {removal.pending && removing && <UndoNotice text={`Deleted “${removing.title}”.`} onUndo={undoRemove} className="mb-3" />}
+ {removal.error && <Notice text={`Couldn’t delete it: ${removal.error}`} error />}
+ <ScenarioList scenarios={listed} onOpen={(s) => setScreen({ kind: 'scenario', id: s.id })} onNew={() => (setSaveError(null), setScreen({ kind: 'edit', scenario: null }))} />
+ </>
+ );
} else if (screen.kind === 'edit') {
body = (
<ScenarioForm
@@ -918,19 +930,8 @@ export const ParallelPage: React.FC<{ onBack?: () => void }> = ({ onBack }) => {
onStart={() => start(shownScenario)}
onPickRun={openRun}
onEdit={() => (setSaveError(null), setScreen({ kind: 'edit', scenario: shownScenario }))}
- onDelete={() => setConfirmDelete(true)}
+ onDelete={() => remove(shownScenario)}
/>
- {confirmDelete && (
- <div role="alertdialog" aria-label="Delete scenario" className="px-3 py-2 rounded-lg border border-rose-500/30 bg-rose-500/5 flex flex-wrap items-center gap-2 text-xs text-rose-200">
- <span className="flex-1 min-w-[12rem]">Delete “{shownScenario.title}”? You won’t be able to open its past runs here afterwards.</span>
- <button type="button" onClick={() => remove(shownScenario)} className={`${actionBtn} border border-rose-500/40 text-rose-100 hover:bg-rose-500/10`}>
- <Trash2 size={12} aria-hidden="true" /> Delete
- </button>
- <button type="button" onClick={() => setConfirmDelete(false)} className={quietBtn}>
- <X size={12} aria-hidden="true" /> Keep it
- </button>
- </div>
- )}
</>
);
} else {
diff --git a/frontend/src/components/RoutinesPanel.tsx b/frontend/src/components/RoutinesPanel.tsx
index 86fad274..b8624de2 100644
--- a/frontend/src/components/RoutinesPanel.tsx
+++ b/frontend/src/components/RoutinesPanel.tsx
@@ -1,4 +1,6 @@
import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { useUndoableDelete } from '../undoDelete';
+import { UndoNotice } from './UndoNotice';
import { AlertTriangle, CalendarClock, ChevronDown, ChevronRight, History, Loader2, Pencil, Play, Plus, RefreshCw, Trash2 } from 'lucide-react';
import {
Routine,
@@ -363,7 +365,7 @@ const RunHistory: React.FC<{ routineId: string; tick: number }> = ({ routineId,
);
};
-const RoutineRow: React.FC<{
+export const RoutineRow: React.FC<{
routine: Routine;
kwantName?: string;
placeLabel: string;
@@ -372,7 +374,9 @@ const RoutineRow: React.FC<{
focusPause?: number;
onEdit: () => void;
onChanged: () => void;
-}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onChanged }) => {
+ /** Tests: start in the Undo window. */
+ initialPending?: boolean;
+}> = ({ routine, kwantName, placeLabel, tick, focusPause, onEdit, onChanged, initialPending = false }) => {
const rowRef = useRef<HTMLLIElement>(null);
const switchRef = useRef<HTMLInputElement>(null);
const [highlight, setHighlight] = useState(false);
@@ -384,10 +388,10 @@ const RoutineRow: React.FC<{
}, [focusPause]);
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
- const [confirm, setConfirm] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const historyId = useId();
+ const removal = useUndoableDelete(onChanged, initialPending);
const act = async (fn: () => Promise<unknown>) => {
setBusy(true);
@@ -410,6 +414,8 @@ const RoutineRow: React.FC<{
playSfx('click');
});
+ if (removal.pending) return <UndoNotice as="li" text={`Deleted “${routine.name}”. It won’t run again.`} onUndo={removal.undo} />;
+
return (
<li ref={rowRef} className={`rounded-xl border bg-zinc-950/60 p-3 space-y-2 ${highlight ? 'border-sky-500/60 ring-1 ring-sky-500/30' : 'border-zinc-800'}`}>
<div className="flex items-start gap-2.5">
@@ -455,18 +461,17 @@ const RoutineRow: React.FC<{
<button
type="button"
disabled={busy}
- onBlur={() => setConfirm(false)}
- onClick={() => (confirm ? act(() => continuityApi.removeRoutine(routine.id)) : setConfirm(true))}
- className={`${smallBtn} ${confirm ? 'border-rose-500/50 bg-rose-500/15 text-rose-200' : 'border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200'}`}
+ onClick={() => removal.start(() => continuityApi.removeRoutine(routine.id))}
+ className={`${smallBtn} border-zinc-700/70 bg-zinc-800/70 text-zinc-300 hover:text-rose-200`}
>
- <Trash2 size={11} /> {confirm ? 'Delete?' : 'Delete'}
+ <Trash2 size={11} /> Delete
</button>
{notice && <span className="text-[11px] text-zinc-400" role="status">{notice}</span>}
{highlight && routine.enabled && !notice && (
<span className="text-[11px] text-sky-200" role="status">Turn the switch off to pause it.</span>
)}
</div>
- {error && <p className="pl-9 text-[11px] text-rose-400" role="alert">{error}</p>}
+ {(error ?? removal.error) && <p className="pl-9 text-[11px] text-rose-400" role="alert">{error ?? `Couldn’t delete it: ${removal.error}`}</p>}
{open && (
<div id={historyId} className="pl-9 pt-1">
<RunHistory routineId={routine.id} tick={tick} />
diff --git a/frontend/src/components/SkillsPanel.tsx b/frontend/src/components/SkillsPanel.tsx
index ec769872..5e5b571d 100644
--- a/frontend/src/components/SkillsPanel.tsx
+++ b/frontend/src/components/SkillsPanel.tsx
@@ -1,4 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react';
+import { useUndoableDelete } from '../undoDelete';
+import { UndoNotice } from './UndoNotice';
import { Bot, Check, ChevronDown, ChevronRight, Globe2, Loader2, Pencil, Plus, RefreshCw, Trash2, User, X } from 'lucide-react';
import { formatWhen, onContinuity } from '../continuity';
import { playSfx } from '../audio/chiptune';
@@ -207,12 +209,12 @@ const SkillMeta: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, replac
</div>
);
-const PendingSkill: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, replaces }) => {
+export const PendingSkill: React.FC<{ skill: Skill; replaces?: Skill; initialPending?: boolean }> = ({ skill, replaces, initialPending = false }) => {
const [mode, setMode] = useState<'view' | 'edit'>('view');
const [open, setOpen] = useState(true);
const [busy, setBusy] = useState<'approve' | 'reject' | null>(null);
- const [confirmReject, setConfirmReject] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const rejection = useUndoableDelete(undefined, initialPending);
const approve = async (edits?: SkillDraft) => {
setBusy('approve');
@@ -225,22 +227,13 @@ const PendingSkill: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, rep
return errText(e);
}
};
- const reject = async () => {
- if (!confirmReject) {
- setConfirmReject(true);
- return;
- }
- setBusy('reject');
+ const reject = () => {
setError(null);
- try {
- await skillsApi.reject(skill.id);
- } catch (e) {
- setError(errText(e));
- setBusy(null);
- setConfirmReject(false);
- }
+ rejection.start(() => skillsApi.reject(skill.id));
};
+ if (rejection.pending) return <UndoNotice as="li" text={`Rejected “${skill.name}”. Nothing was added.`} onUndo={rejection.undo} />;
+
return (
<li className="p-3 rounded-lg border border-amber-500/25 bg-amber-500/[0.04] space-y-2">
<div className="flex items-start gap-2">
@@ -280,16 +273,15 @@ const PendingSkill: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, rep
<button type="button" onClick={() => setMode('edit')} disabled={!!busy} className={quietBtn}>
<Pencil size={11} aria-hidden="true" /> Edit, then approve
</button>
- <button type="button" onClick={reject} onBlur={() => setConfirmReject(false)} disabled={!!busy} className={dangerBtn}>
- {busy === 'reject' ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <X size={11} aria-hidden="true" />}
- {confirmReject ? 'Reject it?' : 'Reject'}
+ <button type="button" onClick={reject} disabled={!!busy} className={dangerBtn}>
+ <X size={11} aria-hidden="true" /> Reject
</button>
</div>
</>
)}
- {error && (
+ {(error ?? rejection.error) && (
<p className="text-[11px] text-rose-400" role="alert">
- {error}
+ {error ?? `Couldn’t reject it: ${rejection.error}`}
</p>
)}
</div>
@@ -297,12 +289,12 @@ const PendingSkill: React.FC<{ skill: Skill; replaces?: Skill }> = ({ skill, rep
);
};
-const ActiveSkill: React.FC<{ skill: Skill }> = ({ skill }) => {
+export const ActiveSkill: React.FC<{ skill: Skill; initialPending?: boolean }> = ({ skill, initialPending = false }) => {
const [editing, setEditing] = useState(false);
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
- const [confirmDelete, setConfirmDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const removal = useUndoableDelete(undefined, initialPending);
const enabled = skill.status === 'enabled';
const run = async (fn: () => Promise<unknown>) => {
@@ -317,14 +309,12 @@ const ActiveSkill: React.FC<{ skill: Skill }> = ({ skill }) => {
}
};
const remove = () => {
- if (!confirmDelete) {
- setConfirmDelete(true);
- return;
- }
- setConfirmDelete(false);
- run(() => skillsApi.remove(skill.id));
+ setError(null);
+ removal.start(() => skillsApi.remove(skill.id));
};
+ if (removal.pending) return <UndoNotice as="li" text={`Deleted “${skill.name}”. Bots stop using it.`} onUndo={removal.undo} />;
+
return (
<li className={`p-2.5 rounded-lg border border-zinc-800 bg-zinc-950/60 space-y-1.5 ${enabled ? '' : 'opacity-70'}`}>
<div className="flex items-start gap-2">
@@ -366,8 +356,8 @@ const ActiveSkill: React.FC<{ skill: Skill }> = ({ skill }) => {
<button type="button" onClick={() => setEditing(true)} className={quietBtn}>
<Pencil size={11} aria-hidden="true" /> Edit
</button>
- <button type="button" onClick={remove} onBlur={() => setConfirmDelete(false)} disabled={busy} className={dangerBtn}>
- <Trash2 size={11} aria-hidden="true" /> {confirmDelete ? 'Delete it?' : 'Delete'}
+ <button type="button" onClick={remove} disabled={busy} className={dangerBtn}>
+ <Trash2 size={11} aria-hidden="true" /> Delete
</button>
</span>
</div>
@@ -389,9 +379,9 @@ const ActiveSkill: React.FC<{ skill: Skill }> = ({ skill }) => {
onCancel={() => setEditing(false)}
/>
)}
- {error && (
+ {(error ?? removal.error) && (
<p className="text-[11px] text-rose-400" role="alert">
- {error}
+ {error ?? `Couldn’t delete it: ${removal.error}`}
</p>
)}
</li>
diff --git a/frontend/src/components/UndoNotice.tsx b/frontend/src/components/UndoNotice.tsx
new file mode 100644
index 00000000..29deaed6
--- /dev/null
+++ b/frontend/src/components/UndoNotice.tsx
@@ -0,0 +1,25 @@
+import React, { useEffect, useRef } from 'react';
+import { Undo2 } from 'lucide-react';
+
+/** Takes the place of something just deleted while Undo is still possible. Focus moves to Undo,
+ * since the Delete button that had it is gone. */
+export const UndoNotice: React.FC<{ text: string; onUndo: () => void; className?: string; as?: 'li' | 'div' }> = ({ text, onUndo, className = '', as = 'div' }) => {
+ const btn = useRef<HTMLButtonElement>(null);
+ useEffect(() => btn.current?.focus({ preventScroll: true }), []);
+ const Tag = as;
+ return (
+ <Tag data-undo className={`flex flex-wrap items-center gap-2 px-2.5 py-2 rounded-lg border border-zinc-800 bg-zinc-900/60 text-[11px] text-zinc-400 ${className}`}>
+ <span role="status" className="flex-1 min-w-0 break-words">
+ {text}
+ </span>
+ <button
+ ref={btn}
+ type="button"
+ onClick={onUndo}
+ className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium border border-sky-500/40 bg-sky-500/10 text-sky-200 hover:bg-sky-500/20 transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <Undo2 size={11} aria-hidden="true" /> Undo
+ </button>
+ </Tag>
+ );
+};
diff --git a/frontend/src/letters.ts b/frontend/src/letters.ts
index 2cd42307..7df1a453 100644
--- a/frontend/src/letters.ts
+++ b/frontend/src/letters.ts
@@ -1,6 +1,7 @@
// Camera-to-Completed: a photographed or uploaded letter becomes a Loose ends case (`source:
-// "document"`). kwant reads it once, marks what it isn't sure of, and keeps every field unconfirmed
-// until the person confirms it. Only a confirmed, certain deadline starts reminders. Nothing is ever
+// "document"`). kwant reads it once and marks what it isn't sure of. A field it is sure of is
+// confirmed on its own (`auto`) and can still be edited or cleared; an uncertain one waits for the
+// person. Only a confirmed, certain deadline starts reminders. Nothing is ever
// sent: the reply is a draft the person copies (or opens in their own mail app).
import { LooseCase, LooseEndsError, call, shortDate } from './looseEnds';
@@ -12,6 +13,8 @@ export interface LetterField {
quote: string;
uncertain: boolean;
confirmed: boolean;
+ /** Confirmed on its own because kwant was sure; the person hasn't touched it. Absent means false. */
+ auto?: boolean;
/** Checklist items only. */
done?: boolean | null;
}
@@ -170,7 +173,7 @@ export function readingText(e: Extraction | null): { title: string; body: string
case 'running':
return { title: 'Reading the letter…', body: 'This usually takes under a minute. You can leave this page; the case stays in Loose ends.', tone: 'sky' };
case 'read':
- return { title: 'Read', body: `${methodText(e.method)} Check each field against the letter, then confirm it.`, tone: 'emerald' };
+ return { title: 'Read', body: `${methodText(e.method)} Fields marked Uncertain need you to check them against the letter; the rest are confirmed already.`, tone: 'emerald' };
case 'text_only':
return { title: 'Only the PDF text was read', body: `The text was kept, but the details couldn’t be picked out.${note}${fillIn('Fill in the fields from the letter.')}`, tone: 'amber' };
case 'unreadable':
@@ -202,6 +205,16 @@ export function reminderGate(deadline: LetterField | null | undefined): { on: bo
return { on: true, text: `Reminders 7 days before, 1 day before and on ${shortDate(deadline!.value)}, at 09:00.` };
}
+/** Confirmed by kwant itself, not by the person. */
+export const isAuto = (f: LetterField | null | undefined): boolean => fieldState(f) === 'confirmed' && !!f?.auto;
+
+/** How many fields still need the person: the uncertain ones. */
+export function needsLook(fields: LetterFields | null | undefined): number {
+ if (!fields) return 0;
+ const all = [fields.sender, fields.request, fields.reply_to, fields.deadline, ...(fields.references ?? []), ...(fields.amounts ?? []), ...(fields.checklist ?? [])];
+ return all.filter((f) => fieldState(f) === 'uncertain').length;
+}
+
export const reminderLabel = (offset: number): string => (offset === 0 ? 'On the day' : offset === 1 ? '1 day before' : `${offset} days before`);
export const reminderWhen = (iso: string): string => {
diff --git a/frontend/src/undoDelete.ts b/frontend/src/undoDelete.ts
new file mode 100644
index 00000000..2033671a
--- /dev/null
+++ b/frontend/src/undoDelete.ts
@@ -0,0 +1,111 @@
+// Delete with Undo instead of "Delete?": the item goes from view at once and the request is only
+// sent after UNDO_MS, so Undo just cancels it and nothing has to be restored on the server. Used
+// for things that are cheap to lose (routines, skills, memories, Parallel Universe scenarios).
+// Leaving the screen sends the delete straight away; closing the page before it goes keeps the item.
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export const UNDO_MS = 6000;
+
+export interface Timers {
+ set: (fn: () => void, ms: number) => unknown;
+ clear: (handle: unknown) => void;
+}
+
+const realTimers: Timers = {
+ set: (fn, ms) => setTimeout(fn, ms),
+ clear: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),
+};
+
+/** One delete waiting out its Undo window. Framework-free so it can be tested with fake timers. */
+export class DeferredDelete {
+ private handle: unknown = null;
+ private run: (() => Promise<unknown>) | null = null;
+
+ constructor(
+ private readonly onCommitted: (error: string | null) => void,
+ private readonly ms = UNDO_MS,
+ private readonly timers: Timers = realTimers,
+ ) {}
+
+ get pending(): boolean {
+ return this.run !== null;
+ }
+
+ /** Starts the window. A second start while one is waiting replaces it. */
+ start(run: () => Promise<unknown>): void {
+ this.cancelTimer();
+ this.run = run;
+ this.handle = this.timers.set(() => void this.flush(), this.ms);
+ }
+
+ /** Cancels the waiting delete; nothing is sent. Returns whether there was one. */
+ undo(): boolean {
+ const had = this.pending;
+ this.cancelTimer();
+ this.run = null;
+ return had;
+ }
+
+ /** Sends the waiting delete now (the window ran out, or the screen is going away). */
+ async flush(): Promise<void> {
+ const run = this.run;
+ if (!run) return;
+ this.cancelTimer();
+ this.run = null;
+ try {
+ await run();
+ this.onCommitted(null);
+ } catch (e) {
+ this.onCommitted(e instanceof Error ? e.message : 'That failed.');
+ }
+ }
+
+ private cancelTimer() {
+ if (this.handle !== null) this.timers.clear(this.handle);
+ this.handle = null;
+ }
+}
+
+/**
+ * `pending` while the Undo window is open. `start(run)` hides the item, `undo()` brings it back,
+ * and `run` is sent when the window closes or the component unmounts. A failed delete brings the
+ * item back with `error` set; `onDone` runs after a successful one (e.g. to reload the list).
+ */
+export function useUndoableDelete(onDone?: () => void, initialPending = false) {
+ const [pending, setPending] = useState(initialPending);
+ const [error, setError] = useState<string | null>(null);
+ const alive = useRef(true);
+ const done = useRef(onDone);
+ done.current = onDone;
+ const box = useRef<DeferredDelete | null>(null);
+ if (!box.current) {
+ box.current = new DeferredDelete((err) => {
+ if (!alive.current) return;
+ setPending(false);
+ setError(err);
+ if (!err) done.current?.();
+ });
+ }
+
+ useEffect(() => {
+ alive.current = true;
+ const d = box.current;
+ return () => {
+ alive.current = false;
+ void d?.flush();
+ };
+ }, []);
+
+ const start = useCallback((run: () => Promise<unknown>) => {
+ setError(null);
+ setPending(true);
+ box.current?.start(run);
+ }, []);
+ const undo = useCallback(() => {
+ box.current?.undo();
+ setPending(false);
+ }, []);
+
+ return { pending, error, start, undo };
+}
diff --git a/frontend/tests/fewerConfirms.test.mjs b/frontend/tests/fewerConfirms.test.mjs
new file mode 100644
index 00000000..47ba60bf
--- /dev/null
+++ b/frontend/tests/fewerConfirms.test.mjs
@@ -0,0 +1,152 @@
+// Fewer confirms (approval audit, cut 6): deleting a routine, skill or memory, rejecting a proposed
+// skill, and deleting a Parallel Universe scenario take one click and offer Undo. The delete is only
+// sent once the Undo window closes, so Undo never has to restore anything on the server.
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const root = join(dirname(fileURLToPath(import.meta.url)), '..');
+const u = await loadBundled(`export * from './src/undoDelete';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { RoutineRow } from './src/components/RoutinesPanel';
+ import { ActiveSkill, PendingSkill } from './src/components/SkillsPanel';
+ import { MemoryRow } from './src/components/MemoryPanel';
+ import { UndoNotice } from './src/components/UndoNotice';
+ const r = (C) => (props) => renderToStaticMarkup(React.createElement(C, props));
+ export const routine = r(RoutineRow);
+ export const active = r(ActiveSkill);
+ export const pending = r(PendingSkill);
+ export const memory = r(MemoryRow);
+ export const undo = r(UndoNotice);
+`);
+
+/** Timers that only move when told to. */
+const fakeTimers = () => {
+ let next = 1;
+ const due = new Map();
+ return {
+ set: (fn, ms) => (due.set(next, { fn, ms }), next++),
+ clear: (h) => due.delete(h),
+ fire: () => {
+ const all = [...due.values()];
+ due.clear();
+ all.forEach((t) => t.fn());
+ },
+ get count() {
+ return due.size;
+ },
+ get lastMs() {
+ return [...due.values()].at(-1)?.ms;
+ },
+ };
+};
+const settle = () => new Promise((r) => setImmediate(r));
+
+test('a delete waits out the Undo window, then is sent once', async () => {
+ const t = fakeTimers();
+ const results = [];
+ let sent = 0;
+ const d = new u.DeferredDelete((err) => results.push(err), u.UNDO_MS, t);
+ d.start(async () => sent++);
+ assert.equal(d.pending, true);
+ assert.equal(t.lastMs, u.UNDO_MS);
+ assert.equal(sent, 0, 'nothing is sent while Undo is still possible');
+ t.fire();
+ await settle();
+ assert.equal(sent, 1);
+ assert.deepEqual(results, [null]);
+ assert.equal(d.pending, false);
+ await d.flush();
+ assert.equal(sent, 1, 'never sent twice');
+});
+
+test('Undo cancels it and nothing reaches the server', async () => {
+ const t = fakeTimers();
+ let sent = 0;
+ const d = new u.DeferredDelete(() => {}, u.UNDO_MS, t);
+ d.start(async () => sent++);
+ assert.equal(d.undo(), true);
+ assert.equal(t.count, 0, 'the timer is gone');
+ t.fire();
+ await d.flush();
+ assert.equal(sent, 0);
+ assert.equal(d.undo(), false, 'nothing left to undo');
+});
+
+test('leaving the screen sends it at once; a failed delete reports why', async () => {
+ const t = fakeTimers();
+ const results = [];
+ let sent = 0;
+ const d = new u.DeferredDelete((err) => results.push(err), u.UNDO_MS, t);
+ d.start(async () => sent++);
+ await d.flush();
+ assert.equal(sent, 1);
+ assert.equal(t.count, 0);
+
+ d.start(async () => {
+ throw new Error('HTTP 500');
+ });
+ t.fire();
+ await settle();
+ assert.deepEqual(results, [null, 'HTTP 500']);
+});
+
+const routine = {
+ id: 'r1', kwant_id: 'k1', channel_id: null, name: 'Morning digest', instructions: 'x',
+ schedule: { type: 'daily', time: '09:00', tz: 'UTC' }, enabled: true, next_run_at: null, last_run_at: null, last_status: null, created_at: '2026-10-20T08:00:00Z',
+};
+const skill = (over = {}) => ({
+ id: 's1', kwant_id: 'k1', name: 'weekly-report', description: 'Friday report', body: 'steps', status: 'enabled', source: 'user', proposed_by: null,
+ replaces_id: null, created_at: '2026-10-17T10:00:00Z', updated_at: '2026-10-17T10:00:00Z', reviewed_at: null, ...over,
+});
+const memory = { id: 'm1', text: 'Oleks likes short replies', source: 'user', created_at: '2026-10-20T08:00:00Z', updated_at: '2026-10-20T08:00:00Z' };
+const noop = () => {};
+const none = async () => {};
+
+test('routines, skills and memories show one plain Delete (or Reject), never a second "are you sure?"', () => {
+ const r = ui.routine({ routine, placeLabel: 'Direct chat', tick: 0, onEdit: noop, onChanged: noop });
+ assert.match(r, /Delete/);
+ assert.doesNotMatch(r, /Delete\?/);
+ const p = ui.pending({ skill: skill({ status: 'pending', source: 'agent' }) });
+ assert.match(p, /Reject/);
+ assert.doesNotMatch(p, /Reject it\?/);
+ const m = ui.memory({ memory, onSave: none, onDelete: none });
+ assert.match(m, /aria-label="Delete memory"/);
+ assert.doesNotMatch(m, /Delete\?|Confirm delete/);
+});
+
+test('while Undo is possible the item is replaced by what happened and an Undo button', () => {
+ const r = ui.routine({ routine, placeLabel: 'Direct chat', tick: 0, onEdit: noop, onChanged: noop, initialPending: true });
+ assert.match(r, /Deleted “Morning digest”/);
+ assert.match(r, />.*Undo<\/button>/);
+ assert.match(r, /^<li/, 'still a list item, so the list stays valid');
+ assert.doesNotMatch(r, /Run now/);
+ assert.match(ui.active({ skill: skill(), initialPending: true }), /Deleted “weekly-report”[^]*Undo/);
+ assert.match(ui.pending({ skill: skill({ status: 'pending' }), initialPending: true }), /Rejected “weekly-report”[^]*Undo/);
+ assert.match(ui.memory({ memory, onSave: none, onDelete: none, initialPending: true }), /Memory deleted[^]*Undo/);
+ const n = ui.undo({ text: 'Deleted “x”.', onUndo: noop });
+ assert.match(n, /role="status"/, 'screen readers hear it');
+});
+
+test('the four cheap deletes lost their confirm; the irreversible ones kept theirs', () => {
+ const src = (f) => readFileSync(join(root, 'src/components', f), 'utf8');
+ for (const f of ['RoutinesPanel.tsx', 'SkillsPanel.tsx', 'MemoryPanel.tsx', 'ParallelUniverseView.tsx']) {
+ const s = src(f);
+ assert.doesNotMatch(s, /'Delete\?'|>Delete\?<|Delete it\?|Reject it\?|confirmDelete|confirmReject|aria-label="Delete scenario"/, f);
+ assert.match(s, /useUndoableDelete/, `${f} uses Undo`);
+ }
+ // Group A stays as it was
+ assert.match(src('DeleteBotDialog.tsx'), /alertdialog|confirm/i);
+ assert.match(src('LetterView.tsx'), /confirmDelete/);
+ assert.match(src('McpServersModal.tsx'), /confirmDelete/);
+ assert.match(src('SavedPasswordsPanel.tsx'), /confirmDelete/);
+ assert.match(src('SpaceSettings.tsx'), /setConfirmArchive/);
+ assert.match(src('ApprovalsSetting.tsx'), /setConfirming/);
+});
diff --git a/frontend/tests/letters.test.mjs b/frontend/tests/letters.test.mjs
index 8282fd19..36832440 100644
--- a/frontend/tests/letters.test.mjs
+++ b/frontend/tests/letters.test.mjs
@@ -208,7 +208,40 @@ test('the pages sit next to the fields: photos inline, PDFs as a link, plus what
assert.match(html, /What was read from it/);
assert.match(html, /lg:grid-cols-\[minmax\(0,1fr\)_minmax\(0,1fr\)\]/, 'side by side on a wide screen');
assert.ok(html.indexOf('The letter') < html.indexOf('What it says'), 'pages first, so a phone shows the photo above the fields');
- assert.match(html, /Nothing is confirmed until you confirm it/);
+ assert.match(html, /1 field needs a look/, 'only the uncertain deadline needs the person');
+});
+
+test('sure fields arrive confirmed with an auto mark, still editable; uncertain ones still need a tap', () => {
+ const auto = ui.row({ fkey: 'sender', label: 'From', hint: '', field: f('Thames Water', { confirmed: true, auto: true }), disabled: false, onSave: save });
+ assert.match(auto, /data-state="confirmed"/);
+ assert.match(auto, /data-auto="true"/);
+ assert.match(auto, />auto</);
+ assert.match(auto, /confirmed automatically, not by you/, 'screen readers hear who confirmed it');
+ assert.doesNotMatch(auto, /> Confirm</, 'nothing to tap');
+ assert.match(auto, /Edit/);
+ assert.match(auto, /Clear/);
+ assert.match(auto, /“Thames Water”/, 'the quote stays visible so it can be checked');
+
+ const mine = ui.row({ fkey: 'sender', label: 'From', hint: '', field: f('Thames Water', { confirmed: true }), disabled: false, onSave: save });
+ assert.doesNotMatch(mine, /data-auto/, 'a field the person confirmed has no auto mark');
+
+ const unsure = ui.row({ fkey: 'deadline', label: 'Deadline', hint: 'YYYY-MM-DD', field: f('2026-11-14', { uncertain: true }), disabled: false, onSave: save });
+ assert.doesNotMatch(unsure, /data-auto/);
+ assert.match(unsure, /> Confirm</);
+
+ // A sure deadline starts reminders on its own; an uncertain one never does
+ assert.equal(m.reminderGate(f('2026-11-14', { confirmed: true, auto: true })).on, true);
+ assert.equal(m.reminderGate(f('2026-11-14', { uncertain: true })).on, false);
+ assert.equal(m.isAuto(f('x', { confirmed: true, auto: true, uncertain: true })), false, 'uncertain beats auto');
+
+ const list = ui.list({ fkey: 'amounts', label: 'Amounts', hint: '', empty: '', items: [f('GBP 142.60', { confirmed: true, auto: true }), f('GBP 9.99', { uncertain: true })], disabled: false, onSave: save });
+ assert.equal((list.match(/data-auto="true"/g) ?? []).length, 1);
+ assert.match(list, /Not all checked/);
+
+ const sure = { sender: f('A', { confirmed: true, auto: true }), deadline: f('2026-11-14', { confirmed: true, auto: true }), amounts: [f('GBP 1.00', { uncertain: true })] };
+ assert.equal(m.needsLook(sure), 1);
+ const html = ui.detail(detailProps(view({}, { fields: { ...sure, amounts: [] } })));
+ assert.match(html, /Nothing needs a look/);
});
test('the draft: a paper letter is copy only; an email has a mailto; nothing is sent either way', () => {
diff --git a/src/documents/extract.rs b/src/documents/extract.rs
index f39ed049..898835df 100644
--- a/src/documents/extract.rs
+++ b/src/documents/extract.rs
@@ -313,12 +313,13 @@ fn single(old: &Option<Field>, v: &Value, key: &str, kind: Kind) -> Result<Optio
f.value = valid(&f.value, key, kind)?;
f.confirmed = true;
f.uncertain = false;
+ f.auto = false;
Ok(Some(f))
}
Some(Value::String(s)) if obj.len() == 1 => {
let value = valid(s, key, kind)?;
let quote = old.as_ref().filter(|o| o.value == value).map(|o| o.quote.clone()).unwrap_or_default();
- Ok(Some(Field { value, quote, uncertain: false, confirmed: true, done: None }))
+ Ok(Some(Field { value, quote, uncertain: false, confirmed: true, auto: false, done: None }))
}
_ => Err(format!("{key}: send null, {{}} or {{\"value\": \"...\"}}")),
}
@@ -349,11 +350,11 @@ fn list(old: &[Field], v: &Value, key: &str, kind: Kind) -> Result<Vec<Field>, S
};
// A new or changed entry, or one the person confirms, is confirmed; an unchanged one
// (say, ticking another checklist item) keeps what it was
- let (uncertain, confirmed) = match before {
- Some(b) if !confirm => (b.uncertain, b.confirmed),
- _ => (false, true),
+ let (uncertain, confirmed, auto) = match before {
+ Some(b) if !confirm => (b.uncertain, b.confirmed, b.auto),
+ _ => (false, true, false),
};
- Ok(Field { quote: before.map(|b| b.quote.clone()).unwrap_or_default(), value, uncertain, confirmed, done })
+ Ok(Field { quote: before.map(|b| b.quote.clone()).unwrap_or_default(), value, uncertain, confirmed, auto, done })
})
.collect()
}
@@ -552,6 +553,26 @@ mod tests {
assert!(patch(&old, &json!({"amounts": [{"value": "GBP 142.60", "confirmed": "yes"}]})).is_err());
}
+ #[test]
+ fn touching_an_auto_confirmed_field_makes_it_the_persons() {
+ let mut old = fields();
+ old.sender = Some(Field { value: "Northfield Water".into(), quote: "Northfield Water".into(), confirmed: true, auto: true, ..Default::default() });
+ old.checklist = vec![Field { value: "Pay".into(), quote: "pay by".into(), confirmed: true, auto: true, done: Some(false), ..Default::default() }];
+ // Editing or confirming takes the auto mark off; clearing removes the field
+ let f = patch(&old, &json!({"sender": {"value": "Northfield Water Ltd"}})).unwrap();
+ assert!(f.sender.as_ref().is_some_and(|s| s.confirmed && !s.auto));
+ let f = patch(&old, &json!({"sender": {}})).unwrap();
+ assert!(f.sender.as_ref().is_some_and(|s| s.confirmed && !s.auto));
+ assert!(patch(&old, &json!({"sender": null})).unwrap().sender.is_none());
+ // Ticking an unchanged item keeps it auto-confirmed
+ let f = patch(&old, &json!({"checklist": [{"value": "Pay", "done": true}]})).unwrap();
+ assert!(f.checklist[0].confirmed && f.checklist[0].auto && f.checklist[0].done == Some(true));
+ // Fields stored before `auto` existed still read, as not auto
+ let legacy: Field = serde_json::from_value(json!({"value": "x", "quote": "", "uncertain": false, "confirmed": false})).unwrap();
+ assert!(!legacy.auto && !legacy.confirmed);
+ assert!(serde_json::to_value(&legacy).unwrap().get("auto").is_none());
+ }
+
#[test]
fn the_case_takes_only_a_confirmed_deadline() {
let now = Utc::now();
diff --git a/src/documents/mod.rs b/src/documents/mod.rs
index c10f5025..081d3606 100644
--- a/src/documents/mod.rs
+++ b/src/documents/mod.rs
@@ -7,8 +7,10 @@
//!
//! Every field is `{value, quote, uncertain}`. A field is uncertain when the model says so, when
//! its quote is not word for word in the text read from the letter, or when its date or amount
-//! does not parse. An uncertain deadline is shown but never schedules a reminder (`reminders`)
-//! until the person confirms it. Nothing here sends anything: the draft reply is copy or mailto.
+//! does not parse. A field that is not uncertain is confirmed on its own (`auto`), so a sure
+//! deadline starts reminders at once; the person can still edit or clear it. An uncertain field
+//! waits for the person, and an uncertain deadline schedules no reminder (`reminders`) until they
+//! confirm it. Nothing here sends anything: the draft reply is copy or mailto.
//!
//! The letter's text is the person's private paper: it is stored next to the case and never logged.
@@ -40,9 +42,12 @@ pub struct Field {
/// Shown highlighted: the person should check it. An uncertain deadline schedules nothing.
#[serde(default)]
pub uncertain: bool,
- /// The person confirmed or typed it.
+ /// Confirmed: by the person, or on its own when kwant read it and was sure (`auto`).
#[serde(default)]
pub confirmed: bool,
+ /// Confirmed on its own because nothing made it uncertain; the person has not touched it yet.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub auto: bool,
/// Checklist items only: ticked off.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub done: Option<bool>,
@@ -72,6 +77,8 @@ impl Fields {
pub fn all_uncertain(mut self) -> Self {
for f in self.iter_mut() {
f.uncertain = true;
+ f.confirmed = false;
+ f.auto = false;
}
self
}
@@ -98,7 +105,8 @@ impl Fields {
self.iter().filter(|f| f.uncertain).count()
}
- /// The deadline reminders may use: one the person confirmed, that is not uncertain and parses.
+ /// The deadline reminders may use: one confirmed (by the person or on its own), that is not
+ /// uncertain and parses.
pub fn confirmed_deadline(&self) -> Option<NaiveDate> {
let d = self.deadline.as_ref().filter(|d| d.confirmed && !d.uncertain)?;
parse_date(&d.value)
@@ -203,7 +211,8 @@ fn checked(raw: RawField, text: &str, kind: Kind) -> Option<Field> {
}
},
};
- Some(Field { value, quote, uncertain, confirmed: false, done: None })
+ // Sure means confirmed: only an uncertain field waits for the person
+ Some(Field { value, quote, uncertain, confirmed: !uncertain, auto: !uncertain, done: None })
}
/// An ISO date, `YYYY-MM-DD`; nothing else counts.
@@ -409,8 +418,9 @@ mod tests {
assert_eq!(f.checklist[0].done, Some(false));
assert!(f.reply_to.as_ref().unwrap().uncertain, "the address is not in this text");
assert_eq!(f.uncertain_count(), 5);
- // Never usable for reminders until confirmed
- assert_eq!(f.confirmed_deadline(), None);
+ // Sure fields confirm on their own, uncertain ones wait for the person
+ assert!(f.iter().all(|x| x.confirmed == !x.uncertain && x.auto == !x.uncertain));
+ assert_eq!(f.confirmed_deadline(), NaiveDate::from_ymd_opt(2026, 11, 30), "a sure deadline is usable at once");
}
#[test]
diff --git a/tests/documents_test.rs b/tests/documents_test.rs
index 2dcc6033..48e46aa9 100644
--- a/tests/documents_test.rs
+++ b/tests/documents_test.rs
@@ -347,6 +347,30 @@ async fn a_photo_no_model_can_read_is_left_for_the_person() {
assert_eq!(v["reminders"].as_array().unwrap().len(), 3);
}
+#[tokio::test]
+async fn an_uncertain_deadline_waits_for_the_person_and_schedules_nothing() {
+ let mut answer = water_bill_answer();
+ answer["deadline"]["uncertain"] = json!(true);
+ let e = setup_with(Stub::new(Ok(answer.to_string()))).await;
+ let pdf = e.upload("water-bill.pdf", PDF).await;
+ let (s, v) = e.create(&[&pdf]).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{v}");
+ let case_id = v["case_id"].as_str().unwrap().to_string();
+ let doc = e.read_through(&case_id).await;
+ let f = &doc["extraction"]["fields"];
+ assert_eq!(f["deadline"]["uncertain"], true, "{doc}");
+ assert_eq!(f["deadline"]["confirmed"], false);
+ assert_eq!(f["sender"]["confirmed"], true, "the sure fields don't wait");
+ assert!(doc["case"]["deadline"].is_null(), "an uncertain deadline is not the case's deadline");
+ assert!(doc["reminders"].as_array().unwrap().is_empty(), "an uncertain deadline schedules nothing");
+
+ // One tap confirms it and starts the reminders
+ let (s, v) = e.person("PATCH", &format!("/api/zombie/cases/{case_id}/fields"), Some(json!({"deadline": {}}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["extraction"]["fields"]["deadline"]["confirmed"], true);
+ assert_eq!(v["case"]["deadline"].as_str().unwrap().get(..10), Some("2026-11-30"));
+}
+
#[tokio::test]
async fn a_text_pdf_and_a_photo_are_read_in_one_model_call() {
let logs = Logs::global();
@@ -380,18 +404,23 @@ async fn a_text_pdf_and_a_photo_are_read_in_one_model_call() {
assert_eq!(f["sender"]["value"], "Northfield Water Ltd");
assert_eq!(f["sender"]["uncertain"], false);
assert_eq!(f["deadline"]["value"], "2026-11-30");
- assert_eq!(f["deadline"]["confirmed"], false, "nothing is confirmed until the person says so");
+ assert_eq!(f["deadline"]["confirmed"], true, "a sure deadline confirms on its own");
+ assert_eq!(f["deadline"]["auto"], true);
+ assert_eq!(f["sender"]["auto"], true);
assert_eq!(f["amounts"][0]["value"], "GBP 142.60");
assert_eq!(f["references"][0]["value"], "NW-448812");
assert_eq!(f["checklist"][0]["uncertain"], false, "a quote from the photo's transcript stands");
assert_eq!(f["checklist"][0]["done"], false);
assert_eq!(f["checklist"][1]["uncertain"], true, "a quote that is in neither page is uncertain");
+ assert_eq!(f["checklist"][1]["confirmed"], false, "an uncertain item waits for the person");
+ assert!(f["checklist"][1].get("auto").is_none(), "auto is only sent when true");
assert!(x["text"].as_str().unwrap().contains("Reply slip"));
let case = &doc["case"];
assert_eq!(case["title"], "Letter from Northfield Water Ltd");
- assert!(case["deadline"].is_null(), "an unconfirmed deadline is not the case's deadline");
- assert!(doc["reminders"].as_array().unwrap().is_empty(), "an unconfirmed deadline schedules nothing");
+ assert_eq!(case["deadline"].as_str().unwrap().get(..10), Some("2026-11-30"), "a sure deadline is the case's deadline at once");
+ let ahead = chrono::NaiveDate::from_ymd_opt(2026, 11, 30).unwrap() >= chrono::Utc::now().date_naive();
+ assert_eq!(!doc["reminders"].as_array().unwrap().is_empty(), ahead, "a sure deadline starts its reminders: {doc}");
assert_eq!(case["draft"]["channel"], "email");
assert_eq!(case["draft"]["to"], "[email protected]");
@@ -409,7 +438,9 @@ async fn a_text_pdf_and_a_photo_are_read_in_one_model_call() {
assert_eq!(v["extraction"]["fields"]["deadline"]["confirmed"], true);
assert_eq!(v["extraction"]["fields"]["checklist"].as_array().unwrap().len(), 1);
assert_eq!(v["extraction"]["fields"]["checklist"][0]["done"], true);
- assert_eq!(v["extraction"]["fields"]["checklist"][0]["confirmed"], false, "ticking an item doesn't confirm it");
+ assert_eq!(v["extraction"]["fields"]["checklist"][0]["confirmed"], true, "ticking keeps it as it was: auto-confirmed");
+ assert_eq!(v["extraction"]["fields"]["checklist"][0]["auto"], true);
+ assert!(v["extraction"]["fields"]["deadline"].get("auto").is_none(), "a date the person set is theirs, not auto");
assert_eq!(v["extraction"]["fields"]["checklist"][0]["quote"], "Tick the box and return this slip by post.", "an unchanged item keeps its quote");
assert_eq!(v["case"]["deadline"].as_str().unwrap().get(..10), Some("2099-03-01"));
let rem = v["reminders"].as_array().unwrap();