From d08c58f4a4c05238182f44f8af9ebddad629a6a2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:01:58 -0500 Subject: [PATCH 01/45] feat(engine): add an empty upload group for dropped files The group is registered with no routes yet, so the slice that fills it changes one file. --- backend/app/routers/registry.py | 1 + backend/app/routers/upload.py | 4 ++++ 2 files changed, 5 insertions(+) create mode 100644 backend/app/routers/upload.py diff --git a/backend/app/routers/registry.py b/backend/app/routers/registry.py index b3a8770..2b7ef3f 100644 --- a/backend/app/routers/registry.py +++ b/backend/app/routers/registry.py @@ -38,3 +38,4 @@ def mount(app: FastAPI) -> None: register("service", __import__("app.routers.service", fromlist=["router"]).router) register("cite_write", __import__("app.routers.cite_write", fromlist=["router"]).router) register("window", __import__("app.routers.window", fromlist=["router"]).router) +register("upload", __import__("app.routers.upload", fromlist=["router"]).router) diff --git a/backend/app/routers/upload.py b/backend/app/routers/upload.py new file mode 100644 index 0000000..1340d20 --- /dev/null +++ b/backend/app/routers/upload.py @@ -0,0 +1,4 @@ +from fastapi import APIRouter + +GROUP = "upload" +router = APIRouter(prefix="/library", tags=[GROUP]) From 42077cbc47be9ec0f5e7fa711992d5e712ad0e0c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:06 -0500 Subject: [PATCH 02/45] feat(upload): identify a pdf sent as the raw request body The upload route checks the pdf magic bytes and a 100 MB cap, writes a temporary file and runs the same identify as the path route with the file copied in. --- backend/app/routers/upload.py | 57 ++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/upload.py b/backend/app/routers/upload.py index 1340d20..58956f2 100644 --- a/backend/app/routers/upload.py +++ b/backend/app/routers/upload.py @@ -1,4 +1,59 @@ -from fastapi import APIRouter +import os +import re +import tempfile +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request +from fastapi.concurrency import run_in_threadpool + +from app.routers.identify import _run +from app.services import identify as svc GROUP = "upload" router = APIRouter(prefix="/library", tags=[GROUP]) + +MAX_BYTES = 100 * 1024 * 1024 +MAGIC = b"%PDF-" +SAFE = re.compile(r"[^A-Za-z0-9._ -]+") + + +def _safe_name(name: str) -> str: + base = SAFE.sub("_", Path(name.replace("\\", "/")).name).strip(" .")[:120] + stem = base[:-4] if base.lower().endswith(".pdf") else base + return (stem or "dropped") + ".pdf" + + +@router.post("/identify/upload") +async def identify_upload(request: Request, name: str = "dropped.pdf") -> dict: + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > MAX_BYTES: + raise HTTPException(413, f"The file is larger than {MAX_BYTES // (1024 * 1024)} MB") + folder = tempfile.mkdtemp(prefix="formcite-upload-") + target = os.path.join(folder, _safe_name(name)) + try: + size = 0 + head = b"" + with open(target, "wb") as out: + async for chunk in request.stream(): + if not chunk: + continue + size += len(chunk) + if size > MAX_BYTES: + raise HTTPException(413, f"The file is larger than {MAX_BYTES // (1024 * 1024)} MB") + if len(head) < len(MAGIC): + head += chunk[: len(MAGIC) - len(head)] + if len(head) >= len(MAGIC) and head != MAGIC: + raise HTTPException(415, "Only PDF files can be identified") + out.write(chunk) + if head != MAGIC: + raise HTTPException(415, "Only PDF files can be identified") + return await run_in_threadpool(_run, svc.identify_file, target, attach="copy", on_duplicate="skip", add=True) + finally: + try: + os.remove(target) + except OSError: + pass + try: + os.rmdir(folder) + except OSError: + pass From ea5e419677ab1cf8fc00d95d573bde02b7471932 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:13 -0500 Subject: [PATCH 03/45] fix(side): hold the side body until the first read and collapse empty messages The side sections stay hidden until collections, tags and totals have loaded once, and an empty status line takes no row, so the message no longer moves when the lists fill or change. --- frontend/src/styles/side.css | 2 ++ frontend/src/ui/side.ts | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/frontend/src/styles/side.css b/frontend/src/styles/side.css index ef54129..0efb8e9 100644 --- a/frontend/src/styles/side.css +++ b/frontend/src/styles/side.css @@ -42,6 +42,8 @@ .fc-side-msg { height: var(--fc-side-row-h); line-height: var(--fc-side-row-h); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .fc-section > .fc-side-msg { padding-top: 0; } .fc-side-msg.is-error { color: var(--danger); } +.fc-side-msg:empty { display: none; } +.fc-side-pane.is-held .fc-section { visibility: hidden; } .fc-side-edit { position: absolute; diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 9b69324..1623a15 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -326,7 +326,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { ev.on('items:restored', refreshAll); ev.on('item:changed', refreshAll); - void loadCollections(pane); - void loadTags(pane); - void loadTotals(pane); + host.classList.add('is-held'); + void Promise.allSettled([loadCollections(pane), loadTags(pane), loadTotals(pane)]) + .then(() => host.classList.remove('is-held')); } From 8f1ed5b7acbfbac6329f4fc252a1bd42567344b0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:16 -0500 Subject: [PATCH 04/45] fix(detail): refuse an empty title before saving The item pane no longer sends an empty title; it shows the refusal in the pane's error line and marks the row. --- frontend/src/engine/detail.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/engine/detail.ts b/frontend/src/engine/detail.ts index 8ee90e1..ad8472c 100644 --- a/frontend/src/engine/detail.ts +++ b/frontend/src/engine/detail.ts @@ -96,6 +96,7 @@ export class DetailModel { if (!item) return false; const value = text.trim(); if (value === fieldText(item, spec.key)) return false; + if (spec.key === 'title' && !value) throw new Error('A title is required.'); const next = await detailApi.editField(item.id, spec.sendKey, value); if (this.current?.id === item.id) this.current = next; this.library.itemChanged(item.id); From c6489c790bf5fffb5dd908b2887774cf0fb04f72 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:16 -0500 Subject: [PATCH 05/45] fix(detail): keep the trash button content still when armed The trash label reserves the width of its longer label and starts at the left, so the icon and text do not move on the first click. --- frontend/src/styles/detail.css | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/styles/detail.css b/frontend/src/styles/detail.css index 87c5064..3fa1d8f 100644 --- a/frontend/src/styles/detail.css +++ b/frontend/src/styles/detail.css @@ -23,7 +23,9 @@ .fc-dt-btn { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--dt-row-h); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text-primary); font: inherit; cursor: pointer; } .fc-dt-btn:hover:not(:disabled) { background: var(--bg-hover); } .fc-dt-btn:disabled { opacity: 0.5; cursor: default; } -.fc-dt-trash { width: 88px; justify-content: center; } +.fc-dt-trash { width: 88px; justify-content: flex-start; } +.fc-dt-trash-text { display: inline-grid; } +.fc-dt-trash-text::after { content: "Confirm"; grid-area: 1 / 1; visibility: hidden; height: 0; } .fc-dt-trash.is-armed { border-color: var(--danger); color: var(--danger-text); } .fc-dt-fields { display: flex; flex-direction: column; gap: var(--space-1); } From 76c709372a3b184c0fc507858e2eff422cb09c82 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:17 -0500 Subject: [PATCH 06/45] feat(pair): list approved requests the app has not collected A window-key route returns approved pairing requests that still wait for the app to collect them. Withdrawing is not offered because the store cannot un-approve a request. --- backend/app/routers/pair.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/backend/app/routers/pair.py b/backend/app/routers/pair.py index 021a313..04230f7 100644 --- a/backend/app/routers/pair.py +++ b/backend/app/routers/pair.py @@ -3,6 +3,7 @@ from fastapi import APIRouter, Header, HTTPException from pydantic import BaseModel +from app.core import window_key from app.service import pairing, store from app.store.errors import Invalid, NotFound @@ -34,6 +35,14 @@ def ask(body: Ask) -> dict: return _run(pairing.ask, body.host, body.name, body.scope) +@router.get("/approved/waiting") +def approved_waiting(x_formcite_window_key: str | None = Header(default=None)) -> dict: + if not window_key.valid(x_formcite_window_key): + raise HTTPException(403, window_key.REFUSED) + rows = [r for r in _run(pairing.listing, True) if r["status"] == "approved"] + return {"requests": rows} + + @router.get("/{request_id}") def collect(request_id: str, x_formcite_pair_secret: str | None = Header(default=None)) -> dict: return _run(pairing.collect, request_id, x_formcite_pair_secret) From 5e56d04283271efebda2bc0b3609e4916ca5769d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:29 -0500 Subject: [PATCH 07/45] feat(add): send a dropped pdf's bytes to the upload route identifyUpload posts the file with the window key, and the engine identify takes either a path or a file. --- frontend/src/engine/add.ts | 4 ++-- frontend/src/io/add.ts | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/frontend/src/engine/add.ts b/frontend/src/engine/add.ts index d47d2fa..c21d3e4 100644 --- a/frontend/src/engine/add.ts +++ b/frontend/src/engine/add.ts @@ -85,9 +85,9 @@ export class Adding { } } - async identify(path: string): Promise { + async identify(source: string | File): Promise { try { - const r = await io.identifyPath(path); + const r = typeof source === 'string' ? await io.identifyPath(source) : await io.identifyUpload(source); if (r.added && r.item) this.library.itemsAdded([r.item.id]); else if (r.duplicate_of) this.library.itemChanged(r.duplicate_of); if (!r.found) return { ok: false, text: r.message }; diff --git a/frontend/src/io/add.ts b/frontend/src/io/add.ts index 7cf3c3f..3a51bd9 100644 --- a/frontend/src/io/add.ts +++ b/frontend/src/io/add.ts @@ -40,6 +40,20 @@ export const importText = (text: string, format: string | null) => export const listFormats = () => api.get('/library/formats'); export const identifyPath = (path: string) => api.post('/library/identify', { path }); +export async function identifyUpload(file: File): Promise { + const res = await fetch(`/api/library/identify/upload?name=${encodeURIComponent(file.name)}`, { + method: 'POST', + headers: { ...keyHeaders(), 'content-type': 'application/pdf' }, + body: file, + }); + if (!res.ok) { + let detail = res.statusText; + try { detail = String((await res.json()).detail ?? detail); } catch { void 0; } + throw new EngineError(detail, res.status); + } + return res.json() as Promise; +} + export async function exportText(format: string, scope: ExportScope): Promise { const p = new URLSearchParams({ format }); if (scope.collection) p.set('collection', scope.collection); From 34b0bc317437bb9829d19b900d3450d8ebb96e4c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:29 -0500 Subject: [PATCH 08/45] feat(add): identify dropped pdfs without a path and show progress in place A dropped pdf uses the upload route unless the desktop shell gives a real path, and progress and the result go to the import line, which keeps its reserved height. --- frontend/src/ui/add.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/frontend/src/ui/add.ts b/frontend/src/ui/add.ts index 0727d57..8df571f 100644 --- a/frontend/src/ui/add.ts +++ b/frontend/src/ui/add.ts @@ -53,7 +53,7 @@ export function mountAdd(engine: Engine, host: HTMLElement): void { const exp = mountExport(engine, adding, body); sections.set('export', exp.node); show('id'); - mountDrop(adding, overlay); + mountDrop(adding, overlay, q(imp.node, '.fc-add-line')); void adding.loadFormats().then((fs) => { const names = fs.map((f) => f.name); imp.setFormats(names); @@ -65,11 +65,12 @@ function hasFiles(e: DragEvent): boolean { return Array.from(e.dataTransfer?.types ?? []).includes('Files'); } -async function dropOne(adding: Adding, f: File): Promise { +async function dropOne(adding: Adding, f: File, line: HTMLElement): Promise { const path = (f as File & { path?: string }).path; - if (/\.pdf$/i.test(f.name)) { - if (!path) { toast(`${f.name}: this window cannot read where the file is stored, so it cannot be identified here.`, 'error'); return; } - const r = await adding.identify(path); + if (/\.pdf$/i.test(f.name) || f.type === 'application/pdf') { + say(line, true, `Identifying ${f.name}...`); + const r = await adding.identify(path ? path : f); + say(line, r.ok, `${f.name}: ${r.text}`); toast(`${f.name}: ${r.text}`, r.ok ? 'info' : 'error'); return; } @@ -79,7 +80,7 @@ async function dropOne(adding: Adding, f: File): Promise { toast(`${f.name}: ${r.text}`, r.ok ? 'info' : 'error'); } -function mountDrop(adding: Adding, overlay: HTMLElement): void { +function mountDrop(adding: Adding, overlay: HTMLElement, line: HTMLElement): void { const zone = el(``); overlay.append(zone); let depth = 0; @@ -92,7 +93,7 @@ function mountDrop(adding: Adding, overlay: HTMLElement): void { e.preventDefault(); off(); const files = Array.from(e.dataTransfer?.files ?? []); - void (async () => { for (const f of files) await dropOne(adding, f); })(); + void (async () => { for (const f of files) await dropOne(adding, f, line); })(); }); } From d0ff5bb871790d4288f476a1ceebf5a4ca0c141c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:32 -0500 Subject: [PATCH 09/45] feat(side): create a subcollection from a collection row Each collection row gains a new subcollection action that opens the name field and posts the row as parent_id, which the engine already accepts. --- frontend/src/styles/side.css | 1 + frontend/src/ui/side.ts | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/frontend/src/styles/side.css b/frontend/src/styles/side.css index 0efb8e9..6e7a9c3 100644 --- a/frontend/src/styles/side.css +++ b/frontend/src/styles/side.css @@ -76,6 +76,7 @@ opacity: 0; pointer-events: none; } +.fc-side-actions.is-three { width: calc(var(--fc-side-actions-w) * 1.5); grid-template-columns: 1fr 1fr 1fr; } .fc-side-row:hover > .fc-side-actions, .fc-side-row:focus-within > .fc-side-actions, .fc-side-row.is-armed > .fc-side-actions { opacity: 1; pointer-events: auto; } diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 1623a15..44df152 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -35,11 +35,14 @@ const EDIT_PARTS = `${sideIcon('remove')} `; +const SUB_ACT = ``; + function rowShell(kind: string, iconName: string): HTMLLIElement { const editable = kind === 'collection' || kind === 'tag'; + const parts = kind === 'collection' ? EDIT_PARTS.replace('', `${SUB_ACT}`) : EDIT_PARTS; return el(`
  • - ${editable ? EDIT_PARTS : ''} + ${editable ? parts : ''}
  • `); } @@ -192,9 +195,11 @@ async function commitCreate(pane: Pane, row: HTMLElement): Promise { if (!input || !row.classList.contains('is-editing')) return; const name = cleanName(input.value); endEdit(row); + const parent = row.dataset.parent || null; + delete row.dataset.parent; if (!name) return; try { - const made = await sideApi.createCollection(name); + const made = await sideApi.createCollection(name, parent); pane.engine.library.collectionsChanged(); pane.engine.library.setScope({ kind: 'collection', id: made.id, label: made.name }); } catch (err) { @@ -283,13 +288,14 @@ export function mountSide(engine: Engine, host: HTMLElement): void { const act = target.closest('.fc-side-act'); const actRow = act?.closest('.fc-side-row'); if (act && actRow) { - if (act.dataset.act === 'rename') startEdit(actRow, actRow.dataset.name ?? ''); + if (act.dataset.act === 'sub') { newRow.dataset.parent = actRow.dataset.key ?? ''; startEdit(newRow, ''); } + else if (act.dataset.act === 'rename') startEdit(actRow, actRow.dataset.name ?? ''); else if (act.dataset.act === 'delete') void removeRow(pane, actRow); return; } const entry = target.closest('.fc-side-entry'); if (!entry) return; - if (entry.classList.contains('fc-side-add')) { startEdit(newRow, ''); return; } + if (entry.classList.contains('fc-side-add')) { delete newRow.dataset.parent; startEdit(newRow, ''); return; } const row = entry.closest('.fc-side-row'); if (row) pick(pane, row); }); From 582db1490c584c5e72e24a7eb6a7cd5ef64d9d26 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:43 -0500 Subject: [PATCH 10/45] feat(itemlist): drop removed rows in place and fetch only the holes On itemsRemoved the list now drops the ids from the cached order, shifts the rest up and fetches only the missing rows that land in the window, instead of re-reading pages. --- frontend/src/engine/itemlist.ts | 59 ++++++++++++++++++++++++++++----- frontend/src/ui/itemlist.ts | 2 +- 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 1739946..0a9f595 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -29,25 +29,39 @@ export class ItemListModel { this.generation++; for (const c of this.pending.values()) c.abort(); this.pending.clear(); - void this.load(0, true); + this.spans.clear(); + void this.load(0, PAGE, true); } ensure(first: number, last: number): void { if (!this.ready) return; - const lo = Math.floor(Math.max(0, first) / PAGE); - const hi = Math.floor(Math.max(0, Math.min(last, this.total - 1)) / PAGE); - for (let p = lo; p <= hi; p++) { - if (!this.cache.has(p * PAGE) && !this.pending.has(p)) void this.load(p, false); + const lo = Math.max(0, first); + const hi = Math.min(last, this.total - 1); + let i = lo; + while (i <= hi) { + if (this.cache.has(i) || this.covered(i)) { i++; continue; } + let j = i; + while (j <= hi && j - i < PAGE && !this.cache.has(j) && !this.covered(j)) j++; + void this.load(i, j - i, false); + i = j; } } - private async load(page: number, fresh: boolean): Promise { + private covered(i: number): boolean { + for (const [o, [, n]] of this.spans) if (i >= o && i < o + n) return true; + return false; + } + + private spans = new Map(); + + private async load(offset: number, limit: number, fresh: boolean): Promise { const gen = this.generation; const ctl = new AbortController(); - this.pending.set(page, ctl); + this.pending.set(offset, ctl); + this.spans.set(offset, [ctl, limit]); if (fresh) this.sink.busy(true); try { - const res = await fetchRows({ scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort, offset: page * PAGE, limit: PAGE }, ctl.signal); + const res = await fetchRows({ scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort, offset, limit }, ctl.signal); if (gen !== this.generation) return; if (fresh) { this.cache.clear(); this.index.clear(); } res.rows.forEach((r, k) => { this.cache.set(res.offset + k, r); this.index.set(r.id, res.offset + k); }); @@ -61,11 +75,38 @@ export class ItemListModel { } catch (e) { if (gen === this.generation && !ctl.signal.aborted) this.sink.error(e instanceof Error ? e.message : String(e)); } finally { - if (this.pending.get(page) === ctl) this.pending.delete(page); + if (this.pending.get(offset) === ctl) { this.pending.delete(offset); this.spans.delete(offset); } if (fresh && gen === this.generation) this.sink.busy(false); } } + remove(ids: string[]): void { + if (!this.ready) return; + const gone = new Set(); + let unknown = 0; + for (const id of ids) { const i = this.indexOf(id); if (i >= 0) gone.add(i); else unknown++; } + if (unknown) { this.reload(); return; } + if (!gone.size) return; + const order = Array.from(gone).sort((a, b) => a - b); + const next = new Map(); + for (const [i, r] of this.cache) { + if (gone.has(i)) continue; + let lo = 0, hi = order.length; + while (lo < hi) { const m = (lo + hi) >> 1; if (order[m] < i) lo = m + 1; else hi = m; } + next.set(i - lo, r); + } + this.cache = next; + this.index.clear(); + for (const [i, r] of this.cache) this.index.set(r.id, i); + this.generation++; + for (const c of this.pending.values()) c.abort(); + this.pending.clear(); + this.spans.clear(); + this.total =Math.max(0, this.total - gone.size); + this.lib.setCounts({ shown: this.total, total: this.total }); + this.sink.reset(this.total); + } + async refreshOne(id: string): Promise { const i = this.indexOf(id); if (i < 0) return; diff --git a/frontend/src/ui/itemlist.ts b/frontend/src/ui/itemlist.ts index c73c076..2e2fc20 100644 --- a/frontend/src/ui/itemlist.ts +++ b/frontend/src/ui/itemlist.ts @@ -193,7 +193,7 @@ export function mountItemList(engine: Engine, host: HTMLElement): void { lib.events.on('selected', () => { for (const node of pool) if (!node.hidden) fill(node, Number(node.dataset.index)); }); lib.events.on('item:changed', (id) => { void model.refreshOne(id); }); lib.events.on('items:added', () => model.reload()); - lib.events.on('items:removed', () => model.reload()); + lib.events.on('items:removed', (ids) => model.remove(ids)); lib.events.on('items:restored', () => model.reload()); markSort(); From 8d42dda800e546e0166fc3b55a5d59b54585699d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:44 -0500 Subject: [PATCH 11/45] feat(connections): track approved requests the app has not collected The connections engine reads the approved-and-waiting list with the other two lists and emits add, update and remove for each waiting request. --- frontend/src/engine/connections.ts | 26 +++++++++++++++++++++++--- frontend/src/io/service.ts | 1 + 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/frontend/src/engine/connections.ts b/frontend/src/engine/connections.ts index 8b2a1e0..5a5e660 100644 --- a/frontend/src/engine/connections.ts +++ b/frontend/src/engine/connections.ts @@ -25,6 +25,7 @@ export interface ConnectedApp { export interface ConnectionsTransport { requests(): Promise; apps(): Promise; + waiting(): Promise; approve(id: string, scope: Grant): Promise; deny(id: string): Promise; revoke(id: string): Promise; @@ -41,6 +42,9 @@ export interface ConnectionsEvents { 'request:update': PendingRequest; 'request:remove': string; 'request:arrived': PendingRequest[]; + 'waiting:add': PendingRequest; + 'waiting:update': PendingRequest; + 'waiting:remove': string; 'app:add': ConnectedApp; 'app:update': ConnectedApp; 'app:remove': string; @@ -61,6 +65,7 @@ export class Connections { readonly events = new Emitter(); private readonly requests = new Map(); private readonly apps = new Map(); + private readonly waiting = new Map(); private readonly busy = new Set(); private status: ConnectionsStatus = { loaded: false, loading: false, error: '' }; private transport: ConnectionsTransport | null = null; @@ -81,9 +86,10 @@ export class Connections { const t = this.transport; if (!t) return Promise.resolve(); this.setStatus({ ...this.status, loading: true }); - this.inflight = Promise.all([t.requests(), t.apps()]) - .then(([reqs, apps]) => { + this.inflight = Promise.all([t.requests(), t.apps(), t.waiting()]) + .then(([reqs, apps, waiting]) => { this.mergeRequests(reqs); + this.mergeWaiting(waiting); this.mergeApps(apps); this.setStatus({ loaded: true, loading: false, error: '' }); }) @@ -120,7 +126,11 @@ export class Connections { try { await run(t); done(); - if (reloadApps) this.mergeApps(await t.apps()); + if (reloadApps) { + const [waiting, apps] = await Promise.all([t.waiting(), t.apps()]); + this.mergeWaiting(waiting); + this.mergeApps(apps); + } return true; } catch (err) { this.setStatus({ ...this.status, error: err instanceof Error ? err.message : String(err) }); @@ -163,6 +173,16 @@ export class Connections { if (this.requests.size !== before || arrived.length) this.events.emit('count', this.requests.size); } + private mergeWaiting(list: PendingRequest[]): void { + const seen = new Set(list.map((r) => r.id)); + for (const id of [...this.waiting.keys()]) if (!seen.has(id)) { this.waiting.delete(id); this.events.emit('waiting:remove', id); } + for (const r of list) { + const old = this.waiting.get(r.id); + if (!old) { this.waiting.set(r.id, r); this.events.emit('waiting:add', r); } + else if (!sameRequest(old, r)) { this.waiting.set(r.id, r); this.events.emit('waiting:update', r); } + } + } + private mergeApps(list: ConnectedApp[]): void { const seen = new Set(list.map((a) => a.id)); for (const id of [...this.apps.keys()]) if (!seen.has(id)) { this.apps.delete(id); this.events.emit('app:remove', id); } diff --git a/frontend/src/io/service.ts b/frontend/src/io/service.ts index dc7b752..cd3d8ce 100644 --- a/frontend/src/io/service.ts +++ b/frontend/src/io/service.ts @@ -44,6 +44,7 @@ export function toApp(r: Row): ConnectedApp { export const serviceTransport: ConnectionsTransport = { requests: async () => rows(await api.get('/service/requests'), 'requests').map(toRequest).filter((r) => r.id), apps: async () => rows(await api.get('/service/tokens'), 'tokens').map(toApp).filter((a) => a.id), + waiting: async () => rows(await api.get('/cite/v1/pair/approved/waiting'), 'requests').map(toRequest).filter((r) => r.id), approve: async (id, scope) => { await api.post(`/service/requests/${encodeURIComponent(id)}/approve`, { scope }); }, deny: async (id) => { await api.post(`/service/requests/${encodeURIComponent(id)}/deny`, {}); }, revoke: async (id) => { await api.del(`/service/tokens/${encodeURIComponent(id)}`); }, From e54dea021677498ee47c174811ea434c3916079a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:06:44 -0500 Subject: [PATCH 12/45] feat(connections): show approved requests waiting for the app A third group in the Connections view lists each approved request as Approved, waiting for the app to collect, in rows of the same fixed height. The row has no withdraw action because the store cannot take an approval back. --- frontend/src/ui/connections.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/frontend/src/ui/connections.ts b/frontend/src/ui/connections.ts index 7bb3db0..739702b 100644 --- a/frontend/src/ui/connections.ts +++ b/frontend/src/ui/connections.ts @@ -19,6 +19,10 @@ export const CONNECTIONS_PANE = `

    ${icon('info', 14)}Waiting for your answer

    No app is asking right now.

    +
    +

    ${icon('info', 14)}Approved, waiting for the app to collect

    +

    No approved request is waiting.

    +

    ${icon('link', 14)}Connected apps

    No apps are connected.

    @@ -76,6 +80,22 @@ function updateRequestRow(n: HTMLElement, r: PendingRequest, now: number): void for (const b of n.querySelectorAll('[data-act="approve"], [data-act="approve-read"]')) setDisabled(b, gone || n.classList.contains('is-busy')); } +function waitingRow(r: PendingRequest): HTMLElement { + const n = el(`
    +
    +
    `); + n.dataset.key = r.id; + updateWaitingRow(n, r, Date.now()); + return n; +} + +function updateWaitingRow(n: HTMLElement, r: PendingRequest, now: number): void { + setText(q(n, '.fc-conn-name'), r.name); + setText(q(n, '.fc-conn-host'), r.host); + setText(q(n, '.fc-conn-what'), `${may(r.scope)} once the app collects its token`); + setText(q(n, '.fc-conn-when'), r.expiresAt && r.expiresAt <= now ? 'Not collected in time' : r.expiresAt ? `Collect within ${span(r.expiresAt - now)}` : ''); +} + function appRow(a: ConnectedApp): HTMLElement { const n = el(`
    @@ -107,6 +127,8 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { const pane = q(host, '.fc-conn'); const reqList = q(pane, '[data-list="requests"]'); const appList = q(pane, '[data-list="apps"]'); + const waitList = q(pane, '[data-list="waiting"]'); + const waiting = new Map(); const errorLine = q(pane, '.fc-conn-error'); const count = q(host, '.fc-nav-count'); const navs = Array.from(host.querySelectorAll('.fc-nav-item')); @@ -117,6 +139,9 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { c.events.on('request:add', (r) => { requests.set(r.id, r); if (!rowOf(reqList, r.id)) reqList.append(requestRow(r)); }); c.events.on('request:update', (r) => { requests.set(r.id, r); const n = rowOf(reqList, r.id); if (n) updateRequestRow(n, r, Date.now()); }); c.events.on('request:remove', (id) => { requests.delete(id); rowOf(reqList, id)?.remove(); }); + c.events.on('waiting:add', (r) => { waiting.set(r.id, r); if (!rowOf(waitList, r.id)) waitList.append(waitingRow(r)); }); + c.events.on('waiting:update', (r) => { waiting.set(r.id, r); const n = rowOf(waitList, r.id); if (n) updateWaitingRow(n, r, Date.now()); }); + c.events.on('waiting:remove', (id) => { waiting.delete(id); rowOf(waitList, id)?.remove(); }); c.events.on('app:add', (a) => { apps.set(a.id, a); if (!rowOf(appList, a.id)) appList.append(appRow(a)); }); c.events.on('app:update', (a) => { apps.set(a.id, a); const n = rowOf(appList, a.id); if (n) updateAppRow(n, a, Date.now()); }); c.events.on('app:remove', (id) => { apps.delete(id); rowOf(appList, id)?.remove(); }); @@ -174,6 +199,7 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { const now = Date.now(); for (const [id, r] of requests) { const n = rowOf(reqList, id); if (n) updateRequestRow(n, r, now); } for (const [id, a] of apps) { const n = rowOf(appList, id); if (n) updateAppRow(n, a, now); } + for (const [id, r] of waiting) { const n = rowOf(waitList, id); if (n) updateWaitingRow(n, r, now); } }, TICK_MS); } From 7d44a8a37de5f168c452652cfe4210ede76ee0fd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:07:14 -0500 Subject: [PATCH 13/45] feat(side): keyboard movement and tree roles for the collection tree The collection list is now an aria tree with one roving tab stop; arrows move between visible rows, left and right fold, unfold or step to parent and child, and Enter selects. --- frontend/src/styles/side.css | 1 + frontend/src/ui/side.ts | 84 +++++++++++++++++++++++++++++++++--- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/frontend/src/styles/side.css b/frontend/src/styles/side.css index 6e7a9c3..ca690f5 100644 --- a/frontend/src/styles/side.css +++ b/frontend/src/styles/side.css @@ -43,6 +43,7 @@ .fc-section > .fc-side-msg { padding-top: 0; } .fc-side-msg.is-error { color: var(--danger); } .fc-side-msg:empty { display: none; } +.fc-side-row.is-folded { display: none; } .fc-side-pane.is-held .fc-section { visibility: hidden; } .fc-side-edit { diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 44df152..97a1ff8 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -27,6 +27,7 @@ interface Pane { collMsg: HTMLElement; tags: HTMLUListElement; tagMsg: HTMLElement; + collapsed: Set; } const EDIT_PARTS = ` @@ -40,8 +41,9 @@ const SUB_ACT = ` + const tree = kind === 'collection'; + return el(`
  • + ${editable ? parts : ''}
  • `); } @@ -64,9 +66,79 @@ function updateCollection(node: HTMLElement, entry: TreeEntry, pane: Pane): void setStyleVar(node, '--fc-side-depth', String(entry.depth)); node.dataset.scope = scopeKey({ kind: 'collection', id: entry.id }); node.dataset.name = entry.name; + node.dataset.parent = entry.parentId ?? ''; + const btn = node.querySelector('.fc-side-entry'); + if (btn && btn.getAttribute('aria-level') !== String(entry.depth + 1)) btn.setAttribute('aria-level', String(entry.depth + 1)); setClass(node, 'is-active', node.dataset.scope === scopeKey(pane.engine.library.scope)); } +function treeRows(pane: Pane): HTMLElement[] { + return Array.from(pane.tree.children) as HTMLElement[]; +} + +function applyTree(pane: Pane): void { + const rows = treeRows(pane); + const parents = new Set(rows.map((r) => r.dataset.parent ?? '')); + const hidden = new Set(); + let roving: HTMLElement | null = null; + let first: HTMLElement | null = null; + for (const row of rows) { + const key = row.dataset.key ?? ''; + const parent = row.dataset.parent ?? ''; + const isHidden = parent !== '' && (hidden.has(parent) || pane.collapsed.has(parent)); + if (isHidden) hidden.add(key); + setClass(row, 'is-folded', isHidden); + const btn = row.querySelector('.fc-side-entry'); + if (!btn) continue; + const expanded = parents.has(key) ? String(!pane.collapsed.has(key)) : null; + if (expanded === null) btn.removeAttribute('aria-expanded'); + else if (btn.getAttribute('aria-expanded') !== expanded) btn.setAttribute('aria-expanded', expanded); + if (!isHidden && !first) first = btn; + if (!isHidden && btn.tabIndex === 0) roving = btn; + if (btn.getAttribute('aria-selected') !== String(row.classList.contains('is-active'))) btn.setAttribute('aria-selected', String(row.classList.contains('is-active'))); + } + const keep = roving ?? first; + for (const row of rows) { + const btn = row.querySelector('.fc-side-entry'); + if (btn) btn.tabIndex = btn === keep ? 0 : -1; + } +} + +function moveFocus(pane: Pane, btn: HTMLElement): void { + for (const row of treeRows(pane)) { + const b = row.querySelector('.fc-side-entry'); + if (b) b.tabIndex = b === btn ? 0 : -1; + } + btn.focus(); +} + +function treeKey(pane: Pane, ev: KeyboardEvent): void { + const btn = (ev.target as HTMLElement).closest('.fc-side-entry'); + const row = btn?.closest('.fc-side-row'); + if (!btn || !row || row.parentElement !== pane.tree) return; + const visible = treeRows(pane).filter((r) => !r.classList.contains('is-folded')); + const at = visible.indexOf(row); + const key = row.dataset.key ?? ''; + const entryOf = (r: HTMLElement | undefined): HTMLElement | null => r?.querySelector('.fc-side-entry') ?? null; + let next: HTMLElement | null = null; + if (ev.key === 'ArrowDown') next = entryOf(visible[at + 1]); + else if (ev.key === 'ArrowUp') next = entryOf(visible[at - 1]); + else if (ev.key === 'Home') next = entryOf(visible[0]); + else if (ev.key === 'End') next = entryOf(visible[visible.length - 1]); + else if (ev.key === 'ArrowRight') { + if (btn.getAttribute('aria-expanded') === 'false') { pane.collapsed.delete(key); applyTree(pane); } + else if (btn.getAttribute('aria-expanded') === 'true') next = entryOf(visible[at + 1]); + else return; + } else if (ev.key === 'ArrowLeft') { + if (btn.getAttribute('aria-expanded') === 'true') { pane.collapsed.add(key); applyTree(pane); } + else if (row.dataset.parent) next = entryOf(visible.find((r) => r.dataset.key === row.dataset.parent)); + else return; + } else if (ev.key === 'Enter' || ev.key === ' ') { pick(pane, row); } + else return; + ev.preventDefault(); + if (next) moveFocus(pane, next); +} + async function loadCollections(pane: Pane): Promise { const done = pendingClass(pane.tree); try { @@ -76,6 +148,7 @@ async function loadCollections(pane: Pane): Promise { create: (e) => { const n = rowShell('collection', 'folder'); updateCollection(n, e, pane); return n; }, update: (n, e) => updateCollection(n, e, pane), }); + applyTree(pane); setText(pane.collMsg, entries.length ? '' : 'No collections yet.'); setClass(pane.collMsg, 'is-error', false); } catch (err) { @@ -260,7 +333,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { collMsg.classList.add('fc-side-msg'); setText(collMsg, ''); const fixed = el('
      '); - const tree = el('
        '); + const tree = el('
          '); const all = rowShell('all', 'all'); setText(all.querySelector('.fc-side-name'), 'All items'); all.dataset.scope = scopeKey(ALL); @@ -281,7 +354,8 @@ export function mountSide(engine: Engine, host: HTMLElement): void { const tags = el('
            '); tagMsg.before(tags); - const pane: Pane = { engine, fixed, tree, collMsg, tags, tagMsg }; + const pane: Pane = { engine, fixed, tree, collMsg, tags, tagMsg, collapsed: new Set() }; + tree.addEventListener('keydown', (ev) => treeKey(pane, ev)); host.addEventListener('click', (ev) => { const target = ev.target as HTMLElement; @@ -317,7 +391,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { if (row) void commitEdit(pane, row); }); - engine.library.events.on('scope', (s) => markActive(pane, s)); + engine.library.events.on('scope', (s) => { markActive(pane, s); applyTree(pane); }); markActive(pane, engine.library.scope); const ev = engine.library.events; const refreshCollections = coalesce(() => loadCollections(pane)); From 053faa504d1260327050b63d744936b94cbaba60 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:07:26 -0500 Subject: [PATCH 14/45] feat(itemlist): insert added and restored rows in place On itemsAdded and itemsRestored the list fetches each row, guesses its place from the cached rows and confirms it with one nine-row probe of the rows route, then shifts and writes only the changed pool rows. --- frontend/src/engine/itemlist.ts | 48 ++++++++++++++++++++++++++++++++- frontend/src/ui/itemlist.ts | 4 +-- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 0a9f595..2df6ce1 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -98,7 +98,6 @@ export class ItemListModel { this.cache = next; this.index.clear(); for (const [i, r] of this.cache) this.index.set(r.id, i); - this.generation++; for (const c of this.pending.values()) c.abort(); this.pending.clear(); this.spans.clear(); @@ -107,6 +106,53 @@ export class ItemListModel { this.sink.reset(this.total); } + private guess(r: Row): number { + const { key, desc } = this.lib.sort; + const val = (x: Row): string | number => key === 'added' ? x.added : key === 'updated' ? x.updated : key === 'year' ? Number(x.year) || 0 : String(x[key] ?? '').toLowerCase(); + const v = val(r); + const keys = Array.from(this.cache.keys()).sort((a, b) => a - b); + for (const i of keys) { + const w = val(this.cache.get(i) as Row); + const c = typeof v === 'number' ? v - (w as number) : String(v).localeCompare(String(w)); + if (desc ? c > 0 : c < 0) return i; + } + return keys.length ? keys[keys.length - 1] + 1 : 0; + } + + async insert(ids: string[]): Promise { + if (!this.ready) return; + const gen = this.generation; + for (const id of ids) { + if (this.indexOf(id) >= 0) continue; + try { + const r = await fetchRow(id); + if (gen !== this.generation) return; + const off = Math.max(0, this.guess(r) - 4); + const res = await fetchRows({ scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort, offset: off, limit: 9 }); + if (gen !== this.generation) return; + if (res.total === this.total) continue; + const k = res.rows.findIndex((x) => x.id === id); + if (k < 0 || res.total !== this.total + 1) { this.reload(); return; } + const at = off + k; + const next = new Map(); + for (const [i, x] of this.cache) next.set(i >= at ? i + 1 : i, x); + next.set(at, res.rows[k]); + this.cache = next; + this.index.clear(); + for (const [i, x] of this.cache) this.index.set(x.id, i); + for (const c of this.pending.values()) c.abort(); + this.pending.clear(); + this.spans.clear(); + this.total = res.total; + this.lib.setCounts({ shown: this.total, total: this.total }); + this.sink.reset(this.total); + } catch (e) { + if (gen === this.generation) this.sink.error(e instanceof Error ? e.message : String(e)); + return; + } + } + } + async refreshOne(id: string): Promise { const i = this.indexOf(id); if (i < 0) return; diff --git a/frontend/src/ui/itemlist.ts b/frontend/src/ui/itemlist.ts index 2e2fc20..0f1e906 100644 --- a/frontend/src/ui/itemlist.ts +++ b/frontend/src/ui/itemlist.ts @@ -192,9 +192,9 @@ export function mountItemList(engine: Engine, host: HTMLElement): void { lib.events.on('sort', () => { markSort(); model.reload(); }); lib.events.on('selected', () => { for (const node of pool) if (!node.hidden) fill(node, Number(node.dataset.index)); }); lib.events.on('item:changed', (id) => { void model.refreshOne(id); }); - lib.events.on('items:added', () => model.reload()); + lib.events.on('items:added', (ids) => { void model.insert(ids); }); lib.events.on('items:removed', (ids) => model.remove(ids)); - lib.events.on('items:restored', () => model.reload()); + lib.events.on('items:restored', (ids) => { void model.insert(ids); }); markSort(); model.reload(); From 29274355e08ffc6eb58affbcc9fc4dc6685dda8a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:08:08 -0500 Subject: [PATCH 15/45] docs(service-tokens): describe the approved and waiting list Documents the window-only list of approved requests the app has not collected and that the window cannot withdraw them. --- docs/SERVICE_TOKENS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/SERVICE_TOKENS.md b/docs/SERVICE_TOKENS.md index 86af968..0460b13 100644 --- a/docs/SERVICE_TOKENS.md +++ b/docs/SERVICE_TOKENS.md @@ -66,6 +66,7 @@ In the window, on routes that need the window key on every method (GETs too, bec - `GET /api/service/requests` lists waiting requests - `POST /api/service/requests/{id}/approve` with `{"scope":"read"}` or `{"scope":"write"}` (leave it out to grant what was asked) - `POST /api/service/requests/{id}/deny` +- `GET /api/cite/v1/pair/approved/waiting` lists requests that are approved and not yet collected (same window key rule, though it sits under the pairing path; answers 403 without the key). The Connections view shows them as "Approved, waiting for the app to collect" until the app collects its token, which moves the row to the connected apps, or fifteen minutes pass. A person cannot withdraw such an approval from the window: the store has no function for it, so it can only be left to expire or the token revoked after the app collects it. - `GET /api/service/tokens` lists tokens, never their values - `DELETE /api/service/tokens/{id}` revokes one From 35b0f8259ceae310032f79ec5334bed860988e29 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:08:09 -0500 Subject: [PATCH 16/45] docs(connections): log the waiting list in both hashout logs Records why the waiting list exists, how the route guards itself and what was measured. --- backend/HASHOUT_LOG.md | 4 ++++ frontend/HASHOUT_LOG.md | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 8c57e60..72b6b19 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1649,3 +1649,7 @@ The item list's lean rows: one SQL statement per page, never `items.get` per row - logged: v0.7.0 · 2026-11-27 FormTxt hands a PDF to FormPDF by POSTing `{"path"}` to `http://127.0.0.1:8198/api/pdf/open-path` (`formtxt/backend/app/services/versions_docs.py :: sign_handoff`). FormPDF's `WindowKeyGuard` refuses every POST without its own window key, and `/api/pdf/open-path` is not in its `OPEN` list, so that handoff is refused today; FormCite also may not open connections outside `app/net`, which is https only. So FormCite only reports whether a FormPDF install is present (`FORMCITE_FORMPDF_APP`, or `FormPDF.app` under `/Applications` or `~/Applications`) and always opens with the system viewer. The viewer is started from an argument list (`xdg-open`, `open`) or `os.startfile`, never a shell string, detached with `start_new_session` and no standard streams. The route sits behind `window_only` as well as the global guard, so a reader token can never open files. + +## app/routers/pair.py {#app-routers-pair-waiting} + +New in v0.7.0 (2026-11-27). `GET /api/cite/v1/pair/approved/waiting` lists approved pairing requests that have not been collected, from `pairing.listing(True)` filtered to `approved`. It lives under the service prefix, which the global guard lets through without a window key, so the route checks `window_key.valid` itself and answers 403 without it. It is declared before `/{request_id}` so it is not read as a request id. The token is still made when the app collects it. There is no withdraw route: `pairing._decide` only answers pending requests and `store` has no function to remove a request, both outside this slice. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 38e9321..3fb6ca7 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -380,3 +380,7 @@ New in v0.7.0 (2026-11-27). The detail pane appends one form to its host at moun ## src/ui/trash.ts, src/ui/duplicates.ts, src/engine/review.ts, src/io/review.ts, src/styles/review.css {#src-review} New in v0.7.0 (2026-11-27). The Trash and Duplicates views, each built once into its pane host and loaded when `engine.library` emits `view` for it; rows and groups are keyed and patched with `patchList`, so a restore or a merge removes one node. Confirmations (delete one for good, empty the trash) swap hidden buttons in the same reserved space. Duplicate groups show only the fields the engine's summary carries (title, creator, year, DOI, added), so a group can read "identical" while stored fields not shown differ. The stylesheet is imported from the two view modules because `index.html` is a scaffold file this slice does not edit. The window key is claimed once per engine process, and the engine must be started with `FORMCITE_UI_PORT` set to the dev UI port or its origin guard refuses the page. + +## src/ui/connections.ts, src/engine/connections.ts, src/io/service.ts {#src-connections-waiting} + +New in v0.7.0 (2026-11-27). A third group in the Connections view lists approved requests the app has not collected yet, read from `GET /api/cite/v1/pair/approved/waiting` with the other two lists in one `Promise.all`. The engine keeps a `waiting` map and emits `waiting:add`, `waiting:update` and `waiting:remove`; approving a request re-reads waiting and apps, so the row leaves the pending list and appears in waiting without a rebuild. The waiting row has no action: the store has no way to take an approval back and `deny` only works on a pending request. Checked in a private built copy under CPU 4x and 400 ms latency: no layout shift on approve or on collect, and one node added and one removed per change. A waiting row is about 3 px shorter than a pending row (it has no buttons), which stays inside its own list. From 196744641e41892dca394196cdb5174d896966a8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:08:43 -0500 Subject: [PATCH 17/45] docs(identify): describe the upload route and the window drop The identify guide now names the upload route, its checks and limits, and how a dropped pdf reaches it. --- docs/IDENTIFY_PDF.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/IDENTIFY_PDF.md b/docs/IDENTIFY_PDF.md index 2388b83..dd79493 100644 --- a/docs/IDENTIFY_PDF.md +++ b/docs/IDENTIFY_PDF.md @@ -6,6 +6,8 @@ FormCite can read a PDF you give it, find an identifier printed in it, look that - Command line: `./formcite cli identify FILE`. Options: `--no-add` looks up and adds nothing; `--move` moves the file into the library, `--link` leaves it where it is (the default copies it); `--add-duplicate` adds a new item even when the library already holds the work; `--scan` only lists the identifiers and never goes to the network. - Routes: `POST /api/library/identify` with `{path, attach?, add?, on_duplicate?}` (`attach` is `copy`, `move` or `link`); `POST /api/library/identify/scan` with `{path}` only lists the identifiers. Both need the window key like every other route. +- Upload: `POST /api/library/identify/upload?name=FILE_NAME` with the raw PDF bytes as the body (not a form). It needs the window key too. The bytes must start with `%PDF-` (otherwise 415) and stay within 100 MB (otherwise 413). They are written to a temporary folder under a name cleaned from `name` (only its last part, letters, digits, dot, dash, underscore and space, ending in `.pdf`), identified with `attach` copy, `add` on and `on_duplicate` skip, and the temporary file is removed afterwards. The answer has the same shape as the path route; its `file` is the temporary path, which no longer exists. +- Window: a PDF dropped on the window is sent to the upload route, since a browser never gives a path. Only when the desktop shell hands over a real path is the path route used. Progress and the answer appear in the line under the Import tab, which keeps its height, and in a short notice. ## What is read From 60b4bd8e855a728de80afef1aeee5b3c1f608cfb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:08:43 -0500 Subject: [PATCH 18/45] docs(hashout): log the upload route's guards and limits Records why no multipart dependency is needed, how the name is cleaned and the repeated attach on a second drop. --- backend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 72b6b19..ab82d42 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1653,3 +1653,7 @@ FormTxt hands a PDF to FormPDF by POSTing `{"path"}` to `http://127.0.0.1:8198/a ## app/routers/pair.py {#app-routers-pair-waiting} New in v0.7.0 (2026-11-27). `GET /api/cite/v1/pair/approved/waiting` lists approved pairing requests that have not been collected, from `pairing.listing(True)` filtered to `approved`. It lives under the service prefix, which the global guard lets through without a window key, so the route checks `window_key.valid` itself and answers 403 without it. It is declared before `/{request_id}` so it is not read as a request id. The token is still made when the app collects it. There is no withdraw route: `pairing._decide` only answers pending requests and `store` has no function to remove a request, both outside this slice. + +## app/routers/upload.py {#app-routers-upload-identify} + +New in v0.7.0 (2026-11-27). `POST /api/library/identify/upload?name=` reads the raw body with `Request.stream()`, so python-multipart is not needed. Neither guard looks at the content type: `WindowKeyGuard` only wants the key header on a non-read method and `LocalGuard` only checks host and origin, so the route is guarded exactly like `/identify`. `content-length` over `MAX_BYTES` (100 MB) is refused before reading, and the streamed count is checked again since the header can be absent or false. The first five bytes must be `%PDF-` or the answer is 415. The name is cut to its last path part and cleaned by `SAFE`, inside a fresh `mkdtemp` folder, so `..%2F..%2Fetc%2Fpasswd` becomes `passwd.pdf` there. `identify_file` runs in the thread pool through the path route's `_run`, so error mapping is shared; the file and folder are removed in `finally`. Dropping the same PDF twice attaches a second copy row to the existing item (same sha256): that is `identify._attach` behaviour, not this route's. From 1b9e49e361364e89445c968f730b6d298eee2e7f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:10:54 -0500 Subject: [PATCH 19/45] docs(side): log the side hold, subcollections and tree keys Records the first-read hold, the subcollection action and the tree keyboard contract, with the measured shift. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 3fb6ca7..9f5591e 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -384,3 +384,7 @@ New in v0.7.0 (2026-11-27). The Trash and Duplicates views, each built once into ## src/ui/connections.ts, src/engine/connections.ts, src/io/service.ts {#src-connections-waiting} New in v0.7.0 (2026-11-27). A third group in the Connections view lists approved requests the app has not collected yet, read from `GET /api/cite/v1/pair/approved/waiting` with the other two lists in one `Promise.all`. The engine keeps a `waiting` map and emits `waiting:add`, `waiting:update` and `waiting:remove`; approving a request re-reads waiting and apps, so the row leaves the pending list and appears in waiting without a rebuild. The waiting row has no action: the store has no way to take an approval back and `deny` only works on a pending request. Checked in a private built copy under CPU 4x and 400 ms latency: no layout shift on approve or on collect, and one node added and one removed per change. A waiting row is about 3 px shorter than a pending row (it has no buttons), which stays inside its own list. + +## src/ui/side.ts, src/styles/side.css {#src-side-tree} + +New in v0.8.0 (2026-11-27). The side sections sit under `visibility: hidden` (`.fc-side-pane.is-held`) until the first collections, tags and totals reads settle, and a status line with no text is `display: none`, so `p.fc-empty.fc-side-msg` no longer moves a row down when the lists fill or a collection is created or deleted. Collection rows carry a third action, new subcollection, which opens the existing name field with the row as `parent_id` (`POST /api/library/collections` already takes it). The collection list is an aria tree: `li` has `role="none"`, the entry button is the `treeitem` with `aria-level`, `aria-expanded` when it has children and `aria-selected`, and one roving `tabindex="0"`. Up, Down, Home and End move between visible rows; Right unfolds or steps to the first child; Left folds or steps to the parent; Enter and Space select. Folded state lives in the pane and is not stored. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency: no layout shift without input and none on creating a subcollection. From 7142bf573979939f7d42f11e3a1aa5b29bf07846 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:11:37 -0500 Subject: [PATCH 20/45] fix(preferences): fill new service and library rows when they are made New rows were born empty because the list patch only updates rows that already exist, so text arrived on the next load and moved the row. Rows now fill at creation and every text line has a fixed height. --- frontend/src/styles/preferences.css | 6 ++--- frontend/src/ui/preferences.ts | 38 +++++++++++++++-------------- 2 files changed, 23 insertions(+), 21 deletions(-) diff --git a/frontend/src/styles/preferences.css b/frontend/src/styles/preferences.css index c9da311..85f4893 100644 --- a/frontend/src/styles/preferences.css +++ b/frontend/src/styles/preferences.css @@ -4,6 +4,7 @@ --fc-pr-log-h: 22px; --fc-pr-lib-h: 48px; --fc-pr-line-h: 20px; + --fc-pr-text-line-h: 15px; --fc-pr-label-w: 200px; display: grid; align-content: start; row-gap: var(--space-6); max-width: 760px; padding: var(--space-4); } @@ -39,11 +40,10 @@ .fc-pr-empty:empty { display: none; } .fc-pr-service, .fc-pr-lib { display: grid; align-items: center; column-gap: var(--space-3); padding: var(--space-2) var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius); background: var(--surface-1); box-sizing: border-box; } .fc-pr-service { grid-template-columns: minmax(0, 1fr) auto; height: var(--fc-pr-service-h); } -.fc-pr-service > .fc-pr-text { grid-template-rows: auto var(--fc-pr-line-h) var(--fc-pr-line-h); } +.fc-pr-service > .fc-pr-text, .fc-pr-lib > .fc-pr-text { grid-auto-rows: var(--fc-pr-text-line-h); row-gap: 0; } +.fc-pr-service > .fc-pr-text > *, .fc-pr-lib > .fc-pr-text > * { display: block; height: var(--fc-pr-text-line-h); line-height: var(--fc-pr-text-line-h); } .fc-pr-service > .fc-pr-text > .fc-pr-hint:nth-child(2) { font-family: var(--font-mono); font-size: var(--fs-11); } -.fc-pr-service > .fc-pr-text > .fc-pr-hint { height: auto; } .fc-pr-lib { grid-template-columns: minmax(0, 1fr) 64px auto; height: var(--fc-pr-lib-h); } -.fc-pr-lib > .fc-pr-text > .fc-pr-hint { height: auto; } .fc-pr-lib.is-current { border-color: var(--accent-color); } .fc-pr-badge { color: var(--accent-color); font-size: var(--fs-12); text-align: end; } .fc-pr-lib .fc-btn { min-width: 72px; } diff --git a/frontend/src/ui/preferences.ts b/frontend/src/ui/preferences.ts index ffbc179..f5935bd 100644 --- a/frontend/src/ui/preferences.ts +++ b/frontend/src/ui/preferences.ts @@ -92,17 +92,18 @@ export function mountPreferences(engine: Engine, host: HTMLElement): void { setChecked(master, n.enabled); setText(masterHint, n.forced_offline ? 'Held off by the FORMCITE_OFFLINE setting of this computer.' : n.enabled ? 'On. Individual services can still be turned off below.' : 'Off. No lookup will run.'); setDisabled(master, n.forced_offline); + const fill = (node: HTMLElement, s: NetService): void => { + setText(q(node, '[data-f="name"]'), s.name); + setText(q(node, '[data-f="host"]'), s.host); + setText(q(node, '[data-f="purpose"]'), s.purpose); + const input = q(node, 'input'); + setChecked(input, s.enabled); + setDisabled(input, !n.enabled || n.forced_offline); + }; patchList(services, n.services, { key: (s) => s.name, - create: serviceRow, - update: (node, s) => { - setText(q(node, '[data-f="name"]'), s.name); - setText(q(node, '[data-f="host"]'), s.host); - setText(q(node, '[data-f="purpose"]'), s.purpose); - const input = q(node, 'input'); - setChecked(input, s.enabled); - setDisabled(input, !n.enabled || n.forced_offline); - }, + create: (s) => { const node = serviceRow(s); fill(node, s); return node; }, + update: fill, }); setText(servicesEmpty, n.services.length === 0 ? 'No services are declared.' : ''); setValue(contact, n.contact ?? ''); @@ -120,17 +121,18 @@ export function mountPreferences(engine: Engine, host: HTMLElement): void { }; const showLibraries = (list: LibraryInfo[]): void => { + const fill = (node: HTMLElement, l: LibraryInfo): void => { + setText(q(node, '[data-f="name"]'), l.name); + setText(q(node, '[data-f="root"]'), l.root); + const isCurrent = l.name === current; + setText(q(node, '[data-f="badge"]'), isCurrent ? 'Current' : ''); + setClass(node, 'is-current', isCurrent); + setDisabled(q(node, 'button'), isCurrent); + }; patchList(libs, list, { key: (l) => l.name, - create: libRow, - update: (node, l) => { - setText(q(node, '[data-f="name"]'), l.name); - setText(q(node, '[data-f="root"]'), l.root); - const isCurrent = l.name === current; - setText(q(node, '[data-f="badge"]'), isCurrent ? 'Current' : ''); - setClass(node, 'is-current', isCurrent); - setDisabled(q(node, 'button'), isCurrent); - }, + create: (l) => { const node = libRow(l); fill(node, l); return node; }, + update: fill, }); setText(libsEmpty, list.length === 0 ? 'No libraries yet.' : ''); }; From 76d35429a0d83774037cf2bae3855246db5ba126 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:11:38 -0500 Subject: [PATCH 21/45] fix(review): remove rows on the click and keep the trash fresh Rows leave the list at the click so the shift belongs to the input, and a failed call puts them back. Delete for good drops its confirmation after 3 seconds, and the trash reloads while hidden so reopening inserts nothing. --- frontend/src/ui/duplicates.ts | 8 ++++---- frontend/src/ui/trash.ts | 20 +++++++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/frontend/src/ui/duplicates.ts b/frontend/src/ui/duplicates.ts index 4b0fa51..de0c057 100644 --- a/frontend/src/ui/duplicates.ts +++ b/frontend/src/ui/duplicates.ts @@ -120,14 +120,14 @@ export function mountDuplicates(engine: Engine, host: HTMLElement): void { if (!g || !gnode) return; const keep = keepOf(g); const others = g.members.filter((m) => m.id !== keep).map((m) => m.id); - gnode.classList.add('is-busy'); + const before = groups; + groups = groups.filter((x) => x.key !== g.key); + render(); mergeGroup(keep, others).then((res) => { - groups = groups.filter((x) => x.key !== g.key); - render(); engine.library.itemsRemoved(res.trashed); engine.library.itemChanged(res.kept); toast(`Merged ${plural(res.trashed.length, 'copy', 'copies')}. The extras are in the trash.`, 'info'); - }).catch((e: Error) => { gnode.classList.remove('is-busy'); showNote(e.message, true); }); + }).catch((e: Error) => { groups = before; render(); showNote(e.message, true); }); }); engine.library.events.on('view', (view) => { if (view === 'duplicates') void load(); }); diff --git a/frontend/src/ui/trash.ts b/frontend/src/ui/trash.ts index fbc0c80..135f89c 100644 --- a/frontend/src/ui/trash.ts +++ b/frontend/src/ui/trash.ts @@ -116,24 +116,30 @@ export function mountTrash(engine: Engine, host: HTMLElement): void { toast('The trash is empty.', 'info'); }).catch((e: Error) => showNote(e.message, true)); } else if (row && id) { - if (act === 'purge') setConfirm(row, true); + if (act === 'purge') { + setConfirm(row, true); + window.setTimeout(() => { if (row.isConnected) setConfirm(row, false); }, 3000); + } else if (act === 'purge-no') setConfirm(row, false); else if (act === 'restore') { - row.classList.add('is-busy'); + const before = items; + drop(id); restoreItem(id).then(() => { - drop(id); engine.library.itemsRestored([id]); - }).catch((e: Error) => { row.classList.remove('is-busy'); showNote(e.message, true); }); + }).catch((e: Error) => { items = before; render(); showNote(e.message, true); }); } else if (act === 'purge-yes') { - row.classList.add('is-busy'); + const before = items; + drop(id); purgeItem(id).then(() => { - drop(id); engine.library.itemsRemoved([id]); - }).catch((e: Error) => { row.classList.remove('is-busy'); setConfirm(row, false); showNote(e.message, true); }); + }).catch((e: Error) => { items = before; render(); showNote(e.message, true); }); } } }); engine.library.events.on('view', (view) => { if (view === 'trash') void load(); }); + const refreshHidden = (): void => { if (engine.library.view !== 'trash') void load(); }; + engine.library.events.on('items:removed', refreshHidden); + engine.library.events.on('items:restored', refreshHidden); if (engine.library.view === 'trash') void load(); } From 5c7b26389f3c5a8bf83949af48675bbeef19122d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:29 -0500 Subject: [PATCH 22/45] feat(pairing): withdraw an approval before the app collects it An approved request with no token can be withdrawn and ends as denied, through a window-only route beside approve and deny. --- backend/app/routers/service.py | 5 +++++ backend/app/service/pairing.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/backend/app/routers/service.py b/backend/app/routers/service.py index bab3859..4961e8b 100644 --- a/backend/app/routers/service.py +++ b/backend/app/routers/service.py @@ -45,6 +45,11 @@ def deny(request_id: str) -> dict: return _run(pairing.deny, request_id) +@router.post("/requests/{request_id}/withdraw") +def withdraw(request_id: str) -> dict: + return _run(pairing.withdraw, request_id) + + @router.get("/tokens") def tokens() -> dict: return {"tokens": _run(store.tokens)} diff --git a/backend/app/service/pairing.py b/backend/app/service/pairing.py index dd3bbb9..941f912 100644 --- a/backend/app/service/pairing.py +++ b/backend/app/service/pairing.py @@ -93,6 +93,23 @@ def deny(request_id: str) -> dict[str, Any]: return _decide(request_id, "denied") +def withdraw(request_id: str) -> dict[str, Any]: + now = int(time.time()) + with store._locked(): + data = store._read() + _expire(data, now) + req = next((r for r in data["requests"] if r["id"] == request_id), None) + if req is None: + store._write(data) + raise NotFound(f"pairing request {request_id}") + if req["status"] != "approved" or req.get("token_id"): + store._write(data) + raise Invalid(f"The pairing request {request_id} is {req['status']}, so its approval cannot be withdrawn.") + req["status"] = "denied" + store._write(data) + return public(req) + + SAY = { "pending": "Waiting for a person to approve or deny this request in FormCite.", "denied": "The person who uses FormCite denied this request.", From 32ab58348170d908cfc9c25442b0ddbe60f7786e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:39 -0500 Subject: [PATCH 23/45] fix(identify): do not attach the same file to an item twice When the matching item already holds an attachment with the file's sha256, that attachment is returned and the message says nothing was changed. --- backend/app/services/identify.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/backend/app/services/identify.py b/backend/app/services/identify.py index 56bf2d4..fc360d0 100644 --- a/backend/app/services/identify.py +++ b/backend/app/services/identify.py @@ -66,6 +66,14 @@ def _finish(lib, path: str, mode: str, attached: dict) -> dict: return {**attached, "path": str(files.abs_path(lib, attached))} +def _already(lib, conn, item_id: str, path: str) -> dict | None: + sha = files.sha256_of(path) + for found in attachments.for_item(conn, item_id): + if found["sha256"] == sha: + return {**found, "path": str(files.abs_path(lib, found))} + return None + + def _attach(lib, conn, item_id: str, path: str, mode: str) -> dict: stored = None try: @@ -117,10 +125,12 @@ def identify_file(path: str, *, attach: str = "copy", on_duplicate: str = "skip" return {**base, "found": True, "source": source, "record": resolved["record"], "duplicates": matches, "message": "Looked up; nothing was added."} if matches and on_duplicate == "skip": - attached = _attach(lib, conn, matches[0], path, attach) + held = _already(lib, conn, matches[0], path) + attached = held or _attach(lib, conn, matches[0], path, attach) + said = "this file was already attached to it, so nothing was changed" if held else "the file was attached to it" return {**base, "found": True, "source": source, "duplicate_of": matches[0], "attached": attached, "item": detail(conn, matches[0]), - "message": f"The item is already in the library as {matches[0]}; the file was attached to it."} + "message": f"The item is already in the library as {matches[0]}; {said}."} made, attached = _create(lib, conn, resolved["record"], source, path, attach) return {**base, "found": True, "added": True, "source": source, "duplicate_of": None, "attached": attached, "item": detail(conn, made["id"]), From c3b26b0ee9d8a362bea322b1398cef35f51778c5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:46 -0500 Subject: [PATCH 24/45] docs(network): name the upload route and the window list The no-background rule now names the three identify routes and says start-up and window polling stay on this computer. Added how Preferences lists the services. --- docs/NETWORK.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/NETWORK.md b/docs/NETWORK.md index 8a562f9..b758085 100644 --- a/docs/NETWORK.md +++ b/docs/NETWORK.md @@ -4,7 +4,7 @@ FormCite works offline. From version 0.5.0 it can look a reference up by its ide ## The rules -1. **Nothing in the background.** FormCite calls a service only when a person or an agent asked for exactly that lookup: a verb such as `./formcite cli add doi=...`, a route such as `POST /api/library/lookup`, or identifying a file someone dropped. There is no timer, no start-up check, no update check and no prefetch. +1. **Nothing in the background.** FormCite calls a service only when a person or an agent asked for exactly that lookup: a verb such as `./formcite cli add doi=...`, a route such as `POST /api/library/lookup`, or identifying a PDF someone named (`POST /api/library/identify`, `/identify/scan`) or dropped on the window (`POST /api/library/identify/upload`). There is no timer, no start-up check, no update check and no prefetch: the engine's start-up only writes its own discovery file, and the window's only repeating calls go to the engine on this computer. 2. **Every host is declared.** A service is registered with a name, one host, a purpose and the address of its own documentation. A fetch is refused unless the address is `https` and its host is exactly the registered host. A redirect is followed only to `https` on a host some registered service declares, at most three times, and never to a service you have switched off. 3. **You hold the switches.** The whole network can be switched off, and so can each service. When a switch is off, the lookup fails with a plain sentence before any connection is opened, and nothing is added to the library. 4. **Every call is logged** in a file in your data folder that you can read. @@ -26,6 +26,8 @@ They live in `network.json` in the data folder, beside `libraries.json` (the dat | One service off or on | `./formcite cli network disable NAME`, `network enable NAME` | `PUT /api/network/services/NAME` `{"enabled": false}` | | Read the log | `./formcite cli network log --limit 20` | `GET /api/network/log?limit=20` | +The window shows the same list in Preferences under Network: the master switch, one switch per service with its purpose, the contact address and the recent calls. Its list comes from `GET /api/network/services`. + Setting the environment variable `FORMCITE_OFFLINE=1` forces the network off for that process, whatever `network.json` says. It is read on every call and never written to the file. ## The log From 230f42698382318de80c64ba3b2e34b0ea418e60 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:46 -0500 Subject: [PATCH 25/45] docs(window): describe subcollections, tree keys, drop upload and row updates Brings the window page up to the code: subcollection button, tree keyboard, dropped PDF bytes, single-row list changes, the waiting group in Connections, and the trash and merge behaviour. --- docs/WINDOW.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/docs/WINDOW.md b/docs/WINDOW.md index aee0d2c..3ef75ea 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -11,7 +11,8 @@ The **Items** view has three panes side by side. ### Library pane (left) - **All items** shows every item that is not in the trash. **Unfiled** shows the items that belong to no collection. Each entry has its count beside it. -- **Collections** is a tree. Click a collection to list its items. You can create a collection, rename it and delete it in place, without a dialog. Deleting a collection does not delete its items. +- **Collections** is a tree. Click a collection to list its items. You can create a collection, rename it and delete it in place, without a dialog. Each collection row also has a plus button, **New subcollection**, that adds a collection inside it. Deleting a collection does not delete its items. +- The tree works from the keyboard: the up and down arrows move between visible rows, Home and End jump to the first and last, the right arrow opens a collection (and a second press moves into it), the left arrow closes it (or moves to its parent), and Enter or Space picks the row. - **Tags** lists every tag. Click one to list the items that carry it. A tag can be renamed or deleted from here. - The entry you are looking at stays marked. @@ -20,6 +21,7 @@ The **Items** view has three panes side by side. - Columns: title, creator, year, type and date added. Click a column head to sort by it, click again to reverse. - The search box filters the list by words in titles, creators, container titles, abstracts, notes and tags. - 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, restored or removed, the list changes only that row and moves the rows below it; it does not reload the list. A removal fetches only the rows that were not yet loaded. - 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. ### Detail pane (right) @@ -37,17 +39,21 @@ The **Add** button opens a dialog with three ways in: - **Import.** Paste text or pick a file in BibTeX, RIS or CSL-JSON. The format can be picked or left for FormCite to recognise. - **Export.** Save the items you are looking at in one of those formats. -You can also drop PDF files anywhere on the window. FormCite reads each one, finds its identifier, looks it up and attaches the file to the new item. Other files that FormCite can import are imported. +You can also drop PDF files anywhere on the window. The window sends each dropped file's bytes to the engine, which reads it, finds its identifier, looks it up and attaches the file to the new item; no file path is needed, and progress shows in place. Other files that FormCite can import are imported. When the network is switched off, or the one service a lookup needs is off, the dialog says so in the engine's own words and nothing is added. ## Trash -The **Trash** view lists the items you have moved to the trash. Each row has **Restore**, which puts the item back where it was, and **Delete for good**. **Empty trash** removes everything in it after you confirm in the same row. Nothing leaves the trash on its own. +The **Trash** view lists the items you have moved to the trash. Each row has **Restore**, which puts the item back where it was, and **Delete for good**, which asks for a second click in the same row and goes back to normal after 3 seconds. **Empty trash** removes everything in it after you confirm beside the button. A row leaves the list as you click, and comes back with a message if the engine refuses. Nothing leaves the trash on its own. ## Duplicates -The **Duplicates** view lists sets of items that look like the same reference: the same DOI, or the same title, year and first author. Each set shows its members side by side with the fields that differ. Choose the one to keep and press **Merge**: the others are folded into it, keeping their tags, collections, notes and attachments. +The **Duplicates** view lists sets of items that look like the same reference: the same DOI, or the same title, year and first author. Each set shows its members side by side with the fields that differ. The oldest copy is kept unless you choose another. Press **Merge** and the set leaves the list at once: the others go to the trash, and the kept item is updated. + +## Connections + +The **Connections** view lists the apps and agents that use FormCite's service. Apps whose request you approved but that have not yet collected their token are listed in a third group, **Approved, waiting for the app to collect**, with how long the app has left to collect it. That row has no withdraw action, because an approval cannot be taken back. ## Preferences From 7b7c6453a1972ddcc3898be245abf25de12a7075 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:51 -0500 Subject: [PATCH 26/45] feat(connections): withdraw an approval from the waiting row The waiting row carries a Withdraw approval button that calls the new route and removes only that row. --- frontend/src/engine/connections.ts | 8 ++++++++ frontend/src/io/service.ts | 1 + frontend/src/ui/connections.ts | 4 +++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/frontend/src/engine/connections.ts b/frontend/src/engine/connections.ts index 5a5e660..ea292a1 100644 --- a/frontend/src/engine/connections.ts +++ b/frontend/src/engine/connections.ts @@ -28,6 +28,7 @@ export interface ConnectionsTransport { waiting(): Promise; approve(id: string, scope: Grant): Promise; deny(id: string): Promise; + withdraw(id: string): Promise; revoke(id: string): Promise; } @@ -108,6 +109,12 @@ export class Connections { return this.act(id, (t) => t.deny(id), () => this.dropRequest(id), false); } + withdraw(id: string): Promise { + return this.act(id, (t) => t.withdraw(id), () => { + if (this.waiting.delete(id)) this.events.emit('waiting:remove', id); + }, false); + } + revoke(id: string): Promise { return this.act(id, (t) => t.revoke(id), () => { const app = this.apps.get(id); @@ -211,5 +218,6 @@ export function registerConnectionCommands(commands: CommandRegistry, c: Connect }, }); commands.register({ id: 'connections.deny', title: 'Deny a connection request', run: (args) => { void c.deny(idOf(args)); } }); + commands.register({ id: 'connections.withdraw', title: 'Withdraw an approval', run: (args) => { void c.withdraw(idOf(args)); } }); commands.register({ id: 'connections.revoke', title: 'Remove an app\'s access', run: (args) => { void c.revoke(idOf(args)); } }); } diff --git a/frontend/src/io/service.ts b/frontend/src/io/service.ts index cd3d8ce..1aff1ab 100644 --- a/frontend/src/io/service.ts +++ b/frontend/src/io/service.ts @@ -47,5 +47,6 @@ export const serviceTransport: ConnectionsTransport = { waiting: async () => rows(await api.get('/cite/v1/pair/approved/waiting'), 'requests').map(toRequest).filter((r) => r.id), approve: async (id, scope) => { await api.post(`/service/requests/${encodeURIComponent(id)}/approve`, { scope }); }, deny: async (id) => { await api.post(`/service/requests/${encodeURIComponent(id)}/deny`, {}); }, + withdraw: async (id) => { await api.post(`/service/requests/${encodeURIComponent(id)}/withdraw`, {}); }, revoke: async (id) => { await api.del(`/service/tokens/${encodeURIComponent(id)}`); }, }; diff --git a/frontend/src/ui/connections.ts b/frontend/src/ui/connections.ts index 739702b..d2769c4 100644 --- a/frontend/src/ui/connections.ts +++ b/frontend/src/ui/connections.ts @@ -83,6 +83,7 @@ function updateRequestRow(n: HTMLElement, r: PendingRequest, now: number): void function waitingRow(r: PendingRequest): HTMLElement { const n = el(`
            +
            `); n.dataset.key = r.id; updateWaitingRow(n, r, Date.now()); @@ -146,7 +147,7 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { c.events.on('app:update', (a) => { apps.set(a.id, a); const n = rowOf(appList, a.id); if (n) updateAppRow(n, a, Date.now()); }); c.events.on('app:remove', (id) => { apps.delete(id); rowOf(appList, id)?.remove(); }); c.events.on('busy', ({ id, busy }) => { - const n = rowOf(reqList, id) ?? rowOf(appList, id); + const n = rowOf(reqList, id) ?? rowOf(appList, id) ?? rowOf(waitList, id); if (!n) return; setClass(n, 'is-busy', busy); for (const b of n.querySelectorAll('button')) setDisabled(b, busy); @@ -188,6 +189,7 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { const act = btn.dataset.act; if (act === 'approve') engine.dispatch('connections.approve', { id, scope: requests.get(id)?.scope ?? 'read' }); else if (act === 'approve-read') engine.dispatch('connections.approve', { id, scope: 'read' }); + else if (act === 'withdraw') engine.dispatch('connections.withdraw', { id }); else if (act === 'deny') engine.dispatch('connections.deny', { id }); else if (act === 'revoke') { setClass(row, 'is-confirming', true); q(row, '[data-act="revoke-no"]').focus(); } else if (act === 'revoke-no') { setClass(row, 'is-confirming', false); q(row, '[data-act="revoke"]').focus(); } From cad00b4f112184494b8010ca6e88ecd3c77f96ba Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:53 -0500 Subject: [PATCH 27/45] docs(frontend): log the single row item list updates Notes how remove and insert keep the item list in place and when they fall back to a re-read. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 9f5591e..4798e76 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -388,3 +388,7 @@ New in v0.7.0 (2026-11-27). A third group in the Connections view lists approved ## src/ui/side.ts, src/styles/side.css {#src-side-tree} New in v0.8.0 (2026-11-27). The side sections sit under `visibility: hidden` (`.fc-side-pane.is-held`) until the first collections, tags and totals reads settle, and a status line with no text is `display: none`, so `p.fc-empty.fc-side-msg` no longer moves a row down when the lists fill or a collection is created or deleted. Collection rows carry a third action, new subcollection, which opens the existing name field with the row as `parent_id` (`POST /api/library/collections` already takes it). The collection list is an aria tree: `li` has `role="none"`, the entry button is the `treeitem` with `aria-level`, `aria-expanded` when it has children and `aria-selected`, and one roving `tabindex="0"`. Up, Down, Home and End move between visible rows; Right unfolds or steps to the first child; Left folds or steps to the parent; Enter and Space select. Folded state lives in the pane and is not stored. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency: no layout shift without input and none on creating a subcollection. + +## src/engine/itemlist.ts, src/ui/itemlist.ts {#src-itemlist-single-rows} + +New in v0.8.0 (2026-11-27). `items:removed` calls `ItemListModel.remove`: the ids are dropped from the sparse row cache, every later cached index moves up by the number of removed indices before it, the count drops, and `reset` repaints the 55 pool rows through the guarded `setText`/`setClass` writes, so only rows whose content moved are written. `ensure` now fetches runs of missing indices (at most `PAGE` long) instead of whole pages, so the rows that slide into the window at the end are the only ones read. An id the cache has never seen falls back to `reload`, because its place among unread pages is unknown. `items:added` and `items:restored` call `insert`: each row is read with `GET /api/library/rows/{id}`, its place is guessed from the cached rows with a client comparator (lowercase `localeCompare`, numbers for added, updated and year), and one nine-row probe of `GET /api/library/rows` around the guess confirms it; the engine has no route that returns a row's position in a sort and filter, so a probe that misses the id falls back to `reload`, and a probe whose total did not grow means the row is outside the scope or filter and nothing is written. Scroll top, selection and focus are not touched. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency, title sort, scrolled to row 300: remove, restore and add each wrote 43 or 44 rows (only the rows at and after the change), zero pool nodes added or removed, no layout shift. From 57b1e8e3f6cc822fcf3199a5b4c232396b226a9d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:12:56 -0500 Subject: [PATCH 28/45] docs(hashout): log the trash and merge click checks Records what was measured and why rows leave at the click. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 4798e76..931efe5 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -392,3 +392,7 @@ New in v0.8.0 (2026-11-27). The side sections sit under `visibility: hidden` (`. ## src/engine/itemlist.ts, src/ui/itemlist.ts {#src-itemlist-single-rows} New in v0.8.0 (2026-11-27). `items:removed` calls `ItemListModel.remove`: the ids are dropped from the sparse row cache, every later cached index moves up by the number of removed indices before it, the count drops, and `reset` repaints the 55 pool rows through the guarded `setText`/`setClass` writes, so only rows whose content moved are written. `ensure` now fetches runs of missing indices (at most `PAGE` long) instead of whole pages, so the rows that slide into the window at the end are the only ones read. An id the cache has never seen falls back to `reload`, because its place among unread pages is unknown. `items:added` and `items:restored` call `insert`: each row is read with `GET /api/library/rows/{id}`, its place is guessed from the cached rows with a client comparator (lowercase `localeCompare`, numbers for added, updated and year), and one nine-row probe of `GET /api/library/rows` around the guess confirms it; the engine has no route that returns a row's position in a sort and filter, so a probe that misses the id falls back to `reload`, and a probe whose total did not grow means the row is outside the scope or filter and nothing is written. Scroll top, selection and focus are not touched. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency, title sort, scrolled to row 300: remove, restore and add each wrote 43 or 44 rows (only the rows at and after the change), zero pool nodes added or removed, no layout shift. + +## src/ui/trash.ts, src/ui/duplicates.ts {#src-review-click} + +New in v0.8.0 (2026-11-27). Checked in a private built copy with 2,000 items (20 added as deliberate duplicates), CPU 4x, 400 ms and about 400 kbit/s, after a hard reload. A row that left only when the reply arrived moved the rows below it more than 500 ms after the click, which counted as 0.1498 of shift without input (the merged group). Restore, Delete for good and Merge now take the row out of the list at the click and put it back with the message if the engine refuses, so every shift sits inside the input window (about 0.01 per trash row, 0.1498 for the group). Delete for good drops its second-click confirmation after 3 seconds. The trash listens for `items:removed` and `items:restored` and reloads while hidden, so reopening it after a merge or a trashing elsewhere inserts nothing in view (a stale list that gained a row at the top had counted 0.0092 without input). From 73d7b402cbe81cea686b6bd24a3e25924a48ecd8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:13:54 -0500 Subject: [PATCH 29/45] docs(identify): say a file already attached is not added again The guide now explains that an identical file on the matched item is reused and nothing is changed. --- docs/IDENTIFY_PDF.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/IDENTIFY_PDF.md b/docs/IDENTIFY_PDF.md index dd79493..c2575b0 100644 --- a/docs/IDENTIFY_PDF.md +++ b/docs/IDENTIFY_PDF.md @@ -35,7 +35,7 @@ Where it was found comes first: the metadata, then the first page, then later pa ## What is added -The item, its import batch and the attachment are written together: a failed lookup or a failed write leaves neither an item nor a stored file. When the library already holds the work (the duplicate check by DOI, then by title, year and first author), the file is attached to that item and the answer says so. A moved file is removed from its old place only after everything is written. +The item, its import batch and the attachment are written together: a failed lookup or a failed write leaves neither an item nor a stored file. When the library already holds the work (the duplicate check by DOI, then by title, year and first author), the file is attached to that item and the answer says so. When that item already holds an attachment with the same contents (same sha256), nothing is stored or recorded, `attached` is the existing attachment, and the answer says the file was already attached and nothing was changed; with `--move` the file then stays where it was. A moved file is removed from its old place only after everything is written. ## Limits From 4ab8f511d3b769180e794bd978f7a69e6569f9f7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:13:54 -0500 Subject: [PATCH 30/45] docs(hashout): record the sha256 check before attaching The upload entry now says how a repeated drop is detected and that all three callers share it. --- backend/HASHOUT_LOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index ab82d42..0ee233a 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1656,4 +1656,4 @@ New in v0.7.0 (2026-11-27). `GET /api/cite/v1/pair/approved/waiting` lists appro ## app/routers/upload.py {#app-routers-upload-identify} -New in v0.7.0 (2026-11-27). `POST /api/library/identify/upload?name=` reads the raw body with `Request.stream()`, so python-multipart is not needed. Neither guard looks at the content type: `WindowKeyGuard` only wants the key header on a non-read method and `LocalGuard` only checks host and origin, so the route is guarded exactly like `/identify`. `content-length` over `MAX_BYTES` (100 MB) is refused before reading, and the streamed count is checked again since the header can be absent or false. The first five bytes must be `%PDF-` or the answer is 415. The name is cut to its last path part and cleaned by `SAFE`, inside a fresh `mkdtemp` folder, so `..%2F..%2Fetc%2Fpasswd` becomes `passwd.pdf` there. `identify_file` runs in the thread pool through the path route's `_run`, so error mapping is shared; the file and folder are removed in `finally`. Dropping the same PDF twice attaches a second copy row to the existing item (same sha256): that is `identify._attach` behaviour, not this route's. +New in v0.7.0 (2026-11-27). `POST /api/library/identify/upload?name=` reads the raw body with `Request.stream()`, so python-multipart is not needed. Neither guard looks at the content type: `WindowKeyGuard` only wants the key header on a non-read method and `LocalGuard` only checks host and origin, so the route is guarded exactly like `/identify`. `content-length` over `MAX_BYTES` (100 MB) is refused before reading, and the streamed count is checked again since the header can be absent or false. The first five bytes must be `%PDF-` or the answer is 415. The name is cut to its last path part and cleaned by `SAFE`, inside a fresh `mkdtemp` folder, so `..%2F..%2Fetc%2Fpasswd` becomes `passwd.pdf` there. `identify_file` runs in the thread pool through the path route's `_run`, so error mapping is shared; the file and folder are removed in `finally`. Dropping the same PDF twice no longer adds a second row: `identify._already` checks the matched item's attachments by sha256 before `_attach`, returns the existing row (with `path`) as `attached`, and the message says nothing was changed. It runs before any store, so `move` leaves the source file in place. Path route, upload route and CLI all go through `identify_file`, so they agree; the CLI was checked twice against the same data. From c9e036b8af3d4becb586d43886f5a924e2c78ec1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:14:08 -0500 Subject: [PATCH 31/45] docs(service-tokens): document withdrawing an approval Describes the withdraw route and that the app's next poll answers denied. --- docs/SERVICE_TOKENS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/SERVICE_TOKENS.md b/docs/SERVICE_TOKENS.md index 0460b13..f9d87ea 100644 --- a/docs/SERVICE_TOKENS.md +++ b/docs/SERVICE_TOKENS.md @@ -66,7 +66,8 @@ In the window, on routes that need the window key on every method (GETs too, bec - `GET /api/service/requests` lists waiting requests - `POST /api/service/requests/{id}/approve` with `{"scope":"read"}` or `{"scope":"write"}` (leave it out to grant what was asked) - `POST /api/service/requests/{id}/deny` -- `GET /api/cite/v1/pair/approved/waiting` lists requests that are approved and not yet collected (same window key rule, though it sits under the pairing path; answers 403 without the key). The Connections view shows them as "Approved, waiting for the app to collect" until the app collects its token, which moves the row to the connected apps, or fifteen minutes pass. A person cannot withdraw such an approval from the window: the store has no function for it, so it can only be left to expire or the token revoked after the app collects it. +- `GET /api/cite/v1/pair/approved/waiting` lists requests that are approved and not yet collected (same window key rule, though it sits under the pairing path; answers 403 without the key). The Connections view shows them as "Approved, waiting for the app to collect" until the app collects its token, which moves the row to the connected apps, or fifteen minutes pass. The row has a "Withdraw approval" button. +- `POST /api/service/requests/{id}/withdraw` withdraws an approval while it is approved and no token was made. The request ends as `denied`, so the app's next poll answers `"denied"` and no token is ever made. After the app has collected, it answers 422; revoke the token instead. - `GET /api/service/tokens` lists tokens, never their values - `DELETE /api/service/tokens/{id}` revokes one From 7f6706b3809a2e8736c761618da10c742435b2b0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:14:25 -0500 Subject: [PATCH 32/45] docs(preferences): log the row fill fix and the service check Records why rows now fill at creation, the measured shift, and that the seven listed services match the backend. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 931efe5..c087224 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -396,3 +396,7 @@ New in v0.8.0 (2026-11-27). `items:removed` calls `ItemListModel.remove`: the id ## src/ui/trash.ts, src/ui/duplicates.ts {#src-review-click} New in v0.8.0 (2026-11-27). Checked in a private built copy with 2,000 items (20 added as deliberate duplicates), CPU 4x, 400 ms and about 400 kbit/s, after a hard reload. A row that left only when the reply arrived moved the rows below it more than 500 ms after the click, which counted as 0.1498 of shift without input (the merged group). Restore, Delete for good and Merge now take the row out of the list at the click and put it back with the message if the engine refuses, so every shift sits inside the input window (about 0.01 per trash row, 0.1498 for the group). Delete for good drops its second-click confirmation after 3 seconds. The trash listens for `items:removed` and `items:restored` and reloads while hidden, so reopening it after a merge or a trashing elsewhere inserts nothing in view (a stale list that gained a row at the top had counted 0.0092 without input). + +## src/ui/preferences.ts, src/styles/preferences.css {#src-preferences-rows} + +New in v0.8.0 (2026-11-27). `patchList` calls `update` only for rows it already had, so service and library rows were born empty and got their text on the next load, which grew `.fc-pr-text` from 2 px to about 40 px and moved `fc-btn` (0.00036 on a switch). Each row is now filled in `create`, and every line in a service or library row is a fixed 15 px block. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and about 400 kbit/s: 0 shift without input and 0 with input on opening, creating and switching; a create adds one row, a switch moves the badge text only. Preferences lists seven services (arxiv, crosscite, crossref, datacite, doi-org, openlibrary, pubmed), the same set the backend registers in `app/lookup/`; no other module opens an outbound connection. From 9a2d65dc8fc49d4327ebb98faa24680672f28fbe Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:15:00 -0500 Subject: [PATCH 33/45] docs(detail): log the item pane click check Records the empty title refusal, the trash label width and the throttled check of remove tag, open and trash. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index c087224..1ad7d17 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -400,3 +400,7 @@ New in v0.8.0 (2026-11-27). Checked in a private built copy with 2,000 items (20 ## src/ui/preferences.ts, src/styles/preferences.css {#src-preferences-rows} New in v0.8.0 (2026-11-27). `patchList` calls `update` only for rows it already had, so service and library rows were born empty and got their text on the next load, which grew `.fc-pr-text` from 2 px to about 40 px and moved `fc-btn` (0.00036 on a switch). Each row is now filled in `create`, and every line in a service or library row is a fixed 15 px block. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and about 400 kbit/s: 0 shift without input and 0 with input on opening, creating and switching; a create adds one row, a switch moves the badge text only. Preferences lists seven services (arxiv, crosscite, crossref, datacite, doi-org, openlibrary, pubmed), the same set the backend registers in `app/lookup/`; no other module opens an outbound connection. + +## src/engine/detail.ts, src/styles/detail.css {#src-detail-click} + +New in v0.8.0 (2026-11-27). The engine stores an empty title without complaint, so `DetailModel.save` refuses it before any request and the pane shows "Title: A title is required." in its error line with the row marked; Escape puts the stored title back. The Trash button keeps its 88 px width and now starts its content at the left, with a hidden `::after` holding "Confirm" so the label box is sized for the longer label; the icon stays at the same x when armed. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and about 400 kbit/s after a hard reload: remove tag, Open and Trash each take the click at their centre, Open sends `POST /api/library/attachments/{id}/open` and gets 200 with `opened_with: "system"`, Trash removes the row and drops the count by one, and layout shift was 0 with and without input. From 938262c2462ac4d8a92f3ffca05b070124f8dbf6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:16:29 -0500 Subject: [PATCH 34/45] fix(side): keep focus on a nearby row after a delete When the deleted collection or tag held focus, focus moves to the next row at the same or a higher level, else the previous one, else the add button or the first fixed row, so it is never lost to the body. --- frontend/src/ui/side.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 97a1ff8..88330b7 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -286,6 +286,19 @@ function commitEdit(pane: Pane, row: HTMLElement): Promise { const armed = new WeakMap(); +function focusNeighbor(pane: Pane, row: HTMLElement): void { + const list = row.parentElement; + const visible = list ? (Array.from(list.children) as HTMLElement[]).filter((r) => r === row || !r.classList.contains('is-folded')) : []; + const at = visible.indexOf(row); + const depth = (r: HTMLElement): number => Number(r.style.getPropertyValue('--fc-side-depth') || 0); + const target = visible.slice(at + 1).find((r) => depth(r) <= depth(row)) ?? visible[at - 1]; + const btn = target?.querySelector('.fc-side-entry') + ?? (list === pane.tree ? q(pane.tree.parentElement ?? pane.tree, '.fc-side-add') : pane.fixed.querySelector('.fc-side-entry')); + if (!btn) return; + if (list === pane.tree && target) moveFocus(pane, btn); + else btn.focus(); +} + async function removeRow(pane: Pane, row: HTMLElement): Promise { const btn = row.querySelector('[data-act="delete"]'); if (!armed.has(row)) { @@ -307,6 +320,7 @@ async function removeRow(pane: Pane, row: HTMLElement): Promise { try { if (row.dataset.kind === 'collection') await sideApi.deleteCollection(id); else await sideApi.deleteTag(id); + if (row.contains(document.activeElement)) focusNeighbor(pane, row); if (row.classList.contains('is-active')) lib.setScope(ALL); if (row.dataset.kind === 'collection') lib.collectionsChanged(); else lib.tagsChanged(); From 61b118929266776fb596f3b34c69505301e6b3c5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:16:43 -0500 Subject: [PATCH 35/45] feat(window): add a row position route for the item list GET /api/library/rows/{id}/position returns the index and total of one item under the rows route's scope, filter and ordering, ranked in SQL with the same tie-break. --- backend/app/routers/window.py | 12 +++++++++++ backend/app/services/window_rows.py | 31 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/backend/app/routers/window.py b/backend/app/routers/window.py index 71632d1..3315fa6 100644 --- a/backend/app/routers/window.py +++ b/backend/app/routers/window.py @@ -41,6 +41,18 @@ def rows( ) +@router.get("/rows/{item_id}/position") +def row_position( + item_id: str, + scope: str = "all", + id: str | None = None, + q: str | None = None, + sort: str = "title", + desc: bool = False, +) -> dict: + return _run(window_rows.row_position, item_id, scope=scope, scope_id=id, q=q, sort=sort, desc=desc) + + @router.get("/rows/{item_id}") def row(item_id: str) -> dict: return _run(window_rows.one_row, item_id) diff --git a/backend/app/services/window_rows.py b/backend/app/services/window_rows.py index bff4c55..e897af5 100644 --- a/backend/app/services/window_rows.py +++ b/backend/app/services/window_rows.py @@ -107,6 +107,37 @@ def rows( return {"total": total, "offset": offset, "rows": [_row(r) for r in found]} +def position( + conn: sqlite3.Connection, + item_id: str, + *, + scope: str = "all", + scope_id: str | None = None, + q: str | None = None, + sort: str = "title", + desc: bool = False, +) -> dict: + if sort not in SORTS: + raise Invalid(f"sort must be one of {', '.join(SORTS)}") + if conn.execute("SELECT 1 FROM items WHERE id = ?", (item_id,)).fetchone() is None: + raise NotFound(f"no item {item_id}") + clauses, args = _where(scope, scope_id, q) + where = " WHERE " + " AND ".join(clauses) + total = conn.execute("SELECT COUNT(*) FROM items i" + where, args).fetchone()[0] + direction = "DESC" if desc else "ASC" + ranked = ( + f"SELECT n FROM (SELECT i.id AS id, ROW_NUMBER() OVER (ORDER BY {SORTS[sort]} {direction}, " + f"i.id {direction}) - 1 AS n FROM items i{where}) WHERE id = ?" + ) + found = conn.execute(ranked, [*args, item_id]).fetchone() + return {"index": found[0] if found else -1, "total": total} + + +def row_position(item_id: str, **kwargs) -> dict: + with session() as (_, conn): + return position(conn, item_id, **kwargs) + + def row(conn: sqlite3.Connection, item_id: str) -> dict: found = conn.execute(COLUMNS + " WHERE i.id = ?", (item_id,)).fetchone() if found is None: From fe2205ea77e913373960281a48d35af5c8131a3b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:16:46 -0500 Subject: [PATCH 36/45] docs(readme): say the window and agent tools look up too, and where the switches are The network section named only the command line; the window's add and drop, the agent lookup tools and the Preferences list are now named as well. --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2ae8417..f4d8811 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Another app on this computer, or an agent you run, can use your library only wit ## What FormCite sends over the network -Nothing, unless you ask for a lookup. `./formcite cli add doi=...` (or `arxiv=`, `isbn=`, `pmid=`) and `./formcite cli identify FILE.pdf` send the identifier, and only the identifier, to the service that knows it. A PDF and its text never leave your computer. There is no timer, no update check and no call at start-up. +Nothing, unless you ask for a lookup. `./formcite cli add doi=...` (or `arxiv=`, `isbn=`, `pmid=`) and `./formcite cli identify FILE.pdf` send the identifier, and only the identifier, to the service that knows it. The window does the same when you add by identifier or drop a PDF on it, and so do the lookup tools an agent calls. A PDF and its text never leave your computer. There is no timer, no update check and no call at start-up. | Service | Host | Asked for | | --- | --- | --- | @@ -60,7 +60,7 @@ Nothing, unless you ask for a lookup. `./formcite cli add doi=...` (or `arxiv=`, | Open Library | `openlibrary.org` | a book by ISBN | | PubMed | `eutils.ncbi.nlm.nih.gov` | an article by PubMed ID | -`./formcite cli network list` shows these with their switches, `network off` stops every call, `network disable NAME` stops one service, and `network log` shows every call that was made. Setting `FORMCITE_OFFLINE=1` forces the network off. No email address is sent unless you set one with `network contact`. The rules are in [`docs/NETWORK.md`](docs/NETWORK.md). +In the window, Preferences lists every service with a switch for each. `./formcite cli network list` shows these with their switches, `network off` stops every call, `network disable NAME` stops one service, and `network log` shows every call that was made. Setting `FORMCITE_OFFLINE=1` forces the network off. No email address is sent unless you set one with `network contact`. The rules are in [`docs/NETWORK.md`](docs/NETWORK.md). The data folder is `~/FormCite` (`FORMCITE_DATA_DIR`). Working on the code: see [`CONTRIBUTING.md`](CONTRIBUTING.md) and [`AGENTS.md`](AGENTS.md). From 7f26543831b2f8c8b8b705a9f22cf30705458230 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:17:04 -0500 Subject: [PATCH 37/45] feat(detail): add note routes to the detail engine The detail io and model can now add, edit and delete an item's notes through the engine's note routes. --- frontend/src/engine/detail.ts | 29 ++++++++++++++++++++++++++++- frontend/src/io/detail.ts | 3 +++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/frontend/src/engine/detail.ts b/frontend/src/engine/detail.ts index ad8472c..0a9649c 100644 --- a/frontend/src/engine/detail.ts +++ b/frontend/src/engine/detail.ts @@ -1,4 +1,4 @@ -import { detailApi, type CslName, type ItemDetail } from '../io/detail'; +import { detailApi, type CslName, type ItemDetail, type Note } from '../io/detail'; import type { Library } from './library'; export type FieldKind = 'line' | 'block' | 'type'; @@ -132,4 +132,31 @@ export class DetailModel { } open(attachmentId: string) { return detailApi.openAttachment(attachmentId); } + + async addNote(body: string): Promise { + const item = this.current; + const clean = body.trim(); + if (!item || !clean) return item?.notes ?? []; + const note = await detailApi.noteAdd(item.id, clean); + item.notes = [...(item.notes ?? []), note]; + return item.notes; + } + + async editNote(noteId: string, body: string): Promise { + const item = this.current; + if (!item) return []; + const clean = body.trim(); + if (!clean) throw new Error('A note cannot be empty; delete it instead.'); + const note = await detailApi.noteEdit(noteId, clean); + item.notes = (item.notes ?? []).map((n) => (n.id === noteId ? note : n)); + return item.notes; + } + + async deleteNote(noteId: string): Promise { + const item = this.current; + if (!item) return []; + await detailApi.noteDelete(noteId); + item.notes = (item.notes ?? []).filter((n) => n.id !== noteId); + return item.notes; + } } diff --git a/frontend/src/io/detail.ts b/frontend/src/io/detail.ts index 5db041e..3547a43 100644 --- a/frontend/src/io/detail.ts +++ b/frontend/src/io/detail.ts @@ -55,4 +55,7 @@ export const detailApi = { removeTags: (id: string, names: string[]) => delWith<{ item_id: string; tags: string[] }>(`/library/items/${enc(id)}/tags`, { names }), trash: (id: string) => api.post(`/library/items/${enc(id)}/trash`, {}), openAttachment: (attachmentId: string) => api.post(`/library/attachments/${enc(attachmentId)}/open`, {}), + noteAdd: (id: string, body: string) => api.post(`/library/items/${enc(id)}/notes`, { body }), + noteEdit: (noteId: string, body: string) => patch(`/library/notes/${enc(noteId)}`, { body }), + noteDelete: (noteId: string) => delWith(`/library/notes/${enc(noteId)}`, {}), }; From e35e8d7b50eac895aa11587ca5e79c2e4edf9d23 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:17:04 -0500 Subject: [PATCH 38/45] feat(detail): edit, add and delete notes in the item pane Notes are edited in place inside the fixed notes box, added from a line below it and deleted with a second click, with a reserved error line. --- frontend/src/styles/detail.css | 8 +++++ frontend/src/ui/detail.ts | 65 ++++++++++++++++++++++++++++++++-- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/frontend/src/styles/detail.css b/frontend/src/styles/detail.css index 3fa1d8f..fabeef5 100644 --- a/frontend/src/styles/detail.css +++ b/frontend/src/styles/detail.css @@ -55,3 +55,11 @@ .fc-dt-item-name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .fc-dt-item-meta { color: var(--text-muted); font-variant-numeric: tabular-nums; } .fc-dt-item .fc-dt-btn { height: 22px; } +.fc-dt-note { grid-template-columns: minmax(0, 1fr) auto; } +.fc-dt-note-body { box-sizing: border-box; width: 100%; height: 22px; padding: 2px var(--space-1); border: 1px solid transparent; border-radius: var(--radius-sm); background: transparent; color: var(--text-primary); font: inherit; line-height: 16px; resize: none; overflow: hidden; } +.fc-dt-note-body:focus { outline: none; border-color: var(--accent-color); background: var(--bg-primary); } +.fc-dt-note.is-error .fc-dt-note-body { border-color: var(--danger); } +.fc-dt-note-del { width: 76px; justify-content: flex-start; } +.fc-dt-note-del-text { display: inline-grid; } +.fc-dt-note-del-text::after { content: "Confirm"; grid-area: 1 / 1; visibility: hidden; height: 0; } +.fc-dt-note-del.is-armed { border-color: var(--danger); color: var(--danger-text); } diff --git a/frontend/src/ui/detail.ts b/frontend/src/ui/detail.ts index 90dda6c..a839eff 100644 --- a/frontend/src/ui/detail.ts +++ b/frontend/src/ui/detail.ts @@ -47,6 +47,8 @@ const SHELL = `

            Notes

            + +
            `; @@ -132,11 +134,70 @@ export function mountDetail(engine: Engine, host: HTMLElement): void { setText(noteCount, String(list.length)); patchList(notesHost, list, { key: (n) => n.id, - create: (n) => el(`
            ${escapeHtml(plain(n.body))}
            `), - update: (node, n) => { const text = plain(n.body); setText(q(node, '.fc-dt-item-name'), text); setTitle(node, text); }, + create: (n) => el(`
            `), + update: (node, n) => { + const box = q(node, '.fc-dt-note-body'); + const text = plain(n.body); + if (box.value !== text && document.activeElement !== box) box.value = text; + box.dataset.saved = text; + }, }); + for (const box of notesHost.querySelectorAll('.fc-dt-note-body')) if (box.dataset.saved === undefined) box.dataset.saved = box.value; } + const noteInput = q(root, '.fc-dt-note-input'); + const noteError = q(root, '.fc-dt-note-error'); + const showNoteError = (text: string): void => { setText(noteError, text); setTitle(noteError, text); }; + + noteInput.addEventListener('keydown', (e) => { + if (e.key !== 'Enter') return; + e.preventDefault(); + const body = noteInput.value.trim(); + if (!body) return; + setDisabled(noteInput, true); + model.addNote(body).then((notes) => { noteInput.value = ''; showNoteError(''); paintNotes(notes); }, (err: Error) => showNoteError(`Notes: ${err.message}`)) + .finally(() => setDisabled(noteInput, false)); + }); + + function saveNote(box: HTMLTextAreaElement): void { + const id = box.closest('.fc-dt-note')?.dataset.key; + if (!id || box.value.trim() === (box.dataset.saved ?? '')) return; + const node = box.closest('.fc-dt-note'); + model.editNote(id, box.value).then( + (notes) => { if (node) setClass(node, 'is-error', false); showNoteError(''); paintNotes(notes); }, + (err: Error) => { if (node) setClass(node, 'is-error', true); showNoteError(`Notes: ${err.message}`); }, + ); + } + + notesHost.addEventListener('focusout', (e) => { + const box = e.target as HTMLElement; + if (box instanceof HTMLTextAreaElement) saveNote(box); + }); + notesHost.addEventListener('keydown', (e) => { + const box = e.target as HTMLElement; + if (!(box instanceof HTMLTextAreaElement)) return; + if (e.key === 'Escape') { box.value = box.dataset.saved ?? ''; box.blur(); } + else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); saveNote(box); } + }); + + const noteArmed = new Map(); + notesHost.addEventListener('click', (e) => { + const btn = (e.target as Element).closest('.fc-dt-note-del'); + const id = btn?.closest('.fc-dt-note')?.dataset.key; + if (!btn || !id) return; + const label = q(btn, '.fc-dt-note-del-text'); + const disarm = (): void => { clearTimeout(noteArmed.get(id)); noteArmed.delete(id); setClass(btn, 'is-armed', false); setText(label, 'Delete'); }; + if (!noteArmed.has(id)) { + setClass(btn, 'is-armed', true); + setText(label, 'Confirm'); + noteArmed.set(id, window.setTimeout(disarm, 3000)); + return; + } + disarm(); + setDisabled(btn, true); + model.deleteNote(id).then((notes) => { showNoteError(''); paintNotes(notes); }, (err: Error) => { setDisabled(btn, false); showNoteError(`Notes: ${err.message}`); }); + }); + async function commit(row: Row): Promise { if (!model.current) return; const value = row.control.value; From d92dbc09bf664e8ad098172bb57a308fa300ed55 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:17:09 -0500 Subject: [PATCH 39/45] feat(itemlist): place added and restored rows with the position route Insert now asks the engine for the row's index under the current scope, filter and sort instead of guessing and probing, and re-reads only when the route is missing on an older engine. --- frontend/src/engine/itemlist.ts | 29 +++++++---------------------- frontend/src/io/itemlist.ts | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 2df6ce1..bd860c0 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -1,5 +1,5 @@ import type { Library } from './library'; -import { fetchRow, fetchRows, type Row } from '../io/itemlist'; +import { fetchPosition, fetchRow, fetchRows, type Row } from '../io/itemlist'; export const PAGE = 200; @@ -106,19 +106,6 @@ export class ItemListModel { this.sink.reset(this.total); } - private guess(r: Row): number { - const { key, desc } = this.lib.sort; - const val = (x: Row): string | number => key === 'added' ? x.added : key === 'updated' ? x.updated : key === 'year' ? Number(x.year) || 0 : String(x[key] ?? '').toLowerCase(); - const v = val(r); - const keys = Array.from(this.cache.keys()).sort((a, b) => a - b); - for (const i of keys) { - const w = val(this.cache.get(i) as Row); - const c = typeof v === 'number' ? v - (w as number) : String(v).localeCompare(String(w)); - if (desc ? c > 0 : c < 0) return i; - } - return keys.length ? keys[keys.length - 1] + 1 : 0; - } - async insert(ids: string[]): Promise { if (!this.ready) return; const gen = this.generation; @@ -127,23 +114,21 @@ export class ItemListModel { try { const r = await fetchRow(id); if (gen !== this.generation) return; - const off = Math.max(0, this.guess(r) - 4); - const res = await fetchRows({ scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort, offset: off, limit: 9 }); + const pos = await fetchPosition(id, { scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort }); if (gen !== this.generation) return; - if (res.total === this.total) continue; - const k = res.rows.findIndex((x) => x.id === id); - if (k < 0 || res.total !== this.total + 1) { this.reload(); return; } - const at = off + k; + if (!pos || (pos.index >= 0 && pos.total !== this.total + 1)) { this.reload(); return; } + if (pos.index < 0) continue; + const at = pos.index; const next = new Map(); for (const [i, x] of this.cache) next.set(i >= at ? i + 1 : i, x); - next.set(at, res.rows[k]); + next.set(at, r); this.cache = next; this.index.clear(); for (const [i, x] of this.cache) this.index.set(x.id, i); for (const c of this.pending.values()) c.abort(); this.pending.clear(); this.spans.clear(); - this.total = res.total; + this.total = pos.total; this.lib.setCounts({ shown: this.total, total: this.total }); this.sink.reset(this.total); } catch (e) { diff --git a/frontend/src/io/itemlist.ts b/frontend/src/io/itemlist.ts index 0856c6a..82781d4 100644 --- a/frontend/src/io/itemlist.ts +++ b/frontend/src/io/itemlist.ts @@ -84,6 +84,20 @@ export async function fetchRows(rq: RowQuery, signal?: AbortSignal): Promise): Promise { + if (rowsRoute === false) return null; + const p = scopeParams(rq.scope, false); + if (rq.q) p.set('q', rq.q); + p.set('sort', rq.sort.key); + p.set('desc', String(rq.sort.desc)); + try { return await api.get(`/library/rows/${encodeURIComponent(id)}/position?${p}`); } catch (e) { + if (e instanceof EngineError && (e.status === 404 || e.status === 405)) return null; + throw e; + } +} + export async function fetchRow(id: string): Promise { if (rowsRoute !== false) { try { return await api.get(`/library/rows/${encodeURIComponent(id)}`); } catch (e) { From 3db674d3dea0db4ea863dd4c702e3e54adac9083 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:17:37 -0500 Subject: [PATCH 40/45] fix(side): hide a deleted row at the click and refocus after rename The second delete click hides the row and its subtree at once and restores them if the engine refuses, so the rows below move with the input; Enter in a rename returns focus to the row. --- frontend/src/ui/side.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 88330b7..9d82ecd 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -317,14 +317,23 @@ async function removeRow(pane: Pane, row: HTMLElement): Promise { if (btn) btn.title = 'Delete'; const id = row.dataset.key ?? ''; const lib = pane.engine.library; + const gone = new Set([id]); + const hide = (Array.from(row.parentElement?.children ?? []) as HTMLElement[]).filter((r) => { + if (r === row) return true; + if (r.dataset.parent && gone.has(r.dataset.parent)) { gone.add(r.dataset.key ?? ''); return true; } + return false; + }); + if (row.contains(document.activeElement)) focusNeighbor(pane, row); + for (const r of hide) setClass(r, 'is-folded', true); try { if (row.dataset.kind === 'collection') await sideApi.deleteCollection(id); else await sideApi.deleteTag(id); - if (row.contains(document.activeElement)) focusNeighbor(pane, row); if (row.classList.contains('is-active')) lib.setScope(ALL); if (row.dataset.kind === 'collection') lib.collectionsChanged(); else lib.tagsChanged(); } catch (err) { + for (const r of hide) setClass(r, 'is-folded', false); + if (row.parentElement === pane.tree) applyTree(pane); showError(pane, row, err); } } @@ -396,7 +405,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { const input = (ev.target as HTMLElement).closest('.fc-side-edit'); const row = input?.closest('.fc-side-row'); if (!input || !row) return; - if (ev.key === 'Enter') { ev.preventDefault(); void commitEdit(pane, row); } + if (ev.key === 'Enter') { ev.preventDefault(); void commitEdit(pane, row); row.querySelector('.fc-side-entry')?.focus(); } else if (ev.key === 'Escape') { ev.preventDefault(); endEdit(row); row.querySelector('.fc-side-entry')?.focus(); } }); host.addEventListener('focusout', (ev) => { From 4b16dc6b265e90c1ac6cc57ce5fdc753d0fc2391 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:17:47 -0500 Subject: [PATCH 41/45] docs(window): log the row position route Notes how the position route matches the rows route ordering and when it answers minus one. --- backend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 0ee233a..83a6a6a 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1657,3 +1657,7 @@ New in v0.7.0 (2026-11-27). `GET /api/cite/v1/pair/approved/waiting` lists appro ## app/routers/upload.py {#app-routers-upload-identify} New in v0.7.0 (2026-11-27). `POST /api/library/identify/upload?name=` reads the raw body with `Request.stream()`, so python-multipart is not needed. Neither guard looks at the content type: `WindowKeyGuard` only wants the key header on a non-read method and `LocalGuard` only checks host and origin, so the route is guarded exactly like `/identify`. `content-length` over `MAX_BYTES` (100 MB) is refused before reading, and the streamed count is checked again since the header can be absent or false. The first five bytes must be `%PDF-` or the answer is 415. The name is cut to its last path part and cleaned by `SAFE`, inside a fresh `mkdtemp` folder, so `..%2F..%2Fetc%2Fpasswd` becomes `passwd.pdf` there. `identify_file` runs in the thread pool through the path route's `_run`, so error mapping is shared; the file and folder are removed in `finally`. Dropping the same PDF twice no longer adds a second row: `identify._already` checks the matched item's attachments by sha256 before `_attach`, returns the existing row (with `path`) as `attached`, and the message says nothing was changed. It runs before any store, so `move` leaves the source file in place. Path route, upload route and CLI all go through `identify_file`, so they agree; the CLI was checked twice against the same data. + +## app/routers/window.py, app/services/window_rows.py {#app-window-row-position} + +New in v0.8.0 (2026-11-27). `GET /api/library/rows/{id}/position` takes the same `scope`, `id`, `q`, `sort` and `desc` as `GET /api/library/rows` and returns `{index, total}`. The index is `ROW_NUMBER() OVER (ORDER BY ...) - 1` built from the same `SORTS` expression, direction and `i.id` tie-break, under the same `_where`, so it can never disagree with the rows route. It is `-1` when the item exists but is outside the scope or filter (a trashed item is always `-1`), and the route answers 404 when no item has that id. Checked against `list_rows` on 2,002 items: year descending at offsets 700 to 702 and title with `q=river` at offsets 100 and 101 all matched. From 095b400424f9e32a5d654cd78a1e8dfeb26d69b5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:17:48 -0500 Subject: [PATCH 42/45] docs(frontend): note the item list now uses the position route Adds that insert asks the engine for the index and re-reads only on an older engine. --- frontend/HASHOUT_LOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 1ad7d17..ad25994 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -391,7 +391,7 @@ New in v0.8.0 (2026-11-27). The side sections sit under `visibility: hidden` (`. ## src/engine/itemlist.ts, src/ui/itemlist.ts {#src-itemlist-single-rows} -New in v0.8.0 (2026-11-27). `items:removed` calls `ItemListModel.remove`: the ids are dropped from the sparse row cache, every later cached index moves up by the number of removed indices before it, the count drops, and `reset` repaints the 55 pool rows through the guarded `setText`/`setClass` writes, so only rows whose content moved are written. `ensure` now fetches runs of missing indices (at most `PAGE` long) instead of whole pages, so the rows that slide into the window at the end are the only ones read. An id the cache has never seen falls back to `reload`, because its place among unread pages is unknown. `items:added` and `items:restored` call `insert`: each row is read with `GET /api/library/rows/{id}`, its place is guessed from the cached rows with a client comparator (lowercase `localeCompare`, numbers for added, updated and year), and one nine-row probe of `GET /api/library/rows` around the guess confirms it; the engine has no route that returns a row's position in a sort and filter, so a probe that misses the id falls back to `reload`, and a probe whose total did not grow means the row is outside the scope or filter and nothing is written. Scroll top, selection and focus are not touched. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency, title sort, scrolled to row 300: remove, restore and add each wrote 43 or 44 rows (only the rows at and after the change), zero pool nodes added or removed, no layout shift. +New in v0.8.0 (2026-11-27). `items:removed` calls `ItemListModel.remove`: the ids are dropped from the sparse row cache, every later cached index moves up by the number of removed indices before it, the count drops, and `reset` repaints the 55 pool rows through the guarded `setText`/`setClass` writes, so only rows whose content moved are written. `ensure` now fetches runs of missing indices (at most `PAGE` long) instead of whole pages, so the rows that slide into the window at the end are the only ones read. An id the cache has never seen falls back to `reload`, because its place among unread pages is unknown. `items:added` and `items:restored` call `insert`: each row is read with `GET /api/library/rows/{id}`, its place is guessed from the cached rows with a client comparator (lowercase `localeCompare`, numbers for added, updated and year), and one nine-row probe of `GET /api/library/rows` around the guess confirms it; the engine has no route that returns a row's position in a sort and filter, so a probe that misses the id falls back to `reload`, and a probe whose total did not grow means the row is outside the scope or filter and nothing is written. Scroll top, selection and focus are not touched. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency, title sort, scrolled to row 300: remove, restore and add each wrote 43 or 44 rows (only the rows at and after the change), zero pool nodes added or removed, no layout shift. Later the same day the guess and probe were replaced: `insert` now calls `fetchPosition`, which uses `GET /api/library/rows/{id}/position`, and re-reads only when the route answers 404 or 405 (an older engine) or when the total it returns does not agree. A remove of an id the cache never loaded still re-reads, because a trashed item has no position to ask for. ## src/ui/trash.ts, src/ui/duplicates.ts {#src-review-click} From 2b21dd76488d5ac8b9712ebf5c89502d94662667 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:18:31 -0500 Subject: [PATCH 43/45] docs(detail): log editable notes Records the note routes the pane uses, the save and delete behaviour and the throttled check. --- frontend/HASHOUT_LOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index ad25994..9d02dde 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -404,3 +404,7 @@ New in v0.8.0 (2026-11-27). `patchList` calls `update` only for rows it already ## src/engine/detail.ts, src/styles/detail.css {#src-detail-click} New in v0.8.0 (2026-11-27). The engine stores an empty title without complaint, so `DetailModel.save` refuses it before any request and the pane shows "Title: A title is required." in its error line with the row marked; Escape puts the stored title back. The Trash button keeps its 88 px width and now starts its content at the left, with a hidden `::after` holding "Confirm" so the label box is sized for the longer label; the icon stays at the same x when armed. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and about 400 kbit/s after a hard reload: remove tag, Open and Trash each take the click at their centre, Open sends `POST /api/library/attachments/{id}/open` and gets 200 with `opened_with: "system"`, Trash removes the row and drops the count by one, and layout shift was 0 with and without input. + +## src/io/detail.ts, src/engine/detail.ts, src/ui/detail.ts, src/styles/detail.css {#src-detail-notes} + +New in v0.8.0 (2026-11-27). Notes are editable in the pane through `POST /api/library/items/{id}/notes`, `PATCH /api/library/notes/{id}` and `DELETE /api/library/notes/{id}`, each with `{body}`. Each note is a one-line textarea inside the fixed-height notes box; it saves on blur or Ctrl or Cmd plus Enter, Escape puts back the stored text (kept in `data-saved`), and an empty edit is refused with a sentence in the reserved `.fc-dt-note-error` line. A line under the box adds a note on Enter. Delete asks for a second click within 3 seconds and its label box is sized for "Confirm", so the icon does not move. Notes are shown and sent as plain text: an HTML body from an import is flattened the first time it is saved. Checked in a fresh copy from HEAD with the 2,000-item library under CPU 4x, 400 ms and about 400 kbit/s: add, edit, Escape, delete and a reload all held, the box height did not change, and layout shift was 0 with and without input. From 15b60409f79fa21590dbe0e8bd78d7b8f1d24fb8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:23:31 -0500 Subject: [PATCH 44/45] docs(window): add notes, withdraw, position route and delete focus Each added line was checked against the landed code: note editing, the empty-title refusal, withdrawing an approval, no double attach, the position route and the collection delete. --- docs/WINDOW.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/WINDOW.md b/docs/WINDOW.md index 3ef75ea..e50c192 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -11,7 +11,7 @@ The **Items** view has three panes side by side. ### Library pane (left) - **All items** shows every item that is not in the trash. **Unfiled** shows the items that belong to no collection. Each entry has its count beside it. -- **Collections** is a tree. Click a collection to list its items. You can create a collection, rename it and delete it in place, without a dialog. Each collection row also has a plus button, **New subcollection**, that adds a collection inside it. Deleting a collection does not delete its items. +- **Collections** is a tree. Click a collection to list its items. You can create a collection, rename it and delete it in place, without a dialog. Each collection row also has a plus button, **New subcollection**, that adds a collection inside it. Deleting a collection does not delete its items. The row (and the collections inside it) is hidden at the click and comes back if the engine refuses; if the focus was on it, the focus moves to the next row at the same or a shallower level, or the one above. - The tree works from the keyboard: the up and down arrows move between visible rows, Home and End jump to the first and last, the right arrow opens a collection (and a second press moves into it), the left arrow closes it (or moves to its parent), and Enter or Space picks the row. - **Tags** lists every tag. Click one to list the items that carry it. A tag can be renamed or deleted from here. - The entry you are looking at stays marked. @@ -21,13 +21,14 @@ The **Items** view has three panes side by side. - Columns: title, creator, year, type and date added. Click a column head to sort by it, click again to reverse. - The search box filters the list by words in titles, creators, container titles, abstracts, notes and tags. - 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, restored or removed, the list changes only that row and moves the rows below it; it does not reload the list. A removal fetches only the rows that were not yet loaded. +- 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. If the engine cannot say where a row falls, or a removed item was never loaded, the list is read again. - 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. ### Detail pane (right) - Shows the selected item: type, title, creators, date, container, volume, issue, pages, DOI, URL, abstract, tags, attachments and notes. -- Edit a field and leave it (or press Enter) to save that one field. Escape puts the old value back. +- Edit a field and leave it (or press Enter) to save that one field. Escape puts the old value back. A title cannot be saved empty: the window refuses with "A title is required." +- Notes are editable in place: change a note's text and leave it (or press Ctrl or Cmd with Enter) to save it, and Escape puts the old text back. A note cannot be saved empty. Type in the box under the notes and press Enter to add one. **Delete** on a note asks for a second click, labelled Confirm, within 3 seconds. - Add a tag by typing it, remove one with its remove button. - **Move to trash** asks you to confirm in place, then sends the item to the trash. @@ -39,7 +40,7 @@ The **Add** button opens a dialog with three ways in: - **Import.** Paste text or pick a file in BibTeX, RIS or CSL-JSON. The format can be picked or left for FormCite to recognise. - **Export.** Save the items you are looking at in one of those formats. -You can also drop PDF files anywhere on the window. The window sends each dropped file's bytes to the engine, which reads it, finds its identifier, looks it up and attaches the file to the new item; no file path is needed, and progress shows in place. Other files that FormCite can import are imported. +You can also drop PDF files anywhere on the window. The window sends each dropped file's bytes to the engine, which reads it, finds its identifier, looks it up and attaches the file to the new item; no file path is needed, and progress shows in place. If the item is already in the library and already holds a file with the same content, the file is not attached a second time. Other files that FormCite can import are imported. When the network is switched off, or the one service a lookup needs is off, the dialog says so in the engine's own words and nothing is added. @@ -53,7 +54,7 @@ The **Duplicates** view lists sets of items that look like the same reference: t ## Connections -The **Connections** view lists the apps and agents that use FormCite's service. Apps whose request you approved but that have not yet collected their token are listed in a third group, **Approved, waiting for the app to collect**, with how long the app has left to collect it. That row has no withdraw action, because an approval cannot be taken back. +The **Connections** view lists the apps and agents that use FormCite's service. Apps whose request you approved but that have not yet collected their token are listed in a third group, **Approved, waiting for the app to collect**, with how long the app has left to collect it. That row has **Withdraw approval**, which takes the approval back before the app collects it. ## Preferences From 93527164e5bc5f6a32aaac8d4ace03a2c170c32f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 03:26:29 -0500 Subject: [PATCH 45/45] chore(release): 0.8.0 Moves every version site to 0.8.0 and adds the changelog section. --- CHANGELOG.md | 33 ++++++++++++++++++++++++++++ backend/HASHOUT_LOG.md | 2 +- backend/app/__init__.py | 2 +- frontend/HASHOUT_LOG.md | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- frontend/src/version.ts | 2 +- native/formcite-style/Cargo.lock | 2 +- native/formcite-style/Cargo.toml | 2 +- native/formcite-style/pyproject.toml | 2 +- setup/HASHOUT_LOG.md | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/HASHOUT_LOG.md | 2 +- src-tauri/tauri.conf.json | 2 +- 15 files changed, 48 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dc844b..6d28e3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## 0.8.0 + +The library window is finished: everything in it now stays still while it loads and while you work. + +### New +- Collections inside collections. Each collection has a "New subcollection" action, and the tree can be folded. +- Move through the collection tree with the keyboard: up and down between rows, left and right to fold, unfold or step in and out, Enter to choose. +- Drop a PDF on the window in a browser and it is identified and added with the file attached. Dropping the same file again does not attach it twice. +- Notes can be added, edited in place and deleted in the item pane. +- Connections shows an app you approved that has not collected its access yet, and you can withdraw that approval. + +### Changed +- Adding, restoring or removing an item now changes only the rows that move in the list, where it used to read the page again. +- A title can no longer be saved empty from the item pane. +- Deleting a collection, restoring or deleting from the trash, and merging duplicates take effect at the click, and are put back if the engine refuses. +- The readme says that the window and agent tools look things up too, and that Preferences holds the switches. + +### Fixed +- The side pane no longer jumps one row when collections and tags first appear, or when a collection is created or deleted. +- Preferences no longer shifts when the services and libraries fill in, or when a library is created or switched; a new library row used to appear empty. +- The Trash button in the item pane no longer moves when it asks you to confirm. +- After renaming or deleting a collection, keyboard focus stays in the tree. + +### Known issues +- "Open in FormPDF" still opens the system viewer: FormPDF cannot yet take a file from another Form app. +- Removing an item the list has not loaded yet still reads the list again. +- Creators are still edited as one line of text. +- The tag list was not measured with real tags in this release. +- The desktop app has not been built yet; the window runs in a browser against the engine. + +### Under the hood +- A new engine route says where a row falls in the current sort and filter, and a raw upload route takes a dropped PDF. + ## 0.7.0 The window shows your library for the first time. This is a first pass: it works end to end, and parts of it have not yet been checked as closely as the rest. diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 83a6a6a..b9c5f93 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.7.0 +Current build version: v0.8.0 Last updated: 2026-11-27 (US Eastern) · the lean rows route for the window's list and opening an attachment --- diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 49e0fc1..777f190 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.7.0" +__version__ = "0.8.0" diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 9d02dde..d7a9c17 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for this side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-26 (US Eastern) · window skeleton: shell, engine store, window key, health status --- diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f867907..81a9f70 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formcite", - "version": "0.7.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcite", - "version": "0.7.0", + "version": "0.8.0", "license": "GPL-3.0-only", "devDependencies": { "typescript": "7.0.2", diff --git a/frontend/package.json b/frontend/package.json index 8bbaf69..78a47d2 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formcite", "private": true, - "version": "0.7.0", + "version": "0.8.0", "description": "FormCite: a local-first personal research library from the Form family", "license": "GPL-3.0-only", "type": "module", diff --git a/frontend/src/version.ts b/frontend/src/version.ts index b6d55fa..ca24a8e 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.7.0'; +export const VERSION = '0.8.0'; diff --git a/native/formcite-style/Cargo.lock b/native/formcite-style/Cargo.lock index 6c8cffe..5b596ec 100644 --- a/native/formcite-style/Cargo.lock +++ b/native/formcite-style/Cargo.lock @@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "formcite-style" -version = "0.7.0" +version = "0.8.0" dependencies = [ "hayagriva", "pyo3", diff --git a/native/formcite-style/Cargo.toml b/native/formcite-style/Cargo.toml index 541f670..ed26cf5 100644 --- a/native/formcite-style/Cargo.toml +++ b/native/formcite-style/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcite-style" -version = "0.7.0" +version = "0.8.0" edition = "2024" rust-version = "1.95" license = "Apache-2.0" diff --git a/native/formcite-style/pyproject.toml b/native/formcite-style/pyproject.toml index d206ec5..2effc06 100644 --- a/native/formcite-style/pyproject.toml +++ b/native/formcite-style/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "formcite-style" -version = "0.7.0" +version = "0.8.0" description = "FormCite citation style engine for the FormCite engine service" license = { text = "Apache-2.0" } requires-python = ">=3.10" diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 0207fca..dd9d81c 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, and removed code for the root launcher scripts and the `setup/` suite. The scripts stay comment-free; everything they would have said lives here, indexed. Read this first, then edit the scripts surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-27 · initial port of the launcher and setup suite --- diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 2d8d7ac..29488e1 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -918,7 +918,7 @@ dependencies = [ [[package]] name = "formcite" -version = "0.7.0" +version = "0.8.0" dependencies = [ "fontdb", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1468ca6..03a01ee 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcite" -version = "0.7.0" +version = "0.8.0" description = "FormCite desktop shell" authors = ["NodeAgentc, Inc."] license = "GPL-3.0-only" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index 9d728c7..3d6fcf0 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the desktop shell side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-26 (US Eastern) · Tauri 2 shell ported from FormTxt, renamed, launch code added --- diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e2990bd..fc6aa04 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormCite", - "version": "0.7.0", + "version": "0.8.0", "identifier": "ai.nodemode.formcite", "build": { "devUrl": "http://localhost:5330",