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.

Camera-to-Completed: add a letter and the letter case view (frontend)

Lin (kwant bot)b63fff2bc4ce
diff --git a/frontend/src/components/LetterView.tsx b/frontend/src/components/LetterView.tsx
new file mode 100644
index 00000000..3812c2b0
--- /dev/null
+++ b/frontend/src/components/LetterView.tsx
@@ -0,0 +1,941 @@
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { AlertTriangle, Bell, Camera, Check, CheckCircle2, ChevronLeft, Copy, ExternalLink, FileText, Loader2, Pencil, Plus, Quote, RotateCcw, Trash2, Upload, X } from 'lucide-react';
+import { playSfx } from '../audio/chiptune';
+import { fileKind, formatBytes, isInlineImage, uploadAttachment } from '../attachments';
+import { LooseCase, LooseEndsError, draftCopyText, draftOpen, looseApi, shortDate } from '../looseEnds';
+import {
+ FIELD_STATE_LABEL,
+ Extraction,
+ LETTER_ACCEPT,
+ LIST_FIELDS,
+ LetterField,
+ LetterView as LetterViewData,
+ ListKey,
+ MAX_LETTER_PAGES,
+ Reminder,
+ SINGLE_FIELDS,
+ SingleKey,
+ checkLetterFiles,
+ clearBody,
+ confirmBody,
+ deleteErrorText,
+ draftChannelText,
+ fieldState,
+ fieldValueError,
+ isIsoDate,
+ letterApi,
+ letterErrorText,
+ listBody,
+ readingText,
+ reminderGate,
+ reminderLabel,
+ reminderWhen,
+ setBody,
+ stillReading,
+} from '../letters';
+
+const actionBtn =
+ 'inline-flex items-center gap-1.5 min-h-[36px] sm:min-h-[30px] px-3 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const quietBtn = `${actionBtn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700 hover:border-zinc-600`;
+const primaryBtn = `${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`;
+const input =
+ 'w-full min-w-0 min-h-[36px] px-2.5 py-1.5 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-sky-500';
+const sectionTitle = 'text-[11px] font-semibold text-zinc-500 uppercase tracking-wider';
+
+const STATE_TONE: Record<string, string> = {
+ confirmed: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-200',
+ uncertain: 'border-amber-500/40 bg-amber-500/15 text-amber-200',
+ unconfirmed: 'border-zinc-700 bg-zinc-800 text-zinc-300',
+ empty: 'border-zinc-800 bg-transparent text-zinc-500',
+};
+const BANNER_TONE = {
+ sky: 'border-sky-500/30 bg-sky-500/10 text-sky-100',
+ emerald: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-100',
+ amber: 'border-amber-500/30 bg-amber-500/10 text-amber-100',
+ rose: 'border-rose-500/30 bg-rose-500/10 text-rose-100',
+};
+
+const spin = 'animate-spin motion-reduce:animate-none';
+
+/** Saves a change; resolves to an error message, or null when it was saved. */
+type Save = (body: Record<string, unknown>) => Promise<string | null>;
+
+const coarsePointer = () => typeof window !== 'undefined' && !!window.matchMedia?.('(pointer: coarse)').matches;
+
+// ---------------------------------------------------------------------------
+// Add a letter
+
+interface Picked {
+ key: string;
+ file: File;
+ preview: string | null;
+ /** Set once uploaded, so a retry after "busy" doesn't upload again. */
+ attachmentId?: string;
+ progress: number;
+}
+
+/** Photograph (on a phone) or pick 1–5 pages, upload them, then ask kwant to read them as one letter. */
+export const AddLetterForm: React.FC<{ onCreated: (caseId: string) => void; onCancel: () => void; initialCamera?: boolean }> = ({ onCreated, onCancel, initialCamera }) => {
+ const id = useId();
+ const [pages, setPages] = useState<Picked[]>([]);
+ const [phase, setPhase] = useState<'idle' | 'uploading' | 'starting'>('idle');
+ const [error, setError] = useState<{ text: string; calm: boolean } | null>(null);
+ const [camera] = useState(() => initialCamera ?? coarsePointer());
+ const pickRef = useRef<HTMLInputElement>(null);
+ const cameraRef = useRef<HTMLInputElement>(null);
+ const pagesRef = useRef(pages);
+ pagesRef.current = pages;
+
+ useEffect(() => () => pagesRef.current.forEach((p) => p.preview && URL.revokeObjectURL(p.preview)), []);
+
+ const problem = pages.length ? checkLetterFiles(pages.map((p) => ({ name: p.file.name, type: p.file.type, size: p.file.size }))) : null;
+ const working = phase !== 'idle';
+
+ const add = (list: FileList | null) => {
+ if (!list || list.length === 0) return;
+ const added = Array.from(list).map((file, i) => ({
+ key: `${Date.now()}-${i}-${file.name}`,
+ file,
+ preview: isInlineImage(file.type) ? URL.createObjectURL(file) : null,
+ progress: 0,
+ }));
+ setPages((cur) => [...cur, ...added]);
+ setError(null);
+ };
+
+ const remove = (key: string) => {
+ setPages((cur) => {
+ const gone = cur.find((p) => p.key === key);
+ if (gone?.preview) URL.revokeObjectURL(gone.preview);
+ return cur.filter((p) => p.key !== key);
+ });
+ setError(null);
+ };
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ const why = checkLetterFiles(pages.map((p) => ({ name: p.file.name, type: p.file.type, size: p.file.size })));
+ if (why) return setError({ text: why, calm: false });
+ setError(null);
+ setPhase('uploading');
+ const ids: string[] = [];
+ try {
+ for (const p of pages) {
+ if (p.attachmentId) {
+ ids.push(p.attachmentId);
+ continue;
+ }
+ const a = await uploadAttachment(p.file, (f) => setPages((cur) => cur.map((x) => (x.key === p.key ? { ...x, progress: f } : x))));
+ ids.push(a.id);
+ setPages((cur) => cur.map((x) => (x.key === p.key ? { ...x, attachmentId: a.id, progress: 1 } : x)));
+ }
+ } catch (err) {
+ setPhase('idle');
+ return setError({ text: `Couldn’t upload a page: ${err instanceof Error ? err.message : 'something went wrong.'}`, calm: false });
+ }
+ setPhase('starting');
+ try {
+ const r = await letterApi.create(ids);
+ playSfx('coin');
+ onCreated(r.case_id);
+ } catch (err) {
+ const t = letterErrorText(err);
+ // A page used by another letter must be uploaded again; a busy server can take the same ones.
+ if (err instanceof LooseEndsError && err.status === 409 && err.code !== 'busy') setPages((cur) => cur.map((x) => ({ ...x, attachmentId: undefined, progress: 0 })));
+ setError(t);
+ setPhase('idle');
+ }
+ };
+
+ return (
+ <form onSubmit={submit} className="rounded-xl border border-sky-500/30 bg-zinc-900/60 p-3 sm:p-4 space-y-3" aria-labelledby={`${id}-h`} data-add-letter>
+ <div className="flex items-center justify-between gap-2">
+ <h3 id={`${id}-h`} className="text-sm font-semibold text-zinc-100">
+ Add a letter
+ </h3>
+ <button type="button" onClick={onCancel} aria-label="Close" className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">
+ <X size={14} />
+ </button>
+ </div>
+ <p className="text-xs text-zinc-400">
+ Photograph each page, or pick up to {MAX_LETTER_PAGES} photos or PDFs of one letter (PNG, JPEG, WebP or PDF). It’s read into a case with the deadline and a reply draft. Nothing is sent to anyone.
+ </p>
+
+ <div className="flex flex-wrap gap-2">
+ {camera && (
+ <>
+ <input ref={cameraRef} id={`${id}-cam`} type="file" accept="image/*" capture="environment" className="sr-only" tabIndex={-1} onChange={(e) => (add(e.target.files), (e.target.value = ''))} />
+ <button type="button" disabled={working || pages.length >= MAX_LETTER_PAGES} onClick={() => cameraRef.current?.click()} className={primaryBtn}>
+ <Camera size={14} aria-hidden="true" /> {pages.length ? 'Photograph another page' : 'Take a photo'}
+ </button>
+ </>
+ )}
+ <input ref={pickRef} id={`${id}-pick`} type="file" multiple accept={LETTER_ACCEPT} className="sr-only" tabIndex={-1} onChange={(e) => (add(e.target.files), (e.target.value = ''))} data-letter-files />
+ <button type="button" disabled={working || pages.length >= MAX_LETTER_PAGES} onClick={() => pickRef.current?.click()} className={camera ? quietBtn : primaryBtn}>
+ <Upload size={14} aria-hidden="true" /> {camera ? 'Choose files' : pages.length ? 'Add more pages' : 'Choose photos or PDFs'}
+ </button>
+ </div>
+
+ {pages.length > 0 && (
+ <ol className="grid grid-cols-2 sm:grid-cols-3 gap-2" aria-label="Pages to read">
+ {pages.map((p, i) => (
+ <li key={p.key} className="relative min-w-0 rounded-lg border border-zinc-800 bg-zinc-950/60 p-2 space-y-1">
+ {p.preview ? (
+ <img src={p.preview} alt={`Page ${i + 1}`} className="w-full h-24 object-cover object-top rounded" />
+ ) : (
+ <div className="h-24 flex items-center justify-center rounded bg-zinc-900 text-zinc-500">
+ <FileText size={28} aria-hidden="true" />
+ </div>
+ )}
+ <p className="text-[11px] text-zinc-300 truncate" title={p.file.name}>
+ {i + 1}. {p.file.name}
+ </p>
+ <p className="text-[11px] text-zinc-500">
+ {fileKind(p.file.type, p.file.name)} · {formatBytes(p.file.size)}
+ {p.attachmentId ? ' · uploaded' : phase === 'uploading' && p.progress > 0 ? ` · ${Math.round(p.progress * 100)}%` : ''}
+ </p>
+ <button
+ type="button"
+ disabled={working}
+ onClick={() => remove(p.key)}
+ aria-label={`Remove page ${i + 1}, ${p.file.name}`}
+ className="absolute top-1 right-1 p-1.5 rounded-md bg-zinc-900/90 text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800"
+ >
+ <X size={12} />
+ </button>
+ </li>
+ ))}
+ </ol>
+ )}
+
+ <div role="status" aria-live="polite">
+ {(error || problem) && (
+ <p
+ className={`flex items-start gap-1.5 text-xs break-words ${error?.calm ? 'px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 text-amber-100' : 'text-rose-300'}`}
+ data-letter-error={error?.calm ? 'busy' : 'invalid'}
+ >
+ {!error?.calm && <AlertTriangle size={13} className="mt-px shrink-0" aria-hidden="true" />}
+ {error?.text ?? problem}
+ </p>
+ )}
+ </div>
+
+ <div className="flex flex-wrap justify-end gap-2">
+ <button type="button" onClick={onCancel} disabled={working} className={quietBtn}>
+ Cancel
+ </button>
+ <button type="submit" disabled={working || pages.length === 0 || !!problem} className={primaryBtn}>
+ {working ? <Loader2 size={13} className={spin} aria-hidden="true" /> : <FileText size={13} aria-hidden="true" />}
+ {phase === 'uploading' ? 'Uploading…' : phase === 'starting' ? 'Starting…' : error?.calm ? 'Try again' : `Read ${pages.length > 1 ? `${pages.length} pages` : 'the letter'}`}
+ </button>
+ </div>
+ </form>
+ );
+};
+
+// ---------------------------------------------------------------------------
+// The letter itself
+
+export const StateBadge: React.FC<{ field: LetterField | null | undefined }> = ({ field }) => {
+ const s = fieldState(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}>
+ {s === 'uncertain' && <AlertTriangle size={11} aria-hidden="true" />}
+ {s === 'confirmed' && <Check size={11} aria-hidden="true" />}
+ {FIELD_STATE_LABEL[s]}
+ </span>
+ );
+};
+
+const FieldQuote: React.FC<{ field: LetterField }> = ({ field }) =>
+ field.quote ? (
+ <blockquote className="flex gap-1.5 text-[11px] text-zinc-400 whitespace-pre-wrap break-words">
+ <Quote size={11} className="mt-0.5 shrink-0 text-zinc-600" aria-hidden="true" />
+ <span>
+ <span className="sr-only">From the letter: </span>
+ {field.quote}
+ </span>
+ </blockquote>
+ ) : (
+ <p className="text-[11px] text-zinc-500">No matching words were found in the letter. Check the page.</p>
+ );
+
+/** One field: its value, the quote it came from, whether it's uncertain or confirmed, and Confirm / Edit / Clear. */
+export const FieldRow: React.FC<{ fkey: SingleKey; label: string; hint: string; field: LetterField | null | undefined; disabled: boolean; onSave: Save; initialEditing?: boolean; missing?: string }> = ({
+ fkey,
+ label,
+ hint,
+ field,
+ disabled,
+ onSave,
+ initialEditing = false,
+ missing = 'Not found in the letter.',
+}) => {
+ const id = useId();
+ const [editing, setEditing] = useState(initialEditing);
+ const [value, setValue] = useState(field?.value ?? '');
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const state = fieldState(field);
+ const isDate = fkey === 'deadline';
+ // Confirming "as it is" still has to parse: a deadline must be a real YYYY-MM-DD date.
+ const confirmBlocked = isDate && field?.value && !isIsoDate(field.value) ? 'This isn’t a YYYY-MM-DD date yet: edit it before confirming.' : null;
+
+ const save = async (body: Record<string, unknown>) => {
+ setSaving(true);
+ setError(null);
+ const err = await onSave(body);
+ setSaving(false);
+ if (err) setError(err);
+ else setEditing(false);
+ };
+
+ const submit = (e: React.FormEvent) => {
+ e.preventDefault();
+ const why = fieldValueError(fkey, value);
+ if (why) return setError(why);
+ save(setBody(fkey, value));
+ };
+
+ const busy = disabled || saving;
+ return (
+ <div className={`rounded-lg border p-2.5 space-y-1.5 min-w-0 ${state === 'uncertain' ? 'border-amber-500/40 bg-amber-500/5' : 'border-zinc-800 bg-zinc-950/40'}`} data-field={fkey} data-state={state}>
+ <div className="flex flex-wrap items-center justify-between gap-1.5">
+ <span id={`${id}-l`} className="text-[11px] font-semibold text-zinc-400">
+ {label}
+ </span>
+ <StateBadge field={field} />
+ </div>
+ {!editing && (
+ <>
+ {field?.value ? (
+ <p className="text-sm text-zinc-100 break-words" aria-labelledby={`${id}-l`}>
+ {isDate && isIsoDate(field.value) ? (
+ <>
+ {shortDate(field.value)} <span className="font-mono text-[11px] text-zinc-500">{field.value}</span>
+ </>
+ ) : (
+ field.value
+ )}
+ </p>
+ ) : (
+ <p className="text-xs text-zinc-500">{missing}</p>
+ )}
+ {field?.value && <FieldQuote field={field} />}
+ {confirmBlocked && <p className="text-[11px] text-amber-200">{confirmBlocked}</p>}
+ <div className="flex flex-wrap gap-2 pt-0.5">
+ {field?.value && state !== 'confirmed' && (
+ <button type="button" disabled={busy || !!confirmBlocked} onClick={() => save(confirmBody(fkey))} className={`${actionBtn} bg-emerald-600/90 hover:bg-emerald-500 text-white`}>
+ <Check size={13} aria-hidden="true" /> Confirm
+ </button>
+ )}
+ <button type="button" disabled={busy} onClick={() => (setValue(field?.value ?? ''), setError(null), setEditing(true))} className={quietBtn}>
+ {field?.value ? <Pencil size={13} aria-hidden="true" /> : <Plus size={13} aria-hidden="true" />}
+ {field?.value ? 'Edit' : 'Add'}
+ <span className="sr-only"> {label}</span>
+ </button>
+ {field?.value && (
+ <button type="button" disabled={busy} onClick={() => save(clearBody(fkey))} className={`${actionBtn} text-zinc-300 hover:bg-zinc-800`}>
+ <X size={13} aria-hidden="true" /> Clear<span className="sr-only"> {label}</span>
+ </button>
+ )}
+ {saving && <Loader2 size={13} className={`${spin} self-center text-zinc-400`} aria-label="Saving" />}
+ </div>
+ </>
+ )}
+ {editing && (
+ <form onSubmit={submit} className="space-y-2" noValidate>
+ {fkey === 'request' ? (
+ <textarea
+ aria-labelledby={`${id}-l`}
+ className={`${input} min-h-[72px]`}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder={hint}
+ maxLength={500}
+ autoFocus
+ />
+ ) : (
+ <input
+ aria-labelledby={`${id}-l`}
+ aria-describedby={isDate ? `${id}-fmt` : undefined}
+ aria-invalid={!!error}
+ className={`${input} ${isDate ? 'font-mono' : ''}`}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder={hint}
+ maxLength={500}
+ inputMode={isDate ? 'numeric' : undefined}
+ autoComplete="off"
+ spellCheck={!isDate}
+ autoFocus
+ />
+ )}
+ {isDate && (
+ <p id={`${id}-fmt`} className="text-[11px] text-zinc-500">
+ Year-month-day, for example 2026-11-14. Saving confirms it.
+ </p>
+ )}
+ {error && (
+ <p role="alert" className="text-[11px] text-rose-300 break-words">
+ {error}
+ </p>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={busy} className={primaryBtn}>
+ {saving ? <Loader2 size={13} className={spin} aria-hidden="true" /> : <Check size={13} aria-hidden="true" />} Save
+ </button>
+ <button type="button" disabled={saving} onClick={() => (setEditing(false), setError(null))} className={quietBtn}>
+ Cancel
+ </button>
+ </div>
+ </form>
+ )}
+ {!editing && error && (
+ <p role="alert" className="text-[11px] text-rose-300 break-words">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+};
+
+/** References, amounts or the checklist. The server takes the whole list, and saving confirms all of it. */
+export const ListField: React.FC<{ fkey: ListKey; label: string; hint: string; empty: string; items: LetterField[]; disabled: boolean; onSave: Save; initialEditing?: boolean }> = ({
+ fkey,
+ label,
+ hint,
+ empty,
+ items,
+ disabled,
+ onSave,
+ initialEditing = false,
+}) => {
+ const id = useId();
+ const [editing, setEditing] = useState(initialEditing);
+ const [rows, setRows] = useState<Array<{ value: string; done?: boolean | null }>>(items.map((i) => ({ value: i.value, done: i.done })));
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const checklist = fkey === 'checklist';
+ const unchecked = items.some((i) => fieldState(i) !== 'confirmed');
+ const busy = disabled || saving;
+
+ const save = async (list: Array<{ value: string; done?: boolean | null }>, confirm: boolean) => {
+ setSaving(true);
+ setError(null);
+ const err = await onSave(listBody(fkey, list, confirm));
+ setSaving(false);
+ if (err) setError(err);
+ else setEditing(false);
+ };
+
+ const submit = (e: React.FormEvent) => {
+ e.preventDefault();
+ const kept = rows.filter((r) => r.value.trim());
+ for (const r of kept) {
+ const why = fieldValueError(fkey, r.value);
+ if (why) return setError(`“${r.value.trim().slice(0, 40)}”: ${why}`);
+ }
+ if (kept.length > 20) return setError('At most 20 entries.');
+ save(kept, true);
+ };
+
+ const tick = (i: number, done: boolean) => save(items.map((x, j) => ({ value: x.value, done: j === i ? done : x.done })), false);
+
+ return (
+ <div className="rounded-lg border border-zinc-800 bg-zinc-950/40 p-2.5 space-y-2 min-w-0" data-list={fkey}>
+ <div className="flex flex-wrap items-center justify-between gap-1.5">
+ <span id={`${id}-l`} className="text-[11px] font-semibold text-zinc-400">
+ {label}
+ </span>
+ {items.length > 0 && !editing && <span className="text-[11px] text-zinc-500">{unchecked ? 'Not all checked' : 'All confirmed'}</span>}
+ </div>
+
+ {!editing && (
+ <>
+ {items.length === 0 ? (
+ <p className="text-xs text-zinc-500">{empty}</p>
+ ) : (
+ <ul className="space-y-1.5" aria-labelledby={`${id}-l`}>
+ {items.map((it, i) => {
+ const s = fieldState(it);
+ return (
+ <li key={`${i}-${it.value}`} className={`rounded-md px-2 py-1.5 space-y-1 ${s === 'uncertain' ? 'border border-amber-500/40 bg-amber-500/5' : 'border border-transparent'}`} data-state={s}>
+ <div className="flex items-start gap-2 min-w-0">
+ {checklist ? (
+ <label className="flex items-start gap-2 min-w-0 flex-1 cursor-pointer">
+ <input type="checkbox" className="mt-0.5 h-4 w-4 shrink-0 accent-emerald-500" checked={!!it.done} disabled={busy} onChange={(e) => tick(i, e.target.checked)} />
+ <span className={`text-xs break-words ${it.done ? 'text-zinc-500 line-through' : 'text-zinc-100'}`}>{it.value}</span>
+ </label>
+ ) : (
+ <span className={`text-xs text-zinc-100 break-words min-w-0 flex-1 ${fkey === 'amounts' || fkey === 'references' ? 'font-mono' : ''}`}>{it.value}</span>
+ )}
+ <StateBadge field={it} />
+ </div>
+ {s !== 'confirmed' && <FieldQuote field={it} />}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <div className="flex flex-wrap gap-2">
+ {items.length > 0 && unchecked && (
+ <button type="button" disabled={busy} onClick={() => save(items.map((x) => ({ value: x.value, done: x.done })), true)} className={`${actionBtn} bg-emerald-600/90 hover:bg-emerald-500 text-white`}>
+ <Check size={13} aria-hidden="true" /> Confirm all<span className="sr-only"> {label}</span>
+ </button>
+ )}
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => (setRows(items.length ? items.map((x) => ({ value: x.value, done: x.done })) : [{ value: '' }]), setError(null), setEditing(true))}
+ className={quietBtn}
+ >
+ {items.length ? <Pencil size={13} aria-hidden="true" /> : <Plus size={13} aria-hidden="true" />}
+ {items.length ? 'Edit' : 'Add'}
+ <span className="sr-only"> {label}</span>
+ </button>
+ {saving && <Loader2 size={13} className={`${spin} self-center text-zinc-400`} aria-label="Saving" />}
+ </div>
+ </>
+ )}
+
+ {editing && (
+ <form onSubmit={submit} className="space-y-2" noValidate>
+ {rows.map((r, i) => (
+ <div key={i} className="flex items-center gap-2 min-w-0">
+ <input
+ aria-label={`${label} ${i + 1}`}
+ className={`${input} ${fkey === 'checklist' ? '' : 'font-mono'}`}
+ value={r.value}
+ placeholder={hint}
+ maxLength={500}
+ autoComplete="off"
+ onChange={(e) => setRows((cur) => cur.map((x, j) => (j === i ? { ...x, value: e.target.value } : x)))}
+ />
+ <button type="button" onClick={() => setRows((cur) => cur.filter((_, j) => j !== i))} aria-label={`Remove ${label.toLowerCase()} ${i + 1}`} className="shrink-0 p-2 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">
+ <X size={14} />
+ </button>
+ </div>
+ ))}
+ {rows.length < 20 && (
+ <button type="button" onClick={() => setRows((cur) => [...cur, { value: '' }])} className={quietBtn}>
+ <Plus size={13} aria-hidden="true" /> Add one
+ </button>
+ )}
+ {fkey === 'amounts' && <p className="text-[11px] text-zinc-500">Include the currency, like GBP 142.60 or £142.60.</p>}
+ <p className="text-[11px] text-zinc-500">Saving confirms every entry in this list.</p>
+ {error && (
+ <p role="alert" className="text-[11px] text-rose-300 break-words">
+ {error}
+ </p>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <button type="submit" disabled={busy} className={primaryBtn}>
+ {saving ? <Loader2 size={13} className={spin} aria-hidden="true" /> : <Check size={13} aria-hidden="true" />} Save
+ </button>
+ <button type="button" disabled={saving} onClick={() => (setEditing(false), setError(null))} className={quietBtn}>
+ Cancel
+ </button>
+ </div>
+ </form>
+ )}
+ {!editing && error && (
+ <p role="alert" className="text-[11px] text-rose-300 break-words">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+};
+
+/** The pages as the person sent them: what each field should be checked against. */
+export const LetterPages: React.FC<{ extraction: Extraction | null }> = ({ extraction }) => {
+ const pages = extraction?.pages ?? [];
+ return (
+ <section aria-labelledby="letter-pages" className="space-y-2 min-w-0">
+ <h3 id="letter-pages" className={sectionTitle}>
+ The letter{pages.length > 1 ? ` · ${pages.length} pages` : ''}
+ </h3>
+ {pages.length === 0 && <p className="text-xs text-zinc-500">No pages are stored for this letter.</p>}
+ <ol className="space-y-3">
+ {pages.map((p, i) => (
+ <li key={p.id} className="rounded-lg border border-zinc-800 bg-zinc-900/40 overflow-hidden">
+ {isInlineImage(p.mime) ? (
+ <a href={p.url} target="_blank" rel="noopener noreferrer" title="Open full size">
+ <img src={p.url} alt={`Page ${i + 1} of the letter`} loading="lazy" className="block w-full max-h-[75vh] object-contain bg-zinc-950" />
+ </a>
+ ) : (
+ <a href={p.url} target="_blank" rel="noopener noreferrer" className="flex items-center gap-2 p-3 text-xs text-sky-300 hover:text-sky-200 hover:bg-zinc-800/60">
+ <FileText size={18} className="shrink-0" aria-hidden="true" />
+ <span className="min-w-0 break-all">{p.name}</span>
+ <span className="ml-auto shrink-0 inline-flex items-center gap-1 text-[11px]">
+ Open {fileKind(p.mime, p.name)} <ExternalLink size={11} aria-hidden="true" />
+ </span>
+ </a>
+ )}
+ <p className="px-3 py-1 text-[11px] text-zinc-500 border-t border-zinc-800 truncate">
+ Page {i + 1} · {p.name}
+ </p>
+ </li>
+ ))}
+ </ol>
+ {extraction && extraction.text.trim() && (
+ <details className="rounded-lg border border-zinc-800 bg-zinc-900/40">
+ <summary className="cursor-pointer px-3 py-2 text-xs text-zinc-300 min-h-[36px] flex items-center">What was read from it</summary>
+ <pre className="max-h-80 overflow-y-auto whitespace-pre-wrap break-words font-sans text-[11px] text-zinc-300 px-3 pb-3">{extraction.text}</pre>
+ </details>
+ )}
+ </section>
+ );
+};
+
+/** Reminders: off until the deadline is confirmed and certain; then 7, 1 and 0 days before. */
+export const LetterReminders: React.FC<{ deadline: LetterField | null | undefined; reminders: Reminder[]; closed: boolean }> = ({ deadline, reminders, closed }) => {
+ const gate = reminderGate(deadline);
+ return (
+ <section aria-labelledby="letter-reminders" className="space-y-2" data-reminders={gate.on && !closed ? 'on' : 'off'}>
+ <h3 id="letter-reminders" className={`${sectionTitle} flex items-center gap-1.5`}>
+ <Bell size={12} aria-hidden="true" /> Reminders
+ </h3>
+ {closed ? (
+ <p className="text-xs text-zinc-400">This letter is closed, so its reminders are off. Reopen it to bring back the ones still ahead.</p>
+ ) : (
+ <p className={`text-xs ${gate.on ? 'text-zinc-300' : 'px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 text-amber-100'}`}>{gate.text}</p>
+ )}
+ {!closed && gate.on && reminders.length === 0 && <p className="text-xs text-zinc-500">No reminders are left: the deadline has passed or is today.</p>}
+ {reminders.length > 0 && (
+ <ul className="divide-y divide-zinc-800 rounded-lg border border-zinc-800">
+ {[...reminders]
+ .sort((a, b) => b.offset_days - a.offset_days)
+ .map((r) => (
+ <li key={r.offset_days} className="flex flex-wrap items-center gap-x-3 gap-y-0.5 px-3 py-2 text-xs">
+ <span className="text-zinc-200 w-28 shrink-0">{reminderLabel(r.offset_days)}</span>
+ <time dateTime={r.due_at} className="text-zinc-400">
+ {reminderWhen(r.due_at)}
+ </time>
+ <span className={`ml-auto px-1.5 py-px rounded-full border text-[11px] ${r.fired_at ? STATE_TONE.confirmed : STATE_TONE.unconfirmed}`}>
+ {r.fired_at ? `Sent ${reminderWhen(r.fired_at)}` : 'Due'}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ <p className="text-[11px] text-zinc-500">A reminder is a notification with counts only, never the sender, amounts or words of the letter.</p>
+ </section>
+ );
+};
+
+/** The reply: copy it, or open it in the person's own mail app. Nothing is sent from kwant. */
+export const LetterDraft: React.FC<{ c: LooseCase }> = ({ c }) => {
+ const [copied, setCopied] = useState<'ok' | 'failed' | null>(null);
+ const d = c.draft;
+ if (!d) return null;
+ const open = d.channel === 'email' ? draftOpen(d) : null;
+ const copy = async () => {
+ try {
+ await navigator.clipboard.writeText(draftCopyText(d));
+ setCopied('ok');
+ playSfx('click');
+ } catch {
+ setCopied('failed');
+ }
+ };
+ return (
+ <section aria-labelledby="letter-draft" className="rounded-lg border border-sky-500/20 bg-sky-500/5 p-3 space-y-2" data-draft-channel={d.channel}>
+ <h3 id="letter-draft" className="text-[11px] font-semibold text-sky-200 break-words">
+ {d.channel === 'letter' ? 'Reply by post' : 'Reply by email'}
+ {d.to ? ` to ${d.to}` : ''}
+ {d.generated_by === 'model' && <span className="ml-1 font-normal text-zinc-500">(written by a model)</span>}
+ </h3>
+ <p className="text-[11px] text-amber-200" data-nothing-sent>
+ {draftChannelText(d.channel)}
+ </p>
+ {d.subject && <p className="text-xs text-zinc-300 break-words">Subject: {d.subject}</p>}
+ <pre className="max-h-64 overflow-y-auto whitespace-pre-wrap break-words font-sans text-xs text-zinc-100 bg-zinc-950/60 border border-zinc-800 rounded-lg p-2.5 select-text">{d.body}</pre>
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={copy} className={quietBtn}>
+ {copied === 'ok' ? <Check size={13} aria-hidden="true" /> : <Copy size={13} aria-hidden="true" />}
+ {copied === 'ok' ? 'Copied' : 'Copy reply'}
+ </button>
+ {open && (
+ <a href={open.href} rel="noopener noreferrer" className={quietBtn}>
+ <ExternalLink size={13} aria-hidden="true" /> {open.label}
+ </a>
+ )}
+ <span role="status" className="text-[11px] text-zinc-400">
+ {copied === 'failed' ? 'Couldn’t copy here: select the text above and copy it.' : ''}
+ </span>
+ </div>
+ </section>
+ );
+};
+
+export interface LetterDetailProps {
+ view: LetterViewData | null;
+ loading: boolean;
+ error: string | null;
+ notice?: { text: string; calm: boolean } | null;
+ acting?: boolean;
+ onSave: Save;
+ onDone: () => void;
+ onReopen: () => void;
+ onDelete: () => void;
+ onBack: () => void;
+ onRetry: () => void;
+ /** Tests open the delete confirmation. */
+ initialConfirmDelete?: boolean;
+}
+
+/** One letter: reading progress, the pages beside the fields, reminders, the reply and what to do with it. */
+export const LetterDetail: React.FC<LetterDetailProps> = ({ view, loading, error, notice = null, acting = false, onSave, onDone, onReopen, onDelete, onBack, onRetry, initialConfirmDelete = false }) => {
+ const [confirmDelete, setConfirmDelete] = useState(initialConfirmDelete);
+ const c = view?.case;
+ const e = view?.extraction ?? null;
+ const reading = stillReading(view);
+ const status = readingText(e);
+ const fields = e?.fields ?? {};
+ const closed = !!c && (c.status === 'closed' || c.status === 'dismissed');
+ const canEdit = !!e && !reading;
+ // Only a letter that was read can say a field was "not found" in it
+ const wasRead = e?.status === 'read';
+
+ return (
+ <div className="flex-1 flex flex-col h-full bg-zinc-950 overflow-hidden" data-letter={c?.id}>
+ <div className="h-14 border-b border-zinc-800/80 px-2 sm:px-6 flex items-center gap-2 bg-zinc-900/30 backdrop-blur-sm select-none">
+ <button
+ type="button"
+ onClick={onBack}
+ aria-label="Back to Loose ends"
+ className="shrink-0 p-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <ChevronLeft size={18} />
+ </button>
+ <div className="min-w-0 flex-1">
+ <h2 className="text-sm font-semibold text-zinc-100 truncate">{c?.title ?? 'Letter'}</h2>
+ <p className="text-[11px] text-zinc-400 truncate mt-0.5">Loose ends · letter</p>
+ </div>
+ {c && closed && <span className="shrink-0 px-1.5 py-px rounded-full border text-[11px] border-emerald-500/30 bg-emerald-500/10 text-emerald-200">{c.status === 'closed' ? 'Done' : 'Dismissed'}</span>}
+ </div>
+
+ <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-6" aria-busy={loading || reading}>
+ <div className="max-w-6xl mx-auto space-y-4">
+ {error && (
+ <div role="alert" className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 flex flex-wrap items-center gap-2 text-xs text-rose-300">
+ <span className="break-words">Couldn’t load the letter: {error}</span>
+ <button type="button" onClick={onRetry} className="ml-auto px-2 py-0.5 rounded border border-rose-500/30 hover:bg-rose-500/10">
+ Retry
+ </button>
+ </div>
+ )}
+ {!view && loading && (
+ <p className="flex items-center gap-2 text-xs text-zinc-400">
+ <Loader2 size={14} className={spin} aria-hidden="true" /> Loading…
+ </p>
+ )}
+
+ {view && (
+ <>
+ <div role="status" aria-live="polite" className={`px-3 py-2 rounded-lg border text-xs space-y-1 ${BANNER_TONE[status.tone]}`} data-read-status={e?.status ?? 'none'}>
+ <p className="font-semibold flex items-center gap-1.5">
+ {reading && <Loader2 size={13} className={spin} aria-hidden="true" />}
+ {status.title}
+ </p>
+ <p className="break-words opacity-90">{status.body}</p>
+ {reading && (
+ <div className="h-1 rounded-full bg-sky-950 overflow-hidden" role="progressbar" aria-label="Reading the letter" aria-valuetext="Reading">
+ <div className="h-full w-1/3 rounded-full bg-sky-400 animate-pulse motion-reduce:animate-none" />
+ </div>
+ )}
+ </div>
+
+ <div role="status" aria-live="polite">
+ {notice && (
+ <p className={`px-3 py-2 rounded-lg border text-xs break-words ${notice.calm ? 'border-amber-500/30 bg-amber-500/10 text-amber-100' : 'border-rose-500/30 bg-rose-500/10 text-rose-200'}`}>{notice.text}</p>
+ )}
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-5 items-start">
+ <div className="lg:sticky lg:top-0 min-w-0">
+ <LetterPages extraction={e} />
+ </div>
+
+ <div className="space-y-5 min-w-0">
+ <section aria-labelledby="letter-fields" className="space-y-2">
+ <h3 id="letter-fields" className={sectionTitle}>
+ What it says
+ </h3>
+ {reading ? (
+ <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>
+ {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.'} />
+ ))}
+ {LIST_FIELDS.map((f) => (
+ <ListField
+ key={`${f.key}-${JSON.stringify(fields[f.key] ?? [])}`}
+ fkey={f.key}
+ label={f.label}
+ hint={f.hint}
+ empty={wasRead ? f.empty : 'None added yet.'}
+ items={fields[f.key] ?? []}
+ disabled={!canEdit || acting}
+ onSave={onSave}
+ />
+ ))}
+ </>
+ )}
+ </section>
+
+ {!reading && <LetterReminders deadline={fields.deadline} reminders={view.reminders} closed={closed} />}
+
+ {!reading && c && !closed && <LetterDraft c={c} />}
+
+ {c && (
+ <section aria-label="What to do with this letter" className="space-y-2 border-t border-zinc-800 pt-4">
+ <div className="flex flex-wrap gap-2">
+ {closed ? (
+ <button type="button" disabled={acting} onClick={onReopen} className={quietBtn}>
+ <RotateCcw size={13} aria-hidden="true" /> Reopen
+ </button>
+ ) : (
+ <button type="button" disabled={acting || reading} onClick={onDone} className={`${actionBtn} bg-emerald-600/90 hover:bg-emerald-500 text-white`}>
+ <CheckCircle2 size={13} aria-hidden="true" /> Mark done
+ </button>
+ )}
+ {!confirmDelete && (
+ <button type="button" disabled={acting} onClick={() => setConfirmDelete(true)} className={`${actionBtn} text-rose-300 hover:bg-rose-500/10`}>
+ <Trash2 size={13} aria-hidden="true" /> Delete letter
+ </button>
+ )}
+ {acting && <Loader2 size={13} className={`${spin} self-center text-zinc-400`} aria-label="Saving" />}
+ </div>
+ {confirmDelete && (
+ <div role="group" aria-label="Delete this letter" className="rounded-lg border border-rose-500/30 bg-rose-500/5 p-3 space-y-2" data-confirm-delete>
+ <p className="text-xs text-rose-100">Delete this letter, its pages, everything read from it and its reminders? This can’t be undone.</p>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" disabled={acting} onClick={() => (setConfirmDelete(false), onDelete())} className={`${actionBtn} bg-rose-600 hover:bg-rose-500 text-white`}>
+ <Trash2 size={13} aria-hidden="true" /> Delete it
+ </button>
+ <button type="button" onClick={() => setConfirmDelete(false)} className={quietBtn}>
+ Keep it
+ </button>
+ </div>
+ </div>
+ )}
+ </section>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+/** Loads one letter, polls while it's read, saves field changes and runs done / reopen / delete. */
+export const LetterPage: React.FC<{ caseId: string; onBack: () => void; onDeleted: (title: string) => void }> = ({ caseId, onBack, onDeleted }) => {
+ const [view, setView] = useState<LetterViewData | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<{ text: string; calm: boolean } | null>(null);
+ const [acting, setActing] = useState(false);
+ const alive = useRef(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const v = await letterApi.get(caseId);
+ if (alive.current) (setView(v), setError(null));
+ return v;
+ } catch (e) {
+ if (alive.current) setError(e instanceof Error ? e.message : 'Something went wrong.');
+ return null;
+ } finally {
+ if (alive.current) setLoading(false);
+ }
+ }, [caseId]);
+
+ useEffect(() => {
+ alive.current = true;
+ load();
+ return () => {
+ alive.current = false;
+ };
+ }, [load]);
+
+ const reading = stillReading(view);
+ const wasReading = useRef(false);
+ useEffect(() => {
+ if (!reading) {
+ // The server stores what was read a moment before it updates the case (title, draft):
+ // one more load once reading ends picks those up.
+ if (!wasReading.current) return;
+ wasReading.current = false;
+ const t = window.setTimeout(() => load(), 1000);
+ return () => window.clearTimeout(t);
+ }
+ wasReading.current = true;
+ const t = window.setInterval(() => load(), 2000);
+ return () => window.clearInterval(t);
+ }, [reading, load]);
+
+ const save: Save = async (body) => {
+ try {
+ const v = await letterApi.patch(caseId, body);
+ if (alive.current) (setView(v), setNotice(null));
+ return null;
+ } catch (e) {
+ if (e instanceof LooseEndsError && e.status === 409) {
+ load();
+ return 'This letter is still being read. Try again once it has finished.';
+ }
+ return `${e instanceof Error ? e.message : 'Something went wrong.'} Nothing was changed.`;
+ }
+ };
+
+ const act = async (a: 'done' | 'reopen') => {
+ setActing(true);
+ setNotice(null);
+ try {
+ await looseApi.act(caseId, a);
+ await load();
+ } catch (e) {
+ setNotice({ text: `${e instanceof Error ? e.message : 'Something went wrong.'} The letter is unchanged.`, calm: false });
+ } finally {
+ setActing(false);
+ }
+ };
+
+ const remove = async () => {
+ setActing(true);
+ setNotice(null);
+ try {
+ await letterApi.remove(caseId);
+ onDeleted(view?.case.title ?? 'Letter');
+ } catch (e) {
+ if (alive.current) setNotice(deleteErrorText(e));
+ } finally {
+ if (alive.current) setActing(false);
+ }
+ };
+
+ return (
+ <LetterDetail
+ view={view}
+ loading={loading}
+ error={error}
+ notice={notice}
+ acting={acting}
+ onSave={save}
+ onDone={() => act('done')}
+ onReopen={() => act('reopen')}
+ onDelete={remove}
+ onBack={onBack}
+ onRetry={load}
+ />
+ );
+};
diff --git a/frontend/src/components/LooseEndsView.tsx b/frontend/src/components/LooseEndsView.tsx
index 51900280..0c659efe 100644
--- a/frontend/src/components/LooseEndsView.tsx
+++ b/frontend/src/components/LooseEndsView.tsx
@@ -7,6 +7,7 @@ import {
ChevronLeft,
Copy,
ExternalLink,
+ FileText,
GitBranch,
Loader2,
Mail,
@@ -22,6 +23,7 @@ import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { playSfx } from '../audio/chiptune';
import { storeApi } from '../passwordStore';
import { BitwardenLoginForm, usePasswordStore } from './PasswordStorePanel';
+import { AddLetterForm, LetterPage } from './LetterView';
import {
ACTION_LABELS,
CASE_TABS,
@@ -64,6 +66,7 @@ const SOURCE_ICON: Record<string, React.ReactNode> = {
imap: <Mail size={12} aria-hidden="true" />,
github: <GitBranch size={12} aria-hidden="true" />,
kwant: <MessageSquare size={12} aria-hidden="true" />,
+ document: <FileText size={12} aria-hidden="true" />,
};
const actionBtn =
@@ -88,13 +91,15 @@ export interface LooseCaseCardProps {
onAction: (c: LooseCase, action: CaseAction, body?: unknown) => void;
/** Opens a bot thread in the app; without it a case shows no chat link. */
onOpenChat?: (kwantId: string, threadId: string) => void;
+ /** Opens a letter case (`source: "document"`) with its pages and fields. */
+ onOpenLetter?: (caseId: string) => void;
/** Tests open a choice. */
initialChoice?: 'snooze' | 'dismiss' | null;
}
/** One loose end: who, why it stalled, the evidence, the draft and what to do with it. Generic
* over the source, so a letter or a bank statement can use the same card. */
-export const LooseCaseCard: React.FC<LooseCaseCardProps> = ({ c, busy, now = Date.now(), onAction, onOpenChat, initialChoice = null }) => {
+export const LooseCaseCard: React.FC<LooseCaseCardProps> = ({ c, busy, now = Date.now(), onAction, onOpenChat, onOpenLetter, initialChoice = null }) => {
const id = useId();
const [choice, setChoice] = useState<'snooze' | 'dismiss' | null>(initialChoice);
const [copied, setCopied] = useState<'ok' | 'failed' | null>(null);
@@ -189,6 +194,12 @@ export const LooseCaseCard: React.FC<LooseCaseCardProps> = ({ c, busy, now = Dat
</div>
)}
+ {c.source === 'document' && onOpenLetter && (
+ <button type="button" onClick={() => onOpenLetter(c.id)} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`} data-open-letter>
+ <FileText size={13} aria-hidden="true" /> Open letter
+ </button>
+ )}
+
{chat && (
<button
type="button"
@@ -614,6 +625,9 @@ export interface LooseEndsViewProps {
onScan: () => void;
onAction: (c: LooseCase, action: CaseAction, body?: unknown) => void;
onOpenChat?: (kwantId: string, threadId: string) => void;
+ onOpenLetter?: (caseId: string) => void;
+ /** "Add a letter": a button, or the open form. */
+ addLetter?: React.ReactNode;
onBack?: () => void;
}
@@ -635,6 +649,8 @@ export const LooseEndsView: React.FC<LooseEndsViewProps> = ({
onScan,
onAction,
onOpenChat,
+ onOpenLetter,
+ addLetter = null,
onBack,
}) => {
const counts = CASE_TABS.reduce((acc, t) => ({ ...acc, [t.key]: (cases ?? []).filter((c) => tabOf(c.status) === t.key).length }), {} as Record<CaseTab, number>);
@@ -707,6 +723,8 @@ export const LooseEndsView: React.FC<LooseEndsViewProps> = ({
</p>
)}
+ {cases && addLetter}
+
{cases && (
<>
<div role="tablist" aria-label="Loose ends by status" className="flex gap-1 overflow-x-auto -mx-1 px-1">
@@ -736,7 +754,7 @@ export const LooseEndsView: React.FC<LooseEndsViewProps> = ({
) : (
<ul className="space-y-3">
{shown.map((c) => (
- <LooseCaseCard key={c.id} c={c} busy={busy === c.id} now={now} onAction={onAction} onOpenChat={onOpenChat} />
+ <LooseCaseCard key={c.id} c={c} busy={busy === c.id} now={now} onAction={onAction} onOpenChat={onOpenChat} onOpenLetter={onOpenLetter} />
))}
</ul>
)}
@@ -751,6 +769,15 @@ export const LooseEndsView: React.FC<LooseEndsViewProps> = ({
);
};
+export const AddLetterButton: React.FC<{ onClick: () => void }> = ({ onClick }) => (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-xl border border-dashed border-zinc-700 p-3">
+ <button type="button" onClick={onClick} className={`${actionBtn} bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold`} data-add-letter-button>
+ <FileText size={13} aria-hidden="true" /> Add a letter
+ </button>
+ <p className="text-[11px] text-zinc-500 min-w-0 flex-1">Photograph or upload a bill or form to get its deadline and a reply draft. Nothing is sent.</p>
+ </div>
+);
+
/** Loads cases and sources, runs the card actions and scans. */
export const LooseEndsPage: React.FC<{ onBack?: () => void; onOpenChat?: (kwantId: string, threadId: string) => void }> = ({ onBack, onOpenChat }) => {
const [cases, setCases] = useState<LooseCase[] | null>(null);
@@ -764,6 +791,8 @@ export const LooseEndsPage: React.FC<{ onBack?: () => void; onOpenChat?: (kwantI
const [sources, setSources] = useState<LooseSource[] | null>(null);
const [sourcesError, setSourcesError] = useState<string | null>(null);
const [nextReview, setNextReview] = useState<string | null>(null);
+ const [letter, setLetter] = useState<string | null>(null);
+ const [addingLetter, setAddingLetter] = useState(false);
const alive = useRef(true);
const loadSources = useCallback(async () => {
@@ -853,6 +882,19 @@ export const LooseEndsPage: React.FC<{ onBack?: () => void; onOpenChat?: (kwantI
}
};
+ if (letter)
+ return (
+ <LetterPage
+ caseId={letter}
+ onBack={() => (setLetter(null), load())}
+ onDeleted={(title) => {
+ setLetter(null);
+ setNotice({ text: `Deleted “${title}”, its pages and everything read from it.`, error: false });
+ load();
+ }}
+ />
+ );
+
return (
<LooseEndsView
cases={cases}
@@ -869,6 +911,21 @@ export const LooseEndsPage: React.FC<{ onBack?: () => void; onOpenChat?: (kwantI
onScan={scan}
onAction={act}
onOpenChat={onOpenChat}
+ onOpenLetter={(id) => (setNotice(null), setLetter(id))}
+ addLetter={
+ addingLetter ? (
+ <AddLetterForm
+ onCancel={() => setAddingLetter(false)}
+ onCreated={(id) => {
+ setAddingLetter(false);
+ setNotice(null);
+ setLetter(id);
+ }}
+ />
+ ) : (
+ <AddLetterButton onClick={() => setAddingLetter(true)} />
+ )
+ }
onBack={onBack}
sources={<LooseSources sources={sources} error={sourcesError} onChanged={() => (loadSources(), load())} />}
/>
diff --git a/frontend/src/letters.ts b/frontend/src/letters.ts
new file mode 100644
index 00000000..2cd42307
--- /dev/null
+++ b/frontend/src/letters.ts
@@ -0,0 +1,255 @@
+// 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
+// sent: the reply is a draft the person copies (or opens in their own mail app).
+
+import { LooseCase, LooseEndsError, call, shortDate } from './looseEnds';
+import { MAX_ATTACHMENT_BYTES } from './attachments';
+
+export interface LetterField {
+ value: string;
+ /** Where in the letter the value came from; empty when kwant found no quote. */
+ quote: string;
+ uncertain: boolean;
+ confirmed: boolean;
+ /** Checklist items only. */
+ done?: boolean | null;
+}
+
+export type SingleKey = 'sender' | 'request' | 'reply_to' | 'deadline';
+export type ListKey = 'references' | 'amounts' | 'checklist';
+
+export interface LetterFields {
+ sender?: LetterField | null;
+ request?: LetterField | null;
+ reply_to?: LetterField | null;
+ deadline?: LetterField | null;
+ references?: LetterField[];
+ amounts?: LetterField[];
+ checklist?: LetterField[];
+}
+
+export type ReadStatus = 'running' | 'read' | 'text_only' | 'unreadable';
+
+export interface LetterPage {
+ id: string;
+ name: string;
+ mime: string;
+ url: string;
+}
+
+export interface Extraction {
+ status: ReadStatus | string;
+ method: string | null;
+ note: string | null;
+ fields: LetterFields;
+ text: string;
+ read_by: string | null;
+ pages: LetterPage[];
+ updated_at: string;
+}
+
+export interface Reminder {
+ offset_days: number;
+ due_at: string;
+ fired_at: string | null;
+}
+
+export interface LetterView {
+ case: LooseCase;
+ extraction: Extraction | null;
+ reminders: Reminder[];
+}
+
+export const MAX_LETTER_PAGES = 5;
+export const LETTER_MIMES = ['image/png', 'image/jpeg', 'image/webp', 'application/pdf'];
+const LETTER_EXTS: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', pdf: 'application/pdf' };
+/** For the file picker. */
+export const LETTER_ACCEPT = 'image/png,image/jpeg,image/webp,application/pdf,.png,.jpg,.jpeg,.webp,.pdf';
+
+/** A page's type from the browser's MIME, or its extension when the browser gives none. */
+export function letterMime(f: { name: string; type: string }): string | null {
+ const t = f.type.toLowerCase();
+ if (LETTER_MIMES.includes(t)) return t;
+ if (t && t !== 'application/octet-stream') return null;
+ const ext = /\.([a-z0-9]+)$/i.exec(f.name)?.[1]?.toLowerCase();
+ return (ext && LETTER_EXTS[ext]) || null;
+}
+
+/** Why these pages can't be read as one letter, or null. Checked before anything is uploaded. */
+export function checkLetterFiles(files: Array<{ name: string; type: string; size: number }>): string | null {
+ if (files.length === 0) return 'Add a photo or a PDF of the letter.';
+ if (files.length > MAX_LETTER_PAGES) return `A letter can have at most ${MAX_LETTER_PAGES} pages. You picked ${files.length}: remove ${files.length - MAX_LETTER_PAGES}.`;
+ for (const f of files) {
+ const name = f.name || 'That file';
+ if (!letterMime(f)) return `${name} isn’t a photo or a PDF. Use PNG, JPEG, WebP or PDF.`;
+ if (f.size === 0) return `${name} is empty.`;
+ if (f.size > MAX_ATTACHMENT_BYTES) return `${name} is too big (${(f.size / (1024 * 1024)).toFixed(1)} MB). Max 20 MB per page.`;
+ }
+ return null;
+}
+
+/** A real calendar date written `YYYY-MM-DD`, the only form a deadline is saved in. */
+export function isIsoDate(s: string): boolean {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s.trim());
+ if (!m) return false;
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
+ const dt = new Date(Date.UTC(y, mo - 1, d));
+ return dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d;
+}
+
+/** An amount kwant can save: a number and a currency (`GBP 142.60`, `£142.60`, `142,60 EUR`). */
+export const looksLikeAmount = (s: string): boolean => /\d/.test(s) && (/(^|[^A-Za-z])[A-Z]{3}([^A-Za-z]|$)/.test(s) || /[€$£₴]/.test(s));
+
+export const MAX_FIELD_CHARS = 500;
+
+/** Why a value can't be saved in this field, or null. The server checks again. */
+export function fieldValueError(key: SingleKey | ListKey, value: string): string | null {
+ const v = value.trim();
+ if (!v) return 'Type something, or use Clear to remove it.';
+ if (v.length > MAX_FIELD_CHARS) return `At most ${MAX_FIELD_CHARS} characters.`;
+ if (key === 'deadline' && !isIsoDate(v)) return 'Write the date as YYYY-MM-DD, for example 2026-11-14.';
+ if (key === 'amounts' && !looksLikeAmount(v)) return 'Include the currency, for example GBP 142.60.';
+ return null;
+}
+
+export type FieldState = 'empty' | 'confirmed' | 'uncertain' | 'unconfirmed';
+
+/** Confirmed wins: the person checked it. Otherwise an uncertain mark is never hidden. */
+export function fieldState(f: LetterField | null | undefined): FieldState {
+ if (!f || !f.value) return 'empty';
+ if (f.confirmed && !f.uncertain) return 'confirmed';
+ if (f.uncertain) return 'uncertain';
+ return 'unconfirmed';
+}
+
+export const FIELD_STATE_LABEL: Record<FieldState, string> = {
+ empty: 'Empty',
+ confirmed: 'Confirmed',
+ uncertain: 'Uncertain',
+ unconfirmed: 'Not checked yet',
+};
+
+export const SINGLE_FIELDS: Array<{ key: SingleKey; label: string; hint: string }> = [
+ { key: 'sender', label: 'From', hint: 'Who sent the letter' },
+ { key: 'request', label: 'What they want', hint: 'What the letter asks you to do' },
+ { key: 'deadline', label: 'Deadline', hint: 'YYYY-MM-DD' },
+ { key: 'reply_to', label: 'Reply to', hint: 'An email or postal address from the letter' },
+];
+
+export const LIST_FIELDS: Array<{ key: ListKey; label: string; hint: string; empty: string }> = [
+ { key: 'references', label: 'References', hint: 'Account or case number', empty: 'No reference numbers found.' },
+ { key: 'amounts', label: 'Amounts', hint: 'GBP 142.60', empty: 'No amounts found.' },
+ { key: 'checklist', label: 'Checklist', hint: 'Something to do', empty: 'Nothing to do was found.' },
+];
+
+/** The body for confirming a single field as it is, setting it, or clearing it. */
+export const confirmBody = (key: SingleKey) => ({ [key]: {} });
+export const setBody = (key: SingleKey, value: string) => ({ [key]: { value: value.trim() } });
+export const clearBody = (key: SingleKey) => ({ [key]: null });
+
+/** A list is always sent whole. Saving it confirms every item in it (the server's rule). */
+/** A whole list for the server. `confirm` confirms every entry as it is; without it only new or changed entries are confirmed. */
+export function listBody(key: ListKey, items: Array<{ value: string; done?: boolean | null }>, confirm = false) {
+ return {
+ [key]: items.map((i) => ({
+ value: i.value.trim(),
+ ...(key === 'checklist' ? { done: !!i.done } : {}),
+ ...(confirm ? { confirmed: true } : {}),
+ })),
+ };
+}
+
+/** How far kwant got with the letter, said plainly. */
+export function readingText(e: Extraction | null): { title: string; body: string; tone: 'sky' | 'emerald' | 'amber' | 'rose' } {
+ if (!e) return { title: 'Waiting to read', body: 'This letter hasn’t been read yet.', tone: 'sky' };
+ const note = e.note ? ` ${sentence(e.note)}` : '';
+ // The server's note may already ask the person to fill the fields in: don't say it twice
+ const fillIn = (text: string) => (/fill in the fields/i.test(e.note ?? '') ? '' : ` ${text}`);
+ switch (e.status) {
+ 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' };
+ 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':
+ return { title: 'This letter couldn’t be read', body: `Nothing was picked out of it.${note}${fillIn('Fill in the fields yourself from the pages shown here.')}`, tone: 'rose' };
+ default:
+ return { title: 'Unknown state', body: `The reader reports “${e.status}”.${note}`, tone: 'amber' };
+ }
+}
+
+export function methodText(method: string | null): string {
+ switch (method) {
+ case 'pdf_text':
+ return 'Read from the PDF’s text.';
+ case 'model_vision':
+ return 'Read from the photos by your Claude model: compare each field with the page.';
+ case 'pdf_text+model_vision':
+ return 'Read from the PDF’s text and, for the photos, by your Claude model.';
+ default:
+ return '';
+ }
+}
+
+/** Whether reminders run, and why not. Mirrors the server: confirmed and not uncertain. */
+export function reminderGate(deadline: LetterField | null | undefined): { on: boolean; text: string } {
+ const s = fieldState(deadline);
+ if (s === 'empty') return { on: false, text: 'No deadline yet. Reminders start once you add and confirm one.' };
+ if (s === 'uncertain') return { on: false, text: 'The deadline is marked uncertain, so there are no reminders. Check it against the letter and confirm it to start them.' };
+ if (s === 'unconfirmed') return { on: false, text: 'Reminders start once you confirm the deadline.' };
+ return { on: true, text: `Reminders 7 days before, 1 day before and on ${shortDate(deadline!.value)}, at 09:00.` };
+}
+
+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 => {
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(undefined, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
+};
+
+/** Text for a refused upload of a letter: busy reads calmly, the rest says what to change. */
+export function letterErrorText(e: unknown): { text: string; calm: boolean } {
+ if (e instanceof LooseEndsError) {
+ if (e.status === 409 && e.code === 'busy') return { text: 'Another letter is being read right now. Your pages are saved here: try again in a minute.', calm: true };
+ if (e.status === 409) return { text: `${e.message} Pick the pages again.`, calm: false };
+ return { text: e.message, calm: false };
+ }
+ return { text: e instanceof Error ? e.message : 'Something went wrong.', calm: false };
+}
+
+/** Text for a refused delete. The letter is never half-deleted. */
+export function deleteErrorText(e: unknown): { text: string; calm: boolean } {
+ if (e instanceof LooseEndsError && e.status === 409) return { text: 'This letter is still being read. It can be deleted once reading finishes.', calm: true };
+ return { text: `${e instanceof Error ? e.message : 'Something went wrong.'} Nothing was deleted.`, calm: false };
+}
+
+/** Where a letter's reply goes. Nothing is ever sent from kwant. */
+export function draftChannelText(channel: string): string {
+ if (channel === 'email') return 'Nothing is sent from kwant bots. Copy the reply, or open it in your own mail app and send it from there.';
+ if (channel === 'letter') return 'Nothing is sent from kwant bots. This is a paper reply: copy it, then print or write it out and post it yourself.';
+ return 'Nothing is sent from kwant bots. Copy it and send it yourself.';
+}
+
+export const isLetter = (c: Pick<LooseCase, 'source'>) => c.source === 'document';
+
+/** Poll while kwant reads. */
+export const stillReading = (v: LetterView | null) => !!v && (!v.extraction || v.extraction.status === 'running');
+
+const sentence = (s: string) => {
+ const t = s.trim();
+ if (!t) return t;
+ // The brand stays lowercase ("kwant restarted while reading it").
+ const c = /^kwant\b/.test(t) ? t : t[0].toUpperCase() + t.slice(1);
+ return /[.!?]$/.test(c) ? c : `${c}.`;
+};
+
+const enc = encodeURIComponent;
+
+export const letterApi = {
+ create: (attachment_ids: string[]) => call<{ case_id: string }>('/api/documents', 'POST', { attachment_ids }),
+ get: (id: string) => call<LetterView>(`/api/documents/${enc(id)}`),
+ remove: (id: string) => call<{ deleted: boolean }>(`/api/documents/${enc(id)}`, 'DELETE'),
+ patch: (id: string, body: Record<string, unknown>) => call<LetterView>(`/api/zombie/cases/${enc(id)}/fields`, 'PATCH', body),
+};
diff --git a/frontend/src/looseEnds.ts b/frontend/src/looseEnds.ts
index c3475ca3..fee1f4f9 100644
--- a/frontend/src/looseEnds.ts
+++ b/frontend/src/looseEnds.ts
@@ -16,7 +16,7 @@ export interface Evidence {
}
export interface CaseDraft {
- /** `email`, `github` or `kwant`: where the person sends it themselves. */
+ /** `email`, `github`, `kwant` or `letter` (a paper reply: copy only). Where the person sends it themselves. */
channel: string;
to: string | null;
subject: string | null;
@@ -81,9 +81,10 @@ const KINDS: Record<string, { label: string; tone: Tone }> = {
stale_issue: { label: 'Gone quiet', tone: 'zinc' },
failed_task: { label: 'Task failed', tone: 'rose' },
unanswered_question: { label: 'Question open', tone: 'amber' },
+ document_request: { label: 'Letter to deal with', tone: 'sky' },
};
-const SOURCES: Record<string, string> = { imap: 'Email', github: 'GitHub', kwant: 'Bot chats' };
+const SOURCES: Record<string, string> = { imap: 'Email', github: 'GitHub', kwant: 'Bot chats', document: 'Letter' };
/** `bank_statement` → `Bank statement`: how an unknown kind or source still reads. */
export function humanize(s: string): string {
@@ -199,6 +200,8 @@ export class LooseEndsError extends Error {
public needsBitwarden = false,
/** 423: Bitwarden holds the logins and is locked. */
public locked = false,
+ /** The server's `code`, e.g. `busy` on a 409. */
+ public code: string | null = null,
) {
super(message);
}
@@ -211,7 +214,7 @@ const sentence = (s: string) => {
return /[.!?]$/.test(c) ? c : `${c}.`;
};
-async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
+export async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T> {
let res: Response;
try {
res = await personFetch(url, {
@@ -229,11 +232,12 @@ async function call<T>(url: string, method = 'GET', body?: unknown): Promise<T>
const needs = needsBitwardenFrom(res.status, answer);
if (needs) throw new LooseEndsError(needs.message, 409, true);
const err = answer && typeof answer === 'object' ? (answer as Record<string, unknown>).error : null;
+ const code = answer && typeof answer === 'object' && typeof (answer as Record<string, unknown>).code === 'string' ? ((answer as Record<string, unknown>).code as string) : null;
const msg = typeof err === 'string' && err.trim() ? sentence(err) : `Something went wrong (HTTP ${res.status}).`;
if (res.status === 423) throw new LooseEndsError(msg, 423, false, true);
if (res.status === 403) throw new LooseEndsError('Only you can see and change loose ends.', 403);
if (res.status === 404 && !err) throw new LooseEndsError('This server doesn’t have loose ends yet. Update the app and try again.', 404);
- throw new LooseEndsError(msg, res.status);
+ throw new LooseEndsError(msg, res.status, false, false, code);
}
const enc = encodeURIComponent;
diff --git a/frontend/tests/letters.test.mjs b/frontend/tests/letters.test.mjs
new file mode 100644
index 00000000..8282fd19
--- /dev/null
+++ b/frontend/tests/letters.test.mjs
@@ -0,0 +1,293 @@
+// Camera-to-Completed (idea 05): a letter becomes a Loose ends case. Uncertain fields are never shown
+// as checked, a deadline is only ever YYYY-MM-DD, reminders wait for a confirmed and certain deadline,
+// a busy server reads calmly, an unreadable letter says so, and a paper reply is copy only.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const m = await loadBundled(`export * from './src/letters'; export { LooseEndsError } from './src/looseEnds';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { LetterDetail, FieldRow, ListField, LetterReminders, LetterDraft, AddLetterForm } from './src/components/LetterView';
+ import { LooseCaseCard } from './src/components/LooseEndsView';
+ const r = (C) => (props) => renderToStaticMarkup(React.createElement(C, props));
+ export const detail = r(LetterDetail);
+ export const row = r(FieldRow);
+ export const list = r(ListField);
+ export const reminders = r(LetterReminders);
+ export const draft = r(LetterDraft);
+ export const add = r(AddLetterForm);
+ export const card = (props) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(LooseCaseCard, props)));
+`);
+
+const noop = () => {};
+const save = async () => null;
+const f = (value, over = {}) => ({ value, quote: `“${value}”`, uncertain: false, confirmed: false, ...over });
+
+// Shaped like DocumentView in src/server/document_routes.rs.
+const letterCase = (over = {}) => ({
+ id: 'd1', status: 'open', kind: 'document_request', conv_kind: 'document', source: 'document', source_id: 'd1',
+ title: 'Letter from Thames Water', counterpart: null, counterpart_name: 'Thames Water', reference: 'TW-88213',
+ link: null, why: 'Pay the outstanding balance', evidence: [],
+ draft: { channel: 'letter', to: 'Thames Water', subject: 'Re: TW-88213', body: 'Dear Thames Water,\nre TW-88213.', mailto: null, open_url: null, kwant_thread_id: null, generated_by: 'template', created_at: '2026-10-20T08:00:00Z' },
+ age_days: 0, last_activity_at: '2026-10-20T08:00:00Z', snoozed_until: null, waiting_since: null, follow_ups: 0,
+ deadline: null, resolution: null, dismiss_reason: null,
+ ...over,
+});
+const extraction = (over = {}) => ({
+ status: 'read', method: 'pdf_text+model_vision', note: null,
+ fields: {
+ sender: f('Thames Water', { confirmed: true }),
+ request: f('Pay the outstanding balance'),
+ reply_to: null,
+ deadline: f('2026-11-14', { uncertain: true }),
+ references: [f('TW-88213')],
+ amounts: [f('GBP 142.60')],
+ checklist: [f('Pay the bill', { done: true, confirmed: true }), f('Send meter reading', { done: false })],
+ },
+ text: 'Water bill', read_by: 'cli',
+ pages: [
+ { id: 'a1', name: 'water-bill.pdf', mime: 'application/pdf', url: '/api/attachments/a1/content' },
+ { id: 'a2', name: 'letter-page2.png', mime: 'image/png', url: '/api/attachments/a2/content' },
+ ],
+ updated_at: '2026-10-20T08:00:00Z',
+ ...over,
+});
+const view = (over = {}, ext = {}) => ({ case: letterCase(over), extraction: extraction(ext), reminders: [] });
+const detailProps = (v, over = {}) => ({ view: v, loading: false, error: null, onSave: save, onDone: noop, onReopen: noop, onDelete: noop, onBack: noop, onRetry: noop, ...over });
+
+test('a field is Confirmed only when confirmed and not uncertain; uncertain is never hidden', () => {
+ assert.equal(m.fieldState(null), 'empty');
+ assert.equal(m.fieldState(f('')), 'empty');
+ assert.equal(m.fieldState(f('x')), 'unconfirmed');
+ assert.equal(m.fieldState(f('x', { uncertain: true })), 'uncertain');
+ assert.equal(m.fieldState(f('x', { confirmed: true })), 'confirmed');
+ assert.equal(m.fieldState(f('x', { confirmed: true, uncertain: true })), 'uncertain');
+
+ const uncertain = ui.row({ fkey: 'deadline', label: 'Deadline', hint: 'YYYY-MM-DD', field: f('2026-11-14', { uncertain: true }), disabled: false, onSave: save });
+ assert.match(uncertain, /data-state="uncertain"/);
+ assert.match(uncertain, />Uncertain</);
+ assert.match(uncertain, />.*Confirm</);
+ assert.match(uncertain, /“2026-11-14”/, 'the quote is shown next to the value');
+
+ const ok = ui.row({ fkey: 'sender', label: 'From', hint: '', field: f('Thames Water', { confirmed: true }), disabled: false, onSave: save });
+ assert.match(ok, />Confirmed</);
+ assert.doesNotMatch(ok, />Uncertain</);
+ assert.doesNotMatch(ok, /> Confirm</, 'a confirmed field offers no Confirm');
+ assert.match(ok, /Edit/);
+ assert.match(ok, /Clear/);
+
+ const none = ui.row({ fkey: 'reply_to', label: 'Reply to', hint: '', field: null, disabled: false, onSave: save });
+ assert.match(none, /Not found in the letter/);
+ assert.match(none, /Add/);
+ assert.doesNotMatch(none, /Clear/);
+
+ const noQuote = ui.row({ fkey: 'sender', label: 'From', hint: '', field: { value: 'ACME', quote: '', uncertain: true, confirmed: false }, disabled: false, onSave: save });
+ assert.match(noQuote, /No matching words were found in the letter/);
+});
+
+test('the PATCH bodies match the API: {} confirms, {value} sets, null clears, lists go whole', () => {
+ assert.deepEqual(m.confirmBody('deadline'), { deadline: {} });
+ assert.deepEqual(m.setBody('deadline', ' 2026-11-14 '), { deadline: { value: '2026-11-14' } });
+ assert.deepEqual(m.clearBody('sender'), { sender: null });
+ assert.deepEqual(m.listBody('checklist', [{ value: 'Pay', done: true }, { value: 'Call' }]), { checklist: [{ value: 'Pay', done: true }, { value: 'Call', done: false }] });
+ assert.deepEqual(m.listBody('amounts', [{ value: 'GBP 142.60', done: true }]), { amounts: [{ value: 'GBP 142.60' }] }, 'done only on checklist');
+ assert.deepEqual(m.listBody('checklist', [{ value: 'Pay', done: true }], true), { checklist: [{ value: 'Pay', done: true, confirmed: true }] }, 'confirm all / save');
+ assert.deepEqual(m.listBody('references', [{ value: 'TW-1' }], true), { references: [{ value: 'TW-1', confirmed: true }] });
+});
+
+test('a deadline must be a real YYYY-MM-DD date', () => {
+ for (const ok of ['2026-11-14', '2028-02-29', ' 2026-01-01 ']) assert.equal(m.isIsoDate(ok), true, ok);
+ for (const bad of ['14/11/2026', '2026-11-31', '2027-02-29', '2026-1-4', '20261114', '2026-13-01', 'next Friday', '']) assert.equal(m.isIsoDate(bad), false, bad);
+ assert.match(m.fieldValueError('deadline', '14 Nov 2026'), /YYYY-MM-DD/);
+ assert.equal(m.fieldValueError('deadline', '2026-11-14'), null);
+ assert.match(m.fieldValueError('amounts', '142.60'), /currency/);
+ assert.equal(m.fieldValueError('amounts', 'GBP 142.60'), null);
+ assert.equal(m.fieldValueError('amounts', '£142.60'), null);
+ assert.match(m.fieldValueError('sender', ' '), /Clear/);
+ assert.match(m.fieldValueError('sender', 'x'.repeat(501)), /500/);
+
+ // A model's deadline that isn't ISO can't be confirmed as it is: it must be edited first.
+ const html = ui.row({ fkey: 'deadline', label: 'Deadline', hint: 'YYYY-MM-DD', field: f('14 November', { uncertain: true }), disabled: false, onSave: save });
+ assert.match(html, /isn’t a YYYY-MM-DD date yet/);
+ assert.match(html, /<button[^>]*disabled=""[^>]*>[^<]*<svg[^]*?Confirm/);
+ // The edit box says the format.
+ const editing = ui.row({ fkey: 'deadline', label: 'Deadline', hint: 'YYYY-MM-DD', field: f('2026-11-14'), disabled: false, onSave: save, initialEditing: true });
+ assert.match(editing, /placeholder="YYYY-MM-DD"/);
+ assert.match(editing, /Year-month-day, for example 2026-11-14/);
+});
+
+test('reminders wait for a confirmed, certain deadline, then list 7/1/0 days with due or sent', () => {
+ assert.equal(m.reminderGate(null).on, false);
+ assert.match(m.reminderGate(null).text, /No deadline yet/);
+ assert.equal(m.reminderGate(f('2026-11-14')).on, false);
+ assert.match(m.reminderGate(f('2026-11-14')).text, /once you confirm the deadline/);
+ assert.equal(m.reminderGate(f('2026-11-14', { uncertain: true })).on, false);
+ assert.match(m.reminderGate(f('2026-11-14', { uncertain: true })).text, /uncertain, so there are no reminders/);
+ assert.equal(m.reminderGate(f('2026-11-14', { confirmed: true })).on, true);
+
+ const off = ui.reminders({ deadline: f('2026-11-14', { uncertain: true }), reminders: [], closed: false });
+ assert.match(off, /data-reminders="off"/);
+ assert.match(off, /uncertain/);
+
+ const on = ui.reminders({
+ deadline: f('2026-11-14', { confirmed: true }),
+ reminders: [
+ { offset_days: 0, due_at: '2026-11-14T09:00:00Z', fired_at: null },
+ { offset_days: 7, due_at: '2026-11-07T09:00:00Z', fired_at: '2026-11-07T09:02:00Z' },
+ { offset_days: 1, due_at: '2026-11-13T09:00:00Z', fired_at: null },
+ ],
+ closed: false,
+ });
+ assert.match(on, /data-reminders="on"/);
+ const order = ['7 days before', '1 day before', 'On the day'].map((t) => on.indexOf(t));
+ assert.ok(order.every((i) => i > 0) && order[0] < order[1] && order[1] < order[2], 'listed 7, 1, 0');
+ assert.match(on, />Sent /);
+ assert.equal((on.match(/>Due</g) || []).length, 2);
+ assert.match(on, /counts only/);
+
+ assert.match(ui.reminders({ deadline: f('2026-11-14', { confirmed: true }), reminders: [], closed: true }), /closed, so its reminders are off/);
+});
+
+test('lists: amounts with currency, checklist ticks, and saving says it confirms the whole list', () => {
+ const amounts = ui.list({ fkey: 'amounts', label: 'Amounts', hint: 'GBP 142.60', empty: 'No amounts found.', items: [f('GBP 142.60', { uncertain: true })], disabled: false, onSave: save });
+ assert.match(amounts, /GBP 142.60/);
+ assert.match(amounts, />Uncertain</);
+ assert.match(amounts, /Confirm all/);
+
+ const check = ui.list({ fkey: 'checklist', label: 'Checklist', hint: '', empty: '', items: [f('Pay the bill', { done: true, confirmed: true }), f('Send meter reading')], disabled: false, onSave: save });
+ assert.equal((check.match(/type="checkbox"/g) || []).length, 2);
+ assert.match(check, /checked=""[^>]*>[^]*?line-through[^>]*>Pay the bill/);
+ assert.doesNotMatch(check, /Ticking an item also confirms/);
+
+ const editing = ui.list({ fkey: 'references', label: 'References', hint: '', empty: '', items: [f('TW-88213')], disabled: false, onSave: save, initialEditing: true });
+ assert.match(editing, /Saving confirms every entry in this list/);
+ assert.match(ui.list({ fkey: 'references', label: 'References', hint: '', empty: 'No reference numbers found.', items: [], disabled: false, onSave: save }), /No reference numbers found/);
+});
+
+test('reading shows progress and no fields; every status is said honestly', () => {
+ const running = ui.detail(detailProps(view({ title: 'Letter (reading…)' }, { status: 'running', method: null, fields: {} })));
+ assert.match(running, /data-read-status="running"/);
+ assert.match(running, /Reading the letter…/);
+ assert.match(running, /role="progressbar"/);
+ assert.match(running, /fields appear here once the letter has been read/);
+ assert.doesNotMatch(running, /data-field=/);
+ assert.equal(m.stillReading(view({}, { status: 'running' })), true);
+ assert.equal(m.stillReading(view({}, { status: 'read' })), false);
+
+ assert.match(m.readingText(extraction({ method: 'model_vision' })).body, /by your Claude model/);
+ const textOnly = m.readingText(extraction({ status: 'text_only', note: 'no model can read it' }));
+ assert.match(textOnly.title, /Only the PDF text/);
+ assert.match(textOnly.body, /No model can read it\./);
+
+ const unreadable = ui.detail(detailProps(view({}, { status: 'unreadable', method: null, note: 'kwant restarted while reading it', fields: {} })));
+ assert.match(unreadable, /data-read-status="unreadable"/);
+ assert.match(unreadable, /This letter couldn’t be read/);
+ assert.match(unreadable, /kwant restarted while reading it\./);
+ assert.match(unreadable, /Fill in the fields yourself from the pages/);
+ // Still fillable by hand, and the pages are still shown.
+ assert.match(unreadable, /data-field="sender" data-state="empty"/);
+ assert.match(unreadable, /Page 2 of the letter/);
+ // Nothing was read, so no field claims it was "not found" in the letter.
+ assert.doesNotMatch(unreadable, /Not found in the letter|No reference numbers found/);
+ assert.match(unreadable, /Not filled in yet/);
+ assert.match(unreadable, /None added yet/);
+
+ // The server's note already asks for the fields: it isn't said twice.
+ const failed = m.readingText(extraction({ status: 'unreadable', note: 'the model could not read it (the claude command exited with 1): fill in the fields yourself' }));
+ assert.equal(failed.body.match(/fill in the fields/gi).length, 1);
+});
+
+test('the pages sit next to the fields: photos inline, PDFs as a link, plus what kwant read', () => {
+ const html = ui.detail(detailProps(view()));
+ assert.match(html, /<img src="\/api\/attachments\/a2\/content" alt="Page 2 of the letter"/);
+ assert.match(html, /href="\/api\/attachments\/a1\/content"[^>]*>[^]*?Open PDF/);
+ 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/);
+});
+
+test('the draft: a paper letter is copy only; an email has a mailto; nothing is sent either way', () => {
+ const paper = ui.draft({ c: letterCase() });
+ assert.match(paper, /data-draft-channel="letter"/);
+ assert.match(paper, /Reply by post to Thames Water/);
+ assert.match(paper, /Nothing is sent from kwant bots/);
+ assert.match(paper, /print or write it out/);
+ assert.match(paper, /Copy reply/);
+ assert.doesNotMatch(paper, /mailto:|Open in my mail app/);
+
+ const email = ui.draft({
+ c: letterCase({ draft: { ...letterCase().draft, channel: 'email', to: '[email protected]', mailto: 'mailto:[email protected]?subject=Re' } }),
+ });
+ assert.match(email, /Reply by email to [email protected]/);
+ assert.match(email, /href="mailto:[email protected]\?subject=Re"/);
+ assert.match(email, /Open in my mail app/);
+ assert.match(email, /Nothing is sent from kwant bots/);
+
+ // A letter channel never gets a link, even if the server sent one.
+ const odd = ui.draft({ c: letterCase({ draft: { ...letterCase().draft, mailto: 'mailto:[email protected]' } }) });
+ assert.doesNotMatch(odd, /mailto:/);
+});
+
+test('a busy server reads calmly; bad files and counts say what to change', () => {
+ const busy = m.letterErrorText(new m.LooseEndsError('Another letter is being read: try again in a minute.', 409, false, false, 'busy'));
+ assert.equal(busy.calm, true);
+ assert.match(busy.text, /Another letter is being read right now/);
+ assert.doesNotMatch(busy.text, /409|HTTP|error/i);
+ const used = m.letterErrorText(new m.LooseEndsError('A page was already used: upload it again.', 409));
+ assert.equal(used.calm, false);
+ assert.equal(m.letterErrorText(new m.LooseEndsError('Pages must be photos (PNG, JPEG, WebP) or PDFs.', 400)).calm, false);
+
+ const page = (name, type = 'image/png', size = 1000) => ({ name, type, size });
+ assert.equal(m.checkLetterFiles([page('a.png'), page('b.pdf', 'application/pdf'), page('c.jpg', 'image/jpeg'), page('d.webp', 'image/webp')]), null);
+ assert.equal(m.checkLetterFiles([page('scan.PDF', '')]), null, 'no MIME: the extension decides');
+ assert.match(m.checkLetterFiles([]), /Add a photo or a PDF/);
+ assert.match(m.checkLetterFiles(Array.from({ length: 6 }, (_, i) => page(`${i}.png`))), /at most 5 pages\. You picked 6: remove 1/);
+ assert.match(m.checkLetterFiles([page('notes.txt', 'text/plain')]), /notes\.txt isn’t a photo or a PDF/);
+ assert.match(m.checkLetterFiles([page('anim.gif', 'image/gif')]), /PNG, JPEG, WebP or PDF/);
+ assert.match(m.checkLetterFiles([page('huge.jpg', 'image/jpeg', 25 * 1024 * 1024)]), /too big/);
+ assert.match(m.checkLetterFiles([page('empty.png', 'image/png', 0)]), /empty/);
+
+ const form = ui.add({ onCreated: noop, onCancel: noop, initialCamera: true });
+ assert.match(form, /Take a photo/);
+ assert.match(form, /capture="environment"/);
+ assert.match(form, /accept="image\/png,image\/jpeg,image\/webp,application\/pdf/);
+ assert.match(form, /Nothing is sent to anyone/);
+ assert.match(form, /<button type="submit" disabled=""/, 'nothing to read yet');
+ assert.doesNotMatch(ui.add({ onCreated: noop, onCancel: noop, initialCamera: false }), /Take a photo/);
+});
+
+test('delete asks first; a 409 while reading is calm and nothing is half-deleted', () => {
+ const html = ui.detail(detailProps(view(), { initialConfirmDelete: true }));
+ assert.match(html, /data-confirm-delete/);
+ assert.match(html, /can’t be undone/);
+ assert.match(html, /Delete it/);
+ assert.match(html, /Keep it/);
+ const reading = m.deleteErrorText(new m.LooseEndsError('The letter is still being read.', 409));
+ assert.equal(reading.calm, true);
+ assert.match(reading.text, /still being read/);
+ assert.match(m.deleteErrorText(new Error('Network down.')).text, /Nothing was deleted/);
+});
+
+test('done and reopen: an open letter offers Mark done, a closed one Reopen with reminders off', () => {
+ const open = ui.detail(detailProps(view()));
+ assert.match(open, /Mark done/);
+ assert.doesNotMatch(open, /Reopen/);
+ const done = ui.detail(detailProps({ ...view({ status: 'closed' }), reminders: [] }));
+ assert.match(done, /Reopen/);
+ assert.doesNotMatch(done, /Mark done/);
+ assert.match(done, /closed, so its reminders are off/);
+ assert.doesNotMatch(done, /data-draft-channel/, 'no reply draft on a closed letter');
+});
+
+test('a letter card in the Loose ends list says Letter and opens the letter', () => {
+ const html = ui.card({ c: letterCase(), busy: false, onAction: noop, onOpenLetter: noop });
+ assert.match(html, />Letter</);
+ assert.match(html, /Letter to deal with/);
+ assert.match(html, /data-open-letter/);
+ assert.doesNotMatch(ui.card({ c: { ...letterCase(), source: 'imap', kind: 'awaiting_reply' }, busy: false, onAction: noop, onOpenLetter: noop }), /data-open-letter/);
+});