Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
49.0 KB
Raw Blame
"""Case lifecycle, notes, entities and links through the REST API."""

import json
from pathlib import Path

import graph_read
from fastapi.testclient import TestClient

from azimut import layout
from azimut.workspace import Case


def test_health(client):
    assert client.get("/api/health").json()["status"] == "ok"


def test_entity_status_is_validated_consistently(client):
    cid = client.post("/api/cases", json={"name": "Statuses"}).json()["id"]
    invalid_create = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "person", "label": "Lead", "status": "pending"},
    )
    assert invalid_create.status_code == 422
    assert graph_read.entities(cid) == []

    entity = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "person", "label": "Lead", "status": "suggested"},
    ).json()
    invalid_patch = client.patch(
        f"/api/cases/{cid}/entities/{entity['id']}", json={"status": "pending"}
    )
    assert invalid_patch.status_code == 422
    saved = next(item for item in graph_read.entities(cid) if item["id"] == entity["id"])
    assert saved["provenance"]["status"] == "suggested"


def test_list_cases_filters_by_name(client):
    for name in ("Kharkiv Strike", "Bakhmut Front", "Kharkiv Bridge"):
        client.post("/api/cases", json={"name": name})

    hits = client.get("/api/cases", params={"q": "kharkiv"}).json()
    assert {c["name"] for c in hits} == {"Kharkiv Strike", "Kharkiv Bridge"}
    # unfiltered still returns everything
    assert len(client.get("/api/cases").json()) == 3


def test_list_cases_respects_limit(client):
    for name in ("One", "Two", "Three", "Four"):
        client.post("/api/cases", json={"name": name})
    assert len(client.get("/api/cases", params={"limit": 2}).json()) == 2


def test_case_search_folds_accents_and_matches_each_word(client, monkeypatch):
    for name in ("Étude du port", "Proof geo", "Other work"):
        client.post("/api/cases", json={"name": name})
    opened = []
    original = Case.entity_count

    def count(case):
        opened.append(case.id)
        return original(case)

    monkeypatch.setattr(Case, "entity_count", count)
    hits = client.get("/api/cases", params={"q": "  PORT etude "}).json()
    assert [case["name"] for case in hits] == ["Étude du port"]
    assert opened == ["Étude du port"]
    hits = client.get("/api/cases", params={"q": "geo proof"}).json()
    assert [case["name"] for case in hits] == ["Proof geo"]


def test_catalog_relevance_ranks_across_pages_with_folded_names(client):
    cid = client.post("/api/cases", json={"name": "Harbour"}).json()["id"]
    case = Case.open(cid)
    for label in ("Airport", "Notes from Port", "Pórt Sudan", "Port"):
        case.add_entity("note", label, {}, by="user")
    params = {"q": "port", "order": "relevance", "limit": 2}
    first = client.get(f"/api/cases/{cid}/catalog/entities", params=params)
    assert first.status_code == 200
    page = first.json()
    assert page["total"] == 4
    assert [item["label"] for item in page["items"]] == ["Port", "Pórt Sudan"]
    second = client.get(
        f"/api/cases/{cid}/catalog/entities", params={**params, "cursor": page["next_cursor"]}
    ).json()
    assert [item["label"] for item in second["items"]] == ["Notes from Port", "Airport"]
    assert second["next_cursor"] is None


def test_case_lifecycle(client):
    created = client.post("/api/cases", json={"name": "Kharkiv Strike"}).json()
    # The folder is the name the analyst typed, the way every other saved thing
    # already carries its own (`layout.case_folder_name`).
    assert created["id"] == "Kharkiv Strike"
    assert graph_read.entities(created["id"]) == []

    # duplicate name → 409
    assert client.post("/api/cases", json={"name": "Kharkiv Strike"}).status_code == 409

    listed = client.get("/api/cases").json()
    assert [c["id"] for c in listed] == ["Kharkiv Strike"]

    client.patch("/api/cases/Kharkiv Strike", json={"name": "Kharkiv Strike v2"})
    assert client.get("/api/cases/Kharkiv Strike").json()["name"] == "Kharkiv Strike v2"

    assert client.delete("/api/cases/Kharkiv Strike").json()["status"] == "deleted"
    assert client.get("/api/cases/Kharkiv Strike").status_code == 404


def test_duplicate_name_rejected_case_insensitively(client):
    client.post("/api/cases", json={"name": "Alpha Site"})

    # a differently-cased name maps to the same case → 409
    assert client.post("/api/cases", json={"name": "alpha site"}).status_code == 409
    # a genuinely new name is fine
    assert client.post("/api/cases", json={"name": "Beta Site"}).status_code == 200


def test_a_case_named_in_another_script_keeps_its_name(client):
    """The folder used to be an ASCII slug, so a name with no a–z in it landed on
    the fallback `case` — and the *second* such case could then never be created,
    refused over a folder whose name nobody had typed."""
    first = client.post("/api/cases", json={"name": "Маріуполь"})
    second = client.post("/api/cases", json={"name": "Харків"})

    assert first.status_code == 200 and second.status_code == 200
    assert first.json()["id"] == "Маріуполь"
    assert second.json()["id"] == "Харків"
    assert {c["name"] for c in client.get("/api/cases").json()} == {"Маріуполь", "Харків"}


def test_two_names_that_reduce_to_one_folder_both_get_a_case(client):
    """Different names, one folder: the folder is numbered, because it is the
    tool's business. Refusing there was a dead end the analyst could not resolve,
    and the case that already existed must come through untouched."""
    first = client.post("/api/cases", json={"name": "Kyiv: 4 June"}).json()
    client.put(f"/api/cases/{first['id']}/notes", json={"text": "# the first case\n"})

    second = client.post("/api/cases", json={"name": "Kyiv? 4 June"})

    assert second.status_code == 200
    assert second.json()["id"] != first["id"]
    # The first case still holds its own work — a new case never lands on one.
    assert "the first case" in client.get(f"/api/cases/{first['id']}/notes").json()["text"]
    assert len(client.get("/api/cases").json()) == 2


def test_a_name_that_would_break_its_own_url_is_filed_under_a_safe_folder(client):
    """`#` and `%` cut a URL path short, and the folder name is the case id."""
    created = client.post("/api/cases", json={"name": "Sortie #4 (100% sûr)"}).json()

    assert "#" not in created["id"] and "%" not in created["id"]
    assert created["name"] == "Sortie #4 (100% sûr)"  # what the analyst sees is kept
    assert client.get(f"/api/cases/{created['id']}").status_code == 200


def test_rename_rejects_existing_name_but_allows_self(client):
    a = client.post("/api/cases", json={"name": "One"}).json()
    client.post("/api/cases", json={"name": "Two"})

    # renaming onto another case's name (any casing) → 409
    assert client.patch(f"/api/cases/{a['id']}", json={"name": "two"}).status_code == 409
    # renaming to its own current name is allowed (no false positive)
    assert client.patch(f"/api/cases/{a['id']}", json={"name": "One"}).status_code == 200


def test_promote_rejects_existing_name(client):
    client.post("/api/cases", json={"name": "Taken"})
    scratch = client.post("/api/cases/scratch").json()
    res = client.post(f"/api/cases/{scratch['id']}/promote", json={"name": "Taken"})
    assert res.status_code == 409


def test_delete_wipes_whole_case_folder(client):
    import azimut.config as cfg

    cid = client.post("/api/cases", json={"name": "Doomed"}).json()["id"]
    # plant content across subdirs so we can prove the whole tree is gone
    _plant_capture(client, cid)
    case_dir = cfg.cases_dir() / cid
    assert case_dir.exists()

    assert client.delete(f"/api/cases/{cid}").json()["status"] == "deleted"
    assert not case_dir.exists()
    assert client.get(f"/api/cases/{cid}").status_code == 404


def test_scratch_promote(client):
    scratch = client.post("/api/cases/scratch").json()
    assert scratch["id"].startswith("scratch_")
    assert client.get(f"/api/cases/{scratch['id']}").json()["scratch"] is True

    promoted = client.post(
        f"/api/cases/{scratch['id']}/promote", json={"name": "Real Case"}
    ).json()
    assert promoted["id"] == "Real Case"
    assert client.get(f"/api/cases/{promoted['id']}").json()["scratch"] is False
    # old scratch id is gone
    assert client.get(f"/api/cases/{scratch['id']}").status_code == 404


def test_notes_roundtrip(client):
    case = client.post("/api/cases", json={"name": "Notes"}).json()
    client.put(f"/api/cases/{case['id']}/notes", json={"text": "# hello\n\nworld"})
    assert client.get(f"/api/cases/{case['id']}/notes").json()["text"] == "# hello\n\nworld"


def test_filed_notes_are_markdown_files(client):

    cid = client.post("/api/cases", json={"name": "Notebook"}).json()["id"]
    note = client.post(
        f"/api/cases/{cid}/notes",
        json={"title": "Lead", "folder": "Research", "content": "# First lead"},
    ).json()

    # the name is the filename, and the notebook's folder is mirrored on disk
    assert note["attrs"] == {"folder": "Research", "path": "notes/Research/Lead.md"}
    assert Case.open(cid).resolve_inside(note["attrs"]["path"]).read_text(
        encoding="utf-8"
    ) == "# First lead"
    assert client.get(f"/api/cases/{cid}/notes/{note['id']}").json()["text"] == "# First lead"

    client.put(f"/api/cases/{cid}/notes/{note['id']}", json={"text": "Updated"})
    assert client.get(f"/api/cases/{cid}/notes/{note['id']}").json()["text"] == "Updated"


def test_a_report_note_records_the_case_files_it_was_written_from(client):
    """A note composed out of case files is an artifact made from them, and says so.

    Without this the report note was the one filed artifact with no chain: its images
    pointed at a proof and its media that nothing in the graph knew it depended on, so
    Details showed "nothing filed against this" on a page full of evidence.
    """
    cid = client.post("/api/cases", json={"name": "Report chain"}).json()["id"]
    case = Case.open(cid)
    proof = case.add_entity("proof", "Convoy", {"path": "proofs/convoy.png"}, by="proof-composer")
    photo = case.add_entity("media", "clip.jpg", {"path": "media/clip.jpg"}, by="user")

    note = client.post(
        f"/api/cases/{cid}/notes",
        json={
            "title": "Convoy report",
            "content": "![](proofs/convoy.png)",
            "sources": ["proofs/convoy.png", "media/clip.jpg"],
        },
    ).json()

    chain = client.get(f"/api/cases/{cid}/entities/{note['id']}/chain").json()
    assert {row["entity"]["id"] for row in chain["sources"]} == {proof["id"], photo["id"]}
    assert {row["type"] for row in chain["sources"]} == {"derived-from"}
    # and the other way round: the proof knows the report leans on it
    proof_chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()
    assert [row["entity"]["id"] for row in proof_chain["dependents"]] == [note["id"]]


def test_a_note_typed_by_hand_files_no_chain_at_all(client):
    """Most notes are written, not composed. Sending no sources must leave the note
    exactly as it has always been, with no edge invented for it."""
    cid = client.post("/api/cases", json={"name": "Plain note"}).json()["id"]

    note = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead"}).json()

    chain = client.get(f"/api/cases/{cid}/entities/{note['id']}/chain").json()
    assert chain["sources"] == [] and chain["lost"] == []


def test_a_report_source_that_is_already_gone_is_kept_as_a_tombstone(client):
    """A proof deleted while the composer was open cannot be linked, but the fact that
    the report was written from it is not dropped in silence."""
    cid = client.post("/api/cases", json={"name": "Vanished source"}).json()["id"]

    note = client.post(
        f"/api/cases/{cid}/notes",
        json={"title": "Report", "sources": ["proofs/gone.png"]},
    ).json()

    chain = client.get(f"/api/cases/{cid}/entities/{note['id']}/chain").json()
    assert chain["sources"] == []
    assert [lost["path"] for lost in chain["lost"]] == ["proofs/gone.png"]


def _sources_of(client, cid, note_id):
    chain = client.get(f"/api/cases/{cid}/entities/{note_id}/chain").json()
    return {row["entity"]["id"] for row in chain["sources"]}


def test_a_note_restates_its_chain_from_its_own_body_on_every_save(client):
    """The Notebook inserts case media at any time, so birth is not when a note's
    chain is settled.

    An image added afterwards was a dependency nothing in the graph knew about —
    deleting it left the note showing a hole — and one taken out of the text left a
    scar the note had stopped earning.
    """
    cid = client.post("/api/cases", json={"name": "Note body chain"}).json()["id"]
    case = Case.open(cid)
    proof = case.add_entity("proof", "Convoy", {"path": "proofs/convoy.png"}, by="proof-composer")
    photo = case.add_entity("media", "clip.jpg", {"path": "media/clip.jpg"}, by="user")
    note = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead"}).json()
    assert _sources_of(client, cid, note["id"]) == set()

    client.put(
        f"/api/cases/{cid}/notes/{note['id']}",
        json={"text": f"# Lead\n\n[[media:{proof['id']}|Convoy]]\n[[media:{photo['id']}|clip]]"},
    )
    assert _sources_of(client, cid, note["id"]) == {proof["id"], photo["id"]}

    # the photo is taken back out: the edge goes with it
    client.put(
        f"/api/cases/{cid}/notes/{note['id']}",
        json={"text": f"# Lead\n\n[[media:{proof['id']}|Convoy]]"},
    )
    assert _sources_of(client, cid, note["id"]) == {proof["id"]}


def test_saving_a_report_keeps_the_draft_it_was_composed_in(client):
    """The body names the files it shows; it cannot name the draft. So a body-driven
    restatement reconciles only what the text speaks for, or the first edit to a
    report would quietly drop the post it came out of."""
    cid = client.post("/api/cases", json={"name": "Report draft"}).json()["id"]
    case = Case.open(cid)
    post = case.add_entity("post", "Thread", {"draft": ".drafts/thread.json"}, by="post-composer")
    proof = case.add_entity("proof", "Convoy", {"path": "proofs/convoy.png"}, by="proof-composer")
    note = client.post(
        f"/api/cases/{cid}/notes",
        json={"title": "Report", "sources": [".drafts/thread.json", "proofs/convoy.png"]},
    ).json()
    assert _sources_of(client, cid, note["id"]) == {post["id"], proof["id"]}

    client.put(
        f"/api/cases/{cid}/notes/{note['id']}",
        json={"text": f"# Report\n\n[[media:{proof['id']}|Convoy]]"},
    )

    assert _sources_of(client, cid, note["id"]) == {post["id"], proof["id"]}


def test_a_note_body_naming_something_unjoinable_still_saves(client):
    """A body is prose. A token pointing at a place, at a missing id or at the note
    itself is skipped, never a 400 that loses the analyst's writing."""
    cid = client.post("/api/cases", json={"name": "Odd tokens"}).json()["id"]
    case = Case.open(cid)
    place = case.add_entity("place", "Quay", {"lat": 1.0, "lon": 2.0}, by="user")
    note = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead"}).json()

    saved = client.put(
        f"/api/cases/{cid}/notes/{note['id']}",
        json={
            "text": (
                f"[[media:{place['id']}|Quay]] [[media:e_missing|Gone]] "
                f"[[media:{note['id']}|Itself]] [[entity:{place['id']}|Quay]]"
            )
        },
    )

    assert saved.status_code == 200
    assert _sources_of(client, cid, note["id"]) == set()


def test_deleting_filed_note_removes_markdown_file(client):

    cid = client.post("/api/cases", json={"name": "Notebook delete"}).json()["id"]
    note = client.post(f"/api/cases/{cid}/notes", json={"title": "Disposable"}).json()
    path = Case.open(cid).resolve_inside(note["attrs"]["path"])
    assert path.exists()

    client.delete(f"/api/cases/{cid}/entities/{note['id']}")
    assert not path.exists()


def test_entities_and_deletion_cleanup(client):
    cid = client.post("/api/cases", json={"name": "Graph"}).json()["id"]

    person = client.post(
        f"/api/cases/{cid}/entities", json={"type": "person", "label": "John Doe"}
    ).json()
    account = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "account", "label": "@johnd", "status": "suggested"},
    ).json()
    assert person["provenance"]["status"] == "confirmed"
    assert account["provenance"]["status"] == "suggested"

    # confirm the suggestion (spec §3.5: analyst decides)
    patched = client.patch(
        f"/api/cases/{cid}/entities/{account['id']}", json={"status": "confirmed"}
    ).json()
    assert patched["provenance"]["status"] == "confirmed"

    from azimut.workspace import Case

    link = Case.open(cid).add_link(person["id"], account["id"], "owns", by="user")
    assert link["type"] == "owns"

    # deleting an entity cascades to its links
    client.delete(f"/api/cases/{cid}/entities/{account['id']}")
    assert len(graph_read.entities(cid)) == 1
    assert graph_read.links(cid) == []


def test_catalog_pagination_and_summary(client):
    cid = client.post("/api/cases", json={"name": "Catalog"}).json()["id"]
    for i in range(5):
        client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": f"P{i}"})
    client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "account", "label": "@acct", "status": "suggested"},
    )

    # walk the whole catalog in bounded pages
    seen: list[str] = []
    cursor = None
    while True:
        params: dict[str, object] = {"limit": 2}
        if cursor:
            params["cursor"] = cursor
        page = client.get(f"/api/cases/{cid}/catalog/entities", params=params).json()
        assert len(page["items"]) <= 2
        seen.extend(e["label"] for e in page["items"])
        cursor = page["next_cursor"]
        if not cursor:
            break
    assert seen == ["P0", "P1", "P2", "P3", "P4", "@acct"]

    # server-side filters
    people = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"type": "person"}
    ).json()
    assert {e["label"] for e in people["items"]} == {"P0", "P1", "P2", "P3", "P4"}
    suggested = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"status": "suggested"}
    ).json()
    assert [e["label"] for e in suggested["items"]] == ["@acct"]

    # summary counts without shipping the graph
    summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
    assert summary["total"] == 6
    assert summary["by_type"] == {"person": 5, "account": 1}
    assert summary["by_status"] == {"confirmed": 5, "suggested": 1}


def test_catalog_filters_by_folder(client):
    cid = client.post("/api/cases", json={"name": "Foldered"}).json()["id"]
    client.post(f"/api/cases/{cid}/folders", json={"name": "Alpha"})
    client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "person", "label": "filed", "attrs": {"folder": "Alpha"}},
    )
    client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": "loose"})

    in_alpha = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"folder": "Alpha"}
    ).json()
    assert [e["label"] for e in in_alpha["items"]] == ["filed"]

    unfiled = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"unfiled": "true"}
    ).json()
    assert [e["label"] for e in unfiled["items"]] == ["loose"]

    assert client.get(f"/api/cases/{cid}/catalog/summary").json()["by_folder"] == {"Alpha": 1}


def test_catalog_summary_counts_accepted_rows_apart(client):
    """Files, the sidebar and Home's Unfiled list accepted rows only, with suggestions
    under review. Counted over every row, Home said 18 unfiled where the sidebar
    beside it said 15."""
    cid = client.post("/api/cases", json={"name": "Review"}).json()["id"]
    client.post(f"/api/cases/{cid}/folders", json={"name": "Alpha"})
    for label, folder, status in (
        ("kept", "Alpha", "confirmed"),
        ("loose", None, "confirmed"),
        ("proposed", None, "suggested"),
        ("proposed here", "Alpha", "suggested"),
    ):
        attrs = {"folder": folder} if folder else {}
        client.post(
            f"/api/cases/{cid}/entities",
            json={"type": "person", "label": label, "attrs": attrs, "status": status},
        )

    summary = client.get(f"/api/cases/{cid}/catalog/summary").json()

    assert summary["by_folder"] == {"Alpha": 2}
    assert summary["confirmed"] == {"by_type": {"person": 2}, "by_folder": {"Alpha": 1}, "unfiled": 1}
    sidebar = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"unfiled": "true", "status": "confirmed"}
    ).json()
    assert sidebar["total"] == summary["confirmed"]["unfiled"]


def test_catalog_searches_notes_and_descendant_folders(client):
    cid = client.post("/api/cases", json={"name": "Search"}).json()["id"]
    client.post(
        f"/api/cases/{cid}/entities",
        json={
            "type": "media",
            "label": "frame",
            "attrs": {"folder": "Sources/Telegram", "notes": "bridge crossing"},
        },
    )
    client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "media", "label": "other", "attrs": {"folder": "Research"}},
    )

    page = client.get(
        f"/api/cases/{cid}/catalog/entities",
        params={"folder": "Sources", "recursive": "true", "q": "bridge"},
    ).json()
    assert page["total"] == 1
    assert [entity["label"] for entity in page["items"]] == ["frame"]


def test_catalog_answers_which_videos_have_coordinates(client):
    """The sentence the Board can now ask, term by term, each chosen from the case:
    *media, kind video, linked to a place.* The count is the answer and the page is
    which ones — and neither was expressible anywhere in the app before."""
    cid = client.post("/api/cases", json={"name": "Sentence"}).json()["id"]

    def entity(type_, label, attrs=None):
        return client.post(
            f"/api/cases/{cid}/entities",
            json={"type": type_, "label": label, "attrs": attrs or {}},
        ).json()["id"]

    placed = entity("media", "clip.mp4", {"kind": "video"})
    entity("media", "orphan.mp4", {"kind": "video"})
    entity("media", "still.jpg", {"kind": "image"})
    quay = entity("place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
    client.post(
        f"/api/cases/{cid}/links",
        json={"from_id": placed, "to_id": quay, "type": "located-at"},
    )

    page = client.get(
        f"/api/cases/{cid}/catalog/entities",
        params={"type": "media", "attr": "kind", "value": "video", "linked": "place"},
    ).json()
    assert page["total"] == 1
    assert [row["id"] for row in page["items"]] == [placed]


def test_the_field_and_value_menus_are_populated_from_the_case(client):
    """No query language: every term of a search is chosen from what the case holds.
    Including `kind`, which the vocabulary declares nowhere."""
    cid = client.post("/api/cases", json={"name": "Menus"}).json()["id"]
    for label, kind in (("a.mp4", "video"), ("b.mp4", "video"), ("c.jpg", "image")):
        client.post(
            f"/api/cases/{cid}/entities",
            json={"type": "media", "label": label, "attrs": {"kind": kind}},
        )

    body = client.get(
        f"/api/cases/{cid}/catalog/attributes", params={"type": "media"}
    ).json()
    kinds = next(row for row in body["attrs"] if row["key"] == "kind")
    assert kinds["entities"] == 3
    assert kinds["values"] == [
        {"value": "video", "count": 2},
        {"value": "image", "count": 1},
    ]


def test_catalog_lists_what_the_case_connects_to_nothing(client):
    """The case's unexploited material, and the one question the catalog could not
    ask: the graph counts these, but counting is not reaching them."""
    cid = client.post("/api/cases", json={"name": "Loose"}).json()["id"]

    def entity(type_, label, attrs=None):
        return client.post(
            f"/api/cases/{cid}/entities",
            json={"type": type_, "label": label, "attrs": attrs or {}},
        ).json()["id"]

    joined = entity("media", "clip.mp4", {"kind": "video"})
    quay = entity("place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
    alone = entity("media", "orphan.mp4", {"kind": "video"})
    linked = client.post(
        f"/api/cases/{cid}/links",
        json={"from_id": joined, "to_id": quay, "type": "located-at"},
    )
    assert linked.status_code == 200

    page = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"unlinked": "true"}
    ).json()
    assert page["total"] == 1
    assert [row["id"] for row in page["items"]] == [alone]
    # and the summary states the same number, so the menu can price the term before
    # it is chosen rather than landing the analyst on an empty table
    assert client.get(f"/api/cases/{cid}/catalog/summary").json()["unlinked"] == 1


def test_catalog_lists_the_claims_with_no_source_or_no_assessment(client):
    cid = client.post("/api/cases", json={"name": "Waiting"}).json()["id"]
    clip = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "media", "label": "clip.mp4", "attrs": {"kind": "video"}},
    ).json()["id"]

    def claim(statement, **extra):
        body = {"statement": statement, **extra}
        response = client.post(f"/api/cases/{cid}/timeline/claims", json=body)
        assert response.status_code == 200, response.text
        return response.json()["entity"]["id"]

    bare = claim("Heard of it")
    graded = claim("Graded, no source", confidence="probable")
    sourced = claim("Sourced, not graded", cites=[clip])
    whole = claim("Sourced and graded", cites=[clip], confidence="certain")

    def ids(**params):
        page = client.get(f"/api/cases/{cid}/catalog/entities", params=params)
        assert page.status_code == 200, page.text
        return {row["id"] for row in page.json()["items"]}

    # The media is neither: a file is its own source and nothing grades it.
    assert ids(lacks="source") == {bare, graded}
    assert ids(lacks="assessment") == {bare, sourced}
    assert ids(lacks="source,assessment") == {bare}
    assert whole not in ids(lacks="source") | ids(lacks="assessment")
    # The graph route asks the same predicate.
    drawn = client.get(f"/api/cases/{cid}/graph", params={"lacks": "source"}).json()
    assert {node["id"] for node in drawn["nodes"]} >= {bare, graded}
    assert sourced not in {node["id"] for node in drawn["nodes"]}
    refused = client.get(f"/api/cases/{cid}/catalog/entities", params={"lacks": "photo"})
    assert refused.status_code == 400


def test_the_summary_prices_linked_to_by_what_it_would_answer_with(client):
    """Four media pointing at one place is **four** under "linked to a place" and one
    under "type: place". The filter asks the first, so the menu has to price the
    first — a count answering the neighbouring question looks like an answer and is
    not one, which is exactly how a menu stops being trusted."""
    cid = client.post("/api/cases", json={"name": "Counts"}).json()["id"]

    def entity(type_, label, attrs=None):
        return client.post(
            f"/api/cases/{cid}/entities",
            json={"type": type_, "label": label, "attrs": attrs or {}},
        ).json()["id"]

    quay = entity("place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
    for i in range(4):
        clip = entity("media", f"clip{i}.mp4", {"kind": "video"})
        client.post(
            f"/api/cases/{cid}/links",
            json={"from_id": clip, "to_id": quay, "type": "located-at"},
        )

    summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
    assert summary["by_type"]["place"] == 1  # the case holds one place
    assert summary["linked_to"]["place"] == 4  # four things touch it
    assert summary["linked_to"]["media"] == 1  # and it touches four, which is one row

    # and the filter itself answers with exactly what the menu promised
    page = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"linked": "place"}
    ).json()
    assert page["total"] == 4


def test_a_pair_joined_twice_counts_once_in_the_menu(client):
    """A media joined to one place by two verbs is one row that is linked to a place,
    not two — or the menu promises more than the table can hand back."""
    cid = client.post("/api/cases", json={"name": "Twice"}).json()["id"]
    clip = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "media", "label": "clip.mp4", "attrs": {"kind": "video"}},
    ).json()["id"]
    quay = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "place", "label": "48.0, 2.0", "attrs": {"lat": 48.0, "lon": 2.0}},
    ).json()["id"]
    for verb in ("located-at", "depicts"):
        client.post(
            f"/api/cases/{cid}/links", json={"from_id": clip, "to_id": quay, "type": verb}
        )

    summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
    assert summary["linked_to"]["place"] == 1
    assert (
        client.get(f"/api/cases/{cid}/catalog/entities", params={"linked": "place"}).json()[
            "total"
        ]
        == 1
    )


def test_catalog_narrows_on_when_a_row_was_filed(client, monkeypatch):
    """*What came in this week* is a question about the case, and `prov_at` already
    holds the answer. A bare date reaches the whole of that day at both ends."""
    cid = client.post("/api/cases", json={"name": "Dates"}).json()["id"]
    for label, at in (
        ("old", "2026-07-01T09:00:00Z"),
        ("edge", "2026-08-10T23:59:59Z"),
        ("new", "2026-08-11T08:00:00Z"),
    ):
        monkeypatch.setattr("azimut.sqlite_backend._now", lambda at=at: at)
        client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": label})

    page = client.get(
        f"/api/cases/{cid}/catalog/entities",
        params={"since": "2026-08-01", "until": "2026-08-10"},
    ).json()
    # the row filed a second before midnight is inside the day it was filed on
    assert [row["label"] for row in page["items"]] == ["edge"]
    assert page["total"] == 1


def test_catalog_tells_what_a_tool_proposed_from_what_was_entered_by_hand(client):
    """`provenance.by` is the difference between the case's own work and a machine's,
    and the menu is populated from the case like every other term."""
    cid = client.post("/api/cases", json={"name": "Filers"}).json()["id"]
    client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": "typed"})
    client.post(f"/api/cases/{cid}/entities", json={"type": "place", "label": "48.0, 2.0"})

    summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
    assert summary["by_source"] == {"user": 2}

    page = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"by": "user"}
    ).json()
    assert page["total"] == 2
    assert client.get(
        f"/api/cases/{cid}/catalog/entities", params={"by": "satellite"}
    ).json()["total"] == 0


def test_catalog_sorts_the_case_rather_than_the_page(client, monkeypatch):
    """The difference an ordering makes: *the newest in this case* is not *the newest
    of the rows one page happened to load*, which is all a client-side sort can say."""
    cid = client.post("/api/cases", json={"name": "Order"}).json()["id"]
    for label, at in (
        ("first", "2026-07-01T09:00:00Z"),
        ("second", "2026-07-02T09:00:00Z"),
        ("third", "2026-07-03T09:00:00Z"),
    ):
        monkeypatch.setattr("azimut.sqlite_backend._now", lambda at=at: at)
        client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": label})

    page = client.get(
        f"/api/cases/{cid}/catalog/entities", params={"order": "-created", "limit": 2}
    ).json()
    assert [row["label"] for row in page["items"]] == ["third", "second"]
    rest = client.get(
        f"/api/cases/{cid}/catalog/entities",
        params={"order": "-created", "limit": 2, "cursor": page["next_cursor"]},
    ).json()
    assert [row["label"] for row in rest["items"]] == ["first"]
    assert rest["next_cursor"] is None


def test_catalog_refuses_an_ordering_it_does_not_have(client):
    cid = client.post("/api/cases", json={"name": "BadOrder"}).json()["id"]
    res = client.get(f"/api/cases/{cid}/catalog/entities", params={"order": "size"})
    assert res.status_code == 400


def test_a_field_name_the_store_cannot_ask_for_is_refused(client):
    cid = client.post("/api/cases", json={"name": "BadField"}).json()["id"]
    res = client.get(
        f"/api/cases/{cid}/catalog/entities",
        params={"attr": 'kind"] or 1=1 --', "value": "video"},
    )
    assert res.status_code == 400


def test_catalog_rejects_a_bad_cursor(client):
    cid = client.post("/api/cases", json={"name": "BadCursor"}).json()["id"]
    res = client.get(f"/api/cases/{cid}/catalog/entities", params={"cursor": "not-an-int"})
    assert res.status_code == 400


def test_catalog_clamps_the_page_size(client):
    cid = client.post("/api/cases", json={"name": "Clamp"}).json()["id"]
    for i in range(3):
        client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": f"P{i}"})
    # a limit below 1 is clamped up to 1 so a page always makes progress
    page = client.get(f"/api/cases/{cid}/catalog/entities", params={"limit": 0}).json()
    assert len(page["items"]) == 1 and page["next_cursor"] is not None


# ---------------------------------------------------------------------------
# Satellite capture notes (PATCH /api/cases/{id}/satellite)
# Uses a pre-written sidecar to avoid a live tile fetch.
# ---------------------------------------------------------------------------



def _plant_capture(client, cid: str) -> dict:
    """File a fake satellite capture through the media pipeline (its real store)."""
    from PIL import Image

    from azimut.engine import media as media_engine
    from azimut.workspace import Case

    prov = {
        "provider": "esri-world-imagery",
        "provider_label": "Esri World Imagery",
        "zoom": 16,
        "lat": 50.0,
        "lon": 30.0,
        "bearing": 0.0,
        "fetched_at": "2026-07-08T12:00:00Z",
        "tiles": 9,
        "tiles_missing": 0,
    }
    result = media_engine.import_image(
        Case.open(cid),
        Image.new("RGB", (32, 32), (10, 120, 10)),
        "sat_test_z16_esri.png",
        {"type": "satellite", **prov},
        by="satellite",
        entity_type="capture",
        extra_attrs={"coords": "50.000000, 30.000000", "lat": 50.0, "lon": 30.0,
                     "zoom": 16, "bearing": 0.0},
        title="50.000000, 30.000000",
        dedupe=False,
    )
    return {"path": result["item"]["path"], **prov}


def test_satellite_patch_notes(client):
    cid = client.post("/api/cases", json={"name": "SatNotes"}).json()["id"]
    capture = _plant_capture(client, cid)

    updated = client.patch(
        f"/api/cases/{cid}/satellite",
        json={"path": capture["path"], "notes": "good reference point"},
    ).json()
    assert updated["notes"] == "good reference point"

    # persisted: shows up in listing
    listed = client.get(f"/api/cases/{cid}/satellite").json()
    assert listed[0]["notes"] == "good reference point"


def test_satellite_patch_clear_notes(client):
    cid = client.post("/api/cases", json={"name": "SatClear"}).json()["id"]
    capture = _plant_capture(client, cid)

    client.patch(
        f"/api/cases/{cid}/satellite",
        json={"path": capture["path"], "notes": "initial"},
    )
    updated = client.patch(
        f"/api/cases/{cid}/satellite",
        json={"path": capture["path"], "notes": ""},
    ).json()
    assert "notes" not in updated


def test_satellite_patch_not_found(client):
    cid = client.post("/api/cases", json={"name": "SatMissing"}).json()["id"]
    res = client.patch(
        f"/api/cases/{cid}/satellite",
        json={"path": "satellite/nonexistent.png", "notes": "x"},
    )
    assert res.status_code == 404


# ---------------------------------------------------------------------------
# Folders (case-level organisational buckets)
# ---------------------------------------------------------------------------


def test_folders_crud(client):
    cid = client.post("/api/cases", json={"name": "Folders"}).json()["id"]

    # empty by default
    assert client.get(f"/api/cases/{cid}/folders").json() == []

    # create, deduped and sorted case-insensitively
    client.post(f"/api/cases/{cid}/folders", json={"name": "Videos"})
    folders = client.post(f"/api/cases/{cid}/folders", json={"name": "Aerial"}).json()
    assert folders == ["Aerial", "Videos"]
    # idempotent
    assert client.post(f"/api/cases/{cid}/folders", json={"name": "Videos"}).json() == [
        "Aerial",
        "Videos",
    ]

    # persisted in case.json
    assert client.get(f"/api/cases/{cid}").json()["folders"] == ["Aerial", "Videos"]

    # delete
    remaining = client.delete(f"/api/cases/{cid}/folders", params={"name": "Videos"}).json()
    assert remaining == ["Aerial"]


def test_delete_folder_unassigns_entities(client):
    cid = client.post("/api/cases", json={"name": "Unassign"}).json()["id"]
    client.post(f"/api/cases/{cid}/folders", json={"name": "Suspects"})
    ent = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "person", "label": "John", "attrs": {"folder": "Suspects"}},
    ).json()

    client.delete(f"/api/cases/{cid}/folders", params={"name": "Suspects"})
    data = client.get(f"/api/cases/{cid}").json()
    assert data["folders"] == []
    entity = next(e for e in graph_read.entities(cid) if e["id"] == ent["id"])
    assert "folder" not in entity["attrs"]


def test_nested_folder_materialises_ancestors(client):
    cid = client.post("/api/cases", json={"name": "Nested"}).json()["id"]

    # creating a leaf path also creates every ancestor node
    folders = client.post(
        f"/api/cases/{cid}/folders", json={"name": "Sources/Telegram/Group A"}
    ).json()
    assert folders == ["Sources", "Sources/Telegram", "Sources/Telegram/Group A"]

    # segments are trimmed and empty ones dropped
    folders = client.post(
        f"/api/cases/{cid}/folders", json={"name": " Sources / Signal "}
    ).json()
    assert "Sources/Signal" in folders


def test_delete_folder_cascades_subtree(client):
    cid = client.post("/api/cases", json={"name": "Cascade"}).json()["id"]
    client.post(f"/api/cases/{cid}/folders", json={"name": "Sources/Telegram"})
    deep = client.post(
        f"/api/cases/{cid}/entities",
        json={"type": "note", "label": "chat log",
              "attrs": {"folder": "Sources/Telegram"}},
    ).json()

    # deleting the parent removes the whole subtree and unfiles its entities
    remaining = client.delete(
        f"/api/cases/{cid}/folders", params={"name": "Sources"}
    ).json()
    assert remaining == []
    entity = next(e for e in graph_read.entities(cid) if e["id"] == deep["id"])
    assert "folder" not in entity["attrs"]


def test_delete_media_entity_removes_file(client):
    import io

    cid = client.post("/api/cases", json={"name": "Sync"}).json()["id"]
    png = (
        b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
        b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00"
        b"\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82"
    )
    item = client.post(
        f"/api/cases/{cid}/media/upload",
        files={"file": ("frame.png", io.BytesIO(png), "image/png")},
    ).json()["item"]
    entity = next(
        e for e in graph_read.entities(cid)
        if e["type"] == "media"
    )

    # deleting the media entity from the sidebar deletes the underlying file too
    client.delete(f"/api/cases/{cid}/entities/{entity['id']}")
    assert client.get(f"/files/{cid}/{item['path']}").status_code == 404
    assert not any(
        e["type"] == "media" for e in graph_read.entities(cid)
    )



def test_cleanup_scratch_reaps_only_old_empty_sessions(tmp_workspace):
    import json as jsonlib

    from azimut.workspace import Case

    old_stamp = "2000-01-01T00:00:00Z"

    def _age(case):
        data = jsonlib.loads(case.json_path.read_text(encoding="utf-8"))
        data["updated_at"] = old_stamp
        case.json_path.write_text(jsonlib.dumps(data), encoding="utf-8")

    # old and empty → reaped
    empty_old = Case.create("Scratch session", scratch=True)
    _age(empty_old)
    # old but holding an entity → kept
    with_entity = Case.create("Scratch session", scratch=True)
    with_entity.add_entity("place", "Somewhere", attrs={}, by="test")
    _age(with_entity)
    # old but holding a media file → kept
    with_file = Case.create("Scratch session", scratch=True)
    (with_file.subdir("media") / "shot.png").write_bytes(b"png")
    _age(with_file)
    # fresh and empty → kept (it may be in use right now)
    empty_new = Case.create("Scratch session", scratch=True)

    assert Case.cleanup_scratch() == 1
    assert not empty_old.path.exists()
    assert with_entity.path.exists()
    assert with_file.path.exists()
    assert empty_new.path.exists()


def test_cleanup_scratch_treats_a_stranded_sidecar_temp_file_as_debris(tmp_workspace):
    """A sidecar write renames a scratch file into place. A power cut in that window
    strands one, and counting it as content would keep an empty scratch session
    alive forever — the exact accumulation cleanup exists to stop."""
    import json as jsonlib

    from azimut.workspace import Case

    stranded = Case.create("Scratch session", scratch=True)
    (stranded.subdir("media") / ".shot.png.azimut.json.deadbeef.tmp").write_bytes(b"{}")
    data = jsonlib.loads(stranded.json_path.read_text(encoding="utf-8"))
    data["updated_at"] = "2000-01-01T00:00:00Z"
    stranded.json_path.write_text(jsonlib.dumps(data), encoding="utf-8")

    assert Case.cleanup_scratch() == 1
    assert not stranded.path.exists()


def test_renaming_a_note_moves_its_file(client):
    """The name is the filename, as it already is for proofs, sessions and
    drafts. Notes were the last holdout."""
    cid = client.post("/api/cases", json={"name": "Renames"}).json()["id"]
    note = client.post(
        f"/api/cases/{cid}/notes",
        json={"title": "Draft lead", "folder": "Research", "content": "# body"},
    ).json()
    case = Case.open(cid)
    assert note["attrs"]["path"] == "notes/Research/Draft lead.md"

    renamed = client.patch(
        f"/api/cases/{cid}/entities/{note['id']}", json={"label": "Confirmed lead"}
    ).json()

    assert renamed["attrs"]["path"] == "notes/Research/Confirmed lead.md"
    assert case.resolve_inside(renamed["attrs"]["path"]).read_text(encoding="utf-8") == "# body"
    assert not case.resolve_inside(note["attrs"]["path"]).exists()


def test_moving_a_note_between_folders_moves_its_file(client):
    """The notebook's tree is mirrored on disk, so filing a note is a move."""
    cid = client.post("/api/cases", json={"name": "Filing"}).json()["id"]
    note = client.post(
        f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 1"}
    ).json()
    case = Case.open(cid)
    assert note["attrs"]["path"] == "notes/Video 1/Summary.md"

    moved = client.patch(
        f"/api/cases/{cid}/entities/{note['id']}", json={"attrs": {"folder": "Video 2"}}
    ).json()

    assert moved["attrs"]["path"] == "notes/Video 2/Summary.md"
    # the emptied folder does not linger: a mirror that keeps every directory a
    # note passed through stops being a mirror
    assert not case.resolve_inside("notes/Video 1").exists()


def test_a_note_moves_cleanly_under_a_symlinked_workspace(monkeypatch, tmp_path):
    """The same move, reached through a symlink, still prunes what it emptied.

    macOS reaches every temporary directory as `/var` → `/private/var`, and a
    workspace under a linked or synced folder does the same anywhere. The case
    knows its directory by the path it was given while `resolve_inside` hands
    back the resolved one, so a containment check comparing the two spellings
    answers "outside" about a directory that is inside — and the pruning it
    guards silently stops happening.
    """
    real = tmp_path / "real"
    real.mkdir()
    linked = tmp_path / "linked"
    linked.symlink_to(real, target_is_directory=True)
    monkeypatch.setenv("AZIMUT_HOME", str(linked))
    from azimut.server import create_app

    with TestClient(create_app(), base_url="http://127.0.0.1") as client:
        cid = client.post("/api/cases", json={"name": "Filing"}).json()["id"]
        note = client.post(
            f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 1"}
        ).json()
        case = Case.open(cid)
        assert case.resolve_inside(note["attrs"]["path"]).is_file()

        client.patch(
            f"/api/cases/{cid}/entities/{note['id']}", json={"attrs": {"folder": "Video 2"}}
        )

        assert not case.resolve_inside("notes/Video 1").exists()


def test_the_same_title_lives_in_two_folders(client):
    """Uniqueness is scoped to the folder. This is why the tree is mirrored at
    all: one folder per video is the analyst's whole workflow."""
    cid = client.post("/api/cases", json={"name": "Two videos"}).json()["id"]
    first = client.post(
        f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 1"}
    ).json()
    second = client.post(
        f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 2"}
    ).json()

    assert first["attrs"]["path"] == "notes/Video 1/Summary.md"
    assert second["attrs"]["path"] == "notes/Video 2/Summary.md"


def test_the_same_title_twice_in_one_folder_takes_a_suffix(client):
    """A note is the most frequent thing an analyst creates, so a taken name is
    numbered rather than refused."""
    cid = client.post("/api/cases", json={"name": "Same name"}).json()["id"]
    first = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead", "folder": ""}).json()
    second = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead", "folder": ""}).json()

    assert first["attrs"]["path"] == "notes/Lead.md"
    assert second["attrs"]["path"] == "notes/Lead-2.md"
    assert Case.open(cid).resolve_inside(second["attrs"]["path"]).exists()


def test_details_title_edit_moves_every_named_tool_file(client):
    """The shared Details editor bypasses the tool-specific save routes, so its
    generic entity patch must still keep labels and filenames aligned."""
    cid = client.post("/api/cases", json={"name": "Details renames"}).json()["id"]
    case = Case.open(cid)
    fixtures = [
        (
            "proof",
            "spec",
            layout.proof_spec_rel("Old proof"),
            "New proof",
            layout.proof_spec_rel("New proof"),
        ),
        (
            "inspect-session",
            "spec",
            layout.session_rel("Old inspect"),
            "New inspect",
            layout.session_rel("New inspect"),
        ),
        (
            "compare-session",
            "spec",
            layout.compare_session_rel("Old comparison"),
            "New comparison",
            layout.compare_session_rel("New comparison"),
        ),
        (
            "post",
            "draft",
            layout.draft_rel("Old post"),
            "New post",
            layout.draft_rel("New post"),
        ),
    ]
    entities = []
    for type_, attribute, old, new_label, new in fixtures:
        path = case.resolve_inside(old)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps({"title": Path(old).stem}), encoding="utf-8")
        attrs = {attribute: old}
        if type_ == "proof":
            export = layout.proof_export_rel("Old proof")
            case.resolve_inside(export).write_bytes(b"png")
            attrs["path"] = export
        entity = case.add_entity(type_, Path(old).stem, attrs, by="user")
        entities.append((entity, old, new_label, new))

    for entity, old, new_label, new in entities:
        updated = client.patch(
            f"/api/cases/{cid}/entities/{entity['id']}",
            json={"label": new_label},
        ).json()
        attribute = "draft" if entity["type"] == "post" else "spec"
        assert updated["label"] == new_label
        assert updated["attrs"][attribute] == new
        assert not case.resolve_inside(old).exists()
        assert case.resolve_inside(new).is_file()
        body = json.loads(case.resolve_inside(new).read_text(encoding="utf-8"))
        assert body["title"] == new_label

    proof = next(entity for entity in case.list_entities() if entity["type"] == "proof")
    assert proof["attrs"]["path"] == layout.proof_export_rel("New proof")
    assert case.resolve_inside(proof["attrs"]["path"]).is_file()


def test_a_picker_page_brings_the_preview_each_source_already_has(client):
    cid = client.post("/api/cases", json={"name": "Previews"}).json()["id"]
    case = Case.open(cid)
    frame = case.add_entity("media", "frame.jpg", {"path": "media/frame.jpg", "kind": "image"}, by="user")
    case.upsert_media_item(
        {"path": "media/frame.jpg", "filename": "frame.jpg", "kind": "image",
         "added_at": "2026-08-11T10:00:00Z", "thumbnail": ".thumbs/frame.jpg"},
        entity_id=frame["id"],
    )
    capture = case.add_entity("capture", "S2 11 Mar", {"thumb": ".thumbs/s2.jpg"}, by="user")
    note = case.add_entity("note", "Interview", {}, by="user")

    def thumbs(**params):
        page = client.get(f"/api/cases/{cid}/catalog/entities", params=params).json()
        return {row["id"]: row.get("thumb") for row in page["items"]}

    # The table draws its own pictures and does not ask.
    assert thumbs()[frame["id"]] is None
    picked = thumbs(previews="true")
    assert picked[frame["id"]] == ".thumbs/frame.jpg"
    assert picked[capture["id"]] == ".thumbs/s2.jpg"
    assert picked[note["id"]] is None