Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): stop the scroll brake pinning a busy full-screen pane
Ruben Lütke64eaa156db34
diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsxindex 001dcbf181..5ff21d13e4 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.test.tsx@@ -3,7 +3,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Terminal } from "@xterm/xterm";import { PaneScrollbar } from "./PaneScrollbar";-import { LINES_PER_NOTCH } from "./scrollbarModel";+import { LINES_PER_NOTCH, SETTLE_MS } from "./scrollbarModel";const REGION = { top: 0, bottom: 300, left: 0, right: 400 };const TRACK_PX = 300;@@ -366,6 +366,55 @@ describe("PaneScrollbar", () => {);});+ /*+ * The pinned-pane deadlock, end to end: the brake engages MID-DRAG (the+ * CLI stopped answering), and the rest of the drag must still send one+ * probe notch per step instead of going dead — the escape hatch that lets+ * a wrongly-braked pane free itself.+ */+ it("keeps probing upward while the brake holds", async () => {+ let clock = 1_000_000;+ vi.spyOn(Date, "now").mockImplementation(() => clock);+ const { state, term, fire } = appTerminal(24);+ state.lines = Array.from({ length: 24 }, (_, i) => `transcript row ${i}`);+ state.lines[20] = " 12 Jump to bottom (ctrl+End) ↓";+ render(<Harness term={term} />);+ reachThePane();++ // Prove movement once — a brake without proven movement must not engage.+ // Then WAIT for the frame that carries the sync: the change must be on+ // record before the drag below piles up unconfirmed notches.+ state.lines[0] = "transcript moved";+ fire("render");+ await act(+ () =>+ new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+ expect(bar()!.dataset.kind).toBe("travel");++ // Grab the thumb and pull: the burst is relayed, the screen stays still.+ const seen = watchScreen();+ fireEvent.pointerDown(thumb(), { clientY: 250, pointerId: 1 });+ dragTo(thumb(), 220);+ expect(seen.length).toBeGreaterThan(0);++ // The pty stays silent past the settle window: the brake engages.+ clock += SETTLE_MS + 100;+ fire("render");+ await waitFor(() =>+ expect(bar()!.getAttribute("aria-valuemax")).toBe("3"),+ );++ // Further pulling probes with exactly one notch per step, never a burst.+ const before = seen.length;+ dragTo(thumb(), 100);+ fireEvent.pointerUp(thumb(), { pointerId: 1 });+ expect(seen.length - before).toBe(1);+ expect(seen[seen.length - 1]).toBe(-1);+ });+it("starts a fresh terminal's count from zero", async () => {const first = appTerminal(24).term;const { rerender } = render(<Harness term={first} epoch={1} />);diff --git a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsxindex 7c30784931..5492ed7bd2 100644--- a/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/PaneScrollbar.tsx@@ -359,9 +359,15 @@ export function PaneScrollbar({const term = getTerminal();if (!term || lines === 0) return;if (appOwnsScreen(term)) {- // Nothing above the top: while the brake holds, an up-notch would be- // ignored by the application and only pollute its pty.- if (lines > 0 && travelRef.current.saturated) return;+ // While the brake holds, an up-drag relays ONE probe notch instead+ // of a burst. At a genuine top it is ignored and costs nothing; at a+ // false one (a CLI that was merely busy) it moves the screen, the+ // fingerprint changes, and the brake releases itself — the escape+ // hatch that keeps a wrong verdict from pinning the pane for good.+ if (lines > 0 && travelRef.current.saturated) {+ relayNotches(hostRef.current, -1, 1);+ return;+ }const notches = notchesFor(lines);relayNotches(hostRef.current,diff --git a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.ts b/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.tsindex d81cde3ff6..0ffd76004c 100644--- a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.test.ts@@ -195,7 +195,7 @@ describe("screenTravel", () => {it("un-counts ups the application ignored at the top, and measures it", () => {// The user's other reported bug: scrolling past a top nobody can see.- const t: Travel = { ...seen(90), pendingUp: 30, lastUpAt: 0 };+ const t: Travel = { ...seen(90), pendingUp: 30, lastUpAt: 0, moved: true };const next = screenTravel(t,{ markerRow: 22, fingerprint: "same" },@@ -207,7 +207,7 @@ describe("screenTravel", () => {});it("waits for the pty before judging an unmoved screen", () => {- const t: Travel = { ...seen(90), pendingUp: 30, lastUpAt: 0 };+ const t: Travel = { ...seen(90), pendingUp: 30, lastUpAt: 0, moved: true };const next = screenTravel(t,{ markerRow: 22, fingerprint: "same" },@@ -217,6 +217,52 @@ describe("screenTravel", () => {expect(next.saturated).toBe(false);});+ it("never calls an episode that has not moved a top", () => {+ // The pinned-thumb deadlock: a busy CLI leaves the screen unchanged far+ // past the settle window without a single notch having reached the top.+ // The ups still leave the count, but no brake and no false ceiling.+ const t: Travel = { ...seen(30), pendingUp: 30, lastUpAt: 0 };+ const next = screenTravel(+ t,+ { markerRow: 22, fingerprint: "same" },+ SETTLE_MS,+ );+ expect(next.travelled).toBe(3);+ expect(next.saturated).toBe(false);+ expect(next.ceiling).toBeNull();+ });++ it("a fingerprint CHANGE proves movement; the first look only records", () => {+ const first = screenTravel(+ freshTravel(),+ { markerRow: 22, fingerprint: "a" },+ 0,+ );+ expect(first.moved).toBe(false);+ const second = screenTravel(+ first,+ { markerRow: 22, fingerprint: "b" },+ 1,+ );+ expect(second.moved).toBe(true);+ });++ it("closing the episode at the live end demands fresh proof next time", () => {+ const t: Travel = { ...seen(60), moved: true };+ const home = screenTravel(t, { markerRow: -1, fingerprint: "" }, 0);+ expect(home.moved).toBe(false);+ });++ it("keeps the ceiling graspable however small the measured top", () => {+ const t: Travel = { ...seen(3), pendingUp: 3, lastUpAt: 0, moved: true };+ const next = screenTravel(+ t,+ { markerRow: 22, fingerprint: "same" },+ SETTLE_MS,+ );+ expect(next.ceiling).toBeGreaterThanOrEqual(LINES_PER_NOTCH);+ });+it("floors the count while the overlay says the view is away", () => {const t = screenTravel({ ...seen(0), fingerprint: "a" },diff --git a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.ts b/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.tsindex 5b668c1c93..c703984c58 100644--- a/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.ts+++ b/jarvis/ui/web/frontend/src/components/agentic/scrollbarModel.ts@@ -139,9 +139,12 @@ export function travelView(/*** How long the pty gets to answer an up-notch before an unchanged screen* counts as proof the notch fell off the top. The CLI answers a notch in- * 1–30 ms (measured); the margin covers the socket and a busy render loop.+ * 1–30 ms when idle (measured), but a CLI mid-task plus a loaded render+ * loop can stretch far past that — and a wrong verdict here once pinned a+ * pane's thumb to a false top (2026-07-28). Hence the generous window AND+ * the `moved` requirement in {@link screenTravel}.*/-export const SETTLE_MS = 350;+export const SETTLE_MS = 500;/*** Overlays a full-screen CLI paints while its view is away from the live@@ -167,6 +170,17 @@ export interface Travel {fingerprint: string | null;/** Ups are known to be falling off the top right now. */saturated: boolean;+ /**+ * The transcript has been SEEN to move during this scroll-back episode.+ *+ * The brake's precondition, and the fix for the pinned-thumb deadlock: a+ * busy CLI can leave the screen unchanged long past {@link SETTLE_MS}+ * without a single notch having fallen off the top. Genuinely reaching+ * the top requires having scrolled through content first, which repaints+ * — so an episode that never moved proves latency, not a boundary, and+ * must neither saturate nor measure a ceiling.+ */+ moved: boolean;}export function freshTravel(): Travel {@@ -178,6 +192,7 @@ export function freshTravel(): Travel {lastUpAt: 0,fingerprint: null,saturated: false,+ moved: false,};}@@ -228,12 +243,14 @@ export function screenTravel(if (glance.markerRow < 0) {// No overlay. From an application known to paint one, that is proof of- // the live end — the anchor that ends "thumb stuck mid-track".+ // the live end — the anchor that ends "thumb stuck mid-track". It also+ // closes the scroll-back episode: the next one proves movement afresh.if (!travel.markerSeen) return travel;if (travel.travelled === 0 &&travel.pendingUp === 0 &&- !travel.saturated+ !travel.saturated &&+ !travel.moved) {return travel;}@@ -243,6 +260,7 @@ export function screenTravel(pendingUp: 0,saturated: false,fingerprint: null,+ moved: false,};}@@ -251,24 +269,31 @@ export function screenTravel(: { ...travel, markerSeen: true };if (next.fingerprint !== glance.fingerprint) {- // The transcript moved: whatever was pending has been answered.+ // The transcript moved: whatever was pending has been answered. Only a+ // CHANGE proves movement — the episode's first look merely records.next = {...next,fingerprint: glance.fingerprint,pendingUp: 0,saturated: false,+ moved: next.moved || next.fingerprint !== null,};} else if (next.pendingUp > 0 && now - next.lastUpAt >= SETTLE_MS) {- // Counted ups, an answered pty, an unmoved screen: those notches fell- // off the top. Un-count them and remember where the top IS.+ // Counted ups, an answered pty, an unmoved screen: those notches did+ // nothing, so they leave the count either way. But they only prove a+ // TOP when this episode has scrolled before — an episode that never+ // moved is a busy CLI, and a ceiling measured from it pinned a pane's+ // thumb to a false top with every further relay refused (2026-07-28).const travelled = Math.max(0, next.travelled - next.pendingUp);- next = {- ...next,- travelled,- pendingUp: 0,- saturated: true,- ceiling: travelled,- };+ next = next.moved+ ? {+ ...next,+ travelled,+ pendingUp: 0,+ saturated: true,+ ceiling: Math.max(travelled, LINES_PER_NOTCH),+ }+ : { ...next, travelled, pendingUp: 0 };}// The overlay itself says the view is away from the live end — a count ofdiff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/MergeQueuePanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/MergeQueuePanel.test.tsxnew file mode 100644index 0000000000..645b4a5b8e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/MergeQueuePanel.test.tsx@@ -0,0 +1,209 @@+/**+ * MergeQueuePanel tests — the one place a human decides an identity.+ *+ * The load-bearing property is the ASYMMETRY between the two answers. "One+ * person" merges and can be undone; "two people" is permanent and outranks+ * every later piece of evidence. A UI that treats them as two equal buttons+ * turns a stray click into an unfixable statement about someone's identity,+ * so the arming step is tested as hard as the happy path.+ *+ * The second property is honesty: the store's refusal sentence ("undo merge+ * 12 first") is the entire value of a 409 and must reach the screen intact,+ * never re-worded and never swallowed.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { MergeQueuePanel } from "@/components/ultrawiki/MergeQueuePanel";+import type { UltraWikiMergeProposal } from "@/lib/ultrawikiIdentityApi";++const PROPOSAL: UltraWikiMergeProposal = {+ id: 7,+ status: "pending",+ score: 0.8724,+ evidence: [+ { tier: "probable", kind: "name_similar", value: "R. Vasquez", score: 0.87 },+ ],+ created_at: "2026-07-20T10:00:00Z",+ updated_at: "2026-07-20T10:00:00Z",+ decided_at: null,+ decided_by: null,+ left: { id: 11, kind: "person", display_name: "Rita Vasquez" },+ right: { id: 12, kind: "person", display_name: "R. Vasquez" },+};++function makeClient(): QueryClient {+ return new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+}++interface Call {+ url: string;+ method: string;+}++function installFetch(+ handler: (url: string, method: string) => { status?: number; body: unknown },+): Call[] {+ const calls: Call[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ calls.push({ url, method });+ const answer = handler(url, method);+ const status = answer.status ?? 200;+ return {+ ok: status < 400,+ status,+ json: async () => answer.body,+ } as unknown as Response;+ }),+ );+ return calls;+}++function renderQueue(+ proposals: UltraWikiMergeProposal[] = [PROPOSAL],+ onOpenPerson?: (id: number) => void,+) {+ return render(+ <QueryClientProvider client={makeClient()}>+ <MergeQueuePanel proposals={proposals} onOpenPerson={onOpenPerson} />+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("asking the question", () => {+ it("names both sides and how alike they are", () => {+ renderQueue();++ const card = screen.getByTestId("merge-proposal-7");+ expect(card.textContent).toContain("Rita Vasquez");+ expect(card.textContent).toContain("R. Vasquez");+ // 0.8724 is a matcher's number, not a human's.+ expect(screen.getByTestId("merge-score-7").textContent).toContain("87%");+ });++ it("explains the evidence in words, never as the matcher's token", () => {+ renderQueue();++ const evidence = screen.getByTestId("merge-evidence-7");+ expect(evidence.textContent).toContain("Similar name");+ expect(evidence.textContent).not.toContain("name_similar");+ });++ it("says so when nothing is waiting", () => {+ renderQueue([]);+ expect(screen.getByTestId("identity-queue-empty")).toBeTruthy();+ });++ it("offers each side as a way into the full profile", () => {+ const onOpenPerson = vi.fn();+ renderQueue([PROPOSAL], onOpenPerson);++ fireEvent.click(screen.getByTestId("merge-side-12"));+ expect(onOpenPerson).toHaveBeenCalledWith(12);+ });+});++describe("saying yes", () => {+ it("merges on one click and points at the undo", async () => {+ const calls = installFetch(() => ({+ body: { ok: true, queue_id: 7, merge_id: 42 },+ }));+ renderQueue();++ fireEvent.click(screen.getByTestId("merge-confirm-7"));++ await waitFor(() => {+ expect(screen.getByTestId("merge-confirmed-7")).toBeTruthy();+ });+ expect(calls).toEqual([+ { url: "/api/ultrawiki/identity/queue/7/confirm", method: "POST" },+ ]);+ expect(screen.getByTestId("merge-confirmed-7").textContent).toContain("undo");+ });++ it("does not promise an undo that does not exist", async () => {+ // merge_id 0 = the pair had already become one entity by other evidence.+ // There is no merge row, so "you can undo this" would be a lie.+ installFetch(() => ({ body: { ok: true, queue_id: 7, merge_id: 0 } }));+ renderQueue();++ fireEvent.click(screen.getByTestId("merge-confirm-7"));++ await waitFor(() => {+ expect(screen.getByTestId("merge-confirmed-7").textContent).toContain(+ "already one person",+ );+ });+ });+});++describe("saying no", () => {+ it("does not reject on the first click — it warns first", () => {+ const calls = installFetch(() => ({ body: { ok: true } }));+ renderQueue();++ fireEvent.click(screen.getByTestId("merge-reject-7"));++ expect(screen.getByTestId("merge-reject-armed-7")).toBeTruthy();+ expect(screen.getByTestId("merge-reject-armed-7").textContent).toContain(+ "permanent",+ );+ expect(calls).toEqual([]);+ });++ it("rejects once the warning has been read and confirmed", async () => {+ const calls = installFetch(() => ({+ body: { ok: true, queue_id: 7, status: "rejected" },+ }));+ renderQueue();++ fireEvent.click(screen.getByTestId("merge-reject-7"));+ fireEvent.click(screen.getByTestId("merge-reject-confirm-7"));++ await waitFor(() => {+ expect(calls).toEqual([+ { url: "/api/ultrawiki/identity/queue/7/reject", method: "POST" },+ ]);+ });+ });++ it("lets the user back out of the armed state without deciding", () => {+ const calls = installFetch(() => ({ body: { ok: true } }));+ renderQueue();++ fireEvent.click(screen.getByTestId("merge-reject-7"));+ fireEvent.click(screen.getByTestId("merge-reject-cancel-7"));++ expect(screen.queryByTestId("merge-reject-armed-7")).toBeNull();+ expect(screen.getByTestId("merge-confirm-7")).toBeTruthy();+ expect(calls).toEqual([]);+ });+});++describe("a refusal from the store", () => {+ it("prints the reason it was given, word for word", async () => {+ installFetch(() => ({+ status: 409,+ body: { detail: "queue row 7 was already decided" },+ }));+ renderQueue();++ fireEvent.click(screen.getByTestId("merge-confirm-7"));++ const error = await screen.findByTestId("merge-error-7");+ expect(error.textContent).toContain("queue row 7 was already decided");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/MergeQueuePanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/MergeQueuePanel.tsxnew file mode 100644index 0000000000..38784ffb09--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/MergeQueuePanel.tsx@@ -0,0 +1,326 @@+/**+ * "Are these the same person?" — the one question the identity layer refuses+ * to answer on its own.+ *+ * A shared e-mail, phone number or address-book entry is proof, and the layer+ * merges on it silently. A similar NAME is not: "Ruben Lütke" and "R. Lütke"+ * are the same person often enough to be worth asking about and different+ * often enough that guessing corrupts the knowledge base. Everything in this+ * queue is that second case, and nothing in it has been merged.+ *+ * The two answers are deliberately NOT symmetrical, because the actions are+ * not:+ *+ * - "one person" merges, and the merge is reversible — one click, and the+ * answer even hands back the undo handle.+ * - "two people" is PERMANENT. There is no un-reject route by design: a+ * rejected pair is never proposed again, which is exactly what keeps the+ * queue from asking the same settled question forever. So it arms first and+ * says what it costs, rather than turning one stray click into a decision+ * that outranks every later piece of evidence.+ *+ * A refusal from the store (409) is printed verbatim on the card it came+ * from: "undo merge 12 first" is the entire value of that answer, and a+ * re-worded version of it would be a second opinion on a question the store+ * already answered.+ */+import { useState } from "react";+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { Check, Loader2, Users, X } from "lucide-react";++import { cn } from "@/lib/utils";+import { useT } from "@/i18n";+import {+ confirmIdentityMerge,+ evidenceParts,+ identityErrorMessage,+ rejectIdentityMerge,+ scorePercent,+ tierKey,+ type UltraWikiMatchEvidence,+ type UltraWikiMergeProposal,+} from "@/lib/ultrawikiIdentityApi";++/**+ * Every identity query hangs under this prefix, so one decision can+ * invalidate the People list, the open profile and the queue in a single+ * call — a confirmed merge changes all three at once, and a screen where two+ * of them agree and the third does not is worse than a slow refresh.+ */+export const IDENTITY_QUERY_KEY = ["ultrawiki", "identity"] as const;++export interface MergeQueuePanelProps {+ proposals: UltraWikiMergeProposal[];+ /** Jump to one side of a pair — deciding often needs the full profile. */+ onOpenPerson?: (entityId: number) => void;+ /** Rendered when the queue is empty; the caller words its own emptiness. */+ emptyMessage?: string;+ className?: string;+}++export function MergeQueuePanel({+ proposals,+ onOpenPerson,+ emptyMessage,+ className,+}: MergeQueuePanelProps): JSX.Element {+ const t = useT();++ if (proposals.length === 0) {+ return (+ <div+ data-testid="identity-queue-empty"+ className={cn(+ "rounded-xl border border-dashed border-border/70 bg-card/30 p-4 text-xs text-muted-foreground",+ className,+ )}+ >+ {emptyMessage ?? t("ultrawiki.people.queue_empty")}+ </div>+ );+ }++ return (+ <ul+ data-testid="identity-queue"+ className={cn("space-y-2.5", className)}+ >+ {proposals.map((proposal) => (+ <MergeProposalCard+ key={proposal.id}+ proposal={proposal}+ onOpenPerson={onOpenPerson}+ />+ ))}+ </ul>+ );+}++export interface MergeProposalCardProps {+ proposal: UltraWikiMergeProposal;+ onOpenPerson?: (entityId: number) => void;+}++export function MergeProposalCard({+ proposal,+ onOpenPerson,+}: MergeProposalCardProps): JSX.Element {+ const t = useT();+ const queryClient = useQueryClient();+ // The reject button arms before it fires. Not confirmation theatre: this is+ // the only identity action with no way back.+ const [arming, setArming] = useState(false);++ const invalidate = () =>+ queryClient.invalidateQueries({ queryKey: IDENTITY_QUERY_KEY });++ const confirmMutation = useMutation({+ mutationFn: () => confirmIdentityMerge(proposal.id),+ onSuccess: () => void invalidate(),+ });++ const rejectMutation = useMutation({+ mutationFn: () => rejectIdentityMerge(proposal.id),+ onSuccess: () => {+ setArming(false);+ void invalidate();+ },+ });++ const busy = confirmMutation.isPending || rejectMutation.isPending;+ const failure = confirmMutation.error ?? rejectMutation.error;+ const percent = scorePercent(proposal.score);++ return (+ <li+ data-testid={`merge-proposal-${proposal.id}`}+ data-score={String(percent)}+ className="rounded-xl border border-border/70 bg-card/40 px-3.5 py-3"+ >+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <Users className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <span className="text-[11px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("ultrawiki.people.queue_question")}+ </span>+ <span className="flex-1" />+ <span+ data-testid={`merge-score-${proposal.id}`}+ className="shrink-0 rounded-full border border-border px-2 py-0.5 text-[10px] tabular-nums text-muted-foreground"+ >+ {t("ultrawiki.people.match_strength").replace("{0}", String(percent))}+ </span>+ </div>++ <div className="mt-2 flex flex-wrap items-center gap-2">+ <ProposalSide side={proposal.left} onOpenPerson={onOpenPerson} />+ <span className="text-xs text-muted-foreground" aria-hidden>+ ↔+ </span>+ <ProposalSide side={proposal.right} onOpenPerson={onOpenPerson} />+ </div>++ <EvidenceList evidence={proposal.evidence} proposalId={proposal.id} />++ {arming ? (+ <div+ data-testid={`merge-reject-armed-${proposal.id}`}+ className="mt-2.5 rounded-lg border border-destructive/40 bg-destructive/5 px-2.5 py-2"+ >+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {t("ultrawiki.people.reject_warning")}+ </p>+ <div className="mt-1.5 flex flex-wrap gap-1.5">+ <button+ type="button"+ data-testid={`merge-reject-confirm-${proposal.id}`}+ onClick={() => rejectMutation.mutate()}+ disabled={busy}+ className="inline-flex items-center gap-1 rounded-md border border-destructive/50 px-2.5 py-1 text-[11px] text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-60"+ >+ {rejectMutation.isPending && (+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ )}+ {t("ultrawiki.people.reject_final")}+ </button>+ <button+ type="button"+ data-testid={`merge-reject-cancel-${proposal.id}`}+ onClick={() => setArming(false)}+ disabled={busy}+ className="rounded-md border border-border px-2.5 py-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-60"+ >+ {t("ultrawiki.people.cancel")}+ </button>+ </div>+ </div>+ ) : (+ <div className="mt-2.5 flex flex-wrap gap-1.5">+ <button+ type="button"+ data-testid={`merge-confirm-${proposal.id}`}+ onClick={() => confirmMutation.mutate()}+ disabled={busy}+ className="inline-flex items-center gap-1 rounded-md border border-primary/50 bg-primary/10 px-2.5 py-1 text-[11px] text-foreground transition-colors hover:bg-primary/20 disabled:opacity-60"+ >+ {confirmMutation.isPending ? (+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ ) : (+ <Check className="h-3 w-3" aria-hidden />+ )}+ {t("ultrawiki.people.same_person")}+ </button>+ <button+ type="button"+ data-testid={`merge-reject-${proposal.id}`}+ onClick={() => setArming(true)}+ disabled={busy}+ className="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-60"+ >+ <X className="h-3 w-3" aria-hidden />+ {t("ultrawiki.people.different_people")}+ </button>+ </div>+ )}++ {confirmMutation.data && (+ <p+ data-testid={`merge-confirmed-${proposal.id}`}+ className="mt-1.5 text-[11px] text-muted-foreground"+ >+ {/* merge_id 0 = the pair had already become one entity by other+ evidence, so there is nothing to reverse and saying "undo it+ under the profile" would be a lie. */}+ {confirmMutation.data.merge_id > 0+ ? t("ultrawiki.people.merged_undoable")+ : t("ultrawiki.people.merged_already")}+ </p>+ )}++ {failure && (+ <p+ role="alert"+ data-testid={`merge-error-${proposal.id}`}+ className="mt-1.5 text-[11px] text-destructive"+ >+ {t("ultrawiki.people.action_failed").replace(+ "{0}",+ identityErrorMessage(failure),+ )}+ </p>+ )}+ </li>+ );+}++function ProposalSide({+ side,+ onOpenPerson,+}: {+ side: UltraWikiMergeProposal["left"];+ onOpenPerson?: (entityId: number) => void;+}): JSX.Element {+ const label = side.display_name || String(side.id);+ const className =+ "min-w-0 max-w-full truncate rounded-lg border border-border bg-background/60 px-2.5 py-1 text-xs text-foreground";+ if (!onOpenPerson) {+ return (+ <span data-testid={`merge-side-${side.id}`} className={className}>+ {label}+ </span>+ );+ }+ return (+ <button+ type="button"+ data-testid={`merge-side-${side.id}`}+ onClick={() => onOpenPerson(side.id)}+ className={cn(className, "transition-colors hover:border-primary/50")}+ >+ {label}+ </button>+ );+}++/**+ * Why the layer asked. Rendered as a sentence, never as the raw token: the+ * reader is not the person who wrote the matcher, and "name_similar" tells+ * them nothing about whether to say yes.+ */+function EvidenceList({+ evidence,+ proposalId,+}: {+ evidence: UltraWikiMatchEvidence[];+ proposalId: number;+}): JSX.Element | null {+ const t = useT();+ if (!evidence || evidence.length === 0) return null;+ return (+ <ul+ data-testid={`merge-evidence-${proposalId}`}+ className="mt-2 space-y-0.5"+ >+ {evidence.map((item, index) => {+ const parts = evidenceParts(item.kind);+ const noun = parts.nounKey ? t(parts.nounKey) : parts.raw;+ const tier = tierKey(item.tier);+ return (+ <li+ key={`${item.kind}-${item.value}-${index}`}+ className="text-[11px] leading-relaxed text-muted-foreground"+ >+ <span className="text-foreground/80">+ {t(parts.phraseKey).replace("{0}", noun)}+ </span>+ {item.value && <span>: {item.value}</span>}+ {tier && (+ <span className="ml-1.5 opacity-60">({t(tier)})</span>+ )}+ </li>+ );+ })}+ </ul>+ );+}++export default MergeQueuePanel;diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/PeoplePanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/PeoplePanel.test.tsxnew file mode 100644index 0000000000..7b1cb823e3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/PeoplePanel.test.tsx@@ -0,0 +1,522 @@+/**+ * PeoplePanel tests — the corpus seen through people.+ *+ * Three properties carry this view, and each of them once had a plausible+ * wrong implementation:+ *+ * 1. A profile is TWO halves. The standing facts (identifiers) and the things+ * that happened (events) come from different layers and different+ * requests, so a corpus with no event extraction must still render a+ * working profile instead of an error page.+ * 2. Typing is instant and local, but a search for an e-mail address cannot+ * be — identifiers are not in the list payload. The server is asked only+ * once the local list has genuinely nothing.+ * 3. A merge that still stands can be undone from the profile; one that was+ * already undone must not offer the button, and a refusal to undo is+ * printed as the store worded it.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { PeoplePanel } from "@/components/ultrawiki/PeoplePanel";++const COUNTS = {+ entities: 3,+ people: 2,+ identifiers: 5,+ pending_confirmations: 1,+ merges: 1,+};++const PEOPLE = [+ {+ id: 11,+ kind: "person",+ display_name: "Rita Vasquez",+ source_ref: "contacts:rita",+ identifier_count: 4,+ created_at: "2026-07-01T10:00:00Z",+ updated_at: "2026-07-02T10:00:00Z",+ },+ {+ id: 21,+ kind: "person",+ display_name: "Tomas Bauer",+ source_ref: "",+ identifier_count: 1,+ created_at: "2026-07-03T10:00:00Z",+ updated_at: "2026-07-03T10:00:00Z",+ },+];++const PROPOSAL = {+ id: 7,+ status: "pending",+ score: 0.87,+ evidence: [+ { tier: "probable", kind: "name_similar", value: "R. Vasquez", score: 0.87 },+ ],+ created_at: "2026-07-20T10:00:00Z",+ updated_at: "2026-07-20T10:00:00Z",+ decided_at: null,+ decided_by: null,+ left: { id: 11, kind: "person", display_name: "Rita Vasquez" },+ right: { id: 12, kind: "person", display_name: "R. Vasquez" },+};++const RITA = {+ id: 11,+ kind: "person",+ display_name: "Rita Vasquez",+ canonical_key: "rita vasquez",+ merged_into: null,+ source_ref: "contacts:rita",+ profile: {},+ created_at: "2026-07-01T10:00:00Z",+ updated_at: "2026-07-02T10:00:00Z",+ identifiers: [+ {+ id: 1,+ kind: "email",+ value: "[email protected]",+ display_value: "[email protected]",+ source_ref: "contacts:rita",+ },+ {+ id: 2,+ kind: "name",+ value: "rita vasquez",+ display_value: "Rita Vasquez",+ source_ref: "",+ },+ ],+ emails: ["[email protected]"],+ phones: [],+ handles: [],+ names: ["Rita Vasquez"],+ contacts: [],+ merged_from: [{ id: 31, display_name: "Rita V." }],+ merges: [+ {+ id: 5,+ winner_id: 11,+ loser_id: 31,+ tier: "deterministic",+ reason: "same e-mail",+ evidence: [+ {+ tier: "deterministic",+ kind: "email_exact",+ value: "[email protected]",+ score: 1,+ },+ ],+ queue_id: null,+ merged_at: "2026-07-02T10:00:00Z",+ undone_at: null,+ },+ {+ id: 4,+ winner_id: 11,+ loser_id: 41,+ tier: "probable",+ reason: "similar name",+ evidence: [],+ queue_id: 3,+ merged_at: "2026-07-01T12:00:00Z",+ undone_at: "2026-07-01T13:00:00Z",+ },+ ],+ pending_proposals: [PROPOSAL],+ requested_id: 11,+};++const EVENTS = [+ {+ id: 91,+ item_id: 501,+ kind: "meal",+ title: "Dinner with Rita",+ summary: "At the harbour place.",+ occurred_at: "2026-07-04T19:00:00Z",+ occurred_end: "2026-07-04T21:00:00Z",+ occurred_precision: "day",+ time_anchor: "stated",+ recorded_at: "2026-07-04T22:00:00Z",+ date_label: "4 July 2026",+ place: "Hamburg",+ place_entity_id: null,+ confidence: 0.9,+ source_id: "src1",+ permalink: "app://evidence/501",+ item_title: "Chat log",+ participants: [{ entity_id: 11, display_name: "Rita Vasquez" }],+ },+];++interface Call {+ url: string;+ method: string;+}++type Answer = { status?: number; body: unknown };+type Route = Answer | ((url: string) => Answer);++function makeClient(): QueryClient {+ return new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+}++/**+ * Route by `METHOD /path`, longest key first — `/identity/people/11` and+ * `/identity/people` are otherwise the same prefix, and a shorter accidental+ * match would answer a profile request with the list.+ */+function installRoutes(overrides: Record<string, Route> = {}): Call[] {+ const routes: Record<string, Route> = {+ "GET /api/ultrawiki/identity/people": {+ body: {+ ok: true,+ people: PEOPLE,+ query: "",+ limit: 500,+ offset: 0,+ counts: COUNTS,+ },+ },+ "GET /api/ultrawiki/identity/queue": {+ body: {+ ok: true,+ proposals: [PROPOSAL],+ status: "pending",+ limit: 100,+ counts: COUNTS,+ },+ },+ "GET /api/ultrawiki/identity/people/11": {+ body: { ok: true, person: RITA, forwarded: false },+ },+ "GET /api/ultrawiki/events": {+ body: { events: EVENTS, total: EVENTS.length, limit: 25, offset: 0 },+ },+ ...overrides,+ };+ const calls: Call[] = [];+ const keys = Object.keys(routes).sort((a, b) => b.length - a.length);+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ calls.push({ url, method });+ const key = keys.find((candidate) =>+ `${method} ${url}`.startsWith(candidate),+ );+ if (!key) throw new Error(`unrouted fetch: ${method} ${url}`);+ const route = routes[key];+ const answer = typeof route === "function" ? route(url) : route;+ const status = answer.status ?? 200;+ return {+ ok: status < 400,+ status,+ json: async () => answer.body,+ } as unknown as Response;+ }),+ );+ return calls;+}++function renderPanel(onOpenSources = () => {}) {+ return render(+ <QueryClientProvider client={makeClient()}>+ <PeoplePanel onOpenSources={onOpenSources} />+ </QueryClientProvider>,+ );+}++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++describe("the list", () => {+ it("lists the people the knowledge base has identified", async () => {+ installRoutes();+ renderPanel();++ expect(await screen.findByTestId("person-row-11")).toBeTruthy();+ expect(screen.getByTestId("person-row-21").textContent).toContain(+ "Tomas Bauer",+ );+ });++ it("filters as the user types, without asking the server", async () => {+ const calls = installRoutes();+ renderPanel();+ await screen.findByTestId("person-row-11");+ const before = calls.length;++ fireEvent.change(screen.getByTestId("people-search"), {+ target: { value: "tom" },+ });++ await waitFor(() => {+ expect(screen.queryByTestId("person-row-11")).toBeNull();+ });+ expect(screen.getByTestId("person-row-21")).toBeTruthy();+ expect(calls.length).toBe(before);+ });++ it("asks the server only when no name matches — that is where e-mails live", async () => {+ const calls = installRoutes({+ "GET /api/ultrawiki/identity/people?q=": (url) => ({+ body: {+ ok: true,+ people: url.includes("rita%40example.org") ? [PEOPLE[0]] : [],+ query: "[email protected]",+ limit: 200,+ offset: 0,+ counts: COUNTS,+ },+ }),+ });+ renderPanel();+ await screen.findByTestId("person-row-11");++ fireEvent.change(screen.getByTestId("people-search"), {+ target: { value: "[email protected]" },+ });++ expect(await screen.findByTestId("people-by-identifier")).toBeTruthy();+ expect(screen.getByTestId("person-row-11")).toBeTruthy();+ expect(+ calls.some((call) => call.url.includes("q=rita%40example.org")),+ ).toBe(true);+ });++ it("says so when nothing matches at all", async () => {+ installRoutes({+ "GET /api/ultrawiki/identity/people?q=": {+ body: {+ ok: true,+ people: [],+ query: "zzz",+ limit: 200,+ offset: 0,+ counts: COUNTS,+ },+ },+ });+ renderPanel();+ await screen.findByTestId("person-row-11");++ fireEvent.change(screen.getByTestId("people-search"), {+ target: { value: "zzz" },+ });++ expect(await screen.findByTestId("people-no-search-hits")).toBeTruthy();+ });++ it("reports a dead identity layer instead of an empty shell", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => {+ throw new Error("network down");+ }),+ );+ renderPanel();++ expect(await screen.findByTestId("people-error")).toBeTruthy();+ });+});++describe("the decision queue", () => {+ it("opens on the queue, because that is what goes stale by being ignored", async () => {+ installRoutes();+ renderPanel();++ expect(await screen.findByTestId("people-queue-pane")).toBeTruthy();+ expect(screen.getByTestId("merge-proposal-7")).toBeTruthy();+ });++ it("counts the open questions on the way in", async () => {+ installRoutes();+ renderPanel();++ await waitFor(() => {+ expect(screen.getByTestId("people-open-queue").textContent).toContain("1");+ });+ });++ it("says so when the queue is empty", async () => {+ installRoutes({+ "GET /api/ultrawiki/identity/queue": {+ body: {+ ok: true,+ proposals: [],+ status: "pending",+ limit: 100,+ counts: { ...COUNTS, pending_confirmations: 0 },+ },+ },+ });+ renderPanel();++ expect(await screen.findByTestId("identity-queue-empty")).toBeTruthy();+ });+});++describe("one person", () => {+ it("shows the standing facts grouped by what they are", async () => {+ installRoutes();+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));++ const facts = await screen.findByTestId("person-facts");+ expect(facts.textContent).toContain("[email protected]");+ expect(screen.getByTestId("person-facts-email")).toBeTruthy();+ expect(screen.getByTestId("person-facts-name")).toBeTruthy();+ // Nothing is invented for a kind the person has none of.+ expect(screen.queryByTestId("person-facts-phone")).toBeNull();+ });++ it("shows what happened, dated the way the source could support it", async () => {+ installRoutes();+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));++ const event = await screen.findByTestId("person-event-91");+ expect(event.textContent).toContain("Dinner with Rita");+ expect(event.textContent).toContain("4 July 2026");+ expect(screen.getByTestId("person-event-link-91").getAttribute("href")).toBe(+ "app://evidence/501",+ );+ });++ it("keeps the profile readable when the event layer is dead", async () => {+ // Events are their own layer. A corpus that never ran event extraction —+ // or a store that fails this one query — must not take the identity half+ // of the page down with it.+ installRoutes({+ "GET /api/ultrawiki/events": { status: 500, body: { detail: "no events" } },+ });+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));++ expect(await screen.findByTestId("person-events-failed")).toBeTruthy();+ expect(screen.getByTestId("person-facts").textContent).toContain(+ "[email protected]",+ );+ });++ it("raises the open questions about that person on their own profile", async () => {+ installRoutes();+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));++ expect(await screen.findByTestId("merge-proposal-7")).toBeTruthy();+ });+});++describe("undoing a merge", () => {+ it("offers the undo only for a merge that still stands", async () => {+ installRoutes();+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));+ await screen.findByTestId("person-merges");++ expect(screen.getByTestId("person-merge-undo-5")).toBeTruthy();+ // Merge 4 was already undone — the record stays, the button does not.+ expect(screen.queryByTestId("person-merge-undo-4")).toBeNull();+ expect(screen.getByTestId("person-merge-undone-4")).toBeTruthy();+ });++ it("undoes through the audit id, not the entity id", async () => {+ const calls = installRoutes({+ "POST /api/ultrawiki/identity/merges/5/unmerge": {+ body: { ok: true, merge_id: 5, status: "undone" },+ },+ });+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));+ fireEvent.click(await screen.findByTestId("person-merge-undo-5"));++ await waitFor(() => {+ expect(+ calls.some(+ (call) =>+ call.method === "POST" &&+ call.url === "/api/ultrawiki/identity/merges/5/unmerge",+ ),+ ).toBe(true);+ });+ });++ it("repeats the store's reason when it refuses to undo", async () => {+ installRoutes({+ "POST /api/ultrawiki/identity/merges/5/unmerge": {+ status: 409,+ body: { detail: "undo merge 9 first" },+ },+ });+ renderPanel();++ fireEvent.click(await screen.findByTestId("person-row-11"));+ fireEvent.click(await screen.findByTestId("person-merge-undo-5"));++ const error = await screen.findByTestId("person-merge-error-5");+ expect(error.textContent).toContain("undo merge 9 first");+ });+});++describe("seeding from the address book", () => {+ it("reports what one pass actually changed", async () => {+ installRoutes({+ "POST /api/ultrawiki/identity/seed": {+ body: {+ ok: true,+ report: {+ created: 3,+ linked: 12,+ identifiers_added: 4,+ merged: 1,+ queued: 2,+ skipped: 0,+ },+ counts: COUNTS,+ },+ },+ });+ renderPanel();++ fireEvent.click(await screen.findByTestId("people-seed"));++ const line = await screen.findByTestId("people-seed-result");+ expect(line.textContent).toContain("3");+ expect(line.textContent).toContain("12");+ });++ it("does not hide a refused import", async () => {+ installRoutes({+ "POST /api/ultrawiki/identity/seed": {+ status: 409,+ body: { detail: "UltraWiki mode is off" },+ },+ });+ renderPanel();++ fireEvent.click(await screen.findByTestId("people-seed"));++ const error = await screen.findByTestId("people-seed-error");+ expect(error.textContent).toContain("UltraWiki mode is off");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/PeoplePanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/PeoplePanel.tsxnew file mode 100644index 0000000000..d2b7c56f04--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/PeoplePanel.tsx@@ -0,0 +1,819 @@+/**+ * People — who the knowledge base thinks exists, and what it knows about them.+ *+ * Explore answers "what topics run through my life". This answers the other+ * half: the same corpus seen through PEOPLE. One person is usually scattered+ * across a dozen spellings, two e-mail addresses and an address-book entry,+ * and the identity layer's whole job is folding those back into one. This+ * view is where that becomes visible — and correctable.+ *+ * Layout: a list on the left, one thing at a time on the right.+ *+ * ┌───────────┬──────────────────────────────┐+ * │ people │ the decision queue │+ * │ (18 rem) │ ── or one person's profile │+ * └───────────┴──────────────────────────────┘+ *+ * The right column opens on the QUEUE, not on an empty profile pane. Merge+ * proposals are the only thing here that goes stale by being ignored: an+ * unanswered "are these the same person?" leaves the knowledge base holding+ * one human as two, and every later answer inherits the split. A profile, by+ * contrast, is only interesting once you have picked someone.+ *+ * A profile is two halves, because the store holds two different kinds of+ * knowledge about a person: the standing FACTS (the identifiers they are+ * known by) and what HAPPENED (the episodic events they took part in). Under+ * both sits the merge history, which is the only place an over-eager merge+ * can be taken back.+ */+import { useMemo, useState } from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import {+ AlertCircle,+ ArrowLeft,+ CalendarClock,+ ExternalLink,+ Loader2,+ Search,+ Undo2,+ UserPlus,+ Users,+} from "lucide-react";++import { cn } from "@/lib/utils";+import { useT } from "@/i18n";+import {+ IDENTITY_QUERY_KEY,+ MergeQueuePanel,+} from "@/components/ultrawiki/MergeQueuePanel";+import {+ ULTRAWIKI_IDENTIFIER_KINDS,+ fetchIdentityQueue,+ fetchPeople,+ fetchPerson,+ fetchPersonEvents,+ identityErrorMessage,+ seedIdentities,+ undoableMerges,+ unmergeIdentity,+ type UltraWikiIdentifier,+ type UltraWikiMergeRecord,+ type UltraWikiPerson,+ type UltraWikiPersonEvent,+ type UltraWikiPersonRow,+} from "@/lib/ultrawikiIdentityApi";++/** One request covers any realistic address book; typing filters in place. */+const PEOPLE_LIMIT = 500;+/** Long enough that a stray letter does not fire a request of its own. */+const IDENTIFIER_SEARCH_MIN = 2;+const EVENT_LIMIT = 25;++export interface PeoplePanelProps {+ /** The way out of an empty knowledge base — no source, nobody to know. */+ onOpenSources?: () => void;+}++export function PeoplePanel({ onOpenSources }: PeoplePanelProps): JSX.Element {+ const t = useT();+ const queryClient = useQueryClient();+ const [search, setSearch] = useState("");+ const [selected, setSelected] = useState<number | null>(null);+ const [pane, setPane] = useState<"queue" | "profile">("queue");++ const peopleQuery = useQuery({+ queryKey: [...IDENTITY_QUERY_KEY, "people"],+ queryFn: () => fetchPeople({ limit: PEOPLE_LIMIT }),+ staleTime: 30_000,+ });++ const queueQuery = useQuery({+ queryKey: [...IDENTITY_QUERY_KEY, "queue"],+ queryFn: () => fetchIdentityQueue({ status: "pending", limit: 100 }),+ staleTime: 15_000,+ });++ const people = peopleQuery.data?.people ?? [];+ const needle = search.trim().toLowerCase();++ const localHits = useMemo(() => {+ if (!needle) return people;+ return people.filter((person) =>+ person.display_name.toLowerCase().includes(needle),+ );+ }, [people, needle]);++ // A name search runs locally and stays instant. Searching by e-mail or+ // phone number cannot: identifiers are not in the list payload, and loading+ // every identifier of every person to make them searchable would be a far+ // bigger cost than one request on the rare miss. So the server is only+ // asked once the local list has genuinely nothing.+ const identifierQuery = useQuery({+ queryKey: [...IDENTITY_QUERY_KEY, "people", "search", needle],+ queryFn: () => fetchPeople({ q: needle, limit: 200 }),+ enabled:+ needle.length >= IDENTIFIER_SEARCH_MIN &&+ localHits.length === 0 &&+ !peopleQuery.isLoading,+ staleTime: 30_000,+ });++ const identifierHits = identifierQuery.data?.people ?? [];+ const byIdentifier = localHits.length === 0 && identifierHits.length > 0;+ const rows = byIdentifier ? identifierHits : localHits;++ const seedMutation = useMutation({+ mutationFn: seedIdentities,+ onSuccess: () =>+ void queryClient.invalidateQueries({ queryKey: IDENTITY_QUERY_KEY }),+ });++ const proposals = queueQuery.data?.proposals ?? [];+ const counts = peopleQuery.data?.counts ?? {};++ const openPerson = (entityId: number) => {+ setSelected(entityId);+ setPane("profile");+ };++ if (peopleQuery.isLoading) {+ return (+ <div+ data-testid="people-loading"+ className="flex flex-1 items-center justify-center p-6 text-sm text-muted-foreground"+ >+ {t("ultrawiki.people.loading")}+ </div>+ );+ }++ if (peopleQuery.isError) {+ return (+ <div className="flex flex-1 items-center justify-center p-6">+ <p+ role="alert"+ data-testid="people-error"+ className="max-w-md rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"+ >+ {t("ultrawiki.people.error")}+ </p>+ </div>+ );+ }++ return (+ // h-full rather than flex-1, and min-w-0 on every column: the same two+ // rules the Explore workspace needs, for the same two reasons (an inner+ // list must scroll instead of stretching the page, and no child may set+ // the section's minimum width).+ <div className="flex h-full min-h-0 min-w-0 flex-col" data-testid="people-panel">+ <div className="flex flex-wrap items-center gap-2 border-b border-border px-3 py-2">+ <div className="relative min-w-[12rem] flex-1">+ <Search+ className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"+ aria-hidden+ />+ <input+ data-testid="people-search"+ value={search}+ onChange={(event) => setSearch(event.target.value)}+ placeholder={t("ultrawiki.people.search_placeholder")}+ aria-label={t("ultrawiki.people.search_placeholder")}+ className="h-8 w-full rounded-lg border border-border bg-background/60 pl-8 pr-2.5 text-xs outline-none transition-colors focus-visible:border-primary/50 focus-visible:ring-1 focus-visible:ring-primary/40"+ />+ </div>++ <button+ type="button"+ data-testid="people-open-queue"+ onClick={() => setPane("queue")}+ data-active={pane === "queue" ? "true" : "false"}+ className={cn(+ "inline-flex shrink-0 items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[11px] transition-colors",+ pane === "queue"+ ? "border-primary/50 bg-primary/10 text-foreground"+ : "border-border text-muted-foreground hover:text-foreground",+ )}+ >+ <Users className="h-3.5 w-3.5" aria-hidden />+ {proposals.length > 0+ ? t("ultrawiki.people.queue_open").replace(+ "{0}",+ String(proposals.length),+ )+ : t("ultrawiki.people.queue_tab")}+ </button>++ <button+ type="button"+ data-testid="people-seed"+ onClick={() => seedMutation.mutate()}+ disabled={seedMutation.isPending}+ title={t("ultrawiki.people.seed_hint")}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-2.5 py-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-60"+ >+ {seedMutation.isPending ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <UserPlus className="h-3.5 w-3.5" aria-hidden />+ )}+ {seedMutation.isPending+ ? t("ultrawiki.people.seeding")+ : t("ultrawiki.people.seed")}+ </button>+ </div>++ {seedMutation.data && (+ <p+ data-testid="people-seed-result"+ className="border-b border-border bg-muted/20 px-4 py-1.5 text-[11px] tabular-nums text-muted-foreground"+ >+ {t("ultrawiki.people.seed_result")+ .replace("{0}", String(seedMutation.data.report.created))+ .replace("{1}", String(seedMutation.data.report.linked))+ .replace("{2}", String(seedMutation.data.report.merged))+ .replace("{3}", String(seedMutation.data.report.queued))}+ </p>+ )}++ {seedMutation.error && (+ <p+ role="alert"+ data-testid="people-seed-error"+ className="border-b border-border bg-destructive/10 px-4 py-1.5 text-[11px] text-destructive"+ >+ {t("ultrawiki.people.action_failed").replace(+ "{0}",+ identityErrorMessage(seedMutation.error),+ )}+ </p>+ )}++ <div className="flex min-h-0 min-w-0 flex-1 flex-col lg:flex-row">+ <aside className="flex min-h-0 min-w-0 shrink-0 flex-col border-b border-border lg:w-[18rem] lg:border-b-0 lg:border-r">+ <p className="shrink-0 px-4 pb-1.5 pt-2 text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("ultrawiki.people.count").replace("{0}", String(rows.length))}+ </p>++ <div className="scrollbar-jarvis min-h-0 flex-1 overflow-y-auto px-1.5 pb-2 max-lg:max-h-56">+ {byIdentifier && (+ <p+ data-testid="people-by-identifier"+ className="px-2.5 py-1.5 text-[11px] text-muted-foreground"+ >+ {t("ultrawiki.people.found_by_identifier")}+ </p>+ )}++ {rows.length === 0 && needle !== "" && !identifierQuery.isFetching && (+ <p+ data-testid="people-no-search-hits"+ className="px-2.5 py-3 text-xs text-muted-foreground"+ >+ {t("ultrawiki.people.no_search_hits").replace("{0}", search.trim())}+ </p>+ )}++ {rows.length === 0 && needle === "" && (+ <div+ data-testid="people-empty"+ className="px-2.5 py-3 text-xs text-muted-foreground"+ >+ <p>{t("ultrawiki.people.empty")}</p>+ {onOpenSources && (+ <button+ type="button"+ data-testid="people-empty-sources"+ onClick={onOpenSources}+ className="mt-1 underline underline-offset-2 hover:text-foreground"+ >+ {t("ultrawiki.panel.tab_sources")}+ </button>+ )}+ </div>+ )}++ {rows.map((person) => (+ <PersonRow+ key={person.id}+ person={person}+ active={person.id === selected && pane === "profile"}+ onSelect={() => openPerson(person.id)}+ />+ ))}+ </div>++ <p+ data-testid="people-counts"+ className="shrink-0 border-t border-border px-4 py-1.5 text-[10px] tabular-nums text-muted-foreground"+ >+ {t("ultrawiki.people.counts_line")+ .replace("{0}", String(counts.people ?? 0))+ .replace("{1}", String(counts.identifiers ?? 0))+ .replace("{2}", String(counts.merges ?? 0))}+ </p>+ </aside>++ <section className="scrollbar-jarvis min-h-0 min-w-0 flex-1 overflow-y-auto">+ {pane === "queue" ? (+ <div className="space-y-2.5 p-3.5" data-testid="people-queue-pane">+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {t("ultrawiki.people.queue_intro")}+ </p>+ {queueQuery.isError ? (+ <p+ role="alert"+ data-testid="people-queue-error"+ className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"+ >+ {t("ultrawiki.people.action_failed").replace(+ "{0}",+ identityErrorMessage(queueQuery.error),+ )}+ </p>+ ) : (+ <MergeQueuePanel+ proposals={proposals}+ onOpenPerson={openPerson}+ />+ )}+ </div>+ ) : selected === null ? (+ <p+ data-testid="people-pick-hint"+ className="p-6 text-xs text-muted-foreground"+ >+ {t("ultrawiki.people.pick_hint")}+ </p>+ ) : (+ <PersonProfile+ entityId={selected}+ onOpenPerson={openPerson}+ onBack={() => setPane("queue")}+ />+ )}+ </section>+ </div>+ </div>+ );+}++function PersonRow({+ person,+ active,+ onSelect,+}: {+ person: UltraWikiPersonRow;+ active: boolean;+ onSelect: () => void;+}): JSX.Element {+ const t = useT();+ return (+ <button+ type="button"+ onClick={onSelect}+ data-testid={`person-row-${person.id}`}+ data-active={active ? "true" : "false"}+ className={cn(+ "block w-full rounded-lg px-2.5 py-1.5 text-left transition-colors",+ active+ ? "bg-primary/10 ring-1 ring-inset ring-primary/25"+ : "hover:bg-muted/60",+ )}+ >+ <span className="flex items-baseline justify-between gap-2">+ <span+ className={cn(+ "truncate text-xs",+ active ? "text-primary" : "text-foreground",+ )}+ >+ {person.display_name}+ </span>+ <span+ className="shrink-0 text-[11px] tabular-nums text-muted-foreground"+ title={t("ultrawiki.people.identifiers").replace(+ "{0}",+ String(person.identifier_count),+ )}+ >+ {person.identifier_count}+ </span>+ </span>+ </button>+ );+}++// ---------------------------------------------------------------------------+// One person+// ---------------------------------------------------------------------------++function PersonProfile({+ entityId,+ onOpenPerson,+ onBack,+}: {+ entityId: number;+ onOpenPerson: (id: number) => void;+ onBack: () => void;+}): JSX.Element {+ const t = useT();++ const personQuery = useQuery({+ queryKey: [...IDENTITY_QUERY_KEY, "person", entityId],+ queryFn: () => fetchPerson(entityId),+ staleTime: 15_000,+ });++ // Their timeline is a SEPARATE layer and a separate request on purpose: a+ // corpus with no event extraction yet still has a working profile, and a+ // failure here degrades to one muted line instead of taking the identity+ // half of the page down with it.+ const eventsQuery = useQuery({+ queryKey: [...IDENTITY_QUERY_KEY, "events", entityId],+ queryFn: () => fetchPersonEvents(entityId, { limit: EVENT_LIMIT }),+ staleTime: 30_000,+ retry: false,+ });++ if (personQuery.isLoading) {+ return (+ <p+ data-testid="person-loading"+ className="p-6 text-xs text-muted-foreground"+ >+ {t("ultrawiki.people.loading")}+ </p>+ );+ }++ if (personQuery.isError || !personQuery.data) {+ return (+ <p+ role="alert"+ data-testid="person-error"+ className="m-4 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"+ >+ {t("ultrawiki.people.action_failed").replace(+ "{0}",+ identityErrorMessage(personQuery.error),+ )}+ </p>+ );+ }++ const { person, forwarded } = personQuery.data;+ const events = eventsQuery.data?.events ?? [];++ return (+ <div data-testid={`person-profile-${person.id}`} className="pb-6">+ <header className="flex items-start gap-2 border-b border-border px-4 py-3">+ <button+ type="button"+ data-testid="person-back"+ onClick={onBack}+ aria-label={t("ultrawiki.people.back")}+ title={t("ultrawiki.people.back")}+ className="mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:text-primary"+ >+ <ArrowLeft className="h-3.5 w-3.5" aria-hidden />+ </button>+ <div className="min-w-0 flex-1">+ <h3 className="truncate text-sm text-foreground">+ {person.display_name}+ </h3>+ <p className="mt-0.5 text-[11px] tabular-nums text-muted-foreground">+ {t("ultrawiki.people.identifiers").replace(+ "{0}",+ String(person.identifiers.length),+ )}+ {person.merged_from.length > 0 && (+ <>+ {" · "}+ {t("ultrawiki.people.folded_count").replace(+ "{0}",+ String(person.merged_from.length),+ )}+ </>+ )}+ </p>+ {forwarded && (+ <p+ data-testid="person-forwarded"+ className="mt-1 text-[11px] text-muted-foreground"+ >+ {t("ultrawiki.people.forwarded").replace(+ "{0}",+ String(person.requested_id),+ )}+ </p>+ )}+ </div>+ </header>++ <FactsSection identifiers={person.identifiers} />++ <EventsSection+ events={events}+ total={eventsQuery.data?.total ?? 0}+ failed={eventsQuery.isError}+ loading={eventsQuery.isLoading}+ />++ {person.pending_proposals.length > 0 && (+ <section className="border-t border-border px-4 py-3">+ <h4 className="text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("ultrawiki.people.open_questions")}+ </h4>+ <MergeQueuePanel+ className="mt-2"+ proposals={person.pending_proposals}+ onOpenPerson={onOpenPerson}+ />+ </section>+ )}++ <MergeHistory person={person} />+ </div>+ );+}++/**+ * The standing facts — what this person is KNOWN BY.+ *+ * Grouped by kind rather than listed flat, because the kinds are not equally+ * interesting: an e-mail address is why two identities merged, a name variant+ * is usually just spelling. Grouping puts the deterministic ones together.+ */+function FactsSection({+ identifiers,+}: {+ identifiers: UltraWikiIdentifier[];+}): JSX.Element {+ const t = useT();+ const groups = useMemo(() => {+ const byKind = new Map<string, string[]>();+ for (const item of identifiers) {+ const label = item.display_value || item.value;+ if (!label) continue;+ const bucket = byKind.get(item.kind);+ if (bucket) bucket.push(label);+ else byKind.set(item.kind, [label]);+ }+ return ULTRAWIKI_IDENTIFIER_KINDS.filter((kind) => byKind.has(kind)).map(+ (kind) => ({ kind, values: byKind.get(kind) as string[] }),+ );+ }, [identifiers]);++ return (+ <section className="border-b border-border px-4 py-3" data-testid="person-facts">+ <h4 className="text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("ultrawiki.people.facts_title")}+ </h4>+ {groups.length === 0 ? (+ <p className="mt-1 text-xs text-muted-foreground">+ {t("ultrawiki.people.no_facts")}+ </p>+ ) : (+ <dl className="mt-2 space-y-1.5">+ {groups.map((group) => (+ <div+ key={group.kind}+ data-testid={`person-facts-${group.kind}`}+ className="flex flex-wrap items-baseline gap-x-2 gap-y-1"+ >+ <dt className="w-24 shrink-0 text-[11px] text-muted-foreground">+ {t(`ultrawiki.people.facts_${group.kind}`)}+ </dt>+ <dd className="flex min-w-0 flex-wrap gap-1.5">+ {group.values.map((value) => (+ <span+ key={value}+ className="rounded-full border border-border px-2 py-0.5 text-[11px] text-foreground"+ >+ {value}+ </span>+ ))}+ </dd>+ </div>+ ))}+ </dl>+ )}+ </section>+ );+}++/** What HAPPENED — the episodic half of a profile. */+function EventsSection({+ events,+ total,+ failed,+ loading,+}: {+ events: UltraWikiPersonEvent[];+ total: number;+ failed: boolean;+ loading: boolean;+}): JSX.Element {+ const t = useT();+ return (+ <section className="border-b border-border px-4 py-3" data-testid="person-events">+ <h4 className="flex items-center gap-1.5 text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ <CalendarClock className="h-3 w-3" aria-hidden />+ {t("ultrawiki.people.events_title")}+ </h4>++ {loading && (+ <p className="mt-1 text-xs text-muted-foreground">+ {t("ultrawiki.people.loading")}+ </p>+ )}++ {!loading && failed && (+ <p+ data-testid="person-events-failed"+ className="mt-1 flex items-center gap-1.5 text-[11px] text-muted-foreground"+ >+ <AlertCircle className="h-3 w-3 shrink-0" aria-hidden />+ {t("ultrawiki.people.events_failed")}+ </p>+ )}++ {!loading && !failed && events.length === 0 && (+ <p className="mt-1 text-xs text-muted-foreground">+ {t("ultrawiki.people.no_events")}+ </p>+ )}++ {events.length > 0 && (+ <ol className="mt-2 space-y-1.5">+ {events.map((event) => (+ <li+ key={event.id}+ data-testid={`person-event-${event.id}`}+ className="rounded-lg border border-border/70 bg-card/40 px-2.5 py-2"+ >+ <p className="flex flex-wrap items-baseline gap-x-2">+ <span className="text-[11px] tabular-nums text-muted-foreground">+ {event.date_label || event.occurred_at.slice(0, 10)}+ </span>+ <span className="min-w-0 flex-1 text-xs text-foreground">+ {event.title}+ </span>+ </p>+ {event.summary && (+ <p className="mt-0.5 line-clamp-2 text-[11px] leading-relaxed text-muted-foreground">+ {event.summary}+ </p>+ )}+ <p className="mt-1 flex flex-wrap items-center gap-x-2 text-[10px] text-muted-foreground">+ {event.place && (+ <span>+ {t("ultrawiki.people.event_place").replace("{0}", event.place)}+ </span>+ )}+ {event.permalink && (+ <a+ href={event.permalink}+ data-testid={`person-event-link-${event.id}`}+ className="inline-flex items-center gap-0.5 transition-colors hover:text-primary"+ >+ <ExternalLink className="h-2.5 w-2.5" aria-hidden />+ {t("ultrawiki.people.open_source")}+ </a>+ )}+ </p>+ </li>+ ))}+ </ol>+ )}++ {events.length > 0 && total > events.length && (+ <p+ data-testid="person-events-more"+ className="mt-1.5 text-[10px] tabular-nums text-muted-foreground"+ >+ {t("ultrawiki.people.events_shown")+ .replace("{0}", String(events.length))+ .replace("{1}", String(total))}+ </p>+ )}+ </section>+ );+}++/**+ * The merge history — and the undo it exists for.+ *+ * Every merge stays on the record, undone or not: "these two were once one+ * person" is a fact about the knowledge base even after the split. Only a+ * merge that still STANDS gets an undo button, and the store refuses one that+ * a later merge shadows, naming the merge to undo first — that sentence is+ * printed as it arrives.+ */+function MergeHistory({ person }: { person: UltraWikiPerson }): JSX.Element | null {+ const t = useT();+ const merges = person.merges ?? [];+ const standing = undoableMerges(person);+ if (merges.length === 0) return null;++ const names = new Map<number, string>(+ person.merged_from.map((entry) => [entry.id, entry.display_name]),+ );++ return (+ <section className="px-4 py-3" data-testid="person-merges">+ <h4 className="text-[10px] uppercase tracking-[0.14em] text-muted-foreground">+ {t("ultrawiki.people.merges_title")}+ </h4>+ <p className="mt-1 text-[11px] text-muted-foreground">+ {standing.length > 0+ ? t("ultrawiki.people.merges_hint")+ : t("ultrawiki.people.merges_all_undone")}+ </p>+ <ul className="mt-2 space-y-1.5">+ {merges.map((merge) => (+ <MergeRow+ key={merge.id}+ merge={merge}+ loserName={names.get(merge.loser_id) ?? ""}+ />+ ))}+ </ul>+ </section>+ );+}++function MergeRow({+ merge,+ loserName,+}: {+ merge: UltraWikiMergeRecord;+ loserName: string;+}): JSX.Element {+ const t = useT();+ const queryClient = useQueryClient();+ const undoMutation = useMutation({+ mutationFn: () => unmergeIdentity(merge.id),+ onSuccess: () =>+ void queryClient.invalidateQueries({ queryKey: IDENTITY_QUERY_KEY }),+ });++ const undone = Boolean(merge.undone_at);+ const who = loserName || `#${merge.loser_id}`;++ return (+ <li+ data-testid={`person-merge-${merge.id}`}+ data-undone={undone ? "true" : "false"}+ className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-border/70 bg-card/40 px-2.5 py-1.5"+ >+ <span className="min-w-0 flex-1 text-[11px] text-foreground">+ {t("ultrawiki.people.merge_line").replace("{0}", who)}+ <span className="ml-1.5 text-muted-foreground">+ {merge.merged_at.slice(0, 10)}+ {merge.tier && ` · ${t(`ultrawiki.people.tier_${merge.tier}`)}`}+ </span>+ </span>++ {undone ? (+ <span+ data-testid={`person-merge-undone-${merge.id}`}+ className="shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground"+ >+ {t("ultrawiki.people.merge_undone")}+ </span>+ ) : (+ <button+ type="button"+ data-testid={`person-merge-undo-${merge.id}`}+ onClick={() => undoMutation.mutate()}+ disabled={undoMutation.isPending}+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-border px-2 py-0.5 text-[10px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-60"+ >+ {undoMutation.isPending ? (+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ ) : (+ <Undo2 className="h-3 w-3" aria-hidden />+ )}+ {t("ultrawiki.people.undo_merge")}+ </button>+ )}++ {undoMutation.error && (+ <p+ role="alert"+ data-testid={`person-merge-error-${merge.id}`}+ className="w-full text-[11px] text-destructive"+ >+ {t("ultrawiki.people.action_failed").replace(+ "{0}",+ identityErrorMessage(undoMutation.error),+ )}+ </p>+ )}+ </li>+ );+}++export default PeoplePanel;diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 10780eddb5..20f55c8bb5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -2822,6 +2822,70 @@"result_error": "Discord nicht erreichbar, bitte später erneut versuchen."},"ultrawiki": {+ "people": {+ "tab": "Personen",+ "loading": "Lese, was über Personen bekannt ist …",+ "error": "Die Personen der Wissensbasis konnten nicht gelesen werden.",+ "search_placeholder": "Person suchen …",+ "count": "{0} Personen",+ "counts_line": "{0} Personen · {1} Merkmale · {2} Zusammenführungen",+ "no_search_hits": "Niemand passt zu „{0}“.",+ "found_by_identifier": "Über eine E-Mail-Adresse, Telefonnummer oder einen Nutzernamen gefunden.",+ "empty": "Es ist noch niemand bekannt. Importiere dein Adressbuch oder verbinde eine Quelle, aus der sich etwas lernen lässt.",+ "identifiers": "{0} Merkmale",+ "pick_hint": "Wähle links jemanden aus, um zu sehen, was über die Person bekannt ist.",+ "back": "Zurück zu den offenen Fragen",+ "seed": "Adressbuch importieren",+ "seeding": "Importiere …",+ "seed_hint": "Übernimmt die Personen aus deinen Kontakten. Lässt sich jederzeit wiederholen — ein zweiter Durchlauf verknüpft, statt zu verdoppeln.",+ "seed_result": "{0} neu, {1} bereits bekannt, {2} zusammengeführt, {3} zu bestätigen.",+ "action_failed": "Das hat nicht geklappt: {0}",+ "queue_tab": "Offene Fragen",+ "queue_open": "{0} zu entscheiden",+ "queue_intro": "Zwei Einträge sehen nach derselben Person aus, aber das Einzige, was sie verbindet, ist ein ähnlicher Name. Eine gemeinsame E-Mail-Adresse oder Telefonnummer wäre ohne Nachfrage zusammengeführt worden.",+ "queue_question": "Ist das dieselbe Person?",+ "queue_empty": "Es wartet nichts auf eine Entscheidung.",+ "open_questions": "Offene Fragen zu dieser Person",+ "match_strength": "{0} % ähnlich",+ "same_person": "Ja, eine Person",+ "different_people": "Nein, zwei Personen",+ "reject_warning": "Das ist endgültig. Das Paar wird nie wieder vorgeschlagen, auch nicht, wenn später derselbe Hinweis auftaucht — und es lässt sich nicht zurücknehmen.",+ "reject_final": "Getrennt lassen",+ "cancel": "Abbrechen",+ "merged_undoable": "Zusammengeführt. Du kannst das im Verlauf der Zusammenführungen rückgängig machen.",+ "merged_already": "Das war bereits eine Person — es gab nichts zusammenzuführen.",+ "evidence_same": "{0} identisch",+ "evidence_similar": "{0} ähnlich",+ "noun_email": "E-Mail-Adresse",+ "noun_phone": "Telefonnummer",+ "noun_contact": "Adressbuch-Eintrag",+ "noun_handle": "Nutzername",+ "noun_name": "Name",+ "tier_deterministic": "Beleg",+ "tier_probable": "wahrscheinlich",+ "tier_weak": "schwach",+ "facts_title": "Bekannt durch",+ "no_facts": "Diese Person ist bisher durch nichts gekennzeichnet.",+ "facts_email": "E-Mail",+ "facts_phone": "Telefon",+ "facts_contact": "Adressbuch",+ "facts_handle": "Nutzernamen",+ "facts_name": "Namen",+ "events_title": "Woran sie beteiligt war",+ "no_events": "Es ist noch nichts mit dieser Person verknüpft, was passiert ist.",+ "events_failed": "Der Verlauf dieser Person konnte nicht gelesen werden.",+ "events_shown": "{0} von {1} angezeigt",+ "event_place": "in {0}",+ "open_source": "Beleg öffnen",+ "folded_count": "{0} eingegliedert",+ "forwarded": "Eintrag {0} wurde in diese Person überführt.",+ "merges_title": "Zusammenführungen",+ "merges_hint": "Eine Zusammenführung lässt sich rückgängig machen — beide Identitäten kommen genau so zurück, wie sie waren. Rückgängig geht es in umgekehrter Reihenfolge, die neueste zuerst.",+ "merges_all_undone": "Hier ist nichts mehr zusammengeführt.",+ "merge_line": "{0} wurde eingegliedert",+ "merge_undone": "Rückgängig gemacht",+ "undo_merge": "Rückgängig"+ },"explore": {"vault": {"title": "Obsidian-Vault",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 40450b9de4..421f2c09be 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -2823,6 +2823,70 @@"result_error": "Couldn't reach Discord, please try again later."},"ultrawiki": {+ "people": {+ "tab": "People",+ "loading": "Reading what is known about people …",+ "error": "The people in the knowledge base could not be read.",+ "search_placeholder": "Search a person …",+ "count": "{0} people",+ "counts_line": "{0} people · {1} details · {2} merges",+ "no_search_hits": "Nobody matches “{0}”.",+ "found_by_identifier": "Found by an e-mail address, phone number or handle.",+ "empty": "Nobody is known yet. Import your address book, or connect a source there is something to learn from.",+ "identifiers": "{0} details",+ "pick_hint": "Pick someone on the left to see what is known about them.",+ "back": "Back to the open questions",+ "seed": "Import address book",+ "seeding": "Importing …",+ "seed_hint": "Adds the people from your contacts. Safe to run again — a second pass links instead of duplicating.",+ "seed_result": "{0} added, {1} already known, {2} merged, {3} to confirm.",+ "action_failed": "That did not work: {0}",+ "queue_tab": "Open questions",+ "queue_open": "{0} to decide",+ "queue_intro": "Two entries look like the same person, but the only thing linking them is a similar name. A shared e-mail address or phone number would have been merged without asking.",+ "queue_question": "Are these the same person?",+ "queue_empty": "Nothing is waiting for a decision.",+ "open_questions": "Open questions about this person",+ "match_strength": "{0}% alike",+ "same_person": "Yes, one person",+ "different_people": "No, two people",+ "reject_warning": "This is permanent. The pair will never be proposed again, not even if the same evidence turns up later — and there is no way to take it back.",+ "reject_final": "Keep them apart",+ "cancel": "Cancel",+ "merged_undoable": "Merged. You can undo this in their merge history.",+ "merged_already": "They were already one person — there was nothing to merge.",+ "evidence_same": "Same {0}",+ "evidence_similar": "Similar {0}",+ "noun_email": "e-mail address",+ "noun_phone": "phone number",+ "noun_contact": "address-book entry",+ "noun_handle": "handle",+ "noun_name": "name",+ "tier_deterministic": "proof",+ "tier_probable": "likely",+ "tier_weak": "weak",+ "facts_title": "Known by",+ "no_facts": "Nothing identifies this person yet.",+ "facts_email": "E-mail",+ "facts_phone": "Phone",+ "facts_contact": "Address book",+ "facts_handle": "Handles",+ "facts_name": "Names",+ "events_title": "What they were part of",+ "no_events": "Nothing that happened has been linked to them yet.",+ "events_failed": "Their timeline could not be read.",+ "events_shown": "{0} of {1} shown",+ "event_place": "in {0}",+ "open_source": "Open the evidence",+ "folded_count": "{0} folded in",+ "forwarded": "Entry {0} was merged into this person.",+ "merges_title": "Merge history",+ "merges_hint": "A merge can be undone — both identities come back exactly as they were. They undo in reverse order, the newest first.",+ "merges_all_undone": "Nothing here is merged any more.",+ "merge_line": "{0} was folded in",+ "merge_undone": "Undone",+ "undo_merge": "Undo"+ },"explore": {"vault": {"title": "Obsidian vault",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 65977c09eb..6bf3264307 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -2822,6 +2822,70 @@"result_error": "No se pudo llegar a Discord, inténtalo de nuevo más tarde."},"ultrawiki": {+ "people": {+ "tab": "Personas",+ "loading": "Leyendo lo que se sabe de las personas …",+ "error": "No se pudieron leer las personas de la base de conocimiento.",+ "search_placeholder": "Buscar una persona …",+ "count": "{0} personas",+ "counts_line": "{0} personas · {1} datos · {2} fusiones",+ "no_search_hits": "Nadie coincide con «{0}».",+ "found_by_identifier": "Encontrada por una dirección de correo, un teléfono o un usuario.",+ "empty": "Todavía no se conoce a nadie. Importa tu libreta de direcciones o conecta una fuente de la que aprender.",+ "identifiers": "{0} datos",+ "pick_hint": "Elige a alguien de la lista para ver qué se sabe de esa persona.",+ "back": "Volver a las preguntas abiertas",+ "seed": "Importar libreta",+ "seeding": "Importando …",+ "seed_hint": "Añade las personas de tus contactos. Se puede repetir sin riesgo: la segunda pasada enlaza en vez de duplicar.",+ "seed_result": "{0} nuevas, {1} ya conocidas, {2} fusionadas, {3} por confirmar.",+ "action_failed": "Eso no funcionó: {0}",+ "queue_tab": "Preguntas abiertas",+ "queue_open": "{0} por decidir",+ "queue_intro": "Dos entradas parecen la misma persona, pero lo único que las une es un nombre parecido. Un correo o un teléfono compartido se habría fusionado sin preguntar.",+ "queue_question": "¿Es la misma persona?",+ "queue_empty": "No hay nada esperando una decisión.",+ "open_questions": "Preguntas abiertas sobre esta persona",+ "match_strength": "{0} % de parecido",+ "same_person": "Sí, una sola persona",+ "different_people": "No, dos personas",+ "reject_warning": "Esto es definitivo. La pareja no se volverá a proponer nunca, ni siquiera si más adelante aparece la misma prueba, y no se puede deshacer.",+ "reject_final": "Mantenerlas separadas",+ "cancel": "Cancelar",+ "merged_undoable": "Fusionadas. Puedes deshacerlo en su historial de fusiones.",+ "merged_already": "Ya eran una sola persona: no había nada que fusionar.",+ "evidence_same": "Coincidencia en {0}",+ "evidence_similar": "Similitud en {0}",+ "noun_email": "correo electrónico",+ "noun_phone": "número de teléfono",+ "noun_contact": "entrada de la libreta",+ "noun_handle": "usuario",+ "noun_name": "nombre",+ "tier_deterministic": "prueba",+ "tier_probable": "probable",+ "tier_weak": "débil",+ "facts_title": "Se le reconoce por",+ "no_facts": "Todavía no hay nada que identifique a esta persona.",+ "facts_email": "Correo",+ "facts_phone": "Teléfono",+ "facts_contact": "Libreta",+ "facts_handle": "Usuarios",+ "facts_name": "Nombres",+ "events_title": "En qué participó",+ "no_events": "Todavía no hay nada ocurrido enlazado con esta persona.",+ "events_failed": "No se pudo leer su cronología.",+ "events_shown": "{0} de {1} mostrados",+ "event_place": "en {0}",+ "open_source": "Abrir la prueba",+ "folded_count": "{0} fusionadas",+ "forwarded": "La entrada {0} se fusionó con esta persona.",+ "merges_title": "Historial de fusiones",+ "merges_hint": "Una fusión se puede deshacer: ambas identidades vuelven tal y como estaban. Se deshacen en orden inverso, la más reciente primero.",+ "merges_all_undone": "Aquí ya no hay nada fusionado.",+ "merge_line": "{0} se incorporó",+ "merge_undone": "Deshecha",+ "undo_merge": "Deshacer"+ },"explore": {"vault": {"title": "Bóveda de Obsidian",diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiIdentityApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiIdentityApi.tsnew file mode 100644index 0000000000..af4011bede--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiIdentityApi.ts@@ -0,0 +1,507 @@+/**+ * Typed fetchers for the UltraWiki identity surface+ * (`jarvis/ui/web/ultrawiki_identity_routes.py`).+ *+ * The identity layer decides which mentions across the corpus are the SAME+ * person. It merges on its own ONLY on deterministic evidence — a shared+ * e-mail, phone number or address-book entry — and everything weaker becomes a+ * proposal a human decides. That split is the whole contract this client+ * carries into the UI:+ *+ * - a merge that already happened is REVERSIBLE (`unmergeIdentity`),+ * - a rejection is PERMANENT (there is no un-reject route, by design: the+ * pair is never proposed again, which is what stops the queue from asking+ * the same settled question forever),+ * - and `confirmIdentityMerge` hands back the very `merge_id` that reverses+ * it, so the UI can offer the undo without a second lookup.+ *+ * Like the rest of the UltraWiki surface, 409 means "Ultra mode is off" or+ * "the store refused this operation" and 503 means the service is not wired+ * yet. Both arrive as an {@link UltraWikiApiError} carrying the backend's own+ * sentence — never re-worded here, because the store is the one authority on+ * why it said no.+ */++import { UltraWikiApiError } from "@/lib/ultrawikiApi";++// ---------------------------------------------------------------------------+// Value sets — mirrors of jarvis/ultrawiki/identity.py+// ---------------------------------------------------------------------------+//+// Five-layer anti-drift discipline (AP-4 / BUG-008): these cross Python → SQL+// CHECK → REST → TypeScript → UI, and are pinned against the Python enums by+// tests/unit/ultrawiki/test_identity_ui_parity.py. Never retype them elsewhere.++/** What an entity *is*. The People view only ever lists `person`. */+export const ULTRAWIKI_ENTITY_KINDS = [+ "person",+ "place",+ "org",+ "project",+ "topic",+] as const;+export type UltraWikiEntityKind = (typeof ULTRAWIKI_ENTITY_KINDS)[number];++/** One raw handle mapped onto an entity — the "facts" a person is known by. */+export const ULTRAWIKI_IDENTIFIER_KINDS = [+ "email",+ "phone",+ "contact",+ "handle",+ "name",+] as const;+export type UltraWikiIdentifierKind =+ (typeof ULTRAWIKI_IDENTIFIER_KINDS)[number];++/** How strong the evidence linking two identities is. */+export const ULTRAWIKI_MATCH_TIERS = [+ "deterministic",+ "probable",+ "weak",+] as const;+export type UltraWikiMatchTier = (typeof ULTRAWIKI_MATCH_TIERS)[number];++/** State of one confirmation-queue row. `rejected` is permanent by design. */+export const ULTRAWIKI_QUEUE_STATUSES = [+ "pending",+ "confirmed",+ "rejected",+] as const;+export type UltraWikiQueueStatus = (typeof ULTRAWIKI_QUEUE_STATUSES)[number];++/** The queue filter the REST layer accepts, plus its "every status" value. */+export type UltraWikiQueueFilter = UltraWikiQueueStatus | "all";++// ---------------------------------------------------------------------------+// Payloads+// ---------------------------------------------------------------------------++/**+ * Honest counters that travel with EVERY list answer.+ *+ * They are what turns an empty list into a diagnosis: `people: 0` means+ * nothing was ever seeded, while `people: 40` on an empty list means the+ * filter matched nobody — two different problems that look identical without+ * the counters.+ */+export interface UltraWikiIdentityCounts {+ entities: number;+ people: number;+ identifiers: number;+ pending_confirmations: number;+ merges: number;+}++/** One row of the People list. */+export interface UltraWikiPersonRow {+ id: number;+ kind: UltraWikiEntityKind | string;+ display_name: string;+ source_ref: string;+ identifier_count: number;+ created_at: string;+ updated_at: string;+}++/** One thing a person is known by (an e-mail, a phone number, a name…). */+export interface UltraWikiIdentifier {+ id: number;+ kind: UltraWikiIdentifierKind | string;+ value: string;+ /** The spelling a human should see; `value` is the normalized match key. */+ display_value: string;+ source_ref: string;+}++/** One reason two identities were linked — or proposed. */+export interface UltraWikiMatchEvidence {+ tier: UltraWikiMatchTier | string;+ /** e.g. `email`, `email_exact`, `name_similar` — see {@link evidenceParts}. */+ kind: string;+ value: string;+ score: number;+}++/** The two sides of a proposal, as much as a card needs to name them. */+export interface UltraWikiEntityStub {+ id: number;+ kind: UltraWikiEntityKind | string;+ display_name: string;+}++/** One merge that happened — the audit trail row, and the undo handle. */+export interface UltraWikiMergeRecord {+ id: number;+ winner_id: number;+ loser_id: number;+ tier: UltraWikiMatchTier | string;+ reason: string;+ evidence: UltraWikiMatchEvidence[];+ queue_id: number | null;+ merged_at: string;+ /** Non-null once the merge was undone — the row stays as evidence. */+ undone_at: string | null;+}++/** One pair the layer thinks MIGHT be the same person. Nothing is merged yet. */+export interface UltraWikiMergeProposal {+ id: number;+ status: UltraWikiQueueStatus | string;+ score: number;+ evidence: UltraWikiMatchEvidence[];+ created_at: string;+ updated_at: string;+ decided_at: string | null;+ decided_by: string | null;+ left: UltraWikiEntityStub;+ right: UltraWikiEntityStub;+}++/** Everything the identity layer holds about one person. */+export interface UltraWikiPerson {+ id: number;+ kind: UltraWikiEntityKind | string;+ display_name: string;+ canonical_key: string;+ merged_into: number | null;+ source_ref: string;+ profile: Record<string, unknown>;+ created_at: string;+ updated_at: string;+ identifiers: UltraWikiIdentifier[];+ emails: string[];+ phones: string[];+ handles: string[];+ names: string[];+ contacts: string[];+ /** Identities folded INTO this one by a merge. */+ merged_from: Array<{ id: number; display_name: string }>;+ merges: UltraWikiMergeRecord[];+ pending_proposals: UltraWikiMergeProposal[];+ /** The id that was asked for — differs from `id` after a forward. */+ requested_id: number;+}++export interface UltraWikiPeoplePage {+ ok: boolean;+ people: UltraWikiPersonRow[];+ query: string;+ limit: number;+ offset: number;+ counts: Partial<UltraWikiIdentityCounts>;+}++export interface UltraWikiPersonAnswer {+ ok: boolean;+ person: UltraWikiPerson;+ /** True when a merged-away id was forwarded to the survivor. */+ forwarded: boolean;+}++export interface UltraWikiQueuePage {+ ok: boolean;+ proposals: UltraWikiMergeProposal[];+ status: string;+ limit: number;+ counts: Partial<UltraWikiIdentityCounts>;+}++export interface UltraWikiMergeLogPage {+ ok: boolean;+ merges: UltraWikiMergeRecord[];+ entity_id: number | null;+ limit: number;+ counts: Partial<UltraWikiIdentityCounts>;+}++/** What one seeding pass changed. Re-running is safe: `created` drops to 0. */+export interface UltraWikiSeedReport {+ created: number;+ linked: number;+ identifiers_added: number;+ merged: number;+ queued: number;+ skipped: number;+}++export interface UltraWikiSeedAnswer {+ ok: boolean;+ report: UltraWikiSeedReport;+ counts: Partial<UltraWikiIdentityCounts>;+}++export interface UltraWikiConfirmAnswer {+ ok: boolean;+ queue_id: number;+ /** The audit id that reverses this merge; 0 = the pair was already one. */+ merge_id: number;+}++export interface UltraWikiRejectAnswer {+ ok: boolean;+ queue_id: number;+ status: string;+}++export interface UltraWikiUnmergeAnswer {+ ok: boolean;+ merge_id: number;+ status: string;+}++/** One participant of an episodic event. */+export interface UltraWikiEventParticipant {+ entity_id: number | null;+ display_name: string;+}++/**+ * One episodic event (`GET /api/ultrawiki/events`).+ *+ * The person profile answers "what do you know about them" in two halves:+ * the identifiers above are the standing FACTS, these are the things that+ * HAPPENED. `date_label` is the backend's own rendering of `occurred_at` at+ * the precision the source actually supported, so the UI never invents a day+ * for an event the source only pinned to a month.+ */+export interface UltraWikiPersonEvent {+ id: number;+ item_id: number;+ kind: string;+ title: string;+ summary: string;+ occurred_at: string;+ occurred_end: string;+ occurred_precision: string;+ time_anchor: string;+ recorded_at: string;+ date_label: string;+ place: string;+ place_entity_id: number | null;+ confidence: number;+ source_id: string;+ permalink: string;+ item_title: string;+ participants: UltraWikiEventParticipant[];+}++export interface UltraWikiPersonEventsPage {+ events: UltraWikiPersonEvent[];+ total: number;+ limit: number;+ offset: number;+}++// ---------------------------------------------------------------------------+// Transport+// ---------------------------------------------------------------------------++const BASE = "/api/ultrawiki";++async function failure(response: Response): Promise<UltraWikiApiError> {+ let detail: unknown = null;+ try {+ const body = await response.json();+ detail = (body as { detail?: unknown })?.detail ?? body;+ } catch {+ detail = null;+ }+ // The backend's own sentence when it wrote one — a refusal like "undo merge+ // 12 first" is the entire value of the 409 and must reach the user intact.+ const message =+ typeof detail === "string" && detail.trim()+ ? detail+ : `HTTP ${response.status}`;+ return new UltraWikiApiError(message, response.status, detail);+}++async function getJson<T>(path: string): Promise<T> {+ const response = await fetch(path);+ if (!response.ok) throw await failure(response);+ return (await response.json()) as T;+}++async function postJson<T>(path: string): Promise<T> {+ const response = await fetch(path, { method: "POST" });+ if (!response.ok) throw await failure(response);+ return (await response.json()) as T;+}++function queryString(params: Record<string, string | number | undefined>): string {+ const search = new URLSearchParams();+ for (const [key, value] of Object.entries(params)) {+ if (value === undefined || value === "") continue;+ search.set(key, String(value));+ }+ const encoded = search.toString();+ return encoded ? `?${encoded}` : "";+}++// ---------------------------------------------------------------------------+// People+// ---------------------------------------------------------------------------++export async function fetchPeople(+ options: { q?: string; limit?: number; offset?: number } = {},+): Promise<UltraWikiPeoplePage> {+ return getJson<UltraWikiPeoplePage>(+ `${BASE}/identity/people${queryString({+ q: options.q,+ limit: options.limit,+ offset: options.offset,+ })}`,+ );+}++export async function fetchPerson(+ entityId: number,+): Promise<UltraWikiPersonAnswer> {+ return getJson<UltraWikiPersonAnswer>(+ `${BASE}/identity/people/${encodeURIComponent(String(entityId))}`,+ );+}++/** Import the address book as identity entities. Idempotent, re-runnable. */+export async function seedIdentities(): Promise<UltraWikiSeedAnswer> {+ return postJson<UltraWikiSeedAnswer>(`${BASE}/identity/seed`);+}++/**+ * The episodic events one person took part in.+ *+ * Served by the main UltraWiki route module rather than the identity one —+ * events are their own layer and the identity id is merely a filter on them.+ * A merged-away id still finds its events: the store forwards it.+ */+export async function fetchPersonEvents(+ entityId: number,+ options: { limit?: number } = {},+): Promise<UltraWikiPersonEventsPage> {+ return getJson<UltraWikiPersonEventsPage>(+ `${BASE}/events${queryString({+ entity_id: entityId,+ limit: options.limit ?? 25,+ })}`,+ );+}++// ---------------------------------------------------------------------------+// The confirmation queue+// ---------------------------------------------------------------------------++export async function fetchIdentityQueue(+ options: { status?: UltraWikiQueueFilter; limit?: number } = {},+): Promise<UltraWikiQueuePage> {+ return getJson<UltraWikiQueuePage>(+ `${BASE}/identity/queue${queryString({+ status: options.status,+ limit: options.limit,+ })}`,+ );+}++/** Apply one proposal. The answer's `merge_id` is what reverses it. */+export async function confirmIdentityMerge(+ queueId: number,+): Promise<UltraWikiConfirmAnswer> {+ return postJson<UltraWikiConfirmAnswer>(+ `${BASE}/identity/queue/${encodeURIComponent(String(queueId))}/confirm`,+ );+}++/** Decline one proposal — permanently. There is no un-reject route. */+export async function rejectIdentityMerge(+ queueId: number,+): Promise<UltraWikiRejectAnswer> {+ return postJson<UltraWikiRejectAnswer>(+ `${BASE}/identity/queue/${encodeURIComponent(String(queueId))}/reject`,+ );+}++// ---------------------------------------------------------------------------+// The merge audit trail + its undo+// ---------------------------------------------------------------------------++export async function fetchIdentityMerges(+ options: { entityId?: number; limit?: number } = {},+): Promise<UltraWikiMergeLogPage> {+ return getJson<UltraWikiMergeLogPage>(+ `${BASE}/identity/merges${queryString({+ entity_id: options.entityId,+ limit: options.limit,+ })}`,+ );+}++/** Undo one merge. Merges undo in reverse order; a shadowed one 409s. */+export async function unmergeIdentity(+ mergeId: number,+): Promise<UltraWikiUnmergeAnswer> {+ return postJson<UltraWikiUnmergeAnswer>(+ `${BASE}/identity/merges/${encodeURIComponent(String(mergeId))}/unmerge`,+ );+}++// ---------------------------------------------------------------------------+// Presentation helpers+// ---------------------------------------------------------------------------++/**+ * Split an evidence `kind` into the two i18n keys that render it.+ *+ * The backend emits a small family of kinds — `email`, `email_exact`,+ * `name_similar` — where the suffix says HOW it matched and the stem says+ * WHAT matched. Rendering the raw token ("name_similar") in a sentence a+ * non-developer reads is the thing this avoids, while an unknown stem still+ * degrades to the token itself rather than to a blank line.+ */+export function evidenceParts(kind: string): {+ phraseKey: string;+ nounKey: string | null;+ raw: string;+} {+ const token = String(kind || "").trim().toLowerCase();+ const similar = token.endsWith("_similar");+ const stem = token.replace(/_(exact|similar)$/, "");+ const known = (ULTRAWIKI_IDENTIFIER_KINDS as readonly string[]).includes(stem);+ return {+ phraseKey: similar+ ? "ultrawiki.people.evidence_similar"+ : "ultrawiki.people.evidence_same",+ nounKey: known ? `ultrawiki.people.noun_${stem}` : null,+ raw: token,+ };+}++/** The i18n key naming one match tier; unknown tiers fall back to the token. */+export function tierKey(tier: string): string | null {+ return (ULTRAWIKI_MATCH_TIERS as readonly string[]).includes(String(tier))+ ? `ultrawiki.people.tier_${tier}`+ : null;+}++/** A 0…1 score as a whole percentage — never "83.4711 %". */+export function scorePercent(score: number): number {+ if (!Number.isFinite(score)) return 0;+ return Math.round(Math.max(0, Math.min(1, score)) * 100);+}++/**+ * The merges of a person that still STAND and can therefore be undone.+ *+ * The audit trail keeps undone rows on purpose (a merge that was reversed is+ * still a fact about what happened), so "what can I undo here" is a filter,+ * never the raw list.+ */+export function undoableMerges(+ person: Pick<UltraWikiPerson, "merges">,+): UltraWikiMergeRecord[] {+ return (person.merges ?? []).filter((merge) => !merge.undone_at);+}++/** The human message behind a failed identity action. */+export function identityErrorMessage(error: unknown): string {+ if (error instanceof UltraWikiApiError) return error.message;+ if (error instanceof Error) return error.message;+ return String(error ?? "");+}diff --git a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsxindex b77de74e8b..350a95fd25 100644--- a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx@@ -31,6 +31,7 @@ import {MessageCircleQuestion,Plug,Settings2,+ UsersRound,} from "lucide-react";import { useQuery } from "@tanstack/react-query";@@ -47,8 +48,22 @@ import { ContentsPanel } from "@/components/ultrawiki/ContentsPanel";import { SlotsPanel } from "@/components/ultrawiki/SlotsPanel";import { ImportProgress } from "@/components/ultrawiki/ImportProgress";import { ExplorePanel } from "@/components/ultrawiki/ExplorePanel";+import { PeoplePanel } from "@/components/ultrawiki/PeoplePanel";-type UltraTab = "overview" | "explore" | "ask" | "sources" | "contents" | "settings";+type UltraTab =+ | "overview"+ | "explore"+ | "people"+ | "ask"+ | "sources"+ | "contents"+ | "settings";++/** Tabs that own their scrolling: a workspace, not a document (see below). */+const SELF_SCROLLING: ReadonlySet<UltraTab> = new Set<UltraTab>([+ "explore",+ "people",+]);export function UltraWikiPanel(): JSX.Element {const t = useT();@@ -157,6 +172,13 @@ export function UltraWikiPanel(): JSX.Element {label={t("ultrawiki.explore.tab")}testId="ultrawiki-tab-explore"/>+ <UltraTabButton+ active={tab === "people"}+ onClick={() => setTab("people")}+ icon={<UsersRound className="h-3.5 w-3.5" aria-hidden />}+ label={t("ultrawiki.people.tab")}+ testId="ultrawiki-tab-people"+ /><UltraTabButtonactive={tab === "ask"}onClick={() => setTab("ask")}@@ -187,14 +209,14 @@ export function UltraWikiPanel(): JSX.Element {/></div>- {/* Explore is the one tab that manages its own scrolling: it is a- three-column workspace whose map fills the height it is given, and- an outer scroll container would let that height grow without limit- instead of pinning it to the window. */}+ {/* Explore and People manage their own scrolling: both are column+ workspaces whose panes fill the height they are given, and an outer+ scroll container would let that height grow without limit instead of+ pinning it to the window. */}<divclassName={cn("min-h-0 flex-1",- tab === "explore"+ SELF_SCROLLING.has(tab)? "overflow-hidden": "scrollbar-jarvis overflow-y-auto",)}@@ -213,6 +235,9 @@ export function UltraWikiPanel(): JSX.Element {onOpenSettings={() => setTab("settings")}/>)}+ {tab === "people" && (+ <PeoplePanel onOpenSources={() => setTab("sources")} />+ )}{tab === "ask" && (<AskPanelsearchLegs={status.search_legs}diff --git a/tests/unit/ultrawiki/test_identity_ui_parity.py b/tests/unit/ultrawiki/test_identity_ui_parity.pynew file mode 100644index 0000000000..e60d0f2ecd--- /dev/null+++ b/tests/unit/ultrawiki/test_identity_ui_parity.py@@ -0,0 +1,160 @@+"""Five-layer drift guard for the identity UI (AP-4 / BUG-008).++``test_identity_parity.py`` pins the identity value sets down to the two SQL+dialects. This pins the two layers ABOVE them: the TypeScript unions the+People view is written against, and the i18n keys it derives from those+values.++Both are silent when they drift. A missing TS member simply never renders —+an identifier kind added in Python would show up as an empty group nobody+notices. A missing locale key renders as the raw key on screen+("ultrawiki.people.noun_alias"), which is how the layer that exists to explain+a merge to a human ends up printing matcher jargon at them.++The derived keys are the point here: the components build+``ultrawiki.people.facts_<kind>``, ``noun_<kind>`` and ``tier_<tier>`` from+the enum values at runtime, so the enum is the only place a new key can be+demanded from, and nothing in the frontend can notice that it was never+written.+"""++from __future__ import annotations++import json+import re+from pathlib import Path++from jarvis.ultrawiki.identity import (+ EntityKind,+ IdentifierKind,+ MatchTier,+ QueueStatus,+)++FRONTEND = Path(__file__).resolve().parents[3] / "jarvis/ui/web/frontend/src"+API_TS = FRONTEND / "lib/ultrawikiIdentityApi.ts"+LOCALES = FRONTEND / "i18n/locales"+SUPPORTED_LOCALES = ("de", "en", "es")++#: Every component that renders an ``ultrawiki.people.*`` string.+PEOPLE_COMPONENTS = (+ FRONTEND / "components/ultrawiki/PeoplePanel.tsx",+ FRONTEND / "components/ultrawiki/MergeQueuePanel.tsx",+ FRONTEND / "views/ultrawiki/UltraWikiPanel.tsx",+)+++def ts_const_values(name: str) -> set[str]:+ """The quoted members of an ``export const NAME = [...] as const`` array."""+ source = API_TS.read_text(encoding="utf-8")+ match = re.search(rf"{name}\s*=\s*\[(.*?)\]\s*as const", source, re.DOTALL)+ assert match is not None, f"{name} array not found in {API_TS.name}"+ return set(re.findall(r'"([^"]+)"', match.group(1)))+++def locale_keys(locale: str) -> dict:+ return json.loads((LOCALES / f"{locale}.json").read_text(encoding="utf-8"))+++def nested(data: dict, dotted: str) -> object | None:+ node: object = data+ for part in dotted.split("."):+ if not isinstance(node, dict) or part not in node:+ return None+ node = node[part]+ return node+++def assert_in_every_locale(keys: set[str]) -> None:+ for locale in SUPPORTED_LOCALES:+ data = locale_keys(locale)+ missing = sorted(+ key for key in keys if not (isinstance(nested(data, key), str) and nested(data, key))+ )+ assert not missing, f"{locale}.json is missing: {missing}"+++# ---------------------------------------------------------------------------+# Python -> TypeScript+# ---------------------------------------------------------------------------+++def test_typescript_entity_kinds_match_the_python_enum():+ assert ts_const_values("ULTRAWIKI_ENTITY_KINDS") == {kind.value for kind in EntityKind}+++def test_typescript_identifier_kinds_match_the_python_enum():+ assert ts_const_values("ULTRAWIKI_IDENTIFIER_KINDS") == {kind.value for kind in IdentifierKind}+++def test_typescript_match_tiers_match_the_python_enum():+ assert ts_const_values("ULTRAWIKI_MATCH_TIERS") == {tier.value for tier in MatchTier}+++def test_typescript_queue_statuses_match_the_python_enum():+ assert ts_const_values("ULTRAWIKI_QUEUE_STATUSES") == {status.value for status in QueueStatus}+++# ---------------------------------------------------------------------------+# Enum -> i18n (the keys no grep can find, because they are built at runtime)+# ---------------------------------------------------------------------------+++def test_every_identifier_kind_has_a_heading_and_a_noun_in_every_locale():+ """The profile groups facts by kind and the evidence line names the kind+ in a sentence — two different words for the same value, both required."""+ keys = set()+ for kind in IdentifierKind:+ keys.add(f"ultrawiki.people.facts_{kind.value}")+ keys.add(f"ultrawiki.people.noun_{kind.value}")+ assert_in_every_locale(keys)+++def test_every_match_tier_has_a_label_in_every_locale():+ assert_in_every_locale({f"ultrawiki.people.tier_{tier.value}" for tier in MatchTier})+++# ---------------------------------------------------------------------------+# Component -> i18n+# ---------------------------------------------------------------------------+++def people_keys_used_in_components() -> set[str]:+ """Every literal ``t("ultrawiki.people.…")`` the People view asks for."""+ used: set[str] = set()+ for path in PEOPLE_COMPONENTS:+ source = path.read_text(encoding="utf-8")+ used |= set(re.findall(r't\(\s*"(ultrawiki\.people\.[^"]+)"', source))+ return used+++def test_every_string_the_people_view_asks_for_exists_in_every_locale():+ used = people_keys_used_in_components()+ assert used, "no i18n keys found — the extraction regex went stale"+ assert_in_every_locale(used)+++def test_the_people_locale_blocks_are_identical_across_locales():+ """A key added to one locale only is the same silent failure from the+ other direction: English renders, German prints the raw key."""+ reference = set(locale_keys("en")["ultrawiki"]["people"])+ for locale in SUPPORTED_LOCALES:+ assert set(locale_keys(locale)["ultrawiki"]["people"]) == reference, (+ f"{locale}.json has a different ultrawiki.people key set"+ )+++def test_the_view_never_hardcodes_a_person_string():+ """Placeholder-bearing copy is the usual leak: a sentence assembled in TSX+ around a name looks harmless, reads fine in English, and is untranslatable.++ The signature is a literal that CONTAINS a placeholder being filled in+ place — ``"Same {0}".replace(…)`` — as opposed to the legitimate form,+ where the template comes out of a ``t(…)`` lookup and only the VALUE is a+ literal (``.replace("{0}", name)``).+ """+ template_literal = re.compile(r'"[^"]*\{\d\}[^"]*"\s*\.replace')+ for path in PEOPLE_COMPONENTS:+ source = path.read_text(encoding="utf-8")+ hits = template_literal.findall(source)+ assert not hits, f"{path.name}: placeholder copy outside i18n: {hits}"