From ab4ab2e8800d5b844c4f93af1a3c1cf90e5b05b4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:39:07 -0500 Subject: [PATCH 01/36] feat(store): record every library write in a changes table (0.16.0) Migration 0003 adds a changes table filled by SQLite triggers on items, item_tags, tags, collections, collection_items, notes, attachments, relations and saved searches, so a write from the engine, ./formcite cli, the stdio MCP server, an import or a direct sqlite3 write is recorded the same way, with a monotonic sequence. db.tx() stamps the writing request's origin into the one-row change_origin table inside the transaction and clears it before COMMIT, so no other connection ever sees it. The table keeps the last 5000 changes. --- backend/app/store/changes.py | 24 +++++ backend/app/store/db.py | 16 +++ backend/app/store/migrations/0003_changes.sql | 99 +++++++++++++++++++ 3 files changed, 139 insertions(+) create mode 100644 backend/app/store/changes.py create mode 100644 backend/app/store/migrations/0003_changes.sql diff --git a/backend/app/store/changes.py b/backend/app/store/changes.py new file mode 100644 index 0000000..fa2e8fe --- /dev/null +++ b/backend/app/store/changes.py @@ -0,0 +1,24 @@ +import sqlite3 + +BATCH = 1000 + + +def bounds(conn: sqlite3.Connection) -> tuple[int, int]: + latest = conn.execute("SELECT COALESCE(MAX(seq), 0) FROM sqlite_sequence WHERE name = 'changes'").fetchone()[0] + oldest = conn.execute("SELECT MIN(seq) FROM changes").fetchone()[0] + return (latest + 1 if oldest is None else oldest), latest + + +def behind(conn: sqlite3.Connection, since: int) -> bool: + oldest, latest = bounds(conn) + return since > latest or since < oldest - 1 + + +def after(conn: sqlite3.Connection, since: int, limit: int = BATCH) -> list[tuple]: + return conn.execute( + "SELECT seq, kind, item_id, ref_id, origin FROM changes WHERE seq > ? ORDER BY seq LIMIT ?", (since, limit) + ).fetchall() + + +def version(conn: sqlite3.Connection) -> int: + return conn.execute("PRAGMA data_version").fetchone()[0] diff --git a/backend/app/store/db.py b/backend/app/store/db.py index b055d8e..482acf8 100644 --- a/backend/app/store/db.py +++ b/backend/app/store/db.py @@ -1,4 +1,5 @@ import base64 +import contextvars import re import secrets import sqlite3 @@ -80,14 +81,29 @@ def tx(conn: sqlite3.Connection) -> Iterator[sqlite3.Connection]: conn.execute(f"RELEASE {name}") return conn.execute("BEGIN IMMEDIATE") + origin = ORIGIN.get() + stamped = origin is not None and _stamp(conn, origin) try: yield conn + if stamped: + _stamp(conn, None) except BaseException: conn.execute("ROLLBACK") raise conn.execute("COMMIT") +ORIGIN: contextvars.ContextVar[str | None] = contextvars.ContextVar("formcite_change_origin", default=None) + + +def _stamp(conn: sqlite3.Connection, origin: str | None) -> bool: + try: + conn.execute("UPDATE change_origin SET origin = ? WHERE id = 1", (origin,)) + except sqlite3.OperationalError: + return False + return True + + def rows(cursor: sqlite3.Cursor) -> list[dict]: return [dict(r) for r in cursor.fetchall()] diff --git a/backend/app/store/migrations/0003_changes.sql b/backend/app/store/migrations/0003_changes.sql new file mode 100644 index 0000000..9289178 --- /dev/null +++ b/backend/app/store/migrations/0003_changes.sql @@ -0,0 +1,99 @@ +CREATE TABLE changes( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + item_id TEXT, + ref_id TEXT, + origin TEXT +); + +CREATE TABLE change_origin( + id INTEGER PRIMARY KEY CHECK(id = 1), + origin TEXT +); +INSERT INTO change_origin(id, origin) VALUES (1, NULL); + +CREATE TRIGGER changes_prune AFTER INSERT ON changes WHEN NEW.seq % 500 = 0 BEGIN + DELETE FROM changes WHERE seq <= NEW.seq - 5000; +END; + +CREATE TRIGGER changes_item_ins AFTER INSERT ON items BEGIN + INSERT INTO changes(kind, item_id, origin) VALUES ('item.add', NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_item_upd AFTER UPDATE ON items BEGIN + INSERT INTO changes(kind, item_id, origin) VALUES ( + CASE + WHEN OLD.trashed_at IS NULL AND NEW.trashed_at IS NOT NULL THEN 'item.trash' + WHEN OLD.trashed_at IS NOT NULL AND NEW.trashed_at IS NULL THEN 'item.restore' + ELSE 'item.edit' + END, + NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_item_del AFTER DELETE ON items BEGIN + INSERT INTO changes(kind, item_id, origin) VALUES ('item.delete', OLD.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; + +CREATE TRIGGER changes_tagged_ins AFTER INSERT ON item_tags BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('tag.add', NEW.item_id, NEW.tag_id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_tagged_del AFTER DELETE ON item_tags BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('tag.remove', OLD.item_id, OLD.tag_id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_tag_upd AFTER UPDATE ON tags BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('tag.edit', NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_tag_del AFTER DELETE ON tags BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('tag.delete', OLD.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; + +CREATE TRIGGER changes_coll_ins AFTER INSERT ON collections BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('collection.add', NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_coll_upd AFTER UPDATE ON collections BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('collection.edit', NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_coll_del AFTER DELETE ON collections BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('collection.delete', OLD.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_filed_ins AFTER INSERT ON collection_items BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('collection.file', NEW.item_id, NEW.collection_id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_filed_del AFTER DELETE ON collection_items BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('collection.unfile', OLD.item_id, OLD.collection_id, (SELECT origin FROM change_origin WHERE id = 1)); +END; + +CREATE TRIGGER changes_note_ins AFTER INSERT ON notes BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('note', NEW.item_id, NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_note_upd AFTER UPDATE ON notes BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('note', NEW.item_id, NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_note_del AFTER DELETE ON notes BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('note', OLD.item_id, OLD.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; + +CREATE TRIGGER changes_file_ins AFTER INSERT ON attachments BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('attachment', NEW.item_id, NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_file_upd AFTER UPDATE ON attachments BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('attachment', NEW.item_id, NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_file_del AFTER DELETE ON attachments BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('attachment', OLD.item_id, OLD.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; + +CREATE TRIGGER changes_rel_ins AFTER INSERT ON relations BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('relation', NEW.from_id, NEW.to_id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_rel_del AFTER DELETE ON relations BEGIN + INSERT INTO changes(kind, item_id, ref_id, origin) VALUES ('relation', OLD.from_id, OLD.to_id, (SELECT origin FROM change_origin WHERE id = 1)); +END; + +CREATE TRIGGER changes_search_ins AFTER INSERT ON saved_searches BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('search', NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_search_upd AFTER UPDATE ON saved_searches BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('search', NEW.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; +CREATE TRIGGER changes_search_del AFTER DELETE ON saved_searches BEGIN + INSERT INTO changes(kind, ref_id, origin) VALUES ('search', OLD.id, (SELECT origin FROM change_origin WHERE id = 1)); +END; From d902cd7eee1960b9fdda75a9d109ba227b731899 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:39:08 -0500 Subject: [PATCH 02/36] feat(engine): stream library changes to the window (0.16.0) GET /api/changes/stream is a server-sent event stream for the window key only. It opens with hello (library name, sequence, and whether the caller fell behind or the library switched), then sends each batch of new changes as one message with kind, item id, reference id and origin. Changes the window made itself are dropped from the batch and only advance the sequence, so they never echo back. A stream lives 30 seconds and the window reconnects from its last sequence, which keeps engine shutdown prompt. OriginStamp tags each engine request as window or agent for the change rows. --- backend/app/core/origin.py | 21 +++++++++ backend/app/main.py | 2 + backend/app/routers/changes.py | 75 +++++++++++++++++++++++++++++++++ backend/app/routers/registry.py | 1 + 4 files changed, 99 insertions(+) create mode 100644 backend/app/core/origin.py create mode 100644 backend/app/routers/changes.py diff --git a/backend/app/core/origin.py b/backend/app/core/origin.py new file mode 100644 index 0000000..e0c8ac8 --- /dev/null +++ b/backend/app/core/origin.py @@ -0,0 +1,21 @@ +from app.core import window_key +from app.store.db import ORIGIN + +WINDOW = "window" +AGENT = "agent" + + +class OriginStamp: + def __init__(self, app) -> None: + self.app = app + + async def __call__(self, scope, receive, send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + given = next((v.decode("latin-1") for k, v in scope.get("headers", []) if k.decode("latin-1").lower() == window_key.HEADER), None) + token = ORIGIN.set(WINDOW if window_key.valid(given) else AGENT) + try: + await self.app(scope, receive, send) + finally: + ORIGIN.reset(token) diff --git a/backend/app/main.py b/backend/app/main.py index 8a22022..cad6145 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -14,6 +14,7 @@ from app.core import config, look_store from app.core.local_guard import LocalGuard +from app.core.origin import OriginStamp from app.core.window_key import WindowKeyGuard from app.routers import registry @@ -48,6 +49,7 @@ async def lifespan(_: FastAPI): app = FastAPI(title=config.APP_TITLE, version=config.VERSION, lifespan=lifespan) app.add_middleware(CORSMiddleware, allow_origins=config.cors_origins(), allow_methods=["*"], allow_headers=["*"]) +app.add_middleware(OriginStamp) app.add_middleware(WindowKeyGuard) app.add_middleware(LocalGuard, origins=config.cors_origins()) registry.mount(app) diff --git a/backend/app/routers/changes.py b/backend/app/routers/changes.py new file mode 100644 index 0000000..5df92e9 --- /dev/null +++ b/backend/app/routers/changes.py @@ -0,0 +1,75 @@ +import asyncio +import json +import time + +from fastapi import APIRouter, Depends, Request +from fastapi.responses import StreamingResponse + +from app.core.origin import WINDOW +from app.routers.service import window_only +from app.store import changes, db, libraries + +GROUP = "changes" +router = APIRouter(prefix="/changes", tags=[GROUP], dependencies=[Depends(window_only)]) + +TICK_S = 0.25 +LIBRARY_CHECK_S = 2.0 +PING_S = 15.0 +LIFETIME_S = 30.0 + + +def _frame(message: dict) -> str: + return f"data: {json.dumps(message, separators=(',', ':'))}\n\n" + + +def _compact(found: list[tuple]) -> list[list]: + return [[seq, kind, item_id, ref_id, origin or ""] for seq, kind, item_id, ref_id, origin in found if origin != WINDOW] + + +async def _feed(request: Request, since: int | None, lib_name: str): + lib = libraries.current() + conn = db.open(lib.db_path) + try: + oldest, latest = changes.bounds(conn) + same = lib_name == lib.name and since is not None + stale = not same or changes.behind(conn, since) + cursor = latest if stale else since + yield _frame({"t": "hello", "lib": lib.name, "seq": cursor, "stale": stale and lib_name != "", "switched": bool(lib_name) and lib_name != lib.name}) + seen = -1 + started = pinged = checked = time.monotonic() + while not await request.is_disconnected(): + now = time.monotonic() + if now - started > LIFETIME_S: + return + if now - checked > LIBRARY_CHECK_S: + checked = now + if libraries.current().name != lib.name: + yield _frame({"t": "switch"}) + return + version = changes.version(conn) + if version != seen: + seen = version + found = changes.after(conn, cursor) + if len(found) >= changes.BATCH: + cursor = changes.bounds(conn)[1] + yield _frame({"t": "stale", "lib": lib.name, "seq": cursor}) + pinged = now + elif found: + cursor = found[-1][0] + yield _frame({"t": "changes", "lib": lib.name, "seq": cursor, "ch": _compact(found)}) + pinged = now + if now - pinged > PING_S: + pinged = now + yield ": ping\n\n" + await asyncio.sleep(TICK_S) + finally: + conn.close() + + +@router.get("/stream") +def stream(request: Request, since: int | None = None, lib: str = "") -> StreamingResponse: + return StreamingResponse( + _feed(request, since, lib), + media_type="text/event-stream", + headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}, + ) diff --git a/backend/app/routers/registry.py b/backend/app/routers/registry.py index 81c7141..e034e94 100644 --- a/backend/app/routers/registry.py +++ b/backend/app/routers/registry.py @@ -50,3 +50,4 @@ def mount(app: FastAPI) -> None: register("upload", __import__("app.routers.upload", fromlist=["router"]).router) register("titles", __import__("app.routers.titles", fromlist=["router"]).router) register("dock", __import__("app.routers.dock", fromlist=["mounted"]).mounted) +register("changes", __import__("app.routers.changes", fromlist=["router"]).router) From 8483519f2a94db39ee8445dc56654d5a2adabb6f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:11 -0500 Subject: [PATCH 03/36] fix(engine): the changes stream ends at once when the engine stops (0.16.0) uvicorn waits for open responses on Ctrl+C, so an open window kept ./formcite serve alive for up to the stream's 30 second life. The stream now also ends as soon as uvicorn's own exit flag is set, read from the SIGINT handler uvicorn installs; shutdown with the window open measured 0.28 s, down from 29.8 s. --- backend/app/routers/changes.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/changes.py b/backend/app/routers/changes.py index 5df92e9..fd00350 100644 --- a/backend/app/routers/changes.py +++ b/backend/app/routers/changes.py @@ -1,5 +1,6 @@ import asyncio import json +import signal import time from fastapi import APIRouter, Depends, Request @@ -22,6 +23,11 @@ def _frame(message: dict) -> str: return f"data: {json.dumps(message, separators=(',', ':'))}\n\n" +def _exiting() -> bool: + server = getattr(signal.getsignal(signal.SIGINT), "__self__", None) + return bool(getattr(server, "should_exit", False)) + + def _compact(found: list[tuple]) -> list[list]: return [[seq, kind, item_id, ref_id, origin or ""] for seq, kind, item_id, ref_id, origin in found if origin != WINDOW] @@ -39,7 +45,7 @@ async def _feed(request: Request, since: int | None, lib_name: str): started = pinged = checked = time.monotonic() while not await request.is_disconnected(): now = time.monotonic() - if now - started > LIFETIME_S: + if now - started > LIFETIME_S or _exiting(): return if now - checked > LIBRARY_CHECK_S: checked = now From f3e5ad8ee52dc2be6b9e26c958bd8facac9e3bb1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:29 -0500 Subject: [PATCH 04/36] feat(window): apply the engine's change feed in place (0.16.0) io/changes.ts reads /api/changes/stream with the window key header, the same way as every other window call. engine/live.ts keeps the last sequence and library, reconnects from them, and turns each batch into the Library notices the panes already patch from: items added, removed or restored, an item changed, collections changed, tags changed. Bursts settle for 120 ms (600 ms at most), so 30 adds and 30 tag writes in half a second arrive as a few notices, not 60. Filing in or out of the shown collection or tag, or out of Unfiled, adds or removes the rows in view; deleting the shown collection or tag returns to All items. Items an agent added are remembered for six seconds for the row highlight. --- frontend/src/engine/live.ts | 155 ++++++++++++++++++++++++++++++++++++ frontend/src/io/changes.ts | 33 ++++++++ 2 files changed, 188 insertions(+) create mode 100644 frontend/src/engine/live.ts create mode 100644 frontend/src/io/changes.ts diff --git a/frontend/src/engine/live.ts b/frontend/src/engine/live.ts new file mode 100644 index 0000000..c24ab43 --- /dev/null +++ b/frontend/src/engine/live.ts @@ -0,0 +1,155 @@ +import { ALL, type Library } from './library'; +import { readFeed, type Change, type FeedMessage } from '../io/changes'; + +const SETTLE_MS = 120; +const MAX_WAIT_MS = 600; +const RETRY_MS = [250, 1000, 2000, 5000, 10000]; +const EDITS_MAX = 40; +const MARK_MS = 6000; + +const marks = new Map(); + +export function agentAdded(id: string): boolean { + const until = marks.get(id); + if (until === undefined) return false; + if (until > Date.now()) return true; + marks.delete(id); + return false; +} + +export class LiveFeed { + private seq: number | null = null; + private lib = ''; + private pending: Change[] = []; + private settle: ReturnType | undefined; + private first = 0; + private stop = new AbortController(); + + constructor(private readonly library: Library) {} + + start(): void { + void this.run(); + } + + close(): void { + this.stop.abort(); + } + + private async run(): Promise { + let failures = 0; + while (!this.stop.signal.aborted) { + try { + await readFeed(this.seq, this.lib, (m) => this.take(m), this.stop.signal); + failures = 0; + } catch { + if (this.stop.signal.aborted) return; + await new Promise((r) => setTimeout(r, RETRY_MS[Math.min(failures, RETRY_MS.length - 1)])); + failures++; + } + } + } + + private take(m: FeedMessage): void { + if (m.t === 'switch') return; + if (m.t === 'hello') { + const known = this.lib !== ''; + this.lib = m.lib; + this.seq = m.seq; + if (known && m.switched) { this.drop(); this.library.librarySwitched(); } + else if (m.stale) { this.drop(); this.library.stale(); } + return; + } + this.seq = m.seq; + if (m.t === 'stale') { this.drop(); this.library.stale(); return; } + if (!m.ch.length) return; + this.pending.push(...m.ch); + const now = Date.now(); + if (!this.first) this.first = now; + clearTimeout(this.settle); + this.settle = setTimeout(() => this.flush(), now - this.first >= MAX_WAIT_MS ? 0 : SETTLE_MS); + } + + private drop(): void { + clearTimeout(this.settle); + this.pending = []; + this.first = 0; + } + + private flush(): void { + const batch = this.pending; + this.drop(); + const lib = this.library; + const scope = lib.scope; + const added = new Set(); + const removed = new Set(); + const restored = new Set(); + const edited = new Set(); + let collections = false; + let tags = false; + let lost = false; + const into = (on: boolean, id: string): void => { + if (on) { added.add(id); removed.delete(id); } else { removed.add(id); added.delete(id); } + }; + for (const [, kind, item, ref, origin] of batch) { + const id = item ?? ''; + switch (kind) { + case 'item.add': + into(true, id); + if (origin !== 'window') marks.set(id, Date.now() + MARK_MS); + break; + case 'item.trash': + case 'item.delete': + into(false, id); + restored.delete(id); + collections = tags = true; + break; + case 'item.restore': + restored.add(id); + removed.delete(id); + collections = tags = true; + break; + case 'tag.add': + case 'tag.remove': + tags = true; + edited.add(id); + if (scope.kind === 'tag' && scope.id === ref) into(kind === 'tag.add', id); + break; + case 'tag.edit': + tags = true; + break; + case 'tag.delete': + tags = true; + if (scope.kind === 'tag' && scope.id === ref) lost = true; + break; + case 'collection.add': + case 'collection.edit': + collections = true; + break; + case 'collection.delete': + collections = true; + if (scope.kind === 'collection' && scope.id === ref) lost = true; + break; + case 'collection.file': + case 'collection.unfile': + collections = true; + if (scope.kind === 'collection' && scope.id === ref) into(kind === 'collection.file', id); + else if (scope.kind === 'unfiled') into(kind === 'collection.unfile', id); + break; + default: + if (id) edited.add(id); + } + } + if (lost) { + lib.setScope(ALL); + added.clear(); removed.clear(); restored.clear(); + } + for (const id of [...added, ...removed, ...restored]) edited.delete(id); + if (removed.size) lib.itemsRemoved([...removed]); + if (restored.size) lib.itemsRestored([...restored]); + if (added.size) lib.itemsAdded([...added]); + if (edited.size > EDITS_MAX) lib.stale(); + else for (const id of edited) lib.itemChanged(id); + if (collections) lib.collectionsChanged(); + if (tags) lib.tagsChanged(); + } +} diff --git a/frontend/src/io/changes.ts b/frontend/src/io/changes.ts new file mode 100644 index 0000000..fcb8d9b --- /dev/null +++ b/frontend/src/io/changes.ts @@ -0,0 +1,33 @@ +import { keyHeaders } from './window-key'; + +export type Change = [seq: number, kind: string, item: string | null, ref: string | null, origin: string]; + +export type FeedMessage = + | { t: 'hello'; lib: string; seq: number; stale: boolean; switched: boolean } + | { t: 'changes'; lib: string; seq: number; ch: Change[] } + | { t: 'stale'; lib: string; seq: number } + | { t: 'switch' }; + +export async function readFeed(since: number | null, lib: string, on: (m: FeedMessage) => void, signal: AbortSignal): Promise { + const p = new URLSearchParams(); + if (since !== null) p.set('since', String(since)); + if (lib) p.set('lib', lib); + const res = await fetch(`/api/changes/stream?${p}`, { headers: keyHeaders(), signal, cache: 'no-store' }); + if (!res.ok || !res.body) throw new Error(`changes feed answered ${res.status}`); + const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); + let buf = ''; + for (;;) { + const { value, done } = await reader.read(); + if (done) return; + buf += value; + let cut = buf.indexOf('\n\n'); + while (cut >= 0) { + const frame = buf.slice(0, cut); + buf = buf.slice(cut + 2); + cut = buf.indexOf('\n\n'); + const data = frame.split('\n').filter((l) => l.startsWith('data: ')).map((l) => l.slice(6)).join('\n'); + if (!data) continue; + try { on(JSON.parse(data) as FeedMessage); } catch { void 0; } + } + } +} From ca49e760ac89f0e6dbb138c1f110fa1f7302f67c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:29 -0500 Subject: [PATCH 05/36] feat(window): a stale notice and an in-place refresh for the item list (0.16.0) Library.stale() asks every pane to re-read once, keeping scope, search, sort and selection, for a window that fell more than 5000 changes behind or a burst of more than 40 edits. ItemListModel.refresh() reloads the page around the rows in view rather than from the top, and the insert and remove fallbacks use it, so a burst over the twelve-row insert limit no longer blanks the rows of a scrolled list while page 0 loads. A short agent highlight fades on new rows: a 2 px accent edge and the accent wash as an inset shadow, so the row box never changes; it steps off with reduced motion. --- frontend/src/engine/itemlist.ts | 17 ++++++++++++----- frontend/src/engine/library.ts | 8 ++++++++ frontend/src/styles/itemlist.css | 6 ++++++ 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 22f1831..57f0631 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -26,13 +26,19 @@ export class ItemListModel { indexOf(id: string): number { return this.index.get(id) ?? -1; } get loaded(): boolean { return this.ready; } - reload(): void { + reload(from = 0): void { this.generation++; this.settled = false; for (const c of this.pending.values()) c.abort(); this.pending.clear(); this.spans.clear(); - void this.load(0, PAGE, true); + void this.load(Math.max(0, from), PAGE, true); + } + + private near = 0; + + refresh(): void { + if (this.ready) this.reload(this.near); } private settled = false; @@ -49,6 +55,7 @@ export class ItemListModel { } ensure(first: number, last: number): void { + this.near = Math.max(0, Math.floor(first)); if (!this.ready || !this.settled) return; const lo = Math.max(0, first); const hi = Math.min(last, this.total - 1); @@ -130,7 +137,7 @@ export class ItemListModel { private async removeNow(ids: string[]): Promise { if (!this.ready) return; - if (!this.settled) { this.reload(); return; } + if (!this.settled) { this.refresh(); return; } const gen = this.generation; const gone = new Set(); const unseen: string[] = []; @@ -163,11 +170,11 @@ export class ItemListModel { private async insertNow(ids: string[]): Promise { if (!this.ready) return; - if (!this.settled) { this.reload(); return; } + if (!this.settled) { this.refresh(); return; } 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; } + if (fresh.length > INSERT_MAX || this.total === 0) { this.refresh(); 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)); diff --git a/frontend/src/engine/library.ts b/frontend/src/engine/library.ts index b9724ec..3752ab3 100644 --- a/frontend/src/engine/library.ts +++ b/frontend/src/engine/library.ts @@ -23,6 +23,7 @@ export interface LibraryEvents { 'collections:changed': null; 'tags:changed': null; 'library:switched': null; + 'library:stale': null; 'counts': Counts; } @@ -88,6 +89,13 @@ export class Library { collectionsChanged(): void { this.events.emit('collections:changed', null); } tagsChanged(): void { this.events.emit('tags:changed', null); } + stale(): void { + this.events.emit('library:stale', null); + this.collectionsChanged(); + this.tagsChanged(); + if (this._selected) this.itemChanged(this._selected); + } + librarySwitched(): void { this.select(null); this.setQuery(''); diff --git a/frontend/src/styles/itemlist.css b/frontend/src/styles/itemlist.css index 1a987e8..ce8df03 100644 --- a/frontend/src/styles/itemlist.css +++ b/frontend/src/styles/itemlist.css @@ -81,6 +81,12 @@ .fc-il-row:hover { background: var(--hover); } .fc-il-row.is-selected { background: var(--accent-wash); } .fc-il-scroll:focus-visible .fc-il-row.is-selected { box-shadow: inset 2px 0 0 var(--accent); } +.fc-il-row.is-agent { animation: fc-il-agent 6s ease-out both; } +@keyframes fc-il-agent { + 0%, 40% { box-shadow: inset 2px 0 0 var(--accent), inset 0 0 0 100vmax var(--accent-wash); } + 100% { box-shadow: inset 2px 0 0 transparent, inset 0 0 0 100vmax transparent; } +} +@media (prefers-reduced-motion: reduce) { .fc-il-row.is-agent { animation-timing-function: steps(1, end); } } .fc-il-cell { min-width: 0; padding: 0 var(--space-2); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; line-height: var(--il-row-h); } .fc-il-row .fc-il-c-creator, .fc-il-row .fc-il-c-type, .fc-il-row .fc-il-c-added { color: var(--text-secondary); } .fc-il-row .fc-il-c-creator, .fc-il-row .fc-il-c-type, .fc-il-row .fc-il-c-added { color: var(--text-muted); } From f8acb3acf687481f9d989833acab1f48109627e1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:37 -0500 Subject: [PATCH 06/36] feat(window): a bridge that lets an agent run the open window's commands (0.16.0) The window publishes the commands it offers, each with typed arguments, to PUT /api/window/commands and long-polls GET /api/window/commands/next for runs; it posts each outcome to /api/window/commands/runs/{id}. Every route needs the window key. The engine keeps the catalogue and a short queue in memory, checks arguments against the published types, and never offers Connections, the network switches, the token store, edit and window.close to an agent, whatever the window publishes. --- backend/app/routers/registry.py | 1 + backend/app/routers/window_bridge.py | 50 ++++++++ backend/app/services/window_bridge.py | 170 ++++++++++++++++++++++++++ 3 files changed, 221 insertions(+) create mode 100644 backend/app/routers/window_bridge.py create mode 100644 backend/app/services/window_bridge.py diff --git a/backend/app/routers/registry.py b/backend/app/routers/registry.py index e034e94..cfe63c4 100644 --- a/backend/app/routers/registry.py +++ b/backend/app/routers/registry.py @@ -51,3 +51,4 @@ def mount(app: FastAPI) -> None: register("titles", __import__("app.routers.titles", fromlist=["router"]).router) register("dock", __import__("app.routers.dock", fromlist=["mounted"]).mounted) register("changes", __import__("app.routers.changes", fromlist=["router"]).router) +register("window_bridge", __import__("app.routers.window_bridge", fromlist=["router"]).router) diff --git a/backend/app/routers/window_bridge.py b/backend/app/routers/window_bridge.py new file mode 100644 index 0000000..8d78577 --- /dev/null +++ b/backend/app/routers/window_bridge.py @@ -0,0 +1,50 @@ +from typing import Any, Callable + +from fastapi import APIRouter, Depends, HTTPException, Query +from pydantic import BaseModel, Field + +from app.routers.service import window_only +from app.services import window_bridge +from app.store.errors import Invalid, NotFound + +GROUP = "window_bridge" +router = APIRouter(prefix="/window/commands", tags=[GROUP], dependencies=[Depends(window_only)]) + + +def _run(fn: Callable, *args, **kwargs) -> Any: + try: + return fn(*args, **kwargs) + except NotFound as exc: + raise HTTPException(404, f"not found: {exc}") from exc + except Invalid as exc: + raise HTTPException(422, str(exc)) from exc + + +class Catalog(BaseModel): + commands: list[dict] = Field(default_factory=list, max_length=400) + + +class Outcome(BaseModel): + ok: bool + result: dict | None = None + error: str | None = Field(None, max_length=2000) + + +@router.put("") +def publish(body: Catalog) -> dict: + return window_bridge.publish(body.commands) + + +@router.get("") +def listing() -> dict: + return window_bridge.catalog() + + +@router.get("/next") +def next_run(wait: float = Query(20.0, ge=0, le=window_bridge.MAX_WAIT)) -> dict: + return {"run": window_bridge.next_run(wait)} + + +@router.post("/runs/{run_id}") +def finish(run_id: str, body: Outcome) -> dict: + return _run(window_bridge.finish, run_id, body.ok, body.result, body.error) diff --git a/backend/app/services/window_bridge.py b/backend/app/services/window_bridge.py new file mode 100644 index 0000000..bdb9be4 --- /dev/null +++ b/backend/app/services/window_bridge.py @@ -0,0 +1,170 @@ +import secrets +import threading +import time +from collections import deque + +from app.store.errors import Invalid, NotFound + +SEEN_SECONDS = 45.0 +RUN_SECONDS = 60.0 +KEEP_RUNS = 200 +MAX_WAIT = 25.0 +REFUSED_PREFIXES = ("connections.", "engine.", "edit.", "network.", "service.", "window.close") +ARG_TYPES = {"string": str, "number": (int, float), "integer": int, "boolean": bool} +NO_WINDOW = ("The FormCite window is not open, so window commands cannot run. " + "Ask the person to open FormCite, or use the headless tools, which change the library without a window.") + +_cond = threading.Condition() +_state: dict = {"commands": {}, "seen": 0.0, "published": 0.0} +_queue: deque[str] = deque() +_runs: dict[str, dict] = {} + + +def refused(command_id: str) -> bool: + return any(command_id == p or command_id.startswith(p) for p in REFUSED_PREFIXES) + + +def _clean_spec(raw: dict) -> dict | None: + cid = str(raw.get("id") or "").strip() + if not cid or len(cid) > 80 or refused(cid): + return None + args = raw.get("args") if isinstance(raw.get("args"), dict) else {} + clean_args = {} + for name, spec in list(args.items())[:12]: + if not isinstance(spec, dict) or spec.get("type") not in ARG_TYPES: + continue + one = {"type": spec["type"], "required": bool(spec.get("required"))} + if isinstance(spec.get("enum"), list): + one["enum"] = [str(v) for v in spec["enum"][:40]] + if spec.get("description"): + one["description"] = str(spec["description"])[:200] + clean_args[str(name)[:40]] = one + return {"id": cid, "title": str(raw.get("title") or cid)[:120], "args": clean_args, + "write": bool(raw.get("write")), "group": str(raw.get("group") or cid.split(".", 1)[0])[:40]} + + +def publish(commands: list) -> dict: + found = {} + for raw in commands[:400]: + spec = _clean_spec(raw) if isinstance(raw, dict) else None + if spec: + found[spec["id"]] = spec + with _cond: + _state["commands"] = found + _state["published"] = _state["seen"] = time.time() + return {"commands": len(found)} + + +def window_open() -> bool: + return time.time() - _state["seen"] < SEEN_SECONDS + + +def catalog(group: str | None = None) -> dict: + commands = sorted(_state["commands"].values(), key=lambda c: c["id"]) + if group: + commands = [c for c in commands if c["group"] == group] + return {"window_open": window_open(), "commands": commands} + + +def _check_args(spec: dict, args: dict) -> dict: + out = {} + for key in args: + if key not in spec["args"]: + raise Invalid(f"{spec['id']} takes no argument {key}; it takes {', '.join(spec['args']) or 'none'}") + for name, want in spec["args"].items(): + value = args.get(name) + if value is None or value == "": + if want["required"]: + raise Invalid(f"{spec['id']} needs the argument {name}") + continue + kind = ARG_TYPES[want["type"]] + if not isinstance(value, kind) or (want["type"] != "boolean" and isinstance(value, bool)): + raise Invalid(f"argument {name} of {spec['id']} must be a {want['type']}") + if "enum" in want and str(value) not in want["enum"]: + raise Invalid(f"argument {name} of {spec['id']} must be one of {', '.join(want['enum'])}") + out[name] = value + return out + + +def _prune(now: float) -> None: + for run in _runs.values(): + if run["state"] == "queued" and now - run["at"] > RUN_SECONDS: + run["state"], run["error"] = "expired", "The window did not pick the command up in time." + if len(_runs) > KEEP_RUNS: + for rid in sorted(_runs, key=lambda r: _runs[r]["at"])[: len(_runs) - KEEP_RUNS]: + if _runs[rid]["state"] not in ("queued", "sent"): + _runs.pop(rid, None) + + +def _enqueue(command_id: str, args: dict, by: str) -> dict: + now = time.time() + run = {"id": "run_" + secrets.token_hex(5), "command": command_id, "args": args, "by": by, + "state": "queued", "at": now, "result": None, "error": None} + with _cond: + _prune(now) + _runs[run["id"]] = run + _queue.append(run["id"]) + _cond.notify_all() + return run + + +def submit(command_id: str, args: dict | None = None, by: str = "agent") -> dict: + if refused(command_id): + raise Invalid(f"{command_id} is kept for the person in the window and is not offered to agents") + if not window_open(): + raise Invalid(NO_WINDOW) + spec = _state["commands"].get(command_id) + if spec is None: + raise NotFound(f"window command {command_id}; window_commands lists the ones the open window offers") + return _enqueue(command_id, _check_args(spec, args or {}), by) + + +def notify(command_id: str, args: dict | None = None) -> dict | None: + if not window_open() or command_id not in _state["commands"]: + return None + return _enqueue(command_id, args or {}, "engine") + + +def next_run(wait: float) -> dict | None: + deadline = time.time() + max(0.0, min(wait, MAX_WAIT)) + with _cond: + _state["seen"] = time.time() + while True: + while _queue: + run = _runs.get(_queue.popleft()) + if run and run["state"] == "queued": + run["state"] = "sent" + return {"id": run["id"], "command": run["command"], "args": run["args"]} + left = deadline - time.time() + if left <= 0: + return None + _cond.wait(left) + _state["seen"] = time.time() + + +def finish(run_id: str, ok: bool, result: dict | None, error: str | None) -> dict: + with _cond: + run = _runs.get(run_id) + if run is None: + raise NotFound(f"run {run_id}") + run["state"] = "done" if ok else "failed" + run["result"] = result if isinstance(result, dict) else None + run["error"] = None if ok else (str(error or "The window could not run the command."))[:400] + run["done_at"] = time.time() + _cond.notify_all() + return {"id": run_id, "state": run["state"]} + + +def wait(run_id: str, seconds: float) -> dict: + deadline = time.time() + max(0.0, min(seconds, MAX_WAIT)) + with _cond: + run = _runs.get(run_id) + if run is None: + raise NotFound(f"run {run_id}") + while run["state"] in ("queued", "sent"): + left = deadline - time.time() + if left <= 0: + break + _cond.wait(left) + _prune(time.time()) + return dict(run) From 66040aff05f7ef98af8ea15db63eaaf0f1f8f1b7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:37 -0500 Subject: [PATCH 07/36] feat(mcp): headless tools for everything else a person does with the library (0.16.0) Edit any field of an item, trash, restore, delete forever and empty the Trash, notes, untag, rename and delete tags, attachments and the PDF on disk, fetch an arXiv PDF, add a PDF by the identifier in it, relations, saved and rule searches, duplicates and merging, export, import of a file, import batches and undo, keywords to tags, libraries, items that need a title, the network switches read-only, and window_commands, window_command_run and window_command_result for the open window. Answers are one line per row with ids; permanent deletes carry destructive and need confirm: true. Collection tools stay with the collection slice. --- backend/app/mcp/tools_parity.py | 433 ++++++++++++++++++++++++++++++++ 1 file changed, 433 insertions(+) create mode 100644 backend/app/mcp/tools_parity.py diff --git a/backend/app/mcp/tools_parity.py b/backend/app/mcp/tools_parity.py new file mode 100644 index 0000000..b11d5dc --- /dev/null +++ b/backend/app/mcp/tools_parity.py @@ -0,0 +1,433 @@ +from app.net import overview +from app.services import duplicates, fulltext, identify, library, titles, transfer, window_bridge +from app.store.errors import Invalid + +ID = {"type": "string", "description": "The item id."} +IDS = {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 200, "description": "Item ids."} +CONFIRM = {"type": "boolean", "description": "Must be true: the person asked for this, and it cannot be undone."} +LIMIT = {"type": "integer", "minimum": 1, "maximum": 200, "description": "Most rows to answer (default 20)."} +EXPORT_CAP = 200_000 + + +def _schema(properties: dict, required: tuple[str, ...] = ()) -> dict: + out: dict = {"type": "object", "properties": properties, "additionalProperties": False} + if required: + out["required"] = list(required) + return out + + +def _brief(item: dict) -> dict: + return {k: item.get(k) for k in ("id", "title", "first_creator", "year", "type") if item.get(k) not in (None, "")} + + +def _line(item: dict) -> str: + return f"{item.get('id')} · {item.get('first_creator') or 'no author'} ({item.get('year') or 'n.d.'}) {item.get('title') or 'untitled'}" + + +def _confirmed(args: dict, what: str) -> None: + if args.get("confirm") is not True: + raise Invalid(f"{what} cannot be undone; ask the person, then call again with confirm: true") + + +def _each(ids: list[str], fn) -> tuple[list[str], list[dict]]: + done, failed = [], [] + for item_id in ids: + try: + fn(item_id) + done.append(item_id) + except Exception as exc: + failed.append({"id": item_id, "error": str(exc) or type(exc).__name__}) + return done, failed + + +def _tally(verb: str, done: list[str], failed: list[dict]) -> tuple[str, dict]: + said = f"{verb} {len(done)} item{'s' if len(done) != 1 else ''}." + if failed: + said += f" {len(failed)} failed: " + "; ".join(f"{f['id']}: {f['error']}" for f in failed[:5]) + return said, {"done": done, "failed": failed} + + +def _edit_item(args: dict) -> tuple[str, dict]: + if not args.get("fields") and not args.get("csl"): + raise Invalid("give fields (such as title, author, year, container, doi, url, type, abstract) or a full csl record") + item = library.item_edit(args["id"], args.get("fields"), args.get("csl")) + return "Edited " + _line(item), _brief(item) + + +def _trash_items(args: dict) -> tuple[str, dict]: + return _tally("Moved to Trash", *_each(args["ids"], library.item_trash)) + + +def _restore_items(args: dict) -> tuple[str, dict]: + return _tally("Restored", *_each(args["ids"], library.item_restore)) + + +def _delete_forever(args: dict) -> tuple[str, dict]: + _confirmed(args, "Deleting items forever") + return _tally("Deleted forever", *_each(args["ids"], library.item_purge)) + + +def _empty_trash(args: dict) -> tuple[str, dict]: + _confirmed(args, "Emptying the Trash") + out = library.trash_empty() + gone = [entry.get("id") for entry in out.get("purged") or []] + return f"Emptied the Trash: {len(gone)} items deleted forever.", {"purged": gone} + + +def _list_trash(args: dict) -> tuple[str, dict]: + out = library.item_list(trashed=True, limit=args.get("limit") or 20) + found = out.get("items") or [] + return "\n".join([f"{len(found)} of {out.get('total', len(found))} items in the Trash."] + [_line(i) for i in found]), \ + {"total": out.get("total"), "items": [_brief(i) for i in found]} + + +def _notes(args: dict) -> tuple[str, dict]: + found = library.note_list(args["id"]) + lines = [f"{n['id']} · {(n.get('body') or '')[:120]}" for n in found] + return "\n".join([f"{len(found)} notes."] + lines), {"notes": found} + + +def _add_note(args: dict) -> tuple[str, dict]: + note = library.note_add(args["id"], args["body"]) + return f"Added note {note['id']} to {args['id']}.", {"id": note["id"], "item_id": args["id"]} + + +def _edit_note(args: dict) -> tuple[str, dict]: + note = library.note_edit(args["note_id"], args["body"]) + return f"Edited note {note['id']}.", {"id": note["id"]} + + +def _delete_note(args: dict) -> tuple[str, dict]: + library.note_delete(args["note_id"]) + return f"Deleted note {args['note_id']}.", {"id": args["note_id"], "deleted": True} + + +def _untag(args: dict) -> tuple[str, dict]: + out = library.tag_remove(args["id"], args["tags"]) + return f"Took {', '.join(args['tags'])} off {args['id']}.", out + + +def _tag_id(text: str) -> str: + for tag in library.tag_list(): + if text in (tag["id"], tag["name"]): + return tag["id"] + raise Invalid(f"there is no tag {text}; list_tags names them") + + +def _rename_tag(args: dict) -> tuple[str, dict]: + out = library.tag_rename(_tag_id(args["tag"]), args["name"]) + return f"Renamed the tag to {out.get('name', args['name'])}.", {"id": out.get("id"), "name": out.get("name")} + + +def _delete_tag(args: dict) -> tuple[str, dict]: + tag_id = _tag_id(args["tag"]) + library.tag_delete(tag_id) + return f"Deleted the tag {args['tag']} from every item.", {"id": tag_id, "deleted": True} + + +def _attachments(args: dict) -> tuple[str, dict]: + found = library.attachment_list(args["id"]) + keep = ("id", "name", "mime", "mode", "path", "present", "size") + rows = [{k: a.get(k) for k in keep} for a in found] + lines = [f"{a['id']} · {a.get('name')} ({a.get('mime')}) {'' if a.get('present') else 'missing '}{a.get('path')}" for a in rows] + return "\n".join([f"{len(rows)} attachments."] + lines), {"attachments": rows} + + +def _attach_file(args: dict) -> tuple[str, dict]: + made = library.attachment_add(args["id"], args["path"], args.get("mode") or "copy", args.get("name")) + return f"Attached {made.get('name')} to {args['id']} as {made['id']}.", {"id": made["id"], "item_id": args["id"], "path": made.get("path")} + + +def _remove_attachment(args: dict) -> tuple[str, dict]: + out = library.attachment_remove(args["attachment_id"]) + return f"Removed attachment {args['attachment_id']}.", {"id": args["attachment_id"], "removed_files": out.get("removed_files") or []} + + +def _fulltext(args: dict) -> tuple[str, dict]: + item = library.item_show(args["id"]) + out = fulltext.links(item) + pdf = next((a for a in library.attachment_list(args["id"]) if a.get("id") == out.get("pdf_attachment_id")), None) + out["pdf_path"] = pdf.get("path") if pdf else None + if out["pdf_path"]: + said = f"The PDF is at {out['pdf_path']}; read it from there." + elif out["can_fetch_pdf"]: + said = f"No PDF yet; fetch_pdf can download it from arXiv ({out['arxiv_id']})." + else: + said = "No PDF and no arXiv identifier; attach_file can attach one the person has." + return said, out + + +def _fetch_pdf(args: dict) -> tuple[str, dict]: + out = fulltext.fetch_pdf(args["id"]) + found = out.get("attachment") or {} + said = "The PDF was already attached." if out.get("already") else f"Downloaded and attached the PDF as {found.get('id')}." + return said, {"attachment_id": found.get("id"), "already": bool(out.get("already"))} + + +def _add_pdf(args: dict) -> tuple[str, dict]: + out = identify.identify_file(args["path"], attach=args.get("mode") or "copy", on_duplicate=args.get("on_duplicate") or "skip") + item = out.get("item") or {} + return out.get("message") or "Done.", {"added": out.get("added"), "found": out.get("found"), + "duplicate_of": out.get("duplicate_of"), "item": _brief(item) if item else None} + + +def _relations(args: dict) -> tuple[str, dict]: + out = library.relation_list(args["id"]) + return f"Relations of {args['id']}.", out + + +def _relate(args: dict) -> tuple[str, dict]: + out = library.relation_add(args["id"], args["to"], args.get("kind") or "related") + return f"{args['id']} {args.get('kind') or 'related'} {args['to']}.", out + + +def _unrelate(args: dict) -> tuple[str, dict]: + out = library.relation_remove(args["id"], args["to"], args.get("kind") or "related") + return f"Removed the {args.get('kind') or 'related'} link from {args['id']} to {args['to']}.", out + + +def _saved_searches(args: dict) -> tuple[str, dict]: + found = library.saved_list() + rows = [{"id": s["id"], "name": s["name"], "rules": s.get("rules")} for s in found] + return "\n".join([f"{len(rows)} saved searches."] + [f"{s['id']} · {s['name']}" for s in rows]), {"searches": rows} + + +def _run_saved(args: dict) -> tuple[str, dict]: + if args.get("search"): + out = library.saved_run(args["search"], limit=args.get("limit") or 20) + elif args.get("rules"): + out = library.search_rules(args["rules"], limit=args.get("limit") or 20) + else: + raise Invalid("give search (a saved search id) or rules") + found = out.get("items") or [] + return "\n".join([f"{len(found)} of {out.get('total', len(found))} items."] + [_line(i) for i in found]), \ + {"total": out.get("total"), "items": [_brief(i) for i in found]} + + +def _save_search(args: dict) -> tuple[str, dict]: + out = library.saved_new(args["name"], args["rules"]) + return f"Saved the search {out['name']} as {out['id']}.", {"id": out["id"], "name": out["name"]} + + +def _edit_search(args: dict) -> tuple[str, dict]: + out = library.saved_edit(args["search"], args.get("name"), args.get("rules")) + return f"Edited the saved search {out['id']}.", {"id": out["id"], "name": out["name"]} + + +def _delete_search(args: dict) -> tuple[str, dict]: + library.saved_delete(args["search"]) + return f"Deleted the saved search {args['search']}.", {"id": args["search"], "deleted": True} + + +def _find_duplicates(args: dict) -> tuple[str, dict]: + out = duplicates.duplicates_list() + lines = [" = ".join(f"{m['id']} ({m.get('year') or 'n.d.'}) {(m.get('title') or '')[:60]}" for m in g) for g in out["groups"][:50]] + return "\n".join([f"{out['count']} groups of likely duplicates."] + lines), out + + +def _merge(args: dict) -> tuple[str, dict]: + out = duplicates.duplicates_merge(args["keep"], args["others"]) + return f"Merged {len(args['others'])} into {args['keep']}; the others are in the Trash.", \ + {"keep": args["keep"], "merged": args["others"], "item": _brief(out.get("item") or {})} + + +def _export(args: dict) -> tuple[str, dict]: + text = transfer.run_export(args.get("ids"), args.get("format") or "bibtex", args.get("collection"), args.get("tag")) + if len(text) > EXPORT_CAP: + raise Invalid(f"the export is {len(text)} characters, more than {EXPORT_CAP}; narrow it with ids, collection or tag") + return text or "(nothing to export)", {"format": args.get("format") or "bibtex", "chars": len(text)} + + +def _import_file(args: dict) -> tuple[str, dict]: + out = transfer.run_import_file(args["path"], args.get("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 {out.get('format')} as batch {out.get('batch_id')}: added {counts.get('added')}, " + f"skipped {counts.get('skipped')}, failed {counts.get('failed')}."), {"batch_id": out.get("batch_id"), **counts} + + +def _batches(args: dict) -> tuple[str, dict]: + found = transfer.batch_list()[: args.get("limit") or 20] + lines = [f"{b['id']} · {b.get('source') or ''} {b.get('label') or ''} ({b.get('item_count')} items) {b.get('created_at') or ''}" for b in found] + return "\n".join([f"{len(found)} import batches."] + lines), {"batches": found} + + +def _undo_import(args: dict) -> tuple[str, dict]: + out = transfer.batch_delete(args["batch_id"]) + return f"Undid import {args['batch_id']}: {len(out['trashed'])} items moved to the Trash.", out + + +def _keywords_to_tags(args: dict) -> tuple[str, dict]: + out = transfer.run_tags_from_keywords(args.get("collection"), bool(args.get("dry_run"))) + return f"Keywords to tags{' (dry run)' if args.get('dry_run') else ''}: {out}.", out + + +def _libraries(args: dict) -> tuple[str, dict]: + found = library.library_list() + current = library.library_current() + rows = [{"name": lib["name"], "root": lib.get("root"), "current": lib["name"] == current["name"]} for lib in found] + return "\n".join([f"{len(rows)} libraries; current: {current['name']}."] + [f"{r['name']}{' (current)' if r['current'] else ''}" for r in rows]), \ + {"libraries": rows, "current": current["name"], "counts": current.get("counts")} + + +def _create_library(args: dict) -> tuple[str, dict]: + out = library.library_create(args["name"]) + return f"Created the library {out['name']}; use_library switches to it.", {"name": out["name"], "root": out.get("root")} + + +def _use_library(args: dict) -> tuple[str, dict]: + out = library.library_use(args["name"]) + return f"Switched to the library {out['name']}; the open window follows.", {"name": out["name"]} + + +def _untitled(args: dict) -> tuple[str, dict]: + out = titles.untitled_list(args.get("limit") or 20, 0) + found = out.get("items") or [] + lines = [f"{i['id']} · {', '.join(i.get('creators') or []) or 'no author'} ({i.get('year') or 'n.d.'}) {', '.join(i.get('files') or [])}" for i in found] + return "\n".join([f"{len(found)} of {out.get('total', len(found))} items need a title."] + lines), out + + +def _title_suggestions(args: dict) -> tuple[str, dict]: + out = titles.suggestions(args["id"]) + sugg = out.get("suggestions") or [] + return "\n".join([f"{len(sugg)} suggested titles for {args['id']}."] + [str(s.get("title") if isinstance(s, dict) else s) for s in sugg]), out + + +def _title_lookup(args: dict) -> tuple[str, dict]: + out = titles.look_up(args["id"]) + return f"Found the title {out['title']!r} ({out['reason']}); edit_item sets it.", out + + +def _network_status(args: dict) -> tuple[str, dict]: + out = overview.listing() + off = [s["name"] for s in out.get("services") or [] if not s.get("enabled")] + log = overview.log(args.get("limit") or 10).get("entries") or [] + said = ("Network lookups are " + ("held off on this computer" if out.get("forced_offline") else "on" if out.get("enabled") else "off") + + (f"; services off: {', '.join(off)}" if off else "") + ". Only the person turns these switches, in Preferences, Network.") + return said, {"enabled": out.get("enabled"), "forced_offline": out.get("forced_offline"), "services_off": off, "recent": log} + + +def _window_commands(args: dict) -> tuple[str, dict]: + out = window_bridge.catalog(args.get("group")) + if not out["window_open"]: + return window_bridge.NO_WINDOW, out + lines = [] + for c in out["commands"]: + params = ", ".join(f"{n}{'' if a['required'] else '?'}: {'|'.join(a['enum']) if 'enum' in a else a['type']}" for n, a in c["args"].items()) + lines.append(f"{c['id']}({params}) · {c['title']}{' [changes the library]' if c['write'] else ''}") + return "\n".join([f"{len(lines)} window commands."] + lines), out + + +def _run_line(run: dict) -> str: + if run["state"] == "done": + return f"Ran {run['command']} in the window ({run['id']})." + (f" {run['result'].get('said')}" if (run.get("result") or {}).get("said") else "") + if run["state"] in ("queued", "sent"): + return f"{run['command']} is still running in the window; ask window_command_result with run_id {run['id']}." + return f"{run['command']} {run['state']}: {run.get('error')}" + + +def _run_compact(run: dict) -> dict: + return {k: run.get(k) for k in ("id", "command", "state", "result", "error")} + + +def _window_command_run(args: dict) -> tuple[str, dict]: + run = window_bridge.submit(args["command"], args.get("args") or {}, "agent") + seconds = args.get("wait_seconds") + run = window_bridge.wait(run["id"], 8 if seconds is None else seconds) + if run["state"] == "failed": + raise Invalid(_run_line(run)) + return _run_line(run), _run_compact(run) + + +def _window_command_result(args: dict) -> tuple[str, dict]: + run = window_bridge.wait(args["run_id"], args.get("wait_seconds") or 0) + return _run_line(run), _run_compact(run) + + +TAG = {"type": "string", "description": "A tag id or name."} +SEARCH = {"type": "string", "description": "A saved search id."} +RULES = {"type": "object", "description": "{\"match\": \"all\"|\"any\", \"rules\": [{\"field\": ..., \"op\": \"contains\"|\"is\"|\"is_not\"|\"gte\"|\"lte\", \"value\": ...}]}; fields are those of docs/SCHEMA.md saved searches (text, title, creator, year, type, tag, collection, ...)."} +FORMAT = {"type": "string", "enum": ["bibtex", "ris", "csljson", "formtxt"], "description": "The format (default bibtex)."} +NOTE = {"type": "string", "description": "The note id."} +ON_DUPLICATE = {"type": "string", "enum": ["skip", "add"], "description": "skip (default) keeps the item already in the library; add adds anyway."} +KIND = {"type": "string", "enum": ["related", "cites"], "description": "related (default) or cites."} + + +def _tool(name: str, title: str, description: str, run, props: dict | None = None, required: tuple[str, ...] = (), *, + read_only: bool = False, destructive: bool = False, idempotent: bool = False, open_world: bool = False) -> dict: + out = {"name": name, "title": title, "description": description, "input_schema": _schema(props or {}, required), + "read_only": read_only, "run": run} + if destructive: + out["destructive"] = True + if idempotent: + out["idempotent"] = True + if open_world: + out["open_world"] = True + return out + + +PARITY_TOOLS: list[dict] = [ + _tool("edit_item", "Edit an item", "Change any field of an item: fields such as title, author (\"Family, Given\" or a list), editor, year, issued, container, volume, issue, page, publisher, doi, isbn, url, type, abstract, language; or a whole csl record that replaces the old one.", + _edit_item, {"id": ID, "fields": {"type": "object", "description": "Fields to change; others are kept."}, "csl": {"type": "object", "description": "A whole CSL-JSON record."}}, ("id",), idempotent=True), + _tool("trash_items", "Move items to the Trash", "Move items to the Trash, as the window's Move to Trash does. restore_items brings them back.", + _trash_items, {"ids": IDS}, ("ids",), idempotent=True), + _tool("restore_items", "Restore items from the Trash", "Bring items back from the Trash.", _restore_items, {"ids": IDS}, ("ids",), idempotent=True), + _tool("list_trash", "List the Trash", "Items in the Trash, newest first.", _list_trash, {"limit": LIMIT}, read_only=True), + _tool("delete_items_forever", "Delete items forever", "Delete items and their stored files for good. Only when the person asked; needs confirm: true.", + _delete_forever, {"ids": IDS, "confirm": CONFIRM}, ("ids", "confirm"), destructive=True), + _tool("empty_trash", "Empty the Trash", "Delete every item in the Trash for good. Only when the person asked; needs confirm: true.", + _empty_trash, {"confirm": CONFIRM}, ("confirm",), destructive=True), + _tool("list_notes", "List an item's notes", "The notes of one item with their ids.", _notes, {"id": ID}, ("id",), read_only=True), + _tool("add_note", "Add a note", "Add a note (plain text or Markdown) to an item.", _add_note, {"id": ID, "body": {"type": "string", "description": "The note text."}}, ("id", "body")), + _tool("edit_note", "Edit a note", "Replace the text of a note.", _edit_note, {"note_id": NOTE, "body": {"type": "string", "description": "The new text."}}, ("note_id", "body"), idempotent=True), + _tool("delete_note", "Delete a note", "Delete a note for good.", _delete_note, {"note_id": NOTE}, ("note_id",), destructive=True), + _tool("untag_item", "Take tags off an item", "Remove one or more tags from an item.", _untag, + {"id": ID, "tags": {"type": "array", "items": {"type": "string"}, "minItems": 1, "description": "Tag names."}}, ("id", "tags"), idempotent=True), + _tool("rename_tag", "Rename a tag", "Rename a tag on every item that carries it.", _rename_tag, {"tag": TAG, "name": {"type": "string", "description": "The new name."}}, ("tag", "name"), idempotent=True), + _tool("delete_tag", "Delete a tag", "Delete a tag and take it off every item.", _delete_tag, {"tag": TAG}, ("tag",), destructive=True), + _tool("list_attachments", "List an item's attachments", "Attachments of an item with their file paths, so an agent can read the PDF.", _attachments, {"id": ID}, ("id",), read_only=True), + _tool("attach_file", "Attach a file", "Attach a file on this computer to an item: copy (default) stores a copy in the library, link keeps a link to the file where it is.", + _attach_file, {"id": ID, "path": {"type": "string", "description": "An absolute path."}, "mode": {"type": "string", "enum": ["copy", "link"]}, "name": {"type": "string", "description": "The name to show."}}, ("id", "path")), + _tool("remove_attachment", "Remove an attachment", "Remove an attachment from its item; a stored copy no other item uses is deleted.", + _remove_attachment, {"attachment_id": {"type": "string", "description": "The attachment id."}}, ("attachment_id",), destructive=True), + _tool("get_fulltext", "Find an item's full text", "Where an item's PDF is on disk, or whether fetch_pdf can download it from arXiv.", _fulltext, {"id": ID}, ("id",), read_only=True), + _tool("fetch_pdf", "Fetch the PDF", "Download an item's open-access PDF from arXiv and attach it. Reaches the network under the person's network switches.", + _fetch_pdf, {"id": ID}, ("id",), idempotent=True, open_world=True), + _tool("add_pdf", "Add a PDF", "Identify a PDF on this computer by the DOI or arXiv id in it, add the item and attach the file, as dropping a PDF on the window does. Reaches the network under the person's network switches.", + _add_pdf, {"path": {"type": "string", "description": "An absolute path to a PDF."}, "mode": {"type": "string", "enum": ["copy", "link"]}, "on_duplicate": ON_DUPLICATE}, ("path",), open_world=True), + _tool("list_relations", "List an item's relations", "Items this item cites or is related to, both ways.", _relations, {"id": ID}, ("id",), read_only=True), + _tool("relate_items", "Relate two items", "Record that one item is related to or cites another.", _relate, {"id": ID, "to": {"type": "string", "description": "The other item id."}, "kind": KIND}, ("id", "to"), idempotent=True), + _tool("unrelate_items", "Remove a relation", "Remove a related or cites link between two items.", _unrelate, {"id": ID, "to": {"type": "string", "description": "The other item id."}, "kind": KIND}, ("id", "to"), idempotent=True), + _tool("list_saved_searches", "List saved searches", "The library's saved searches with their rules.", _saved_searches, read_only=True), + _tool("run_search", "Run a saved or rule search", "Items matching a saved search, or matching rules given here, without saving them.", + _run_saved, {"search": SEARCH, "rules": RULES, "limit": LIMIT}, read_only=True), + _tool("save_search", "Save a search", "Save rules as a named search.", _save_search, {"name": {"type": "string"}, "rules": RULES}, ("name", "rules")), + _tool("edit_saved_search", "Edit a saved search", "Rename a saved search or change its rules.", _edit_search, {"search": SEARCH, "name": {"type": "string"}, "rules": RULES}, ("search",), idempotent=True), + _tool("delete_saved_search", "Delete a saved search", "Delete a saved search; the items stay.", _delete_search, {"search": SEARCH}, ("search",), destructive=True), + _tool("find_duplicates", "Find duplicates", "Groups of items that are likely the same work, as the Duplicates view shows.", _find_duplicates, read_only=True), + _tool("merge_duplicates", "Merge duplicates", "Merge items into the one to keep: empty fields are filled, tags, collections, notes, attachments and relations move to it, and the others go to the Trash.", + _merge, {"keep": ID, "others": IDS}, ("keep", "others"), destructive=True), + _tool("export_references", "Export references", "Export items as BibTeX, RIS, CSL-JSON or FormTxt text: the given ids, a collection, a tag, or the whole library.", + _export, {"format": FORMAT, "ids": {**IDS, "maxItems": 5000}, "collection": {"type": "string", "description": "A collection id."}, "tag": {"type": "string", "description": "A tag name."}}, read_only=True), + _tool("import_file", "Import a file", "Import a BibTeX, RIS, CSL-JSON or FormTxt file on this computer as one import batch.", _import_file, + {"path": {"type": "string", "description": "An absolute path."}, "format": FORMAT, "on_duplicate": ON_DUPLICATE, "keywords_as_tags": {"type": "boolean"}}, ("path",)), + _tool("list_import_batches", "List import batches", "Each import and each add by identifier, newest first, with its batch id.", _batches, {"limit": LIMIT}, read_only=True), + _tool("undo_import", "Undo an import", "Move every item of one import batch to the Trash and forget the batch.", _undo_import, {"batch_id": {"type": "string"}}, ("batch_id",), destructive=True), + _tool("keywords_to_tags", "Make tags from keywords", "Add each item's keywords as tags, for the whole library or one collection.", _keywords_to_tags, + {"collection": {"type": "string", "description": "A collection id."}, "dry_run": {"type": "boolean", "description": "Only count what would change."}}), + _tool("list_libraries", "List libraries", "The libraries in the data folder and which one is open.", _libraries, read_only=True), + _tool("create_library", "Create a library", "Make a new, empty library in the data folder.", _create_library, {"name": {"type": "string"}}, ("name",)), + _tool("use_library", "Switch library", "Open another library; the window switches with it.", _use_library, {"name": {"type": "string"}}, ("name",), idempotent=True), + _tool("list_untitled", "List items that need a title", "Items without a title, as the Needs a title view shows.", _untitled, {"limit": LIMIT}, read_only=True), + _tool("title_suggestions", "Suggest titles", "Titles FormCite can suggest for an untitled item from its file names and fields.", _title_suggestions, {"id": ID}, ("id",), read_only=True), + _tool("title_lookup", "Look up a title", "Look up an untitled item's title by its identifier. Reaches the network under the person's network switches.", + _title_lookup, {"id": ID}, ("id",), read_only=True, open_world=True), + _tool("network_status", "Network switches and recent calls", "Whether lookups may reach the network, which services are off, and the latest calls, as Preferences, Network shows. Read-only: the switches are the person's.", + _network_status, {"limit": {**LIMIT, "description": "Recent calls to answer (default 10)."}}, read_only=True), + _tool("window_commands", "List window commands", "The commands the open FormCite window offers, with typed arguments: views, selection, search, sort, scope, the reader, dialogs, appearance and the rest of what a person does with menus and buttons.", + _window_commands, {"group": {"type": "string", "description": "Only one group, such as view, item, list, reader, prefs."}}, read_only=True), + _tool("window_command_run", "Run a window command", "Run one command of window_commands in the open window, where the person sees it. Answers when it finished, or a run id to ask window_command_result about.", + _window_command_run, {"command": {"type": "string", "description": "A command id from window_commands."}, "args": {"type": "object", "description": "Its arguments."}, + "wait_seconds": {"type": "integer", "minimum": 0, "maximum": 20, "description": "How long to wait for it (default 8)."}}, ("command",)), + _tool("window_command_result", "Get a window command's result", "The state and result of a window command run.", _window_command_result, + {"run_id": {"type": "string"}, "wait_seconds": {"type": "integer", "minimum": 0, "maximum": 20}}, ("run_id",), read_only=True), +] From 8daa5791162f54075c90a5c70bf81dd0d0b69e2c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:48 -0500 Subject: [PATCH 08/36] feat(window): every action a person takes in the window is a typed command an agent can run (0.16.0) engine/bridge.ts keeps the argument types of each offered command (describeCommand), checks a run's arguments and answers what the window then shows: view, scope, search, sort, selection and counts. io/bridge.ts publishes the offered commands and long-polls the engine for runs, with a back-off when the engine is away. ui/parity.ts registers the actions that had no command (select and reveal an item, search, sort and scope the list, every view, Preferences at a section, appearance, theme and accent, Home at launch, the title field, switching library, the Add dialog by identifier, minimize and zoom) and describes those and the existing ones, the reader's and the collection commands included. Connections, the network switches and the clipboard edit commands stay the person's. --- frontend/src/engine/bridge.ts | 86 ++++++++++++++++++++ frontend/src/io/bridge.ts | 38 +++++++++ frontend/src/main.ts | 2 + frontend/src/ui/parity.ts | 144 ++++++++++++++++++++++++++++++++++ 4 files changed, 270 insertions(+) create mode 100644 frontend/src/engine/bridge.ts create mode 100644 frontend/src/io/bridge.ts create mode 100644 frontend/src/ui/parity.ts diff --git a/frontend/src/engine/bridge.ts b/frontend/src/engine/bridge.ts new file mode 100644 index 0000000..5dfa914 --- /dev/null +++ b/frontend/src/engine/bridge.ts @@ -0,0 +1,86 @@ +import type { Engine } from './index'; + +export type ArgType = 'string' | 'number' | 'integer' | 'boolean'; + +export interface ArgSpec { + type: ArgType; + required?: boolean; + enum?: readonly string[]; + description?: string; +} + +export interface CommandSpec { + args?: Record; + write?: boolean; + group?: string; + adapt?: (args: Record, engine: Engine) => unknown; + said?: (args: Record, engine: Engine) => string; + settle?: number; +} + +export interface PublishedCommand { + id: string; + title: string; + args: Record; + write: boolean; + group: string; +} + +export interface BridgeRun { id: string; command: string; args: Record } +export interface BridgeOutcome { ok: boolean; result?: Record; error?: string } + +const KEPT_FOR_THE_PERSON = /^(connections\.|engine\.|edit\.|network\.|service\.|window\.close$)/; +const specs = new Map(); + +export function describeCommand(id: string, spec: CommandSpec = {}): void { + if (KEPT_FOR_THE_PERSON.test(id)) return; + specs.set(id, spec); +} + +export function offered(engine: Engine): PublishedCommand[] { + const out: PublishedCommand[] = []; + for (const cmd of engine.commands.list()) { + const spec = specs.get(cmd.id); + if (!spec) continue; + out.push({ id: cmd.id, title: cmd.title, args: spec.args ?? {}, write: !!spec.write, group: spec.group ?? cmd.id.split('.')[0] ?? cmd.id }); + } + return out; +} + +function check(id: string, spec: CommandSpec, args: Record): string | null { + for (const key of Object.keys(args)) if (!spec.args?.[key]) return `${id} takes no argument ${key}`; + for (const [name, want] of Object.entries(spec.args ?? {})) { + const v = args[name]; + if (v === undefined || v === null || v === '') { if (want.required) return `${id} needs ${name}`; continue; } + const ok = want.type === 'string' ? typeof v === 'string' + : want.type === 'boolean' ? typeof v === 'boolean' + : typeof v === 'number' && Number.isFinite(v) && (want.type === 'number' || Number.isInteger(v)); + if (!ok) return `${name} must be a ${want.type}`; + if (want.enum && !want.enum.includes(String(v))) return `${name} must be one of ${want.enum.join(', ')}`; + } + return null; +} + +export function snapshot(engine: Engine): Record { + const lib = engine.library; + return { view: lib.view, scope: { kind: lib.scope.kind, id: lib.scope.id, label: lib.scope.label }, query: lib.query, sort: lib.sort, selected: lib.selected, shown: lib.counts.shown, total: lib.counts.total }; +} + +const pause = (ms: number): Promise => new Promise((r) => { setTimeout(r, ms); }); + +export async function runBridged(engine: Engine, run: BridgeRun): Promise { + const spec = specs.get(run.command); + if (!spec || !engine.commands.has(run.command)) return { ok: false, error: `the window has no command ${run.command}` }; + const args = run.args && typeof run.args === 'object' ? run.args : {}; + const bad = check(run.command, spec, args); + if (bad) return { ok: false, error: bad }; + try { + const given = spec.adapt ? spec.adapt(args, engine) : (Object.keys(args).length ? args : undefined); + engine.dispatch(run.command, given); + await pause(spec.settle ?? 250); + const said = spec.said ? spec.said(args, engine) : ''; + return { ok: true, result: { ...snapshot(engine), ...(said ? { said } : {}) } }; + } catch (e) { + return { ok: false, error: e instanceof Error ? e.message : String(e) }; + } +} diff --git a/frontend/src/io/bridge.ts b/frontend/src/io/bridge.ts new file mode 100644 index 0000000..3ce4979 --- /dev/null +++ b/frontend/src/io/bridge.ts @@ -0,0 +1,38 @@ +import type { Engine } from '../engine'; +import { offered, runBridged, type BridgeRun } from '../engine/bridge'; +import { api } from './api'; +import { loadWindowKey } from './window-key'; + +const WAIT_S = 20; +const BACKOFF_MS = [1000, 2000, 5000, 10000]; + +export function startBridge(engine: Engine): void { + let published = ''; + let failures = 0; + const publish = async (): Promise => { + const commands = offered(engine); + const sign = commands.map((c) => c.id).join(','); + if (sign === published) return; + await api.put('/window/commands', { commands }); + published = sign; + }; + const loop = async (): Promise => { + if (!(await loadWindowKey())) return; + for (;;) { + try { + await publish(); + const { run } = await api.get<{ run: BridgeRun | null }>(`/window/commands/next?wait=${WAIT_S}`); + failures = 0; + if (!run) continue; + const out = await runBridged(engine, run); + await api.post(`/window/commands/runs/${encodeURIComponent(run.id)}`, out); + } catch { + published = ''; + const ms = BACKOFF_MS[Math.min(failures, BACKOFF_MS.length - 1)] ?? 10000; + failures += 1; + await new Promise((r) => { window.setTimeout(r, ms); }); + } + } + }; + void loop(); +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 8b9393b..36a32e8 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -3,8 +3,10 @@ import { activateAll } from './extensions/registry'; import { mountApp } from './ui/app'; import { currentAppearance } from './engine/preferences'; import { applyLook } from './ui/themes'; +import { mountParity } from './ui/parity'; applyLook(); const engine = createEngine(currentAppearance().theme); activateAll(engine); mountApp(engine); +mountParity(engine); diff --git a/frontend/src/ui/parity.ts b/frontend/src/ui/parity.ts new file mode 100644 index 0000000..10e857b --- /dev/null +++ b/frontend/src/ui/parity.ts @@ -0,0 +1,144 @@ +import type { Engine, Scope, SortKey } from '../engine'; +import { ALL } from '../engine'; +import { describeCommand, type ArgSpec } from '../engine/bridge'; +import { chooseAccent, chooseTheme, prefs, setShellPref, setTitleFieldMode } from '../engine/preferences'; +import { startBridge } from '../io/bridge'; +import { fetchPosition } from '../io/itemlist'; +import { sideApi } from '../io/side'; +import { openPreferences } from './preferences'; +import { ALL_THEMES, setLook } from './themes'; +import { toast } from './toast'; + +const ID: Record = { id: { type: 'string', description: 'An item id; the selected item when left out.' } }; +const NEED_ID: Record = { id: { type: 'string', required: true, description: 'An item id.' } }; +const SORTS: readonly SortKey[] = ['title', 'creator', 'year', 'type', 'added', 'updated']; +const SECTIONS = ['general', 'appearance', 'network', 'libraries', 'menus', 'agents'] as const; +const VIEWS: Record = { library: 'Items', duplicates: 'Duplicates', trash: 'Trash', titles: 'Needs a title', connections: 'Connections', home: 'Home' }; + +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); +const itemId = (a: Record, engine: Engine): string => str(a.id) || engine.library.selected || ''; +const press = (sel: string): void => { document.querySelector(sel)?.click(); }; +const openView = (view: string): void => press(`.fc-nav-item[data-view="${view}"]`); + +function type(input: HTMLInputElement | null, text: string): void { + if (!input) return; + input.value = text; + input.dispatchEvent(new Event('input', { bubbles: true })); +} + +async function reveal(engine: Engine, id: string): Promise { + const lib = engine.library; + if (lib.view !== 'library') openView('library'); + lib.select(id); + const at = await fetchPosition(id, { scope: lib.scope, q: lib.query, sort: lib.sort }).catch(() => null); + const scroll = document.querySelector('.fc-il-scroll'); + const row = document.querySelector('.fc-il-row'); + if (!at || typeof at !== 'object' || !scroll || !row || !row.offsetHeight) return; + const top = at.index * row.offsetHeight; + if (top < scroll.scrollTop || top + row.offsetHeight > scroll.scrollTop + scroll.clientHeight) scroll.scrollTop = Math.max(0, top - (scroll.clientHeight - row.offsetHeight) / 2); +} + +async function scopeFor(kind: string, key: string): Promise { + if (kind === 'all') return ALL; + if (kind === 'unfiled') return { kind: 'unfiled', id: '', label: 'Unfiled' }; + if (kind === 'collection') { + const found = (await sideApi.collections()).find((c) => c.id === key || c.name.toLowerCase() === key.toLowerCase()); + if (!found) throw new Error(`no collection ${key}`); + return { kind: 'collection', id: found.id, label: found.name }; + } + if (kind === 'tag') { + const found = (await sideApi.tags()).find((t) => t.id === key || t.name.toLowerCase() === key.toLowerCase()); + if (!found) throw new Error(`no tag ${key}`); + return { kind: 'tag', id: found.id, label: found.name }; + } + return { kind: 'batch', id: key, label: `Import ${key}` }; +} + +function addDialog(tab: 'id' | 'import' | 'export'): HTMLElement | null { + press(`.fc-add-tab[data-tab="${tab}"]`); + press('.fc-add-open'); + return document.querySelector(`.fc-add-sec[data-sec="${tab}"]`); +} + +function failed(what: string): (e: unknown) => void { + return (e) => toast(`${what}: ${e instanceof Error ? e.message : String(e)}`, 'error'); +} + +function windowCall(act: 'minimize' | 'toggleMaximize'): void { + void import('@tauri-apps/api/window').then(({ getCurrentWindow }) => getCurrentWindow()[act]()).catch(() => undefined); +} + +export function mountParity(engine: Engine): void { + const lib = engine.library; + const own: Array<[string, string, (a: Record) => void]> = [ + ['item.select', 'Select an item and show it', (a) => { void reveal(engine, str(a.id)); }], + ['list.search', 'Search the items list', (a) => { if (lib.view !== 'library') openView('library'); lib.setQuery(str(a.text)); }], + ['list.sort', 'Sort the items list', (a) => { lib.setSort({ key: (SORTS.includes(a.key as SortKey) ? a.key : 'added') as SortKey, desc: a.desc === true }); }], + ['list.scope', 'Show a collection, tag, import or the whole library', (a) => { + void scopeFor(str(a.kind) || 'all', str(a.id)).then((s) => { lib.setScope(s); if (lib.view !== 'library') openView('library'); }, failed('Could not show that')); + }], + ['view.titles', 'Needs a title', () => openView('titles')], + ['view.show', 'Show a view', (a) => openView(str(a.view))], + ['prefs.open', 'Open Preferences at a section', (a) => openPreferences(str(a.section) || undefined)], + ['prefs.close', 'Close Preferences', () => press('.cv-prefs-close')], + ['appearance.mode', 'Appearance: system, light or dark', (a) => chooseTheme(engine, str(a.mode))], + ['appearance.theme', 'Pick the dark or light theme', (a) => { + const kind = str(a.kind) === 'light' ? 'light' : 'dark'; + setLook(kind === 'dark' ? { dark: str(a.theme) } : { light: str(a.theme) }); + chooseTheme(engine, kind); + }], + ['appearance.accent', 'Accent color', (a) => chooseAccent(str(a.color))], + ['prefs.home-at-launch', 'Show Home at launch', (a) => setShellPref('homeAtLaunch', a.on === true)], + ['prefs.title-field', 'Details pane title field', (a) => setTitleFieldMode(str(a.mode) === 'grow' ? 'grow' : 'fixed')], + ['library.use', 'Switch library', (a) => { + void prefs.useLibrary(str(a.name)).then(() => lib.librarySwitched(), failed('Could not switch library')); + }], + ['add.identifier', 'Add by identifier in the Add dialog', (a) => { + const sec = addDialog('id'); + type(sec?.querySelector('input') ?? null, str(a.identifier)); + if (a.then === 'preview' || a.then === 'add') sec?.querySelector(`[data-act="${a.then}"]`)?.click(); + }], + ['add.close', 'Close the Add dialog', () => press('.fc-add.is-open [data-close]')], + ['window.minimize', 'Minimize', () => windowCall('minimize')], + ['window.zoom', 'Zoom', () => windowCall('toggleMaximize')], + ]; + for (const [id, title, run] of own) { + if (engine.commands.has(id)) continue; + engine.commands.register({ id, title, run: (args) => run(args && typeof args === 'object' ? args as Record : {}) }); + } + + const asId = (a: Record, e: Engine): string => itemId(a, e); + describeCommand('item.select', { args: NEED_ID, group: 'item', settle: 500, said: (a) => `Selected ${str(a.id)}; the details pane shows it.` }); + for (const id of ['item.open', 'item.copy-citation', 'item.copy-bibliography', 'item.view', 'item.open-system']) describeCommand(id, { args: ID, group: 'item', adapt: asId, settle: id === 'item.view' ? 1500 : 400 }); + describeCommand('item.trash', { args: ID, group: 'item', adapt: asId, write: true, said: (a, e) => `Moved ${itemId(a, e) || 'the selected item'} to the Trash; restore_items brings it back.` }); + describeCommand('list.search', { args: { text: { type: 'string', required: true, description: 'Words to search for; empty clears.' } }, group: 'list', settle: 600 }); + describeCommand('list.sort', { args: { key: { type: 'string', required: true, enum: SORTS }, desc: { type: 'boolean' } }, group: 'list', settle: 500 }); + describeCommand('list.scope', { args: { kind: { type: 'string', required: true, enum: ['all', 'unfiled', 'collection', 'tag', 'batch'] }, id: { type: 'string', description: 'The collection or tag id or name, or the import batch id.' } }, group: 'list', settle: 700 }); + for (const id of ['app.home', 'view.items', 'view.duplicates', 'view.trash', 'view.titles', 'view.connections', 'view.dock']) describeCommand(id, { group: 'view' }); + describeCommand('view.show', { args: { view: { type: 'string', required: true, enum: Object.keys(VIEWS) } }, group: 'view' }); + describeCommand('edit.find', { group: 'list' }); + describeCommand('app.preferences', { group: 'prefs' }); + describeCommand('prefs.open', { args: { section: { type: 'string', enum: SECTIONS } }, group: 'prefs' }); + describeCommand('prefs.close', { group: 'prefs' }); + describeCommand('appearance.mode', { args: { mode: { type: 'string', required: true, enum: ['system', 'light', 'dark'] } }, group: 'prefs' }); + describeCommand('appearance.theme', { args: { kind: { type: 'string', required: true, enum: ['dark', 'light'] }, theme: { type: 'string', required: true, enum: ALL_THEMES.map((t) => t.id).filter((v, i, all) => all.indexOf(v) === i) } }, group: 'prefs' }); + describeCommand('appearance.accent', { args: { color: { type: 'string', required: true, description: 'A color as #rrggbb.' } }, group: 'prefs' }); + describeCommand('prefs.home-at-launch', { args: { on: { type: 'boolean', required: true } }, group: 'prefs' }); + describeCommand('prefs.title-field', { args: { mode: { type: 'string', required: true, enum: ['grow', 'fixed'] } }, group: 'prefs' }); + describeCommand('view.menus-in-window', { group: 'prefs' }); + describeCommand('library.use', { args: { name: { type: 'string', required: true } }, group: 'library', write: true, settle: 800 }); + describeCommand('library.add', { group: 'library' }); + describeCommand('library.import', { group: 'library' }); + describeCommand('library.export', { group: 'library' }); + describeCommand('add.identifier', { args: { identifier: { type: 'string', required: true }, then: { type: 'string', enum: ['preview', 'add'] } }, group: 'library', write: true, settle: 600 }); + describeCommand('add.close', { group: 'library' }); + describeCommand('collection.new', { args: { name: { type: 'string' }, parent: { type: 'string' } }, group: 'collection', write: true }); + describeCommand('collection.add-selection', { args: { collection: { type: 'string', required: true } }, group: 'collection', write: true }); + describeCommand('collection.show', { args: { collection: { type: 'string', required: true } }, group: 'collection', settle: 600 }); + describeCommand('reader.page', { args: { page: { type: 'integer', required: true } }, group: 'reader' }); + describeCommand('reader.find', { args: { text: { type: 'string', required: true } }, group: 'reader', settle: 800 }); + describeCommand('reader.close', { group: 'reader' }); + describeCommand('window.minimize', { group: 'window' }); + describeCommand('window.zoom', { group: 'window' }); + startBridge(engine); +} From 12b2b9a51ffaba2d152e6b0bdda0ec36ac3fa60e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:46:05 -0500 Subject: [PATCH 09/36] docs: the changes table and the window's live feed (0.16.0) SCHEMA.md gains the changes and change_origin tables from schema version 3, with every kind and origin. WINDOW.md says what now shows up live in the item list and sidebar, and documents GET /api/changes/stream, its messages and how a reconnect catches up. --- docs/SCHEMA.md | 14 ++++++++++++++ docs/WINDOW.md | 3 +++ 2 files changed, 17 insertions(+) diff --git a/docs/SCHEMA.md b/docs/SCHEMA.md index d9a13b6..f6cf144 100644 --- a/docs/SCHEMA.md +++ b/docs/SCHEMA.md @@ -187,6 +187,20 @@ HAVING COUNT(*) > 1; The full-text index (SQLite FTS5) behind search. One row per item not in the trash, with columns `item_id`, `title`, `creators`, `container_title`, `abstract`, `notes` and `tags`. The app rewrites an item's row in the same transaction as every change, so you never need to touch it. It is not meant for spreadsheets. +## changes + +Added in schema version 3. Triggers on items, item_tags, tags, collections, collection_items, notes, attachments, relations and saved_searches add one row for every write, whoever makes it: the engine, `./formcite cli`, the stdio MCP server, an import or a direct SQLite write. The open window reads it through `GET /api/changes/stream` to show those changes live. The last 5000 rows are kept. Never write to it, or to `change_origin`, yourself. + +| column | meaning | +| --- | --- | +| seq | the change sequence, rising by one per row | +| kind | `item.add`, `item.edit`, `item.trash`, `item.restore`, `item.delete`, `tag.add`, `tag.remove`, `tag.edit`, `tag.delete`, `collection.add`, `collection.edit`, `collection.delete`, `collection.file`, `collection.unfile`, `note`, `attachment`, `relation` or `search` | +| item_id | the item the change touched, when there is one | +| ref_id | the tag, collection, note, attachment, related item or saved search | +| origin | `window` for the window's own requests, `agent` for any other engine request, empty for another process | + +`change_origin` is a one-row table the engine sets inside a write transaction and clears before it commits, so the triggers can stamp the origin. + ## Example queries Every item not in the trash, with its first author and year: diff --git a/docs/WINDOW.md b/docs/WINDOW.md index 38b5f74..fac388f 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -23,6 +23,7 @@ The **Items** view has three panes side by side. - Click a row or use the arrow keys to select it. The list stays smooth with thousands of items: only the rows on screen exist, and scrolling rewrites them. - When an item is added or restored, the window asks the engine where that one row falls in the current list (`GET /api/library/rows/{id}/position`) and inserts only that row. When an item is removed, the rows below move up and only rows that were not yet loaded are fetched. A removed item the window never loaded is asked for with `include_trashed=true`, which answers where the trashed item sat in the same sort and filter. Several ids in one change are placed in one pass. An unknown id (404 with the engine's `detail`) is skipped on add. The list is read again only when the engine is older (405, or a bare `Not Found`), when an item was deleted for good before the window placed it, or when the count the engine returns does not agree, which today includes a never-loaded remove under a search filter. - The creator column shows the first author, "A and B" for two authors, or "A et al." for more. Items with no year sort after the rest. +- Changes made outside the window show up live, with no reload: items an agent, the command line, the MCP server or an import added, edited, tagged, trashed or restored; notes and attachments; collections created, renamed or deleted, and items filed into or out of them. Only the rows, sidebar entries and counts that changed are touched; the selection, the open details and the scroll position stay. When rows arrive above the ones on screen, the list keeps the same rows in view. Rows an agent just added carry a short accent edge that fades. Changes made in the window itself are not sent back to it. ### Detail pane (right) @@ -78,6 +79,8 @@ Only the window can open files: the request is refused without the window's key. 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}}`. +Live changes come from `GET /api/changes/stream?since=SEQ&lib=NAME`, a server-sent event stream that needs the window key header like every other window call. It opens with `{t: "hello", lib, seq, stale, switched}`, then sends `{t: "changes", lib, seq, ch}`, where each entry of `ch` is `[seq, kind, item_id, ref_id, origin]` from the `changes` table (see [SCHEMA.md](SCHEMA.md)). The window's own changes are left out and only move `seq` on. `{t: "stale"}` (or `stale: true` in hello, after falling more than 5000 changes behind) asks the window to read every pane again once; `switched: true` or `{t: "switch"}` means the current library changed. A stream lasts 30 seconds and the window reconnects from its last `seq`, so nothing is lost across a reconnect. + ## 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 957d84686aec14b74f97949294e6831a8ae5d062 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:46:54 -0500 Subject: [PATCH 10/36] fix(window): re-read once when the change feed first opens (0.16.0) The list loads before the feed can open, since the feed waits for the window key, and the first hello starts from the engine's latest sequence. A write landing in that gap was never shown. The first hello now calls Library.stale() once; when nothing changed, the re-read writes the same text into the same rows and touches no DOM. --- frontend/src/engine/live.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/engine/live.ts b/frontend/src/engine/live.ts index c24ab43..7c5bf28 100644 --- a/frontend/src/engine/live.ts +++ b/frontend/src/engine/live.ts @@ -56,7 +56,7 @@ export class LiveFeed { this.lib = m.lib; this.seq = m.seq; if (known && m.switched) { this.drop(); this.library.librarySwitched(); } - else if (m.stale) { this.drop(); this.library.stale(); } + else if (m.stale || !known) { this.drop(); this.library.stale(); } return; } this.seq = m.seq; From 686258f394e987f583beaded894e765759e12fb5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:48:15 -0500 Subject: [PATCH 11/36] fix(window): list.search takes an empty or missing text to clear the search (0.16.0) An agent clearing the search sent an empty string and the bridge refused it as a missing required argument; the text is now optional, as clearing the search box is for a person. --- frontend/src/ui/parity.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/ui/parity.ts b/frontend/src/ui/parity.ts index 10e857b..6b37d8f 100644 --- a/frontend/src/ui/parity.ts +++ b/frontend/src/ui/parity.ts @@ -111,7 +111,7 @@ export function mountParity(engine: Engine): void { describeCommand('item.select', { args: NEED_ID, group: 'item', settle: 500, said: (a) => `Selected ${str(a.id)}; the details pane shows it.` }); for (const id of ['item.open', 'item.copy-citation', 'item.copy-bibliography', 'item.view', 'item.open-system']) describeCommand(id, { args: ID, group: 'item', adapt: asId, settle: id === 'item.view' ? 1500 : 400 }); describeCommand('item.trash', { args: ID, group: 'item', adapt: asId, write: true, said: (a, e) => `Moved ${itemId(a, e) || 'the selected item'} to the Trash; restore_items brings it back.` }); - describeCommand('list.search', { args: { text: { type: 'string', required: true, description: 'Words to search for; empty clears.' } }, group: 'list', settle: 600 }); + describeCommand('list.search', { args: { text: { type: 'string', description: 'Words to search for; left out or empty clears the search.' } }, group: 'list', settle: 600 }); describeCommand('list.sort', { args: { key: { type: 'string', required: true, enum: SORTS }, desc: { type: 'boolean' } }, group: 'list', settle: 500 }); describeCommand('list.scope', { args: { kind: { type: 'string', required: true, enum: ['all', 'unfiled', 'collection', 'tag', 'batch'] }, id: { type: 'string', description: 'The collection or tag id or name, or the import batch id.' } }, group: 'list', settle: 700 }); for (const id of ['app.home', 'view.items', 'view.duplicates', 'view.trash', 'view.titles', 'view.connections', 'view.dock']) describeCommand(id, { group: 'view' }); From 75e9f21de4c92c38e433acd7bda46a349ba37c52 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:49:12 -0500 Subject: [PATCH 12/36] docs(agents): the parity tools, the window bridge and what stays the person's (0.16.0) docs/MCP.md lists the tools that cover the rest of the library and the three window tools, with their read-only and destructive marks; docs/WINDOW.md says how the bridge works (the registry, describeCommand, the publish and long-poll routes, the refusals); the formcite skill tells an agent which tool fits which request and when to run a window command so the person sees it; the README's agents list says what an agent can now do and what stays the person's. --- .claude/skills/formcite/SKILL.md | 8 +++++++- README.md | 1 + docs/MCP.md | 29 +++++++++++++++++++++++++++++ docs/WINDOW.md | 9 +++++++++ 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/.claude/skills/formcite/SKILL.md b/.claude/skills/formcite/SKILL.md index 6699ab1..ac24761 100644 --- a/.claude/skills/formcite/SKILL.md +++ b/.claude/skills/formcite/SKILL.md @@ -21,6 +21,8 @@ Two ways, in this order of preference. - 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; `keywords_as_tags` only when the person asked for keywords as tags), `tag_item`. + - Everything else a person does, from 0.16.0: `edit_item` (any field), `trash_items`, `restore_items`, `list_trash`, `delete_items_forever` and `empty_trash` (both need `confirm: true`), notes (`list_notes`, `add_note`, `edit_note`, `delete_note`), tags (`untag_item`, `rename_tag`, `delete_tag`), attachments (`list_attachments` gives the PDF's path on disk to read, `attach_file`, `remove_attachment`, `get_fulltext`, `fetch_pdf`, `add_pdf`), relations, saved searches (`run_search`, `save_search` and the rest), `find_duplicates`, `merge_duplicates`, `export_references`, `import_file`, `list_import_batches`, `undo_import`, `keywords_to_tags`, libraries (`list_libraries`, `create_library`, `use_library`), the Needs a title tools and `network_status` (read-only). The collection tools come with the collection slice. + - The open window: `window_commands` lists what the window offers (views, select an item, search, sort and scope of the list, the paper reader with `item.view`, Preferences, appearance, the Add dialog, collections), each with typed arguments, and `window_command_run` runs one where the person sees it. Use it when the person wants to see something in FormCite ("show me", "open the paper", "switch to dark"); use the headless tools for the data. These need the engine's `/mcp` (the dock's agent tabs have it) and an open window; when `window_commands` says the window is not open, say so and carry on headless. 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. @@ -37,8 +39,12 @@ If the MCP tool list has fewer tools than a task needs, use the command line for | 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 | +| Duplicates | MCP `find_duplicates`, or `cli duplicates` (find) | MCP `merge_duplicates`, or merging | | Tag, collect, note | `cli tag`, `cli collection`, `cli note` listings | any change | +| Edit a field, trash, restore | MCP `get_item` | MCP `edit_item`, `trash_items`, `restore_items` | +| Delete for good, empty the Trash | MCP `list_trash` | MCP `delete_items_forever` or `empty_trash` with `confirm: true`, after the person said yes to exactly that | +| Read the paper | MCP `get_fulltext` or `list_attachments` (the PDF's path) | MCP `fetch_pdf` (network) when there is none | +| Show it to me in FormCite | MCP `window_commands` | MCP `window_command_run`, such as `item.view` or `list.scope` | ## What needs the person's say diff --git a/README.md b/README.md index 5fb3036..8f227ab 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,7 @@ The window, the command line, the cite service and the MCP server all work on th - Agents use the MCP server: `./formcite mcp` (read-only unless you start it with `--allow-write`), or `POST /mcp` on the running engine with a token ([`docs/MCP.md`](docs/MCP.md)). `./formcite agents install` registers it with the agent clients it knows; `--dry-run` shows what it would write. - `./formcite cli service log` shows everything a token holder added. - From 0.15.0 the window has an agent dock (View, Agent Dock): shell tabs the engine starts on this computer, and a tab for Claude Code, Codex, Cursor or Antigravity when that program is installed. Each agent tab gets its own token, which is revoked when the tab closes. Only the FormCite window can open one. The dock asks no question of its own: an outside agent is approved by pairing under Connections, as above. +- From 0.16.0 an agent can do what you can: edit any field, notes, tags, attachments and PDFs, the Trash, duplicates, saved searches, import and export, libraries, and run the window's own commands (views, selection, search, sort, the paper reader, Preferences, appearance) with `window_commands` and `window_command_run`, so you watch it happen in the window. Deleting for good asks first. Approving connections and the network switches stay yours. See [`AGENTS.md`](AGENTS.md). diff --git a/docs/MCP.md b/docs/MCP.md index 301bd11..3264493 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -55,6 +55,35 @@ The two network tools go through FormCite's network layer, so they obey the pers Without `--allow-write`, `tools/list` does not show the four write tools, and a `tools/call` to one of them answers a tool error: "The tool add_item changes the library, and this FormCite server was started read-only. Ask the person to start it with --allow-write." +### Everything else a person does (0.16.0) + +An agent can do in FormCite what a person can. The tools in `backend/app/mcp/tools_parity.py` cover the rest of the library, and three of them run the open window's own commands. A permanent delete carries `destructiveHint: true`, so a client asks the person first, and `delete_items_forever` and `empty_trash` also need `confirm: true`. + +| Tool | Read-only | What it does | +| - | - | - | +| `edit_item` | no | change any field (`fields`) or replace the record (`csl`) | +| `trash_items`, `restore_items`, `list_trash` | no, no, yes | the Trash, as Move to Trash and Restore do | +| `delete_items_forever`, `empty_trash` | no, destructive | delete for good (`confirm: true`) | +| `list_notes`, `add_note`, `edit_note`, `delete_note` | yes, no, no, destructive | an item's notes | +| `untag_item`, `rename_tag`, `delete_tag` | no, no, destructive | tags (a tag by id or name) | +| `list_attachments`, `attach_file`, `remove_attachment` | yes, no, destructive | attachments with their paths on disk; copy or link a file | +| `get_fulltext`, `fetch_pdf`, `add_pdf` | yes, no, no | where the PDF is; fetch it from arXiv; add a PDF by the identifier in it (the last two reach the network) | +| `list_relations`, `relate_items`, `unrelate_items` | yes, no, no | related and cites links | +| `list_saved_searches`, `run_search`, `save_search`, `edit_saved_search`, `delete_saved_search` | yes, yes, no, no, destructive | saved and rule searches | +| `find_duplicates`, `merge_duplicates` | yes, destructive | the Duplicates view | +| `export_references` | yes | BibTeX, RIS, CSL-JSON or FormTxt of ids, a collection, a tag or the library | +| `import_file`, `list_import_batches`, `undo_import`, `keywords_to_tags` | no, yes, destructive, no | imports and their batches | +| `list_libraries`, `create_library`, `use_library` | yes, no, no | libraries; the window follows a switch | +| `list_untitled`, `title_suggestions`, `title_lookup` | yes | the Needs a title view (`title_lookup` reaches the network) | +| `network_status` | yes | the network switches and recent calls; only the person turns the switches | +| `window_commands` | yes | the commands the open window offers, each with typed arguments | +| `window_command_run` | no | run one in the window, where the person sees it; answers when it finished or a run id | +| `window_command_result` | yes | the state and result of a run | + +Collections (create, rename, delete, file and unfile items, batch add) are their own tools, listed with the collection slice. + +The window commands are what a person does with menus, buttons and right-click menus: every view, selecting and revealing an item, search, sort and scope of the list, the reader (`item.view`), copying a citation, Preferences at a section, appearance, theme and accent, switching library, the Add dialog, and the collection commands. `window_commands` lists them with their arguments, such as `list.sort(key: title|creator|year|type|added|updated, desc?: boolean)`; `window_command_run` with `{"command": "list.sort", "args": {"key": "year", "desc": true}}` runs one and answers what the window shows afterwards (view, scope, search, sort, selection and counts). They need the engine's `/mcp` with a token that may write, which is what the dock's agent tabs get, and an open window; over stdio, or with the window closed, `window_commands` says so and the headless tools still work. The approvals under Connections, the network switches, the token store, the clipboard edit commands and Close Window are never offered, whatever the token. How the bridge works is in [WINDOW.md](WINDOW.md). + ## Results and errors A tool result holds a short plain text block a model can read (an item line is `id · first author (year) title`; a citation or bibliography is its formatted text), a second text block with the same data as JSON, and `structuredContent` with the service's own answer. diff --git a/docs/WINDOW.md b/docs/WINDOW.md index fac388f..8a0f1d0 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -84,3 +84,12 @@ Live changes come from `GET /api/changes/stream?since=SEQ&lib=NAME`, a server-se ## 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). + +## Agents drive the window + +An agent can do in the window what a person does with menus, buttons and right-click menus, and the person sees each step as it happens. The MCP tools `window_commands`, `window_command_run` and `window_command_result` reach the window through a bridge in the engine (see [MCP.md](MCP.md)). + +- The window registers each action as a command in its command registry. `frontend/src/ui/parity.ts` adds the ones that had none (`item.select`, `list.search`, `list.sort`, `list.scope`, `view.show`, `view.titles`, `prefs.open`, `prefs.close`, `appearance.mode`, `appearance.theme`, `appearance.accent`, `prefs.home-at-launch`, `prefs.title-field`, `library.use`, `add.identifier`, `add.close`, `window.minimize`, `window.zoom`) and gives each offered command its typed arguments with `describeCommand(id, { args, write, group })` from `frontend/src/engine/bridge.ts`. A command that is not described is not offered. +- `frontend/src/io/bridge.ts` publishes the offered commands to `PUT /api/window/commands` and long-polls `GET /api/window/commands/next?wait=20`; it runs each command it receives and posts `{ok, result, error}` to `POST /api/window/commands/runs/{id}`. The result is what the window shows afterwards: view, scope, search, sort, selection and counts. All three routes need the window key; `GET /api/window/commands` lists the catalogue for the window itself. +- The engine (`backend/app/services/window_bridge.py`) checks every run against the published argument types, keeps runs for a minute and answers "the window is not open" when the window has not polled for 45 seconds. Connections, the network switches, the token store, the clipboard edit commands and Close Window are refused by the engine and the window alike, whatever the window publishes. +- Changes an agent makes through the headless tools reach the window through the changes stream above. From 81010acb77c98d572c3caee907a7b7c8ca6e3cfb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:50:15 -0500 Subject: [PATCH 13/36] fix(net): one polite pace for all of arXiv, and retries with backoff on 429 and 503 (0.16.0) A service can now name a pace group, and every service in one group waits its turn on one clock, so a lookup on export.arxiv.org, the OAI fallback on oaipmh.arxiv.org and a PDF download from arxiv.org together keep to arXiv's one request every three seconds instead of three separate clocks. An answer of 429 or 503 is retried twice: the wait is the server's Retry-After when it gives whole seconds, else 4 s then 8 s, at most 20 s, and it holds the whole group so no other call jumps in. Every attempt is still in Recent calls. --- backend/app/net/fetch.py | 34 +++++++++++++++++++++++++--------- backend/app/net/pace.py | 14 ++++++++++---- backend/app/net/services.py | 9 +++++++-- 3 files changed, 42 insertions(+), 15 deletions(-) diff --git a/backend/app/net/fetch.py b/backend/app/net/fetch.py index 0b51e1a..5256048 100644 --- a/backend/app/net/fetch.py +++ b/backend/app/net/fetch.py @@ -18,6 +18,16 @@ CHUNK = 1024 * 1024 MAX_REDIRECTS = 3 REDIRECTS = (301, 302, 303, 307, 308) +RETRIES = 2 +RETRY_STATUS = (429, 503) +BACKOFF_SECONDS = 4.0 +MOST_WAIT_SECONDS = 20.0 + + +def _backoff(exc: Exception, attempt: int) -> float: + said = str(getattr(exc, "retry_after", "") or "").strip() + wait = float(said) if said.isdigit() else BACKOFF_SECONDS * (2 ** attempt) + return min(wait, MOST_WAIT_SECONDS) def user_agent() -> str: @@ -118,17 +128,21 @@ def _request( url = _with_params(url, params) _check_url(service, url) switches.check(service.name) - pace.wait_turn(service.name, service.interval) sent = {"User-Agent": user_agent(), "Accept": accept, "Accept-Encoding": "gzip" if read is None else "identity"} sent.update(headers or {}) - started = time.monotonic() status: int | None = None - hops: list[str] = [url] - try: - body, charset, status = _call(service, url, sent, timeout, read or _read, hosts, hops) - except (Invalid, NotFound) as exc: - calllog.record(service.name, hops[-1], status=status or getattr(exc, "status", None), error=str(exc), ms=(time.monotonic() - started) * 1000) - raise + for attempt in range(RETRIES + 1): + pace.wait_turn(service.pace_key, service.interval) + started = time.monotonic() + hops: list[str] = [url] + try: + body, charset, status = _call(service, url, sent, timeout, read or _read, hosts, hops) + break + except (Invalid, NotFound) as exc: + calllog.record(service.name, hops[-1], status=status or getattr(exc, "status", None), error=str(exc), ms=(time.monotonic() - started) * 1000) + if attempt >= RETRIES or getattr(exc, "status", None) not in RETRY_STATUS: + raise + pace.hold(service.pace_key, _backoff(exc, attempt)) calllog.record(service.name, hops[-1], status=status, error=None, ms=(time.monotonic() - started) * 1000) return body, charset @@ -172,7 +186,9 @@ def _call( def _from_status(service: services.Service, exc: urllib.error.HTTPError) -> Exception: if exc.code == 404: return _with_status(RemoteNotFound(f"{service.name} has no record at that address (404)."), 404) - return _with_status(NetworkError(f"{service.name} answered with status {exc.code} {exc.reason}."), exc.code) + failed = _with_status(NetworkError(f"{service.name} answered with status {exc.code} {exc.reason}."), exc.code) + failed.retry_after = exc.headers.get("Retry-After") if exc.headers else None + return failed def _once(service: services.Service, url: str, sent: dict, timeout: float, read: Callable[[Any], Any]) -> tuple[Any, str, int]: diff --git a/backend/app/net/pace.py b/backend/app/net/pace.py index 9aabaa6..871327e 100644 --- a/backend/app/net/pace.py +++ b/backend/app/net/pace.py @@ -3,6 +3,7 @@ _LOCKS: dict[str, threading.Lock] = {} _LAST: dict[str, float] = {} +_HOLD: dict[str, float] = {} _GUARD = threading.Lock() @@ -14,8 +15,13 @@ def _lock_for(name: str) -> threading.Lock: def wait_turn(name: str, interval: float) -> None: with _lock_for(name): last = _LAST.get(name) - if last is not None: - gap = interval - (time.monotonic() - last) - if gap > 0: - time.sleep(gap) + ready = max(last + interval if last is not None else 0.0, _HOLD.get(name, 0.0)) + gap = ready - time.monotonic() + if gap > 0: + time.sleep(gap) _LAST[name] = time.monotonic() + + +def hold(name: str, seconds: float) -> None: + with _GUARD: + _HOLD[name] = max(_HOLD.get(name, 0.0), time.monotonic() + max(0.0, seconds)) diff --git a/backend/app/net/services.py b/backend/app/net/services.py index e0ef021..9c91c00 100644 --- a/backend/app/net/services.py +++ b/backend/app/net/services.py @@ -11,19 +11,24 @@ class Service: purpose: str docs: str interval: float = 1.0 + group: str = "" + + @property + def pace_key(self) -> str: + return self.group or self.name _LOCK = threading.Lock() _SERVICES: dict[str, Service] = {} -def register(name: str, host: str, purpose: str, docs: str, *, interval: float = 1.0) -> None: +def register(name: str, host: str, purpose: str, docs: str, *, interval: float = 1.0, group: str = "") -> None: name = name.strip() host = host.strip().lower() if not name or not host or "/" in host or ":" in host: raise Invalid(f"A service needs a name and a bare host name, not {host!r}.") with _LOCK: - _SERVICES[name] = Service(name, host, purpose.strip(), docs.strip(), max(0.0, float(interval))) + _SERVICES[name] = Service(name, host, purpose.strip(), docs.strip(), max(0.0, float(interval)), group.strip()) def get(name: str) -> Service: From aeba3caa25ca8a8f099b85e9272f960d068df16f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:50:28 -0500 Subject: [PATCH 14/36] feat(lookup): queued lookups, arXiv ids fetched together, a lookup cache and an add that never doubles (0.16.0) services/lookup_jobs.py is a queue of lookup jobs with one worker for records and one for arXiv PDFs. A job holds up to 50 identifiers; its arXiv ids are asked for in one id_list query (arxiv.fetch_many), the records go into a one-hour cache in lookup.resolve, and each identifier then goes through lookup.add with the PDF left to the second worker, so records never wait behind downloads. A job can file every item into a collection and tag it. The same identifiers sent again while their job is unfinished join that job instead of queueing a second one. lookup.add now checks for a duplicate and creates the item under one lock, so two calls for the same paper at once make one item and the second reports it as existing. add takes fetch_pdf so the queue can attach PDFs later. --- backend/app/lookup/__init__.py | 37 ++++- backend/app/lookup/arxiv.py | 31 ++++ backend/app/services/lookup.py | 9 +- backend/app/services/lookup_jobs.py | 218 ++++++++++++++++++++++++++++ 4 files changed, 291 insertions(+), 4 deletions(-) create mode 100644 backend/app/services/lookup_jobs.py diff --git a/backend/app/lookup/__init__.py b/backend/app/lookup/__init__.py index 76afc7c..cf844a9 100644 --- a/backend/app/lookup/__init__.py +++ b/backend/app/lookup/__init__.py @@ -1,4 +1,7 @@ +import copy import importlib +import threading +import time from types import ModuleType from app.lookup.guess import guess @@ -7,6 +10,10 @@ MODULES = ("doi", "arxiv", "isbn", "pubmed") KINDS: dict[str, ModuleType | None] = {name: None for name in MODULES} ALIASES = {"pmid": "pubmed", "pubmed": "pubmed", "doi": "doi", "arxiv": "arxiv", "isbn": "isbn"} +CACHE_SECONDS = 3600.0 +CACHE_MOST = 500 +_CACHE: dict[tuple[str, str], tuple[float, dict]] = {} +_CACHE_LOCK = threading.Lock() def _load(kind: str) -> ModuleType | None: @@ -51,6 +58,31 @@ def get(kind: str) -> ModuleType: return module +def _cache_key(key: str, value: str) -> tuple[str, str]: + return key, str(get(key).clean(value)) + + +def remember(key: str, value: str, record: dict) -> None: + with _CACHE_LOCK: + _CACHE[_cache_key(key, value)] = (time.monotonic(), copy.deepcopy(record)) + while len(_CACHE) > CACHE_MOST: + _CACHE.pop(next(iter(_CACHE))) + + +def _cached(key: str, value: str) -> dict | None: + with _CACHE_LOCK: + held = _CACHE.get(_cache_key(key, value)) + if held is None or time.monotonic() - held[0] > CACHE_SECONDS: + return None + return copy.deepcopy(held[1]) + + +def identify(text: str) -> tuple[str, str]: + key, value = guess(text) + get(key) + return key, value + + def resolve(text: str, kind: str | None = None) -> dict: if kind: module = get(kind) @@ -59,7 +91,10 @@ def resolve(text: str, kind: str | None = None) -> dict: else: key, value = guess(text) module = get(key) - record = module.fetch(value) + record = _cached(key, value) + if record is None: + record = module.fetch(value) + remember(key, value, record) return { "record": record, "source": {"kind": key, "value": value, "services": list(getattr(module, "SERVICES", ()))}, diff --git a/backend/app/lookup/arxiv.py b/backend/app/lookup/arxiv.py index eb7f605..d8f00f6 100644 --- a/backend/app/lookup/arxiv.py +++ b/backend/app/lookup/arxiv.py @@ -20,6 +20,8 @@ PDF_URL = f"https://{PDF_HOST}/pdf/" ABS_URL = f"https://{PDF_HOST}/abs/" INTERVAL_SECONDS = 3.0 +PACE_GROUP = "arxiv.org" +BATCH_MOST = 50 net.register( SERVICE, @@ -27,6 +29,7 @@ "Look up a preprint's title, authors, dates, abstract and categories by its arXiv identifier.", "https://info.arxiv.org/help/api/user-manual.html", interval=INTERVAL_SECONDS, + group=PACE_GROUP, ) net.register( OAI_SERVICE, @@ -34,6 +37,7 @@ "Look up the same preprint record from arXiv's OAI-PMH service when arXiv's search API refuses or is busy.", "https://info.arxiv.org/help/oa/index.html", interval=INTERVAL_SECONDS, + group=PACE_GROUP, ) net.register( PDF_SERVICE, @@ -41,6 +45,7 @@ "Download a preprint's open-access PDF from arXiv to attach it to the item, only while the arxiv service is also on.", "https://info.arxiv.org/help/bulk_data.html", interval=INTERVAL_SECONDS, + group=PACE_GROUP, ) __all__ = ["KIND", "SERVICES", "clean", "fetch"] @@ -82,3 +87,29 @@ def fetch(value: str) -> dict: record = normalize(to_csl(entry, identifier)) validate(record) return record + + +def fetch_many(values: list[str]) -> dict[str, dict]: + wanted: list[str] = [] + for value in values: + try: + identifier = clean(value) + except Invalid: + continue + if identifier not in wanted: + wanted.append(identifier) + found: dict[str, dict] = {} + for start in range(0, len(wanted), BATCH_MOST): + chunk = wanted[start:start + BATCH_MOST] + try: + answer = parse(net.fetch_text(SERVICE, QUERY_URL, params={"id_list": ",".join(chunk), "max_results": str(len(chunk))}, timeout=20.0)) + except (net.NetworkError, Invalid): + continue + for identifier in chunk: + try: + record = normalize(to_csl(_pick(answer["entries"], identifier), identifier)) + validate(record) + except (Invalid, NotFound): + continue + found[identifier] = record + return found diff --git a/backend/app/services/lookup.py b/backend/app/services/lookup.py index b661e4a..731eef4 100644 --- a/backend/app/services/lookup.py +++ b/backend/app/services/lookup.py @@ -1,3 +1,5 @@ +import threading + from app import lookup from app.services import duplicates, fulltext from app.services.library import detail, session @@ -5,6 +7,7 @@ from app.store.errors import Invalid ON_DUPLICATE = ("skip", "add") +_ADDING = threading.Lock() def _brief(conn, item_ids: list[str]) -> list[dict]: @@ -25,12 +28,12 @@ def preview(text: str, kind: str | None = None) -> dict: return {**found, "duplicates": _brief(conn, matches)} -def add(text: str, *, on_duplicate: str = "skip", kind: str | None = None) -> dict: +def add(text: str, *, on_duplicate: str = "skip", kind: str | None = None, fetch_pdf: bool = True) -> dict: if on_duplicate not in ON_DUPLICATE: raise Invalid(f"on_duplicate must be one of {', '.join(ON_DUPLICATE)}") found = lookup.resolve(text, kind) source = found["source"] - with session() as (_, conn): + with _ADDING, session() as (_, conn): if on_duplicate == "skip": matches = duplicates.find_for(conn, found["record"]) if matches: @@ -39,7 +42,7 @@ def add(text: str, *, on_duplicate: str = "skip", kind: str | None = None) -> di with db.tx(conn): batch = batches.create(conn, source["kind"], source["value"]) made = items.create(conn, found["record"], batch_id=batch["id"]) - pdf = fulltext.try_fetch_pdf(made["id"]) if source["kind"] == "arxiv" else None + pdf = fulltext.try_fetch_pdf(made["id"]) if source["kind"] == "arxiv" and fetch_pdf else None with session() as (_, conn): return {"added": True, "duplicate_of": None, "batch_id": batch["id"], "item": detail(conn, made["id"]), "source": source, "pdf": pdf} diff --git a/backend/app/services/lookup_jobs.py b/backend/app/services/lookup_jobs.py new file mode 100644 index 0000000..3d3708f --- /dev/null +++ b/backend/app/services/lookup_jobs.py @@ -0,0 +1,218 @@ +import queue +import threading +import time +from dataclasses import dataclass, field + +from app import lookup +from app.services import fulltext, library +from app.services import lookup as adding +from app.store.db import new_id +from app.store.errors import Invalid, NotFound + +MOST_IDS = 50 +KEEP_JOBS = 200 +WAIT_SECONDS = 20.0 +KINDS = ("add", "preview") +FINISHED = ("added", "existing", "found", "failed") + + +@dataclass +class Job: + id: str + kind: str + rows: list[dict] + on_duplicate: str = "skip" + collection_id: str | None = None + tags: list[str] = field(default_factory=list) + state: str = "queued" + created: float = field(default_factory=time.time) + records: threading.Event = field(default_factory=threading.Event) + done: threading.Event = field(default_factory=threading.Event) + + +_JOBS: dict[str, Job] = {} +_QUEUE: "queue.Queue[Job]" = queue.Queue() +_PDF_QUEUE: "queue.Queue[Job]" = queue.Queue() +_LOCK = threading.Lock() +_WORKER: list[threading.Thread] = [] + + +def _clean_ids(identifiers: list[str]) -> list[str]: + out: list[str] = [] + for raw in identifiers: + text = str(raw or "").strip() + if text and text not in out: + out.append(text) + if not out: + raise Invalid("give at least one identifier") + if len(out) > MOST_IDS: + raise Invalid(f"give at most {MOST_IDS} identifiers in one call; send the rest in another call") + return out + + +def _same_waiting(kind: str, ids: list[str], collection_id: str | None, tags: list[str]) -> Job | None: + for job in _JOBS.values(): + if job.kind == kind and job.state != "done" and [r["identifier"] for r in job.rows] == ids \ + and job.collection_id == collection_id and job.tags == tags: + return job + return None + + +def _ensure_worker() -> None: + if _WORKER and all(w.is_alive() for w in _WORKER): + return + _WORKER[:] = [threading.Thread(target=_work, name="formcite-lookups", daemon=True), + threading.Thread(target=_work_pdfs, name="formcite-lookup-pdfs", daemon=True)] + for worker in _WORKER: + worker.start() + + +def _forget_old() -> None: + done = [j for j in _JOBS.values() if j.state == "done"] + for job in sorted(done, key=lambda j: j.created)[: max(0, len(_JOBS) - KEEP_JOBS)]: + _JOBS.pop(job.id, None) + + +def submit(kind: str, identifiers: list[str], *, on_duplicate: str = "skip", collection_id: str | None = None, + tags: list[str] | None = None) -> Job: + if kind not in KINDS: + raise Invalid(f"kind must be one of {', '.join(KINDS)}") + if on_duplicate not in adding.ON_DUPLICATE: + raise Invalid(f"on_duplicate must be one of {', '.join(adding.ON_DUPLICATE)}") + ids = _clean_ids(identifiers) + wanted_tags = [t.strip() for t in tags or [] if str(t).strip()] + with _LOCK: + held = _same_waiting(kind, ids, collection_id, wanted_tags) + if held is not None: + return held + _forget_old() + job = Job(new_id(), kind, [{"identifier": i, "status": "queued"} for i in ids], on_duplicate, collection_id, wanted_tags) + _JOBS[job.id] = job + _ensure_worker() + _QUEUE.put(job) + return job + + +def get(job_id: str) -> Job: + job = _JOBS.get(str(job_id or "").strip()) + if job is None: + raise NotFound(f"lookup job {job_id}; jobs are kept until FormCite's engine restarts") + return job + + +def wait(job: Job, seconds: float) -> Job: + job.records.wait(max(0.0, min(seconds, WAIT_SECONDS))) + return job + + +def ahead_of(job: Job) -> int: + with _LOCK: + return sum(len(j.rows) for j in _JOBS.values() if j.state != "done" and j.created < job.created) + + +def _prefetch(job: Job) -> None: + arxiv_values = [] + for row in job.rows: + try: + key, value = lookup.identify(row["identifier"]) + except Invalid as exc: + row.update(status="failed", error=str(exc)) + continue + if key == "arxiv": + arxiv_values.append(value) + if len(arxiv_values) < 2: + return + module = lookup.get("arxiv") + for value, record in module.fetch_many(arxiv_values).items(): + lookup.remember("arxiv", value, record) + + +def _file(job: Job, item_id: str) -> None: + if job.collection_id: + library.collection_add(job.collection_id, [item_id]) + if job.tags: + library.tag_add(item_id, job.tags) + + +def _one(job: Job, row: dict) -> None: + row["status"] = "working" + try: + if job.kind == "preview": + out = adding.preview(row["identifier"]) + dupes = out.get("duplicates") or [] + row.update(status="found", record=out.get("record") or {}, existing=dupes[0]["id"] if dupes else None) + return + out = adding.add(row["identifier"], on_duplicate=job.on_duplicate, fetch_pdf=False) + item = out["item"] + row.update(status="added" if out.get("added") else "existing", item=item, + kind=(out.get("source") or {}).get("kind")) + try: + _file(job, item["id"]) + if job.collection_id or job.tags: + row["item"] = library.item_show(item["id"]) + except (Invalid, NotFound) as exc: + row["filing_error"] = str(exc) + except (Invalid, NotFound) as exc: + row.update(status="failed", error=str(exc)) + except Exception as exc: + row.update(status="failed", error=f"FormCite failed inside ({type(exc).__name__})") + + +def _pdfs(job: Job) -> None: + for row in job.rows: + if row.get("status") != "added" or row.get("kind") != "arxiv": + continue + row["pdf"] = "attaching" + got = fulltext.try_fetch_pdf(row["item"]["id"]) + row["pdf"] = "attached" if got.get("attached") else f"not attached: {got.get('error') or 'unknown reason'}" + + +def _finish(job: Job) -> None: + job.state = "done" + job.records.set() + job.done.set() + + +def _run(job: Job) -> None: + job.state = "running" + try: + _prefetch(job) + for row in job.rows: + if row["status"] == "queued": + _one(job, row) + finally: + job.records.set() + if job.kind == "add" and any(r["status"] == "added" and r.get("kind") == "arxiv" for r in job.rows): + job.state = "attaching_pdfs" + for row in job.rows: + if row["status"] == "added" and row.get("kind") == "arxiv": + row["pdf"] = "queued" + _PDF_QUEUE.put(job) + return + _finish(job) + + +def _drain(source: "queue.Queue[Job]", step) -> None: + while True: + job = source.get() + try: + step(job) + except Exception: + _finish(job) + finally: + source.task_done() + + +def _attach(job: Job) -> None: + try: + _pdfs(job) + finally: + _finish(job) + + +def _work() -> None: + _drain(_QUEUE, _run) + + +def _work_pdfs() -> None: + _drain(_PDF_QUEUE, _attach) From f9f2369ce022b4a3a2ca3695d2ea8d47ca7acba9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:50:31 -0500 Subject: [PATCH 15/36] fix(mcp): a call over HTTP answers inside its 30 s, however many arrive at once (0.16.0) Calls to /mcp ran on asyncio's default thread pool, a handful of threads on a small machine, and the 30 s limit counted the time a call sat waiting for a thread. Twenty parallel lookups therefore all ran out together. /mcp now has its own pool of 64 threads, the limit counts from when the request arrived, and the arrival time travels with the call in a context variable so a tool can ask http.budget how long it may still wait, leaving 8 s to answer. --- backend/app/mcp/http.py | 13 +++++++++++++ backend/app/routers/mcp_http.py | 12 +++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/backend/app/mcp/http.py b/backend/app/mcp/http.py index 14d8867..25a8414 100644 --- a/backend/app/mcp/http.py +++ b/backend/app/mcp/http.py @@ -1,4 +1,6 @@ import json +import time +from contextvars import ContextVar from urllib.parse import urlsplit from app.core.local_guard import LOOPBACK @@ -9,6 +11,17 @@ SESSION_HEADER = "mcp-session-id" MAX_BODY = 1024 * 1024 CALL_SECONDS = 30.0 +ANSWER_MARGIN = 8.0 +WORKERS = 64 +ARRIVED: ContextVar[float | None] = ContextVar("formcite_mcp_arrived", default=None) + + +def budget(asked: float) -> float: + arrived = ARRIVED.get() + if arrived is None: + return asked + left = CALL_SECONDS - ANSWER_MARGIN - (time.monotonic() - arrived) + return max(0.0, min(asked, left)) PARSE_ERROR = -32700 INVALID_REQUEST = -32600 diff --git a/backend/app/routers/mcp_http.py b/backend/app/routers/mcp_http.py index 106d0f7..cb6c534 100644 --- a/backend/app/routers/mcp_http.py +++ b/backend/app/routers/mcp_http.py @@ -1,4 +1,8 @@ import asyncio +import contextvars +import functools +import time +from concurrent.futures import ThreadPoolExecutor from fastapi import APIRouter, Request from fastapi.responses import JSONResponse, Response @@ -9,6 +13,7 @@ GROUP = "mcp" PATH = "/mcp" router = APIRouter(tags=[GROUP]) +_POOL = ThreadPoolExecutor(max_workers=http.WORKERS, thread_name_prefix="formcite-mcp") def _refusal(status: int, message: str, headers: dict | None = None) -> JSONResponse: @@ -43,6 +48,7 @@ async def _body(request: Request) -> bytes: @router.post(PATH) async def mcp_post(request: Request) -> Response: + arrived = time.monotonic() caller = _caller(request) if isinstance(caller, JSONResponse): return caller @@ -55,8 +61,12 @@ async def mcp_post(request: Request) -> Response: return _rpc_error(exc) if "method" not in message: return Response(status_code=http.ACCEPTED) + http.ARRIVED.set(arrived) + context = contextvars.copy_context() + work = functools.partial(context.run, protocol.handle, message, allow_write=caller.scope == "write") try: - answer = await asyncio.wait_for(asyncio.to_thread(protocol.handle, message, allow_write=caller.scope == "write"), http.CALL_SECONDS) + left = max(0.1, http.CALL_SECONDS - (time.monotonic() - arrived)) + answer = await asyncio.wait_for(asyncio.get_running_loop().run_in_executor(_POOL, work), left) except asyncio.TimeoutError: answer = http.error(message.get("id"), http.INTERNAL_ERROR, http.too_slow(http.CALL_SECONDS)) if http.is_request(message) else None if answer is None: From 1a62ebc9da53726c6970752a15197674b6def930 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:50:38 -0500 Subject: [PATCH 16/36] feat(mcp): collection tools, a batch add, lookup jobs and compact answers (0.16.0) New tools: create_collection (name, optional parent; answers the one already there instead of a second), add_to_collection, remove_from_collection, rename_collection and delete_collection over the library service's existing collection functions, each taking a collection id or its exact name. delete_collection carries destructiveHint, so the agent client asks the person, needs confirm equal to the collection's exact name, refuses a collection with sub-collections, and leaves the items in the library. add_by_identifiers takes up to 50 identifiers with an optional collection and tags; add_by_identifier and lookup_preview go through the same queue; every one answers within wait_seconds (default 20, capped by the HTTP budget) and leaves a job_id for the new lookup_status when unfinished. Items now come back compact: id, title, year, an authors summary with the count, identifiers (doi, arXiv, ISBN, PMID, url), tags and collections. fields adds named parts such as abstract, full answers the stored item. One 200-author arXiv paper was 60,421 characters in full and is 774 now. list_items and search take offset, and list_items a collection name. The server instructions say plainly how to make collections, to batch lookups, and to say first when part of a request could not be done. --- backend/app/mcp/compact.py | 84 ++++++++++ backend/app/mcp/protocol.py | 9 +- backend/app/mcp/tools.py | 316 ++++++++++++++++++++++++++++++++---- 3 files changed, 380 insertions(+), 29 deletions(-) create mode 100644 backend/app/mcp/compact.py diff --git a/backend/app/mcp/compact.py b/backend/app/mcp/compact.py new file mode 100644 index 0000000..cec91e2 --- /dev/null +++ b/backend/app/mcp/compact.py @@ -0,0 +1,84 @@ +from app.lookup.arxiv_id import clean as arxiv_clean +from app.store.errors import Invalid + +NAMES_SHOWN = 3 +EXTRA_FIELDS = ("abstract", "container_title", "issued", "type", "url", "csl", "creators", "notes", "attachments", + "relations", "snippet", "created_at", "updated_at", "batch_id") +FIELDS_SCHEMA = { + "type": "array", + "items": {"type": "string", "enum": list(EXTRA_FIELDS)}, + "description": "Extra fields to include beyond the compact default (id, title, year, authors, identifiers, tags, collections), such as [\"abstract\"].", +} +FULL_SCHEMA = {"type": "boolean", "description": "Answer the whole stored item (CSL record, every creator, abstract, notes, attachments). Large: only when the person needs it."} + + +def _name(person: dict) -> str: + return str(person.get("family") or person.get("literal") or person.get("given") or "").strip() + + +def authors(item: dict) -> tuple[str, int]: + people = [c for c in item.get("creators") or [] if c.get("role") in (None, "author")] + if not people: + people = list((item.get("csl") or {}).get("author") or []) + names = [n for n in (_name(p) for p in people) if n] + if not names: + return "", 0 + shown = ", ".join(names[:NAMES_SHOWN]) + more = len(names) - NAMES_SHOWN + return (f"{shown} and {more} more" if more > 0 else shown), len(names) + + +def _arxiv(item: dict) -> str | None: + csl = item.get("csl") or {} + for value in (csl.get("number"), item.get("url"), csl.get("URL")): + text = str(value or "") + if "arxiv" not in text.lower(): + continue + try: + return arxiv_clean(text) + except Invalid: + continue + return None + + +def identifiers(item: dict) -> dict: + csl = item.get("csl") or {} + found = { + "doi": item.get("doi") or csl.get("DOI"), + "arxiv": _arxiv(item), + "isbn": item.get("isbn") or csl.get("ISBN"), + "pmid": csl.get("PMID"), + "url": item.get("url") or csl.get("URL"), + } + return {k: v for k, v in found.items() if v} + + +def _tag_names(item: dict) -> list[str]: + return [t.get("name", "") if isinstance(t, dict) else str(t) for t in item.get("tags") or []] + + +def item(full_item: dict, fields: list[str] | None = None, full: bool = False) -> dict: + if full: + return full_item + who, count = authors(full_item) + out = { + "id": full_item.get("id"), + "title": full_item.get("title") or "", + "year": full_item.get("year"), + "authors": who, + "author_count": count, + "identifiers": identifiers(full_item), + "tags": _tag_names(full_item), + } + if "collections" in full_item: + out["collections"] = [{"id": c.get("id"), "name": c.get("name")} for c in full_item.get("collections") or []] + if full_item.get("attachment_count") is not None: + out["attachment_count"] = full_item.get("attachment_count") + for name in fields or []: + if name in EXTRA_FIELDS and name in full_item: + out[name] = full_item[name] + return out + + +def items(found: list[dict], fields: list[str] | None = None, full: bool = False) -> list[dict]: + return [item(i, fields, full) for i in found] diff --git a/backend/app/mcp/protocol.py b/backend/app/mcp/protocol.py index 20101ae..3ef8920 100644 --- a/backend/app/mcp/protocol.py +++ b/backend/app/mcp/protocol.py @@ -14,7 +14,14 @@ INSTRUCTIONS = ( "FormCite holds the person's reference library. Find items with search or list_items, " "then format them with cite or bibliography using the item ids. Write tools appear only " - "when the person allowed writing: --allow-write over stdio, or a token that may write over HTTP." + "when the person allowed writing: --allow-write over stdio, or a token that may write over HTTP. " + "Collections: make one with create_collection, fill it with add_to_collection (or pass collection to add_by_identifiers), " + "and check it with list_collections and list_items with collection. " + "Lookups by identifier are queued and rate limited (arXiv allows about one request every 3 seconds): " + "to add several papers send them in one add_by_identifiers call, never many parallel add_by_identifier or lookup_preview calls. " + "A lookup that is not finished answers a job_id; poll lookup_status and do not resend the identifiers. " + "Results are compact by default; ask for fields such as abstract, or full, only when needed. " + "When any part of the person's request could not be done, say so in the first line of the reply, before what was done." ) PARSE_ERROR = -32700 diff --git a/backend/app/mcp/tools.py b/backend/app/mcp/tools.py index 4cbc35e..6e42c9d 100644 --- a/backend/app/mcp/tools.py +++ b/backend/app/mcp/tools.py @@ -2,8 +2,9 @@ import sys from typing import Any, Callable -from app.services import formatting, library, lookup, transfer -from app.store import files, libraries +from app.mcp import compact, http +from app.services import formatting, library, lookup_jobs, transfer +from app.store import collections, files, libraries from app.store.errors import Invalid, NotFound TYPES = {"string": str, "integer": int, "array": list, "object": dict, "boolean": bool} @@ -50,29 +51,169 @@ def _items_text(result: dict) -> str: LIMIT = {"type": "integer", "minimum": 1, "maximum": 200, "description": "Most items to answer (default 20)."} +OFFSET = {"type": "integer", "minimum": 0, "maximum": 1000000, "description": "Items to skip first, for the next page (default 0)."} +SHAPE = {"fields": compact.FIELDS_SCHEMA, "full": compact.FULL_SCHEMA} + + +def _with_collections(found: list[dict]) -> list[dict]: + with library.session() as (_, conn): + for item in found: + if "collections" not in item: + item["collections"] = collections.for_item(conn, item["id"]) + return found + + +def _shaped(result: dict, args: dict) -> dict: + found = _with_collections(list(result.get("items") or [])) + return {**result, "items": compact.items(found, args.get("fields"), bool(args.get("full")))} def _search(args: dict) -> tuple[str, dict]: - result = library.search_text(args["text"], args.get("limit") or 20) - return _items_text(result), result + result = library.search_text(args["text"], args.get("limit") or 20, args.get("offset") or 0) + return _items_text(result), _shaped(result, args) def _get_item(args: dict) -> tuple[str, dict]: item = library.item_show(args["id"]) - return _line(item), item + return _line(item), compact.item(item, args.get("fields"), bool(args.get("full"))) def _list_items(args: dict) -> tuple[str, dict]: - result = library.item_list(collection_id=args.get("collection"), tag=args.get("tag"), limit=args.get("limit") or 20) - return _items_text(result), result + result = library.item_list(collection_id=_collection_id(args["collection"]) if args.get("collection") else None, + tag=args.get("tag"), limit=args.get("limit") or 20, offset=args.get("offset") or 0) + return _items_text(result), _shaped(result, args) + + +def _collection_line(c: dict, names: dict[str, str]) -> str: + parent = f", inside {names.get(c['parent_id'], c['parent_id'])}" if c.get("parent_id") else "" + return f"{c['id']} · {c['name']} ({c.get('item_count', 0)} items{parent})" def _list_collections(args: dict) -> tuple[str, dict]: found = library.collection_list(False) - lines = [f"{c['id']} · {c['name']}" for c in found] + names = {c["id"]: c["name"] for c in found} + lines = [_collection_line(c, names) for c in found] return "\n".join([f"{len(found)} collections."] + lines), {"collections": found} +def _find_collection(ref: str) -> dict: + wanted = str(ref or "").strip() + found = library.collection_list(False) + by_id = [c for c in found if c["id"] == wanted] + if by_id: + return by_id[0] + named = [c for c in found if c["name"].casefold() == wanted.casefold()] + if len(named) == 1: + return named[0] + if named: + raise Invalid(f"{len(named)} collections are named {wanted!r}; give the id instead: {', '.join(c['id'] for c in named)}") + raise NotFound(f"no collection has the id or name {wanted!r}; list_collections shows them all") + + +def _collection_id(ref: str) -> str: + return _find_collection(ref)["id"] + + +COLLECTION = {"type": "string", "description": "A collection id, or its exact name (case does not matter) when only one collection has it."} +ITEM_IDS = {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 500, "description": "Item ids."} + + +def _create_collection(args: dict) -> tuple[str, dict]: + parent = _collection_id(args["parent"]) if args.get("parent") else None + name = str(args["name"]).strip() + held = [c for c in library.collection_list(False) if c["parent_id"] == parent and c["name"].casefold() == name.casefold()] + if held: + return f"A collection named {held[0]['name']} is already there: {held[0]['id']}. Nothing new was made.", {"created": False, "collection": held[0]} + made = library.collection_new(name, parent) + return f"Created the collection {made['name']}: {made['id']}.", {"created": True, "collection": made} + + +def _add_to_collection(args: dict) -> tuple[str, dict]: + target = _find_collection(args["collection"]) + out = library.collection_add(target["id"], args["ids"]) + return f"{target['name']} ({target['id']}) now holds {out['item_count']} items.", {"collection": out} + + +def _remove_from_collection(args: dict) -> tuple[str, dict]: + target = _find_collection(args["collection"]) + out = library.collection_remove(target["id"], args["ids"]) + return f"{target['name']} ({target['id']}) now holds {out['item_count']} items. The items stay in the library.", {"collection": out} + + +def _rename_collection(args: dict) -> tuple[str, dict]: + target = _find_collection(args["collection"]) + out = library.collection_edit(target["id"], name=str(args["name"]).strip()) + return f"Renamed {target['name']} to {out['name']} ({out['id']}).", {"collection": out, "old_name": target["name"]} + + +def _delete_collection(args: dict) -> tuple[str, dict]: + target = _find_collection(args["collection"]) + if str(args["confirm"]).strip() != target["name"]: + raise Invalid(f"confirm must be the collection's exact name, {target['name']!r}, to delete it. " + "Ask the person first; nothing was deleted") + children = [c for c in library.collection_list(False) if c["parent_id"] == target["id"]] + if children: + raise Invalid(f"{target['name']} holds {len(children)} sub-collections ({', '.join(c['name'] for c in children)}); " + "delete or move those first. Nothing was deleted") + library.collection_delete(target["id"]) + return (f"Deleted the collection {target['name']} ({target['id']}). Its {target['item_count']} items stay in the library.", + {"deleted": True, "collection": target}) + + +COLLECTION_TOOLS: list[dict] = [ + { + "name": "create_collection", + "title": "Create a collection", + "description": "Make a new collection, optionally inside another. If one with the same name is already there, answers that one and makes nothing.", + "input_schema": _schema({"name": {"type": "string", "description": "The new collection's name."}, + "parent": {"type": "string", "description": "The id or exact name of the collection to put it in. Leave out for the top level."}}, + ("name",)), + "read_only": False, + "idempotent": True, + "run": _create_collection, + }, + { + "name": "add_to_collection", + "title": "Add items to a collection", + "description": "Put library items into a collection. Items already in it stay where they are.", + "input_schema": _schema({"collection": COLLECTION, "ids": ITEM_IDS}, ("collection", "ids")), + "read_only": False, + "idempotent": True, + "run": _add_to_collection, + }, + { + "name": "remove_from_collection", + "title": "Remove items from a collection", + "description": "Take items out of a collection. The items stay in the library and in their other collections.", + "input_schema": _schema({"collection": COLLECTION, "ids": ITEM_IDS}, ("collection", "ids")), + "read_only": False, + "idempotent": True, + "run": _remove_from_collection, + }, + { + "name": "rename_collection", + "title": "Rename a collection", + "description": "Give a collection a new name. Its items and place stay the same.", + "input_schema": _schema({"collection": COLLECTION, "name": {"type": "string", "description": "The new name."}}, ("collection", "name")), + "read_only": False, + "idempotent": True, + "run": _rename_collection, + }, + { + "name": "delete_collection", + "title": "Delete a collection", + "description": "Delete one collection that has no sub-collections. Its items stay in the library. Ask the person before using it, " + "and pass the collection's exact name as confirm.", + "input_schema": _schema({"collection": COLLECTION, + "confirm": {"type": "string", "description": "The collection's exact current name, as the person agreed to delete it."}}, + ("collection", "confirm")), + "read_only": False, + "destructive": True, + "run": _delete_collection, + }, +] + + def _list_tags(args: dict) -> tuple[str, dict]: found = library.tag_list() lines = [f"{t['name']} ({t['item_count']})" for t in found] @@ -162,24 +303,103 @@ def _record_line(record: dict) -> str: return f"{who} ({year or 'n.d.'}) {record.get('title') or 'untitled'}" +def _record_brief(record: dict) -> dict: + year = ((record.get("issued") or {}).get("date-parts") or [[None]])[0][0] + people = record.get("author") or record.get("editor") or [] + who, count = compact.authors({"csl": {"author": people}}) + return {"title": record.get("title") or "", "year": year, "authors": who, "author_count": count, + "identifiers": {k: v for k, v in (("doi", record.get("DOI")), ("number", record.get("number")), ("url", record.get("URL"))) if v}} + + +def _row_out(row: dict, args: dict) -> dict: + out = {"identifier": row["identifier"], "status": row["status"]} + if row.get("item"): + out["item"] = compact.item(row["item"], args.get("fields"), bool(args.get("full"))) + if row.get("record") is not None: + out["record"] = row["record"] if args.get("full") else _record_brief(row["record"]) + out["in_library_as"] = row.get("existing") + for key in ("pdf", "error", "filing_error"): + if row.get(key): + out[key] = row[key] + return out + + +def _job_out(job: lookup_jobs.Job, args: dict) -> dict: + counts: dict[str, int] = {} + for row in job.rows: + counts[row["status"]] = counts.get(row["status"], 0) + 1 + out = {"job_id": job.id, "kind": job.kind, "state": job.state, "counts": counts, + "rows": [_row_out(r, args) for r in job.rows]} + if job.state == "queued": + out["identifiers_ahead"] = lookup_jobs.ahead_of(job) + return out + + +def _row_line(row: dict) -> str: + if row.get("item"): + verb = "added" if row["status"] == "added" else "already in the library" + pdf = f", PDF {row['pdf']}" if row.get("pdf") else "" + return f"{row['identifier']}: {verb} as {_line(row['item'])}{pdf}" + if row.get("record") is not None: + held = f" Already in the library as {row['existing']}." if row.get("existing") else " Not in the library yet." + return f"{row['identifier']}: {_record_line(row['record'])}.{held}" + if row["status"] == "failed": + return f"{row['identifier']}: failed. {row.get('error') or ''}".rstrip() + return f"{row['identifier']}: {row['status']}" + + +def _job_text(job: lookup_jobs.Job) -> str: + unfinished = [r for r in job.rows if r["status"] not in lookup_jobs.FINISHED] + if unfinished: + head = (f"Not finished yet: {len(unfinished)} of {len(job.rows)} lookups are still queued or running (job {job.id}). " + f"Call lookup_status with job_id {job.id} in a few seconds; do not send these identifiers again.") + else: + failed = sum(1 for r in job.rows if r["status"] == "failed") + head = f"Done: {len(job.rows) - failed} of {len(job.rows)} lookups succeeded" + (f", {failed} failed." if failed else ".") + if job.state == "attaching_pdfs": + head += f" The items are in the library; their PDFs are being attached in the background (job {job.id})." + return "\n".join([head] + [_row_line(r) for r in job.rows]) + + +def _wait_for(args: dict) -> float: + asked = args.get("wait_seconds") + return http.budget(lookup_jobs.WAIT_SECONDS if asked is None else float(asked)) + + +def _job_answer(job: lookup_jobs.Job, args: dict) -> tuple[str, dict]: + lookup_jobs.wait(job, _wait_for(args)) + return _job_text(job), _job_out(job, args) + + def _lookup_preview(args: dict) -> tuple[str, dict]: - out = lookup.preview(args["identifier"]) - dupes = out.get("duplicates") or [] - tail = f" Already in the library as {dupes[0]['id']}." if dupes else " Not in the library yet." - return _record_line(out.get("record") or {}) + "." + tail, out + return _job_answer(lookup_jobs.submit("preview", [args["identifier"]]), args) def _add_item(args: dict) -> tuple[str, dict]: if not args.get("csl") and not args.get("fields"): raise Invalid("give csl (a CSL-JSON record) or fields (such as title, author, year)") item = library.item_add(args.get("fields"), args.get("csl")) - return "Added " + _line(item), item + return "Added " + _line(item), compact.item(item) def _add_by_identifier(args: dict) -> tuple[str, dict]: - out = lookup.add(args["identifier"], on_duplicate=args.get("on_duplicate") or "skip") - verb = "Added " if out.get("added") else "Already in the library: " - return verb + _line(out["item"]), out + job = lookup_jobs.submit("add", [args["identifier"]], on_duplicate=args.get("on_duplicate") or "skip") + return _job_answer(job, args) + + +def _add_by_identifiers(args: dict) -> tuple[str, dict]: + target = _collection_id(args["collection"]) if args.get("collection") else None + job = lookup_jobs.submit("add", args["identifiers"], on_duplicate=args.get("on_duplicate") or "skip", + collection_id=target, tags=args.get("tags")) + return _job_answer(job, args) + + +def _lookup_status(args: dict) -> tuple[str, dict]: + return _job_answer(lookup_jobs.get(args["job_id"]), {**args, "wait_seconds": args.get("wait_seconds") or 0}) + + +WAIT = {"type": "integer", "minimum": 0, "maximum": 20, "description": "Seconds to wait for the lookups before answering (default 20). " + "Unfinished lookups go on in the background; poll lookup_status with the job_id."} def _import_references(args: dict) -> tuple[str, dict]: @@ -201,12 +421,24 @@ def _tag_item(args: dict) -> tuple[str, dict]: { "name": "lookup_preview", "title": "Look up an identifier", - "description": "Fetch the record for a DOI, arXiv id, ISBN or PubMed ID from its public service without adding it, and say whether the library already holds it. Reaches the network only when the person's network switches allow that service.", - "input_schema": _schema({"identifier": IDENTIFIER}, ("identifier",)), + "description": "Fetch the record for a DOI, arXiv id, ISBN or PubMed ID from its public service without adding it, and say whether the library already holds it. " + "Lookups are queued and rate limited (arXiv allows about one request every 3 seconds), so do not send many of these at once: " + "to add several papers use add_by_identifiers. Answers within wait_seconds; if the lookup is still queued it answers a job_id for lookup_status. " + "Reaches the network only when the person's network switches allow that service.", + "input_schema": _schema({"identifier": IDENTIFIER, "wait_seconds": WAIT, "full": compact.FULL_SCHEMA}, ("identifier",)), "read_only": True, "open_world": True, "run": _lookup_preview, }, + { + "name": "lookup_status", + "title": "Check queued lookups", + "description": "The state of a lookup job from add_by_identifiers, add_by_identifier or lookup_preview: each identifier's status " + "(queued, working, added, existing, found, failed) with the compact item, and whether its PDF was attached.", + "input_schema": _schema({"job_id": {"type": "string", "description": "The job_id a lookup answered."}, "wait_seconds": WAIT, **SHAPE}, ("job_id",)), + "read_only": True, + "run": _lookup_status, + }, ] WRITE_TOOLS: list[dict] = [ @@ -224,12 +456,35 @@ def _tag_item(args: dict) -> tuple[str, dict]: { "name": "add_by_identifier", "title": "Add an item by identifier", - "description": "Look up a DOI, arXiv id, ISBN or PubMed ID and add the record to the library unless it is already there. Reaches the network under the person's network switches.", - "input_schema": _schema({"identifier": IDENTIFIER, "on_duplicate": ON_DUPLICATE}, ("identifier",)), + "description": "Look up one DOI, arXiv id, ISBN or PubMed ID and add the record to the library unless it is already there; " + "a repeated call answers the item already added and never makes a second one. For more than one paper use add_by_identifiers. " + "Answers within wait_seconds; if the lookup is still queued it answers a job_id for lookup_status. Reaches the network under the person's network switches.", + "input_schema": _schema({"identifier": IDENTIFIER, "on_duplicate": ON_DUPLICATE, "wait_seconds": WAIT, **SHAPE}, ("identifier",)), "read_only": False, "open_world": True, + "idempotent": True, "run": _add_by_identifier, }, + { + "name": "add_by_identifiers", + "title": "Add several items by identifier", + "description": "Add up to 50 papers in one call from DOIs, arXiv ids, ISBNs or PubMed IDs, optionally straight into a collection and with tags. " + "arXiv ids are fetched together in one request, and every lookup goes through FormCite's polite rate limit, so use this instead of many parallel single calls. " + "Answers within wait_seconds with each identifier's status; whatever is unfinished goes on in the background under the returned job_id (poll lookup_status). " + "Items already in the library are reported as existing, never added twice. arXiv PDFs are attached afterwards in the background.", + "input_schema": _schema({ + "identifiers": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": lookup_jobs.MOST_IDS, "description": "The identifiers, such as [\"arXiv:2407.01489\", \"10.1000/xyz\"]."}, + "collection": {"type": "string", "description": "A collection id or exact name to put every added or existing item in (make it first with create_collection)."}, + "tags": {"type": "array", "items": {"type": "string"}, "description": "Tags to put on every added or existing item."}, + "on_duplicate": ON_DUPLICATE, + "wait_seconds": WAIT, + **SHAPE, + }, ("identifiers",)), + "read_only": False, + "open_world": True, + "idempotent": True, + "run": _add_by_identifiers, + }, { "name": "import_references", "title": "Import references", @@ -262,27 +517,31 @@ def _tag_item(args: dict) -> tuple[str, dict]: { "name": "search", "title": "Search the library", - "description": "Full-text search of the current FormCite library over titles, creators, notes and tags. Answers matching items with their ids.", - "input_schema": _schema({"text": {"type": "string", "description": "Words to look for."}, "limit": LIMIT}, ("text",)), + "description": "Full-text search of the current FormCite library over titles, creators, notes and tags. Answers matching items in compact form " + "(id, title, year, authors, identifiers, tags, collections); ask for more with fields or full.", + "input_schema": _schema({"text": {"type": "string", "description": "Words to look for."}, "limit": LIMIT, "offset": OFFSET, **SHAPE}, ("text",)), "read_only": True, "run": _search, }, { "name": "get_item", "title": "Get one item", - "description": "One item of the library by id, with its CSL-JSON record, notes, attachments and collections.", - "input_schema": _schema({"id": {"type": "string", "description": "The item id."}}, ("id",)), + "description": "One item of the library by id, in compact form with its collections. Ask for its abstract, notes or attachments with fields, or for the whole stored record with full.", + "input_schema": _schema({"id": {"type": "string", "description": "The item id."}, **SHAPE}, ("id",)), "read_only": True, "run": _get_item, }, { "name": "list_items", "title": "List items", - "description": "Items of the library, most recently changed first, optionally only those in one collection or with one tag.", + "description": "Items of the library, most recently changed first, optionally only those in one collection or with one tag, in compact form. " + "Answers total, limit and offset; page with offset.", "input_schema": _schema({ - "collection": {"type": "string", "description": "A collection id."}, + "collection": COLLECTION, "tag": {"type": "string", "description": "A tag name."}, "limit": LIMIT, + "offset": OFFSET, + **SHAPE, }), "read_only": True, "run": _list_items, @@ -290,11 +549,12 @@ def _tag_item(args: dict) -> tuple[str, dict]: { "name": "list_collections", "title": "List collections", - "description": "Every collection of the library with its id, name and parent.", + "description": "Every collection of the library with its id, name, parent and number of items.", "input_schema": _schema({}), "read_only": True, "run": _list_collections, }, + *COLLECTION_TOOLS, { "name": "list_tags", "title": "List tags", @@ -316,7 +576,7 @@ def _find(name: str) -> dict | None: def _describe(tool: dict) -> dict: annotations = {"title": tool["title"], "readOnlyHint": tool["read_only"], "openWorldHint": tool.get("open_world", False)} if not tool["read_only"]: - annotations["destructiveHint"] = False + annotations["destructiveHint"] = tool.get("destructive", False) annotations["idempotentHint"] = tool.get("idempotent", False) return {"name": tool["name"], "title": tool["title"], "description": tool["description"], "inputSchema": tool["input_schema"], "annotations": annotations} From 67d6a22d6c5c3f86ee166107504614bb55b6a3ca Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:50:42 -0500 Subject: [PATCH 17/36] fix(engine): a token that may write can make, rename and fill collections (0.16.0) The dock's own Claude Code got 'Only the FormCite window can do this' when it tried to make a collection, because every write under /api/library needs the window key. Creating a collection, renaming or moving it, and adding or removing items are ordinary library writes like adding an item, which a write token may already do through /api/cite/v1 and MCP. So WindowKeyGuard now lets exactly POST /api/library/collections, PATCH /api/library/collections/{id} and POST or DELETE /api/library/collections/{id}/items through with a service token of write scope, and writes each one to the service log with its outcome. Unchanged and window-only: deleting a collection over HTTP, every other write, Connections, the network switches, the token store and the terminal. A read token or no token on those four routes is still refused, now with the token's own reason after the old sentence. --- backend/app/core/window_key.py | 46 +++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/backend/app/core/window_key.py b/backend/app/core/window_key.py index 6e867c1..7e609e2 100644 --- a/backend/app/core/window_key.py +++ b/backend/app/core/window_key.py @@ -1,6 +1,7 @@ import hmac import json import os +import re import secrets HEADER = "x-formcite-window-key" @@ -10,6 +11,13 @@ OPEN = ("/api/window/key",) SERVICE_PREFIX = "/api/cite/v1/" MCP_PATH = "/mcp" +_COLLECTION = r"^/api/library/collections/[A-Za-z0-9_-]+" +AGENT_WRITES = ( + ("POST", re.compile(r"^/api/library/collections$")), + ("PATCH", re.compile(_COLLECTION + r"$")), + ("POST", re.compile(_COLLECTION + r"/items$")), + ("DELETE", re.compile(_COLLECTION + r"/items$")), +) KEY = secrets.token_urlsafe(32) LAUNCH_CODE = os.environ.pop(LAUNCH_ENV, "").strip() STATE = {"claimed": False} @@ -45,6 +53,37 @@ def token_checked(path: str) -> bool: return path.startswith(SERVICE_PREFIX) or path == MCP_PATH +def agent_write(method: str, path: str) -> bool: + return any(method == want and shape.match(path) for want, shape in AGENT_WRITES) + + +def _bearer(scope) -> str | None: + value = next((v.decode("latin-1") for k, v in scope.get("headers", []) if k.decode("latin-1").lower() == "authorization"), "") + kind, _, token = value.partition(" ") + return token.strip() if kind.lower() == "bearer" and token.strip() else None + + +async def _as_agent(app, scope, receive, send) -> str | None: + from app.service import auth, writelog + + route = f"{scope.get('method')} {scope.get('path')}" + try: + caller = auth.check(_bearer(scope), "write") + except auth.Forbidden as exc: + return f"{REFUSED}, or an app holding a service token that may write. {exc}" + status = {"code": 500} + + async def noted(message) -> None: + if message.get("type") == "http.response.start": + status["code"] = int(message.get("status", 500)) + await send(message) + + await app(scope, receive, noted) + ok = status["code"] < 400 + writelog.record(caller, route, outcome="ok" if ok else "refused", error=None if ok else f"status {status['code']}") + return None + + class WindowKeyGuard: def __init__(self, app) -> None: self.app = app @@ -60,6 +99,11 @@ async def __call__(self, scope, receive, send) -> None: if valid(given): await self.app(scope, receive, send) return - body = json.dumps({"detail": REFUSED}).encode("utf-8") + refused = REFUSED + if agent_write(str(scope.get("method", "")), str(scope.get("path", ""))): + refused = await _as_agent(self.app, scope, receive, send) + if refused is None: + return + body = json.dumps({"detail": refused}).encode("utf-8") await send({"type": "http.response.start", "status": 403, "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]}) await send({"type": "http.response.body", "body": body}) From 5926304e7c3896b7412197df703db7e6a416e735 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:52:14 -0500 Subject: [PATCH 18/36] feat(window): start the live change feed at launch (0.16.0) The feed was started from start() in ui/app.ts, a file whose other uncommitted hunks belong to the reader, so the committed tree never opened it and agent writes still did not show (fc-verify V1). main.ts now starts it beside mountParity, and LiveFeed waits for the window key itself (loadWindowKey shares the claim app.ts already started), so it never runs without a key. --- frontend/src/engine/live.ts | 2 ++ frontend/src/main.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/frontend/src/engine/live.ts b/frontend/src/engine/live.ts index 7c5bf28..16272a6 100644 --- a/frontend/src/engine/live.ts +++ b/frontend/src/engine/live.ts @@ -1,5 +1,6 @@ import { ALL, type Library } from './library'; import { readFeed, type Change, type FeedMessage } from '../io/changes'; +import { loadWindowKey } from '../io/window-key'; const SETTLE_MS = 120; const MAX_WAIT_MS = 600; @@ -36,6 +37,7 @@ export class LiveFeed { } private async run(): Promise { + if (!(await loadWindowKey())) return; let failures = 0; while (!this.stop.signal.aborted) { try { diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 36a32e8..d1c88bb 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -4,9 +4,11 @@ import { mountApp } from './ui/app'; import { currentAppearance } from './engine/preferences'; import { applyLook } from './ui/themes'; import { mountParity } from './ui/parity'; +import { LiveFeed } from './engine/live'; applyLook(); const engine = createEngine(currentAppearance().theme); activateAll(engine); mountApp(engine); mountParity(engine); +new LiveFeed(engine.library).start(); From 2b9fd52d6efa6993937129132b896713d1b67b7d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:52:39 -0500 Subject: [PATCH 19/36] feat(window): an agent goes to a page, finds in and closes the open paper (0.16.0) reader.page, reader.find and reader.close drive the reader's own page box, find bar and Back button, so the person sees the same steps they would take, and answer what the reader shows (page 3 of 26, 17 of 50 matches). They step aside when the reader registers commands of those ids itself. The bridge's no-window answer now also names the stdio case, where the MCP server runs apart from the engine and cannot reach a window. --- backend/app/services/window_bridge.py | 5 +++-- frontend/src/ui/parity.ts | 19 +++++++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/backend/app/services/window_bridge.py b/backend/app/services/window_bridge.py index bdb9be4..5fc9d1e 100644 --- a/backend/app/services/window_bridge.py +++ b/backend/app/services/window_bridge.py @@ -11,8 +11,9 @@ MAX_WAIT = 25.0 REFUSED_PREFIXES = ("connections.", "engine.", "edit.", "network.", "service.", "window.close") ARG_TYPES = {"string": str, "number": (int, float), "integer": int, "boolean": bool} -NO_WINDOW = ("The FormCite window is not open, so window commands cannot run. " - "Ask the person to open FormCite, or use the headless tools, which change the library without a window.") +NO_WINDOW = ("No FormCite window is connected, so window commands cannot run: the window is closed, or this MCP server " + "runs apart from the engine (./formcite mcp on stdio), while window commands need the engine's /mcp, as the dock's agent tabs have. " + "The headless tools change the library without a window, and an open window shows those changes live.") _cond = threading.Condition() _state: dict = {"commands": {}, "seen": 0.0, "published": 0.0} diff --git a/frontend/src/ui/parity.ts b/frontend/src/ui/parity.ts index 6b37d8f..ebe538e 100644 --- a/frontend/src/ui/parity.ts +++ b/frontend/src/ui/parity.ts @@ -99,6 +99,18 @@ export function mountParity(engine: Engine): void { if (a.then === 'preview' || a.then === 'add') sec?.querySelector(`[data-act="${a.then}"]`)?.click(); }], ['add.close', 'Close the Add dialog', () => press('.fc-add.is-open [data-close]')], + ['reader.page', 'Go to a page of the open paper', (a) => { + const box = document.querySelector('.fc-rd-page'); + if (!box) return; + box.value = String(a.page); + box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + }], + ['reader.find', 'Find in the open paper', (a) => { + const bar = document.querySelector('.fc-rd-find'); + if (bar?.hidden) press('.fc-rd-bar [data-act="find"]'); + type(document.querySelector('.fc-rd-find-q'), str(a.text)); + }], + ['reader.close', 'Close the paper', () => press('.fc-rd-back')], ['window.minimize', 'Minimize', () => windowCall('minimize')], ['window.zoom', 'Zoom', () => windowCall('toggleMaximize')], ]; @@ -135,8 +147,11 @@ export function mountParity(engine: Engine): void { describeCommand('collection.new', { args: { name: { type: 'string' }, parent: { type: 'string' } }, group: 'collection', write: true }); describeCommand('collection.add-selection', { args: { collection: { type: 'string', required: true } }, group: 'collection', write: true }); describeCommand('collection.show', { args: { collection: { type: 'string', required: true } }, group: 'collection', settle: 600 }); - describeCommand('reader.page', { args: { page: { type: 'integer', required: true } }, group: 'reader' }); - describeCommand('reader.find', { args: { text: { type: 'string', required: true } }, group: 'reader', settle: 800 }); + const shown = (sel: string): string => document.querySelector(sel)?.textContent?.trim() ?? ''; + describeCommand('reader.page', { args: { page: { type: 'integer', required: true } }, group: 'reader', settle: 600, + said: () => `The paper shows page ${document.querySelector('.fc-rd-page')?.value ?? '?'} ${shown('.fc-rd-of')}.` }); + describeCommand('reader.find', { args: { text: { type: 'string', required: true } }, group: 'reader', settle: 1500, + said: (a) => `Find "${str(a.text)}": ${shown('.fc-rd-find-n') || 'searching'}.` }); describeCommand('reader.close', { group: 'reader' }); describeCommand('window.minimize', { group: 'window' }); describeCommand('window.zoom', { group: 'window' }); From 9f297384de5d787f583e39551fd492be67eeb5bc Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:52:53 -0500 Subject: [PATCH 20/36] docs(agents): collections, batched polite lookups and compact results, and say first what could not be done (0.16.0) The formcite skill and docs/MCP.md list the collection tools, add_by_identifiers and lookup_status, and tell an agent plainly: it can make and fill a collection itself, lookups are rate limited so several papers go in one add_by_identifiers call, an unfinished lookup is polled with its job_id and never resent, and when part of a request could not be done the first line of the reply says so. docs/SERVICE_TOKENS.md states which collection routes a write token may use and that deleting a collection over HTTP stays with the window. The server's own instructions in protocol.py say the same. --- .claude/skills/formcite/SKILL.md | 12 +++++++++--- docs/MCP.md | 31 +++++++++++++++++++++++-------- docs/SERVICE_TOKENS.md | 2 ++ 3 files changed, 34 insertions(+), 11 deletions(-) diff --git a/.claude/skills/formcite/SKILL.md b/.claude/skills/formcite/SKILL.md index ac24761..8e5922d 100644 --- a/.claude/skills/formcite/SKILL.md +++ b/.claude/skills/formcite/SKILL.md @@ -18,9 +18,12 @@ The premise: a reference list is only worth anything if every entry in it is rea 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, no network: `search` (`text`), `get_item` (`id`), `list_items` (`collection` or `tag`, `limit`, `offset`), `list_collections`, `list_tags`, `list_styles`, `cite`, `bibliography`, `format_document` (several citations in document order plus their bibliography), `lookup_status` (`job_id` of a lookup that was not finished). - 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; `keywords_as_tags` only when the person asked for keywords as tags), `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` and `add_by_identifiers` (also reach 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`. + - Collections, write: `create_collection` (`name`, optional `parent`), `add_to_collection` and `remove_from_collection` (`collection` id or exact name, `ids`), `rename_collection`, and `delete_collection` (`confirm` is the collection's exact name; only after the person said yes to deleting that collection; its items stay). You can make and fill a collection yourself: never tell the person to do it by hand when these tools are listed. + - Results are compact (id, title, year, authors, identifiers, tags, collections). Ask for `fields` such as `["abstract"]`, or `full: true`, only when the task needs them. + - **Lookups are rate limited** (arXiv allows about one request every 3 seconds). To add several papers, send them in one `add_by_identifiers` call (up to 50, with `collection` and `tags` if wanted), never many parallel `add_by_identifier` or `lookup_preview` calls. An answer that says "Not finished yet" carries a `job_id`: wait a few seconds and call `lookup_status`; do not send the identifiers again. A repeated add never makes a duplicate; it reports the item as `existing`. - Everything else a person does, from 0.16.0: `edit_item` (any field), `trash_items`, `restore_items`, `list_trash`, `delete_items_forever` and `empty_trash` (both need `confirm: true`), notes (`list_notes`, `add_note`, `edit_note`, `delete_note`), tags (`untag_item`, `rename_tag`, `delete_tag`), attachments (`list_attachments` gives the PDF's path on disk to read, `attach_file`, `remove_attachment`, `get_fulltext`, `fetch_pdf`, `add_pdf`), relations, saved searches (`run_search`, `save_search` and the rest), `find_duplicates`, `merge_duplicates`, `export_references`, `import_file`, `list_import_batches`, `undo_import`, `keywords_to_tags`, libraries (`list_libraries`, `create_library`, `use_library`), the Needs a title tools and `network_status` (read-only). The collection tools come with the collection slice. - The open window: `window_commands` lists what the window offers (views, select an item, search, sort and scope of the list, the paper reader with `item.view`, Preferences, appearance, the Add dialog, collections), each with typed arguments, and `window_command_run` runs one where the person sees it. Use it when the person wants to see something in FormCite ("show me", "open the paper", "switch to dark"); use the headless tools for the data. These need the engine's `/mcp` (the dock's agent tabs have it) and an open window; when `window_commands` says the window is not open, say so and carry on headless. 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. @@ -40,6 +43,7 @@ If the MCP tool list has fewer tools than a task needs, use the command line for | 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 | MCP `find_duplicates`, or `cli duplicates` (find) | MCP `merge_duplicates`, or merging | +| Add several papers, into a new collection | MCP `list_collections` | MCP `create_collection`, then one `add_by_identifiers` call with `collection`; check with `list_items` on that collection | | Tag, collect, note | `cli tag`, `cli collection`, `cli note` listings | any change | | Edit a field, trash, restore | MCP `get_item` | MCP `edit_item`, `trash_items`, `restore_items` | | Delete for good, empty the Trash | MCP `list_trash` | MCP `delete_items_forever` or `empty_trash` with `confirm: true`, after the person said yes to exactly that | @@ -51,12 +55,14 @@ If the MCP tool list has fewer tools than a task needs, use the command line for Ask before, every time, in one sentence that names what will happen: - **Anything that writes:** add, import, edit, trash, tag, collect, note, merge, attach, identify, and export to a file. Say how many items and which library. -- **Anything that reaches the network:** `lookup_preview`, `add_by_identifier`, and `cli lookup`, `cli add`, `cli identify`. Say which service will be called. `cli network` shows the services and whether each is on; a person may have turned one off on purpose. Do not turn a service on for them. +- **Anything that reaches the network:** `lookup_preview`, `add_by_identifier`, `add_by_identifiers`, and `cli lookup`, `cli add`, `cli identify`. Say which service will be called. `cli network` shows the services and whether each is on; a person may have turned one off on purpose. Do not turn a service on for them. A read (search, show, list, styles, formats, format a citation) needs no question. ## Telling the person plainly +- **Say what could not be done first.** When any part of the request was not done (a collection not made, papers that failed, lookups still running), the first line of the reply says so, before anything that was done. Never write a reply that reads as finished when part of it is not. + - **The style engine is not built.** If `cli styles` or `cli format` answers that the citation style engine is unavailable, say so in those words, and tell the person it is built with `setup/build_style` from the FormCite folder. Do not hand-format a citation in its place and present it as FormCite's output. If they ask for a hand-written draft, label it as yours. - **The network is off.** If `lookup` or `add` answers that the network or a service is off, say that FormCite's network is off and nothing was added. Offer `cli network` to show the switch; the person decides. - **Not found.** If search returns nothing, say the library has nothing matching. If a lookup answers not found, say the service has no such record. Offer to look up an identifier the person gives; never fill the gap with a remembered reference. diff --git a/docs/MCP.md b/docs/MCP.md index 3264493..319c101 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -8,7 +8,7 @@ The code is in `backend/app/mcp/`: `tools.py` (the tool table), `protocol.py` (o ``` ./formcite mcp read-only tools -./formcite mcp --allow-write read-only tools plus the four write tools +./formcite mcp --allow-write read-only tools plus the write tools ./formcite mcp --library Thesis serve the library named Thesis (the current library is not switched) formcite.bat mcp [--allow-write] the same on Windows ``` @@ -36,18 +36,25 @@ Every tool carries the specification's annotations. `readOnlyHint` is true for t | Tool | Read-only | Reaches the network | What it does | | - | - | - | - | -| `search` | yes | no | full-text search over titles, creators, notes and tags (`text`, `limit`) | -| `get_item` | yes | no | one item with its record, notes, attachments and collections (`id`) | -| `list_items` | yes | no | items, newest change first, optionally in one collection or with one tag (`collection`, `tag`, `limit`) | -| `list_collections` | yes | no | every collection with id, name and parent | +| `search` | yes | no | full-text search over titles, creators, notes and tags (`text`, `limit`, `offset`, `fields`, `full`) | +| `get_item` | yes | no | one item, compact, with its collections (`id`, `fields`, `full`) | +| `list_items` | yes | no | items, newest change first, optionally in one collection (id or name) or with one tag (`collection`, `tag`, `limit`, `offset`, `fields`, `full`); answers `total`, `limit`, `offset` | +| `list_collections` | yes | no | every collection with id, name, parent and item count | +| `create_collection` | no | no | make a collection, optionally inside another (`name`, `parent`); answers the one already there instead of a second | +| `add_to_collection` | no | no | put items in a collection (`collection`, `ids`) | +| `remove_from_collection` | no | no | take items out of a collection; they stay in the library (`collection`, `ids`) | +| `rename_collection` | no | no | rename a collection (`collection`, `name`) | +| `delete_collection` | destructive | no | delete a collection without sub-collections; its items stay (`collection`, `confirm` = its exact name) | +| `lookup_status` | yes | no | the state of a lookup job, per identifier (`job_id`, `wait_seconds`) | | `list_tags` | yes | no | every tag with its item count | | `cite` | yes | no | one in-text citation of items (`ids`, `style`, `locale`, `locators`) | | `bibliography` | yes | no | bibliography entries of items (`ids`, `style`, `locale`) | | `format_document` | yes | no | several citations in document order plus their bibliography (`citations`, `style`, `locale`) | | `list_styles` | yes | no | the styles FormCite can format with, common ones first | -| `lookup_preview` | yes | yes | fetch the record for a DOI, arXiv id, ISBN or PubMed ID without adding it (`identifier`) | +| `lookup_preview` | yes | yes | fetch the record for a DOI, arXiv id, ISBN or PubMed ID without adding it (`identifier`, `wait_seconds`) | | `add_item` | no | no | add an item from CSL-JSON (`csl`) or simple fields (`fields`) | -| `add_by_identifier` | no | yes | look up an identifier and add the record unless it is already there (`identifier`, `on_duplicate`) | +| `add_by_identifier` | no | yes | look up one identifier and add the record unless it is already there (`identifier`, `on_duplicate`, `wait_seconds`) | +| `add_by_identifiers` | no | yes | add up to 50 identifiers in one call, optionally into a collection and with tags (`identifiers`, `collection`, `tags`, `on_duplicate`, `wait_seconds`) | | `import_references` | no | no | import BibTeX, RIS, CSL-JSON or FormTxt text as one import batch (`text`, `format`, `on_duplicate`) | | `tag_item` | no | no | add tags to an item (`id`, `tags`) | @@ -80,7 +87,15 @@ An agent can do in FormCite what a person can. The tools in `backend/app/mcp/too | `window_command_run` | no | run one in the window, where the person sees it; answers when it finished or a run id | | `window_command_result` | yes | the state and result of a run | -Collections (create, rename, delete, file and unfile items, batch add) are their own tools, listed with the collection slice. +Collections (create, rename, delete, file and unfile items, batch add) are their own tools, in the table above. + +### Lookups are queued, batched and polite (0.16.0) + +`lookup_preview`, `add_by_identifier` and `add_by_identifiers` put a job on one queue (`backend/app/services/lookup_jobs.py`) and wait for it at most `wait_seconds` (default 20; over HTTP never past 22 s after the request arrived, so the answer always beats the 30 s limit). What is not finished goes on in the background: the answer says "Not finished yet", names a `job_id`, and `lookup_status` reports each identifier as `queued`, `working`, `added`, `existing`, `found` or `failed`, and each arXiv PDF as `queued`, `attaching`, `attached` or why not. The arXiv ids of one job are fetched in one `id_list` query, records are cached for an hour, and every arXiv host (`export.arxiv.org`, `oaipmh.arxiv.org`, `arxiv.org`) shares one pace of one request every 3 seconds; a 429 or 503 is retried twice after the server's `Retry-After` or 4 and 8 seconds. Adding is idempotent: a repeated or retried call reports the item already there as `existing` and never makes a second one, and identifiers sent again while their job is unfinished join that job. + +### Compact results (0.16.0) + +An item in a tool result is compact: `id`, `title`, `year`, `authors` (the first three family names and "and N more"), `author_count`, `identifiers` (`doi`, `arxiv`, `isbn`, `pmid`, `url` when present), `tags`, `collections` and `attachment_count`. `fields` adds named parts (`abstract`, `container_title`, `issued`, `type`, `url`, `csl`, `creators`, `notes`, `attachments`, `relations`, `snippet`, `created_at`, `updated_at`, `batch_id`); `full: true` answers the stored item whole. A 200-author paper was 60,421 characters whole and is 774 compact. The window commands are what a person does with menus, buttons and right-click menus: every view, selecting and revealing an item, search, sort and scope of the list, the reader (`item.view`), copying a citation, Preferences at a section, appearance, theme and accent, switching library, the Add dialog, and the collection commands. `window_commands` lists them with their arguments, such as `list.sort(key: title|creator|year|type|added|updated, desc?: boolean)`; `window_command_run` with `{"command": "list.sort", "args": {"key": "year", "desc": true}}` runs one and answers what the window shows afterwards (view, scope, search, sort, selection and counts). They need the engine's `/mcp` with a token that may write, which is what the dock's agent tabs get, and an open window; over stdio, or with the window closed, `window_commands` says so and the headless tools still work. The approvals under Connections, the network switches, the token store, the clipboard edit commands and Close Window are never offered, whatever the token. How the bridge works is in [WINDOW.md](WINDOW.md). diff --git a/docs/SERVICE_TOKENS.md b/docs/SERVICE_TOKENS.md index f9d87ea..ec7cc71 100644 --- a/docs/SERVICE_TOKENS.md +++ b/docs/SERVICE_TOKENS.md @@ -2,6 +2,8 @@ FormCite answers two kinds of caller. The FormCite window holds the window key it traded for the launch code, and may do anything. Another app on this computer (FormTxt, FormCel, form.md, FormSubstrate, FormPDF) or a person's own agent holds a service token that the person approved, and may only use the routes under `/api/cite/v1/` and `/mcp`. No token, no answer: every method on those paths, GET included, asks for one. +One exception since 0.16.0: a token that may write may also make and fill collections through the window's own routes, because these are ordinary library writes like adding an item. Exactly `POST /api/library/collections`, `PATCH /api/library/collections/{id}` (rename or move) and `POST` or `DELETE /api/library/collections/{id}/items` take `Authorization: Bearer` with a write token in place of the window key, and each such write goes into the service log. A read token on them is refused with its usual sentence. Deleting a collection over HTTP, and every other write under `/api/library`, stays with the window; an agent deletes a collection only through the MCP tool `delete_collection`, which names the collection and is marked destructive so the agent's client asks the person. + ## The model - A token is `fc_` followed by 32 random bytes in URL-safe text, sent as `Authorization: Bearer fc_...`. From 6ca1cc1234d559305449459e0b9073d5ae7e56db Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:26 -0500 Subject: [PATCH 21/36] fix(window): the item list re-reads on a stale notice by itself (0.16.0) ItemListModel now listens for library:stale and refreshes around the rows in view, so a window that fell behind or took a burst of more than 40 edits re-reads its list even before the list view's scroll-anchor hunks are committed. The view only sets its scroll hold on that notice, so the refresh is not run twice. --- frontend/src/engine/itemlist.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 57f0631..f66ba6d 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -20,7 +20,9 @@ export class ItemListModel { private generation = 0; private ready = false; - constructor(private lib: Library, private sink: ListSink) {} + constructor(private lib: Library, private sink: ListSink) { + lib.events.on('library:stale', () => this.refresh()); + } at(i: number): Row | undefined { return this.cache.get(i); } indexOf(id: string): number { return this.index.get(id) ?? -1; } From 5f5e004df5a514cf4eb5d34af7a41f8776ec66e2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:35 -0500 Subject: [PATCH 22/36] feat(mcp): serve fc-parity's tools beside the collection tools (0.16.0) tools.py imports PARITY_TOOLS from tools_parity.py and lists them last in TOOLS, and the server instructions point an agent at them and at window_commands. 65 tools, no name twice; nine carry destructiveHint, read by _describe from each tool's destructive flag. Done here at fc-parity's request, since tools.py and protocol.py had my hunks. --- backend/app/mcp/protocol.py | 2 ++ backend/app/mcp/tools.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/backend/app/mcp/protocol.py b/backend/app/mcp/protocol.py index 3ef8920..d2107b1 100644 --- a/backend/app/mcp/protocol.py +++ b/backend/app/mcp/protocol.py @@ -21,6 +21,8 @@ "to add several papers send them in one add_by_identifiers call, never many parallel add_by_identifier or lookup_preview calls. " "A lookup that is not finished answers a job_id; poll lookup_status and do not resend the identifiers. " "Results are compact by default; ask for fields such as abstract, or full, only when needed. " + "Everything else a person does has a tool too (edit_item, notes, trash, attachments, saved searches, duplicates, export, libraries); " + "to show the person something in the open window, list window_commands and run one with window_command_run. " "When any part of the person's request could not be done, say so in the first line of the reply, before what was done." ) diff --git a/backend/app/mcp/tools.py b/backend/app/mcp/tools.py index 6e42c9d..7c04e2b 100644 --- a/backend/app/mcp/tools.py +++ b/backend/app/mcp/tools.py @@ -3,6 +3,7 @@ from typing import Any, Callable from app.mcp import compact, http +from app.mcp.tools_parity import PARITY_TOOLS from app.services import formatting, library, lookup_jobs, transfer from app.store import collections, files, libraries from app.store.errors import Invalid, NotFound @@ -566,6 +567,7 @@ def _tag_item(args: dict) -> tuple[str, dict]: *FORMAT_TOOLS, *NET_TOOLS, *WRITE_TOOLS, + *PARITY_TOOLS, ] From e4d2ca265df33763901f9699c2bdba18a0635b5a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:56:15 -0500 Subject: [PATCH 23/36] fix(mcp): use_library makes the open window switch at once (0.16.0) A headless switch left the window on the old library until the change feed's next library check. use_library now also queues the window's own library.use command through the bridge, which posts the same switch again (harmless) and resets the list, the details pane and the sidebar, as the Switch button in Preferences does. With no window open nothing is queued. --- backend/app/mcp/tools_parity.py | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/app/mcp/tools_parity.py b/backend/app/mcp/tools_parity.py index b11d5dc..528b29a 100644 --- a/backend/app/mcp/tools_parity.py +++ b/backend/app/mcp/tools_parity.py @@ -276,6 +276,7 @@ def _create_library(args: dict) -> tuple[str, dict]: def _use_library(args: dict) -> tuple[str, dict]: out = library.library_use(args["name"]) + window_bridge.notify("library.use", {"name": out["name"]}) return f"Switched to the library {out['name']}; the open window follows.", {"name": out["name"]} From 085c9b0ef10e8d3f2f8905ec023dc2d255e57b8b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:07:33 -0500 Subject: [PATCH 24/36] feat(mcp): window_commands takes a query, as agents already send one (0.16.0) In the owner's dock session the agent asked window_commands with {"query": "collection"} and was refused for an unknown argument. query now keeps the commands whose id or title holds every word given, beside the group filter. --- backend/app/mcp/tools_parity.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/backend/app/mcp/tools_parity.py b/backend/app/mcp/tools_parity.py index 528b29a..29cd228 100644 --- a/backend/app/mcp/tools_parity.py +++ b/backend/app/mcp/tools_parity.py @@ -309,6 +309,9 @@ def _network_status(args: dict) -> tuple[str, dict]: def _window_commands(args: dict) -> tuple[str, dict]: out = window_bridge.catalog(args.get("group")) + words = str(args.get("query") or "").lower().split() + if words: + out["commands"] = [c for c in out["commands"] if all(w in f"{c['id']} {c['title']}".lower() for w in words)] if not out["window_open"]: return window_bridge.NO_WINDOW, out lines = [] @@ -425,7 +428,8 @@ def _tool(name: str, title: str, description: str, run, props: dict | None = Non _tool("network_status", "Network switches and recent calls", "Whether lookups may reach the network, which services are off, and the latest calls, as Preferences, Network shows. Read-only: the switches are the person's.", _network_status, {"limit": {**LIMIT, "description": "Recent calls to answer (default 10)."}}, read_only=True), _tool("window_commands", "List window commands", "The commands the open FormCite window offers, with typed arguments: views, selection, search, sort, scope, the reader, dialogs, appearance and the rest of what a person does with menus and buttons.", - _window_commands, {"group": {"type": "string", "description": "Only one group, such as view, item, list, reader, prefs."}}, read_only=True), + _window_commands, {"group": {"type": "string", "description": "Only one group, such as view, item, list, reader, prefs, collection."}, + "query": {"type": "string", "description": "Only commands whose id or title holds these words, such as collection or theme."}}, read_only=True), _tool("window_command_run", "Run a window command", "Run one command of window_commands in the open window, where the person sees it. Answers when it finished, or a run id to ask window_command_result about.", _window_command_run, {"command": {"type": "string", "description": "A command id from window_commands."}, "args": {"type": "object", "description": "Its arguments."}, "wait_seconds": {"type": "integer", "minimum": 0, "maximum": 20, "description": "How long to wait for it (default 8)."}}, ("command",)), From 2ed3cafe55487fa216d5a218cc0b7adcf4c0dc16 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:08:39 -0500 Subject: [PATCH 25/36] fix(window): collection.add-selection takes the item argument it accepts (0.16.0) The collection command files a given item or the selected one, but the bridge described only its collection, so an agent naming the item was refused as an unknown argument. The description now carries item as optional, and the run waits for the filing to land before it answers. --- frontend/src/ui/parity.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/ui/parity.ts b/frontend/src/ui/parity.ts index ebe538e..6f18fe8 100644 --- a/frontend/src/ui/parity.ts +++ b/frontend/src/ui/parity.ts @@ -145,7 +145,7 @@ export function mountParity(engine: Engine): void { describeCommand('add.identifier', { args: { identifier: { type: 'string', required: true }, then: { type: 'string', enum: ['preview', 'add'] } }, group: 'library', write: true, settle: 600 }); describeCommand('add.close', { group: 'library' }); describeCommand('collection.new', { args: { name: { type: 'string' }, parent: { type: 'string' } }, group: 'collection', write: true }); - describeCommand('collection.add-selection', { args: { collection: { type: 'string', required: true } }, group: 'collection', write: true }); + describeCommand('collection.add-selection', { args: { collection: { type: 'string', required: true, description: 'A collection id or exact name.' }, item: { type: 'string', description: 'An item id; the selected item when left out.' } }, group: 'collection', write: true, settle: 600 }); describeCommand('collection.show', { args: { collection: { type: 'string', required: true } }, group: 'collection', settle: 600 }); const shown = (sel: string): string => document.querySelector(sel)?.textContent?.trim() ?? ''; describeCommand('reader.page', { args: { page: { type: 'integer', required: true } }, group: 'reader', settle: 600, From 383b327d537ad1e2dfd196f4043c729ff637f815 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:09:16 -0500 Subject: [PATCH 26/36] feat(engine): the window reads a PDF attachment and opens a paper's links (0.16.0) GET /api/library/attachments/{id}/file answers the stored PDF to the window alone (window key required), with HTTP ranges, no-store and nosniff, so the in-app reader can stream a 100-page paper. It refuses an attachment that is not a PDF. POST /api/library/open-url opens an http, https or mailto address in the person's browser, for links clicked inside a paper in the desktop shell, where a new window cannot open. Anything else is refused. --- backend/app/routers/window.py | 17 +++++++++++++++++ backend/app/services/opener.py | 26 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/backend/app/routers/window.py b/backend/app/routers/window.py index 621d6c2..9101333 100644 --- a/backend/app/routers/window.py +++ b/backend/app/routers/window.py @@ -1,6 +1,8 @@ from typing import Any, Callable from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi.responses import FileResponse +from pydantic import BaseModel from app.routers.service import window_only from app.services import opener, window_rows @@ -19,6 +21,10 @@ def _run(fn: Callable, *args, **kwargs) -> Any: raise HTTPException(422, str(exc)) from exc +class UrlBody(BaseModel): + url: str + + @router.get("/rows") def rows( scope: str = "all", @@ -73,6 +79,17 @@ def open_attachment(attachment_id: str) -> dict: return _run(opener.open_attachment, attachment_id) +@router.get("/attachments/{attachment_id}/file", dependencies=[Depends(window_only)]) +def attachment_file(attachment_id: str) -> FileResponse: + path = _run(opener.stored_pdf, attachment_id) + return FileResponse(path, media_type="application/pdf", headers={"cache-control": "no-store", "x-content-type-options": "nosniff"}) + + +@router.post("/open-url", dependencies=[Depends(window_only)]) +def open_url(body: UrlBody) -> dict: + return _run(opener.open_url, body.url) + + @router.post("/items/{item_id}/open-arxiv", dependencies=[Depends(window_only)]) def open_arxiv(item_id: str) -> dict: return _run(opener.open_arxiv, item_id) diff --git a/backend/app/services/opener.py b/backend/app/services/opener.py index 38d4828..57b4c54 100644 --- a/backend/app/services/opener.py +++ b/backend/app/services/opener.py @@ -1,4 +1,5 @@ import os +import re import subprocess import sys from pathlib import Path @@ -11,6 +12,7 @@ FORMPDF_ENV = "FORMCITE_FORMPDF_APP" FORMPDF_BUNDLES = (Path("/Applications/FormPDF.app"), Path.home() / "Applications" / "FormPDF.app") HANDOFF_WAIT = 2.0 +WEB_URL = re.compile(r"^(?:https?://[^/\s]+|mailto:[^\s]+)", re.IGNORECASE) NOT_PDF = "only a PDF is handed to FormPDF, so FormCite opened the file in the system viewer." NOT_STORED = "a linked file lives outside the library, so FormCite does not hand it to another app and opened it in the system viewer." NOT_FOUND = "FormPDF was not found on this computer, so FormCite opened the file in the system viewer." @@ -36,6 +38,30 @@ def stored_path(attachment_id: str) -> Path: return path +def stored_pdf(attachment_id: str) -> Path: + with session() as (_, conn): + found = attachments.get(conn, attachment_id) + path = stored_path(attachment_id) + if found.get("mime") != "application/pdf" and path.suffix.lower() != ".pdf": + raise Invalid(f"attachment {attachment_id} is not a PDF") + return path + + +def open_url(url: str) -> dict: + url = url.strip() + if not WEB_URL.match(url) or any(ch in url for ch in "\r\n\t "): + raise Invalid("only an http, https or mailto address is opened") + argv = None if sys.platform.startswith("win") else (["open", url] if sys.platform == "darwin" else ["xdg-open", url]) + try: + if argv is None: + os.startfile(url) + else: + subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + except (OSError, AttributeError) as exc: + raise Invalid(f"the web browser could not be started: {exc}") from exc + return {"url": url} + + def system_argv(path: Path) -> list[str] | None: if sys.platform == "darwin": return ["open", str(path)] From 1fdbee2fce021b57e00db3ea23d7aea4c90e388d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:09:21 -0500 Subject: [PATCH 27/36] build(window): add pdfjs-dist 6.5.438 and serve its data files locally (0.16.0) PDF.js (Apache-2.0) renders papers in the window. It is pinned exactly and listed in NOTICE.md with the licenses of the data files it carries. A small Vite plugin serves PDF.js's CMaps, standard fonts, wasm image decoders and ICC profile under /pdfjs/ from node_modules in development, and copies them into dist/pdfjs/ at build time, so nothing is fetched from a CDN or the network. The QuickJS scripting engine is left out because the reader runs no PDF JavaScript. --- NOTICE.md | 3 +- frontend/package-lock.json | 265 ++++++++++++++++++++++++++++++++++++- frontend/package.json | 3 +- frontend/vite.config.ts | 33 ++++- 4 files changed, 300 insertions(+), 4 deletions(-) diff --git a/NOTICE.md b/NOTICE.md index 2641a64..670860a 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -33,6 +33,7 @@ Each component gets a row here with its license and its use before it is added. | ptyprocess 0.7.0, pinned exactly, on macOS and Linux; it pulls in no other package | ISC, read from the wheel's license file (Copyright (c) 2013-2014, Pexpect development team; Copyright (c) 2012, Noah Spurrier) | the terminals of the agent dock, since 0.15.0 | | pywinpty 3.0.5, pinned exactly, on Windows only; its wheel carries `winpty.dll` (winpty, MIT) and `conpty.dll` (Microsoft, MIT) | MIT, read from the wheel's metadata and license file | the terminals of the agent dock on Windows, since 0.15.0 | | @xterm/xterm 6.0.0 and @xterm/addon-fit 0.11.0, pinned exactly, the same versions as FormVis and FormDeck; they pull in no other package | MIT, read from each installed package's license file (Copyright (c) 2017-2019, The xterm.js authors; 2014-2016, SourceLair Private Company; 2012-2013, Christopher Jeffrey) | the terminal emulator in the agent dock, loaded when the first terminal tab opens, since 0.15.0 | +| pdfjs-dist 6.5.438 (Mozilla's PDF.js), pinned exactly; it has no runtime dependencies. Its optional `@napi-rs/canvas` (MIT) is a Node-only renderer that npm may install; the window never loads it and it is not shipped | Apache-2.0, read from the installed package's metadata and license file (Copyright Mozilla Foundation). The files it carries and FormCite serves from the window itself, under `/pdfjs/`: the Adobe CMaps (BSD-3-Clause, Copyright 1990-2009 Adobe Systems Incorporated), the standard fonts (Foxit, BSD-3-Clause, Copyright 2014 PDFium Authors; Liberation, SIL OFL 1.1), the OpenJPEG decoder (BSD-2-Clause), the JBIG2 decoder (BSD-3-Clause, PDFium Authors, with PDF.js's own Apache-2.0 glue), qcms (MIT, Mozilla Corporation and Marti Maria) and one ICC profile (CC0-1.0); each keeps its license file beside it. The QuickJS scripting engine is left out | the in-app paper reader: the worker, page rendering, text layer, links and find, loaded only when a paper first opens, since 0.16.0 | | tzdata 2026.6, pinned exactly; it pulls in no other package | Apache-2.0, read from the wheel's metadata and license file | the IANA time zone data for the engine's Eastern-time logs where the system has none (Windows always), since 0.15.0 | | hayagriva 0.10.1, pinned exactly, with its style parser citationberg | MIT OR Apache-2.0 | the citation style engine, built into the Python module `formcite_style` | | The other crates in `native/formcite-style/Cargo.lock` (pyo3 0.29, serde, serde_json and the rest) | MIT OR Apache-2.0 for most; Unicode-3.0, MIT, Apache-2.0, BSD-2-Clause, Unlicense OR MIT and 0BSD OR CC0-1.0 for the others; `target-lexicon` is Apache-2.0 WITH LLVM-exception and is used at build time only. The full list is in `docs/STYLE_ENGINE.md` | the citation style engine | @@ -45,4 +46,4 @@ Each component gets a row here with its license and its use before it is added. | @tauri-apps/api 2.12.5, pinned exactly; it pulls in no other package | Apache-2.0 OR MIT, read from the installed package's metadata | the macOS system menu in the desktop window (`frontend/src/ui/native-menu.ts`); loaded only inside the desktop shell, since 0.15.0 | | Tauri 2 with tauri-plugin-shell and tauri-plugin-dialog, fontdb, regex, serde, serde_json, windows-sys, objc2 and its companions | the same crates formtxt's shell uses; their licenses have not been read for this repository yet | desktop shell, which has not been compiled yet | -The window's runtime dependencies are @tauri-apps/api, for the macOS system menu, and @xterm/xterm with @xterm/addon-fit, for the agent dock's terminals; it uses the system font stack. +The window's runtime dependencies are @tauri-apps/api, for the macOS system menu, @xterm/xterm with @xterm/addon-fit, for the agent dock's terminals, and pdfjs-dist, for the paper reader; it uses the system font stack. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index ae636f7..27dcf06 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -11,7 +11,8 @@ "dependencies": { "@tauri-apps/api": "2.12.5", "@xterm/addon-fit": "0.11.0", - "@xterm/xterm": "6.0.0" + "@xterm/xterm": "6.0.0", + "pdfjs-dist": "6.5.438" }, "devDependencies": { "@tauri-apps/cli": "2.12.5", @@ -56,6 +57,256 @@ "tslib": "^2.4.0" } }, + "node_modules/@napi-rs/canvas": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.2.1.tgz", + "integrity": "sha512-dTFJYKi4eE9Yr9FlLi7hN/Q+15VVmpnA1HrKkTzGQuWiVw5MWBL2reLXAaXUMENmzKxtlqYCtCp1NIeQqx+uEA==", + "license": "MIT", + "optional": true, + "workspaces": [ + "e2e/*" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@napi-rs/canvas-android-arm64": "1.2.1", + "@napi-rs/canvas-darwin-arm64": "1.2.1", + "@napi-rs/canvas-darwin-x64": "1.2.1", + "@napi-rs/canvas-linux-arm-gnueabihf": "1.2.1", + "@napi-rs/canvas-linux-arm64-gnu": "1.2.1", + "@napi-rs/canvas-linux-arm64-musl": "1.2.1", + "@napi-rs/canvas-linux-riscv64-gnu": "1.2.1", + "@napi-rs/canvas-linux-x64-gnu": "1.2.1", + "@napi-rs/canvas-linux-x64-musl": "1.2.1", + "@napi-rs/canvas-win32-arm64-msvc": "1.2.1", + "@napi-rs/canvas-win32-x64-msvc": "1.2.1" + } + }, + "node_modules/@napi-rs/canvas-android-arm64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.2.1.tgz", + "integrity": "sha512-CtM+0Xieqc8jMyIm6sPLbnvDut4/BmSAP+HQnbbwPcw3ZG+bY1NhwndtpOzAPcNbIPyWuiShSF99/Ja7vYeXbw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-arm64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.2.1.tgz", + "integrity": "sha512-DazlaWwTa1xIdROpA8e95ttU4yNedl6brXbqBm+upoQ/1WIpmDu4zwanYp6ftGIbrjMld/OjJK15kFrDPWLoEQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-darwin-x64": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.2.1.tgz", + "integrity": "sha512-XU9zFjeRusfeP49/Dk4CNqvMzxOiBtrl6Qoyndp2Wxk0LhJxgiUhhSMGLIripipZZKfKJOo1h/k8FswMVk0PuA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.2.1.tgz", + "integrity": "sha512-24R1MI8ZcWSrqU5rD+hRelWsoExMc4Bo8vRbIIge4f5X97P4pvrPMIMV0e5szSyU9y5aF8gA+CCXwWWRwFthYg==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.2.1.tgz", + "integrity": "sha512-2pxxAlQ3wTYxqZnuqXhQbE4sTvLC1/dYkuPpudggCgvQXRb6KYm6K01UAL2kWqpkTqFmy6kHfIjLJ/86vQhOnQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-musl": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.2.1.tgz", + "integrity": "sha512-+Ksk8ilbmbA4oMu+BfOL/WZMeDY0Z40TblthqS8Ssr6K7MFXh9707O1H3uJcVx3H7plXWsDuycGai20FBRO0sg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.2.1.tgz", + "integrity": "sha512-B7Y0cljUn/kTmDiSJ7q94axEvQMJLoJZX8FDf8+JdvAkQiUR2tHnDomGIxtHsvXGmzf3UE736YdtvNLEfCDjdg==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-gnu": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.2.1.tgz", + "integrity": "sha512-1/7y8Yx589PcQE8Xuvc0ZLRwEsjA1FonfV+ZWUS4s+pwI6Aa5i+VHUhAv+pR1692A+mIjuaH5FpH89+CFK0Nng==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-musl": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.2.1.tgz", + "integrity": "sha512-fiO90vFdt9Kq3v+sPHSczzbpRi2CTMx6NQdfD31zfJFeouXVR8EeiGyHpXuV5wwE6ui7IQLmVTHq7Uz3V0xq/w==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-arm64-msvc": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.2.1.tgz", + "integrity": "sha512-COZrzxhGGpWwP+3xMtppDz3J7ycLKsIZfClKxAmJRZFR5sVmiujy+ShnMyzmQtzTzpFInxkzQ35maAxYjR88kA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, + "node_modules/@napi-rs/canvas-win32-x64-msvc": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.2.1.tgz", + "integrity": "sha512-oPzPLrFlox/NAcqVVT8mHaXF0FsQ2XXX3nWy/l5yV/NksxBf9V/nnCes+O5fz+xzzwDNVjL5EOk7+siz5HmfCA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "1.2.6", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", @@ -1285,6 +1536,18 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/pdfjs-dist": { + "version": "6.5.438", + "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.5.438.tgz", + "integrity": "sha512-vg8Pw1x+AFKy4AMDvhuWl5cOYV8d698UoEANoFFhc79hqXDnZQqnOXoxw3HG907WHOg1JYOvLhP756boddFxpA==", + "license": "Apache-2.0", + "engines": { + "node": ">=22.13.0 || >=24" + }, + "optionalDependencies": { + "@napi-rs/canvas": "^1.0.13" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 58f2e2e..7cfaebe 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -17,7 +17,8 @@ "dependencies": { "@tauri-apps/api": "2.12.5", "@xterm/addon-fit": "0.11.0", - "@xterm/xterm": "6.0.0" + "@xterm/xterm": "6.0.0", + "pdfjs-dist": "6.5.438" }, "devDependencies": { "@tauri-apps/cli": "2.12.5", diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 28eb5b9..7b9c954 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,4 +1,34 @@ -import { defineConfig } from 'vite'; +import { cpSync, createReadStream, existsSync, statSync } from 'node:fs'; +import { dirname, join, normalize, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { defineConfig, type Plugin } from 'vite'; + +const PDFJS_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), 'node_modules/pdfjs-dist'); +const PDFJS_DIRS = ['cmaps', 'standard_fonts', 'wasm', 'iccs']; +const PDFJS_SKIP = /quickjs/i; +const PDFJS_TYPES: Record = { '.wasm': 'application/wasm', '.js': 'text/javascript', '.ttf': 'font/ttf' }; + +function pdfjsAssets(): Plugin { + let outDir = 'dist'; + return { + name: 'formcite-pdfjs-assets', + configResolved(config) { outDir = resolve(config.root, config.build.outDir); }, + configureServer(server) { + server.middlewares.use('/pdfjs/', (req, res, next) => { + const rel = normalize(decodeURIComponent((req.url ?? '').split('?')[0])).replace(/^[/\\]+/, ''); + const top = rel.split(/[/\\]/)[0]; + const file = join(PDFJS_ROOT, rel); + if (!PDFJS_DIRS.includes(top) || PDFJS_SKIP.test(rel) || !file.startsWith(PDFJS_ROOT) || !existsSync(file) || !statSync(file).isFile()) { next(); return; } + const ext = rel.slice(rel.lastIndexOf('.')); + res.setHeader('content-type', PDFJS_TYPES[ext] ?? 'application/octet-stream'); + createReadStream(file).pipe(res); + }); + }, + writeBundle() { + for (const dir of PDFJS_DIRS) cpSync(join(PDFJS_ROOT, dir), join(outDir, 'pdfjs', dir), { recursive: true, filter: (src) => !PDFJS_SKIP.test(src) }); + }, + }; +} const FRONTEND_PORT = Number(process.env.FORMCITE_UI_PORT ?? 5330); const PREVIEW_PORT = 5331; @@ -8,6 +38,7 @@ const engine = { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true, export default defineConfig({ root: '.', publicDir: 'public', + plugins: [pdfjsAssets()], server: { port: FRONTEND_PORT, host: false, From 1682e1ea076efc5efb4f8f9ec0f7a917c998933e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:09:31 -0500 Subject: [PATCH 28/36] feat(window): a paper reader inside the window (0.16.0) The reader replaces the main area with the paper and a Back control, the way Duplicates and Trash do, and returns to the view it came from. It renders with PDF.js's viewer: a continuous scroll of pages drawn at the screen's pixel ratio, only the pages near the viewport rendered and a small page cache, so a 100-page paper opens about as fast as a 15-page one. The worker is a local asset and the PDF.js code and styles load only when the first paper opens. The bar holds Back, the sidebar toggle, the title, the page box and count, zoom (out, a Fit width, Fit page, Automatic or percent list, in), find, dark pages, Open in the system viewer, download and print. The sidebar shows page thumbnails, drawn as they scroll into view and capped at 60 at a time, or the paper's outline. Find highlights every match with next and previous and a count. The text layer makes text selectable and copyable; internal links jump within the paper and outside links open in the browser (through the engine in the desktop shell). Ctrl or Cmd with +, - and 0, Ctrl-wheel and pinch zoom; arrows, n, p, j, k, Home, End and Page Up and Down page; Esc closes find, then goes back. The last page and zoom are kept per paper (the most recent 300), with the sidebar, its tab and dark pages as preferences. An item whose PDF is not attached yet gets its open-access copy from arXiv first, with progress shown, then opens; an error offers Try again and the system viewer. The loading veil fades in only after 220 ms, the find bar floats over the pages, and every control has a fixed width, so nothing moves on open or while scrolling. Pages stay white in both themes unless dark pages is on. The new glyphs are added to ui/icons.ts. --- frontend/src/engine/reader.ts | 136 ++++++++++++ frontend/src/io/reader.ts | 15 ++ frontend/src/styles/reader.css | 101 +++++++++ frontend/src/ui/icons.ts | 15 ++ frontend/src/ui/reader-view.ts | 316 +++++++++++++++++++++++++++ frontend/src/ui/reader.ts | 383 +++++++++++++++++++++++++++++++++ 6 files changed, 966 insertions(+) create mode 100644 frontend/src/engine/reader.ts create mode 100644 frontend/src/io/reader.ts create mode 100644 frontend/src/styles/reader.css create mode 100644 frontend/src/ui/reader-view.ts create mode 100644 frontend/src/ui/reader.ts diff --git a/frontend/src/engine/reader.ts b/frontend/src/engine/reader.ts new file mode 100644 index 0000000..a23ae20 --- /dev/null +++ b/frontend/src/engine/reader.ts @@ -0,0 +1,136 @@ +import { Emitter } from './events'; +import { readerApi } from '../io/reader'; + +export type ReaderPhase = 'idle' | 'resolving' | 'fetching' | 'loading' | 'ready' | 'error'; +export type SideTab = 'thumbs' | 'outline'; + +export interface ReaderDoc { itemId: string; attachmentId: string; title: string; name: string } + +export interface ReaderState { + phase: ReaderPhase; + itemId: string | null; + doc: ReaderDoc | null; + progress: number | null; + message: string; +} + +export interface ReaderPrefs { side: boolean; tab: SideTab; darkPage: boolean } + +export interface ReaderEvents { + 'state': ReaderState; + 'show': ReaderDoc; + 'close': null; + 'prefs': ReaderPrefs; +} + +export interface Spot { page: number; scale: string } + +const SPOTS_KEY = 'formcite.reader.spots'; +const PREFS_KEY = 'formcite.reader.prefs'; +const SPOTS_KEPT = 300; +const DEFAULT_PREFS: ReaderPrefs = { side: true, tab: 'thumbs', darkPage: false }; + +function readJson(key: string): T | null { + try { return JSON.parse(localStorage.getItem(key) || 'null') as T | null; } catch { return null; } +} + +function writeJson(key: string, value: unknown): void { + try { localStorage.setItem(key, JSON.stringify(value)); } catch (e) { console.error('[reader] save failed:', e); } +} + +const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); + +export class ReaderModel { + readonly events = new Emitter(); + private _state: ReaderState = { phase: 'idle', itemId: null, doc: null, progress: null, message: '' }; + private _prefs: ReaderPrefs = { ...DEFAULT_PREFS, ...(readJson>(PREFS_KEY) ?? {}) }; + private ask = 0; + + get state(): Readonly { return this._state; } + get prefs(): Readonly { return this._prefs; } + + setPrefs(next: Partial): void { + const merged = { ...this._prefs, ...next }; + if (merged.side === this._prefs.side && merged.tab === this._prefs.tab && merged.darkPage === this._prefs.darkPage) return; + this._prefs = merged; + writeJson(PREFS_KEY, merged); + this.events.emit('prefs', merged); + } + + private set(next: Partial): void { + this._state = { ...this._state, ...next }; + this.events.emit('state', this._state); + } + + async open(itemId: string): Promise { + const ask = ++this.ask; + const same = this._state.doc?.itemId === itemId && (this._state.phase === 'ready' || this._state.phase === 'loading'); + if (same && this._state.doc) { this.events.emit('show', this._state.doc); return; } + this.set({ phase: 'resolving', itemId, progress: null, message: '' }); + try { + const item = await readerApi.item(itemId); + if (ask !== this.ask) return; + const title = String(item.csl.title ?? '').trim() || 'Untitled'; + let pdf = item.attachments.find((a) => a.mime === 'application/pdf' || /\.pdf$/i.test(a.name)) ?? null; + if (!pdf) { + const full = await readerApi.fulltext(itemId); + if (ask !== this.ask) return; + if (!full.can_fetch_pdf) throw new Error('This item has no PDF attached, and FormCite knows no open-access copy to get.'); + this.set({ phase: 'fetching', message: 'Getting the PDF from arXiv' }); + const got = await readerApi.fetchPdf(itemId); + if (ask !== this.ask) return; + pdf = got.attachment; + } + const doc: ReaderDoc = { itemId, attachmentId: pdf.id, title, name: pdf.name || `${title}.pdf` }; + this.set({ phase: 'loading', doc, progress: 0, message: 'Opening the paper' }); + this.events.emit('show', doc); + } catch (e) { + if (ask !== this.ask) return; + this.set({ phase: 'error', message: errText(e) }); + } + } + + progress(attachmentId: string, fraction: number | null): void { + if (this._state.doc?.attachmentId !== attachmentId || this._state.phase !== 'loading') return; + const p = fraction === null ? null : Math.max(0, Math.min(1, fraction)); + if (p === this._state.progress) return; + this.set({ progress: p }); + } + + loaded(attachmentId: string): void { + if (this._state.doc?.attachmentId !== attachmentId) return; + this.set({ phase: 'ready', progress: 1, message: '' }); + } + + failed(attachmentId: string, error: unknown): void { + if (this._state.doc?.attachmentId !== attachmentId) return; + this.set({ phase: 'error', message: `The PDF could not be opened: ${errText(error)}` }); + } + + close(): void { + if (this._state.phase === 'resolving' || this._state.phase === 'fetching' || this._state.phase === 'error') { + this.ask++; + this.set({ phase: 'idle', itemId: null, doc: null, progress: null, message: '' }); + } + this.events.emit('close', null); + } + + spot(attachmentId: string): Spot | null { + const all = readJson>(SPOTS_KEY); + const found = all?.[attachmentId]; + return found && Number.isInteger(found.page) && found.page > 0 ? found : null; + } + + remember(attachmentId: string, spot: Spot): void { + const all = readJson>(SPOTS_KEY) ?? {}; + const was = all[attachmentId]; + if (was && was.page === spot.page && was.scale === spot.scale) return; + delete all[attachmentId]; + all[attachmentId] = spot; + const keys = Object.keys(all); + for (const k of keys.slice(0, Math.max(0, keys.length - SPOTS_KEPT))) delete all[k]; + writeJson(SPOTS_KEY, all); + } +} + +export const reader = new ReaderModel(); diff --git a/frontend/src/io/reader.ts b/frontend/src/io/reader.ts new file mode 100644 index 0000000..2a4634b --- /dev/null +++ b/frontend/src/io/reader.ts @@ -0,0 +1,15 @@ +import { api } from './api'; +import { detailApi } from './detail'; +import { keyHeaders } from './window-key'; + +const enc = encodeURIComponent; + +export const readerApi = { + item: detailApi.item, + fulltext: detailApi.fulltext, + fetchPdf: detailApi.fetchPdf, + openSystem: detailApi.openAttachment, + fileUrl: (attachmentId: string): string => `/api/library/attachments/${enc(attachmentId)}/file`, + fileHeaders: (): Record => keyHeaders(), + openUrl: (url: string) => api.post<{ url: string }>('/library/open-url', { url }), +}; diff --git a/frontend/src/styles/reader.css b/frontend/src/styles/reader.css new file mode 100644 index 0000000..d1e5052 --- /dev/null +++ b/frontend/src/styles/reader.css @@ -0,0 +1,101 @@ +.fc-panes[data-view="reader"] > .fc-view[data-pane="reader"] { display: grid; } +.fc-panes[data-view="reader"] .fc-tb-title > [data-v="reader"] { display: inline; } +.fc-rd-host { overflow: hidden; } +.fc-dt-btn.fc-dt-pdf { border-color: var(--accent-color); background: var(--accent-color); color: var(--text-on-accent); font-weight: var(--weight-medium); } +.fc-dt-btn.fc-dt-pdf:hover:not(:disabled) { background: var(--accent-color-hover); } +.fc-dt-btn.fc-dt-sys { width: 28px; padding: 0; justify-content: center; color: var(--text-secondary); } + +.fc-rd { + --fc-rd-bar-h: 40px; + --fc-rd-side-w: 184px; + --fc-rd-thumb-w: 112px; + --fc-rd-stage: var(--ground); + position: absolute; + inset: 0; + display: grid; + grid-template-rows: var(--fc-rd-bar-h) minmax(0, 1fr); + min-width: 0; + min-height: 0; + font-size: var(--fs-12); +} + +.fc-rd-bar { display: flex; align-items: center; gap: var(--space-1); min-width: 0; padding: 0 var(--space-2); border-bottom: 1px solid var(--line-1); background: var(--sheet); } +.fc-rd-btn { flex: none; display: inline-flex; align-items: center; justify-content: center; gap: var(--space-1); height: 28px; padding: 0 var(--space-2); border: 1px solid transparent; border-radius: var(--radius-sm); background: transparent; color: var(--text-secondary); font: inherit; cursor: pointer; } +.fc-rd-btn.is-icon { width: 28px; padding: 0; } +.fc-rd-btn:hover:not(:disabled) { background: var(--bg-hover); color: var(--text-primary); } +.fc-rd-btn:disabled { opacity: 0.4; cursor: default; } +.fc-rd-btn[aria-pressed="true"] { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-color); } +.fc-rd-back { border-color: var(--line-2); color: var(--text-primary); } +.fc-rd-title { flex: 1 1 auto; min-width: 0; padding: 0 var(--space-2); color: var(--text-primary); font-weight: var(--weight-semibold); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.fc-rd-pages { flex: none; display: inline-flex; align-items: center; gap: var(--space-1h); color: var(--text-muted); font-variant-numeric: tabular-nums; } +.fc-rd-page { width: 5ch; height: 24px; padding: 0 var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--bg-input); color: var(--text-primary); font: inherit; font-variant-numeric: tabular-nums; text-align: right; } +.fc-rd-page:focus { outline: none; border-color: var(--accent); } +.fc-rd-of { display: inline-block; width: 7ch; white-space: nowrap; } +.fc-rd-zoom { flex: none; display: inline-flex; align-items: center; gap: 2px; } +.fc-rd-scale { width: 104px; height: 24px; padding: 0 var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--bg-input); color: var(--text-primary); font: inherit; font-variant-numeric: tabular-nums; } +.fc-rd-sep { flex: none; width: 1px; height: 18px; margin: 0 var(--space-1); background: var(--line-1); } + +.fc-rd-body { position: relative; display: grid; grid-template-columns: 0 minmax(0, 1fr); min-width: 0; min-height: 0; } +.fc-rd.is-side .fc-rd-body { grid-template-columns: var(--fc-rd-side-w) minmax(0, 1fr); } +.fc-rd-side { display: grid; grid-template-rows: 32px minmax(0, 1fr); min-width: 0; min-height: 0; overflow: hidden; border-right: 1px solid var(--line-1); background: var(--sheet); visibility: hidden; } +.fc-rd.is-side .fc-rd-side { visibility: visible; } +.fc-rd-tabs { display: flex; border-bottom: 1px solid var(--line-1); } +.fc-rd-tab { flex: 1 1 0; height: 32px; padding: 0; border: 0; border-bottom: 2px solid transparent; background: transparent; color: var(--text-secondary); font: inherit; cursor: pointer; } +.fc-rd-tab:hover { color: var(--text-primary); } +.fc-rd-tab.is-on { border-bottom-color: var(--accent); color: var(--text-primary); } +.fc-rd-thumbs, .fc-rd-outline { min-height: 0; overflow: auto; overscroll-behavior: contain; } +.fc-rd-thumbs[hidden], .fc-rd-outline[hidden] { display: none; } +.fc-rd-thumbs { display: grid; align-content: start; justify-items: center; gap: var(--space-2); padding: var(--space-3) 0; } +.fc-rd-thumb { display: grid; justify-items: center; gap: var(--space-1); padding: var(--space-1); border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-muted); font: inherit; font-size: var(--fs-11); font-variant-numeric: tabular-nums; cursor: pointer; } +.fc-rd-thumb:hover { background: var(--bg-hover); } +.fc-rd-thumb-box { display: block; width: var(--fc-rd-thumb-w); aspect-ratio: var(--fc-rd-thumb-ratio, 612 / 792); background: #fff; box-shadow: 0 0 0 1px var(--line-2); } +.fc-rd-thumb-box > canvas { display: block; width: 100%; height: 100%; object-fit: contain; } +.fc-rd-thumb.is-on { color: var(--accent-color); } +.fc-rd-thumb.is-on .fc-rd-thumb-box { box-shadow: 0 0 0 2px var(--accent-color); } +.fc-rd-outline { padding: var(--space-2) var(--space-1); } +.fc-rd-none { margin: var(--space-2); color: var(--text-muted); } +.fc-rd-none[hidden] { display: none; } +.fc-rd-tree ul { margin: 0; padding: 0 0 0 var(--space-3); list-style: none; } +.fc-rd-tree > ul { padding-left: 0; } +.fc-rd-ol { display: block; width: 100%; min-height: 24px; padding: var(--space-1) var(--space-2); border: 0; border-radius: var(--radius-sm); background: transparent; color: var(--text-secondary); font: inherit; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; } +.fc-rd-ol:hover { background: var(--bg-hover); color: var(--text-primary); } + +.fc-rd-stage { position: relative; min-width: 0; min-height: 0; background: var(--fc-rd-stage); } +.fc-rd-scroll { position: absolute; inset: 0; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; user-select: text; -webkit-user-select: text; outline: none; } +.fc-rd .pdfViewer { --page-bg-color: #fff; padding: var(--space-3) 0; } +.fc-rd .pdfViewer.removePageBorders .page { margin: 0 auto var(--space-3); box-shadow: 0 1px 3px rgb(0 0 0 / 0.28), 0 0 0 1px rgb(0 0 0 / 0.06); } +.fc-rd.is-dark-page .pdfViewer { --page-bg-color: #1c1c1e; } +.fc-rd.is-dark-page .pdfViewer .page .canvasWrapper, +.fc-rd.is-dark-page .fc-rd-thumb-box { filter: invert(0.88) hue-rotate(180deg); } + +.fc-rd-find { position: absolute; top: var(--space-2); right: var(--space-4); z-index: var(--z-raised); display: flex; align-items: center; gap: 2px; padding: var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-raised, var(--sheet)); box-shadow: var(--shadow-md); } +.fc-rd-find[hidden] { display: none; } +.fc-rd-find-q { width: 220px; height: 26px; padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--bg-input); color: var(--text-primary); font: inherit; } +.fc-rd-find-q:focus { outline: none; border-color: var(--accent); } +.fc-rd-find.is-miss .fc-rd-find-q { border-color: var(--danger); } +.fc-rd-find-n { display: inline-block; width: 11ch; padding: 0 var(--space-1); color: var(--text-muted); font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; overflow: hidden; } + +.fc-rd-veil { position: absolute; inset: 0; z-index: var(--z-raised); display: grid; place-items: center; background: var(--fc-rd-stage); opacity: 0; visibility: hidden; pointer-events: none; } +.fc-rd:is([data-phase="resolving"], [data-phase="fetching"], [data-phase="loading"]) .fc-rd-veil { opacity: 1; visibility: visible; pointer-events: auto; transition: opacity 160ms ease 220ms, visibility 0s linear 220ms; } +.fc-rd[data-phase="error"] .fc-rd-veil { opacity: 1; visibility: visible; pointer-events: auto; } +.fc-rd-card { display: grid; justify-items: center; gap: var(--space-3); width: min(380px, 80%); text-align: center; } +.fc-rd-msg { min-height: 2.7em; margin: 0; color: var(--text-secondary); font-size: var(--fs-13); } +.fc-rd[data-phase="error"] .fc-rd-msg { color: var(--danger-text); } +.fc-rd-track { position: relative; width: 220px; height: 3px; overflow: hidden; border-radius: var(--radius-pill); background: var(--line-1); } +.fc-rd[data-phase="error"] .fc-rd-track { visibility: hidden; } +.fc-rd-fill { position: absolute; inset: 0 auto 0 0; width: 30%; border-radius: inherit; background: var(--accent-color); animation: fc-rd-slide 1.1s ease-in-out infinite; } +.fc-rd.is-known .fc-rd-fill { animation: none; transition: width 120ms linear; } +.fc-rd-acts { display: flex; gap: var(--space-2); visibility: hidden; } +.fc-rd[data-phase="error"] .fc-rd-acts { visibility: visible; } +.fc-rd-acts > [hidden] { display: none; } +@keyframes fc-rd-slide { from { transform: translateX(-100%); } to { transform: translateX(340%); } } +@media (prefers-reduced-motion: reduce) { .fc-rd-fill { animation: none; width: 100%; opacity: 0.5; } } + +.fc-rd-print { display: none; } +@media print { + html, body { height: auto !important; overflow: visible !important; background: #fff !important; } + body > :not(.fc-rd-print) { display: none !important; } + .fc-rd-print { display: block; } + .fc-rd-print > img { display: block; width: 100%; height: auto; break-after: page; } + @page { margin: 0; } +} diff --git a/frontend/src/ui/icons.ts b/frontend/src/ui/icons.ts index 2f99758..3943276 100644 --- a/frontend/src/ui/icons.ts +++ b/frontend/src/ui/icons.ts @@ -14,6 +14,21 @@ export const ICONS: Record = { sliders: ``, close: ``, info: ``, + paper: ``, + back: ``, + panelLeft: ``, + zoomIn: ``, + zoomOut: ``, + search: ``, + chevronUp: ``, + chevronDown: ``, + moon: ``, + download: ``, + print: ``, + external: ``, + fitWidth: ``, + fitPage: ``, + more: ``, }; export function icon(name: string, size = 16): string { diff --git a/frontend/src/ui/reader-view.ts b/frontend/src/ui/reader-view.ts new file mode 100644 index 0000000..c10ca0d --- /dev/null +++ b/frontend/src/ui/reader-view.ts @@ -0,0 +1,316 @@ +import { AnnotationMode, getDocument, GlobalWorkerOptions, type PDFDocumentLoadingTask, type PDFDocumentProxy } from 'pdfjs-dist'; +import { EventBus, LinkTarget, PDFFindController, PDFLinkService, PDFViewer } from 'pdfjs-dist/web/pdf_viewer.mjs'; +import workerSrc from 'pdfjs-dist/build/pdf.worker.min.mjs?url'; +import 'pdfjs-dist/web/pdf_viewer.css'; + +GlobalWorkerOptions.workerSrc = workerSrc; + +const ASSETS = '/pdfjs/'; +const THUMB_W = 112; +const THUMBS_KEPT = 60; +const PRINT_SCALE = 150 / 72; +const MIN_SCALE = 0.25; +const MAX_SCALE = 8; + +export interface OutlineNode { title: string; dest: unknown; url: string | null; items: OutlineNode[] } + +export interface ViewHooks { + page(page: number, count: number): void; + scale(value: string, scale: number): void; + find(current: number, total: number, state: number): void; + progress(fraction: number | null): void; + outline(nodes: OutlineNode[]): void; + link(url: string, event: MouseEvent): boolean; +} + +export interface Spot { page: number; scale: string } + +export class PdfView { + private readonly bus = new EventBus(); + private readonly links: PDFLinkService; + private readonly finder: PDFFindController; + private readonly viewer: PDFViewer; + private task: PDFDocumentLoadingTask | null = null; + private doc: PDFDocumentProxy | null = null; + private openToken = 0; + private thumbsHost: HTMLElement | null = null; + private thumbsSeen: IntersectionObserver | null = null; + private thumbQueue: number[] = []; + private thumbBusy = false; + private thumbsDrawn: number[] = []; + private query = ''; + + constructor(private readonly scroll: HTMLDivElement, private readonly hooks: ViewHooks) { + this.links = new PDFLinkService({ eventBus: this.bus, externalLinkTarget: LinkTarget.BLANK, externalLinkRel: 'noopener noreferrer nofollow' }); + this.finder = new PDFFindController({ eventBus: this.bus, linkService: this.links }); + this.viewer = new PDFViewer({ + container: scroll, + viewer: scroll.firstElementChild as HTMLDivElement, + eventBus: this.bus, + linkService: this.links, + findController: this.finder, + removePageBorders: true, + annotationMode: AnnotationMode.ENABLE, + enableAutoLinking: true, + supportsPinchToZoom: true, + imagesRightClickMinSize: -1, + }); + this.links.setViewer(this.viewer); + this.bus.on('pagechanging', (e: { pageNumber: number }) => { this.hooks.page(e.pageNumber, this.viewer.pagesCount); this.markThumb(e.pageNumber); }); + this.bus.on('scalechanging', (e: { scale: number; presetValue?: string }) => this.hooks.scale(e.presetValue ?? String(e.scale), e.scale)); + this.bus.on('updatefindmatchescount', (e: { matchesCount: { current: number; total: number } }) => this.hooks.find(e.matchesCount.current, e.matchesCount.total, -1)); + this.bus.on('updatefindcontrolstate', (e: { state: number; matchesCount: { current: number; total: number } }) => this.hooks.find(e.matchesCount?.current ?? 0, e.matchesCount?.total ?? 0, e.state)); + scroll.addEventListener('wheel', (e) => { + if (!e.ctrlKey && !e.metaKey) return; + e.preventDefault(); + if (!this.doc) return; + const factor = Math.exp(-e.deltaY / (e.deltaMode === 1 ? 6 : 120)); + const next = this.viewer.currentScale * factor; + if ((next < MIN_SCALE && factor < 1) || (next > MAX_SCALE && factor > 1)) return; + this.viewer.updateScale({ drawingDelay: 300, scaleFactor: factor, origin: [e.clientX, e.clientY] }); + }, { passive: false }); + let width = 0; + let frame = 0; + new ResizeObserver(() => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { + const w = scroll.clientWidth; + if (!this.doc || !w || w === width) { width = w || width; return; } + width = w; + const value = this.viewer.currentScaleValue; + if (value && Number.isNaN(Number(value))) this.viewer.currentScaleValue = value; + }); + }).observe(scroll); + scroll.addEventListener('click', (e) => { + const a = (e.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null; + if (!a || !scroll.contains(a)) return; + const href = a.getAttribute('href') ?? ''; + if (!/^(https?:|mailto:)/i.test(href)) return; + if (this.hooks.link(a.href, e)) e.preventDefault(); + }); + } + + get pages(): number { return this.doc ? this.viewer.pagesCount : 0; } + get page(): number { return this.viewer.currentPageNumber; } + get scaleValue(): string { return this.viewer.currentScaleValue; } + get loaded(): boolean { return this.doc !== null; } + + async open(url: string, headers: Record, spot: Spot | null): Promise { + const token = ++this.openToken; + this.close(); + const task = getDocument({ + url, + httpHeaders: headers, + cMapUrl: `${ASSETS}cmaps/`, + cMapPacked: true, + standardFontDataUrl: `${ASSETS}standard_fonts/`, + wasmUrl: `${ASSETS}wasm/`, + iccUrl: `${ASSETS}iccs/`, + enableXfa: false, + }); + this.task = task; + task.onProgress = ({ loaded, total }: { loaded: number; total: number }) => { if (token === this.openToken) this.hooks.progress(total ? loaded / total : null); }; + const doc = await task.promise; + if (token !== this.openToken) { void task.destroy(); throw new Error('superseded'); } + this.doc = doc; + const ready = new Promise((resolve) => { + const done = (): void => { this.bus.off('pagesinit', done); resolve(); }; + this.bus.on('pagesinit', done); + }); + this.viewer.setDocument(doc); + this.links.setDocument(doc, null); + await ready; + if (token !== this.openToken) throw new Error('superseded'); + this.viewer.currentScaleValue = spot?.scale || 'page-width'; + const page = spot && spot.page <= doc.numPages ? spot.page : 1; + if (page > 1) this.viewer.currentPageNumber = page; + else this.hooks.page(1, doc.numPages); + void doc.getOutline().then((raw) => { if (token === this.openToken) this.hooks.outline(toNodes(raw ?? [])); }, () => this.hooks.outline([])); + } + + close(): void { + this.stopThumbs(); + this.finder.setDocument?.(null as unknown as PDFDocumentProxy); + if (this.doc || this.task) { + this.viewer.setDocument(null as unknown as PDFDocumentProxy); + this.links.setDocument(null, null); + } + const task = this.task; + this.task = null; + this.doc = null; + if (task) void task.destroy(); + } + + goto(page: number): void { + if (!this.doc) return; + this.viewer.currentPageNumber = Math.max(1, Math.min(this.viewer.pagesCount, Math.round(page))); + } + + step(delta: number): void { + if (!this.doc) return; + if (delta > 0) this.viewer.nextPage(); else this.viewer.previousPage(); + } + + setScale(value: string): void { + if (!this.doc) return; + this.viewer.currentScaleValue = value; + } + + zoom(dir: 1 | -1): void { + if (!this.doc) return; + if (dir > 0) this.viewer.increaseScale(); else this.viewer.decreaseScale(); + } + + goDest(dest: unknown): void { + if (this.doc && dest) void this.links.goToDestination(dest as string); + } + + find(query: string, previous = false): void { + const again = query === this.query && query !== ''; + this.query = query; + this.bus.dispatch('find', { source: this, type: again ? 'again' : '', query, caseSensitive: false, entireWord: false, highlightAll: true, findPrevious: previous, matchDiacritics: false }); + } + + findClose(): void { + this.query = ''; + this.bus.dispatch('findbarclose', { source: this }); + } + + async data(): Promise { + return this.doc ? this.doc.getData() : null; + } + + async print(onStep: (done: number, total: number) => void): Promise { + const doc = this.doc; + if (!doc) return null; + const root = document.createElement('div'); + root.className = 'fc-rd-print'; + const urls: string[] = []; + for (let n = 1; n <= doc.numPages; n++) { + const page = await doc.getPage(n); + const vp = page.getViewport({ scale: PRINT_SCALE }); + const canvas = document.createElement('canvas'); + canvas.width = Math.floor(vp.width); + canvas.height = Math.floor(vp.height); + await page.render({ canvas, viewport: vp, intent: 'print', annotationMode: AnnotationMode.ENABLE_STORAGE }).promise; + const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); + canvas.width = 0; + canvas.height = 0; + page.cleanup(); + if (!blob) continue; + const url = URL.createObjectURL(blob); + urls.push(url); + const img = document.createElement('img'); + img.src = url; + img.alt = ''; + root.append(img); + onStep(n, doc.numPages); + if (doc !== this.doc) { for (const u of urls) URL.revokeObjectURL(u); return null; } + } + root.dataset.urls = urls.join(' '); + return root; + } + + thumbs(host: HTMLElement, onPick: (page: number) => void): void { + const doc = this.doc; + this.stopThumbs(); + this.thumbsHost = host; + if (!doc) { host.replaceChildren(); return; } + void doc.getPage(1).then((first) => { + if (doc !== this.doc) return; + const vp = first.getViewport({ scale: 1 }); + host.style.setProperty('--fc-rd-thumb-ratio', `${vp.width} / ${vp.height}`); + const frag = document.createDocumentFragment(); + for (let n = 1; n <= doc.numPages; n++) { + const b = document.createElement('button'); + b.type = 'button'; + b.className = 'fc-rd-thumb'; + b.dataset.page = String(n); + b.setAttribute('aria-label', `Page ${n}`); + b.innerHTML = `${n}`; + frag.append(b); + } + host.replaceChildren(frag); + host.onclick = (e) => { + const b = (e.target as Element).closest('.fc-rd-thumb'); + if (b?.dataset.page) onPick(Number(b.dataset.page)); + }; + this.thumbsSeen = new IntersectionObserver((entries) => { + for (const en of entries) { + if (!en.isIntersecting) continue; + const n = Number((en.target as HTMLElement).dataset.page); + if (!(en.target as HTMLElement).dataset.drawn && !this.thumbQueue.includes(n)) this.thumbQueue.push(n); + } + void this.pumpThumbs(doc); + }, { root: host, rootMargin: '300px 0px' }); + for (const b of host.children) this.thumbsSeen.observe(b); + this.markThumb(this.viewer.currentPageNumber || 1); + }); + } + + private stopThumbs(): void { + this.thumbsSeen?.disconnect(); + this.thumbsSeen = null; + this.thumbQueue = []; + this.thumbsDrawn = []; + if (this.thumbsHost) this.thumbsHost.onclick = null; + } + + private async pumpThumbs(doc: PDFDocumentProxy): Promise { + if (this.thumbBusy) return; + this.thumbBusy = true; + try { + while (this.thumbQueue.length && doc === this.doc && this.thumbsHost) { + const n = this.thumbQueue.shift() as number; + const b = this.thumbsHost.children[n - 1] as HTMLElement | undefined; + if (!b || b.dataset.drawn) continue; + const canvas = b.querySelector('canvas'); + if (!canvas) continue; + const page = await doc.getPage(n); + const base = page.getViewport({ scale: 1 }); + const ratio = Math.min(2, window.devicePixelRatio || 1); + const vp = page.getViewport({ scale: (THUMB_W / base.width) * ratio }); + const off = document.createElement('canvas'); + off.width = Math.floor(vp.width); + off.height = Math.floor(vp.height); + await page.render({ canvas: off, viewport: vp, annotationMode: AnnotationMode.DISABLE }).promise; + page.cleanup(); + if (doc !== this.doc) return; + canvas.width = off.width; + canvas.height = off.height; + canvas.getContext('2d')?.drawImage(off, 0, 0); + off.width = 0; + off.height = 0; + b.dataset.drawn = '1'; + this.thumbsDrawn.push(n); + while (this.thumbsDrawn.length > THUMBS_KEPT) { + const old = this.thumbsDrawn.shift() as number; + const ob = this.thumbsHost.children[old - 1] as HTMLElement | undefined; + const oc = ob?.querySelector('canvas'); + if (ob && oc) { delete ob.dataset.drawn; oc.width = 0; oc.height = 0; } + } + } + } finally { + this.thumbBusy = false; + } + } + + private markThumb(page: number): void { + const host = this.thumbsHost; + if (!host) return; + host.querySelector('.fc-rd-thumb.is-on')?.classList.remove('is-on'); + const b = host.children[page - 1] as HTMLElement | undefined; + if (!b) return; + b.classList.add('is-on'); + if (host.offsetParent !== null) { + const top = b.offsetTop - host.offsetTop; + if (top < host.scrollTop || top + b.offsetHeight > host.scrollTop + host.clientHeight) host.scrollTop = Math.max(0, top - host.clientHeight / 3); + } + } +} + +interface RawOutline { title: string; dest: unknown; url: string | null; items: RawOutline[] } + +function toNodes(raw: RawOutline[]): OutlineNode[] { + return raw.map((r) => ({ title: r.title, dest: r.dest, url: r.url ?? null, items: toNodes(r.items ?? []) })); +} diff --git a/frontend/src/ui/reader.ts b/frontend/src/ui/reader.ts new file mode 100644 index 0000000..9a7d126 --- /dev/null +++ b/frontend/src/ui/reader.ts @@ -0,0 +1,383 @@ +import type { Engine, ViewId } from '../engine'; +import { reader, type ReaderDoc, type ReaderPrefs, type ReaderState } from '../engine/reader'; +import { readerApi } from '../io/reader'; +import { el, escapeHtml, isMac, q, setClass, setDisabled, setHidden, setText, setTitle, setValue } from './dom'; +import { icon } from './icons'; +import { anyDialogOpen } from './menu'; +import { inTauri } from './native-menu'; +import { toast } from './toast'; +import type { OutlineNode, PdfView } from './reader-view'; +import '../styles/reader.css'; + +const MOD = isMac ? 'Cmd' : 'Ctrl'; + +export const READER_PANE = ` +
+

${icon('paper', 14)}Paper

+
+
`; + +const SCALES: Array<[string, string]> = [['page-width', 'Fit width'], ['page-fit', 'Fit page'], ['auto', 'Automatic'], ['0.5', '50%'], ['0.75', '75%'], ['1', '100%'], ['1.25', '125%'], ['1.5', '150%'], ['2', '200%'], ['3', '300%'], ['4', '400%']]; + +const btn = (act: string, name: string, label: string, extra = ''): string => + ``; + +const BODY = `
+ +
+ +
+
+ +
+
+

+
+
+ + +
+
+
+
+
+
`; + +const isTyping = (t: EventTarget | null): boolean => t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || (t instanceof HTMLElement && t.isContentEditable); + +export function mountReader(engine: Engine, host: HTMLElement): void { + host.append(el(BODY)); + const root = q(host, '.fc-rd'); + const title = q(root, '.fc-rd-title'); + const pageIn = q(root, '.fc-rd-page'); + const pageOf = q(root, '.fc-rd-of'); + const scaleSel = q(root, '.fc-rd-scale'); + const custom = q(root, '.fc-rd-scale-custom'); + const sideBtn = q(root, '[data-act="side"]'); + const findBtn = q(root, '.fc-rd-bar [data-act="find"]'); + const darkBtn = q(root, '[data-act="dark"]'); + const tabs = Array.from(root.querySelectorAll('.fc-rd-tab')); + const thumbs = q(root, '.fc-rd-thumbs'); + const outline = q(root, '.fc-rd-outline'); + const tree = q(root, '.fc-rd-tree'); + const none = q(root, '.fc-rd-none'); + const scroll = q(root, '.fc-rd-scroll'); + const findBar = q(root, '.fc-rd-find'); + const findQ = q(root, '.fc-rd-find-q'); + const findN = q(root, '.fc-rd-find-n'); + const msg = q(root, '.fc-rd-msg'); + const fill = q(root, '.fc-rd-fill'); + const retryBtn = q(root, '.fc-rd-acts [data-act="retry"]'); + const tools = Array.from(root.querySelectorAll('.fc-rd-bar [data-act="zoom-in"], .fc-rd-bar [data-act="zoom-out"], .fc-rd-bar [data-act="find"], .fc-rd-bar [data-act="download"], .fc-rd-bar [data-act="print"]')); + + let view: PdfView | null = null; + let viewLoad: Promise | null = null; + let shownFor = ''; + let back: ViewId = 'library'; + let saveTimer = 0; + + const active = (): boolean => (engine.library.view as string) === 'reader'; + const setPressed = (b: HTMLElement, on: boolean): void => { if (b.getAttribute('aria-pressed') !== String(on)) b.setAttribute('aria-pressed', String(on)); }; + + const loadView = (): Promise => { + viewLoad ??= import('./reader-view').then(({ PdfView: Ctor }) => { + view = new Ctor(scroll, { + page: (page, count) => { + if (document.activeElement !== pageIn) setValue(pageIn, String(page)); + setText(pageOf, `of ${count}`); + queueSave(); + }, + scale: (value, scale) => { + const known = SCALES.some(([v]) => v === value); + const pct = `${Math.round(scale * 100)}%`; + if (!known) setText(custom, pct); + if (scaleSel.value !== (known ? value : 'custom')) scaleSel.value = known ? value : 'custom'; + queueSave(); + }, + find: (current, total, state) => { + const text = !findQ.value ? '' : state === 1 && !total ? 'No matches' : total ? `${current} of ${total}` : state === 3 ? '' : findN.textContent ?? ''; + setText(findN, text); + setClass(findBar, 'is-miss', state === 1 && !total); + }, + progress: (f) => { const d = reader.state.doc; if (d) reader.progress(d.attachmentId, f); }, + outline: (nodes) => paintOutline(nodes), + link: (url) => { + if (!inTauri()) return false; + readerApi.openUrl(url).catch((e: Error) => toast(`Could not open the link: ${e.message}`, 'error')); + return true; + }, + }); + return view; + }); + return viewLoad; + }; + + const queueSave = (): void => { + window.clearTimeout(saveTimer); + saveTimer = window.setTimeout(() => { + const d = reader.state.doc; + if (!view || !d || reader.state.phase !== 'ready' || shownFor !== d.attachmentId) return; + reader.remember(d.attachmentId, { page: view.page, scale: view.scaleValue }); + }, 250); + }; + + const paintOutline = (nodes: OutlineNode[]): void => { + const list = (items: OutlineNode[]): HTMLElement => { + const ul = document.createElement('ul'); + for (const n of items) { + const li = document.createElement('li'); + const b = document.createElement('button'); + b.type = 'button'; + b.className = 'fc-rd-ol'; + b.textContent = n.title || 'Untitled'; + b.title = n.title; + b.addEventListener('click', () => { if (n.url) { if (!inTauri()) window.open(n.url, '_blank', 'noopener'); else void readerApi.openUrl(n.url); } else view?.goDest(n.dest); }); + li.append(b); + if (n.items.length) li.append(list(n.items)); + ul.append(li); + } + return ul; + }; + tree.replaceChildren(...(nodes.length ? [list(nodes)] : [])); + setHidden(none, nodes.length > 0); + }; + + const applyPrefs = (p: Readonly): void => { + setClass(root, 'is-side', p.side); + setPressed(sideBtn, p.side); + setClass(root, 'is-dark-page', p.darkPage); + setPressed(darkBtn, p.darkPage); + for (const t of tabs) { + const on = t.dataset.tab === p.tab; + if (t.getAttribute('aria-selected') !== String(on)) t.setAttribute('aria-selected', String(on)); + setClass(t, 'is-on', on); + } + setHidden(thumbs, p.tab !== 'thumbs'); + setHidden(outline, p.tab !== 'outline'); + }; + applyPrefs(reader.prefs); + reader.events.on('prefs', applyPrefs); + + const paintState = (s: Readonly): void => { + if (root.dataset.phase !== s.phase) root.dataset.phase = s.phase; + setText(title, s.doc?.title ?? (s.phase === 'idle' ? '' : 'Opening the paper')); + setTitle(title, s.doc?.title ?? ''); + setText(msg, s.message || (s.phase === 'loading' ? 'Opening the paper' : '')); + const known = s.progress !== null && s.phase === 'loading'; + setClass(root, 'is-known', known); + const w = known ? `${Math.round((s.progress ?? 0) * 100)}%` : ''; + if (fill.style.width !== w) fill.style.width = w; + const ready = s.phase === 'ready'; + for (const b of tools) setDisabled(b, !ready); + setDisabled(pageIn as unknown as HTMLButtonElement, !ready); + setDisabled(scaleSel as unknown as HTMLButtonElement, !ready); + setHidden(retryBtn, s.phase !== 'error'); + }; + paintState(reader.state); + + const enter = (): void => { + if (!active()) { + back = (engine.library.view as string) === 'reader' ? 'library' : engine.library.view; + engine.library.setView('reader' as ViewId); + } + }; + + const show = async (d: ReaderDoc): Promise => { + enter(); + const v = await loadView(); + if (shownFor === d.attachmentId && v.loaded) { + reader.loaded(d.attachmentId); + scroll.focus({ preventScroll: true }); + return; + } + shownFor = d.attachmentId; + closeFind(); + tree.replaceChildren(); + setHidden(none, true); + try { + await v.open(readerApi.fileUrl(d.attachmentId), readerApi.fileHeaders(), reader.spot(d.attachmentId)); + if (reader.state.doc?.attachmentId !== d.attachmentId) return; + reader.loaded(d.attachmentId); + v.thumbs(thumbs, (n) => v.goto(n)); + if (active()) scroll.focus({ preventScroll: true }); + } catch (e) { + if (e instanceof Error && e.message === 'superseded') return; + shownFor = ''; + reader.failed(d.attachmentId, e); + } + }; + + reader.events.on('state', (s) => { + paintState(s); + if (s.phase === 'resolving') enter(); + }); + reader.events.on('show', (d) => { void show(d); }); + reader.events.on('close', () => { + closeFind(); + if (active()) engine.library.setView(back); + }); + engine.library.events.on('view', (v) => { if ((v as string) !== 'reader') closeFind(); }); + + const openFind = (): void => { + if (reader.state.phase !== 'ready') return; + setHidden(findBar, false); + setPressed(findBtn, true); + const sel = window.getSelection()?.toString().trim(); + if (sel && sel.length < 120 && !sel.includes('\n')) findQ.value = sel; + findQ.focus(); + findQ.select(); + if (findQ.value) view?.find(findQ.value); + }; + function closeFind(): void { + if (findBar.hidden) return; + setHidden(findBar, true); + setPressed(findBtn, false); + setText(findN, ''); + view?.findClose(); + if (active()) scroll.focus({ preventScroll: true }); + } + + const download = async (): Promise => { + const d = reader.state.doc; + const data = await view?.data(); + if (!d || !data) return; + const url = URL.createObjectURL(new Blob([data as BlobPart], { type: 'application/pdf' })); + const a = document.createElement('a'); + a.href = url; + a.download = /\.pdf$/i.test(d.name) ? d.name : `${d.name}.pdf`; + document.body.append(a); + a.click(); + a.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 30_000); + }; + + let printing = false; + const print = async (): Promise => { + if (!view || printing) return; + printing = true; + let last = 0; + try { + const sheet = await view.print((done, total) => { if (done === 1 || done - last >= 10 || done === total) { last = done; toast(`Preparing to print: page ${done} of ${total}`); } }); + if (!sheet) return; + document.body.append(sheet); + const urls = (sheet.dataset.urls ?? '').split(' ').filter(Boolean); + const done = (): void => { sheet.remove(); for (const u of urls) URL.revokeObjectURL(u); }; + window.addEventListener('afterprint', done, { once: true }); + await Promise.all(Array.from(sheet.querySelectorAll('img')).map((img) => img.decode().catch(() => undefined))); + window.print(); + } catch (e) { + toast(`Could not print: ${e instanceof Error ? e.message : String(e)}`, 'error'); + } finally { + printing = false; + } + }; + + const openSystem = (): void => { + const d = reader.state.doc; + if (!d) { toast('There is no PDF to open yet.'); return; } + readerApi.openSystem(d.attachmentId).then( + (r) => toast(String(r.opened_with ?? '') === 'formpdf' ? 'Opened in FormPDF.' : 'Opened in the system PDF viewer.'), + (e: Error) => toast(`Could not open: ${e.message}`, 'error'), + ); + }; + + const goBack = (): void => reader.close(); + + root.addEventListener('click', (e) => { + const b = (e.target as Element).closest('[data-act]'); + if (!b || b.disabled) return; + const act = b.dataset.act; + if (act === 'back') goBack(); + else if (act === 'side') reader.setPrefs({ side: !reader.prefs.side }); + else if (act === 'dark') reader.setPrefs({ darkPage: !reader.prefs.darkPage }); + else if (act === 'zoom-in') view?.zoom(1); + else if (act === 'zoom-out') view?.zoom(-1); + else if (act === 'find') { if (findBar.hidden) openFind(); else closeFind(); } + else if (act === 'find-next') view?.find(findQ.value, false); + else if (act === 'find-prev') view?.find(findQ.value, true); + else if (act === 'find-close') closeFind(); + else if (act === 'system') openSystem(); + else if (act === 'download') void download(); + else if (act === 'print') void print(); + else if (act === 'retry') { const id = reader.state.itemId ?? reader.state.doc?.itemId; if (id) { shownFor = ''; void reader.open(id); } } + }); + for (const t of tabs) t.addEventListener('click', () => reader.setPrefs({ tab: t.dataset.tab === 'outline' ? 'outline' : 'thumbs' })); + scaleSel.addEventListener('change', () => { if (scaleSel.value !== 'custom') { view?.setScale(scaleSel.value); scroll.focus({ preventScroll: true }); } }); + const commitPage = (): void => { + const n = Number.parseInt(pageIn.value, 10); + if (view && Number.isFinite(n)) view.goto(n); + if (view) setValue(pageIn, String(view.page)); + }; + pageIn.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { e.preventDefault(); commitPage(); scroll.focus({ preventScroll: true }); } + else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); if (view) pageIn.value = String(view.page); scroll.focus({ preventScroll: true }); } + }); + pageIn.addEventListener('blur', () => { if (view) pageIn.value = String(view.page); }); + pageIn.addEventListener('focus', () => pageIn.select()); + findQ.addEventListener('input', () => view?.find(findQ.value)); + findQ.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { e.preventDefault(); view?.find(findQ.value, e.shiftKey); } + else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeFind(); } + }); + + window.addEventListener('keydown', (e) => { + if (!active() || e.defaultPrevented || anyDialogOpen() || document.querySelector('.fc-menu:not([hidden])')) return; + if (!host.contains(document.activeElement) && document.activeElement !== document.body && document.activeElement !== null) return; + const mod = isMac ? e.metaKey : e.ctrlKey; + const k = e.key; + let done = true; + if (mod && !e.altKey && (k === 'f' || k === 'F') && !e.shiftKey) openFind(); + else if (mod && (k === 'g' || k === 'G')) { if (!findBar.hidden) view?.find(findQ.value, e.shiftKey); else done = false; } + else if (k === 'F3') view?.find(findQ.value, e.shiftKey); + else if (mod && !e.altKey && (k === '=' || k === '+')) view?.zoom(1); + else if (mod && !e.altKey && (k === '-' || k === '_')) view?.zoom(-1); + else if (mod && !e.altKey && k === '0') view?.setScale('page-width'); + else if (mod && !e.altKey && !e.shiftKey && (k === 'p' || k === 'P')) void print(); + else if (mod && !e.altKey && !e.shiftKey && (k === 's' || k === 'S')) void download(); + else if (mod) done = false; + else if (k === 'Escape') { if (!findBar.hidden) closeFind(); else goBack(); } + else if (isTyping(e.target)) done = false; + else if (k === 'ArrowRight' || k === 'n' || k === 'j') view?.step(1); + else if (k === 'ArrowLeft' || k === 'p' || k === 'k') view?.step(-1); + else if (k === 'Home' && view) view.goto(1); + else if (k === 'End' && view) view.goto(view.pages); + else if ((k === 'PageDown' || k === 'PageUp' || k === ' ') && document.activeElement !== scroll) { + const dir = k === 'PageUp' || (k === ' ' && e.shiftKey) ? -1 : 1; + scroll.scrollBy({ top: dir * scroll.clientHeight * 0.9 }); + } else done = false; + if (done) { e.preventDefault(); e.stopPropagation(); } + }, true); +} + +export function openPaper(itemId: string): void { + void reader.open(itemId); +} From 21a29ec38f9bf77184cb0c1727a0a5ab40bd1b6e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:11:04 -0500 Subject: [PATCH 29/36] feat(window): mount the paper reader and the collection window commands (0.16.0) The shell gains the reader's pane after Home, a Paper title in the top bar, and one mountReader call beside the other views. This commit also carries fc-agent's window collection commands, which share app.ts: collection.new {name, parent} makes a collection (under a parent found by name or id) and shows it, or asks for a name in the sidebar when called with none; collection.add-selection {collection, item?} adds the selected item, or the one named, to a collection; collection.show {collection} shows a collection's items. They live in ui/collections.ts with their calls in io/collections.ts (both new), and replace the old collection.new row in app.ts's command table. Both collection.new and collection.show were run once from MCP's window_command_run against an open window. --- frontend/src/io/collections.ts | 19 ++++++++++++++ frontend/src/ui/app.ts | 9 ++++--- frontend/src/ui/collections.ts | 48 ++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 frontend/src/io/collections.ts create mode 100644 frontend/src/ui/collections.ts diff --git a/frontend/src/io/collections.ts b/frontend/src/io/collections.ts new file mode 100644 index 0000000..5502ec1 --- /dev/null +++ b/frontend/src/io/collections.ts @@ -0,0 +1,19 @@ +import { api } from './api'; +import { sideApi, type CollectionRow } from './side'; + +export async function findCollection(key: string): Promise { + const wanted = key.trim(); + const rows = await sideApi.collections(); + const byId = rows.find((c) => c.id === wanted); + if (byId) return byId; + const named = rows.filter((c) => c.name.toLowerCase() === wanted.toLowerCase()); + if (named.length === 1) return named[0]; + throw new Error(named.length ? `${named.length} collections are named ${wanted}; give the id` : `no collection ${wanted}`); +} + +export const collectionsApi = { + find: findCollection, + create: (name: string, parentId: string | null) => sideApi.createCollection(name, parentId), + addItems: (id: string, itemIds: string[]) => + api.post(`/library/collections/${encodeURIComponent(id)}/items`, { item_ids: itemIds }), +}; diff --git a/frontend/src/ui/app.ts b/frontend/src/ui/app.ts index d2bef01..abecfa9 100644 --- a/frontend/src/ui/app.ts +++ b/frontend/src/ui/app.ts @@ -2,12 +2,14 @@ import type { Engine } from '../engine'; import { loadWindowKey, wasLaunched } from '../io/window-key'; import { bindConnections, CONNECTIONS_PANE, navItems, watchConnections } from './connections'; import { mountAdd } from './add'; +import { registerCollectionCommands } from './collections'; import { mountDetail } from './detail'; import { el, mountOnce, q, revealApp, setClass } from './dom'; import { mountDuplicates } from './duplicates'; import { icon } from './icons'; import { mountItemList } from './itemlist'; import { mountPreferences, openPreferences } from './preferences'; +import { mountReader, READER_PANE } from './reader'; import { DETAIL_START } from './start'; import { mountSide } from './side'; import { mountTrash } from './trash'; @@ -43,7 +45,7 @@ const SHELL = `
-

HomeItemsDuplicatesTrashNeeds a titleConnections

+

HomeItemsDuplicatesTrashNeeds a titleConnectionsPaper

@@ -73,7 +75,7 @@ const SHELL = `

${HOME_ICON}Home

-
+ ${READER_PANE}