From 30159ea6ab5da898972163898b36aa6ea45b3ee5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 14:05:07 +0000 Subject: [PATCH 1/2] Let the assistant organise and tidy the tag vocabulary The assistant could change one asset's tags but not the vocabulary itself. It can now propose groups (nested categories, existing ones moved or renamed, tags filed into them), renames and merges across every asset carrying a tag, and deletes of unused tags. Each change is a proposal row with a preview (how many assets, and a sample of their names), and nothing is written until the person applies it. - list_tags gives ids, counts and category paths, the category tree, and pages, so a whole vocabulary can be sorted into groups; find_similar_tags finds spellings of one tag. - A rename onto an existing name is recorded as a merge. Merging keeps one attachment per asset and carries the source's category to an unfiled target. - Apply runs tag ops in dependency order, resolves categories proposed in the same turn, skips a stale op with a sentence and re-indexes touched assets once. - Groups are TagCategory rows: no schema change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V1geD6BRzqbfoJdeGyQ4Kb --- CLAUDE.md | 10 +- backend/app/assistant/apply.py | 194 +++++- backend/app/assistant/prompt.py | 19 +- backend/app/assistant/tools.py | 563 +++++++++++++++++- backend/app/routers/assistant.py | 14 +- backend/app/routers/tags.py | 10 +- backend/app/services/tags.py | 173 ++++++ backend/tests/test_assistant_tags.py | 420 +++++++++++++ backend/tests/test_tags.py | 38 ++ frontend/src/api/assistant.ts | 62 ++ .../src/components/AssistantPanel.test.tsx | 86 +++ frontend/src/components/AssistantPanel.tsx | 162 ++++- frontend/src/stores/assistant.ts | 7 +- 13 files changed, 1727 insertions(+), 31 deletions(-) create mode 100644 backend/tests/test_assistant_tags.py diff --git a/CLAUDE.md b/CLAUDE.md index cf971f6..bcb4e9f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,8 +34,9 @@ Gecko Suite, through the two functions every job already calls, `build_provider` and search falls back to keywords; jobs fail with a sentence and retry. - **The assistant exists only in `suite` mode, and never writes.** Its tools look (`search_assets`, `get_asset`, `read_transcript`, `list_clips`, `list_tags`, - `list_playlists`) or record a proposal (`propose_changes`, `propose_enrichment`, - `propose_clip`, `propose_cut`, `propose_playlist`, `propose_note`); + `find_similar_tags`, `list_playlists`) or record a proposal (`propose_changes`, + `propose_enrichment`, `propose_clip`, `propose_cut`, `propose_playlist`, `propose_note`, + `propose_tag_groups`, `propose_tag_rename`, `propose_tag_delete`); `assistant/apply.py` is the only place a proposal reaches the library, and only when a person presses Apply. A new tool that writes would break that, so make it a proposal kind instead. Every tool re-checks that the asset is the caller's: the model chooses @@ -52,6 +53,11 @@ Gecko Suite, through the two functions every job already calls, `build_provider` `SUITE_BASE_URL`, and the old `NOTES_BASE_URL` is not read) with the caller's own token, which only the Apply request has; their `/a/` links are made absolute there. Notes failing is a skipped item with a sentence, never a failed Apply. + A proposal's `tag_ops` (each with its own `op_ref`) change the vocabulary, not one asset: + groups are `TagCategory` rows (there is no tag-under-tag), and a rename onto a name that + exists is recorded as a merge. Apply runs them in dependency order (`TAG_OP_ORDER`) through + `services/tags`, resolves categories proposed in the same turn by ref, skips a stale op + with a sentence, and re-indexes the touched assets once at the end. `web_search` is one of the looking tools: the suite runs the search (its own backend, else DuckDuckGo) and credits it to the conversation, and what comes back is for the model to read and cite, never a write. A **persona** is the suite's, chosen per turn and kept on the diff --git a/backend/app/assistant/apply.py b/backend/app/assistant/apply.py index 30571f3..a8a296b 100644 --- a/backend/app/assistant/apply.py +++ b/backend/app/assistant/apply.py @@ -24,6 +24,12 @@ Playlists (`proposal["playlists"]`) go through services/playlists, the same as a person building one. Each item is checked again; one whose asset has gone or whose range no longer fits is left out and reported, and the rest of the playlist is still made. + +Tag changes (`proposal["tag_ops"]`) are to the vocabulary rather than to one asset: new +categories, categories moved, tags filed, renamed, merged and deleted. They run in the +order one depends on another (a category is made before tags are filed into it, and tags +are filed before they are merged away), each checked against the library as it is now, and +one that no longer makes sense is skipped with a sentence while the rest still apply. """ from __future__ import annotations @@ -40,6 +46,7 @@ from app.jobs.runner import ACTIVE_STATUSES from app.models.asset import Asset from app.models.job import KIND_AUTOTAG, KIND_DESCRIBE, KIND_EXTRACT_SUBVIDEO, KIND_SUMMARIZE, EnrichmentJob +from app.models.tag import Tag, TagCategory from app.providers import build_provider from app.providers.base import ProviderError from app import notes_client @@ -57,7 +64,8 @@ def apply(session: Session, user_id: str, proposal: dict, only: Optional[Iterable[str]] = None, only_clips: Optional[Iterable[str]] = None, only_playlists: Optional[Iterable[str]] = None, - only_notes: Optional[Iterable[str]] = None, *, + only_notes: Optional[Iterable[str]] = None, + only_tag_ops: Optional[Iterable[str]] = None, *, token: Optional[str] = None, origin: str = "") -> list[dict]: """Apply the proposal's items, clips, playlists and notes, one result per entry. @@ -69,7 +77,8 @@ def apply(session: Session, user_id: str, proposal: dict, or playlists, and must not get them as a side effect). """ everything = (only is None and only_clips is None and only_playlists is None - and only_notes is None) + and only_notes is None and only_tag_ops is None) + wanted_ops = set(only_tag_ops) if only_tag_ops is not None else set() wanted_notes = set(only_notes) if only_notes is not None else set() wanted = set(only) if only is not None else set() wanted_clips = set(only_clips) if only_clips is not None else set() @@ -87,9 +96,190 @@ def apply(session: Session, user_id: str, proposal: dict, for entry in proposal.get("notes", []): if everything or entry["note_ref"] in wanted_notes: results.append(_apply_note(entry, token, origin)) + ops = [op for op in proposal.get("tag_ops", []) if everything or op["op_ref"] in wanted_ops] + if ops: + results.extend(_apply_tag_ops(session, user_id, ops)) return results +# The order tag changes are applied in, whatever order they were proposed in: a category +# exists before anything is filed under it, and a tag is filed before a merge carries its +# category over to the target. +TAG_OP_ORDER = ("create_category", "move_category", "file_tags", "rename_tag", "merge_tags", + "delete_tag") + + +def _apply_tag_ops(session: Session, user_id: str, ops: list[dict]) -> list[dict]: + """Apply the chosen tag changes, one result each, in the proposal's order. + + `made` maps a proposed category's op_ref to the category it became, so an op naming a + new parent or home finds it; one whose category was not chosen or could not be made is + skipped. Every asset whose tag names changed is re-indexed once, at the end, rather than + once per op that touched it. + """ + results: dict[str, dict] = {} + made: dict[str, str] = {} + reindex: set[str] = set() + for op in sorted(ops, key=lambda o: TAG_OP_ORDER.index(o["kind"]) + if o["kind"] in TAG_OP_ORDER else len(TAG_OP_ORDER)): + result = {"asset_id": None, "asset_name": _tag_op_label(op), "applied": [], + "skipped": [], "op_ref": op["op_ref"]} + results[op["op_ref"]] = result + try: + reindex.update(_apply_tag_op(session, user_id, op, made, result)) + except Exception as exc: # noqa: BLE001 - one bad op must not sink the others + logger.exception("Applying tag change %s failed", op.get("kind")) + session.rollback() + result["skipped"].append(f"It could not be applied: {exc}") + if reindex: + asset_service.reindex_ids(session, reindex) + return [results[op["op_ref"]] for op in ops] + + +def _tag_op_label(op: dict) -> str: + kind = op["kind"] + if kind == "create_category": + return op["name"] + if kind == "move_category": + return op["name"] + if kind == "file_tags": + return op.get("category_label") or "No category" + if kind == "rename_tag": + return op["from"] + if kind == "merge_tags": + return op["target_name"] + return op.get("name") or "" + + +def _parent_id(session: Session, user_id: str, op: dict, made: dict[str, str], + ref_key: str, id_key: str) -> tuple[bool, Optional[str]]: + """The category an op points at, as (found, id). None with found means "no category".""" + if op.get(ref_key): + made_id = made.get(op[ref_key]) + return (made_id is not None, made_id) + if op.get(id_key): + row = session.get(TagCategory, op[id_key]) + if row is None or row.user_id != user_id: + return False, None + return True, row.id + return True, None + + +def _apply_tag_op(session: Session, user_id: str, op: dict, made: dict[str, str], + result: dict) -> list[str]: + """Apply one tag change; return the assets to re-index.""" + kind = op["kind"] + if kind == "create_category": + found, parent_id = _parent_id(session, user_id, op, made, "parent_ref", "parent_category_id") + if not found: + result["skipped"].append("Its parent category was not made, or no longer exists.") + return [] + twin = session.exec(select(TagCategory).where( + TagCategory.user_id == user_id, TagCategory.parent_category_id == parent_id)).all() + match = next((c for c in twin if c.name.lower() == op["name"].lower()), None) + if match is not None: + made[op["op_ref"]] = match.id + result["applied"].append("it existed already") + return [] + category = TagCategory(user_id=user_id, name=op["name"], parent_category_id=parent_id) + session.add(category) + session.commit() + made[op["op_ref"]] = category.id + result["applied"].append("category made") + return [] + + if kind == "move_category": + category = session.get(TagCategory, op["category_id"]) + if category is None or category.user_id != user_id: + result["skipped"].append("The category no longer exists.") + return [] + if op.get("move"): + found, parent_id = _parent_id(session, user_id, op, made, "parent_ref", + "parent_category_id") + if not found: + result["skipped"].append("Its new parent was not made, or no longer exists.") + return [] + if tag_service.would_create_cycle(session, user_id, category.id, parent_id): + result["skipped"].append("A category cannot be moved inside itself.") + return [] + category.parent_category_id = parent_id + result["applied"].append("moved") + if op.get("new_name"): + category.name = op["new_name"] + result["applied"].append("renamed") + session.add(category) + session.commit() + return [] + + if kind == "file_tags": + found, category_id = _parent_id(session, user_id, op, made, "category_ref", "category_id") + if not found: + result["skipped"].append("The category was not made, or no longer exists.") + return [] + filed = gone = 0 + for entry in op["tags"]: + tag = session.get(Tag, entry["id"]) + if tag is None or tag.user_id != user_id: + gone += 1 + continue + tag.category_id = category_id + session.add(tag) + filed += 1 + session.commit() + if filed: + result["applied"].append(f"{filed} tag(s) filed") + if gone: + result["skipped"].append(f"{gone} tag(s) no longer exist.") + return [] + + if kind == "rename_tag": + tag = session.get(Tag, op["tag_id"]) + if tag is None or tag.user_id != user_id: + result["skipped"].append("The tag no longer exists.") + return [] + try: + changed = tag_service.rename_tag(session, tag, op["to"]) + except ValueError as exc: + session.rollback() + result["skipped"].append(f"{exc}; merge them instead.") + return [] + session.commit() + result["applied"].append("renamed") + return tag_service.asset_ids_for_tag(session, tag.id) if changed else [] + + if kind == "merge_tags": + sources = [t for t in (session.get(Tag, s["id"]) for s in op["sources"]) + if t is not None and t.user_id == user_id] + if op.get("target_id"): + target = session.get(Tag, op["target_id"]) + if target is None or target.user_id != user_id: + result["skipped"].append("The tag to merge into no longer exists.") + return [] + else: + target = tag_service.get_or_create(session, user_id, op["target_name"]) + sources = [t for t in sources if t.id != target.id] + if not sources: + result["skipped"].append("The tags to merge no longer exist.") + return [] + affected = tag_service.merge_tags(session, sources, target) + result["applied"].append(f"{len(sources)} tag(s) merged into {target.name}") + if len(sources) < len(op["sources"]): + result["skipped"].append(f"{len(op['sources']) - len(sources)} tag(s) no longer exist.") + return affected + + if kind == "delete_tag": + tag = session.get(Tag, op["tag_id"]) + if tag is None or tag.user_id != user_id: + result["skipped"].append("The tag no longer exists.") + return [] + affected = tag_service.delete_tag(session, tag) + result["applied"].append("deleted") + return affected + + result["skipped"].append(f"{kind}: not something the library can do.") + return [] + + def _apply_note(entry: dict, token: Optional[str], origin: str) -> dict: result = {"asset_id": None, "asset_name": entry.get("title") or "", "applied": [], "skipped": [], "note_ref": entry["note_ref"], "note_url": None} diff --git a/backend/app/assistant/prompt.py b/backend/app/assistant/prompt.py index 3d63ff9..55bd062 100644 --- a/backend/app/assistant/prompt.py +++ b/backend/app/assistant/prompt.py @@ -13,7 +13,8 @@ - Search before you answer. Use search_assets for anything about what is in the library, and \ read_transcript when what was said matters. Never describe an asset you have not looked at. - You cannot change the library. propose_changes, propose_enrichment, propose_clip, \ -propose_cut, propose_playlist and propose_note record a proposal; the person reads it \ +propose_cut, propose_playlist, propose_note, propose_tag_groups, propose_tag_rename and \ +propose_tag_delete record a proposal; the person reads it \ and applies it or throws it away. Say plainly what you are proposing and why. Never say \ a change "has been made" or that a clip "exists". - Clips and cuts. To find a moment: search_assets gives where a search matched; \ @@ -52,6 +53,22 @@ - The web is for what the library cannot say. Use web_search sparingly, and say where a fact came from. Never present something from the web as if it were in the asset itself. - Prefer the tags the person already uses (list_tags). Invent a new one only when none fits. +- Organising tags. Groups of tags are categories, which nest (People > Scientists); a tag \ +is filed under one category at most, and filtering by a category finds everything below it. \ +Read list_tags first: it gives every tag's id, how often it is used and where it is filed, \ +and on its first page the categories. To sort the whole vocabulary into groups, page through \ +list_tags (offset) or ask for uncategorised_only, reuse the categories that exist before \ +making new ones, keep the groups few and broad, and nest only where a group is large or \ +mixed. Use web_search for a name you do not recognise rather than guessing. File each tag \ +once: for one that could go in two groups, choose and say why. Then propose_tag_groups, with \ +as many categories and filings in one call as you can. +- Tidying tags. find_similar_tags finds spellings of one tag (case, plurals, typos); read \ +each group, since similar is not always the same, and merge into the most used spelling with \ +propose_tag_rename. A rename or merge applies to every asset carrying the tag. \ +propose_tag_delete is for unused tags and junk (list_tags with max_uses 0 finds the unused \ +ones); a tag still in use is better merged, and if asked to delete one anyway, say how many \ +assets lose it. These change the vocabulary, not one asset, so use propose_changes only for \ +the tags of particular assets. - Change as little as you must. Leave a good name, description or summary alone. Propose \ changes to the assets the request is about, not to everything you happened to see. - Names are short and plain. A description says what the asset shows or contains. A summary is \ diff --git a/backend/app/assistant/tools.py b/backend/app/assistant/tools.py index f8efc1b..4b86a48 100644 --- a/backend/app/assistant/tools.py +++ b/backend/app/assistant/tools.py @@ -1,8 +1,8 @@ """The assistant's tools: those that look, and those that propose. None of them writes to the library. `propose_changes`, `propose_enrichment`, `propose_clip`, -`propose_cut`, `propose_playlist` and `propose_note` add to a `Working` proposal that the turn ends with, -and that is all they do. The person applies +`propose_cut`, `propose_playlist`, `propose_note` and the three `propose_tag_*` add to a +`Working` proposal that the turn ends with, and that is all they do. The person applies it (routers/assistant.py) or throws it away, so a model that misreads a request costs a discarded card and not a rewritten library. @@ -32,11 +32,12 @@ from app.enrichment.summarize import summarisable from app.ingest.filetypes import TYPE_AUDIO, TYPE_VIDEO from app.models.asset import Asset -from app.models.tag import Tag +from app.models.tag import Tag, TagCategory from app.models.transcript import TranscriptSegment from app.services import assets as asset_service from app.services import playlists as playlist_service from app.services import search as search_service +from app.schemas_tags import MAX_CATEGORY_LENGTH, MAX_TAG_LENGTH from app.services import tags as tag_service # What a proposal may ask the enrichment pipeline to do once applied. @@ -64,6 +65,22 @@ # until applied; past this the model is told to stop and say what is left. MAX_PLAYLIST_ITEMS = 60 +# Tag operations one turn may propose. Counted in operations, not tags: filing 300 tags into +# one group is one operation, so sorting a whole vocabulary costs about one per group. +MAX_TAG_OPS = 100 +# Tags one filing, merge or delete may name. A vocabulary is hundreds, not thousands. +MAX_TAG_IDS = 500 +# Tags list_tags hands over at a time; past this it says where to carry on. +TAG_PAGE = 200 +# Groups of look-alike tags find_similar_tags reports at once. +MAX_SIMILAR_GROUPS = 50 +# How far a walk up the proposed category tree goes before calling it a loop. +TREE_DEPTH = 64 +# Matching the REST API's limits (schemas_tags), so a proposal never makes what a person +# could not. +TAG_NAME_MAX = MAX_TAG_LENGTH +CATEGORY_MAX = MAX_CATEGORY_LENGTH + SPECS: List[ToolSpec] = [ ToolSpec( "search_assets", @@ -101,7 +118,23 @@ "required": ["asset_id"]}), ToolSpec( "list_tags", - "The person's existing tags, most used first. Look here before proposing a tag.", + "The person's existing tags, most used first, each with its id, how many assets carry " + "it and the category (group) it is filed under; the first page also lists the " + "categories, nested as Parent > Child, with their ids. Look here before proposing a " + "tag, and before organising tags. Comes in pages: pass offset to carry on.", + {"type": "object", "properties": { + "offset": {"type": "integer", "description": "Where to carry on from. Default 0."}, + "uncategorised_only": {"type": "boolean", + "description": "Only tags not filed under any category."}, + "max_uses": {"type": "integer", + "description": "Only tags on at most this many assets (0: unused)."}, + }}), + ToolSpec( + "find_similar_tags", + "Groups of the person's tags that look like spellings of one tag: different case, " + "plurals, punctuation, small typos (interview / Interviews / intervew). Each with its " + "id and how many assets carry it. Use it to find duplicates to merge. Similar is not " + "the same: read each group before proposing a merge.", {"type": "object", "properties": {}}), ToolSpec( "web_search", @@ -206,11 +239,69 @@ "reason": {"type": "string", "description": "One sentence on why this stretch, shown to the person."}, }, "required": ["asset_id", "start_seconds", "end_seconds"]}), + ToolSpec( + "propose_tag_groups", + "Propose organising tags into groups. Groups are categories, which nest (People > " + "Scientists); each tag is filed under at most one. In one call: new categories, " + "existing categories moved under another or renamed, and tags filed into a category. " + "Name a category by its id from list_tags (or its path, People > Scientists, when that " + "names one), or by the ref of one proposed in this turn (a new one's ref is its name " + "unless you give one). Nothing changes until the person " + "applies the proposal. Call again to add more.", + {"type": "object", "properties": { + "categories": {"type": "array", "description": "New categories.", "items": { + "type": "object", "properties": { + "name": {"type": "string"}, + "parent": {"type": "string", + "description": "Category id or ref to nest it under; omit for top level."}, + "ref": {"type": "string", + "description": "What to call it in this turn, if not its name."}, + }, "required": ["name"]}}, + "moves": {"type": "array", "description": "Existing categories to move or rename.", + "items": {"type": "object", "properties": { + "category_id": {"type": "string"}, + "parent": {"type": ["string", "null"], + "description": "New parent id or ref; null for top level; omit to leave it."}, + "new_name": {"type": "string"}, + }, "required": ["category_id"]}}, + "file": {"type": "array", "description": "Tags to file under a category.", + "items": {"type": "object", "properties": { + "tag_ids": {"type": "array", "items": {"type": "string"}}, + "category": {"type": ["string", "null"], + "description": "Category id or ref; null takes them out of any."}, + }, "required": ["tag_ids", "category"]}}, + }}), + ToolSpec( + "propose_tag_rename", + "Propose renaming tags, or merging several into one, across every asset that carries " + "them. A rename onto a name another tag already has is a merge. A merge moves every " + "asset from the source tags onto the target and deletes the sources; merge into the " + "most used spelling. Nothing changes until the person applies the proposal.", + {"type": "object", "properties": { + "renames": {"type": "array", "items": {"type": "object", "properties": { + "tag_id": {"type": "string"}, + "new_name": {"type": "string"}, + }, "required": ["tag_id", "new_name"]}}, + "merges": {"type": "array", "items": {"type": "object", "properties": { + "source_tag_ids": {"type": "array", "items": {"type": "string"}}, + "target_tag_id": {"type": "string", "description": "An existing tag to keep."}, + "target_name": {"type": "string", + "description": "Or a name to merge into, new or existing."}, + }, "required": ["source_tag_ids"]}}, + }}), + ToolSpec( + "propose_tag_delete", + "Propose deleting tags everywhere they are used. Meant for unused tags and junk; a " + "tag still on assets is better merged into another, and if asked to delete one, say " + "how many assets lose it. Nothing changes until the person applies the proposal.", + {"type": "object", "properties": { + "tag_ids": {"type": "array", "items": {"type": "string"}}, + }, "required": ["tag_ids"]}), ] # Tools that only look. The worker reports a step for the rest. READS = frozenset({"search_assets", "get_asset", "read_transcript", "list_clips", "list_tags", - "list_playlists", "web_search"}) + "find_similar_tags", "list_playlists", "web_search"}) # What a web search may hand back to the model in one call. A page of results, not a crawl. MAX_WEB_CHARS = 6_000 @@ -282,6 +373,11 @@ def __init__(self, user_id: str, open_session: Callable[[], ContextManager[Sessi self.playlists: List[dict] = [] # Notes for Gecko Notes, each with its own `note_ref`. self.notes: List[dict] = [] + # Changes to the tag vocabulary: categories made, moved and filed into, tags renamed, + # merged and deleted. In proposal order; apply runs them in dependency order. + self.tag_ops: List[dict] = [] + # A new category's ref, as the model names it (lowercased), -> its op. + self._category_refs: Dict[str, dict] = {} # Set by the worker once it holds a connection to the suite: `query -> results`. # Unset, the tool says so instead of failing. self.search: Optional[Callable[[str], list]] = None @@ -296,6 +392,7 @@ def handlers(self) -> Dict[str, Callable[[dict], object]]: "read_transcript": self.read_transcript, "list_clips": self.list_clips, "list_tags": self.list_tags, + "find_similar_tags": self.find_similar_tags, "list_playlists": self.list_playlists, "web_search": self.web_search, "propose_changes": self.propose_changes, @@ -304,6 +401,9 @@ def handlers(self) -> Dict[str, Callable[[dict], object]]: "propose_cut": self.propose_cut, "propose_playlist": self.propose_playlist, "propose_note": self.propose_note, + "propose_tag_groups": self.propose_tag_groups, + "propose_tag_rename": self.propose_tag_rename, + "propose_tag_delete": self.propose_tag_delete, } @contextmanager @@ -440,13 +540,61 @@ def list_clips(self, args: dict) -> object: return "\n".join(lines) def list_tags(self, args: dict) -> object: + offset = args.get("offset") + offset = offset if isinstance(offset, int) and offset > 0 else 0 + max_uses = args.get("max_uses") + max_uses = max_uses if isinstance(max_uses, int) and not isinstance(max_uses, bool) \ + and max_uses >= 0 else None + unfiled_only = args.get("uncategorised_only") is True with self._session() as session: counts = tag_service.usage_counts(session, self.user_id) rows = session.exec(select(Tag).where(Tag.user_id == self.user_id)).all() - if not rows: + categories = session.exec( + select(TagCategory).where(TagCategory.user_id == self.user_id)).all() + if not rows and not categories: return "There are no tags yet." - rows = sorted(rows, key=lambda t: (-counts.get(t.id, 0), t.name.lower()))[:200] - return "\n".join(f"{t.name} ({counts.get(t.id, 0)})" for t in rows) + paths = tag_service.category_paths(categories) + unfiled = sum(1 for t in rows if t.category_id not in paths) + lines = [f"{len(rows)} tag(s), {unfiled} not in any category; " + f"{len(categories)} categor{'y' if len(categories) == 1 else 'ies'}."] + if offset == 0 and categories: + lines.append("Categories:") + lines += [f"- {cid} | {path}" for cid, path in sorted(paths.items(), key=lambda p: p[1].lower())] + + chosen = [t for t in rows + if (not unfiled_only or t.category_id not in paths) + and (max_uses is None or counts.get(t.id, 0) <= max_uses)] + chosen.sort(key=lambda t: (-counts.get(t.id, 0), t.name.lower())) + page = chosen[offset:offset + TAG_PAGE] + if not page: + lines.append("No tags match." if offset == 0 else "No more tags.") + return "\n".join(lines) + lines.append(f"Tags {offset + 1}-{offset + len(page)} of {len(chosen)} " + "(id | name (assets) | category):") + for t in page: + where = f" | {paths[t.category_id]}" if t.category_id in paths else "" + lines.append(f"- {t.id} | {t.name} ({counts.get(t.id, 0)}){where}") + if offset + len(page) < len(chosen): + lines.append(f"[more: call again with offset={offset + len(page)}]") + return "\n".join(lines) + + def find_similar_tags(self, args: dict) -> object: + with self._session() as session: + counts = tag_service.usage_counts(session, self.user_id) + rows = list(session.exec(select(Tag).where(Tag.user_id == self.user_id)).all()) + self._step("read", "Looking for tags that are spellings of one another") + groups = tag_service.similar_groups(rows) + if not groups: + return "No tags look like spellings of one another." + for group in groups: + group.sort(key=lambda t: (-counts.get(t.id, 0), t.name.lower())) + groups.sort(key=lambda g: -sum(counts.get(t.id, 0) for t in g)) + lines = [" | ".join(f"{t.name} {t.id} ({counts.get(t.id, 0)})" for t in group) + for group in groups[:MAX_SIMILAR_GROUPS]] + more = len(groups) - MAX_SIMILAR_GROUPS + return ("Each line is one group, most used first: name id (assets).\n" + + "\n".join(f"- {line}" for line in lines) + + (f"\n[{more} more groups not shown]" if more > 0 else "")) def list_playlists(self, args: dict) -> object: from app.models.playlist import Playlist @@ -684,6 +832,401 @@ def propose_note(self, args: dict) -> object: return (f"Recorded the note {title!r} ({len(markdown)} characters, " f"{len(ids)} linked asset(s)).") + # ─── the tag vocabulary ────────────────────────────────────────────────── + + def propose_tag_groups(self, args: dict) -> object: + """Record new categories, moves of existing ones, and tags filed into them. + + Done in that order within the call, so a category made in it can be the parent of + another or the home of tags in the same call. Each entry is checked on its own and + the good ones kept, as for playlist items; the model hears which failed and why. + """ + creates = args.get("categories") if isinstance(args.get("categories"), list) else [] + moves = args.get("moves") if isinstance(args.get("moves"), list) else [] + files = args.get("file") if isinstance(args.get("file"), list) else [] + if not (creates or moves or files): + return _fail("Give categories to make, moves, or tags to file.") + done, problems = [], [] + with self._session() as session: + for index, raw in enumerate(creates, start=1): + said = self._create_category(session, raw) if isinstance(raw, dict) else _fail("not an object.") + (problems.append(f"category {index}: {said[0]}") if isinstance(said, tuple) + else done.append(said)) + for index, raw in enumerate(moves, start=1): + said = self._move_category(session, raw) if isinstance(raw, dict) else _fail("not an object.") + (problems.append(f"move {index}: {said[0]}") if isinstance(said, tuple) + else done.append(said)) + for index, raw in enumerate(files, start=1): + said = self._file_tags(session, raw) if isinstance(raw, dict) else _fail("not an object.") + (problems.append(f"filing {index}: {said[0]}") if isinstance(said, tuple) + else done.append(said)) + return self._tag_reply(done, problems) + + def propose_tag_rename(self, args: dict) -> object: + renames = args.get("renames") if isinstance(args.get("renames"), list) else [] + merges = args.get("merges") if isinstance(args.get("merges"), list) else [] + if not (renames or merges): + return _fail("Give renames or merges.") + done, problems = [], [] + with self._session() as session: + for index, raw in enumerate(renames, start=1): + said = self._rename(session, raw) if isinstance(raw, dict) else _fail("not an object.") + (problems.append(f"rename {index}: {said[0]}") if isinstance(said, tuple) + else done.append(said)) + for index, raw in enumerate(merges, start=1): + said = self._merge(session, raw) if isinstance(raw, dict) else _fail("not an object.") + (problems.append(f"merge {index}: {said[0]}") if isinstance(said, tuple) + else done.append(said)) + return self._tag_reply(done, problems) + + def propose_tag_delete(self, args: dict) -> object: + ids = self._ids(args.get("tag_ids")) + if not ids: + return _fail("Give the ids of the tags to delete, from list_tags.") + done, problems = [], [] + with self._session() as session: + for tag_id in ids: + tag = self._owned_tag(session, tag_id) + if tag is None: + problems.append(f"{tag_id}: no such tag.") + continue + if self._claimed(tag.id, "delete_tag"): + problems.append(f"{tag.name}: already being renamed or merged in this proposal.") + continue + if any(op["kind"] == "delete_tag" and op["tag_id"] == tag.id for op in self.tag_ops): + continue + if self._full(): + problems.append(self._full_sentence()) + break + count, sample = tag_service.asset_names_for_tags(session, [tag.id]) + self._add_op({"kind": "delete_tag", "tag_id": tag.id, "name": tag.name, + "asset_count": count, "sample_assets": sample}) + done.append(f"delete {tag.name}" + (f" (on {count} asset(s))" if count else " (unused)")) + return self._tag_reply(done, problems) + + def _create_category(self, session: Session, raw: dict): + name = _clean(raw.get("name")) + if not name: + return _fail("give it a name.") + name = " ".join(name.split()) + if len(name) > CATEGORY_MAX: + return _fail(f"the name is too long ({len(name)} of {CATEGORY_MAX} characters).") + ref = (_clean(raw.get("ref")) or name).lower() + parent = None + if raw.get("parent") is not None: + parent = self._category(session, raw.get("parent")) + if parent is None: + return _fail("its parent is not a category id from list_tags or a ref from this turn.") + if ref in self._category_refs: + held = self._category_refs[ref] + return f"{held['name']} is already proposed" + + # One that exists already under the same parent is that one, not a twin of it. + if parent is None or parent[0] == "id": + parent_id = parent[1] if parent else None + twin = session.exec(select(TagCategory).where( + TagCategory.user_id == self.user_id, + TagCategory.parent_category_id == parent_id)).all() + match = next((c for c in twin if c.name.lower() == name.lower()), None) + if match is not None: + self._category_refs[ref] = {"existing_id": match.id, "name": match.name} + return f"{match.name} exists already ({match.id}), so that is used" + if self._full(): + return _fail(self._full_sentence()) + op = self._add_op({ + "kind": "create_category", "name": name, + "parent_category_id": parent[1] if parent and parent[0] == "id" else None, + "parent_ref": parent[1] if parent and parent[0] == "ref" else None, + "parent_label": self._category_label(session, parent), + }) + self._category_refs[ref] = op + return f"new category {self._category_label(session, ('ref', op['op_ref']))}" + + def _move_category(self, session: Session, raw: dict): + category = self._owned_category(session, raw.get("category_id")) + if category is None: + return _fail("no such category. Use an id from list_tags.") + new_name = _clean(raw.get("new_name")) + new_name = " ".join(new_name.split()) if new_name else None + if new_name and len(new_name) > CATEGORY_MAX: + return _fail(f"the name is too long ({len(new_name)} of {CATEGORY_MAX} characters).") + moving = "parent" in raw + parent = None + if moving and raw.get("parent") is not None: + parent = self._category(session, raw.get("parent")) + if parent is None: + return _fail("its new parent is not a category id from list_tags or a ref from this turn.") + if self._would_loop(session, category.id, parent): + return _fail(f"{category.name} cannot go inside itself or one of its own subcategories.") + if not moving and not new_name: + return _fail("give a new parent or a new name.") + if moving and parent is None and category.parent_category_id is None and not new_name: + return f"{category.name} is already at the top level" + if self._full(): + return _fail(self._full_sentence()) + paths = tag_service.category_paths( + session.exec(select(TagCategory).where(TagCategory.user_id == self.user_id)).all()) + self.tag_ops = [op for op in self.tag_ops + if not (op["kind"] == "move_category" and op["category_id"] == category.id)] + op = self._add_op({ + "kind": "move_category", "category_id": category.id, "name": category.name, + "from_path": paths.get(category.id, category.name), "move": moving, + "parent_category_id": parent[1] if parent and parent[0] == "id" else None, + "parent_ref": parent[1] if parent and parent[0] == "ref" else None, + "parent_label": self._category_label(session, parent) if moving else None, + "new_name": new_name, + }) + where = f" under {op['parent_label']}" if parent else (" to the top level" if moving else "") + return f"move {category.name}{where}" + (f", renamed {new_name}" if new_name else "") + + def _file_tags(self, session: Session, raw: dict): + ids = self._ids(raw.get("tag_ids")) + if not ids: + return _fail("give tag_ids from list_tags.") + if "category" not in raw: + return _fail("give a category, or null to take the tags out of any.") + target = None + if raw.get("category") is not None: + target = self._category(session, raw.get("category")) + if target is None: + return _fail("not a category id from list_tags or a ref from this turn.") + tags = [t for t in (self._owned_tag(session, i) for i in ids) if t is not None] + unknown = len(ids) - len(tags) + if not tags: + return _fail("none of those are tags. Use ids from list_tags.") + # Already where they are going: nothing to propose for those. + home = target[1] if target and target[0] == "id" else None + if target is None or target[0] == "id": + settled = [t for t in tags if t.category_id == home] + tags = [t for t in tags if t.category_id != home] + if not tags: + return f"{len(settled)} tag(s) are already filed there" + key = (target[0], target[1]) if target else None + # A tag filed again moves to the latest home, and is taken out of the earlier one. + moving = {t.id for t in tags} + for op in [o for o in self.tag_ops if o["kind"] == "file_tags"]: + if self._file_key(op) == key: + continue + op["tags"] = [t for t in op["tags"] if t["id"] not in moving] + if not op["tags"]: + self.tag_ops.remove(op) + else: + op["asset_count"], op["sample_assets"] = tag_service.asset_names_for_tags( + session, [t["id"] for t in op["tags"]]) + op = next((o for o in self.tag_ops if o["kind"] == "file_tags" and self._file_key(o) == key), None) + if op is None: + if self._full(): + return _fail(self._full_sentence()) + op = self._add_op({ + "kind": "file_tags", "tags": [], + "category_id": target[1] if target and target[0] == "id" else None, + "category_ref": target[1] if target and target[0] == "ref" else None, + "category_label": self._category_label(session, target), + }) + held = {t["id"] for t in op["tags"]} + op["tags"] += [{"id": t.id, "name": t.name} for t in tags if t.id not in held] + op["tags"] = op["tags"][:MAX_TAG_IDS] + op["asset_count"], op["sample_assets"] = tag_service.asset_names_for_tags( + session, [t["id"] for t in op["tags"]]) + where = op["category_label"] or "no category" + return (f"file {len(tags)} tag(s) under {where}" + + (f" ({unknown} id(s) were not tags)" if unknown else "")) + + def _rename(self, session: Session, raw: dict): + tag = self._owned_tag(session, raw.get("tag_id")) + if tag is None: + return _fail("no such tag. Use an id from list_tags.") + new_name = tag_service.normalise(raw.get("new_name") if isinstance(raw.get("new_name"), str) else "") + if not new_name: + return _fail("give the new name.") + if len(new_name) > TAG_NAME_MAX: + return _fail(f"the name is too long ({len(new_name)} of {TAG_NAME_MAX} characters).") + if new_name == tag.name: + return f"{tag.name} is already called that" + clash = tag_service.find(session, self.user_id, new_name) + if clash is not None and clash.id != tag.id: + return self._merge(session, {"source_tag_ids": [tag.id], "target_tag_id": clash.id}) + if self._claimed(tag.id, "rename_tag"): + return _fail(f"{tag.name} is already being merged or deleted in this proposal.") + taken = next((op for op in self.tag_ops if op["kind"] == "rename_tag" and op["tag_id"] != tag.id + and op["to"].lower() == new_name.lower()), None) + if taken is not None: + return _fail(f"{taken['from']} is already being renamed {taken['to']}; merge them instead.") + self.tag_ops = [op for op in self.tag_ops + if not (op["kind"] == "rename_tag" and op["tag_id"] == tag.id)] + if self._full(): + return _fail(self._full_sentence()) + count, sample = tag_service.asset_names_for_tags(session, [tag.id]) + self._add_op({"kind": "rename_tag", "tag_id": tag.id, "from": tag.name, "to": new_name, + "asset_count": count, "sample_assets": sample}) + return f"rename {tag.name} to {new_name} on {count} asset(s)" + + def _merge(self, session: Session, raw: dict): + ids = self._ids(raw.get("source_tag_ids")) + sources = [t for t in (self._owned_tag(session, i) for i in ids) if t is not None] + target = None + target_name = None + if raw.get("target_tag_id"): + target = self._owned_tag(session, raw.get("target_tag_id")) + if target is None: + return _fail("the target is not a tag. Use an id from list_tags, or give target_name.") + else: + target_name = tag_service.normalise( + raw.get("target_name") if isinstance(raw.get("target_name"), str) else "") + if not target_name: + return _fail("give target_tag_id or target_name.") + if len(target_name) > TAG_NAME_MAX: + return _fail(f"the name is too long ({len(target_name)} of {TAG_NAME_MAX} characters).") + target = tag_service.find(session, self.user_id, target_name) + if target is not None: + sources = [t for t in sources if t.id != target.id] + if not sources: + return _fail("give at least one source tag, other than the target, from list_tags.") + for tag in sources + ([target] if target else []): + if self._claimed(tag.id, "merge_tags"): + return _fail(f"{tag.name} is already being renamed, merged or deleted in this proposal.") + if self._full(): + return _fail(self._full_sentence()) + count, sample = tag_service.asset_names_for_tags(session, [t.id for t in sources]) + into = target.name if target else target_name + self._add_op({ + "kind": "merge_tags", + "sources": [{"id": t.id, "name": t.name} for t in sources], + "target_id": target.id if target else None, "target_name": into, + "asset_count": count, "sample_assets": sample, + }) + return (f"merge {', '.join(t.name for t in sources)} into " + f"{into}{'' if target else ' (a new tag)'} on {count} asset(s)") + + # helpers for the above + + def _owned_tag(self, session: Session, tag_id: object) -> Optional[Tag]: + tag = session.get(Tag, tag_id) if isinstance(tag_id, str) and tag_id else None + return tag if tag is not None and tag.user_id == self.user_id else None + + def _owned_category(self, session: Session, category_id: object) -> Optional[TagCategory]: + row = session.get(TagCategory, category_id) if isinstance(category_id, str) and category_id else None + return row if row is not None and row.user_id == self.user_id else None + + def _category(self, session: Session, value: object) -> Optional[tuple]: + """A category named by the model: ("ref", op_ref) for one proposed this turn, or + ("id", id) for one that exists. A ref is looked up first, since the model is told it + may call a new category by its name, and an id is never a name it was given.""" + if not isinstance(value, str) or not value.strip(): + return None + held = self._category_refs.get(value.strip().lower()) + if held is not None: + return ("id", held["existing_id"]) if "existing_id" in held else ("ref", held["op_ref"]) + row = self._owned_category(session, value.strip()) + if row is not None: + return ("id", row.id) + # Models name a category by what they read ("People", "People > Scientists") as + # often as by its id. Taken when it picks out exactly one; two "Other"s under + # different parents is a question for the model, not a guess for this tool. + wanted = " > ".join(part.strip() for part in value.split(">")).lower() + paths = tag_service.category_paths(session.exec( + select(TagCategory).where(TagCategory.user_id == self.user_id)).all()) + hits = [cid for cid, path in paths.items() + if path.lower() == wanted or path.lower().split(" > ")[-1] == wanted] + exact = [cid for cid in hits if paths[cid].lower() == wanted] + chosen = exact if len(exact) == 1 else hits + return ("id", chosen[0]) if len(chosen) == 1 else None + + def _category_label(self, session: Session, which: Optional[tuple]) -> Optional[str]: + """The path a person reads, "People > Scientists", for an existing or proposed one.""" + if which is None: + return None + names, current = [], which + for _ in range(TREE_DEPTH): + if current is None: + break + if current[0] == "ref": + op = next((o for o in self.tag_ops if o["op_ref"] == current[1]), None) + if op is None: + break + names.append(op["name"]) + current = (("ref", op["parent_ref"]) if op["parent_ref"] + else ("id", op["parent_category_id"]) if op["parent_category_id"] else None) + else: + row = self._owned_category(session, current[1]) + if row is None: + break + names.append(row.name) + current = ("id", row.parent_category_id) if row.parent_category_id else None + return " > ".join(reversed(names)) + + def _would_loop(self, session: Session, category_id: str, parent: tuple) -> bool: + """True if putting the category under this parent makes it its own ancestor, taking + account of the moves and new categories already proposed this turn.""" + moved = {op["category_id"]: op for op in self.tag_ops + if op["kind"] == "move_category" and op["move"] and op["category_id"] != category_id} + current: Optional[tuple] = parent + for _ in range(TREE_DEPTH): + if current is None: + return False + kind, value = current + if kind == "id" and value == category_id: + return True + op = (next((o for o in self.tag_ops if o["op_ref"] == value), None) if kind == "ref" + else moved.get(value)) + if op is not None: + current = (("ref", op["parent_ref"]) if op["parent_ref"] + else ("id", op["parent_category_id"]) if op["parent_category_id"] else None) + continue + row = self._owned_category(session, value) if kind == "id" else None + if row is None: + return False + current = ("id", row.parent_category_id) if row.parent_category_id else None + return True + + @staticmethod + def _file_key(op: dict) -> Optional[tuple]: + if op["category_ref"]: + return ("ref", op["category_ref"]) + return ("id", op["category_id"]) if op["category_id"] else None + + def _claimed(self, tag_id: str, kind: str) -> bool: + """Whether another rename, merge or delete in this proposal already names the tag. + One change to a tag's identity per proposal: two would have to apply in an order + the person never sees, and the second would find the tag gone.""" + for op in self.tag_ops: + if op["kind"] == "rename_tag" and op["tag_id"] == tag_id and kind != "rename_tag": + return True + if op["kind"] == "delete_tag" and op["tag_id"] == tag_id and kind != "delete_tag": + return True + if op["kind"] == "merge_tags" and (op["target_id"] == tag_id + or any(t["id"] == tag_id for t in op["sources"])): + return True + return False + + def _full(self) -> bool: + return len(self.tag_ops) >= MAX_TAG_OPS + + @staticmethod + def _full_sentence() -> str: + return (f"that is {MAX_TAG_OPS} tag changes already, the most one request may " + "propose. Say what is left and let the person ask for more.") + + def _add_op(self, op: dict) -> dict: + op = {"op_ref": str(uuid.uuid4()), **op} + self.tag_ops.append(op) + return op + + @staticmethod + def _ids(value: object) -> List[str]: + seen: List[str] = [] + for raw in value if isinstance(value, list) else []: + if isinstance(raw, str) and raw.strip() and raw.strip() not in seen: + seen.append(raw.strip()) + return seen[:MAX_TAG_IDS] + + def _tag_reply(self, done: List[str], problems: List[str]) -> object: + if not done: + return _fail("Nothing was recorded. " + " ".join(problems)) + self._step("propose", f"Proposing {len(done)} change(s) to the tags") + return ("Recorded: " + "; ".join(done) + "." + + (" Not recorded: " + " ".join(problems) if problems else "")) + def _playlist_entry(self, existing, name: Optional[str], description: Optional[str]) -> dict: for held in self.playlists: if existing is not None and held["playlist_id"] == existing.id: @@ -752,10 +1295,10 @@ def proposal(self) -> Optional[dict]: items = [i for i in self.items.values() if any(i.get(f) for f in ("name", "description", "summary", "add_tags", "remove_tags", "enrich"))] - if not (items or self.clips or self.playlists or self.notes): + if not (items or self.clips or self.playlists or self.notes or self.tag_ops): return None return {"items": items, "clips": list(self.clips), "playlists": list(self.playlists), - "notes": list(self.notes)} + "notes": list(self.notes), "tag_ops": list(self.tag_ops)} def proposal_json(self) -> Optional[str]: proposal = self.proposal() diff --git a/backend/app/routers/assistant.py b/backend/app/routers/assistant.py index d46e1d2..1333fdc 100644 --- a/backend/app/routers/assistant.py +++ b/backend/app/routers/assistant.py @@ -89,14 +89,14 @@ class TurnCreate(BaseModel): class ApplyBody(BaseModel): - # Apply only these assets' entries, these clips and cuts, these playlists and these - # notes. All - # absent: all of it. Any present: each restricts its own kind, and a kind left out is + # Apply only these assets' entries, these clips and cuts, these playlists, these notes + # and these tag changes. All absent: all of it. Any present: each restricts its own kind, and a kind left out is # not applied (see `apply_service.apply`). asset_ids: Optional[List[str]] = None clip_ids: Optional[List[str]] = None playlist_refs: Optional[List[str]] = None note_refs: Optional[List[str]] = None + tag_op_refs: Optional[List[str]] = None class ItemResult(BaseModel): @@ -116,6 +116,8 @@ class ItemResult(BaseModel): # Set on the result of a note: which proposed one, and where it is in Gecko Notes. note_ref: Optional[str] = None note_url: Optional[str] = None + # Set on the result of a change to the tag vocabulary: which proposed one. + op_ref: Optional[str] = None def _turn_read(row: AssistantTurn) -> TurnRead: @@ -338,8 +340,8 @@ def _pending(turn: AssistantTurn) -> dict: @router.post("/turns/{turn_id}/apply", response_model=DataResponse[List[ItemResult]]) def apply_turn(turn_id: str, user: CurrentUser, request: Request, body: ApplyBody = ApplyBody(), session: Session = Depends(get_session)) -> DataResponse[List[ItemResult]]: - """Make the proposed changes (all of them, or those for `asset_ids`, `clip_ids` and - `playlist_refs`). + """Make the proposed changes (all of them, or those for `asset_ids`, `clip_ids`, + `playlist_refs`, `note_refs` and `tag_op_refs`). Applying twice would repeat a rename over an edit made in between, so the proposal is marked applied before anything is written and a second request is refused. A failure @@ -353,7 +355,7 @@ def apply_turn(turn_id: str, user: CurrentUser, request: Request, body: ApplyBod session.add(turn) session.commit() results = apply_service.apply(session, user.id, proposal, body.asset_ids, body.clip_ids, - body.playlist_refs, body.note_refs, + body.playlist_refs, body.note_refs, body.tag_op_refs, token=_caller_token(request), origin=_origin(request)) return DataResponse(data=[ItemResult(**r) for r in results]) diff --git a/backend/app/routers/tags.py b/backend/app/routers/tags.py index cc32c7c..c2ea00a 100644 --- a/backend/app/routers/tags.py +++ b/backend/app/routers/tags.py @@ -128,12 +128,10 @@ def update_tag( renamed = False if "name" in fields and fields["name"]: - cleaned = service.normalise(fields["name"]) - clash = service.find(session, user.id, cleaned) - if clash and clash.id != tag.id: - raise _bad_request(f"You already have a tag called {clash.name}") - renamed = cleaned.lower() != tag.name.lower() or cleaned != tag.name - tag.name = cleaned + try: + renamed = service.rename_tag(session, tag, fields["name"]) + except ValueError as exc: # TagNameClash is one, with the sentence to show + raise _bad_request(str(exc)) from exc if "category_id" in fields: if fields["category_id"]: diff --git a/backend/app/services/tags.py b/backend/app/services/tags.py index a63d97d..961063b 100644 --- a/backend/app/services/tags.py +++ b/backend/app/services/tags.py @@ -6,7 +6,10 @@ from __future__ import annotations +import difflib import logging +import re +import unicodedata from typing import Iterable, Optional from sqlalchemy import text @@ -105,6 +108,158 @@ def delete_tag(session: Session, tag: Tag) -> list[str]: return asset_ids +class TagNameClash(ValueError): + """A rename onto a name another of the person's tags already has.""" + + def __init__(self, existing: Tag): + super().__init__(f"You already have a tag called {existing.name}") + self.existing = existing + + +def rename_tag(session: Session, tag: Tag, new_name: str) -> bool: + """Rename a tag, or refuse with `TagNameClash`. True if the name changed. + + A change of case alone ("nato" to "NATO") is a rename like any other: the unique index + is case-insensitive, so the tag finds itself as the clash and that is not one. The + caller re-indexes the tag's assets on True, or the old word keeps answering searches. + Does not commit, so a caller doing several things commits them together. + """ + cleaned = normalise(new_name) + if not cleaned: + raise ValueError("A tag name cannot be blank") + clash = find(session, tag.user_id, cleaned) + if clash is not None and clash.id != tag.id: + raise TagNameClash(clash) + if cleaned == tag.name: + return False + tag.name = cleaned + session.add(tag) + return True + + +def merge_tags(session: Session, sources: list[Tag], target: Tag) -> list[str]: + """Fold the source tags into the target: every asset that carried a source carries the + target, and the sources are gone. Returns the assets whose tags changed. + + The new rows skip the assets that already carry the target, because the join's + composite primary key would refuse the duplicate and fail the whole flush; an asset + tagged with both "nato" and "NATO" simply ends with one. A target with no category takes the + first source's, so merging into a new spelling does not unfile the tag. + """ + source_ids = [tag.id for tag in sources if tag.id != target.id] + if not source_ids: + return [] + affected = list(session.exec( + select(AssetTag.asset_id).where(col(AssetTag.tag_id).in_(source_ids)).distinct() + ).all()) + + held = set(session.exec(select(AssetTag.asset_id).where(AssetTag.tag_id == target.id)).all()) + session.add_all(AssetTag(asset_id=asset_id, tag_id=target.id) + for asset_id in affected if asset_id not in held) + # One transaction with the delete and the commit below, so a merge that fails part way + # leaves both tags as they were rather than an asset carrying neither. + session.flush() + session.exec(delete(AssetTag).where(col(AssetTag.tag_id).in_(source_ids))) + if target.category_id is None: + filed = next((tag.category_id for tag in sources if tag.category_id), None) + if filed: + target.category_id = filed + session.add(target) + for tag in sources: + if tag.id != target.id: + session.delete(tag) + session.commit() + return affected + + +def asset_names_for_tags( + session: Session, tag_ids: Iterable[str], limit: int = 5 +) -> tuple[int, list[str]]: + """How many assets carry any of these tags, and the names of the first few. + + What a proposal shows before it is applied: "14 assets: Interview with ..., ...". The + count and the sample are of distinct assets, so an asset carrying two of the tags + being merged is one asset, which is what the person will see change. + """ + ids = list(tag_ids) + if not ids: + return 0, [] + carrying = select(AssetTag.asset_id).where(col(AssetTag.tag_id).in_(ids)) + count = session.exec( + select(func.count()).select_from(Asset).where(col(Asset.id).in_(carrying)) + ).one() + names = session.exec( + select(Asset.name).where(col(Asset.id).in_(carrying)).order_by(col(Asset.name)).limit(limit) + ).all() + return int(count), list(names) + + +_PUNCTUATION = re.compile(r"[^\w\s]") +# Below this length a one-letter difference is a different word ("cat"/"car"), not a typo. +TYPO_MIN_LENGTH = 5 +TYPO_RATIO = 0.88 + + +def fold(name: str) -> str: + """The form two spellings of one tag share: no case, accents or punctuation, and a + naive singular. Naive on purpose: it is for proposing merges a person then reads, so a + false pair costs an untick, and a missed one costs nothing.""" + plain = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode() or name + plain = " ".join(_PUNCTUATION.sub("", plain.lower()).split()) + words = plain.split(" ") + last = words[-1] + if len(last) > 4 and last.endswith("ies"): + last = last[:-3] + "y" + elif len(last) > 4 and last.endswith(("ches", "shes", "sses", "xes")): + last = last[:-2] + elif len(last) > 3 and last.endswith("s") and not last.endswith("ss"): + last = last[:-1] + words[-1] = last + return " ".join(words) + + +def similar_groups(tags: list[Tag]) -> list[list[Tag]]: + """Tags that look like spellings of one another, in groups of two or more. + + Two passes: the same folded form ("Interviews", "interview"), then near misses between + folded forms long enough for a typo to be one ("intervew"). The second is quadratic, + which over a personal vocabulary of hundreds is nothing; joined by union-find so a + chain of near misses lands in one group rather than several overlapping ones. + """ + parent: dict[str, str] = {tag.id: tag.id for tag in tags} + + def root(tag_id: str) -> str: + while parent[tag_id] != tag_id: + parent[tag_id] = parent[parent[tag_id]] + tag_id = parent[tag_id] + return tag_id + + def join(a: str, b: str) -> None: + parent[root(a)] = root(b) + + by_fold: dict[str, str] = {} + folded = {tag.id: fold(tag.name) for tag in tags} + for tag in tags: + key = folded[tag.id] + if key in by_fold: + join(tag.id, by_fold[key]) + else: + by_fold[key] = tag.id + + keys = [k for k in by_fold if len(k) >= TYPO_MIN_LENGTH] + for i, a in enumerate(keys): + for b in keys[i + 1:]: + if abs(len(a) - len(b)) > 2: + continue + if difflib.SequenceMatcher(None, a, b).ratio() >= TYPO_RATIO: + join(by_fold[a], by_fold[b]) + + groups: dict[str, list[Tag]] = {} + for tag in tags: + groups.setdefault(root(tag.id), []).append(tag) + return [group for group in groups.values() if len(group) > 1] + + def detach_all_from_asset(session: Session, asset_id: str) -> None: """Drop every tag attachment belonging to one asset. @@ -232,6 +387,24 @@ def would_create_cycle( return True +def category_paths(categories: Iterable[TagCategory]) -> dict[str, str]: + """Every category's full path, "People > Scientists", from the flat rows. + + Bounded by MAX_CATEGORY_DEPTH rather than trusting the tree: a cycle that somehow got + in would otherwise make this loop forever on a request that only wanted to list tags. + """ + rows = {c.id: c for c in categories} + paths: dict[str, str] = {} + for category in rows.values(): + names, current, steps = [], category, 0 + while current is not None and steps < MAX_CATEGORY_DEPTH: + names.append(current.name) + current = rows.get(current.parent_category_id) if current.parent_category_id else None + steps += 1 + paths[category.id] = " > ".join(reversed(names)) + return paths + + def descendant_category_ids(session: Session, user_id: str, root_id: str) -> list[str]: """A category and everything beneath it. diff --git a/backend/tests/test_assistant_tags.py b/backend/tests/test_assistant_tags.py new file mode 100644 index 0000000..11b0c1a --- /dev/null +++ b/backend/tests/test_assistant_tags.py @@ -0,0 +1,420 @@ +"""The assistant organising the tag vocabulary: groups, renames, merges, deletes. + +As with everything the assistant does, these are proposed and made only when the person +applies them, through the same tag services the Tags panel uses. The suite is faked as in +test_assistant.py. +""" + +import json + +from sqlmodel import select + +from app.models.asset import Asset +from app.models.tag import AssetTag, Tag, TagCategory +from tests.test_assistant import new_session, reply, run +from tests.test_assistant import fake_suite_fixture as fake_suite # noqa: F401 - the fixture +from tests.test_tags import TEST_USER, add_tags, make_asset + + +def tag(session, name) -> Tag: + return session.exec(select(Tag).where(Tag.name == name)).one() + + +def category(session, user_id=TEST_USER, **fields) -> TagCategory: + row = TagCategory(user_id=user_id, **fields) + session.add(row) + session.commit() + session.refresh(row) + return row + + +def answers(fake_suite, call=1) -> list: + """What the tools said to the model, in the chat after `call`.""" + return [r for m in fake_suite.chats[call]["messages"] if m["role"] == "tool" + for r in m["results"]] + + +def apply(library, turn, **body): + res = library.post(f"/api/assistant/turns/{turn['id']}/apply", json=body or None) + assert res.status_code == 200, res.text + return res.json()["data"] + + +def found(library, word) -> list: + return [row["asset"]["id"] for row in library.get("/api/search", params={"q": word}).json()["data"]] + + +# ─── grouping ──────────────────────────────────────────────────────────────── + + +def test_tags_are_grouped_into_new_nested_categories_only_on_apply(library, session, fake_suite): + asset = make_asset(session) + add_tags(library, asset.id, "Giordano", "Schwab", "NATO") + people = category(session, name="People") + fake_suite.script += [ + reply("", ("propose_tag_groups", { + "categories": [{"name": "Scientists", "parent": people.id}, + {"name": "Organisations"}], + "file": [{"tag_ids": [tag(session, "Giordano").id, tag(session, "Schwab").id], + "category": "Scientists"}, + {"tag_ids": [tag(session, "NATO").id], "category": "organisations"}], + })), + reply("Grouped."), + ] + done = run(library, new_session(library), "Sort my tags into groups") + + ops = done["proposal"]["tag_ops"] + assert [op["kind"] for op in ops] == ["create_category", "create_category", "file_tags", + "file_tags"] + assert ops[0]["parent_label"] == "People" + assert ops[2]["category_label"] == "People > Scientists" + assert sorted(t["name"] for t in ops[2]["tags"]) == ["Giordano", "Schwab"] + assert ops[2]["asset_count"] == 1 and ops[2]["sample_assets"] == [asset.name] + # Nothing exists yet. + assert len(session.exec(select(TagCategory)).all()) == 1 + assert tag(session, "NATO").category_id is None + + results = apply(library, done) + assert all(r["skipped"] == [] for r in results), results + session.expire_all() + scientists = session.exec(select(TagCategory).where(TagCategory.name == "Scientists")).one() + organisations = session.exec(select(TagCategory).where(TagCategory.name == "Organisations")).one() + assert scientists.parent_category_id == people.id and organisations.parent_category_id is None + assert tag(session, "Giordano").category_id == scientists.id + assert tag(session, "NATO").category_id == organisations.id + # Filtering by the parent finds what was filed below it. + listed = library.get("/api/assets", params={"category_id": people.id}).json() + assert [a["id"] for a in listed["data"]] == [asset.id] + + +def test_a_category_that_exists_is_reused_not_twinned(library, session, fake_suite): + asset = make_asset(session) + add_tags(library, asset.id, "Giordano") + people = category(session, name="People") + fake_suite.script += [ + reply("", ("propose_tag_groups", { + "categories": [{"name": "people"}], + "file": [{"tag_ids": [tag(session, "Giordano").id], "category": "people"}], + })), + reply("Done."), + ] + done = run(library, new_session(library)) + assert [op["kind"] for op in done["proposal"]["tag_ops"]] == ["file_tags"] + assert "exists already" in answers(fake_suite)[0]["content"] + apply(library, done) + session.expire_all() + assert tag(session, "Giordano").category_id == people.id + assert len(session.exec(select(TagCategory)).all()) == 1 + + +def test_a_category_cannot_be_moved_inside_its_own_subcategory(library, session, fake_suite): + people = category(session, name="People") + scientists = category(session, name="Scientists", parent_category_id=people.id) + fake_suite.script += [ + reply("", ("propose_tag_groups", { + "moves": [{"category_id": people.id, "parent": scientists.id}]}), + ("propose_tag_groups", { + "categories": [{"name": "Inner", "parent": people.id}], + "moves": [{"category_id": people.id, "parent": "Inner"}]})), + reply("Couldn't."), + ] + done = run(library, new_session(library)) + first, second = answers(fake_suite) + assert first["is_error"] and "inside itself" in first["content"] + # A loop through a category proposed in the same turn is caught as well. + assert "inside itself" in second["content"] + assert [op["kind"] for op in done["proposal"]["tag_ops"]] == ["create_category"] + + +def test_an_existing_category_may_be_named_by_its_path(library, session, fake_suite): + asset = make_asset(session) + add_tags(library, asset.id, "Giordano", "misc") + people = category(session, name="People") + scientists = category(session, name="Scientists", parent_category_id=people.id) + category(session, name="Other", parent_category_id=people.id) + top_other = category(session, name="Other") + fake_suite.script += [ + reply("", ("propose_tag_groups", {"file": [ + {"tag_ids": [tag(session, "Giordano").id], "category": "scientists"}, + # Two "Other"s, but only one whose full path is "Other". + {"tag_ids": [tag(session, "misc").id], "category": "Other"}]})), + reply("Done."), + ] + done = run(library, new_session(library)) + assert [op["category_id"] for op in done["proposal"]["tag_ops"]] == [scientists.id, + top_other.id] + + +def test_an_ambiguous_category_name_is_refused(library, session, fake_suite): + asset = make_asset(session) + add_tags(library, asset.id, "Giordano") + for parent in ("People", "Places"): + row = category(session, name=parent) + category(session, name="Other", parent_category_id=row.id) + fake_suite.script += [ + reply("", ("propose_tag_groups", {"file": [{"tag_ids": [tag(session, "Giordano").id], + "category": "other"}]})), + reply("Which one?"), + ] + run(library, new_session(library)) + (said,) = answers(fake_suite) + assert said["is_error"] and "not a category id" in said["content"] + + +def test_a_tag_filed_twice_goes_to_the_latest_group(library, session, fake_suite): + asset = make_asset(session) + add_tags(library, asset.id, "Giordano") + one, two = category(session, name="One"), category(session, name="Two") + gid = tag(session, "Giordano").id + fake_suite.script += [ + reply("", ("propose_tag_groups", {"file": [{"tag_ids": [gid], "category": one.id}]}), + ("propose_tag_groups", {"file": [{"tag_ids": [gid], "category": two.id}]})), + reply("Done."), + ] + done = run(library, new_session(library)) + (op,) = done["proposal"]["tag_ops"] + assert op["category_id"] == two.id + + +# ─── renaming and merging ──────────────────────────────────────────────────── + + +def test_a_rename_applies_to_every_asset_and_moves_the_searchable_word(library, session, fake_suite): + a, b = make_asset(session, name="One"), make_asset(session, name="Two") + add_tags(library, a.id, "intervew") + add_tags(library, b.id, "intervew") + fake_suite.script += [ + reply("", ("propose_tag_rename", { + "renames": [{"tag_id": tag(session, "intervew").id, "new_name": "interview"}]})), + reply("Fixed the spelling."), + ] + done = run(library, new_session(library)) + (op,) = done["proposal"]["tag_ops"] + assert (op["kind"], op["from"], op["to"], op["asset_count"]) == ("rename_tag", "intervew", + "interview", 2) + assert op["sample_assets"] == ["One", "Two"] + assert found(library, "interview") == [] + + apply(library, done) + assert sorted(found(library, "interview")) == sorted([a.id, b.id]) + assert found(library, "intervew") == [] + + +def test_a_rename_onto_an_existing_name_is_a_merge(library, session, fake_suite): + a, b, both = (make_asset(session, name=n) for n in ("One", "Two", "Both")) + add_tags(library, a.id, "nato") + add_tags(library, b.id, "N.A.T.O.") + add_tags(library, both.id, "nato", "N.A.T.O.") + people = category(session, name="Organisations") + small = tag(session, "N.A.T.O.") + small.category_id = people.id + session.add(small) + session.commit() + fake_suite.script += [ + reply("", ("propose_tag_rename", { + "renames": [{"tag_id": small.id, "new_name": "NATO"}]})), + reply("Merged."), + ] + done = run(library, new_session(library)) + (op,) = done["proposal"]["tag_ops"] + assert op["kind"] == "merge_tags" and op["target_id"] == tag(session, "nato").id + assert op["asset_count"] == 2 # the assets carrying the source + + (result,) = apply(library, done) + assert result["skipped"] == [] and result["op_ref"] == op["op_ref"] + session.expire_all() + target = tag(session, "nato") + assert session.exec(select(Tag).where(Tag.name == "N.A.T.O.")).first() is None + carriers = session.exec(select(AssetTag.asset_id).where(AssetTag.tag_id == target.id)).all() + # Each asset once, including the one that already carried both. + assert sorted(carriers) == sorted([a.id, b.id, both.id]) + # The target had no category, so it takes the source's. + assert target.category_id == people.id + + +def test_a_merge_into_a_new_name_makes_the_tag(library, session, fake_suite): + a = make_asset(session) + add_tags(library, a.id, "interview", "Interviews") + ids = [tag(session, "interview").id, tag(session, "Interviews").id] + fake_suite.script += [ + reply("", ("propose_tag_rename", { + "merges": [{"source_tag_ids": ids, "target_name": "Interview (video)"}]})), + reply("Merged."), + ] + done = run(library, new_session(library)) + apply(library, done) + session.expire_all() + assert [t.name for t in session.exec(select(Tag)).all()] == ["Interview (video)"] + assert found(library, "video") == [a.id] + + +def test_one_tag_is_not_renamed_and_deleted_in_one_proposal(library, session, fake_suite): + a = make_asset(session) + add_tags(library, a.id, "tmp") + tid = tag(session, "tmp").id + fake_suite.script += [ + reply("", ("propose_tag_rename", {"renames": [{"tag_id": tid, "new_name": "temp"}]}), + ("propose_tag_delete", {"tag_ids": [tid]})), + reply("Done."), + ] + done = run(library, new_session(library)) + assert answers(fake_suite)[1]["is_error"] + assert [op["kind"] for op in done["proposal"]["tag_ops"]] == ["rename_tag"] + + +# ─── deleting ──────────────────────────────────────────────────────────────── + + +def test_unused_tags_are_found_and_deleted_only_on_apply(library, session, fake_suite): + a = make_asset(session) + add_tags(library, a.id, "keep") + library.post("/api/tags", json={"name": "unused"}) + fake_suite.script += [ + reply("", ("list_tags", {"max_uses": 0})), + reply("", ("propose_tag_delete", {"tag_ids": [tag(session, "unused").id]})), + reply("Removed one unused tag."), + ] + done = run(library, new_session(library)) + listing = answers(fake_suite)[0]["content"] + assert "unused (0)" in listing and "keep" not in listing + (op,) = done["proposal"]["tag_ops"] + assert op["asset_count"] == 0 + assert session.exec(select(Tag).where(Tag.name == "unused")).first() is not None + + apply(library, done) + session.expire_all() + assert [t.name for t in session.exec(select(Tag)).all()] == ["keep"] + + +# ─── choosing, staleness, ownership ────────────────────────────────────────── + + +def test_apply_takes_the_chosen_ops_and_skips_stale_ones_with_a_sentence( + library, session, fake_suite): + a = make_asset(session) + add_tags(library, a.id, "one", "two", "three") + fake_suite.script += [ + reply("", ("propose_tag_groups", {"categories": [{"name": "Numbers"}], + "file": [{"tag_ids": [tag(session, "one").id], + "category": "Numbers"}]}), + ("propose_tag_delete", {"tag_ids": [tag(session, "two").id, + tag(session, "three").id]})), + reply("Done."), + ] + done = run(library, new_session(library)) + create, file, del_two, del_three = done["proposal"]["tag_ops"] + # "three" goes away before Apply; the category is not chosen. + library.delete(f"/api/tags/{tag(session, 'three').id}") + + results = apply(library, done, tag_op_refs=[file["op_ref"], del_two["op_ref"], + del_three["op_ref"]]) + by_ref = {r["op_ref"]: r for r in results} + assert create["op_ref"] not in by_ref + assert "not made" in by_ref[file["op_ref"]]["skipped"][0] + assert by_ref[del_two["op_ref"]]["applied"] == ["deleted"] + assert by_ref[del_three["op_ref"]]["skipped"] == ["The tag no longer exists."] + session.expire_all() + assert session.exec(select(TagCategory)).all() == [] + assert tag(session, "one").category_id is None + + +def test_choosing_assets_alone_applies_no_tag_changes(library, session, fake_suite): + """A client that names the assets it wants has never heard of tag changes, and must not + get them as a side effect.""" + a = make_asset(session) + add_tags(library, a.id, "old") + fake_suite.script += [ + reply("", ("propose_changes", {"asset_id": a.id, "name": "Renamed"}), + ("propose_tag_delete", {"tag_ids": [tag(session, "old").id]})), + reply("Done."), + ] + done = run(library, new_session(library)) + apply(library, done, asset_ids=[a.id]) + session.expire_all() + assert session.get(Asset, a.id).name == "Renamed" + assert tag(session, "old") is not None + + +def test_someone_elses_tags_and_categories_are_reported_missing(library, session, fake_suite): + theirs = Tag(user_id="someone-else", name="private") + session.add(theirs) + session.commit() + their_group = category(session, user_id="someone-else", name="Theirs") + fake_suite.script += [ + reply("", ("propose_tag_delete", {"tag_ids": [theirs.id]}), + ("propose_tag_rename", {"renames": [{"tag_id": theirs.id, "new_name": "mine"}]}), + ("propose_tag_groups", {"moves": [{"category_id": their_group.id, "new_name": "x"}]})), + reply("Couldn't."), + ] + done = run(library, new_session(library)) + assert all(r["is_error"] for r in answers(fake_suite)) + assert done["proposal"] is None + session.refresh(theirs) + assert theirs.name == "private" + + +# ─── looking ───────────────────────────────────────────────────────────────── + + +def test_similar_tags_are_found_in_groups(library, session, fake_suite): + a = make_asset(session) + add_tags(library, a.id, "interview", "Interviews", "intervew", "NATO", "nato.", "river") + fake_suite.script += [reply("", ("find_similar_tags", {})), reply("Found two groups.")] + run(library, new_session(library)) + text = answers(fake_suite)[0]["content"] + lines = [line for line in text.splitlines() if line.startswith("- ")] + assert len(lines) == 2 + assert all(n in " ".join(lines) for n in ("interview", "Interviews", "intervew", "NATO", "nato.")) + assert "river" not in text + + +def test_a_large_vocabulary_is_listed_in_pages_and_can_all_be_filed(library, session, fake_suite): + a = make_asset(session) + for start in range(0, 250, 50): + add_tags(library, a.id, *(f"tag {n:03d}" for n in range(start, start + 50))) + filed = category(session, name="Old") + old = tag(session, "tag 000") + old.category_id = filed.id + session.add(old) + session.commit() + ids = [t.id for t in session.exec(select(Tag)).all() if t.name != "tag 000"] + fake_suite.script += [ + reply("", ("list_tags", {}), ("list_tags", {"offset": 200}), + ("list_tags", {"uncategorised_only": True})), + reply("", ("propose_tag_groups", { + "categories": [{"name": "Numbers"}] + [ + {"name": f"Batch {n}", "parent": "Numbers"} for n in range(5)], + "file": [{"tag_ids": ids[n * 50:(n + 1) * 50], "category": f"Batch {n}"} + for n in range(5)], + })), + reply("All filed."), + ] + done = run(library, new_session(library)) + first, second, unfiled = (r["content"] for r in answers(fake_suite)) + assert "250 tag(s), 249 not in any category; 1 category." in first + assert "Tags 1-200 of 250" in first and "[more: call again with offset=200]" in first + assert f"{filed.id} | Old" in first + assert "Tags 201-250 of 250" in second and "[more" not in second + assert "of 249" in unfiled and "| Old" not in unfiled.split("Tags")[1] + + assert len(done["proposal"]["tag_ops"]) == 11 + apply(library, done) + session.expire_all() + assert [t.name for t in session.exec(select(Tag).where(Tag.category_id.is_(None))).all()] == [] + + +def test_a_turn_from_before_tag_changes_existed_still_applies(library, session, fake_suite): + a = make_asset(session) + fake_suite.script += [reply("", ("propose_changes", {"asset_id": a.id, "name": "New"})), + reply("Done.")] + done = run(library, new_session(library)) + from app.models.assistant import AssistantTurn + + row = session.get(AssistantTurn, done["id"]) + proposal = json.loads(row.proposal) + proposal.pop("tag_ops") + row.proposal = json.dumps(proposal) + session.add(row) + session.commit() + (result,) = apply(library, done) + assert result["applied"] == ["name"] diff --git a/backend/tests/test_tags.py b/backend/tests/test_tags.py index bab5d5c..223d8d8 100644 --- a/backend/tests/test_tags.py +++ b/backend/tests/test_tags.py @@ -89,6 +89,44 @@ def test_renaming_a_tag_moves_the_searchable_word(library, session): assert [row["asset"]["id"] for row in found["data"]] == [asset.id] +def test_renaming_onto_another_tags_name_is_refused(library, session): + asset = make_asset(session) + add_tags(library, asset.id, "nato", "psyop") + tag = session.exec(select(Tag).where(Tag.name == "psyop")).one() + + res = library.patch(f"/api/tags/{tag.id}", json={"name": "NATO"}) + assert res.status_code == 400 + assert res.json()["detail"]["message"] == "You already have a tag called nato" + # A change of case alone is a rename, not a clash with itself. + res = library.patch(f"/api/tags/{tag.id}", json={"name": "PSYOP"}) + assert res.status_code == 200 and res.json()["data"]["name"] == "PSYOP" + + +def test_merging_tags_keeps_one_attachment_per_asset(library, session): + """An asset carrying both the source and the target ends with the target once: the + join's composite key would refuse a second row and fail the whole merge.""" + only_source, both = make_asset(session, name="One"), make_asset(session, name="Both") + add_tags(library, only_source.id, "nato") + add_tags(library, both.id, "nato", "NATO alliance") + source = session.exec(select(Tag).where(Tag.name == "nato")).one() + target = session.exec(select(Tag).where(Tag.name == "NATO alliance")).one() + + affected = service.merge_tags(session, [source], target) + + assert sorted(affected) == sorted([only_source.id, both.id]) + assert session.exec(select(Tag).where(Tag.name == "nato")).first() is None + rows = session.exec(select(AssetTag).where(AssetTag.tag_id == target.id)).all() + assert sorted(r.asset_id for r in rows) == sorted([only_source.id, both.id]) + + +def test_look_alike_tags_are_grouped_and_different_words_are_not(): + tags = [Tag(id=name, user_id=TEST_USER, name=name) for name in ( + "interview", "Interviews", "intervew", "Café", "cafe", "cat", "car", "Studies", "study")] + groups = sorted(sorted(t.name for t in g) for g in service.similar_groups(tags)) + assert groups == [["Café", "cafe"], ["Interviews", "intervew", "interview"], + ["Studies", "study"]] + + # ─── case ──────────────────────────────────────────────────────────────────── diff --git a/frontend/src/api/assistant.ts b/frontend/src/api/assistant.ts index c84022d..af7707e 100644 --- a/frontend/src/api/assistant.ts +++ b/frontend/src/api/assistant.ts @@ -116,6 +116,62 @@ export interface ProposalNote { asset_ids: string[] } +/** The assistant's preview of who a tag change touches, taken when it was proposed. */ +interface TagOpPreview { + op_ref: string + /** Distinct assets carrying the tags concerned. */ + asset_count?: number + /** The first few of their names, for the card. */ + sample_assets?: string[] +} + +export interface TagRef { + id: string + name: string +} + +/** + * A change to the tag vocabulary rather than to one asset. Categories are the groups tags + * are filed under, and nest. A `*_ref` names a category proposed in the same turn; on Apply + * the server runs them in dependency order and skips, with a sentence, one that no longer + * makes sense. + */ +export type ProposalTagOp = + | (TagOpPreview & { + kind: 'create_category' + name: string + parent_category_id: string | null + parent_ref: string | null + parent_label: string | null + }) + | (TagOpPreview & { + kind: 'move_category' + category_id: string + name: string + from_path: string + /** False when only renamed. */ + move: boolean + parent_label: string | null + new_name: string | null + }) + | (TagOpPreview & { + kind: 'file_tags' + tags: TagRef[] + category_id: string | null + category_ref: string | null + /** Null: taken out of every category. */ + category_label: string | null + }) + | (TagOpPreview & { kind: 'rename_tag'; tag_id: string; from: string; to: string }) + | (TagOpPreview & { + kind: 'merge_tags' + sources: TagRef[] + /** Null when merging into a name no tag has yet. */ + target_id: string | null + target_name: string + }) + | (TagOpPreview & { kind: 'delete_tag'; tag_id: string; name: string }) + export interface Proposal { items: ProposalItem[] /** Absent on a turn from before clips could be proposed. */ @@ -124,6 +180,8 @@ export interface Proposal { playlists?: ProposalPlaylist[] /** Absent on a turn from before notes could be proposed. */ notes?: ProposalNote[] + /** Absent on a turn from before the tag vocabulary could be changed. */ + tag_ops?: ProposalTagOp[] } export type TurnStatus = 'queued' | 'processing' | 'done' | 'error' | 'cancelled' @@ -170,6 +228,8 @@ export interface ApplyResult { /** Set on the result of a note: which proposed one, and its page in Gecko Notes. */ note_ref?: string | null note_url?: string | null + /** Set on the result of a tag change: which proposed one. */ + op_ref?: string | null } /** @@ -181,6 +241,7 @@ export interface ApplySelection { clipIds?: string[] playlistRefs?: string[] noteRefs?: string[] + tagOpRefs?: string[] } export function isActiveTurn(turn: Pick): boolean { @@ -259,6 +320,7 @@ export const assistantApi = { clip_ids: selection?.clipIds ?? null, playlist_refs: selection?.playlistRefs ?? null, note_refs: selection?.noteRefs ?? null, + tag_op_refs: selection?.tagOpRefs ?? null, }) .then((r) => r.data.data) }, diff --git a/frontend/src/components/AssistantPanel.test.tsx b/frontend/src/components/AssistantPanel.test.tsx index 4def771..cd36fd0 100644 --- a/frontend/src/components/AssistantPanel.test.tsx +++ b/frontend/src/components/AssistantPanel.test.tsx @@ -10,6 +10,7 @@ import { type AssistantTurn, type ProposalItem, } from '@/api/assistant' +import { tagsApi } from '@/api/tags' import AssistantPanel from '@/components/AssistantPanel' import { useAssistantStore } from '@/stores/assistant' @@ -154,6 +155,7 @@ describe('AssistantPanel', () => { clipIds: [], playlistRefs: [], noteRefs: [], + tagOpRefs: [], }) }) @@ -211,6 +213,7 @@ describe('AssistantPanel', () => { clipIds: ['k1'], playlistRefs: [], noteRefs: [], + tagOpRefs: [], }) }) @@ -285,6 +288,7 @@ describe('AssistantPanel', () => { clipIds: [], playlistRefs: ['p1'], noteRefs: [], + tagOpRefs: [], }) }) @@ -379,6 +383,88 @@ describe('AssistantPanel', () => { ).toHaveAttribute('href', 'https://notes.test/notes/abc') }) + it('shows tag changes with who they touch, and applies only the ones ticked', async () => { + const apply = vi.spyOn(assistantApi, 'apply').mockResolvedValue([ + { + asset_id: null, + asset_name: 'NATO', + applied: ['1 tag(s) merged into NATO'], + skipped: [], + op_ref: 'o2', + }, + ]) + const tagList = vi.spyOn(tagsApi, 'list').mockResolvedValue([]) + vi.spyOn(tagsApi, 'listCategories').mockResolvedValue([]) + const proposal = { + items: [], + tag_ops: [ + { + op_ref: 'o1', + kind: 'file_tags' as const, + tags: [ + { id: 't1', name: 'Giordano' }, + { id: 't2', name: 'Schwab' }, + ], + category_id: 'c1', + category_ref: null, + category_label: 'People > Scientists', + asset_count: 3, + sample_assets: ['One', 'Two', 'Three'], + }, + { + op_ref: 'o2', + kind: 'merge_tags' as const, + sources: [{ id: 't3', name: 'nato' }], + target_id: 't4', + target_name: 'NATO', + asset_count: 7, + sample_assets: ['Briefing', 'Summit'], + }, + { + op_ref: 'o3', + kind: 'delete_tag' as const, + tag_id: 't5', + name: 'tmp', + asset_count: 0, + sample_assets: [], + }, + ], + } + vi.spyOn(assistantApi, 'getTurn').mockResolvedValue( + turn({ outcome: 'applied', proposal }) + ) + await show(READY, [turn({ outcome: 'pending', proposal })]) + const card = await screen.findByLabelText(/proposed changes/i) + expect(within(card).getByText('People > Scientists')).toBeInTheDocument() + expect(within(card).getByText(/2 tags filed here · on 3 assets/)).toBeInTheDocument() + await userEvent.click(within(card).getByRole('button', { name: 'Show the tags' })) + expect(within(card).getByLabelText(/tags filed in people/i)).toHaveTextContent( + 'GiordanoSchwab' + ) + expect(within(card).getByText('nato → NATO')).toBeInTheDocument() + expect(within(card).getByText(/Briefing, Summit \+5 more/)).toBeInTheDocument() + expect(within(card).getByText('unused')).toBeInTheDocument() + + await userEvent.click( + within(card).getByRole('checkbox', { name: /include file tags/i }) + ) + await userEvent.click( + within(card).getByRole('checkbox', { name: /include delete tag/i }) + ) + await userEvent.click(within(card).getByRole('button', { name: /apply 1 of 3/i })) + expect(apply).toHaveBeenCalledWith('t1', { + assetIds: [], + clipIds: [], + playlistRefs: [], + noteRefs: [], + tagOpRefs: ['o2'], + }) + const after = await screen.findByLabelText(/proposed changes/i) + expect(await within(after).findByText(/merged into NATO/)).toBeInTheDocument() + // The vocabulary changed, so the catalogue the Tags panel shows is fetched again. + expect(tagList).toHaveBeenCalled() + }) + it('applies everything with no selection when nothing is unticked', async () => { const apply = vi.spyOn(assistantApi, 'apply').mockResolvedValue([]) vi.spyOn(assistantApi, 'getTurn').mockResolvedValue(turn()) diff --git a/frontend/src/components/AssistantPanel.tsx b/frontend/src/components/AssistantPanel.tsx index 8a131c3..1e88681 100644 --- a/frontend/src/components/AssistantPanel.tsx +++ b/frontend/src/components/AssistantPanel.tsx @@ -11,6 +11,7 @@ import { type ProposalNote, type ProposalPlaylist, type ProposalItem, + type ProposalTagOp, } from '@/api/assistant' import { currentConfig, loadConfig } from '@/api/config' import { suiteSpeechApi, type DictationReadiness } from '@/api/suiteSpeech' @@ -398,16 +399,23 @@ function ProposalCard({ const clips = proposal.clips ?? [] const playlists = proposal.playlists ?? [] const notes = proposal.notes ?? [] + const tagOps = proposal.tag_ops ?? [] // Ticked off by id: an asset's id for its edits, a clip's own id for a clip or a cut, - // a playlist's ref for a playlist, a note's for a note. + // a playlist's ref for a playlist, a note's for a note, an op's for a tag change. const [skipped, setSkipped] = useState>(new Set()) const chosen = items.filter((item) => !skipped.has(item.asset_id)) const chosenClips = clips.filter((clip) => !skipped.has(clip.clip_id)) const chosenPlaylists = playlists.filter((p) => !skipped.has(p.playlist_ref)) const chosenNotes = notes.filter((n) => !skipped.has(n.note_ref)) - const total = items.length + clips.length + playlists.length + notes.length + const chosenTagOps = tagOps.filter((op) => !skipped.has(op.op_ref)) + const total = + items.length + clips.length + playlists.length + notes.length + tagOps.length const picked = - chosen.length + chosenClips.length + chosenPlaylists.length + chosenNotes.length + chosen.length + + chosenClips.length + + chosenPlaylists.length + + chosenNotes.length + + chosenTagOps.length const pending = turn.outcome === 'pending' function toggle(id: string) { @@ -500,6 +508,20 @@ function ProposalCard({ } /> ))} + {tagOps.map((op) => ( + toggle(op.op_ref)} + result={ + !pending && turn.outcome === 'applied' + ? applied?.find((r) => r.op_ref === op.op_ref) + : undefined + } + /> + ))} {pending && (
@@ -517,6 +539,7 @@ function ProposalCard({ clipIds: chosenClips.map((c) => c.clip_id), playlistRefs: chosenPlaylists.map((p) => p.playlist_ref), noteRefs: chosenNotes.map((n) => n.note_ref), + tagOpRefs: chosenTagOps.map((op) => op.op_ref), } ) } @@ -773,6 +796,139 @@ function NoteRow({ ) } +const TAG_OP_BADGE: Record = { + create_category: 'New group', + move_category: 'Move group', + file_tags: 'File tags', + rename_tag: 'Rename tag', + merge_tags: 'Merge tags', + delete_tag: 'Delete tag', +} + +/** What a tag change does, in a line: the thing changed and where it ends up. */ +function tagOpSummary(op: ProposalTagOp): { title: string; detail: string } { + switch (op.kind) { + case 'create_category': + return { + title: op.name, + detail: op.parent_label ? `Inside ${op.parent_label}` : 'At the top level', + } + case 'move_category': { + const parts = [] + if (op.move) + parts.push(op.parent_label ? `Into ${op.parent_label}` : 'To the top level') + if (op.new_name) parts.push(`renamed “${op.new_name}”`) + return { title: op.from_path, detail: parts.join(', ') } + } + case 'file_tags': { + const n = op.tags.length + return { + title: op.category_label ?? 'No group', + detail: `${n} ${n === 1 ? 'tag' : 'tags'}${op.category_label ? ' filed here' : ' taken out of their group'}`, + } + } + case 'rename_tag': + return { title: `${op.from} → ${op.to}`, detail: '' } + case 'merge_tags': + return { + title: `${op.sources.map((t) => t.name).join(', ')} → ${op.target_name}`, + detail: op.target_id ? '' : `“${op.target_name}” is a new tag`, + } + case 'delete_tag': + return { title: op.name, detail: '' } + } +} + +/** One change to the tag vocabulary, with who it touches, to read before applying. */ +function TagOpRow({ + op, + pending, + included, + onToggle, + result, +}: { + op: ProposalTagOp + pending: boolean + included: boolean + onToggle: () => void + result?: ApplyResult +}) { + const [open, setOpen] = useState(false) + const { title, detail } = tagOpSummary(op) + const count = op.asset_count + const sample = op.sample_assets ?? [] + // Renames, merges and deletes change what assets carry, so how many is the point. Filing + // only moves tags between groups; its count is context, not a warning. + const touchesAssets = + op.kind === 'rename_tag' || op.kind === 'merge_tags' || op.kind === 'delete_tag' + return ( +
  • +
    + {pending && ( + + )} + + {TAG_OP_BADGE[op.kind]} + + + {title} + +
    + {(detail || count !== undefined) && ( +

    + {detail} + {detail && count !== undefined && ' · '} + {count !== undefined && + (count === 0 + ? touchesAssets + ? 'unused' + : 'on no assets yet' + : `${touchesAssets ? '' : 'on '}${count} ${count === 1 ? 'asset' : 'assets'}`)} + {op.kind === 'file_tags' && ( + <> + {' '} + + + )} +

    + )} + {op.kind === 'file_tags' && open && ( +

    + {op.tags.map((tag) => ( + + {tag.name} + + ))} +

    + )} + {touchesAssets && sample.length > 0 && ( +

    + {sample.join(', ')} + {count !== undefined && + count > sample.length && + ` +${count - sample.length} more`} +

    + )} + +
  • + ) +} + function Changes({ item }: { item: ProposalItem }) { const rows: { label: string; from?: string | null; to: string }[] = [] if (item.name) rows.push({ label: 'Name', from: item.before.name, to: item.name }) diff --git a/frontend/src/stores/assistant.ts b/frontend/src/stores/assistant.ts index a2d17d8..60e4873 100644 --- a/frontend/src/stores/assistant.ts +++ b/frontend/src/stores/assistant.ts @@ -263,7 +263,12 @@ export const useAssistantStore = create((set, get) => { putTurn(turn) // The library on screen and the tag vocabulary are now behind what was written. void useLibraryStore.getState().load() - useTagStore.getState().reset() + // A reset is enough when only assets' tags changed: the catalogue is fetched again + // where it is next needed. Changes to the vocabulary itself are reloaded at once, + // because the Tags panel and the filter bar are likely open beside the card, and + // they would sit empty after a reset until something else asked. + if (results.some((r) => r.op_ref)) void useTagStore.getState().load() + else useTagStore.getState().reset() // A playlist it made or added to, perhaps the one open on the page beside it. const playlists = usePlaylistStore.getState() if (playlists.loaded) void playlists.load() From 5c04f115f18c07ef70d42562727fd34097dd4cea Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 14:10:18 +0000 Subject: [PATCH 2/2] Add merging to the Tags panel A tag row gets a merge button that opens a "Merge into" step. It says what will happen before anything does: how many assets will carry the target instead, that the source is deleted and this can't be undone, and whether the target takes over its category. Renaming a tag onto a name another tag has opens the same step, already pointed at that tag, rather than only refusing. Backed by POST /api/tags/{id}/merge, over the same services.tags.merge_tags the assistant's merges apply through. It returns the target with its new count and re-indexes the moved assets. The store's merge is not optimistic: the count is the server's, and a merge cannot be put back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V1geD6BRzqbfoJdeGyQ4Kb --- backend/app/routers/tags.py | 26 ++ backend/app/schemas_tags.py | 6 + backend/tests/test_tags.py | 33 +++ frontend/src/api/tags.ts | 7 + frontend/src/components/TagPanel.test.tsx | 69 +++++ frontend/src/components/TagPanel.tsx | 328 ++++++++++++++++------ frontend/src/stores/tags.test.ts | 24 ++ frontend/src/stores/tags.ts | 23 ++ 8 files changed, 431 insertions(+), 85 deletions(-) diff --git a/backend/app/routers/tags.py b/backend/app/routers/tags.py index c2ea00a..beb1ce6 100644 --- a/backend/app/routers/tags.py +++ b/backend/app/routers/tags.py @@ -14,6 +14,7 @@ TagCategoryRead, TagCategoryUpdate, TagCreate, + TagMerge, TagRead, TagUpdate, ) @@ -148,6 +149,31 @@ def update_tag( return DataResponse[TagRead](data=_to_read(tag)) +@router.post("/{tag_id}/merge", response_model=DataResponse[TagRead]) +def merge_tag( + tag_id: str, + payload: TagMerge, + user: CurrentUser, + session: Session = Depends(get_session), +) -> DataResponse[TagRead]: + """Fold this tag into another: every asset carrying it carries the target instead, and + this tag is deleted. Returns the target with its new count. + + What a rename onto an existing name would have to be. A rename refuses that, because + two tags becoming one is not undoable and should be asked for by name, not stumbled + into by typing. + """ + source = _owned_tag(tag_id, user.id, session) + target = _owned_tag(payload.target_id, user.id, session) + if source.id == target.id: + raise _bad_request("A tag cannot be merged into itself") + affected = service.merge_tags(session, [source], target) + session.refresh(target) + asset_service.reindex_ids(session, affected) + counts = service.usage_counts(session, user.id) + return DataResponse[TagRead](data=_to_read(target, counts)) + + # response_model=None alongside the `-> None` annotation: FastAPI infers a response # model from the return type, and NoneType is a type like any other, so it would try # to give a 204 a body and refuse at import time. diff --git a/backend/app/schemas_tags.py b/backend/app/schemas_tags.py index 1c6d7ab..1755873 100644 --- a/backend/app/schemas_tags.py +++ b/backend/app/schemas_tags.py @@ -59,6 +59,12 @@ def _clean(cls, value: Optional[str]) -> Optional[str]: return None if value is None else _not_blank(value, "A tag name") +class TagMerge(BaseModel): + """Fold the tag in the path into this one.""" + + target_id: str = Field(min_length=1) + + class TagCategoryRead(BaseModel): id: str name: str diff --git a/backend/tests/test_tags.py b/backend/tests/test_tags.py index 223d8d8..2ef6022 100644 --- a/backend/tests/test_tags.py +++ b/backend/tests/test_tags.py @@ -119,6 +119,39 @@ def test_merging_tags_keeps_one_attachment_per_asset(library, session): assert sorted(r.asset_id for r in rows) == sorted([only_source.id, both.id]) +def test_merging_through_the_api_moves_every_asset_and_the_searchable_word(library, session): + a, b = make_asset(session, name="One"), make_asset(session, name="Two") + add_tags(library, a.id, "nato") + add_tags(library, b.id, "nato", "NATO alliance") + source = session.exec(select(Tag).where(Tag.name == "nato")).one() + target = session.exec(select(Tag).where(Tag.name == "NATO alliance")).one() + + res = library.post(f"/api/tags/{source.id}/merge", json={"target_id": target.id}) + + assert res.status_code == 200, res.text + assert res.json()["data"] == {"id": target.id, "name": "NATO alliance", + "category_id": None, "asset_count": 2} + assert [t["name"] for t in library.get("/api/tags").json()["data"]] == ["NATO alliance"] + found = library.get("/api/search", params={"q": "alliance"}).json()["data"] + assert sorted(row["asset"]["id"] for row in found) == sorted([a.id, b.id]) + + +def test_a_tag_cannot_be_merged_into_itself_or_someone_elses(library, session): + asset = make_asset(session) + add_tags(library, asset.id, "nato") + mine = session.exec(select(Tag).where(Tag.name == "nato")).one() + theirs = Tag(user_id="someone-else", name="NATO") + session.add(theirs) + session.commit() + + itself = library.post(f"/api/tags/{mine.id}/merge", json={"target_id": mine.id}) + assert itself.status_code == 400 + assert itself.json()["detail"]["code"] == "bad_request" + stranger = library.post(f"/api/tags/{mine.id}/merge", json={"target_id": theirs.id}) + assert stranger.status_code == 404 + assert session.get(Tag, mine.id) is not None + + def test_look_alike_tags_are_grouped_and_different_words_are_not(): tags = [Tag(id=name, user_id=TEST_USER, name=name) for name in ( "interview", "Interviews", "intervew", "Café", "cafe", "cat", "car", "Studies", "study")] diff --git a/frontend/src/api/tags.ts b/frontend/src/api/tags.ts index d029b57..153e26b 100644 --- a/frontend/src/api/tags.ts +++ b/frontend/src/api/tags.ts @@ -64,6 +64,13 @@ export const tagsApi = { return client.delete(`/tags/${id}`).then(() => undefined) }, + /** Fold one tag into another across every asset. Returns the target, with its new count. */ + merge(id: string, targetId: string): Promise { + return client + .post>(`/tags/${id}/merge`, { target_id: targetId }) + .then((r) => r.data.data) + }, + listCategories(): Promise { return client .get>('/tags/categories/all') diff --git a/frontend/src/components/TagPanel.test.tsx b/frontend/src/components/TagPanel.test.tsx index c11d63f..6ed3c37 100644 --- a/frontend/src/components/TagPanel.test.tsx +++ b/frontend/src/components/TagPanel.test.tsx @@ -113,6 +113,75 @@ describe('TagPanel', () => { ).toBeInTheDocument() }) + it('merges a tag into another after saying what will happen', async () => { + vi.spyOn(tagsApi, 'list').mockResolvedValue([ + tag(), + tag({ id: 't2', name: 'Interviews', asset_count: 10 }), + ]) + const merge = vi + .spyOn(tagsApi, 'merge') + .mockResolvedValue(tag({ id: 't2', name: 'Interviews', asset_count: 12 })) + render() + await screen.findByText('interview') + + await userEvent.click( + screen.getByRole('button', { name: 'Merge interview into another tag' }) + ) + const step = screen.getByRole('group', { name: 'Merge interview' }) + expect(screen.getByRole('button', { name: 'Merge' })).toBeDisabled() + await userEvent.selectOptions( + screen.getByRole('combobox', { name: 'Merge interview into' }), + 't2' + ) + expect(step).toHaveTextContent( + '3 assets will carry “Interviews” instead of “interview”. “interview” is then deleted.' + ) + await userEvent.click(screen.getByRole('button', { name: 'Merge' })) + + await waitFor(() => expect(merge).toHaveBeenCalledWith('t1', 't2')) + await waitFor(() => expect(screen.queryByText('interview')).not.toBeInTheDocument()) + expect(useTagStore.getState().tags).toEqual([ + tag({ id: 't2', name: 'Interviews', asset_count: 12 }), + ]) + }) + + it('offers a merge, already pointed at the other tag, when a rename collides', async () => { + vi.spyOn(tagsApi, 'list').mockResolvedValue([ + tag(), + tag({ id: 't2', name: 'Talk', asset_count: 1 }), + ]) + const rename = vi.spyOn(tagsApi, 'rename') + render() + await screen.findByText('interview') + + await userEvent.click(screen.getByRole('button', { name: 'Rename interview' })) + const field = screen.getByRole('textbox', { name: 'Rename interview' }) + await userEvent.clear(field) + await userEvent.type(field, 'talk{Enter}') + + expect(rename).not.toHaveBeenCalled() + expect(screen.getByRole('combobox', { name: 'Merge interview into' })).toHaveValue( + 't2' + ) + expect(screen.getByRole('button', { name: 'Merge' })).toBeEnabled() + }) + + it('cancelling a merge changes nothing', async () => { + const merge = vi.spyOn(tagsApi, 'merge') + render() + await screen.findByText('interview') + + await userEvent.click( + screen.getByRole('button', { name: 'Merge interview into another tag' }) + ) + await userEvent.click(screen.getByRole('button', { name: 'Cancel' })) + + expect( + screen.queryByRole('group', { name: 'Merge interview' }) + ).not.toBeInTheDocument() + expect(merge).not.toHaveBeenCalled() + }) + it('says a category delete keeps its contents, because it does', async () => { render() await screen.findByText('interview') diff --git a/frontend/src/components/TagPanel.tsx b/frontend/src/components/TagPanel.tsx index e4e010f..69e53b2 100644 --- a/frontend/src/components/TagPanel.tsx +++ b/frontend/src/components/TagPanel.tsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useState } from 'react' -import { Check, FolderPlus, Pencil, Plus, Tags, Trash2, X } from 'lucide-react' +import { Check, FolderPlus, GitMerge, Pencil, Plus, Tags, Trash2, X } from 'lucide-react' import { buildCategoryTree, type CategoryNode, type Tag } from '@/api/tags' import { useTagStore } from '@/stores/tags' @@ -26,6 +26,7 @@ export default function TagPanel() { const renameTag = useTagStore((s) => s.rename) const recategorise = useTagStore((s) => s.recategorise) const removeTag = useTagStore((s) => s.remove) + const mergeTags = useTagStore((s) => s.merge) const createCategory = useTagStore((s) => s.createCategory) const updateCategory = useTagStore((s) => s.updateCategory) const removeCategory = useTagStore((s) => s.removeCategory) @@ -35,6 +36,9 @@ export default function TagPanel() { const [editingTag, setEditingTag] = useState(null) const [editingCategory, setEditingCategory] = useState(null) const [draft, setDraft] = useState('') + // The tag being merged, and into which. One at a time: the step under a row is a + // question about that row, and two open at once could each name the other. + const [merging, setMerging] = useState<{ id: string; targetId: string } | null>(null) useEffect(() => { ensureLoaded() @@ -80,6 +84,16 @@ export default function TagPanel() { const name = draft.trim() setEditingTag(null) if (!name || name === tag.name) return + // Renaming onto a name another tag has is refused by the server: two tags becoming one + // is a merge, and a merge should be asked for. So offer it, already pointed at that tag, + // rather than only saying no. + const clash = tags.find( + (t) => t.id !== tag.id && t.name.toLowerCase() === name.toLowerCase() + ) + if (clash) { + setMerging({ id: tag.id, targetId: clash.id }) + return + } try { await renameTag(tag.id, name) } catch { @@ -87,6 +101,24 @@ export default function TagPanel() { } } + const commitMerge = async () => { + if (!merging?.targetId) return + const { id, targetId } = merging + setMerging(null) + try { + await mergeTags(id, targetId) + } catch { + /* the store holds the sentence */ + } + } + + const mergeProps = { + allTags: tags, + merging, + setMerging, + commitMerge, + } + const commitCategoryRename = async (node: CategoryNode) => { const name = draft.trim() setEditingCategory(null) @@ -106,8 +138,9 @@ export default function TagPanel() {

    - Rename, delete and file your tags. Deleting a category keeps its tags and - sub-categories — they move to the top level rather than going with it. + Rename, merge, delete and file your tags. Merging folds one tag into another on + every asset that carries it. Deleting a category keeps its tags and sub-categories + — they move to the top level rather than going with it.

    {storeError && ( @@ -256,6 +289,7 @@ export default function TagPanel() { commitRename={commitRename} recategorise={recategorise} removeTag={removeTag} + {...mergeProps} />
    ))} @@ -274,6 +308,7 @@ export default function TagPanel() { commitRename={commitRename} recategorise={recategorise} removeTag={removeTag} + {...mergeProps} /> @@ -291,6 +326,10 @@ interface RowsProps { commitRename: (tag: Tag) => Promise recategorise: (id: string, categoryId: string | null) => Promise removeTag: (id: string) => Promise + allTags: Tag[] + merging: { id: string; targetId: string } | null + setMerging: (value: { id: string; targetId: string } | null) => void + commitMerge: () => Promise } function TagRows({ @@ -303,6 +342,10 @@ function TagRows({ commitRename, recategorise, removeTag, + allTags, + merging, + setMerging, + commitMerge, }: RowsProps) { if (tags.length === 0) { return

    No tags here.

    @@ -311,89 +354,114 @@ function TagRows({ return (
      {tags.map((tag) => ( -
    • - {editingTag === tag.id ? ( - <> - setDraft(e.target.value)} - onKeyDown={(e) => { - if (e.key === 'Enter') void commitRename(tag) - if (e.key === 'Escape') setEditingTag(null) - }} - aria-label={`Rename ${tag.name}`} - /> - - - - ) : ( - <> - - {tag.name} - - {typeof tag.asset_count === 'number' && ( - - {tag.asset_count} +
    • +
      + {editingTag === tag.id ? ( + <> + setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') void commitRename(tag) + if (e.key === 'Escape') setEditingTag(null) + }} + aria-label={`Rename ${tag.name}`} + /> + + + + ) : ( + <> + + {tag.name} - )} - - - - + {typeof tag.asset_count === 'number' && ( + + {tag.asset_count} + + )} + + + + + + )} +
      + {merging?.id === tag.id && ( + setMerging({ id: tag.id, targetId })} + onCancel={() => setMerging(null)} + onMerge={() => void commitMerge()} + /> )}
    • ))} @@ -401,6 +469,96 @@ function TagRows({ ) } +/** + * Choosing what a tag merges into, and saying what will happen before it does. + * + * The preview is the point: a merge cannot be undone, and "12 assets will carry NATO + * instead" is what a person needs to read to know they picked the right one. + */ +function MergeStep({ + source, + allTags, + targetId, + onTarget, + onCancel, + onMerge, +}: { + source: Tag + allTags: Tag[] + targetId: string + onTarget: (id: string) => void + onCancel: () => void + onMerge: () => void +}) { + const others = useMemo( + () => + allTags + .filter((t) => t.id !== source.id) + .sort((a, b) => a.name.localeCompare(b.name)), + [allTags, source.id] + ) + const target = others.find((t) => t.id === targetId) + const count = source.asset_count + const plural = (n: number) => (n === 1 ? 'asset' : 'assets') + return ( +
      + + {target && ( +

      + {typeof count === 'number' + ? count === 0 + ? `“${source.name}” is on no assets, so this only removes it.` + : `${count} ${plural(count)} will carry “${target.name}” instead of “${source.name}”.` + : `Every asset carrying “${source.name}” will carry “${target.name}” instead.`}{' '} + {`“${source.name}” is then deleted. This cannot be undone.`} + {!target.category_id && source.category_id + ? ` “${target.name}” takes over its category.` + : ''} +

      + )} +
      + + +
      +
      + ) +} + function flatten( nodes: CategoryNode[], depth = 0 diff --git a/frontend/src/stores/tags.test.ts b/frontend/src/stores/tags.test.ts index 02cd9ca..69d6f67 100644 --- a/frontend/src/stores/tags.test.ts +++ b/frontend/src/stores/tags.test.ts @@ -46,6 +46,30 @@ describe('useTagStore', () => { expect(useTagStore.getState().error).toBeTruthy() }) + it('leaves both tags in place until a merge succeeds, and keeps them if it fails', async () => { + const both = [tag(), tag({ id: 't2', name: 'Interviews', asset_count: 4 })] + useTagStore.setState({ tags: both }) + let finish: (value: Tag) => void = () => {} + vi.spyOn(tagsApi, 'merge').mockReturnValueOnce( + new Promise((resolve) => (finish = resolve)) + ) + + const pending = useTagStore.getState().merge('t1', 't2') + // Not optimistic: nothing has changed while the server works. + expect(useTagStore.getState().tags).toEqual(both) + finish(tag({ id: 't2', name: 'Interviews', asset_count: 5 })) + await pending + expect(useTagStore.getState().tags).toEqual([ + tag({ id: 't2', name: 'Interviews', asset_count: 5 }), + ]) + + useTagStore.setState({ tags: both }) + vi.spyOn(tagsApi, 'merge').mockRejectedValueOnce(new Error('gone')) + await expect(useTagStore.getState().merge('t1', 't2')).rejects.toThrow() + expect(useTagStore.getState().tags).toEqual(both) + expect(useTagStore.getState().error).toBeTruthy() + }) + it('moves a tag into a category', async () => { useTagStore.setState({ tags: [tag()] }) vi.spyOn(tagsApi, 'recategorise').mockResolvedValue(tag({ category_id: 'c1' })) diff --git a/frontend/src/stores/tags.ts b/frontend/src/stores/tags.ts index 5bc9f4a..735d2e9 100644 --- a/frontend/src/stores/tags.ts +++ b/frontend/src/stores/tags.ts @@ -36,6 +36,8 @@ interface TagState { /** Move a tag into a category, or out of every category with null. */ recategorise: (id: string, categoryId: string | null) => Promise remove: (id: string) => Promise + /** Fold one tag into another: the source goes, the target gains its assets. */ + merge: (id: string, targetId: string) => Promise createCategory: (name: string, parentId?: string | null) => Promise updateCategory: ( id: string, @@ -161,6 +163,27 @@ export const useTagStore = create((set, get) => ({ } }, + async merge(id, targetId) { + // Not optimistic, unlike rename and delete: the target's new count is the server's to + // say (assets carrying both are counted once), and a merge cannot be put back, so the + // list changes only once it has happened. + const token = requestToken + try { + const saved = await tagsApi.merge(id, targetId) + if (token !== requestToken) return + set((state) => ({ + tags: state.tags + .filter((t) => t.id !== id) + .map((t) => (t.id === saved.id ? { ...t, ...saved } : t)), + error: null, + })) + } catch (error) { + if (token !== requestToken) return + set({ error: apiErrorMessage(error, 'Could not merge those tags') }) + throw error + } + }, + async createCategory(name, parentId) { const token = requestToken try {