From a6fd505b1a61101b06c5f4bdefbe820b641915d6 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 07:45:25 +0000 Subject: [PATCH 1/3] feat(entities): merge entities from the list and the side panel, with undo Tick rows on the Entities page to merge them into one (the one on the fixed list, else the most mentioned) or give them one type. The side panel gets Merge (a find box; Enter merges the pick into it), Maybe the same (likely doubles with Merge and Not the same), and a merge offer when a rename clashes. Merges, type changes and hiding have Undo on their toast instead of a confirm. One entity's suggestions now look only in its own namespace. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EzVhJCpwskyo5NhHEtS822 --- CHANGELOG.md | 6 + docs/processing.md | 9 +- fastapi_backend/app/domain/entities.py | 3 + fastapi_backend/tests/domain/test_entities.py | 3 + .../__tests__/entities-curate.test.tsx | 156 ++++++++ .../components/entities/bulk-bar.tsx | 94 +++++ .../components/entities/curate.tsx | 347 ++++++++++++++++++ .../components/entities/entities-page.tsx | 119 +++++- .../components/entities/entity-drawer.tsx | 91 ++++- 9 files changed, 813 insertions(+), 15 deletions(-) create mode 100644 nextjs-frontend/__tests__/entities-curate.test.tsx create mode 100644 nextjs-frontend/components/entities/bulk-bar.tsx create mode 100644 nextjs-frontend/components/entities/curate.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 480efd55e..5a1c3f252 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Merge entities in fewer clicks, and undo instead of confirm.** On the Entities page, tick rows and the bar at the + bottom merges them into one (the one on the fixed list, else the most mentioned) or gives them one type. An entity's + side panel has **Merge**, a find box where Enter merges the entity picked into it, and **Maybe the same**, its likely + doubles with **Merge** and **Not the same**. Renaming an entity to another's name offers to merge them. Merges, type + changes and hiding say what happened with **Undo** ([Entities](docs/processing.md#entities-and-the-graph-explorer)). + ## 0.9.0 October 15, 2026 {id="0.9.0"} - **Evidence PDFs hold everything Lens found.** After each resource's own file come pages of what Lens knows about diff --git a/docs/processing.md b/docs/processing.md index 8d371c69b..765418de1 100644 --- a/docs/processing.md +++ b/docs/processing.md @@ -111,7 +111,14 @@ People, organisations, products, places, events, works and topics are extracted numbers are extracted too, but hidden unless asked for. The **Entities** page in the web app lists a namespace's entities (search, type and collection filters, a Hidden tab) -and opens each in a side panel where editors rename, retype, describe and hide it. +and opens each in a side panel where editors rename, retype, describe, merge and hide it. + +- **Merge from the side panel:** **Merge** opens a find box; type a name and press Enter, and the entity picked is + merged into the open one at once. Its **Maybe the same** list offers likely doubles (same letters, an acronym, a near + spelling) with **Merge** and **Not the same**. Renaming an entity to a name another entity has offers to merge them. +- **Merge or retype many:** editors tick rows (or the whole page) and the bar at the bottom merges them into one (the + one on the fixed list, else the most mentioned; the arrow picks another) or gives them all one type. +- Every merge and bulk type change happens at once and has **Undo** on its notice, so nothing asks to confirm. - **Index** (`GET /api/v1/entities`): - Search forgives misspellings and covers aliases. diff --git a/fastapi_backend/app/domain/entities.py b/fastapi_backend/app/domain/entities.py index e43d77e63..62848b478 100644 --- a/fastapi_backend/app/domain/entities.py +++ b/fastapi_backend/app/domain/entities.py @@ -606,6 +606,9 @@ def put(a, b, reason, conf): def suggestions(db, spaces, eid=None, limit=50): + if eid: # one entity's: only its namespace can hold its doubles + own = db.one("SELECT space FROM $r", r=R("entity", int(eid))) + spaces = {own["space"]} & set(spaces) if own else set() ents = ( [ e diff --git a/fastapi_backend/tests/domain/test_entities.py b/fastapi_backend/tests/domain/test_entities.py index 189bd6512..1d268a09b 100644 --- a/fastapi_backend/tests/domain/test_entities.py +++ b/fastapi_backend/tests/domain/test_entities.py @@ -32,6 +32,9 @@ def test_suggestions_and_merge_undo(db, cfg, spaces): assert ("same letters", {"Northwind Labs", "North Wind Labs"}) in pairs assert ("acronym", {"AWS", "Amazon Web Services"}) in pairs keep, other = eid(db, spaces, "Northwind Labs"), eid(db, spaces, "North Wind Labs") + mine = entities.suggestions(db, spaces, keep) # one entity's: only pairs with it, from its own namespace + assert [{s["a"]["id"], s["b"]["id"]} for s in mine] == [{keep, other}] + assert entities.suggestions(db, {store.ns_id(db, "calls")}, keep) == [] # not where it can't be read entities.not_same(db, eid(db, spaces, "AWS"), eid(db, spaces, "Amazon Web Services")) assert ("acronym", {"AWS", "Amazon Web Services"}) not in [ (s["reason"], {s["a"]["name"], s["b"]["name"]}) for s in entities.suggestions(db, spaces) diff --git a/nextjs-frontend/__tests__/entities-curate.test.tsx b/nextjs-frontend/__tests__/entities-curate.test.tsx new file mode 100644 index 000000000..957ea22bc --- /dev/null +++ b/nextjs-frontend/__tests__/entities-curate.test.tsx @@ -0,0 +1,156 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Entities } from "@/app/openapi-client"; +import { EntityBulkBar } from "@/components/entities/bulk-bar"; +import { keepOf, MaybeSame, MergeInto, mergeTitle } from "@/components/entities/curate"; +import type { EntityRow } from "@/components/entities/model"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Entities: { + listEntities: jest.fn(), + mergeEntities: jest.fn(), + undoEntityMerge: jest.fn(), + listEntitySuggestions: jest.fn(), + markEntitiesNotSame: jest.fn(), + }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +const toast = jest.fn(); +jest.mock("@/components/ui/toast", () => ({ useToast: () => toast })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const m = (f: unknown) => f as jest.Mock; +const show = (ui: React.ReactNode) => { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + {ui} + , + ); +}; + +const row = (id: number, name: string, mentions: number, extra: Partial = {}): EntityRow => ({ + id, + name, + type: "ORG", + type_label: "Organisation", + key: name.toLowerCase(), + aliases: [], + mentions, + recordings: 1, + hidden: false, + ...extra, +}); + +beforeEach(() => jest.clearAllMocks()); + +describe("which entity a merge keeps", () => { + it("keeps the one on the fixed list, else the most mentioned, else the oldest", () => { + expect(keepOf([row(3, "NWL", 2), row(1, "Northwind Labs", 9)])?.id).toBe(1); + expect(keepOf([row(3, "NWL", 2, { defined: true }), row(1, "Northwind Labs", 9)])?.id).toBe(3); + expect(keepOf([row(5, "B", 4), row(2, "A", 4)])?.id).toBe(2); + expect(keepOf([])).toBeUndefined(); + }); + + it("says what was merged into what", () => { + expect(mergeTitle("Acme", ["Acme Inc"])).toBe("Merged Acme Inc into Acme"); + expect(mergeTitle("Acme", ["Acme Inc", "ACME", "Acme Co"])).toBe("Merged 3 entities into Acme"); + }); +}); + +describe("merging into an entity", () => { + it("finds one by typing and merges it at once, with Undo on the toast", async () => { + m(Entities.listEntities).mockReturnValue( + ok({ + total: 3, + items: [ + { id: 1, name: "Northwind Labs", type_label: "Organisation", mentions: 9 }, + { id: 2, name: "North Wind Labs", type_label: "Organisation", mentions: 2 }, + { id: 7, name: "Unknown", builtin: "unknown", mentions: 0 }, + ], + }), + ); + m(Entities.mergeEntities).mockReturnValue(ok({ ok: true, merge: 44 })); + m(Entities.undoEntityMerge).mockReturnValue(ok({ ok: true })); + show( undefined} />); + const box = screen.getByRole("combobox", { name: "Entity to merge into Northwind Labs" }); + expect(box).toHaveFocus(); + fireEvent.change(box, { target: { value: "north" } }); + // itself and the entities that are always there can't be merged + await waitFor(() => expect(screen.getAllByRole("option")).toHaveLength(1)); + expect(screen.getByRole("option")).toHaveTextContent("North Wind Labs"); + fireEvent.keyDown(box, { key: "Enter" }); + await waitFor(() => expect(Entities.mergeEntities).toHaveBeenCalled()); + expect(m(Entities.mergeEntities).mock.calls[0][0].body).toEqual({ keep: 1, others: [2] }); + await waitFor(() => expect(toast).toHaveBeenCalled()); + const t = toast.mock.calls[0][0]; + expect(t.title).toBe("Merged North Wind Labs into Northwind Labs"); + t.action.onClick(); + await waitFor(() => expect(Entities.undoEntityMerge).toHaveBeenCalled()); + expect(m(Entities.undoEntityMerge).mock.calls[0][0].path).toEqual({ mid: 44 }); + }); + + it("offers the ones that may be the same, to merge or set apart", async () => { + m(Entities.listEntitySuggestions).mockReturnValue( + ok([ + { + reason: "acronym", + confidence: 0.85, + a: { id: 4, name: "AWS", mentions: 3 }, + b: { id: 5, name: "Amazon Web Services", mentions: 1 }, + }, + ]), + ); + m(Entities.markEntitiesNotSame).mockReturnValue(ok({ ok: true })); + m(Entities.mergeEntities).mockReturnValue(ok({ ok: true, merge: 3 })); + show(); + expect(await screen.findByText("AWS")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Not the same" })); + await waitFor(() => expect(Entities.markEntitiesNotSame).toHaveBeenCalled()); + expect(m(Entities.markEntitiesNotSame).mock.calls[0][0].body).toEqual({ a: 5, b: 4 }); + fireEvent.click(screen.getByRole("button", { name: "Merge" })); + await waitFor(() => expect(Entities.mergeEntities).toHaveBeenCalled()); + expect(m(Entities.mergeEntities).mock.calls[0][0].body).toEqual({ keep: 5, others: [4] }); + }); + + it("shows nothing to viewers", () => { + show(); + expect(Entities.listEntitySuggestions).not.toHaveBeenCalled(); + }); +}); + +describe("the bulk bar", () => { + it("merges the picked into the one it guesses, in one click", () => { + const onMerge = jest.fn(); + show( + undefined} + onClear={() => undefined} + />, + ); + expect(screen.getByRole("toolbar", { name: "2 entities selected" })).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: /Merge into Northwind Labs/ })); + expect(onMerge.mock.calls[0][0].id).toBe(1); + }); + + it("needs two to merge", () => { + show( + undefined} + onRetype={() => undefined} + onClear={() => undefined} + />, + ); + expect(screen.getByRole("button", { name: "Merge" })).toBeDisabled(); + }); +}); diff --git a/nextjs-frontend/components/entities/bulk-bar.tsx b/nextjs-frontend/components/entities/bulk-bar.tsx new file mode 100644 index 000000000..ff3c9ee57 --- /dev/null +++ b/nextjs-frontend/components/entities/bulk-bar.tsx @@ -0,0 +1,94 @@ +"use client"; + +import { ChevronDown, GitMerge, Shapes, X } from "lucide-react"; + +import type { EntityType } from "@/app/openapi-client/types.gen"; +import { keepOf } from "@/components/entities/curate"; +import type { EntityRow } from "@/components/entities/model"; +import { Menu, MenuContent, MenuItem, MenuLabel, MenuTrigger } from "@/components/ui/menu"; +import { count, plural } from "@/lib/format"; +import { cn } from "@/lib/utils"; + +const actionCls = + "flex h-[34px] items-center gap-1.5 whitespace-nowrap rounded-pill px-3 text-[13px] font-semibold outline-offset-0 [&_svg]:size-[15px] hover:bg-[color-mix(in_srgb,var(--background)_16%,transparent)] disabled:cursor-not-allowed disabled:opacity-50"; + +/** The Entities page's floating bar for the rows picked: merge them into one (the one to keep is guessed and can be + * changed) or give them all one type. Both happen at once and can be undone from the toast. */ +export function EntityBulkBar({ + picked, + types, + busy, + onMerge, + onRetype, + onClear, +}: { + picked: EntityRow[]; + types: EntityType[]; + busy: boolean; + onMerge: (keep: EntityRow) => void; + onRetype: (type: string) => void; + onClear: () => void; +}) { + if (!picked.length) return null; + const keep = keepOf(picked)!; + const many = picked.length > 1; + return ( +
+
+ + {count(picked.length)} selected + + + + + + + + Merge them all into + {picked.map((e) => ( + onMerge(e)}> + {e.name} + {plural(e.mentions, "mention")} + + ))} + + + + + + Type + + + Make them all + {types.map((t) => ( + onRetype(t.type)}> + {t.label} + + ))} + + + +
+
+ ); +} diff --git a/nextjs-frontend/components/entities/curate.tsx b/nextjs-frontend/components/entities/curate.tsx new file mode 100644 index 000000000..f00a9bb21 --- /dev/null +++ b/nextjs-frontend/components/entities/curate.tsx @@ -0,0 +1,347 @@ +"use client"; + +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { GitMerge, Loader2, X } from "lucide-react"; +import { useCallback, useEffect, useId, useRef, useState } from "react"; + +import { Entities } from "@/app/openapi-client"; +import { Button } from "@/components/ui/button"; +import { Skeleton } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { count, plural } from "@/lib/format"; +import { cn } from "@/lib/utils"; + +/** + * Entity curation wherever entities show (the Entities page and its drawer, the graph, a recording): merging with an + * Undo instead of a confirm, finding the entity to merge by typing, and the ones that may be the same thing. + */ + +/** What shows an entity, so a merge, rename or hide is seen everywhere at once. */ +export const ENTITY_KEYS = [ + ["entity"], + ["entities"], + ["entity-mentions"], + ["entity-suggestions"], + ["entity-find"], + ["mentions"], + ["graph"], + ["recording"], +] as const; + +export function useEntityRefresh(): () => void { + const qc = useQueryClient(); + return useCallback(() => { + for (const k of ENTITY_KEYS) void qc.invalidateQueries({ queryKey: [...k] }); + }, [qc]); +} + +export type EntityPick = { id: number; name: string }; +type Weighed = EntityPick & { mentions?: number | null; defined?: boolean | null }; + +/** Which of several entities to keep when they're merged: one on the fixed list first, then the most mentioned, then + * the oldest (the lowest id). */ +export function keepOf(xs: T[]): T | undefined { + return [...xs].sort( + (a, b) => + Number(Boolean(b.defined)) - Number(Boolean(a.defined)) || (b.mentions ?? 0) - (a.mentions ?? 0) || a.id - b.id, + )[0]; +} + +/** "Merged Acme Inc into Acme", "Merged 3 entities into Acme". */ +export function mergeTitle(keep: string, others: string[]): string { + return others.length === 1 + ? `Merged ${others[0]} into ${keep}` + : `Merged ${plural(others.length, "entity", "entities")} into ${keep}`; +} + +const why = (err: unknown) => (err instanceof ApiError ? err.message : "Please try again."); + +/** Merge entities of one namespace into one, at once, with Undo on the toast. */ +export function useMergeEntities() { + const client = useApiClient(); + const toast = useToast(); + const refresh = useEntityRefresh(); + const [pending, setPending] = useState(false); + // the toast outlives whatever opened it (a drawer closes, a node goes), so undo isn't tied to a mounted component + const undo = useCallback( + async (mid: number) => { + try { + await data(Entities.undoEntityMerge({ client, path: { mid } })); + refresh(); + toast({ title: "Merge undone", tone: "green" }); + } catch (err) { + toast({ title: "Couldn’t undo the merge", body: why(err), tone: "red" }); + } + }, + [client, refresh, toast], + ); + const merge = useCallback( + async (keep: EntityPick, others: EntityPick[]): Promise => { + const rest = others.filter((o) => o.id !== keep.id); + if (!rest.length) return false; + setPending(true); + try { + const r = await data( + Entities.mergeEntities({ client, body: { keep: keep.id, others: rest.map((o) => o.id) } }), + ); + refresh(); + toast({ + title: mergeTitle( + keep.name, + rest.map((o) => o.name), + ), + body: "Their mentions and names are this one’s now.", + tone: "green", + duration: 10000, + action: { label: "Undo", onClick: () => void undo(r.merge) }, + }); + return true; + } catch (err) { + toast({ title: "Couldn’t merge them", body: why(err), tone: "red" }); + return false; + } finally { + setPending(false); + } + }, + [client, refresh, toast, undo], + ); + return { merge, pending }; +} + +type Found = { id: number; name: string; type_label?: string; mentions?: number; builtin?: string | null }; + +/** Find an entity of a namespace by typing: the most mentioned first, arrow keys move, Enter picks, Escape leaves. */ +export function EntityFind({ + ns, + exclude = [], + onPick, + onCancel, + placeholder = "Find an entity…", + label, + autoFocus, + busy, +}: { + ns: string; + exclude?: number[]; + onPick: (e: EntityPick) => void; + onCancel?: () => void; + placeholder?: string; + label: string; + autoFocus?: boolean; + busy?: boolean; +}) { + const client = useApiClient(); + const listId = useId(); + const [q, setQ] = useState(""); + const [debounced, setDebounced] = useState(""); + const [active, setActive] = useState(0); + const input = useRef(null); + useEffect(() => { + const t = setTimeout(() => setDebounced(q.trim()), 200); + return () => clearTimeout(t); + }, [q]); + useEffect(() => { + if (autoFocus) input.current?.focus(); + }, [autoFocus]); + const found = useQuery({ + queryKey: ["entity-find", ns, debounced], + queryFn: () => + data( + Entities.listEntities({ + client, + query: { namespaces: ns, q: debounced || undefined, limit: 8 + exclude.length, sort: "mentions" }, + }), + ), + staleTime: 30_000, + }); + const items = ((found.data?.items ?? []) as unknown as Found[]) + .filter((e) => !e.builtin && !exclude.includes(e.id)) + .slice(0, 8); + useEffect(() => setActive(0), [debounced]); + const pick = (e: Found | undefined) => { + if (!e || busy) return; + onPick({ id: e.id, name: e.name }); + setQ(""); + }; + return ( +
+
+ 0} + aria-controls={listId} + aria-activedescendant={items[active] ? `${listId}-${items[active].id}` : undefined} + aria-autocomplete="list" + value={q} + placeholder={placeholder} + disabled={busy} + onChange={(e) => setQ(e.target.value)} + onKeyDown={(e) => { + if (e.key === "ArrowDown") { + e.preventDefault(); + setActive((a) => Math.min(items.length - 1, a + 1)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setActive((a) => Math.max(0, a - 1)); + } else if (e.key === "Enter") { + e.preventDefault(); + pick(items[active]); + } else if (e.key === "Escape" && onCancel) { + e.preventDefault(); + e.stopPropagation(); + onCancel(); + } + }} + className="h-9 w-full rounded-sm border border-border bg-background px-3 pr-9 text-[14px] text-fg outline-hidden placeholder:text-fg-muted focus:border-blue focus:shadow-[0_0_0_3px_var(--intent-surface)]" + /> + {(busy || found.isFetching) && ( + + )} +
+
    + {items.map((e, i) => ( +
  • setActive(i)} + onMouseDown={(ev) => ev.preventDefault()} + onClick={() => pick(e)} + className={cn( + "flex h-8 cursor-pointer items-center gap-2 rounded-sm px-2 text-[13px]", + i === active ? "bg-hl" : "hover:bg-surface-neutral", + )} + > + {e.name} + + {e.type_label ?? "Entity"} · {plural(e.mentions ?? 0, "mention")} + +
  • + ))} + {found.data && !items.length && ( +
  • + {debounced ? `Nothing in ${ns} is called “${debounced}”.` : "No other entities here."} +
  • + )} +
+
+ ); +} + +/** "Merge another entity into this one": a button that becomes a find box; the one picked is merged at once. */ +export function MergeInto({ + keep, + ns, + open, + onOpenChange, +}: { + keep: EntityPick; + ns: string; + open: boolean; + onOpenChange: (o: boolean) => void; +}) { + const { merge, pending } = useMergeEntities(); + if (!open) return null; + return ( +
+
+ +

+ Merge into {keep.name} +

+ +
+

+ Pick the entity that is the same thing. Its mentions and names become {keep.name}’s, and you can undo it. +

+ onOpenChange(false)} + onPick={(e) => void merge(keep, [e])} + /> +
+ ); +} + +type Side = { id: number; name: string; type?: string; mentions?: number }; +type Suggestion = { reason: string; confidence: number; a: Side; b: Side }; + +/** Entities that may be the same as this one (same letters, an acronym, a near spelling): merge one in, or say they + * aren't the same so it isn't suggested again. */ +export function MaybeSame({ entity, canEdit }: { entity: EntityPick; canEdit: boolean }) { + const client = useApiClient(); + const toast = useToast(); + const refresh = useEntityRefresh(); + const { merge, pending } = useMergeEntities(); + const q = useQuery({ + queryKey: ["entity-suggestions", entity.id], + queryFn: () => data(Entities.listEntitySuggestions({ client, query: { entity: entity.id, limit: 5 } })), + enabled: canEdit, + staleTime: 60_000, + }); + if (!canEdit) return null; + if (q.isLoading) return ; + const items = (q.data ?? []) as unknown as Suggestion[]; + if (!items.length) return null; + const notSame = async (other: Side) => { + try { + await data(Entities.markEntitiesNotSame({ client, body: { a: entity.id, b: other.id } })); + refresh(); + toast({ title: `${entity.name} and ${other.name} aren’t the same`, body: "They won’t be suggested again." }); + } catch (err) { + toast({ title: "Couldn’t change it", body: why(err), tone: "red" }); + } + }; + return ( +
+

Maybe the same

+
    + {items.map((s) => { + const other = s.a.id === entity.id ? s.b : s.a; + return ( +
  • + + {other.name} + + {" "} + · {s.reason} · {count(other.mentions ?? 0)} {other.mentions === 1 ? "mention" : "mentions"} + + + + +
  • + ); + })} +
+
+ ); +} diff --git a/nextjs-frontend/components/entities/entities-page.tsx b/nextjs-frontend/components/entities/entities-page.tsx index aab5331c9..a54d08d2c 100644 --- a/nextjs-frontend/components/entities/entities-page.tsx +++ b/nextjs-frontend/components/entities/entities-page.tsx @@ -6,6 +6,8 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { useEffect, useState } from "react"; import { Entities } from "@/app/openapi-client"; +import { EntityBulkBar } from "@/components/entities/bulk-bar"; +import { useEntityRefresh, useMergeEntities } from "@/components/entities/curate"; import { DefineDialog } from "@/components/entities/define-dialog"; import { EntityDrawer } from "@/components/entities/entity-drawer"; import { @@ -22,11 +24,12 @@ import { useCollectionTree } from "@/components/library/use-collections"; import { Badge } from "@/components/ui/badge"; import { Banner } from "@/components/ui/banner"; import { Button } from "@/components/ui/button"; -import { SearchInput, Select } from "@/components/ui/field"; +import { Checkbox, SearchInput, Select } from "@/components/ui/field"; import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; import { Pagination, SortTh, Table, Td, Th, THead, Tr } from "@/components/ui/table"; import { Tabs } from "@/components/ui/tabs"; -import { data, useApiClient } from "@/lib/api/browser"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; import { count, plural, shortDate } from "@/lib/format"; import { needRole, useArchive } from "@/lib/hooks/session"; @@ -46,6 +49,14 @@ export function EntitiesPage() { const open = Number(params.get("entity")) || null; const view = (["hidden", "types", "setup"] as const).find((v) => v === params.get("view")) ?? "all"; const listing = view === "all" || view === "hidden"; + const editor = Boolean(ns) && can("editor", ns); + // rows picked to merge or retype, kept by id so paging and filtering don't lose them + const [picked, setPicked] = useState>(new Map()); + useEffect(() => setPicked(new Map()), [ns, view]); + const toast = useToast(); + const refresh = useEntityRefresh(); + const { merge, pending: merging } = useMergeEntities(); + const [retyping, setRetyping] = useState(false); const set = (changes: Record, keepPage = false) => { const p = new URLSearchParams(params.toString()); @@ -79,6 +90,71 @@ export function EntitiesPage() { placeholderData: keepPreviousData, }); const rows = (list.data?.items ?? []) as unknown as EntityRow[]; + const pickable = rows.filter((e) => !e.builtin); + const toggle = (e: EntityRow, on: boolean) => + setPicked((m) => { + const next = new Map(m); + if (on) next.set(e.id, e); + else next.delete(e.id); + return next; + }); + const allOn = pickable.length > 0 && pickable.every((e) => picked.has(e.id)); + const someOn = pickable.some((e) => picked.has(e.id)); + + const mergePicked = async (keep: EntityRow) => { + const others = [...picked.values()].filter((e) => e.id !== keep.id); + if (await merge(keep, others)) { + setPicked(new Map()); + if (open && others.some((o) => o.id === open)) set({ entity: String(keep.id) }, true); + } + }; + // Give the picked ones one type; Undo puts each back to the type it had. + const retypePicked = async (type: string) => { + const before = [...picked.values()]; + const label = types.data?.find((t) => t.type === type)?.label ?? type; + const retype = (ids: number[], t: string) => data(Entities.retypeEntities({ client, body: { ids, type: t } })); + setRetyping(true); + try { + await retype( + before.map((e) => e.id), + type, + ); + refresh(); + setPicked(new Map()); + toast({ + title: `${plural(before.length, "entity", "entities")} ${before.length === 1 ? "is" : "are"} ${label} now`, + tone: "green", + duration: 10000, + action: { + label: "Undo", + onClick: () => { + const back = new Map(); + for (const e of before) back.set(e.type, [...(back.get(e.type) ?? []), e.id]); + void Promise.all([...back].map(([t, ids]) => retype(ids, t))) + .then(() => { + refresh(); + toast({ title: "Types put back", tone: "green" }); + }) + .catch((err) => + toast({ + title: "Couldn’t put the types back", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }), + ); + }, + }, + }); + } catch (err) { + toast({ + title: "Couldn’t change the type", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + } finally { + setRetyping(false); + } + }; if (!namespaces.length) return ( @@ -225,6 +301,16 @@ export function EntitiesPage() { + {editor && ( + + )} Name @@ -252,6 +338,17 @@ export function EntitiesPage() { className="h-[50px] cursor-pointer" onClick={() => set({ entity: String(e.id) }, true)} > + {editor && ( + + )}
+ pickable.forEach((e) => toggle(e, on))} + /> + Type Description ev.stopPropagation()}> + {!e.builtin && ( + toggle(e, on)} + /> + )} + + {canEdit && !builtin && ( + + )} ) } @@ -165,6 +227,12 @@ export function EntityDrawer({ {e.isError && {e.error.message}} {d && ( <> +
{[ ["Mentions", count(d.mentions)], @@ -295,6 +363,7 @@ export function EntityDrawer({ )} + {!builtin && }

Where it’s said

{mentions.isLoading && } From 91030cfdbf957b0045f73c79cf2a821362ba095f Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 07:52:05 +0000 Subject: [PATCH 2/3] test(clicks): count merging two entities and undoing it Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EzVhJCpwskyo5NhHEtS822 --- ci/clicks/journeys.mjs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/ci/clicks/journeys.mjs b/ci/clicks/journeys.mjs index 9eb44a377..ff26a04c4 100644 --- a/ci/clicks/journeys.mjs +++ b/ci/clicks/journeys.mjs @@ -639,6 +639,26 @@ export const JOURNEYS = [ await page.getByRole("heading", { name: "Alice", level: 1 }).waitFor(); }, }, + { + id: "entity-merge", + ns: "", + module: "Entities", + feature: "Merge two entities into one, then undo it", + note: "The merge happens at once and the notice has Undo, so nothing asks to confirm; Undo puts both back.", + from: "/", + async run(ctx) { + const { page, meter } = ctx; + await go(ctx, "Entities"); + const main = page.getByRole("main"); + await meter.click(main.getByRole("checkbox", { name: "Pick Lens", exact: true }), "tick Lens"); + await meter.click(main.getByRole("checkbox", { name: "Pick Raspberry Pi", exact: true }), "tick Raspberry Pi"); + const bar = page.getByRole("toolbar", { name: "2 entities selected" }); + await meter.click(bar.getByRole("button", { name: /^Merge into / }), "Merge into the one it keeps"); + await page.getByText(/^Merged (Lens|Raspberry Pi) into /).first().waitFor(); + await meter.click(page.getByRole("button", { name: "Undo" }), "Undo on the notice"); + await page.getByText("Merge undone").first().waitFor(); + }, + }, { // Last: it points Lens at a cloud model, which the stand-in model behind the journeys above isn't id: "cloud-model", From 846005c1c7e54be052a8dcb077ba9078a0bbdf53 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 08:07:47 +0000 Subject: [PATCH 3/3] test(clicks): merge entities in the namespace the imports went to Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EzVhJCpwskyo5NhHEtS822 --- ci/clicks/journeys.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ci/clicks/journeys.mjs b/ci/clicks/journeys.mjs index ff26a04c4..304f62509 100644 --- a/ci/clicks/journeys.mjs +++ b/ci/clicks/journeys.mjs @@ -641,7 +641,9 @@ export const JOURNEYS = [ }, { id: "entity-merge", - ns: "", + // the namespace the imports above went to: with all namespaces picked, Entities opens the first by name, which + // namespace-create has made the empty customer-calls + ns: "interviews", module: "Entities", feature: "Merge two entities into one, then undo it", note: "The merge happens at once and the notice has Undo, so nothing asks to confirm; Undo puts both back.",