From eff727408880077248c55b7cdbe883542c7a69a4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:03:11 -0500 Subject: [PATCH 01/27] feat(titles): suggest titles for untitled entries from what they hold Lists live items with an empty title and builds up to five offline suggestions with reasons, plus an on-request identifier lookup. --- backend/app/services/titles.py | 195 +++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 backend/app/services/titles.py diff --git a/backend/app/services/titles.py b/backend/app/services/titles.py new file mode 100644 index 0000000..e177bfa --- /dev/null +++ b/backend/app/services/titles.py @@ -0,0 +1,195 @@ +import re +import sqlite3 +from pathlib import PurePath + +from app import lookup +from app.services.library import session +from app.store import attachments, items, notes +from app.store.errors import Invalid + +MAX = 5 +TITLE_LEN = 90 +LOOKUP_FIELDS = (("DOI", "doi"), ("ISBN", "isbn"), ("arXiv", "arxiv"), ("PMID", "pmid")) +_NOISE = re.compile( + r"\b(final|draft|copy|v\d+|rev\d*|version\d*|new|old|edited|scan(ned)?|print|preprint|ocr|[0-9a-f]{8,}|\d{8,})\b", + re.I, +) +_SMALL = {"a", "an", "and", "as", "at", "by", "for", "in", "of", "on", "or", "the", "to", "with"} +_TAGS = re.compile(r"<[^>]+>") + + +def _blank(value) -> bool: + return not str(value or "").strip() + + +def _key(text: str) -> str: + return re.sub(r"[\W_]+", "", text.casefold()) + + +def _text(value) -> str: + if isinstance(value, list): + value = value[0] if value else "" + return re.sub(r"\s+", " ", _TAGS.sub(" ", str(value or ""))).strip() + + +def _cut(text: str, limit: int = TITLE_LEN) -> str: + text = text.strip().rstrip(".;:,") + if len(text) <= limit: + return text + cut = text[:limit].rsplit(" ", 1)[0].rstrip(".;:,") + return cut or text[:limit] + + +def _sentence(text: str) -> str: + text = _text(text) + if not text: + return "" + first = re.split(r"(?<=[.!?])\s+(?=[A-Z])", text, maxsplit=1)[0] + return _cut(first) + + +def _capital(word: str, first: bool) -> str: + if word.isupper() and len(word) > 1: + return word + if not first and word.lower() in _SMALL: + return word.lower() + return word[:1].upper() + word[1:] + + +def clean_file_name(name: str) -> str: + stem = PurePath(name or "").stem + stem = re.sub(r"[_\-.+]+", " ", stem) + stem = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", stem) + stem = _NOISE.sub(" ", stem) + words = [w for w in stem.split() if w] + if not words or not any(re.search(r"[A-Za-z]{3,}", w) for w in words): + return "" + lowered = [w if w.isupper() and len(w) > 1 else w.lower() for w in words] + return _cut(" ".join(_capital(w, n == 0) for n, w in enumerate(lowered))) + + +def _family(item: dict) -> str: + for c in item.get("creators") or []: + if c.get("role") == "author": + return c.get("family") or c.get("literal") or "" + first = (item.get("creators") or [{}])[0] if item.get("creators") else {} + return first.get("family") or first.get("literal") or "" + + +def _type_word(item_type: str) -> str: + return { + "article-journal": "article", "paper-conference": "conference paper", "chapter": "chapter", + "book": "book", "thesis": "thesis", "report": "report", "webpage": "web page", + "manuscript": "manuscript", "document": "document", "article": "article", + }.get(item_type or "", (item_type or "document").replace("-", " ")) + + +def identifiers(csl: dict) -> list[dict]: + out = [] + for field, kind in LOOKUP_FIELDS: + value = _text(csl.get(field)) + if value: + out.append({"kind": kind, "field": field, "value": value}) + return out + + +def _brief(conn: sqlite3.Connection, item: dict) -> dict: + files = [a.get("name") or PurePath(a.get("rel_path") or "").name for a in attachments.for_item(conn, item["id"])] + csl = item.get("csl") or {} + return { + "id": item["id"], + "type": item.get("type"), + "creators": [ + " ".join(x for x in (c.get("given"), c.get("family")) if x) or c.get("literal") or "" + for c in item.get("creators") or [] + ], + "year": item.get("year"), + "container": item.get("container_title") or "", + "identifiers": identifiers(csl), + "files": [f for f in files if f], + "added": item.get("created_at"), + "batch_id": item.get("batch_id"), + } + + +def _untitled_where() -> str: + return "trashed_at IS NULL AND TRIM(COALESCE(title, ''), ' ' || char(9) || char(10) || char(13)) = ''" + + +def untitled(conn: sqlite3.Connection, limit: int = 50, offset: int = 0) -> dict: + total = conn.execute(f"SELECT COUNT(*) FROM items WHERE {_untitled_where()}").fetchone()[0] + ids = [r[0] for r in conn.execute( + f"SELECT id FROM items WHERE {_untitled_where()} ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?", + (max(1, min(limit, 500)), max(0, offset)), + )] + return {"total": total, "limit": limit, "offset": offset, + "items": [_brief(conn, item) for item in items.get_many(conn, ids)]} + + +def suggest(conn: sqlite3.Connection, item_id: str) -> dict: + item = items.get(conn, item_id) + csl = item.get("csl") or {} + year = item.get("year") + family = _family(item) + container = _text(item.get("container_title")) + found: list[dict] = [] + + def put(text: str, reason: str) -> None: + text = _cut(_text(text)) + if not text or not _key(text) or len(found) >= MAX: + return + if any(_key(text) == _key(s["title"]) for s in found): + return + found.append({"title": text, "reason": reason}) + + put(csl.get("title-short") or csl.get("shortTitle"), "the short title held on the entry") + put(_sentence(item.get("abstract") or csl.get("abstract")), "the first sentence of the abstract") + for a in attachments.for_item(conn, item_id): + put(clean_file_name(a.get("name") or a.get("rel_path") or ""), f"cleaned from the attached file {a.get('name')}") + for field, label in (("event-title", "event"), ("event", "event"), ("collection-title", "series"), + ("booktitle", "book title"), ("container-title-short", "short container title")): + value = _text(csl.get(field)) + if value and _key(value) != _key(container): + put(value, f"the {label} field") + if container: + put(f"{container}, {year}" if year else container, "the journal or book it appeared in" + (" with the year" if year else "")) + for n in notes.for_item(conn, item_id): + put(_sentence(n.get("body") or ""), "the first sentence of a note") + if family: + bits = [family, str(year) if year else "", _type_word(item.get("type"))] + put(" ".join(b for b in bits[:2] if b) + f", {bits[2]}", "the first creator's family name" + (" with the year and type" if year else " with the type")) + key = _text(csl.get("citation-key")) + if key and re.search(r"[A-Za-z]{3,}", key): + spaced = re.sub(r"(?<=[a-z])(?=[A-Z0-9])|(?<=\d)(?=[A-Za-z])|[_:\-]+", " ", key) + put(" ".join(_capital(w, n == 0) for n, w in enumerate(spaced.split())), f"the citation key {key} from the import") + return {"id": item_id, "suggestions": found[:MAX], "identifiers": identifiers(csl)} + + +def lookup_title(item: dict) -> dict: + item_id = item["id"] + ids = identifiers(item.get("csl") or {}) + if not ids: + raise Invalid("This entry has no DOI, ISBN, arXiv id or PMID to look up") + first = ids[0] + found = lookup.resolve(first["value"], first["kind"]) + title = _cut(_text(found["record"].get("title")), 300) + if not title: + raise Invalid(f"{', '.join(found['source']['services']) or first['kind']} has no title for {first['value']}") + service = ", ".join(found["source"]["services"]) or first["kind"] + return {"id": item_id, "title": title, "service": service, "reason": f"looked up {first['field']} {first['value']} at {service}"} + + +def untitled_list(limit: int = 50, offset: int = 0) -> dict: + with session() as (_, conn): + return untitled(conn, limit, offset) + + +def suggestions(item_id: str) -> dict: + with session() as (_, conn): + return suggest(conn, item_id) + + +def look_up(item_id: str) -> dict: + with session() as (_, conn): + item = items.get(conn, item_id) + return lookup_title(item) From 84a10735e583468f37320a50a5fb4ab6549cba58 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:03:12 -0500 Subject: [PATCH 02/27] feat(titles): serve untitled list, suggestions and lookup routes Adds the untitled, title-suggestions and title-lookup routes and registers them. --- backend/app/routers/registry.py | 1 + backend/app/routers/titles.py | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 backend/app/routers/titles.py diff --git a/backend/app/routers/registry.py b/backend/app/routers/registry.py index 2b7ef3f..9b6d50a 100644 --- a/backend/app/routers/registry.py +++ b/backend/app/routers/registry.py @@ -39,3 +39,4 @@ def mount(app: FastAPI) -> None: register("cite_write", __import__("app.routers.cite_write", fromlist=["router"]).router) register("window", __import__("app.routers.window", fromlist=["router"]).router) register("upload", __import__("app.routers.upload", fromlist=["router"]).router) +register("titles", __import__("app.routers.titles", fromlist=["router"]).router) diff --git a/backend/app/routers/titles.py b/backend/app/routers/titles.py new file mode 100644 index 0000000..c576bb6 --- /dev/null +++ b/backend/app/routers/titles.py @@ -0,0 +1,22 @@ +from fastapi import APIRouter, Query + +from app.routers.library import _run +from app.services import titles as svc + +GROUP = "titles" +router = APIRouter(prefix="/library", tags=[GROUP]) + + +@router.get("/untitled") +def untitled_list(limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0)) -> dict: + return _run(svc.untitled_list, limit, offset) + + +@router.get("/items/{item_id}/title-suggestions") +def title_suggestions(item_id: str) -> dict: + return _run(svc.suggestions, item_id) + + +@router.post("/items/{item_id}/title-lookup") +def title_lookup(item_id: str) -> dict: + return _run(svc.look_up, item_id) From 3dfab8338250ee58da3ff4bb9e2043457e739eaf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:03:19 -0500 Subject: [PATCH 03/27] feat(import): turn keywords into tags when asked Import takes keywords_as_tags, splits each entry's keywords with one shared splitter and tags the new item inside its own record transaction, reusing tags that differ only in case. Adds a from-keywords pass over existing items with a dry run. --- backend/app/services/transfer.py | 89 ++++++++++++++++++++++++++++---- 1 file changed, 80 insertions(+), 9 deletions(-) diff --git a/backend/app/services/transfer.py b/backend/app/services/transfer.py index 215d5f8..ffc1536 100644 --- a/backend/app/services/transfer.py +++ b/backend/app/services/transfer.py @@ -1,11 +1,12 @@ import importlib +import re import sqlite3 from pathlib import Path from typing import Callable from app import formats from app.services.library import session -from app.store import batches, db, items +from app.store import batches, db, items, tags from app.store.errors import Invalid ON_DUPLICATE = ("skip", "add") @@ -37,8 +38,52 @@ def _title(csl: dict) -> str: return str(csl.get("title") or "").strip() +KEYWORD_SPLIT = re.compile(r"[,;\n]") + + +def split_keywords(value) -> list[str]: + parts = value if isinstance(value, list) else [value] + seen: dict[str, str] = {} + for part in parts: + for word in KEYWORD_SPLIT.split(str(part or "")): + word = " ".join(word.split()) + if word and word.casefold() not in seen: + seen[word.casefold()] = word + return list(seen.values()) + + +def _tally() -> dict: + return {"items_tagged": 0, "made": {}, "reused": {}} + + +def _tag_from_keywords(conn: sqlite3.Connection, item_id: str, csl: dict, tally: dict, *, apply: bool = True) -> None: + names: list[str] = [] + for word in split_keywords(csl.get("keyword")): + key = word.casefold() + known = tally["made"].get(key) or tally["reused"].get(key) + if known is None: + found = conn.execute("SELECT name FROM tags WHERE name = ?", (word,)).fetchone() + known = {"name": found[0] if found else word, "items": 0} + tally["reused" if found else "made"][key] = known + known["items"] += 1 + names.append(known["name"]) + if not names: + return + if apply: + tags.add(conn, item_id, names) + tally["items_tagged"] += 1 + + +def _counts(tally: dict) -> dict: + return { + "tags_created": len(tally["made"]), + "tags_reused": len(tally["reused"]), + "items_tagged": tally["items_tagged"], + } + + def import_text(conn: sqlite3.Connection, text: str, format: str, *, on_duplicate: str = "skip", - label: str | None = None) -> dict: + label: str | None = None, keywords_as_tags: bool = False) -> dict: if on_duplicate not in ON_DUPLICATE: raise Invalid(f"on_duplicate must be one of {', '.join(ON_DUPLICATE)}") module = formats.get(format) @@ -50,6 +95,7 @@ def import_text(conn: sqlite3.Connection, text: str, format: str, *, on_duplicat added: list[str] = [] skipped: list[dict] = [] failed: list[dict] = [] + tally = _tally() with db.tx(conn): batch = batches.create(conn, module.NAME, label) for index, csl in enumerate(records): @@ -60,7 +106,10 @@ def import_text(conn: sqlite3.Connection, text: str, format: str, *, on_duplicat if matches: skipped.append({"index": index, "title": _title(record), "duplicate_of": matches[0]}) continue - added.append(items.create(conn, record, batch_id=batch["id"])["id"]) + item_id = items.create(conn, record, batch_id=batch["id"])["id"] + if keywords_as_tags: + _tag_from_keywords(conn, item_id, record, tally) + added.append(item_id) except Invalid as exc: failed.append({"index": index, "title": _title(csl) if isinstance(csl, dict) else "", "error": str(exc)}) return { @@ -70,9 +119,24 @@ def import_text(conn: sqlite3.Connection, text: str, format: str, *, on_duplicat "skipped": skipped, "failed": failed, "duplicates_checked": find_for is not None, + "keywords_as_tags": keywords_as_tags, + **_counts(tally), } +def tags_from_keywords(conn: sqlite3.Connection, *, collection_id: str | None = None, dry_run: bool = False) -> dict: + tally = _tally() + ids = _all_ids(conn, collection_id=collection_id) if collection_id else _all_ids(conn) + with db.tx(conn): + for item in items.get_many(conn, ids): + with db.tx(conn): + _tag_from_keywords(conn, item["id"], item["csl"], tally, apply=not dry_run) + found = [{"name": t["name"], "items": t["items"], "new": key in tally["made"]} + for key, t in {**tally["reused"], **tally["made"]}.items()] + found.sort(key=lambda t: t["name"].casefold()) + return {"dry_run": dry_run, "collection_id": collection_id, "items_checked": len(ids), **_counts(tally), "tags": found} + + def _read(path: Path) -> str: try: return path.read_text(encoding="utf-8-sig") @@ -85,11 +149,12 @@ def _read(path: Path) -> str: def import_file(conn: sqlite3.Connection, path: str | Path, format: str | None = None, *, - on_duplicate: str = "skip", label: str | None = None) -> dict: + on_duplicate: str = "skip", label: str | None = None, keywords_as_tags: bool = False) -> dict: path = Path(path).expanduser() text = _read(path) chosen = format or formats.detect(path, text) - return import_text(conn, text, chosen, on_duplicate=on_duplicate, label=label or path.name) + return import_text(conn, text, chosen, on_duplicate=on_duplicate, label=label or path.name, + keywords_as_tags=keywords_as_tags) def _all_ids(conn: sqlite3.Connection, **query) -> list[str]: @@ -125,14 +190,20 @@ def batch_trash(conn: sqlite3.Connection, batch_id: str) -> dict: return {"id": batch_id, "deleted": True, "trashed": ids} -def run_import_text(text: str, format: str, on_duplicate: str = "skip") -> dict: +def run_import_text(text: str, format: str, on_duplicate: str = "skip", keywords_as_tags: bool = False) -> dict: + with session() as (_, conn): + return import_text(conn, text, format, on_duplicate=on_duplicate, keywords_as_tags=keywords_as_tags) + + +def run_import_file(path: str, format: str | None = None, on_duplicate: str = "skip", + keywords_as_tags: bool = False) -> dict: with session() as (_, conn): - return import_text(conn, text, format, on_duplicate=on_duplicate) + return import_file(conn, path, format, on_duplicate=on_duplicate, keywords_as_tags=keywords_as_tags) -def run_import_file(path: str, format: str | None = None, on_duplicate: str = "skip") -> dict: +def run_tags_from_keywords(collection_id: str | None = None, dry_run: bool = False) -> dict: with session() as (_, conn): - return import_file(conn, path, format, on_duplicate=on_duplicate) + return tags_from_keywords(conn, collection_id=collection_id, dry_run=dry_run) def run_export(ids: list[str] | None = None, format: str = "bibtex", collection_id: str | None = None, From c9d4346ace93e249dfacef61e0c666839f8472e3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:03:30 -0500 Subject: [PATCH 04/27] feat(import): take the keywords option on the import route The import route accepts keywords_as_tags, and a new route converts keywords of existing items into tags with an optional dry run. --- backend/app/routers/transfer.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/backend/app/routers/transfer.py b/backend/app/routers/transfer.py index fd0b755..3a13f33 100644 --- a/backend/app/routers/transfer.py +++ b/backend/app/routers/transfer.py @@ -32,6 +32,12 @@ class ImportBody(BaseModel): path: str | None = None format: str | None = None on_duplicate: str = "skip" + keywords_as_tags: bool = False + + +class FromKeywordsBody(BaseModel): + collection: str | None = None + dry_run: bool = False @router.post("/import", status_code=201) @@ -39,13 +45,18 @@ def import_records(body: ImportBody) -> dict: if (body.text is None) == (body.path is None): raise HTTPException(422, "give either text or path") if body.path is not None: - return _run(svc.run_import_file, body.path, body.format, body.on_duplicate) + return _run(svc.run_import_file, body.path, body.format, body.on_duplicate, body.keywords_as_tags) if not body.format: found = svc.formats.sniff(body.text) if found is None: raise HTTPException(422, "cannot tell the format of the text; pass format") body.format = found - return _run(svc.run_import_text, body.text, body.format, body.on_duplicate) + return _run(svc.run_import_text, body.text, body.format, body.on_duplicate, body.keywords_as_tags) + + +@router.post("/tags/from-keywords") +def tags_from_keywords(body: FromKeywordsBody) -> dict: + return _run(svc.run_tags_from_keywords, body.collection, body.dry_run) @router.get("/export") From ded61a1441eaaf41487359cb4b422981aad1550a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:03:45 -0500 Subject: [PATCH 05/27] feat(cli): add keywords as tags to import and a from-keywords verb The import verb gains --keywords-as-tags and reports the tag counts, and tags from-keywords converts existing items with --collection and --dry-run. --- backend/app/cli_transfer.py | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/backend/app/cli_transfer.py b/backend/app/cli_transfer.py index 646d36d..d73300e 100644 --- a/backend/app/cli_transfer.py +++ b/backend/app/cli_transfer.py @@ -13,11 +13,24 @@ def _from_caller(path: str) -> str: return str(Path(os.environ.get(CALLER_ENV) or os.getcwd()) / Path(path).expanduser()) +def _tag_counts(result: dict) -> str: + return (f"{result['tags_created']} tags created, {result['tags_reused']} reused, " + f"{result['items_tagged']} items tagged") + + def _imported(result: dict, args) -> str: - return ( + said = ( f"Imported {len(result['added'])} items from {Path(args.file).name} as {result['format']} " f"(batch {result['batch_id']}); skipped {len(result['skipped'])} duplicates, {len(result['failed'])} failed." ) + return f"{said} Keywords as tags: {_tag_counts(result)}." if result.get("keywords_as_tags") else said + + +def _from_keywords_said(result: dict, args) -> str: + if result["dry_run"]: + return (f"Dry run over {result['items_checked']} items: would make {result['tags_created']} new tags, " + f"reuse {result['tags_reused']}, tag {result['items_tagged']} items. Nothing changed.") + return f"Checked {result['items_checked']} items: {_tag_counts(result)}." def _export(args) -> dict: @@ -43,10 +56,18 @@ def register(sub) -> None: imp.add_argument("file") imp.add_argument("--format", metavar="NAME", help="format name (default: detect from the file)") imp.add_argument("--duplicates", choices=ON_DUPLICATE, default="skip", help="skip (default) or add items already in the library") + imp.add_argument("--keywords-as-tags", action="store_true", + help="also add each entry's keywords as tags on the new item (off by default)") imp.set_defaults( - run=lambda a: svc.run_import_file(_from_caller(a.file), a.format, a.duplicates), + run=lambda a: svc.run_import_file(_from_caller(a.file), a.format, a.duplicates, a.keywords_as_tags), say=_imported, ) + group = sub.add_parser("tags", help="convert keywords of items already in the library into tags") + verbs = group.add_subparsers(dest="verb", required=True, metavar="VERB") + fk = verbs.add_parser("from-keywords", help="add each item's keywords as tags") + fk.add_argument("--collection", metavar="ID", help="only items in this collection") + fk.add_argument("--dry-run", action="store_true", help="list the tags it would make with counts; change nothing") + fk.set_defaults(run=lambda a: svc.run_tags_from_keywords(a.collection, a.dry_run), say=_from_keywords_said) exp = sub.add_parser("export", help="export items as BibTeX, RIS or CSL-JSON (default: the whole library as BibTeX)") exp.add_argument("--format", metavar="NAME", default="bibtex") exp.add_argument("--ids", nargs="+", metavar="ID") From 45b3e863b2e784a6eaabf1ff05bb0548fb5c2b71 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:03:58 -0500 Subject: [PATCH 06/27] feat(mcp): pass keywords as tags through the import tool The import_references tool takes an optional keywords_as_tags flag and says the tag counts when it is on. --- backend/app/mcp/tools.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/backend/app/mcp/tools.py b/backend/app/mcp/tools.py index b0316f6..4cbc35e 100644 --- a/backend/app/mcp/tools.py +++ b/backend/app/mcp/tools.py @@ -183,9 +183,13 @@ def _add_by_identifier(args: dict) -> tuple[str, dict]: def _import_references(args: dict) -> tuple[str, dict]: - out = transfer.run_import_text(args["text"], args["format"], args.get("on_duplicate") or "skip") + out = transfer.run_import_text(args["text"], args["format"], args.get("on_duplicate") or "skip", + bool(args.get("keywords_as_tags"))) counts = {k: len(v) if isinstance(v, list) else v for k, v in out.items() if k in ("added", "skipped", "failed")} - return f"Imported from {out['format']}: added {counts['added']}, skipped {counts['skipped']}, failed {counts['failed']}.", out + said = f"Imported from {out['format']}: added {counts['added']}, skipped {counts['skipped']}, failed {counts['failed']}." + if out["keywords_as_tags"]: + said += f" Tags: {out['tags_created']} created, {out['tags_reused']} reused, {out['items_tagged']} items tagged." + return said, out def _tag_item(args: dict) -> tuple[str, dict]: @@ -234,6 +238,7 @@ def _tag_item(args: dict) -> tuple[str, dict]: "text": {"type": "string", "description": "The references, as text."}, "format": {"type": "string", "enum": ["bibtex", "ris", "csljson", "formtxt"], "description": "The format of the text."}, "on_duplicate": ON_DUPLICATE, + "keywords_as_tags": {"type": "boolean", "description": "Also add each entry's keywords as tags on the new item. Off unless the person asks."}, }, ("text", "format")), "read_only": False, "run": _import_references, From 7ee5ef4b8dd9f0ceefac64deecb9fa4a2f8e2be2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:04:20 -0500 Subject: [PATCH 07/27] fix(titles): drop citation keys that only repeat name and year Skips placeholder and name-year citation keys and adds a publisher or institution suggestion for entries with no creator. --- backend/app/services/titles.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/backend/app/services/titles.py b/backend/app/services/titles.py index e177bfa..373c640 100644 --- a/backend/app/services/titles.py +++ b/backend/app/services/titles.py @@ -158,8 +158,13 @@ def put(text: str, reason: str) -> None: if family: bits = [family, str(year) if year else "", _type_word(item.get("type"))] put(" ".join(b for b in bits[:2] if b) + f", {bits[2]}", "the first creator's family name" + (" with the year and type" if year else " with the type")) + publisher = _text(csl.get("publisher") or csl.get("authority")) + if publisher and not family: + put(f"{publisher} {_type_word(item.get('type'))}" + (f", {year}" if year else ""), "the publisher or institution with the type") key = _text(csl.get("citation-key")) - if key and re.search(r"[A-Za-z]{3,}", key): + plain = _key(f"{family}{year or ''}") + placeholder = re.fullmatch(r"(empty|untitled|entry|item|ref|misc|doc|doi|filed?|zz+)\d*", key, re.I) + if key and re.search(r"[A-Za-z]{3,}", key) and _key(key) != plain and not placeholder: spaced = re.sub(r"(?<=[a-z])(?=[A-Z0-9])|(?<=\d)(?=[A-Za-z])|[_:\-]+", " ", key) put(" ".join(_capital(w, n == 0) for n, w in enumerate(spaced.split())), f"the citation key {key} from the import") return {"id": item_id, "suggestions": found[:MAX], "identifiers": identifiers(csl)} From ed353e36e04d74fba638720bd900e2724d3b0597 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:04:20 -0500 Subject: [PATCH 08/27] feat(cli): add titles list, suggest and set verbs The command line lists untitled entries, prints the same suggestions with reasons and sets a title, refusing an empty one. --- backend/app/cli.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/backend/app/cli.py b/backend/app/cli.py index 97b69cb..126c690 100644 --- a/backend/app/cli.py +++ b/backend/app/cli.py @@ -132,13 +132,37 @@ def _search(sub) -> None: p.set_defaults(run=lambda a: svc.search_text(" ".join(a.text), a.limit), say=lambda r, a: f"Found {_items_of(r)}.") +def _titles(sub) -> None: + titles = __import__("app.services.titles", fromlist=["suggest"]) + group = sub.add_parser("titles", help="find entries without a title and give them one") + verbs = group.add_subparsers(dest="verb", required=True, metavar="VERB") + lst = verbs.add_parser("list", help="list live entries whose title is empty") + lst.add_argument("--limit", type=int, default=50, metavar="N") + lst.add_argument("--offset", type=int, default=0, metavar="N") + lst.set_defaults(run=lambda a: titles.untitled_list(a.limit, a.offset), + say=lambda r, a: f"{r['total']} entries need a title; showing {len(r['items'])}.") + sug = verbs.add_parser("suggest", help="suggest up to five titles from what the entry already holds") + sug.add_argument("item_id", metavar="ID") + sug.set_defaults(run=lambda a: titles.suggestions(a.item_id), say=lambda r, a: "\n".join( + [f"{len(r['suggestions'])} suggestions for {r['id']}"] + [f" {n}. {s['title']} ({s['reason']})" for n, s in enumerate(r["suggestions"], 1)])) + put = verbs.add_parser("set", help="give an entry its title") + put.add_argument("item_id", metavar="ID") + put.add_argument("title", metavar="TITLE") + def _set(a): + if not a.title.strip(): + raise Invalid("A title is required") + return svc.item_edit(a.item_id, {"title": a.title.strip()}) + + put.set_defaults(run=_set, say=lambda r, a: f"Item {r['id']} is now titled {r['title']!r}.") + + def parser() -> argparse.ArgumentParser: top = argparse.ArgumentParser( prog=PROG, description="Work on the current FormCite library without the engine. Prints JSON on stdout and a sentence on stderr.", ) sub = top.add_subparsers(dest="group", required=True, metavar="GROUP") - for build in (_library, _item, _collection, _tag, _note, _search, cli_duplicates.register): + for build in (_library, _item, _collection, _tag, _note, _search, _titles, cli_duplicates.register): build(sub) __import__("app.cli_format", fromlist=["register"]).register(sub) __import__("app.cli_transfer", fromlist=["register"]).register(sub) From 83fe635c0e6bbd310a9aa8ece7fb8bdb919881b2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:04:44 -0500 Subject: [PATCH 09/27] feat(add): send the keywords choice with an import The engine side of the Add dialog keeps the keywords-as-tags choice for the session, sends it with each import and raises the tags notice when items were tagged. --- frontend/src/engine/add.ts | 5 ++++- frontend/src/io/add.ts | 8 ++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/frontend/src/engine/add.ts b/frontend/src/engine/add.ts index c21d3e4..22a785c 100644 --- a/frontend/src/engine/add.ts +++ b/frontend/src/engine/add.ts @@ -23,6 +23,7 @@ export function scopeForExport(scope: Scope): io.ExportScope | null { export class Adding { formats: io.FormatInfo[] = []; + keywordsAsTags = false; constructor(private readonly library: Library) {} @@ -62,9 +63,11 @@ export class Adding { async importText(text: string, format: string | null): Promise { try { - const r = await io.importText(text, format); + const r = await io.importText(text, format, this.keywordsAsTags); this.library.itemsAdded(r.added); + if (r.items_tagged) this.library.tagsChanged(); const parts = [`Imported ${r.added.length} as ${r.format}`]; + if (r.keywords_as_tags) parts.push(`${(r.tags_created ?? 0) + (r.tags_reused ?? 0)} tags added`); if (r.skipped.length) parts.push(`${r.skipped.length} already in the library`); if (r.failed.length) parts.push(`${r.failed.length} failed: ${r.failed[0].error}`); return { ok: true, ids: r.added, text: parts.join(', ') + '.' }; diff --git a/frontend/src/io/add.ts b/frontend/src/io/add.ts index 3a51bd9..f699573 100644 --- a/frontend/src/io/add.ts +++ b/frontend/src/io/add.ts @@ -21,6 +21,10 @@ export interface ImportResult { added: string[]; skipped: { index: number; title: string; duplicate_of: string }[]; failed: { index: number; title: string; error: string }[]; + keywords_as_tags?: boolean; + tags_created?: number; + tags_reused?: number; + items_tagged?: number; } export interface FormatInfo { name: string; available: boolean; extensions: string[] } export interface IdentifyResult { @@ -35,8 +39,8 @@ export interface ExportScope { collection?: string; tag?: string; ids?: string[] export const lookupPreview = (text: string) => api.post('/library/lookup', { text }); export const addFromIdentifier = (text: string) => api.post('/library/items/from-identifier', { text }); -export const importText = (text: string, format: string | null) => - api.post('/library/import', { text, format: format || null }); +export const importText = (text: string, format: string | null, keywordsAsTags = false) => + api.post('/library/import', { text, format: format || null, keywords_as_tags: keywordsAsTags }); export const listFormats = () => api.get('/library/formats'); export const identifyPath = (path: string) => api.post('/library/identify', { path }); From 9c573b0f7d6480f9a9918f19c521352195a665e9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:04:44 -0500 Subject: [PATCH 10/27] feat(add): add a turn keywords into tags box to the import tab The Import tab gains an unticked box that a dropped or pasted import obeys, and a dropped import now writes its result on the tab's line. --- frontend/src/styles/add.css | 2 ++ frontend/src/ui/add.ts | 9 ++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/frontend/src/styles/add.css b/frontend/src/styles/add.css index 19cfe8c..62187a1 100644 --- a/frontend/src/styles/add.css +++ b/frontend/src/styles/add.css @@ -33,6 +33,8 @@ .fc-add-file { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-secondary); } .fc-add-area { height: var(--fc-add-area-h); resize: none; padding: var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text-primary); font: inherit; font-family: var(--font-mono, monospace); } .fc-add-end { justify-content: flex-end; } +.fc-add-check { display: inline-flex; align-items: center; gap: var(--space-1h); margin-right: auto; color: var(--text-secondary); cursor: pointer; user-select: none; } +.fc-add-check input { margin: 0; accent-color: var(--accent-color); } .fc-add-drop { position: fixed; inset: var(--space-3); z-index: var(--z-scrim); display: grid; place-items: center; border: 2px dashed var(--accent-color); border-radius: var(--radius-md); background: color-mix(in srgb, var(--bg-primary) 70%, transparent); pointer-events: none; opacity: 0; visibility: hidden; transition: opacity 160ms, visibility 0s linear 160ms; } .fc-add-drop.is-on { opacity: 1; visibility: visible; transition: opacity 160ms; } .fc-add-drop-text { margin: 0; padding: var(--space-4); color: var(--text-primary); } diff --git a/frontend/src/ui/add.ts b/frontend/src/ui/add.ts index 8df571f..49579da 100644 --- a/frontend/src/ui/add.ts +++ b/frontend/src/ui/add.ts @@ -77,6 +77,7 @@ async function dropOne(adding: Adding, f: File, line: HTMLElement): Promise -
+
+ + +

`); body.append(s); + const keywords = q(s, '[data-opt="keywords"]'); + keywords.checked = adding.keywordsAsTags; + keywords.addEventListener('change', () => { adding.keywordsAsTags = keywords.checked; }); const sel = q(s, 'select'); const area = q(s, 'textarea'); const file = q(s, 'input[type="file"]'); From 0beef4d10893f753ef91def7f8c90298917dc733 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:06:26 -0500 Subject: [PATCH 11/27] feat(titles): add window calls and title queue for untitled entries Adds the untitled, suggestion, lookup and set-title calls and a small count holder that reports how much the count rose. --- frontend/src/engine/titles.ts | 30 ++++++++++++++++++++++++++++++ frontend/src/io/titles.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 frontend/src/engine/titles.ts create mode 100644 frontend/src/io/titles.ts diff --git a/frontend/src/engine/titles.ts b/frontend/src/engine/titles.ts new file mode 100644 index 0000000..a2f66ab --- /dev/null +++ b/frontend/src/engine/titles.ts @@ -0,0 +1,30 @@ +import { Emitter } from './events'; + +export const MAX_SUGGESTIONS = 5; + +export interface TitleEvents { 'count': number } + +export class TitleQueue { + readonly events = new Emitter(); + private _count = -1; + + get count(): number { return Math.max(0, this._count); } + get known(): boolean { return this._count >= 0; } + + setCount(next: number): number { + const before = this._count; + if (next === before) return 0; + this._count = next; + this.events.emit('count', next); + return before < 0 ? 0 : next - before; + } +} + +export function checkTitle(text: string): string | null { + return text.trim() ? null : 'Type a title or pick a suggestion first.'; +} + +export function knownLine(creators: string[], year: number | null, container: string, files: string[]): string { + const who = creators.length ? (creators.length > 2 ? `${creators[0]} and ${creators.length - 1} others` : creators.join(' and ')) : 'No creator'; + return [who, year ? String(year) : 'no year', container, files[0] ?? ''].filter(Boolean).join(' · '); +} diff --git a/frontend/src/io/titles.ts b/frontend/src/io/titles.ts new file mode 100644 index 0000000..a153b6e --- /dev/null +++ b/frontend/src/io/titles.ts @@ -0,0 +1,28 @@ +import { api } from './api'; +import { detailApi } from './detail'; + +export interface Identifier { kind: string; field: string; value: string } +export interface UntitledItem { + id: string; + type: string; + creators: string[]; + year: number | null; + container: string; + identifiers: Identifier[]; + files: string[]; + added: string; + batch_id: string | null; +} +export interface UntitledPage { total: number; limit: number; offset: number; items: UntitledItem[] } +export interface Suggestion { title: string; reason: string } +export interface Suggestions { id: string; suggestions: Suggestion[]; identifiers: Identifier[] } +export interface LookedUp { id: string; title: string; service: string; reason: string } + +const enc = encodeURIComponent; + +export const titlesApi = { + untitled: (limit = 200, offset = 0) => api.get(`/library/untitled?limit=${limit}&offset=${offset}`), + suggest: (id: string) => api.get(`/library/items/${enc(id)}/title-suggestions`), + lookUp: (id: string) => api.post(`/library/items/${enc(id)}/title-lookup`), + setTitle: (id: string, title: string) => detailApi.editFields(id, { title }), +}; From 961acafdeeb433988c61066ae818c046a4ce8b81 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:06:26 -0500 Subject: [PATCH 12/27] feat(titles): add the needs a title view with suggestion strip Fixed-height rows with a title field, up to five suggestion buttons in a reserved strip, an on-request lookup, a nav count hidden at zero and one toast after an import. --- frontend/src/styles/titles.css | 13 +++ frontend/src/ui/titles.ts | 206 +++++++++++++++++++++++++++++++++ 2 files changed, 219 insertions(+) create mode 100644 frontend/src/styles/titles.css create mode 100644 frontend/src/ui/titles.ts diff --git a/frontend/src/styles/titles.css b/frontend/src/styles/titles.css new file mode 100644 index 0000000..dad9f39 --- /dev/null +++ b/frontend/src/styles/titles.css @@ -0,0 +1,13 @@ +.fc-panes[data-view="titles"] > .fc-view[data-pane="titles"] { display: grid; } +.fc-tt { --tt-row: 112px; --tt-strip: 28px; --tt-sug-max: 260px; } +.fc-tt-row { display: grid; grid-template-rows: var(--rv-line) var(--rv-btn) var(--tt-strip); row-gap: var(--space-1h); align-content: center; height: var(--tt-row); padding: 0 var(--space-4); border-bottom: 1px solid var(--line-0); box-sizing: border-box; contain: layout; } +.fc-tt-known { color: var(--text-secondary); font-size: var(--fs-12); line-height: var(--rv-line); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.fc-tt-form { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: var(--space-2); margin: 0; } +.fc-tt-input { height: var(--rv-btn); box-sizing: border-box; padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text-primary); font: inherit; font-size: var(--fs-13); } +.fc-tt-input:focus { outline: none; border-color: var(--accent-color); } +.fc-tt-strip { display: flex; flex-wrap: nowrap; gap: var(--space-1h); height: var(--tt-strip); overflow: hidden; align-items: center; } +.fc-tt-sug { flex: 0 1 auto; min-width: 0; max-width: var(--tt-sug-max); height: var(--tt-strip); box-sizing: border-box; padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-12); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; } +.fc-tt-sug:hover:not(:disabled), .fc-tt-sug:focus-visible { background: var(--bg-hover); border-color: var(--accent-color); outline: none; } +.fc-tt-sug.is-lookup { border-style: dashed; color: var(--text-secondary); } +.fc-tt-none { color: var(--text-muted); font-size: var(--fs-12); } +.fc-toast-act { pointer-events: auto; height: var(--size-row-sm); padding: 0 var(--space-2); border: 1px solid var(--accent-color); border-radius: var(--radius-sm); background: transparent; color: var(--accent-color); font: inherit; font-size: var(--fs-12); cursor: pointer; } diff --git a/frontend/src/ui/titles.ts b/frontend/src/ui/titles.ts new file mode 100644 index 0000000..9760a01 --- /dev/null +++ b/frontend/src/ui/titles.ts @@ -0,0 +1,206 @@ +import type { Engine, ViewId } from '../engine'; +import { plural } from '../engine/review'; +import { checkTitle, knownLine, MAX_SUGGESTIONS, TitleQueue } from '../engine/titles'; +import { titlesApi, type Suggestion, type UntitledItem } from '../io/titles'; +import { icon } from './icons'; +import { el, patchList, q, setClass, setHidden, setText, setTitle } from './dom'; +import { toast } from './toast'; + +const VIEW = 'titles' as ViewId; +const SLOTS = Array.from({ length: MAX_SUGGESTIONS }, (_, n) => ``).join(''); + +const SHELL = ` +
+
+

+
+
`; + +function rowNode(item: UntitledItem): HTMLElement { + const n = el(`
+ +
+
${SLOTS}
+
`); + fillRow(n, item); + return n; +} + +function fillRow(n: HTMLElement, item: UntitledItem): void { + const line = knownLine(item.creators, item.year, item.container, item.files); + setText(q(n, '.fc-tt-known'), line); + setTitle(q(n, '.fc-tt-known'), line); + const id = item.identifiers[0]; + const look = q(n, '[data-act="lookup"]'); + setHidden(look, !id); + if (id) setTitle(look, `Ask the ${id.field} service for the title of ${id.value}`); +} + +function fillSuggestions(n: HTMLElement, list: Suggestion[]): void { + for (let i = 0; i < MAX_SUGGESTIONS; i++) { + const b = q(n, `[data-slot="${i}"]`); + const s = list[i]; + setHidden(b, !s); + setText(b, s ? s.title : ''); + setTitle(b, s ? `${s.title} · ${s.reason}` : ''); + b.dataset.title = s ? s.title : ''; + } + setHidden(q(n, '.fc-tt-none'), list.length > 0); +} + +export function mountTitles(engine: Engine, host: HTMLElement): void { + host.append(el(SHELL)); + const root = q(host, '.fc-tt'); + const list = q(root, '[data-list="titles"]'); + const summary = q(root, '.fc-rv-summary'); + const note = q(root, '.fc-rv-note'); + const queue = new TitleQueue(); + const panes = host.closest('.fc-panes'); + const trashNav = document.querySelector('.fc-nav-item[data-view="trash"]'); + const nav = el(``); + trashNav?.after(nav); + const badge = q(nav, '.fc-nav-count'); + let items: UntitledItem[] = []; + let loadedOnce = false; + let token = 0; + const asked = new Set(); + + const showNote = (text: string, error = false): void => { setText(note, text); setClass(note, 'is-error', error); }; + + queue.events.on('count', (n) => { + setText(badge, n > 0 ? String(n) : ''); + setClass(badge, 'is-on', n > 0); + }); + + const askSuggestions = (row: HTMLElement, id: string): void => { + if (asked.has(id)) return; + asked.add(id); + titlesApi.suggest(id).then((r) => { if (row.isConnected) fillSuggestions(row, r.suggestions); }).catch(() => asked.delete(id)); + }; + + const render = (): void => { + patchList(list, items, { + key: (i) => i.id, + create: (i) => { const n = rowNode(i); askSuggestions(n, i.id); return n; }, + update: fillRow, + }); + setText(summary, queue.count ? `${plural(queue.count, 'entry needs a title', 'entries need a title')}. Type one or pick a suggestion, then press Enter.` : 'Every entry has a title'); + if (!items.length && loadedOnce) showNote('Nothing here. Imported entries without a title wait here until you give them one.'); + }; + + const load = async (): Promise => { + const mine = ++token; + try { + const page = await titlesApi.untitled(200, 0); + if (mine !== token) return; + items = page.items; + loadedOnce = true; + queue.setCount(page.total); + render(); + } catch (e) { + if (mine === token) showNote((e as Error).message, true); + } + }; + + const recount = async (fromImport: boolean): Promise => { + try { + const page = await titlesApi.untitled(1, 0); + const rose = queue.setCount(page.total); + if (fromImport && rose > 0) offer(rose); + } catch { void 0; } + }; + + const open = (): void => { nav.click(); }; + + const offer = (n: number): void => { + const key = 'titles-needed'; + toast(n === 1 ? '1 imported entry needs a title' : `${n} imported entries need a title`, 'info', { key, ms: 9000 }); + const node = document.querySelector(`#toast-root .fc-toast[data-key="${key}"]`); + if (node && !node.querySelector('.fc-toast-act')) { + const act = el(''); + act.addEventListener('click', open); + node.firstElementChild?.after(act); + } + }; + + const save = (row: HTMLElement, id: string): void => { + const input = q(row, '.fc-tt-input'); + const text = input.value.trim(); + const refused = checkTitle(text); + if (refused) { showNote(refused, true); input.focus(); return; } + const before = items; + const at = items.findIndex((i) => i.id === id); + items = items.filter((i) => i.id !== id); + queue.setCount(queue.count - 1); + render(); + showNote(''); + titlesApi.setTitle(id, text).then(() => { + engine.library.events.emit('item:changed', id); + }).catch((e: Error) => { + items = before; + queue.setCount(queue.count + 1); + render(); + const back = list.querySelector(`[data-key="${CSS.escape(id)}"]`); + if (back) { q(back, '.fc-tt-input').value = text; q(back, '.fc-tt-input').focus(); } + showNote(`Not saved: ${e.message}`, true); + void at; + }); + const next = list.children[Math.min(at, list.children.length - 1)] as HTMLElement | undefined; + next?.querySelector('.fc-tt-input')?.focus(); + }; + + root.addEventListener('submit', (ev) => { + ev.preventDefault(); + const row = (ev.target as HTMLElement).closest('.fc-tt-row'); + if (row?.dataset.key) save(row, row.dataset.key); + }); + + root.addEventListener('click', (ev) => { + const btn = (ev.target as HTMLElement).closest('[data-act]'); + const row = btn?.closest('.fc-tt-row'); + const id = row?.dataset.key; + if (!btn || !row || !id) return; + const input = q(row, '.fc-tt-input'); + if (btn.dataset.act === 'pick' && btn.dataset.title) { + input.value = btn.dataset.title; + input.focus(); + input.setSelectionRange(input.value.length, input.value.length); + } else if (btn.dataset.act === 'lookup') { + btn.disabled = true; + setText(btn, 'Looking it up'); + titlesApi.lookUp(id).then((r) => { + btn.dataset.act = 'pick'; + btn.dataset.title = r.title; + setText(btn, `${r.service}: ${r.title}`); + setTitle(btn, `${r.title} · ${r.reason}`); + }).catch((e: Error) => { + setText(btn, 'Look it up'); + showNote(e.message, true); + }).finally(() => { btn.disabled = false; }); + } + }); + + root.addEventListener('keydown', (ev) => { + if (ev.key !== 'ArrowRight' && ev.key !== 'ArrowLeft') return; + const btn = (ev.target as HTMLElement).closest('.fc-tt-sug'); + const strip = btn?.parentElement; + if (!btn || !strip) return; + const live = Array.from(strip.querySelectorAll('.fc-tt-sug')).filter((b) => !b.hidden); + const at = live.indexOf(btn) + (ev.key === 'ArrowRight' ? 1 : -1); + live[(at + live.length) % live.length]?.focus(); + ev.preventDefault(); + }); + + engine.library.events.on('view', (view) => { + const on = view === VIEW; + setClass(nav, 'is-active', on); + nav.setAttribute('aria-current', on ? 'page' : 'false'); + if (on) void load(); + }); + nav.addEventListener('click', () => { if (panes && panes.dataset.view !== 'titles') panes.dataset.view = 'titles'; }); + engine.library.events.on('items:added', () => { void (engine.library.view === VIEW ? load() : recount(true)); }); + engine.library.events.on('items:removed', () => { void recount(false); }); + engine.library.events.on('items:restored', () => { void recount(false); }); + engine.library.events.on('library:switched', () => { void (engine.library.view === VIEW ? load() : recount(false)); }); + void recount(false); +} From af5250bb7664d1ecfca75661d550a450375991b7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:06:26 -0500 Subject: [PATCH 13/27] feat(window): mount the needs a title view and link its stylesheet Declares and mounts the view beside Trash and links titles.css. --- frontend/index.html | 1 + frontend/src/ui/app.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/frontend/index.html b/frontend/index.html index c81d065..5817331 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -69,6 +69,7 @@ + diff --git a/frontend/src/ui/app.ts b/frontend/src/ui/app.ts index 0f388dc..62593ff 100644 --- a/frontend/src/ui/app.ts +++ b/frontend/src/ui/app.ts @@ -10,6 +10,7 @@ import { mountItemList } from './itemlist'; import { mountPreferences } from './preferences'; import { mountSide } from './side'; import { mountTrash } from './trash'; +import { mountTitles } from './titles'; import { bindStatus, watchEngine } from './status'; import { applyTheme, readChoice, saveChoice } from './themes'; import { toast } from './toast'; @@ -53,6 +54,10 @@ const SHELL = `

${icon('trash', 14)}Trash

+
+

${icon('info', 14)}Needs a title

+
+

${icon('sliders', 14)}Preferences

@@ -77,6 +82,7 @@ export function mountApp(engine: Engine): void { mountAdd(engine, at('tools')); mountDuplicates(engine, at('duplicates')); mountTrash(engine, at('trash')); + mountTitles(engine, at('titles')); mountPreferences(engine, at('preferences')); engine.events.on('theme:changed', (theme) => { const choice = { ...readChoice(), theme }; From d2fd71bc4178b079169a7f310aa6643e9ef871ee Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:07:35 -0500 Subject: [PATCH 14/27] docs(import): describe keywords as tags and the from-keywords verb The import page gives the splitter rules, the new counts, the option on the route and the command line, and the from-keywords pass; the window page names the new box. --- docs/IMPORT_EXPORT.md | 30 +++++++++++++++++++++++++++--- docs/WINDOW.md | 2 +- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/docs/IMPORT_EXPORT.md b/docs/IMPORT_EXPORT.md index 87db648..a006e9e 100644 --- a/docs/IMPORT_EXPORT.md +++ b/docs/IMPORT_EXPORT.md @@ -22,6 +22,7 @@ When no format is given, FormCite picks one from the file extension, then from t - Normalises each record (names, dates, DOI, pages, whitespace) through `app/record/normalize.py`. - With duplicates set to `skip` (the default), a record that matches an item already in the library, by DOI or else by title, year and first author's family name, is skipped. Records added earlier in the same import count. With `add`, every record is added. - A record the library refuses is reported under `failed`, and the rest of the import still goes in. +- With keywords as tags on (`keywords_as_tags`, off by default), each new item also gets its keywords as tags, in the same per-record transaction. See below. The answer: @@ -32,12 +33,33 @@ The answer: "added": ["item id", "..."], "skipped": [{"index": 2, "title": "...", "duplicate_of": "item id"}], "failed": [{"index": 5, "title": "...", "error": "..."}], - "duplicates_checked": true + "duplicates_checked": true, + "keywords_as_tags": false, + "tags_created": 0, + "tags_reused": 0, + "items_tagged": 0 } ``` `index` counts records in the file from 0. +## Keywords as tags + +Imports keep an entry's keywords as one text field (`keyword` in the item's CSL-JSON), and that field is never changed, so an export gives the same keywords back. When asked, FormCite also turns them into tags: + +- One splitter for every format: split on commas and semicolons (RIS `KW` lines arrive already joined with commas), trim, collapse inner white space, drop empty pieces, and keep the first spelling of words that differ only in case. +- A tag that already exists in any case is reused with its stored spelling; otherwise a new tag is made. Tag names have no length limit, so nothing is cut. +- Only items the import adds are tagged. A record skipped as a duplicate leaves the existing item untouched; use `tags from-keywords` for those. +- Counts: `tags_created` (new tags), `tags_reused` (existing tags applied), `items_tagged` (items that got at least one tag). + +For a library imported without the option, convert afterwards: + +``` +./formcite cli tags from-keywords [--collection ID] [--dry-run] +``` + +It walks every item not in the trash (or one collection), adds the same tags and reports the same counts plus `items_checked` and `tags`, each with `name`, `items` and `new`. `--dry-run` lists those tags and changes nothing. + ## What an export does Export writes the chosen items in one format, BibTeX by default. Choose items by id, by collection, by tag, or give nothing for the whole library. Items in the trash are left out unless named by id. @@ -45,7 +67,8 @@ Export writes the chosen items in one format, BibTeX by default. Choose items by ## Command line ``` -./formcite cli import FILE [--format NAME] [--duplicates skip|add] +./formcite cli import FILE [--format NAME] [--duplicates skip|add] [--keywords-as-tags] +./formcite cli tags from-keywords [--collection ID] [--dry-run] ./formcite cli export [--format NAME] [--ids ID...] [--collection ID] [--tag NAME] [--out FILE] ./formcite cli formats ``` @@ -58,7 +81,8 @@ All under `/api/library` on the engine. Reads need nothing; writes need the wind | method and path | does | | --- | --- | -| `POST /import` | body `{text, format?, on_duplicate?}` or `{path, format?, on_duplicate?}`; answers the import result, 201 | +| `POST /import` | body `{text, format?, on_duplicate?, keywords_as_tags?}` or `{path, format?, on_duplicate?, keywords_as_tags?}`; answers the import result, 201 | +| `POST /tags/from-keywords` | body `{collection?, dry_run?}`; turns keywords of existing items into tags and answers the counts | | `GET /export?format=&ids=&collection=&tag=` | the exported text; `ids` is comma-separated | | `GET /formats` | each format with `available` and its extensions | | `GET /batches` | import batches, newest first, with item counts | diff --git a/docs/WINDOW.md b/docs/WINDOW.md index 8474237..b7efa5d 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -37,7 +37,7 @@ The **Items** view has three panes side by side. The **Add** button opens a dialog with three ways in: - **By identifier.** Paste a DOI, an arXiv id, an ISBN or a PubMed ID. FormCite looks it up and shows what it found before you add it, and says plainly when the item is already in your library. Looking something up is the only time FormCite goes on the network, and only when you ask. -- **Import.** Paste text or pick a file in BibTeX, RIS or CSL-JSON. The format can be picked or left for FormCite to recognise. +- **Import.** Paste text or pick a file in BibTeX, RIS or CSL-JSON. The format can be picked or left for FormCite to recognise. Tick **Turn keywords into tags** (off by default, remembered until the window is closed) to also tag each new item with its keywords; it applies to pasted and dropped files alike, the result line says how many tags were added, and the tag list in the library pane fills in place. - **Export.** Save the items you are looking at in one of those formats. You can also drop PDF files anywhere on the window. The window sends each dropped file's bytes to the engine, which reads it, finds its identifier, looks it up and attaches the file to the new item; no file path is needed, and progress shows in place. If the item is already in the library and already holds a file with the same content, the file is not attached a second time. Other files that FormCite can import are imported. From 99bd71cdb6cba62066188f447bd9526ad93672f6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:07:49 -0500 Subject: [PATCH 15/27] docs(skill): teach the formcite skill keywords as tags The skill names the import option on the MCP tool and the command line, asks for it only when the person wants it, and lists the from-keywords verb. --- .claude/skills/formcite/SKILL.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.claude/skills/formcite/SKILL.md b/.claude/skills/formcite/SKILL.md index 47d37a7..6699ab1 100644 --- a/.claude/skills/formcite/SKILL.md +++ b/.claude/skills/formcite/SKILL.md @@ -20,7 +20,7 @@ Two ways, in this order of preference. 1. **The MCP server.** When the client lists a `formcite` server, use its tools. `./formcite agents install` registers it; it runs `./formcite mcp` on stdio and is read-only unless the person registered it with `--allow-write`. Its tools: - Read-only, no network: `search` (`text`), `get_item` (`id`), `list_items` (`collection` or `tag`), `list_collections`, `list_tags`, `list_styles`, `cite`, `bibliography`, `format_document` (several citations in document order plus their bibliography). - Read-only, reaches the network: `lookup_preview` (an identifier; shows the record and whether the library has it, adds nothing). - - Write, listed only when the person allowed writing (the server runs with `--allow-write`, or over HTTP the token may write): `add_item`, `add_by_identifier` (also reaches the network), `import_references` (`text` and `format`: bibtex, ris, csljson, formtxt), `tag_item`. + - Write, listed only when the person allowed writing (the server runs with `--allow-write`, or over HTTP the token may write): `add_item`, `add_by_identifier` (also reaches the network), `import_references` (`text` and `format`: bibtex, ris, csljson, formtxt; `keywords_as_tags` only when the person asked for keywords as tags), `tag_item`. 2. **The command line.** From the FormCite folder, `./formcite cli [group] ...` works on the current library without the engine. It prints JSON on stdout and one plain sentence on stderr. Run `./formcite cli [group] --help` before a verb you have not used in this conversation, because flags are not guessed. If the MCP tool list has fewer tools than a task needs, use the command line for the rest. Do not call a tool name that the server did not list. @@ -34,7 +34,8 @@ If the MCP tool list has fewer tools than a task needs, use the command line for | Cite these in a style, make a bibliography | MCP `list_styles` then `cite`, `bibliography` or `format_document`; or `cli styles` then `cli format` | nothing, formatting changes nothing | | Add this DOI, arXiv id, ISBN, PubMed ID | MCP `lookup_preview`, or `cli lookup` (both reach the network: ask first) | MCP `add_by_identifier`, or `cli add` | | Identify this PDF | nothing reads it without the network | `cli identify` | -| Import this .bib, .ris or CSL-JSON file | `cli formats` | `cli import` | +| Import this .bib, .ris or CSL-JSON file | `cli formats` | `cli import` (add `--keywords-as-tags` only if the person wants keywords as tags) | +| Turn keywords of items already imported into tags | `cli tags from-keywords --dry-run` | `cli tags from-keywords` | | Export as BibTeX, RIS or CSL-JSON | `cli export` prints to stdout | `cli export --out FILE` writes a file the person named | | Duplicates | `cli duplicates` (find) | merging | | Tag, collect, note | `cli tag`, `cli collection`, `cli note` listings | any change | From 00411018237e2186ee96b236f4a903a6a8890e29 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:08:08 -0500 Subject: [PATCH 16/27] docs(hashout): log keywords as tags on import Records the splitter rules, the duplicate choice and the measured counts and window check for keywords as tags. --- backend/HASHOUT_LOG.md | 4 ++++ frontend/HASHOUT_LOG.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index e0ab10e..b45d672 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1669,3 +1669,7 @@ New in v0.9.0 (2026-11-27). `include_trashed=true` on the position route replace ## app/store/items.py {#app-items-title-required} New in v0.9.0 (2026-11-27). `create` refuses a title that is empty or only white space with `Invalid("A title is required.")` (HTTP 422 through the routers, a line on stderr in the CLI) when no `batch_id` is given, which is every interactive path (`POST /api/library/items`, `item add`, the MCP add tool); `update` refuses it only when the item holds a non-blank title, so an old title-less item can still be edited in other fields. The model has no type that exempts a title (`title` is TEXT for ALL types in `record/fields.py`), so the rule covers every type, as the window already did. Import, lookup and identify pass a `batch_id` and keep their old behaviour: a BibTeX, RIS and CSL JSON entry with no title still imports with an empty title (checked: 2 of 2, 2 of 2 and 1 of 1 added, 0 failed). The twelve style regression cases pass. + +## app/services/transfer.py, app/routers/transfer.py, app/cli_transfer.py, app/mcp/tools.py {#app-import-keywords-as-tags} + +New in v0.10.0 (2026-11-27). `keywords_as_tags` (off by default) tags each item the import adds, inside that record's savepoint, through `tags.add`. `split_keywords` is the one splitter: commas, semicolons and newlines, white space collapsed, empties dropped, first spelling kept per `casefold`. The mappers already join (bibtex `", "`, RIS `KW` lines `", "`, ISBN `"; "`), so a keyword that itself holds a comma (an RIS `KW` of "Smith, J.") is split in two; that is the price of one splitter. `tags.name` is `UNIQUE COLLATE NOCASE` with no length limit, so `SELECT name FROM tags WHERE name = ?` already finds a case variant and nothing is ever cut (a 319-character keyword became a tag). Skipped duplicates are not tagged: skip means the existing item is not touched; `tags from-keywords` covers them. `tags_reused` counts distinct pre-existing tags applied. `tags from-keywords` is a new `tags` group in `cli_transfer.py` because the `tag` group lives in `cli.py`; its route is `POST /api/library/tags/from-keywords`. The window-key route in `routers/cite_write.py` (service import) does not take the option. Checked on a fresh data folder with 200 generated BibTeX entries (mixed case, repeats, both separators, one empty, one long): off 0 tags; on 49 created, 199 items tagged, 651 links, equal to a direct count; from-keywords dry run listed the same 49 tags and per-tag counts and changed nothing, the real run gave the same tag table as the on-import; RIS and CSL JSON exports of it imported with the option gave 49, 199 and 651 again; a second import with `--duplicates add` gave 0 created, 49 reused. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index ae2fc1d..ff1b6c7 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -420,3 +420,7 @@ New in v0.9.0 (2026-11-27). The tag list was measured with 28 to 31 real tags on ## src/io/detail.ts, src/engine/detail.ts, src/ui/detail.ts, src/styles/detail.css {#src-detail-creators} New in v0.9.0 (2026-11-27). Creators are edited in a fixed 144 px box under Title, one two-line row per creator: family and given on the first line, role (the 26 CSL name roles `NAME_ROLES` in `backend/app/store/items.py` accepts) with institution toggle, move up, move down and remove on the second. The engine keeps creators per role (`csl.author`, `csl.editor`, ...), each role ordered, with no order across roles; a save sends one `PATCH /api/library/items/{id}` whose `fields` carries every role that had or has names, an emptied role as `""` (which drops it). So the session keeps the order the user set, but after a reload the rows come back grouped by role in `NAME_ROLES` order. An institution is `{literal}`. `DetailModel.reconcile` keeps row keys across the quiet reload after a save, so `patchList` writes no row; a move swaps the two rows' contents and keys in place so no node moves. A row saves on blur out of the row, on Enter, and on a role change; Escape puts the stored row back (a new unsaved row is dropped); a refused save shows in `.fc-dt-cr-error` and puts the stored list back. The row buttons are `tabindex="-1"` so Tab runs family, given, role, next row; Alt plus Up or Down moves a row from the keyboard. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and 50 kB/s, fresh engine: add, reorder, role to editor, institution, refused save (routed 422) and remove each sent one PATCH (200), a reload read `author: [Castillo]`, `editor: [Second Ann, {literal: Acme Institute}]` through the API, the list creator cell went from "Haddad et al." to "Novak et al." to "Novak and Tanaka", the box stayed 144 px, and layout shift was 0 without input and 0.00085 with input (the rows under a removed row move up). + +## src/ui/add.ts, src/engine/add.ts, src/io/add.ts, src/styles/add.css {#src-add-keywords-as-tags} + +New in v0.10.0 (2026-11-27). The Import tab's end row holds an unticked "Turn keywords into tags" box (`margin-right: auto` puts it left of Import, so the row height is unchanged). Its state is `Adding.keywordsAsTags`, a field that lives as long as the page, not browser storage. Pasted and dropped imports both send it; a dropped import now also writes its result on the tab's `.fc-add-line`, which is a fixed 40 px, so "N tags added" (created plus reused) needs no new space. When `items_tagged` is above 0 the engine calls `library.tagsChanged()` and the side pane patches its list. Checked in a private built copy, fresh engine, CPU 4x, 400 ms, 50 kB/s: a 200-entry BibTeX dropped with the box ticked, line "kw200.bib: Imported 200 as bibtex, 49 tags added.", the tag list went 0 to 49 rows in the same `ul` node, layout shift 0 without and 0 with input. Seen but not in this slice: the item list behind the dialog still read 0 items in the status bar when the tag list had filled, and a "The engine is back." toast showed under the throttle. From 58142c0167a008797d75156e34891b676c2975e1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:08:31 -0500 Subject: [PATCH 17/27] fix(dom): patchlist moves only nodes that change place The list patch keeps the longest run of nodes where they are and inserts only the others, so a focused node is not detached when it is already in place. A moved focused node gets focus and its selection range back. --- frontend/src/ui/dom.ts | 56 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/frontend/src/ui/dom.ts b/frontend/src/ui/dom.ts index 65864ae..7781d4a 100644 --- a/frontend/src/ui/dom.ts +++ b/frontend/src/ui/dom.ts @@ -29,19 +29,67 @@ export function patchList(container: HTMLElement, items: T[], opts: PatchList } const seen = new Set(items.map((item) => opts.key(item))); for (const [k, node] of byKey) if (!seen.has(k)) node.remove(); - let cursor: Element | null = container.firstElementChild; + const order = new Map(); + let tail: Element | null = null; + let at = 0; + for (const child of Array.from(container.children)) { + order.set(child, at++); + if (!tail && (child as HTMLElement).dataset.key === undefined) tail = child; + } + const nodes: HTMLElement[] = []; for (const item of items) { const k = opts.key(item); let node = byKey.get(k); - if (node) { + if (node && node.parentElement === container) { opts.update(node, item); } else { node = opts.create(item); node.dataset.key = k; } - if (node !== cursor) container.insertBefore(node, cursor); - else cursor = cursor.nextElementSibling; + nodes.push(node); + } + const stay = longestRun(nodes.map((n) => order.get(n) ?? -1)); + const was = document.activeElement as HTMLElement | null; + let range: [number, number, 'forward' | 'backward' | 'none'] | null = null; + if (was instanceof HTMLInputElement || was instanceof HTMLTextAreaElement) { + try { range = [was.selectionStart ?? 0, was.selectionEnd ?? 0, was.selectionDirection ?? 'none']; } catch { range = null; } + } + let moved = false; + let ref: Element | null = tail; + for (let i = nodes.length - 1; i >= 0; i--) { + const node = nodes[i]; + if (!stay.has(i) && !(node.parentElement === container && node.nextElementSibling === ref)) { + container.insertBefore(node, ref); + if (was && node.contains(was)) moved = true; + } + ref = node; + } + if (moved && was && was.isConnected && document.activeElement !== was) { + was.focus({ preventScroll: true }); + if (range && (was instanceof HTMLInputElement || was instanceof HTMLTextAreaElement)) { + try { was.setSelectionRange(range[0], range[1], range[2]); } catch { void 0; } + } + } +} + +function longestRun(seq: number[]): Set { + const tails: number[] = []; + const prev: number[] = new Array(seq.length).fill(-1); + for (let i = 0; i < seq.length; i++) { + if (seq[i] < 0) continue; + let lo = 0; + let hi = tails.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (seq[tails[mid]] < seq[i]) lo = mid + 1; else hi = mid; + } + if (lo > 0) prev[i] = tails[lo - 1]; + tails[lo] = i; } + const out = new Set(); + let at = tails.length ? tails[tails.length - 1] : -1; + while (at >= 0) { out.add(at); at = prev[at]; } + return out; } export function swapMedia(img: HTMLImageElement, nextSrc: string): Promise { From f8f4874f12cf994d6e25f9285b3d5d5a3365bd89 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:08:31 -0500 Subject: [PATCH 18/27] fix(side): drop late tag reads and add a new tag row at the input Reads of tags and collections older than the latest notice or rename are dropped. A tag typed in the item pane gets its row at once at its sorted place and is rekeyed to the engine's id without moving. The tag list scrolls inside a capped box. --- frontend/src/styles/side.css | 2 ++ frontend/src/ui/side.ts | 65 ++++++++++++++++++++++++++++++++---- 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/frontend/src/styles/side.css b/frontend/src/styles/side.css index ca690f5..b35a20b 100644 --- a/frontend/src/styles/side.css +++ b/frontend/src/styles/side.css @@ -6,6 +6,8 @@ } .fc-side-list { list-style: none; margin: 0; padding: 0; } +.fc-side-tags { max-height: calc(var(--fc-side-row-h) * 12); overflow-y: auto; overscroll-behavior: contain; } +.fc-side-row.is-pending { pointer-events: none; } .fc-side-row { position: relative; diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 50d0585..63f1f66 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -28,8 +28,13 @@ interface Pane { tags: HTMLUListElement; tagMsg: HTMLElement; collapsed: Set; + want: { coll: number; tags: number }; + pending: Map; } +const PENDING = 'new:'; +const PENDING_MS = 10000; + const EDIT_PARTS = ` @@ -157,8 +162,11 @@ function treeKey(pane: Pane, ev: KeyboardEvent): void { async function loadCollections(pane: Pane): Promise { const done = pendingClass(pane.tree); + const mine = pane.want.coll; try { - const entries = flattenTree(await sideApi.collections()); + const rows = await sideApi.collections(); + if (mine !== pane.want.coll) return; + const entries = flattenTree(rows); keepFocus(() => patchList(pane.tree, entries, { key: (e) => e.id, create: (e) => { const n = rowShell('collection', 'folder'); updateCollection(n, e, pane); return n; }, @@ -180,13 +188,51 @@ function updateTag(node: HTMLElement, tag: TagRow, pane: Pane): void { setText(node.querySelector('.fc-side-count'), formatCount(tag.item_count)); setData(node, 'scope', scopeKey({ kind: 'tag', id: tag.id })); setData(node, 'name', tag.name); + setClass(node, 'is-pending', tag.id.startsWith(PENDING)); setCurrent(node, node.dataset.scope === scopeKey(pane.engine.library.scope)); } +function settlePending(pane: Pane, read: TagRow[]): TagRow[] { + const out = [...read]; + const nodes = Array.from(pane.tags.children) as HTMLElement[]; + for (const [name, since] of Array.from(pane.pending)) { + const real = read.find((t) => t.name === name); + const node = nodes.find((n) => n.dataset.key === PENDING + name); + if (real) { + pane.pending.delete(name); + if (node && !nodes.some((n) => n.dataset.key === real.id)) node.dataset.key = real.id; + } else if (Date.now() - since < PENDING_MS) { + out.push({ id: PENDING + name, name, item_count: 1 }); + } else { + pane.pending.delete(name); + } + } + return out; +} + +function addPendingTag(pane: Pane, raw: string): void { + const name = cleanName(raw); + if (!name || pane.pending.has(name)) return; + if ((Array.from(pane.tags.children) as HTMLElement[]).some((r) => r.dataset.name === name)) return; + const tag: TagRow = { id: PENDING + name, name, item_count: 1 }; + const row = rowShell('tag', 'tag'); + updateTag(row, tag, pane); + row.dataset.key = tag.id; + row.classList.add('is-pending'); + pane.pending.set(name, Date.now()); + const others = Array.from(pane.tags.children) as HTMLElement[]; + const next = others.find((r) => (r.dataset.name ?? '').localeCompare(name, undefined, { sensitivity: 'base' }) > 0) ?? null; + pane.tags.insertBefore(row, next); + setText(pane.tagMsg, ''); +} + async function loadTags(pane: Pane): Promise { const done = pendingClass(pane.tags); + const mine = pane.want.tags; try { - const tags = sortTags(await sideApi.tags()); + const read = await sideApi.tags(); + if (mine !== pane.want.tags) return; + const tags = sortTags(settlePending(pane, read)); keepFocus(() => patchList(pane.tags, tags, { key: (t) => t.id, create: (t) => { const n = rowShell('tag', 'tag'); updateTag(n, t, pane); return n; }, @@ -273,7 +319,7 @@ async function commitRename(pane: Pane, row: HTMLElement): Promise { const lib = pane.engine.library; const before = row.dataset.name ?? ''; const tagged = row.dataset.kind === 'tag'; - if (tagged) { setData(row, 'name', name); setText(row.querySelector('.fc-side-name'), name); placeTag(pane, row, name); } + if (tagged) { pane.want.tags++; setData(row, 'name', name); setText(row.querySelector('.fc-side-name'), name); placeTag(pane, row, name); } try { if (row.dataset.kind === 'collection') await sideApi.renameCollection(id, name); else await sideApi.renameTag(id, name); @@ -370,6 +416,7 @@ async function removeRow(pane: Pane, row: HTMLElement): Promise { function pick(pane: Pane, node: HTMLElement): void { const lib = pane.engine.library; const kind = node.dataset.kind; + if ((node.dataset.key ?? '').startsWith(PENDING)) return; if (kind === 'all') lib.setScope(ALL); else if (kind === 'unfiled') lib.setScope({ kind: 'unfiled', id: '', label: 'Unfiled' }); else if (kind === 'collection') lib.setScope({ kind: 'collection', id: node.dataset.key ?? '', label: node.dataset.name ?? '' }); @@ -406,7 +453,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { const tags = el('
    '); tagMsg.before(tags); - const pane: Pane = { engine, fixed, tree, collMsg, tags, tagMsg, collapsed: new Set() }; + const pane: Pane = { engine, fixed, tree, collMsg, tags, tagMsg, collapsed: new Set(), want: { coll: 0, tags: 0 }, pending: new Map() }; tree.addEventListener('keydown', (ev) => treeKey(pane, ev)); host.addEventListener('click', (ev) => { @@ -446,13 +493,19 @@ export function mountSide(engine: Engine, host: HTMLElement): void { engine.library.events.on('scope', (s) => { markActive(pane, s); applyTree(pane); }); markActive(pane, engine.library.scope); const ev = engine.library.events; - const refreshCollections = coalesce(() => loadCollections(pane)); - const refreshTags = coalesce(() => loadTags(pane)); + const scheduleCollections = coalesce(() => loadCollections(pane)); + const scheduleTags = coalesce(() => loadTags(pane)); const refreshTotals = coalesce(() => loadTotals(pane)); + const refreshCollections = (): void => { pane.want.coll++; scheduleCollections(); }; + const refreshTags = (): void => { pane.want.tags++; scheduleTags(); }; const refreshAll = (): void => { refreshCollections(); refreshTags(); refreshTotals(); }; ev.on('collections:changed', refreshTotals); ev.on('collections:changed', refreshCollections); ev.on('tags:changed', refreshTags); + document.addEventListener('keydown', (e) => { + const input = e.target instanceof HTMLInputElement && e.target.classList.contains('fc-dt-tag-input') ? e.target : null; + if (input && e.key === 'Enter' && !e.isComposing) addPendingTag(pane, input.value); + }, true); ev.on('items:added', refreshAll); ev.on('items:removed', refreshAll); ev.on('items:restored', refreshAll); From b288b237a41fc20a7bacb3dbad283cd03cb9b0ff Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:12:14 -0500 Subject: [PATCH 19/27] fix(titles): pin look it up to the strip end and close the toast on open Suggestions arriving no longer move the lookup button, and the toast action dismisses its toast as it opens the view. --- frontend/src/styles/titles.css | 2 +- frontend/src/ui/titles.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/styles/titles.css b/frontend/src/styles/titles.css index dad9f39..c8beea5 100644 --- a/frontend/src/styles/titles.css +++ b/frontend/src/styles/titles.css @@ -8,6 +8,6 @@ .fc-tt-strip { display: flex; flex-wrap: nowrap; gap: var(--space-1h); height: var(--tt-strip); overflow: hidden; align-items: center; } .fc-tt-sug { flex: 0 1 auto; min-width: 0; max-width: var(--tt-sug-max); height: var(--tt-strip); box-sizing: border-box; padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-12); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; } .fc-tt-sug:hover:not(:disabled), .fc-tt-sug:focus-visible { background: var(--bg-hover); border-color: var(--accent-color); outline: none; } -.fc-tt-sug.is-lookup { border-style: dashed; color: var(--text-secondary); } +.fc-tt-sug.is-lookup { order: 2; margin-left: auto; flex-shrink: 0; border-style: dashed; color: var(--text-secondary); } .fc-tt-none { color: var(--text-muted); font-size: var(--fs-12); } .fc-toast-act { pointer-events: auto; height: var(--size-row-sm); padding: 0 var(--space-2); border: 1px solid var(--accent-color); border-radius: var(--radius-sm); background: transparent; color: var(--accent-color); font: inherit; font-size: var(--fs-12); cursor: pointer; } diff --git a/frontend/src/ui/titles.ts b/frontend/src/ui/titles.ts index 9760a01..6209600 100644 --- a/frontend/src/ui/titles.ts +++ b/frontend/src/ui/titles.ts @@ -118,7 +118,7 @@ export function mountTitles(engine: Engine, host: HTMLElement): void { const node = document.querySelector(`#toast-root .fc-toast[data-key="${key}"]`); if (node && !node.querySelector('.fc-toast-act')) { const act = el(''); - act.addEventListener('click', open); + act.addEventListener('click', () => { node.querySelector('.fc-toast-close')?.click(); open(); }); node.firstElementChild?.after(act); } }; From f2dc7326e21c2fe7c2afd0bdf2d9a6e6fb5b2516 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:12:34 -0500 Subject: [PATCH 20/27] docs(titles): describe untitled entries, suggestions and the view Adds TITLES.md and a Needs a title section to WINDOW.md. --- docs/TITLES.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ docs/WINDOW.md | 4 ++++ 2 files changed, 49 insertions(+) create mode 100644 docs/TITLES.md diff --git a/docs/TITLES.md b/docs/TITLES.md new file mode 100644 index 0000000..c753dd0 --- /dev/null +++ b/docs/TITLES.md @@ -0,0 +1,45 @@ +# Entries without a title + +An import never refuses an entry because it has no title. After the import, FormCite asks for a title, entry by entry: type one, or pick one of up to five suggestions built from what the entry already holds. + +## Where it shows + +- The window has a view **Needs a title** under Trash. Its count sits beside the name and is hidden at zero. +- After an import that brought in untitled entries, one notice says "N imported entries need a title" with a button that opens the view. +- Each row shows what is known (creators, year, container, attached file name), a title field and up to five suggestion buttons. A long suggestion is cut with an ellipsis; its full text and its reason are in the button's tooltip. +- Picking a suggestion fills the field and puts the cursor there, so you can edit before saving. Enter saves. The row leaves at once; if the engine refuses, it comes back with the reason. +- An empty title is not saved. +- Keyboard: Tab from the field to the suggestions, Left and Right between suggestions, Enter to pick. + +## Suggestions + +Built only from the entry itself, with no network call, best first, near-duplicates (case and punctuation) dropped, never empty, at most five, fewer rather than filler: + +1. a short title field (`title-short`) +2. the first sentence of the abstract, cut at a word boundary +3. an attached file's name, cleaned (extension, underscores, hashes, `final`, `v2`, `draft` and similar removed, capitalised) +4. an `event-title`, `collection-title` (series) or book title field that differs from the container +5. the container with the year ("Journal of Marine Ecology, 2021") +6. the first sentence of a note +7. the first creator's family name with year and type ("Okafor 2019, article") +8. the publisher or institution with the type, when there is no creator +9. the import's citation key, spaced out, unless it only repeats name and year or is a placeholder + +## Look it up + +When the entry has a DOI, ISBN, arXiv id or PMID, a **Look it up** button asks the matching lookup service for the title, only when clicked. It obeys the network switches. The answer appears as one more choice, labelled with the service's name. + +## Command line + + ./formcite cli titles list [--limit N] [--offset N] + ./formcite cli titles suggest ID + ./formcite cli titles set ID "A title" + +`suggest` prints the suggestions with their reasons on stderr and the JSON on stdout. `set` refuses an empty title. + +## Engine + +- `GET /api/library/untitled?limit=&offset=` · `{total, limit, offset, items: [{id, type, creators, year, container, identifiers, files, added, batch_id}]}` +- `GET /api/library/items/{id}/title-suggestions` · `{id, suggestions: [{title, reason}], identifiers}` +- `POST /api/library/items/{id}/title-lookup` · `{id, title, service, reason}`, 422 when there is no identifier or the network is off +- The title is set with `PATCH /api/library/items/{id}` and `{fields: {title}}`. diff --git a/docs/WINDOW.md b/docs/WINDOW.md index b7efa5d..2915451 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -75,3 +75,7 @@ Only the window can open files: the request is refused without the window's key. ## For developers The item list reads `GET /api/library/rows` (`scope` all, unfiled, collection, tag or batch, with `id` for the last three; `q`; `sort` title, creator, year, type, added or updated; `desc`; `offset`; `limit` up to 500) and `GET /api/library/rows/{id}` for one row. Each row is `{id, type, title, creator, year, container, added, updated, attachments, tags}`. Opening an attachment is `POST /api/library/attachments/{id}/open`, answering `{id, path, opened_with, formpdf: {found, path, used, reason}}`. + +## Needs a title + +Entries imported without a title wait in **Needs a title**, under Trash; its count is hidden at zero. After an import that brought some in, one notice offers to open the view. Each row shows what is known, a title field and up to five suggestions built from the entry itself; pick one to edit it, or type your own, then press Enter. **Look it up** appears only for entries with a DOI, ISBN, arXiv id or PMID and calls the network only when clicked. See [TITLES.md](TITLES.md). From 90483053dcb5170aabc6cfdbd666dd4563f8d1cc Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:12:43 -0500 Subject: [PATCH 21/27] fix(titles): keep the empty view message after the last save The note was cleared after the list rendered, so the last save hid the empty-state message. --- frontend/src/ui/titles.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/ui/titles.ts b/frontend/src/ui/titles.ts index 6209600..67cfea9 100644 --- a/frontend/src/ui/titles.ts +++ b/frontend/src/ui/titles.ts @@ -132,8 +132,8 @@ export function mountTitles(engine: Engine, host: HTMLElement): void { const at = items.findIndex((i) => i.id === id); items = items.filter((i) => i.id !== id); queue.setCount(queue.count - 1); - render(); showNote(''); + render(); titlesApi.setTitle(id, text).then(() => { engine.library.events.emit('item:changed', id); }).catch((e: Error) => { From d61dcb4b74a91a91c08182d70fb256ca41a2792d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:13:09 -0500 Subject: [PATCH 22/27] docs(hashout): log the titles service and view Records the untitled rule, suggestion order, the lookup lock choice, the nav and toast workarounds and the measurements. --- backend/HASHOUT_LOG.md | 4 ++++ frontend/HASHOUT_LOG.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index b45d672..637cdcb 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1673,3 +1673,7 @@ New in v0.9.0 (2026-11-27). `create` refuses a title that is empty or only white ## app/services/transfer.py, app/routers/transfer.py, app/cli_transfer.py, app/mcp/tools.py {#app-import-keywords-as-tags} New in v0.10.0 (2026-11-27). `keywords_as_tags` (off by default) tags each item the import adds, inside that record's savepoint, through `tags.add`. `split_keywords` is the one splitter: commas, semicolons and newlines, white space collapsed, empties dropped, first spelling kept per `casefold`. The mappers already join (bibtex `", "`, RIS `KW` lines `", "`, ISBN `"; "`), so a keyword that itself holds a comma (an RIS `KW` of "Smith, J.") is split in two; that is the price of one splitter. `tags.name` is `UNIQUE COLLATE NOCASE` with no length limit, so `SELECT name FROM tags WHERE name = ?` already finds a case variant and nothing is ever cut (a 319-character keyword became a tag). Skipped duplicates are not tagged: skip means the existing item is not touched; `tags from-keywords` covers them. `tags_reused` counts distinct pre-existing tags applied. `tags from-keywords` is a new `tags` group in `cli_transfer.py` because the `tag` group lives in `cli.py`; its route is `POST /api/library/tags/from-keywords`. The window-key route in `routers/cite_write.py` (service import) does not take the option. Checked on a fresh data folder with 200 generated BibTeX entries (mixed case, repeats, both separators, one empty, one long): off 0 tags; on 49 created, 199 items tagged, 651 links, equal to a direct count; from-keywords dry run listed the same 49 tags and per-tag counts and changed nothing, the real run gave the same tag table as the on-import; RIS and CSL JSON exports of it imported with the option gave 49, 199 and 651 again; a second import with `--duplicates add` gave 0 created, 49 reused. + +## app/services/titles.py, app/routers/titles.py, app/cli.py {#app-titles} + +New in v0.10.0 (2026-11-27). "Untitled" is a live item whose `title`, trimmed of space, tab, CR and LF in SQL, is empty. Suggestions read only the item, its attachments and notes, never the network; order is short title, abstract first sentence, cleaned file name, event, series or book title differing from the container, container plus year, note first sentence, family plus year plus type, publisher plus type (no creator only), citation key. Near-duplicates compare `casefold` with every non-word character removed. A citation key equal to family plus year, or a placeholder such as `empty1`, `doi2017`, `filed2022`, `zz`, is dropped. Suggestions are cut at 90 characters on a word boundary. `title-lookup` resolves the first identifier in DOI, ISBN, arXiv, PMID order outside the library lock, so a slow service does not block the library; `NetworkOff` and `NetworkError` are `Invalid`, so they come back as 422 with the reason. `items.update` still accepts an empty title when the held title is empty, so `titles set` refuses an empty title itself and the window checks before it sends. The BibTeX importer does not map `eprint`/`archiveprefix` to an arXiv id, so an arXiv entry imported from BibTeX gets no Look it up. Checked with 12 untitled BibTeX entries on a fresh data folder: 0 to 4 suggestions each, 10 of 12 with at least one, the two with none hold only a year or nothing. The twelve style regression cases pass. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index ff1b6c7..1537f26 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -424,3 +424,7 @@ New in v0.9.0 (2026-11-27). Creators are edited in a fixed 144 px box under Titl ## src/ui/add.ts, src/engine/add.ts, src/io/add.ts, src/styles/add.css {#src-add-keywords-as-tags} New in v0.10.0 (2026-11-27). The Import tab's end row holds an unticked "Turn keywords into tags" box (`margin-right: auto` puts it left of Import, so the row height is unchanged). Its state is `Adding.keywordsAsTags`, a field that lives as long as the page, not browser storage. Pasted and dropped imports both send it; a dropped import now also writes its result on the tab's `.fc-add-line`, which is a fixed 40 px, so "N tags added" (created plus reused) needs no new space. When `items_tagged` is above 0 the engine calls `library.tagsChanged()` and the side pane patches its list. Checked in a private built copy, fresh engine, CPU 4x, 400 ms, 50 kB/s: a 200-entry BibTeX dropped with the box ticked, line "kw200.bib: Imported 200 as bibtex, 49 tags added.", the tag list went 0 to 49 rows in the same `ul` node, layout shift 0 without and 0 with input. Seen but not in this slice: the item list behind the dialog still read 0 items in the status bar when the tag list had filled, and a "The engine is back." toast showed under the throttle. + +## src/ui/titles.ts, src/engine/titles.ts, src/io/titles.ts, src/styles/titles.css {#src-titles} + +New in v0.10.0 (2026-11-27). `ViewId` has no `titles` and the nav buttons are built in `connections.ts`, neither owned by this slice, so `mountTitles` inserts its own `.fc-nav-item[data-view="titles"]` after Trash once at mount (the shared click handler in `connections.ts` sets `panes.dataset.view` from it) and casts `'titles'` to `ViewId`; `titles.css` holds the matching `.fc-panes[data-view="titles"]` show rule. The count uses `.fc-nav-count` with `is-on` (visibility), so the nav keeps its width at zero. `toast()` has no action argument, so the "Give them titles" button is inserted into the toast found by its key. Rows are a fixed 112 px (known line, field row, 28 px strip); the five suggestion buttons exist from the start and are only unhidden, and Look it up is pinned to the strip end with `margin-left: auto` so arriving suggestions do not move it (that move was the one 0.00092 shift without input before the fix). Checked in a private built copy under CPU 4x, 400 ms, 50 kB/s, fresh engine: import of 4 entries (3 untitled) gave one toast "3 imported entries need a title", count 3; rows 112 px each; pick then Enter, empty Enter refused with "Type a title or pick a suggestion first." and 2 rows kept, type then Enter twice; count 3, 2, then hidden; a MutationObserver on the list saw 0 added and only the 3 saved rows removed, one per save; layout shift 0 without input, 0.0247 and 0.0165 with input (rows below a saved row move up). From c58978df7fa4e48cc192fd9e6664f404dcf898ed Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:15:08 -0500 Subject: [PATCH 23/27] docs(log): tag list faults and the patchlist change Records the patchlist rule, the dropped late reads, the row added at the input and what was measured. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 1537f26..5af9d41 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -428,3 +428,7 @@ New in v0.10.0 (2026-11-27). The Import tab's end row holds an unticked "Turn ke ## src/ui/titles.ts, src/engine/titles.ts, src/io/titles.ts, src/styles/titles.css {#src-titles} New in v0.10.0 (2026-11-27). `ViewId` has no `titles` and the nav buttons are built in `connections.ts`, neither owned by this slice, so `mountTitles` inserts its own `.fc-nav-item[data-view="titles"]` after Trash once at mount (the shared click handler in `connections.ts` sets `panes.dataset.view` from it) and casts `'titles'` to `ViewId`; `titles.css` holds the matching `.fc-panes[data-view="titles"]` show rule. The count uses `.fc-nav-count` with `is-on` (visibility), so the nav keeps its width at zero. `toast()` has no action argument, so the "Give them titles" button is inserted into the toast found by its key. Rows are a fixed 112 px (known line, field row, 28 px strip); the five suggestion buttons exist from the start and are only unhidden, and Look it up is pinned to the strip end with `margin-left: auto` so arriving suggestions do not move it (that move was the one 0.00092 shift without input before the fix). Checked in a private built copy under CPU 4x, 400 ms, 50 kB/s, fresh engine: import of 4 entries (3 untitled) gave one toast "3 imported entries need a title", count 3; rows 112 px each; pick then Enter, empty Enter refused with "Type a title or pick a suggestion first." and 2 rows kept, type then Enter twice; count 3, 2, then hidden; a MutationObserver on the list saw 0 added and only the 3 saved rows removed, one per save; layout shift 0 without input, 0.0247 and 0.0165 with input (rows below a saved row move up). + +## src/ui/dom.ts, src/ui/side.ts, src/styles/side.css {#src-side-tag-faults} + +New in v0.10.0 (2026-11-27). `patchList` now keeps the longest run of nodes that are already in order and inserts only the others (each before its final next sibling), where it used to insert every node ahead of a cursor and so detached untouched neighbours when one node moved far. A moved node that held focus gets focus back with its selection range. Signature and callers are unchanged (item pane tags, notes, creators and attachments in `ui/detail.ts`, Preferences, trash, duplicates). The side pane counts notices (`pane.want`) and drops a tags or collections read that was issued before the latest notice or before a tag rename started, since the coalesced re-read follows it. A tag typed in the item pane gets its row at once: a capture keydown on `.fc-dt-tag-input` inserts a provisional row (`data-key` `new:NAME`, class `is-pending`, not clickable) in sorted place at the input, and the next tags read rekeys it to the engine's id in place; one never confirmed within 10 s is dropped. `engine/library.ts` carries no name in `tags:changed`; a `tags:adding` notice with the name, sent by `DetailModel.addTag` before the request, would replace the keydown listener. The tag list is capped at 12 rows and scrolls inside its box. The focus loss after a rename was not reproduced in this environment: 12 renames before the change and 10 of 10 after kept focus on the renamed entry 2 s later under CPU 4x, 400 ms and 50 kB/s, with a page-side focusout listener, patched `insertBefore`, `remove`, `focus` and `blur` logging stacks; the only focus change was the edit input giving way to the entry. Checked in a private built copy with 2,000 items, 31 tags on 600 items (seeded through the tags store `add` in a Python loop) and four collections: five new tags added from the item pane had their row at 250 ms and layout shift 0 without input, a tag delete, a scope pick, tree arrows (one tab stop) and note add and remove (one POST, one DELETE) all held. From 98efd35baf3b48c96740a1b92803cc8ddf0b0fa4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:15:59 -0500 Subject: [PATCH 24/27] fix(itemlist): re-read once for a large or first insert An insert of more than twelve new ids, or into an empty list, now re-reads the list once instead of asking a position and a row for every id, so a 200-item import shows its rows and count at once. --- frontend/src/engine/itemlist.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 6458870..24dae84 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -2,6 +2,7 @@ import type { Library } from './library'; import { fetchPosition, fetchRow, fetchRows, isUnknown, type PositionAnswer, type Row, type RowPosition, type RowQuery } from '../io/itemlist'; export const PAGE = 200; +const INSERT_MAX = 12; export interface ListSink { reset(total: number): void; @@ -145,6 +146,7 @@ export class ItemListModel { const gen = this.generation; const fresh = Array.from(new Set(ids)).filter((id) => this.indexOf(id) < 0); if (!fresh.length) return; + if (fresh.length > INSERT_MAX || this.total === 0) { this.reload(); return; } let answers: PositionAnswer[]; try { answers = await Promise.all(fresh.map((id) => fetchPosition(id, this.where()))); } catch (e) { if (gen === this.generation) this.sink.error(e instanceof Error ? e.message : String(e)); From 217f5cae5fe4df7ea54f8f642db2e2ff34737324 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:16:41 -0500 Subject: [PATCH 25/27] feat(cite): take keywords as tags on the service import The cite service's import body accepts keywords_as_tags and passes it to the import, off by default. --- backend/app/routers/cite_write.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/cite_write.py b/backend/app/routers/cite_write.py index 7dac557..3377eeb 100644 --- a/backend/app/routers/cite_write.py +++ b/backend/app/routers/cite_write.py @@ -140,12 +140,13 @@ class ImportBody(BaseModel): text: str format: str on_duplicate: str = "skip" + keywords_as_tags: bool = False @router.post("/import", status_code=201) def import_records(body: ImportBody, caller: Caller = Depends(writer)) -> dict: return _write(caller, "POST /api/cite/v1/import", lambda r: (list(r["added"]), []), - transfer.run_import_text, body.text, body.format, body.on_duplicate) + transfer.run_import_text, body.text, body.format, body.on_duplicate, body.keywords_as_tags) class TagNames(BaseModel): From 112f4af26db39b78eac48985b90c8d5653768bac Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:16:48 -0500 Subject: [PATCH 26/27] docs(hashout): log the large insert re-read Records why a big import left the list empty under a slow network and what the re-read measured. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 5af9d41..66a57c6 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -425,6 +425,10 @@ New in v0.9.0 (2026-11-27). Creators are edited in a fixed 144 px box under Titl New in v0.10.0 (2026-11-27). The Import tab's end row holds an unticked "Turn keywords into tags" box (`margin-right: auto` puts it left of Import, so the row height is unchanged). Its state is `Adding.keywordsAsTags`, a field that lives as long as the page, not browser storage. Pasted and dropped imports both send it; a dropped import now also writes its result on the tab's `.fc-add-line`, which is a fixed 40 px, so "N tags added" (created plus reused) needs no new space. When `items_tagged` is above 0 the engine calls `library.tagsChanged()` and the side pane patches its list. Checked in a private built copy, fresh engine, CPU 4x, 400 ms, 50 kB/s: a 200-entry BibTeX dropped with the box ticked, line "kw200.bib: Imported 200 as bibtex, 49 tags added.", the tag list went 0 to 49 rows in the same `ul` node, layout shift 0 without and 0 with input. Seen but not in this slice: the item list behind the dialog still read 0 items in the status bar when the tag list had filled, and a "The engine is back." toast showed under the throttle. +## src/engine/itemlist.ts {#src-itemlist-large-insert} + +New in v0.10.0 (2026-11-27). Cause of the empty list after a 200-item drop: `insertNow` sent one position request per id and then one row request per id, about 400 requests behind the browser's six connections per host; under 400 ms and 50 kB/s that takes tens of seconds, so the list and the count stayed at 0 and the health check starved (the "engine is back" toast). Now an insert of more than `INSERT_MAX` (12) new ids, or into an empty list, calls `reload()` once, which reads the first page in place. Checked in a private built copy, CPU 4x, 400 ms, 50 kB/s, fresh engine: into an empty library the status bar read 200 items 3.2 s after the drop, 0 position and 3 rows requests, 55 pool rows all showing titles, layout shift 0 with and without input; into 2,000 items it read 2,200 items in 3.9 s with the same request counts, pool 55 and shift 0. + ## src/ui/titles.ts, src/engine/titles.ts, src/io/titles.ts, src/styles/titles.css {#src-titles} New in v0.10.0 (2026-11-27). `ViewId` has no `titles` and the nav buttons are built in `connections.ts`, neither owned by this slice, so `mountTitles` inserts its own `.fc-nav-item[data-view="titles"]` after Trash once at mount (the shared click handler in `connections.ts` sets `panes.dataset.view` from it) and casts `'titles'` to `ViewId`; `titles.css` holds the matching `.fc-panes[data-view="titles"]` show rule. The count uses `.fc-nav-count` with `is-on` (visibility), so the nav keeps its width at zero. `toast()` has no action argument, so the "Give them titles" button is inserted into the toast found by its key. Rows are a fixed 112 px (known line, field row, 28 px strip); the five suggestion buttons exist from the start and are only unhidden, and Look it up is pinned to the strip end with `margin-left: auto` so arriving suggestions do not move it (that move was the one 0.00092 shift without input before the fix). Checked in a private built copy under CPU 4x, 400 ms, 50 kB/s, fresh engine: import of 4 entries (3 untitled) gave one toast "3 imported entries need a title", count 3; rows 112 px each; pick then Enter, empty Enter refused with "Type a title or pick a suggestion first." and 2 rows kept, type then Enter twice; count 3, 2, then hidden; a MutationObserver on the list saw 0 added and only the 3 saved rows removed, one per save; layout shift 0 without input, 0.0247 and 0.0165 with input (rows below a saved row move up). From 1a00d744e8c0cd85431292eeba93a07395500a70 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 15:22:39 -0500 Subject: [PATCH 27/27] chore(release): 0.10.0 Moves every version site to 0.10.0 and adds the changelog section. --- CHANGELOG.md | 24 ++++++++++++++++++++++++ backend/HASHOUT_LOG.md | 2 +- backend/app/__init__.py | 2 +- frontend/HASHOUT_LOG.md | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- frontend/src/version.ts | 2 +- native/formcite-style/Cargo.lock | 2 +- native/formcite-style/Cargo.toml | 2 +- native/formcite-style/pyproject.toml | 2 +- setup/HASHOUT_LOG.md | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/HASHOUT_LOG.md | 2 +- src-tauri/tauri.conf.json | 2 +- 15 files changed, 39 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e74492..e4f41f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 0.10.0 + +### New +- Keywords can become tags. Tick "Turn keywords into tags" in the Add dialog's Import tab, or pass `--keywords-as-tags` to `./formcite cli import`. It is off unless you ask. The keywords also stay on the item as text, so an export is unchanged. +- For a library you already imported: `./formcite cli tags from-keywords`, with `--dry-run` to see the tags it would make first. +- "Needs a title": an imported entry with no title is no longer left blank and unnoticed. After an import a notice says how many need a title, and a new view lists them. For each you can type a title or pick one of up to five suggestions made from what the entry already holds (its journal and year, the first author, an attached file's name, the start of its abstract). "Look it up" asks the lookup service only when you press it, for entries with a DOI or ISBN. +- The same from the command line: `./formcite cli titles list`, `titles suggest ID` and `titles set ID "..."`. + +### Fixed +- After a large import the list could stay empty and read "0 items" for many seconds on a slow connection. It asked the engine about every new entry one by one; more than twelve new entries, or an import into an empty library, now read the list once. +- A new tag typed in the item pane appears in the tag list at once, where it used to arrive late and push the rows under it down. + +### Changed +- The tag list shows twelve rows and scrolls inside its own box. +- Lists move only the rows that are out of place when they update. + +### Known issues +- The loss of keyboard focus after a tag rename, reported in 0.9.0, could not be reproduced in seventeen tries and its cause is still unknown. Two guards were added; it is not claimed fixed. +- A suggested title is a starting point, not a real title, when an entry holds only an author and a year. An entry with nothing at all gets no suggestions. +- "Look it up" was not run against a live service in this release, and a BibTeX `eprint` is not yet read as an arXiv id. +- An entry skipped as a duplicate on import is not tagged; run `tags from-keywords` for those. +- "Open in FormPDF" still opens the system viewer. +- The desktop app has not been built yet; the window runs in a browser against the engine. + ## 0.9.0 A small release that closes what the library window had left open. diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 637cdcb..5f5de2e 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for this side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.9.0 +Current build version: v0.10.0 Last updated: 2026-11-27 (US Eastern) · the lean rows route for the window's list and opening an attachment --- diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 3e2f46a..61fb31c 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.9.0" +__version__ = "0.10.0" diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 66a57c6..95dc629 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for this side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.9.0 +Current build version: v0.10.0 Last updated: 2026-11-26 (US Eastern) · window skeleton: shell, engine store, window key, health status --- diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 84de156..4325ce7 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formcite", - "version": "0.9.0", + "version": "0.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcite", - "version": "0.9.0", + "version": "0.10.0", "license": "GPL-3.0-only", "devDependencies": { "typescript": "7.0.2", diff --git a/frontend/package.json b/frontend/package.json index 83ebb09..7a31b97 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formcite", "private": true, - "version": "0.9.0", + "version": "0.10.0", "description": "FormCite: a local-first personal research library from the Form family", "license": "GPL-3.0-only", "type": "module", diff --git a/frontend/src/version.ts b/frontend/src/version.ts index b336f57..699451e 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.9.0'; +export const VERSION = '0.10.0'; diff --git a/native/formcite-style/Cargo.lock b/native/formcite-style/Cargo.lock index dcce086..940c831 100644 --- a/native/formcite-style/Cargo.lock +++ b/native/formcite-style/Cargo.lock @@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "formcite-style" -version = "0.9.0" +version = "0.10.0" dependencies = [ "hayagriva", "pyo3", diff --git a/native/formcite-style/Cargo.toml b/native/formcite-style/Cargo.toml index efe4c0c..cb603be 100644 --- a/native/formcite-style/Cargo.toml +++ b/native/formcite-style/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcite-style" -version = "0.9.0" +version = "0.10.0" edition = "2024" rust-version = "1.95" license = "Apache-2.0" diff --git a/native/formcite-style/pyproject.toml b/native/formcite-style/pyproject.toml index 6f91f9a..654e5da 100644 --- a/native/formcite-style/pyproject.toml +++ b/native/formcite-style/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "formcite-style" -version = "0.9.0" +version = "0.10.0" description = "FormCite citation style engine for the FormCite engine service" license = { text = "Apache-2.0" } requires-python = ">=3.10" diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 21eccc9..b75c8df 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, and removed code for the root launcher scripts and the `setup/` suite. The scripts stay comment-free; everything they would have said lives here, indexed. Read this first, then edit the scripts surgically. -Current build version: v0.9.0 +Current build version: v0.10.0 Last updated: 2026-11-27 · initial port of the launcher and setup suite --- diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 65d760c..efe9c0c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -918,7 +918,7 @@ dependencies = [ [[package]] name = "formcite" -version = "0.9.0" +version = "0.10.0" dependencies = [ "fontdb", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 041ff50..ad1f56c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcite" -version = "0.9.0" +version = "0.10.0" description = "FormCite desktop shell" authors = ["NodeAgentc, Inc."] license = "GPL-3.0-only" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index 5753ddd..fdc9b4e 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the desktop shell side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.9.0 +Current build version: v0.10.0 Last updated: 2026-11-26 (US Eastern) · Tauri 2 shell ported from FormTxt, renamed, launch code added --- diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 2aa9151..a37a1b0 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormCite", - "version": "0.9.0", + "version": "0.10.0", "identifier": "ai.nodemode.formcite", "build": { "devUrl": "http://localhost:5330",