diff --git a/.claude/skills/formcite/SKILL.md b/.claude/skills/formcite/SKILL.md index 6699ab1..8e5922d 100644 --- a/.claude/skills/formcite/SKILL.md +++ b/.claude/skills/formcite/SKILL.md @@ -18,9 +18,14 @@ 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. 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,20 +42,27 @@ 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 | +| 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 | +| 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 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/CHANGELOG.md b/CHANGELOG.md index f8a5715..384602e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 0.16.0 + +Read a paper inside FormCite, see agents' changes in the open window as they happen, and let Claude Code and the other agents do everything you can do in the app, collections included. + +### New +- **View paper.** A paper's PDF opens inside the window: continuous pages drawn sharp at any zoom, page thumbnails or the paper's outline, page number and count, fit width, fit page and percent zoom (Cmd or Ctrl with + and -, pinch), keyboard paging, find with highlighted matches, selectable text, working citation and web links, a dark-page mode, download and print. It remembers the last page of each paper. View paper is the main action in the details pane, on double-click or Enter on a row, in the row and Library menus and on Cmd+O (Ctrl+O elsewhere); Open in System Viewer stays on Cmd+Shift+O. A paper whose PDF is not attached yet fetches it first. The reader runs inside the app with no network. +- **The window follows every change to the library,** whoever makes it: an agent, the command line, an import or another tool. New papers, edits, tags, notes, files, Trash and collections appear within a second, in place, keeping your selection, scroll position and open details. Papers an agent adds glow briefly. +- **Agents can do everything you can.** Claude Code and the other agents in the dock reach every window command (views, selection, search, sort, the reader, Preferences, libraries, collections) and 65 tools for the library: collections (create, add, remove, rename, delete), editing any field, notes, tags, files, Trash, duplicates and merging, import and export, saved searches, relations and undo. Deleting forever, emptying Trash and deleting a collection ask you first. Approving connections and the network switches stay yours alone, and read-only access stays read-only. +- **Add many papers at once:** agents add up to 50 identifiers in one call, straight into a collection with tags if asked. + +### Fixed +- **Agents could not make a collection.** There was no tool for it, and the engine refused the dock's access with "Only the FormCite window can do this". Creating, renaming and filling collections now work for the dock's write access; deleting a collection over the engine's own routes stays with the window. +- **Adding many arXiv papers timed out.** Lookups queued behind each other and the wait counted against a 30 second limit. arXiv is now asked once for a whole batch, politely paced, retried when it asks to slow down, and cached; a retried add reports the paper it already added instead of making a second one. +- **Agents' answers were huge.** One paper came back as about 70,000 characters with every author and the abstract twice. Answers are now short by default, with the full record on request. +- **The window showed nothing an agent added until it was restarted.** +- **Quitting with the window open took about 30 seconds;** it now takes under a second. + +### Known issues +- Not yet tried inside the desktop app: printing and downloading from the reader, links opening in the browser, and copying through the Mac Edit menu. +- A library with fewer than four collections shows a little empty space in the Collections section, which keeps the Tags section from moving when a collection is added. + ## 0.15.2 On a Mac the menus are in the menu bar only, the agent and Preferences buttons sit at the top right as in FormPortal, Preferences floats over the window as in FormVis, a row in Items opens its details again, and an arXiv paper comes with its PDF. 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/README.md b/README.md index 5fb3036..872fde4 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.15.2 + version 0.16.0 TypeScript Python 3.12 or later macOS, Windows, Linux @@ -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/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index e3df1ee..21f7919 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for this side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.15.2 +Current build version: v0.16.0 Last updated: 2026-11-27 (US Eastern) · the lean rows route for the window's list and opening an attachment --- @@ -1783,3 +1783,61 @@ Before, quoted: - `body = gzip.decompress(body)`; - `body = net.fetch_bytes(arxiv.PDF_SERVICE, f"{arxiv.PDF_URL}{identifier}", limit=MAX_BYTES, accept=PDF_MIME)`; - `with os.fdopen(fd, "wb") as handle: handle.write(body)`. + +## app/store/migrations/0003_changes.sql, app/store/db.py, app/store/changes.py, app/core/origin.py, app/routers/changes.py · library changes reach the open window live {#app-changes-feed} + +The owner's report (2 Dec): Claude Code in the dock added 30 items, tagged them and later made a collection, and the open window showed "NOTHING IN THE APP" until a full quit and reopen. The window only ever learned about changes it made itself; nothing told it about anyone else's. + +**Why triggers, not a publish call in the service layer.** Writes reach the library from four places that do not share a process: the engine (window, agent tokens, MCP over HTTP), `./formcite cli`, `./formcite mcp` on stdio, and, as the evidence shows, a direct sqlite3 write. An in-memory bus in the engine would miss three of them. SQLite triggers on every library table record each write in `changes` whatever made it, in the same transaction, so a change is recorded exactly when it commits and a rolled-back write leaves no row. New write paths (fc-agent's collection tools and routes) need nothing extra. + +**Origin.** Triggers cannot see Python state, and a registered SQL function would break every connection that lacks it, including the sqlite3 shell. So the engine's `OriginStamp` middleware sets a ContextVar (`window` when the request carries a valid window key, `agent` otherwise), and `db.tx()` writes it into the one-row `change_origin` table right after `BEGIN IMMEDIATE` and clears it before `COMMIT`. The value is only ever visible inside that transaction, and SQLite allows one writer at a time, so no other writer can pick it up. Writes from another process, or from a thread that did not copy the context (`services/lookup_jobs.py`), carry no origin. FastAPI runs sync routes with `anyio.to_thread.run_sync`, which copies the context; checked: a window POST is stamped `window`, a bearer-token POST `agent`, a CLI write NULL. + +**The stream.** Server-sent events over a plain GET, so the window sends its key in the header as on every other call; a GET passes `WindowKeyGuard`, so the route checks the key itself (`window_only`). Each stream holds its own connection and polls `PRAGMA data_version` every 250 ms, which changes only when another connection commits, so an idle library costs one pragma per tick. New rows go out as one message per tick, with the window's own rows dropped and only the sequence moved on, so the window never applies its own change twice. More than 1000 waiting rows, a cursor past the end (a restored backup), or one older than the 5000 rows kept, answers `stale`, and the window reads every pane again once. + +**Why a stream lasts 30 seconds, and the exit check.** uvicorn waits for open responses on shutdown, and an endless stream kept `./formcite serve` alive after Ctrl+C until the stream ended: 29.8 s measured. The stream ends after 30 s and the window reconnects from its last sequence, which also exercises catch-up all the time. It also ends as soon as uvicorn's `should_exit` is set, read from the SIGINT handler uvicorn installs (`signal.getsignal(SIGINT).__self__`), so shutdown with the window open took 0.28 s. If uvicorn ever changes that handler, the 30 s cap still bounds the wait. The frozen sidecar exits on SIGTERM with `os._exit`, so the desktop app was never affected. + +**Retention.** `changes_prune` runs on every 500th row and keeps 5000, enough for a large import between two reconnects; a window further behind does one full re-read instead of replaying. + +## app/mcp/tools.py, app/mcp/compact.py, app/services/lookup_jobs.py, app/net/pace.py, app/net/fetch.py, app/core/window_key.py, app/routers/mcp_http.py · agents can make collections, lookups are polite, answers are small {#app-agent-collections-lookups} + +New in v0.16.0 (2026-12-02 EST, agent `fc-agent`). Evidence: the owner's Claude Code session in the 0.15.2 dock (`handoff/fc016-evidence/`), asked to collect arXiv papers into a new collection `llm-research`. + +**What failed, from the log.** (1) No MCP tool made a collection or filed an item. (2) `POST /api/library/collections` with the dock's write token answered `{"detail":"Only the FormCite window can do this"}`: `WindowKeyGuard` lets a token through only on `/api/cite/v1/` and `/mcp`. (3) About 20 parallel `lookup_preview` calls: the first 10 answered 3 s apart, every other one answered "The call took longer than 30 seconds and was given up" at the same moment, 02:22:51. That sentence is FormCite's own (`mcp/http.py` `too_slow`), not the client's. The arXiv pace (3 s, a lock held while sleeping) serialised them, and `asyncio.to_thread` ran them on the default pool, so the 30 s counted queue time too. `asyncio.wait_for` does not stop a thread, so a timed-out `add_by_identifier` (2407.01489) went on and committed its item at 02:23:33; the retry at 02:24:07 answered `duplicate_of 34ulcfghzi`. So it was not half-done, but the agent could not know. (4) `add_by_identifier` answered up to 70,901 characters and `list_items` with `limit: 5` 92,219. The limit was honoured (the store clamps and pages, and the saved result's schema shows `limit`); the size is the item shape: `csl` with every author and the abstract, `creators` with every author again, the abstract a second time, and the whole JSON repeated as a text block beside `structuredContent`. DeepSeek-V3 and DeepSeek-R1 have about 200 authors each. Measured here: DeepSeek-V3 whole is 60,421 characters as one `get_item` answer, compact 774. (5) `window_commands` answered `[]`: no bridge existed; fc-parity built it, see their section. + +**Which collection routes a token may use, and why.** The design rule in `cite_write.py` is that a write token may make ordinary library writes (add, import, tag) and that "no delete, trash or file attach is offered to a token". Making, renaming, moving and filling or emptying a collection are the same kind of write as tagging and lose nothing, so `AGENT_WRITES` in `core/window_key.py` admits exactly `POST /collections`, `PATCH /collections/{id}`, `POST` and `DELETE /collections/{id}/items` under `/api/library` with a write-scope bearer token, checked by `auth.check(token, "write")`, and records each in the service log with `ok` or `refused` from the response status (the guard wraps `send` to read it). `DELETE /collections/{id}` stays window-only over HTTP. The id pattern is `[A-Za-z0-9_-]+`, so no dot-segment path can match. A read token or none on those routes gets the old sentence plus the token's reason. Every other path keeps the old rule. + +**delete_collection.** FormCite's consent for agents is the pairing scope (`dock.py` clause 15: the dock gives no per-call consent), and the cite service gives tokens no delete. The MCP tool is the one way an agent deletes a collection: `destructiveHint: true` (`_describe` now reads `destructive` from the tool, which fc-parity's tools use too), so Claude Code and other clients ask the person; `confirm` must equal the collection's exact name; a collection with sub-collections is refused because the store's `ON DELETE CASCADE` would take them too; items are never touched. `create_collection` answers the existing collection when one with the same name sits under the same parent, so a retried call makes nothing new. Collections are named by id or exact name (case-folded); two with the same name answer an error listing their ids. + +**The lookup queue.** `services/lookup_jobs.py`: one worker thread for records, one for arXiv PDFs, a job of 1 to 50 identifiers. The record worker first guesses each identifier and asks arXiv for all of the job's arXiv ids in one `id_list` query (`arxiv.fetch_many`, chunks of 50; one id arXiv rejects spoils the whole query, so a failed batch just falls back to one call per id); results go into the one-hour cache in `lookup.resolve` (500 records, keyed by kind and cleaned value), then each identifier runs `lookup.add(..., fetch_pdf=False)`. PDFs wait on the second worker so ten queued records are not held behind ten downloads. `lookup.add` now does the duplicate check and the create under `_ADDING`, so the window's Add, the cite service and the queue can race and still make one item. Unfinished jobs with the same identifiers, collection and tags are joined, not repeated. Jobs live in memory and are forgotten at restart, oldest finished first past 200; a lost job only loses its status, never an item. + +**Answering inside 30 s.** `/mcp` now runs calls on its own 64-thread pool, and the limit counts from arrival. The arrival time goes into the call through a `ContextVar` (`run_in_executor` does not copy context, so the router runs `context.run`), and `http.budget` lets a tool wait at most until 22 s after arrival. Measured with 14 parallel `add_by_identifier` calls against live arXiv: answers between 1.1 s and 22.5 s, none timed out; the unfinished ones answered "Not finished yet" with a `job_id` and completed in the background. Over stdio there is no budget and `wait_seconds` (default 20) applies. + +**Pacing and retries.** A service may name a `group`; `pace.wait_turn` keys on it. arXiv's three services share `arxiv.org`, so the OAI fallback and PDF downloads no longer run on clocks of their own beside the API. A 429 or 503 is retried twice; `_from_status` keeps `Retry-After` (whole seconds only; an HTTP date falls back to 4 s then 8 s), capped at 20 s, set with `pace.hold` so the whole group waits. Crossref, DataCite, doi.org, Open Library and PubMed keep their own 1 s (PubMed its own) intervals and get the same retry. + +**Compact items.** `mcp/compact.py`: id, title, year, the first three family names and "and N more", the count, identifiers (DOI, arXiv from `number` or the URL, ISBN, PMID, URL), tags, collections (list results get them with one `collections.for_item` per item under the same session) and attachment count. `fields` names extra keys, `full: true` the stored item. The text block stays one line per item. The JSON is still sent twice (text block and `structuredContent`) as the 2025-11-25 tools page asks for backwards compatibility; compact items keep both small. + +**Checked** (scratch data folders `/tmp/fc016-agent-data` and `/tmp/fc016-agent-e2e`, engine on 8397, HTTP MCP with a `FormCite dock` write token, live arXiv through the proxy): `create_collection agentic-code`; one `add_by_identifiers` of 2502.12115, 2501.12948, 2502.18449, 2409.02977, 2409.09030 answered in 0.7 s after one `id_list` request, 5,484 characters; `add_to_collection` of the five ids; `list_items` on the collection, 5 items in 4,685 characters (DeepSeek-R1 among them); PDFs attached in the background, 3 s apart. A repeat `add_by_identifier` answered `existing` with the same id. Over HTTP with the write token: create, rename, add and remove on `/api/library/collections` 200/201 and four `ok` rows in the service log; delete collection and trash item 403; the read token and no token 403 with their reasons; `create_collection` over MCP with the read token refused as read-only. `delete_collection` with a wrong `confirm` refused, with the name done. Not run: the style regression set (the style engine module is not built in this environment). + +## app/mcp/tools_parity.py, app/services/window_bridge.py, app/routers/window_bridge.py · an agent can do what a person can {#app-agent-parity} + +New in v0.16.0 (2026-12-02 EST, agent `fc-parity`). The owner's rule: Claude Code and the other agents must be able to do everything a person does in FormCite. In 0.15.2 an agent had 14 MCP tools and the cite service's four write routes; every other library change and every window action was the window key's alone. The before and after table is in the hand-off `fc16-fc-parity.md`. + +**Headless tools in their own module.** `tools_parity.py` holds 44 tools so `tools.py` gains two lines and keeps fc-agent's collection and lookup work apart. Each tool calls the same service function the window's route calls, so the two cannot drift, and answers one line per row with ids plus a small dict, never a whole stored item; `export_references` refuses past 200,000 characters and asks for narrower ids, a collection or a tag. + +**Consent.** FormCite's consent for agents is the token scope (or `--allow-write` on stdio); the dock asks no per-call question (`dock.py`, contract clause 15). So nothing here weakens a scope: every tool that changes anything needs write, and a permanent delete carries `destructive`, which `_describe` turns into `destructiveHint: true`, so a client such as Claude Code asks the person before the call. `delete_items_forever` and `empty_trash` also need `confirm: true`, because nothing brings their files back. Trashing is not destructive: `restore_items` undoes it. `network_status` is read-only on purpose: the network switches are the person's own limit on what leaves the computer, and an agent turning them back on would undo it. + +**Why a bridge and not more routes.** Window actions (select, scroll to, open the reader at a page, Preferences, appearance) live in the window, not the engine, so the engine cannot do them; it can only ask the window. The window long-polls (`GET /api/window/commands/next?wait=20`), which needs no new socket kind, works through the vite proxy and the desktop shell alike, and survives an engine restart with a back-off. The catalogue and the queue are in memory: a run is meaningless after the window that would run it is gone. A run that is not picked up in 60 s is marked expired, and `window_open()` is false when the window has not polled for 45 s (twice the poll plus slack). Each page polls with a random session id (fc-verify V3, 9c4fcf9). The engine never learns that a reloaded page's long-poll lost its client, so that thread would take the next run and deliver it to nobody. Instead, a new session's first poll supersedes the old session: the old poll returns no run, and runs the old session took but never answered go back to the front of the queue. A `sent` run still unanswered after 30 s expires with a sentence telling the agent to run it again. Requeueing can, in a rare race, run a command twice if the old page answered at the very moment it reloaded. Commands are idempotent window steps (views, selection, scope), so that risk was accepted over losing the command. + +**What is never offered.** `connections.*`, `engine.*`, `edit.*`, `network.*`, `service.*` and `window.close` are refused by the engine even if a window publishes them, and the window's `describeCommand` drops them too: an agent approving its own or another app's pairing would be a scope escalation, the edit commands act on the person's focused field and clipboard, and Close Window ends the dock session the agent runs in. + +**Over stdio.** `./formcite mcp` runs apart from the engine, so its `window_commands` always answers that no window is connected, naming that case; the headless tools work there and the engine's change feed shows their writes. `use_library` also queues the window's own `library.use`, because the feed notices a switch only at its next library check. + +**Checked** (data folder `/tmp/fcp/data2`, engine on 8391 serving a `vite build` of the working tree, HTTP MCP with a write token, headless Chromium): 65 tools listed, nine with `destructiveHint`. With the window open: `add_item` twice appeared live; `view.show`, `list.sort`, `item.select` (selected and scrolled to), `edit_item`, `add_note` and `tag_item` updated the open details pane; `list.search`, `list.scope` tag and all; `trash_items` then `view.trash` showed it in the Trash; `restore_items`; `save_search`; `export_references` BibTeX; `attach_file` of a 26-page PDF, `item.view`, `reader.page 3` answered "page 3 of 26", `reader.find font` answered "17 of 50" with the matches highlighted; `prefs.open appearance`, `appearance.mode light` then dark, `prefs.close`; `add.identifier` and `add.close`; `create_library`, `use_library` (the window showed the empty library, then 6 items after switching back); `collection.new`, `collection.add-selection`, `collection.show`. Refused as designed: `connections.approve` (kept for the person), `list.sort` with a bad key (names the allowed ones), `empty_trash` without `confirm`, `window_command_run` and `delete_note` with a read token (read-only connection). Repo engine: `GET` and `PUT /api/window/commands` without the window key answer 403. Not run: the style regression set (the style engine module is not built in this environment). + +## app/routers/window.py, app/services/opener.py · the window reads a paper and opens its links {#app-reader-routes} + +The in-app reader needs the bytes of a PDF attachment. `GET /api/library/attachments/{id}/file` answers them through `FileResponse`, which handles HTTP ranges, so PDF.js can read a large paper in pieces. It carries `window_only` on purpose: the other `GET` routes of the library answer any caller on this computer, but a paper's file is the person's own document, and only the window shows it. `opener.stored_pdf` reuses `stored_path` (a stored or linked file that is on disk) and refuses anything whose MIME type is not `application/pdf` and whose name does not end in `.pdf`, so the route cannot be used to read other attachments. `no-store` keeps the webview from caching a file the person may later replace, and `nosniff` keeps it a PDF. + +`POST /api/library/open-url` exists because the desktop webview does not open a new window for a link with `target=_blank`, so a link clicked inside a paper would do nothing there. It opens only `http`, `https` or `mailto` addresses with a host or address after the scheme, refuses whitespace and control characters, and starts the browser the way `open_arxiv` does. It is window-only too. + +**Checked** with the reader's Playwright runs (see the frontend entry `#ui-paper-reader`): the route served the 15-, 27-, 75- and 100-page papers. Without the window key it answers 403, which is what made a second browser session fail until the engine was restarted (the key is claimed once per engine). diff --git a/backend/app/__init__.py b/backend/app/__init__.py index c0d4999..5a313cc 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.15.2" +__version__ = "0.16.0" 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/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}) 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/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/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/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/mcp/protocol.py b/backend/app/mcp/protocol.py index 20101ae..d2107b1 100644 --- a/backend/app/mcp/protocol.py +++ b/backend/app/mcp/protocol.py @@ -14,7 +14,16 @@ 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. " + "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." ) PARSE_ERROR = -32700 diff --git a/backend/app/mcp/tools.py b/backend/app/mcp/tools.py index 4cbc35e..7c04e2b 100644 --- a/backend/app/mcp/tools.py +++ b/backend/app/mcp/tools.py @@ -2,8 +2,10 @@ 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.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 TYPES = {"string": str, "integer": int, "array": list, "object": dict, "boolean": bool} @@ -50,29 +52,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 +304,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 +422,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 +457,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 +518,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 +550,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", @@ -306,6 +567,7 @@ def _tag_item(args: dict) -> tuple[str, dict]: *FORMAT_TOOLS, *NET_TOOLS, *WRITE_TOOLS, + *PARITY_TOOLS, ] @@ -316,7 +578,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} diff --git a/backend/app/mcp/tools_parity.py b/backend/app/mcp/tools_parity.py new file mode 100644 index 0000000..29cd228 --- /dev/null +++ b/backend/app/mcp/tools_parity.py @@ -0,0 +1,438 @@ +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"]) + window_bridge.notify("library.use", {"name": out["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")) + 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 = [] + 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, 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",)), + _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), +] 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: diff --git a/backend/app/routers/changes.py b/backend/app/routers/changes.py new file mode 100644 index 0000000..fd00350 --- /dev/null +++ b/backend/app/routers/changes.py @@ -0,0 +1,81 @@ +import asyncio +import json +import signal +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 _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] + + +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 or _exiting(): + 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/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: diff --git a/backend/app/routers/registry.py b/backend/app/routers/registry.py index 81c7141..cfe63c4 100644 --- a/backend/app/routers/registry.py +++ b/backend/app/routers/registry.py @@ -50,3 +50,5 @@ 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) +register("window_bridge", __import__("app.routers.window_bridge", fromlist=["router"]).router) 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/routers/window_bridge.py b/backend/app/routers/window_bridge.py new file mode 100644 index 0000000..919a38e --- /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), session: str = Query("", max_length=64)) -> dict: + return {"run": window_bridge.next_run(wait, session)} + + +@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/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) 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)] diff --git a/backend/app/services/window_bridge.py b/backend/app/services/window_bridge.py new file mode 100644 index 0000000..51a3e50 --- /dev/null +++ b/backend/app/services/window_bridge.py @@ -0,0 +1,189 @@ +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 +SENT_SECONDS = 30.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 = ("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, "session": ""} +_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." + elif run["state"] == "sent" and now - run.get("sent_at", now) > SENT_SECONDS: + run["state"], run["error"] = "expired", "The window took the command but did not answer; it may have been reloaded or closed. Run it again." + 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 _adopt(session: str) -> None: + if not session or session == _state["session"]: + return + _state["session"] = session + for run in sorted(_runs.values(), key=lambda r: r["at"], reverse=True): + if run["state"] == "sent" and run.get("session") != session: + run["state"] = "queued" + run.pop("sent_at", None) + _queue.appendleft(run["id"]) + _cond.notify_all() + + +def next_run(wait: float, session: str = "") -> dict | None: + deadline = time.time() + max(0.0, min(wait, MAX_WAIT)) + with _cond: + _state["seen"] = time.time() + _adopt(session) + while True: + if session and _state["session"] != session: + return None + while _queue: + run = _runs.get(_queue.popleft()) + if run and run["state"] == "queued": + run["state"], run["sent_at"], run["session"] = "sent", time.time(), session + 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) 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; diff --git a/docs/MCP.md b/docs/MCP.md index 301bd11..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`) | @@ -55,6 +62,43 @@ 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, 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). + ## 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/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/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_...`. diff --git a/docs/WINDOW.md b/docs/WINDOW.md index 38b5f74..8a0f1d0 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,17 @@ 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). + +## 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. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 2c2fc9f..66b24d6 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -710,3 +710,84 @@ Removed, quoted: - `.cv-prefs-scrim > .cv-prefs-dlg { animation: cv-prefs-dlg-in 160ms var(--ease-glass) both; }`; - `.cv-prefs-scrim.is-closing > .cv-prefs-dlg { animation: cv-prefs-dlg-out 120ms ease-in both; }`; - the four `@keyframes`, `cv-prefs-scrim-in`, `cv-prefs-scrim-out`, `cv-prefs-dlg-in` and `cv-prefs-dlg-out`. + +## src/io/changes.ts, src/engine/live.ts, src/engine/library.ts, src/engine/itemlist.ts, src/ui/itemlist.ts, src/main.ts, src/styles/itemlist.css · the window shows changes made outside it, in place {#src-live-feed} + +The owner saw nothing of 30 items, their tags and a new collection that Claude Code made from the dock until a full quit and reopen. The panes already knew how to patch themselves (`items:added` places single rows by position, `collections:changed` and `tags:changed` patch the sidebar by key, `item:changed` refreshes one row and a quiet detail reload); nothing ever told them about changes made elsewhere. The engine now streams its `changes` table (see backend `#app-changes-feed`) and `engine/live.ts` turns each batch into those same notices, so no pane grew a second update path. + +**Why fetch and not EventSource.** EventSource cannot send headers, and the window key travels in `x-formcite-window-key` on every call. `io/changes.ts` reads the same text/event-stream body through `fetch` and a `TextDecoderStream`, so the feed is authenticated exactly like the other calls and no ticket or key in a URL is needed. + +**Coalescing.** A batch settles for 120 ms after its last message and never waits more than 600 ms, then becomes one notice of each kind: ids are folded into sets, and an id that was added and then removed in one batch cancels out. Measured with 30 bearer-token adds and 30 tag writes in 576 ms at 4x CPU throttling: 7 page reads of the list, zero pool nodes added or removed (MutationObserver on the spacer), no layout-shift entries. + +**Scope.** Filing into the collection on screen, or tagging with the tag on screen, adds the rows; the opposite removes them; filing anything takes it out of Unfiled and unfiling may bring it back (the position check skips an id that does not match). Deleting the collection or tag on screen returns to All items, as a click would. More than 40 changed items in one batch, a stale answer, or a reconnect after falling behind calls `Library.stale()`: one re-read of the list around the rows in view, the sidebar and the open item, keeping scope, search, sort and selection. + +**Scroll anchor.** `ItemListModel.refresh()` loads the page around the first row in view (the `near` index `ensure` records) instead of page 0, so a burst over `INSERT_MAX` no longer leaves a scrolled list showing pending rows while page 0 loads. The list remembers the first row in view and its offset on every paint; after an add, remove, restore or stale re-read it puts that row back at the same offset by moving `scrollTop` by whole rows. At the top of the list (`scrollTop` 0) new rows simply appear, which is the point. Scope, search, sort and library changes clear the hold so they never jump to an old row. Measured: scrolled to 1500 px with a row selected, 30 agent adds moved `scrollTop` 1500 to 2340 (30 rows of 28 px) and the anchor row and the selected row stayed at 197 px and 309 px on screen. + +**The agent highlight.** Rows from an `item.add` the window did not make (an agent token, MCP, the command line, an import) get `is-agent` for six seconds: an inset 2 px accent edge and the accent wash as an inset box-shadow that fade over the last 60%. A box-shadow never changes the row's box, so the highlight cannot shift anything; under reduced motion it steps off instead of fading. It stays quiet with no badge or toast, since the dock already shows what the agent did. + +**Echo.** The engine drops the window's own rows from every batch, so a tag added in the details pane or an item added by identifier is applied once by the code that made it, never again by the feed. Even an echo would be harmless: `insert` skips ids already in the list and `refreshOne` repaints identical text without touching the DOM. + +**Where it starts.** `main.ts` starts the feed beside `mountParity`, and `LiveFeed.run` awaits `loadWindowKey()` itself. That call shares the claim `ui/app.ts` already began, so the launch code is spent only once, and with no key the feed never opens. It first sat in `start()` in `ui/app.ts`, but that file's other hunks belonged to the reader and stayed uncommitted, so the committed tree never opened the feed (fc-verify V1). + +**Gap at start.** The list loads before the feed opens (the feed waits for the window key), and the first hello starts from the engine's latest sequence. To cover a write landing in between, the first hello calls `Library.stale()` once; with nothing changed, the re-read writes the same text into the same rows and touches no DOM. + +## src/ui/collections.ts, src/io/collections.ts · collection commands an agent can run {#ui-collection-commands} + +New in v0.16.0 (2026-12-02 EST, agent `fc-agent`). In the owner's dock session `window_commands` with "collection" answered nothing. Three commands now live in `ui/collections.ts`, registered by one call after `registerItemCommands` in `app.ts`, and fc-parity's `ui/parity.ts` describes them for the bridge: `collection.new` (no arguments: the sidebar's own name field, as the File menu and Mod+Shift+N always did; with `{ name, parent }`: made through the engine and shown at once), `collection.add-selection` (`{ collection, item? }`, the selected item when `item` is left out; the window selects one item at a time, so "selection" is that one) and `collection.show` (`{ collection }`, sets the list's scope and switches to Items). A collection is named by id or exact name, case ignored; two with one name refuse and ask for the id. After a change the commands call `collectionsChanged` and `itemChanged`, so the sidebar counts and the details pane patch in place like any other edit; nothing is rebuilt. `io/collections.ts` holds the one new call, `POST /library/collections/{id}/items`, which the window had no caller for. The change feed drops the window's own writes as echoes, and `collectionsChanged` and `itemChanged` refresh only the sidebar and the details pane, so adding into the collection on screen left the list empty (found by fc-parity). When the shown scope is that collection the command now also calls `itemsAdded([item])`, and the list's `insert` places the row (or re-reads an empty list). Checked in headless Chromium at 4x CPU throttling: the empty collection on screen gained its row, the status bar read 1 item, layout shift 0. + +## src/engine/bridge.ts, src/io/bridge.ts, src/ui/parity.ts · every window action is a command an agent can run {#ui-agent-parity} + +New in v0.16.0 (2026-12-02 EST, agent `fc-parity`). The owner's rule is that an agent can do in FormCite what a person can. Data changes have headless MCP tools (`backend/HASHOUT_LOG.md`, `#app-agent-parity`); this is the window half: what a person does with menus, buttons, right-click menus and Preferences. + +**Commands, not clicks.** The window already had a command registry, so the bridge runs registry commands and nothing else. `describeCommand(id, spec)` gives an offered command its typed arguments (`string`, `number`, `integer`, `boolean`, with `enum` and `required`), whether it writes, its group, and an `adapt` for commands whose `run` takes another shape (the item commands take a bare id). A command that is not described is not offered, so a new command is private until someone decides an agent may run it. `edit.*`, `connections.*`, `engine.*`, `network.*`, `service.*` and `window.close` are dropped even if described (reasons in the backend entry). + +**What a run answers.** `run` returns nothing, and many actions finish asynchronously, so `runBridged` waits a short `settle` (250 ms by default, more for the reader and library switches) and answers the window's state: view, scope, search, sort, selection and counts, plus a `said` line where a command has more to report (the reader's page and match count are read from its own page box and match counter). The agent learns what the person now sees without a second call. + +**Where parity.ts drives the DOM.** A few actions exist only as a pane's own controls with no function to call from outside: the Add dialog, Preferences' close button, and the reader's page box, find bar and Back button. There `parity.ts` presses the same control a person would, through its class name, so the person sees the identical steps, and each such command is registered only when no command of that id exists (the reader may register its own later; `mountReader` runs first). Everything else calls the engine models directly (`Library.setQuery`, `setSort`, `setScope`, `select`, `chooseTheme`, `setShellPref`). + +**Revealing an item.** `item.select` selects through `Library.select` and then asks `GET /library/rows/{id}/position` for the row's index under the current scope, search and sort, and scrolls the list there only when the row is off screen, so a visible row never moves. + +**Mounted from main.ts.** `mountParity(engine)` runs after `mountApp` so every command `app.ts`, `menus.ts`, the reader and the collection commands register exists before it describes them; it sits in `main.ts` because `ui/app.ts` carried other roles' uncommitted hunks. + +**The poll.** `io/bridge.ts` waits for the window key, publishes the offered commands (again whenever their ids change or a call failed) and long-polls `GET /api/window/commands/next?wait=20`; a failure backs off 1, 2, 5, then 10 s. One run at a time, in order, which is how a person acts too. + +**Checked** in headless Chromium against a `vite build` served by the engine (details and the list of commands driven in the backend entry): every view, `item.select`, `list.search` (and clearing it with no text, fixed in a6d869f), `list.sort`, `list.scope` tag and all, `item.view`, `reader.page`, `reader.find`, `reader.close`, `prefs.open`, `appearance.mode`, `prefs.close`, `add.identifier`, `add.close`, `library.use`, the three collection commands. `npm run check` and `npm run build` pass. + +## src/engine/reader.ts, src/io/reader.ts, src/ui/reader.ts, src/ui/reader-view.ts, src/styles/reader.css, vite.config.ts · the paper reader inside the window {#ui-paper-reader} + +The owner: "you can open a pdf of the research papers yes BUT there needs to be a view paper IN APP that lets the user actually see the paper like they would outside of the app". Until 0.15.2 Open PDF went to `POST /attachments/{id}/open`, which handed the file to FormPDF or the system viewer. + +**A view, not a tab or a dialog.** FormCite's main area already swaps whole views by `data-view` on `.fc-panes` (Duplicates, Trash, Needs a title), so the reader is one more such view, `reader`, that covers columns 2 to the end and keeps the sidebar. Back (and Esc) returns to the view it came from. It needs no nav item: it is reached from an item. The top bar title reads Paper; the paper's own title sits in the reader's bar. + +**Why PDF.js's viewer component and not a hand-made page loop.** `pdfjs-dist/web/pdf_viewer.mjs` exports `PDFViewer`, `PDFLinkService` and `PDFFindController`. `PDFViewer` already renders only the pages near the viewport, keeps a small cache of rendered pages (10 here, counted by `canvas.width > 0`), draws at `devicePixelRatio`, adds a detail canvas past the canvas size cap, and handles touch pinch. The find controller highlights in the text layer. Writing these again would be worse. What the component lacks is the app around it: the bar, thumbnails, the outline, Ctrl-wheel zoom, print and download, which `reader.ts` and `reader-view.ts` add. + +**Load order.** `pdf_viewer.mjs` reads the core library from `globalThis.pdfjsLib`, which `pdf.mjs` sets when it runs, so `reader-view.ts` imports `pdfjs-dist` before the viewer. The whole module, with `pdf_viewer.css`, is a dynamic import from `reader.ts`, so the 620 kB chunk and 230 kB of CSS load when the first paper opens, not at launch. + +**No network.** The worker is `pdf.worker.min.mjs?url`, a hashed local asset. CMaps, standard fonts, the wasm image decoders and the ICC profile are fetched by URL, so `vite.config.ts` gains a plugin that serves them from `node_modules/pdfjs-dist` under `/pdfjs/` in development and copies them into `dist/pdfjs/` at build. QuickJS is skipped: the reader runs no PDF scripts (no scripting manager, `enableXfa: false`). Checked: the Playwright runs below requested nothing outside the engine's origin. + +**The bytes** come from `GET /api/library/attachments/{id}/file` with the window key in `httpHeaders`; PDF.js fetches with them and uses HTTP ranges, which Starlette's `FileResponse` answers. + +**Thumbnails.** Each page gets a fixed box with the first page's aspect ratio and the canvas inside with `object-fit: contain`, so a page of another size never moves the list. They are drawn one at a time as they come within 300 px of view, into an offscreen canvas then copied, and only the latest 60 keep their pixels (older ones go back to `width = 0`), so a long paper's sidebar stays small. + +**Remembered.** `formcite.reader.spots` keeps `{page, scale}` for the 300 most recent attachment ids; `formcite.reader.prefs` the sidebar, its tab and dark pages. The spot is saved 250 ms after the page or zoom settles, and only once the paper is ready, so the page 1 PDF.js reports while it lays out never overwrites the saved page. + +**No shift, no flash.** Every bar control has a fixed width (page box 5ch, count 7ch, zoom list 104 px, match count 11ch). The find bar floats over the pages. The loading veil is always in the layout and fades in only after 220 ms, so a fast open shows nothing in between. Pages stay `#fff` in both themes; dark pages is a CSS filter on `.canvasWrapper`, so turning it on re-renders nothing. + +**Keys.** The reader listens on `window` in the capture phase while its view is shown, so Cmd or Ctrl+F, P, S, +, - and 0 reach it before the menus' `edit.find` binding and the browser's own zoom, find and print. Plain keys skip text fields. + +**Links.** Outside links keep `target=_blank` in the browser build. In the desktop shell a new window cannot open, so a click goes to `POST /api/library/open-url`. + +**Print** renders each page at 150 dpi into a PNG, places the images in a `.fc-rd-print` element on `body`, and `@media print` hides everything else; the images and object URLs go at `afterprint`. **Download** saves `getData()` as a blob under the attachment's name. + +**Checked** in headless Chromium (Playwright, `PLAYWRIGHT_BROWSERS_PATH=/tmp/rp-pw`, device scale 2, 4x CPU throttling) against a `vite build` served by the engine on a throwaway data folder, with three arXiv PDFs (1706.03762, 15 pages; 2005.14165, 75; 2303.08774, 100) and one item with only an arXiv id, in dark and light at 1440 by 900 and 1280 by 800. In all four: zero layout-shift entries on opening the 15-page and the 100-page papers and while scrolling each; canvas backing 2x its CSS width; Ctrl+= to 140%, Ctrl+- twice to 100%, Fit page, Ctrl-wheel to 193%; Home, ArrowRight and End gave pages 1, 2 and 15; the page box went to 3; find "attention" counted 19 of 59 rising to 72 as pages were searched, with Enter and Shift+Enter stepping and 67 highlights drawn; Esc closed find and kept the reader; a mouse drag selected the authors' names; 22 outline entries, one of which went to page 3; thumbnail 7 went to page 7; Esc went back to Items; after an engine restart and reload, Cmd or Ctrl+O reopened at page 7. The 100-page paper opened in 2.7 to 4.6 s throttled (0.8 to 1.3 s for the 15-page one unthrottled) and, after a fast fling to page 79, held 10 rendered page canvases and an 11 MB JS heap. Page 2's citation link went to page 11. View paper on the arXiv-only item got its PDF, then opened 27 pages. Not checked: printing to paper, downloading in the desktop shell, and anything in the Tauri webview. + +## src/ui/side.ts, src/styles/side.css · a collection made elsewhere moves nothing in the sidebar {#src-side-fixed-collections} + +fc-verify V2: once collections arrived live, an agent making one shifted the layout. The "New collection" row moved down (0.00022), and from the second one the Tags section moved too (0.00070), because the Collections section grew with its content up to six rows. A person's own create had always done this, but that shift follows input and the metric does not count it. + +- **The open Collections section has a fixed height.** It uses its former maximum, the heading plus six rows, so nothing below it can move. The cost is up to two empty rows in a library with fewer than four collections. +- **"New collection" is the section's own last grid row.** It is appended to the section after `foldable()` has moved everything else into `.fc-side-scroll`, so it sits below the scroller and new rows inside the scroller never reach it. A sticky row inside the scroller was the other choice. It would need an opaque background over the transparent sidebar and would cover the last collection. +- **"No collections yet." sits right after the tree,** so the first collection replaces it in the same frame. +- **Collections made elsewhere join the end of the tree.** They get the next `position`, and `flattenTree` sorts by it, so no existing row is pushed down. + +Measured with seven collections created through a write token at 4x CPU throttling: no layout-shift entries. Before, quoted: `collMsg.before(fixed, tree, newRow);`. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index ae636f7..433fb6f 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,17 +1,18 @@ { "name": "formcite", - "version": "0.15.2", + "version": "0.16.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcite", - "version": "0.15.2", + "version": "0.16.0", "license": "GPL-3.0-only", "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..3c889b6 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formcite", "private": true, - "version": "0.15.2", + "version": "0.16.0", "description": "FormCite: a local-first personal research library from the Form family", "license": "GPL-3.0-only", "type": "module", @@ -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/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/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 22f1831..f66ba6d 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -20,19 +20,27 @@ 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; } 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 +57,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 +139,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 +172,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/engine/live.ts b/frontend/src/engine/live.ts new file mode 100644 index 0000000..16272a6 --- /dev/null +++ b/frontend/src/engine/live.ts @@ -0,0 +1,157 @@ +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; +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 { + if (!(await loadWindowKey())) return; + 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 || !known) { 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/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/bridge.ts b/frontend/src/io/bridge.ts new file mode 100644 index 0000000..7ff1a45 --- /dev/null +++ b/frontend/src/io/bridge.ts @@ -0,0 +1,43 @@ +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]; +const SESSION = Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(16).padStart(2, '0')).join(''); + +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 asked = Date.now(); + const { run } = await api.get<{ run: BridgeRun | null }>(`/window/commands/next?wait=${WAIT_S}&session=${SESSION}`); + failures = 0; + if (!run) { + if (Date.now() - asked < 1000) await new Promise((r) => { window.setTimeout(r, 1000); }); + 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/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; } + } + } +} 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/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/main.ts b/frontend/src/main.ts index 8b9393b..d1c88bb 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -3,8 +3,12 @@ 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'; +import { LiveFeed } from './engine/live'; applyLook(); const engine = createEngine(currentAppearance().theme); activateAll(engine); mountApp(engine); +mountParity(engine); +new LiveFeed(engine.library).start(); 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); } 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/styles/side.css b/frontend/src/styles/side.css index bb1835f..d9d5887 100644 --- a/frontend/src/styles/side.css +++ b/frontend/src/styles/side.css @@ -18,6 +18,8 @@ .fc-side-pane > .fc-section + .fc-section { border-top: 1px solid var(--line-0); } .fc-side-pane > .fc-section.is-shut { flex: none; grid-template-rows: var(--fc-section-head-h); min-height: 0; padding-bottom: 0; } .fc-side-pane > .fc-section.is-shut > .fc-side-scroll { display: none; } +.fc-side-pane > .fc-section[data-section="collections"]:not(.is-shut) { grid-template-rows: var(--fc-section-head-h) minmax(0, 1fr) auto; height: calc(var(--fc-section-head-h) + var(--fc-side-row-h) * 6 + var(--space-1)); } +.fc-side-pane > .fc-section.is-shut > .fc-side-new { display: none; } .fc-side-scroll { min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; } .fc-side-pane .fc-section-head { display: block; margin: 0; padding: 0 var(--space-2); } .fc-section-toggle { display: grid; grid-template-columns: var(--size-icon-sm) var(--size-icon-sm) minmax(0, 1fr); align-items: center; column-gap: var(--space-1h); width: 100%; height: 100%; padding: 0 var(--space-1); border: 0; border-radius: var(--radius-sm); background: transparent; color: inherit; font: inherit; letter-spacing: inherit; text-transform: inherit; text-align: start; cursor: pointer; } 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}