diff --git a/NOTICE b/NOTICE index 236e655..31faa65 100644 --- a/NOTICE +++ b/NOTICE @@ -25,5 +25,7 @@ Models downloaded at runtime (from the configured host) - PP-OCRv6 tiny / medium (det + rec ONNX), PaddlePaddle ............ Apache-2.0 - IBM Granite Embedding 311M Multilingual R2 (ONNX q8) (ibm-granite / onnx-community ports) ............................. Apache-2.0 +- IBM Granite 4.0 Nano 350M / 1B Instruct (ONNX-web, transformers.js) + (ibm-granite / onnx-community ports) ............................. Apache-2.0 - Qwen2.5 0.5B / 1.5B Instruct, Qwen3.5 0.8B (MLC builds) .......... Apache-2.0 - WebLLM model libraries (mlc-ai/binary-mlc-llm-libs) .............. Apache-2.0 diff --git a/README.md b/README.md index 394a7ac..9cddae5 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ npm run test:e2e # Playwright (fake S3, no real bucket) Host `dist/` on any **HTTPS** static host. Camera, WebGPU, service worker, and crypto need a secure context. -**Tip:** Filling titles/dates with Qwen needs **WebGPU** (recent Chrome / Edge, or Safari 26 / iOS 26). OCR and meaning search still work without it. +**Tip:** Filling titles/dates is fastest with **WebGPU** (recent Chrome / Edge, or Safari 26 / iOS 26). Granite Nano can fall back to WASM without it; Qwen still needs WebGPU. OCR and meaning search work either way. ## Set up your bucket @@ -108,7 +108,7 @@ When you add a document, models download once (then stay cached) and run **local | Step | What it does | Model | | --- | --- | --- | | **Read the page** | Photo/PDF → text | PP-OCRv6 (tiny by default; medium optional) | -| **Fill the filing card** | Suggests title, sender, date, labels | Small Qwen models via WebLLM | +| **Fill the filing card** | Suggests title, sender, date, labels | IBM Granite 4.0 Nano (transformers.js); Qwen via WebLLM still available | | **Search by meaning** | Finds docs by idea, not exact words | IBM Granite Embedding 311M Multilingual R2 | Only **one** engine is in memory at a time (so phones stay stable). While models are downloading, new documents wait with a clear banner. @@ -126,9 +126,11 @@ Only **one** engine is in memory at a time (so phones stay stable). While models | Model | Size | Notes | | --- | --- | --- | -| Qwen2.5 0.5B | ~295 MB | Lightest; safer on phones | -| Qwen3.5 0.8B | ~454 MB | Newer small multilingual Qwen | -| Qwen2.5 1.5B | ~887 MB | Default everyday model | +| Granite 4.0 350M | ~334 MB | Default; IBM Nano via transformers.js (WebGPU / WASM) | +| Granite 4.0 1B | ~1.2 GB | Stronger instruct; heavier | +| Qwen2.5 0.5B | ~295 MB | WebLLM; needs WebGPU | +| Qwen3.5 0.8B | ~454 MB | WebLLM; needs WebGPU | +| Qwen2.5 1.5B | ~887 MB | WebLLM; needs WebGPU | You can pick a **different model per field**. Labels only come from **your** list — the model does not invent categories. @@ -143,7 +145,8 @@ Weights are **not** in git. They download on first use and cache on the device. | Model | Job | License | | --- | --- | --- | | PP-OCRv6 tiny / medium | OCR | Apache-2.0 | -| Qwen2.5 / Qwen3.5 (above) | Metadata | Apache-2.0 | +| Granite 4.0 Nano 350M / 1B | Metadata | Apache-2.0 | +| Qwen2.5 / Qwen3.5 (above) | Metadata (optional) | Apache-2.0 | | Granite Embedding 311M R2 | Meaning search | Apache-2.0 | Libraries and attribution: [NOTICE](NOTICE). @@ -155,7 +158,7 @@ flowchart LR subgraph Device["Your browser"] UI[App UI] --> Q[Processing queue] Q --> OCR["OCR"] - Q --> LLM["Qwen via WebLLM"] + Q --> LLM["Granite / Qwen metadata"] Q --> EMB["Granite Embedding"] UI --> IDB[("Encrypted keys + settings")] UI --> ST["S3 client"] diff --git a/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md b/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md index 6b0cf31..cb5d0e5 100644 --- a/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md +++ b/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md @@ -28,7 +28,7 @@ or keys. deleted on start. - The S3 keys are encrypted with a user password: PBKDF2-SHA-256 (600,000 rounds) → AES-256-GCM, stored in IndexedDB. The app shows an unlock screen on every open and forgets the plain keys after 15 minutes idle. -- OCR (PP-OCRv6 via onnxruntime-web), metadata (WebLLM / Qwen) and meaning-search +- OCR (PP-OCRv6 via onnxruntime-web), metadata (IBM Granite 4.0 Nano via transformers.js; optional Qwen via WebLLM) and meaning-search embeddings (**IBM Granite Embedding 311M Multilingual R2** via transformers.js, Apache-2.0) all run on the device. Models download from Hugging Face / official WebLLM libs on first use and are cached in the browser (not in the document bucket). - Memory rules for phones: one model in memory at a time, downloads one file at a time streamed into the cache, diff --git a/docs/images/05-setup.png b/docs/images/05-setup.png new file mode 100644 index 0000000..9578bb0 Binary files /dev/null and b/docs/images/05-setup.png differ diff --git a/e2e/capture-demo.spec.ts b/e2e/capture-demo.spec.ts index 25e5f05..ab2553a 100644 --- a/e2e/capture-demo.spec.ts +++ b/e2e/capture-demo.spec.ts @@ -68,7 +68,7 @@ test.describe("docs media capture", () => { // 1× CSS pixels → sharper GIF (2× retina looked muddy after palette quantisation). await page.setViewportSize({ width: 1120, height: 720 }); await page.goto("/"); - await expect(page.getByTestId("app-shell").or(page.getByTestId("unlock-screen")).or(page.getByTestId("app-booting"))).toBeVisible({ timeout: 20_000 }); + await expect(page.getByTestId("app-shell").or(page.getByTestId("unlock-screen")).or(page.getByTestId("setup-screen")).or(page.getByTestId("app-booting"))).toBeVisible({ timeout: 20_000 }); await seedStorageSettings(page); await seedVault(page); await page.reload(); diff --git a/e2e/first-run.spec.ts b/e2e/first-run.spec.ts index 7a363e7..32d2ee8 100644 --- a/e2e/first-run.spec.ts +++ b/e2e/first-run.spec.ts @@ -1,30 +1,78 @@ import { test, expect } from "@playwright/test"; +import { FakeBucket, FAKE_BUCKET, FAKE_ENDPOINT, FAKE_REGION, installFakeS3 } from "./helpers/fakeS3"; import { blockModelDownloads } from "./helpers/seed"; test.describe("first run (no vault)", () => { test.beforeEach(async ({ page }) => { await blockModelDownloads(page); await page.goto("/"); - await expect(page.getByTestId("app-shell")).toBeVisible({ timeout: 15_000 }); + await expect(page.getByTestId("setup-screen")).toBeVisible({ timeout: 15_000 }); }); - test("shows empty state and storage setup hint", async ({ page }) => { - await expect(page.getByTestId("empty-state")).toBeVisible(); - await expect(page.getByText(/Set up .*Storage/i)).toBeVisible(); - await expect(page.getByRole("heading", { name: "No documents found" })).toBeVisible(); - }); - - test("opens settings and storage section", async ({ page }) => { - await page.getByRole("complementary", { name: "Folders" }).getByRole("button", { name: /Storage/i }).click(); - await expect(page.getByRole("dialog", { name: /Settings/i })).toBeVisible(); + test("shows setup page with storage fields", async ({ page }) => { + await expect(page.getByRole("heading", { name: /Documents Manager/i })).toBeVisible(); + await expect(page.getByText(/OCR and AI run on this device/i)).toBeVisible(); await expect(page.getByTestId("s3-endpoint")).toBeVisible(); await expect(page.getByTestId("s3-save-keys")).toBeVisible(); + await expect(page.getByTestId("s3-save-keys")).toContainText(/Save and continue/i); + }); + + test("shows what you need beforehand", async ({ page }) => { + await page.getByText(/What you need beforehand/i).click(); + await expect(page.getByText(/CORS rule/i)).toBeVisible(); + }); + + test("stays on setup when passwords do not match", async ({ page }) => { + await page.getByTestId("s3-endpoint").fill(FAKE_ENDPOINT); + await page.getByTestId("s3-bucket").fill(FAKE_BUCKET); + await page.getByTestId("s3-access-key").fill("AKIA_TEST_KEY_0001"); + await page.getByTestId("s3-secret-key").fill("test-secret-key-value"); + await page.getByTestId("s3-password").fill("test-password-123"); + await page.getByTestId("s3-password-repeat").fill("different-password"); + await page.getByTestId("s3-save-keys").click(); + + await expect(page.getByTestId("setup-screen")).toBeVisible(); + await expect(page.getByTestId("s3-status")).toContainText(/do not match/i); + await expect(page.getByTestId("app-shell")).toHaveCount(0); + }); + + test("stays on setup when the bucket cannot be reached", async ({ page }) => { + // No fake S3 route — the browser cannot reach s3.test.local. + await page.getByTestId("s3-endpoint").fill(FAKE_ENDPOINT); + await page.getByTestId("s3-bucket").fill(FAKE_BUCKET); + await page.getByTestId("s3-region").fill(FAKE_REGION); + await page.getByTestId("s3-path-style").check(); + await page.getByTestId("s3-access-key").fill("AKIA_TEST_KEY_0001"); + await page.getByTestId("s3-secret-key").fill("test-secret-key-value"); + await page.getByTestId("s3-password").fill("test-password-123"); + await page.getByTestId("s3-password-repeat").fill("test-password-123"); + await page.getByTestId("s3-save-keys").click(); + + await expect(page.getByTestId("s3-status")).toContainText(/❌/, { timeout: 30_000 }); + await expect(page.getByTestId("setup-screen")).toBeVisible(); + await expect(page.getByTestId("app-shell")).toHaveCount(0); }); - test("opens scan picker", async ({ page }) => { - await page.getByTestId("open-scan").click(); - await expect(page.getByRole("dialog", { name: /Add a document/i })).toBeVisible(); - await expect(page.getByText("Scan with camera")).toBeVisible(); - await expect(page.getByText(/Upload PDF/i)).toBeVisible(); + test("completes setup into the main app", async ({ page }) => { + const bucket = new FakeBucket(); + bucket.seedMeta([]); + await installFakeS3(page, bucket); + // Routes are live for this page; reload so settings start clean with the fake endpoint ready. + await page.reload(); + await expect(page.getByTestId("setup-screen")).toBeVisible({ timeout: 15_000 }); + + await page.getByTestId("s3-endpoint").fill(FAKE_ENDPOINT); + await page.getByTestId("s3-bucket").fill(FAKE_BUCKET); + await page.getByTestId("s3-region").fill(FAKE_REGION); + await page.getByTestId("s3-path-style").check(); + await page.getByTestId("s3-access-key").fill("AKIA_TEST_KEY_0001"); + await page.getByTestId("s3-secret-key").fill("test-secret-key-value"); + await page.getByTestId("s3-password").fill("test-password-123"); + await page.getByTestId("s3-password-repeat").fill("test-password-123"); + await page.getByTestId("s3-save-keys").click(); + + await expect(page.getByTestId("app-shell")).toBeVisible({ timeout: 60_000 }); + await expect(page.getByTestId("empty-state")).toBeVisible(); + await expect(page.getByRole("heading", { name: "No documents found" })).toBeVisible(); }); }); diff --git a/e2e/helpers/session.ts b/e2e/helpers/session.ts index add295f..3ac0a63 100644 --- a/e2e/helpers/session.ts +++ b/e2e/helpers/session.ts @@ -16,7 +16,7 @@ export async function openUnlockedApp(page: Page, docs = DEMO_DOCS): Promise { await blockModelDownloads(page); await page.goto("/"); - await expect(page.getByTestId("app-shell").or(page.getByTestId("unlock-screen")).or(page.getByTestId("app-booting"))).toBeVisible({ timeout: 15_000 }); + await expect(page.getByTestId("app-shell").or(page.getByTestId("unlock-screen")).or(page.getByTestId("setup-screen")).or(page.getByTestId("app-booting"))).toBeVisible({ timeout: 15_000 }); await seedStorageSettings(page); await seedVault(page); await page.reload(); diff --git a/e2e/storage.spec.ts b/e2e/storage.spec.ts index a32067b..49757b2 100644 --- a/e2e/storage.spec.ts +++ b/e2e/storage.spec.ts @@ -3,16 +3,14 @@ import { FakeBucket, FAKE_BUCKET, FAKE_ENDPOINT, FAKE_REGION, installFakeS3 } fr import { blockModelDownloads } from "./helpers/seed"; test.describe("storage setup", () => { - test("saves keys and tests the fake bucket connection", async ({ page }) => { + test("saves keys and tests the fake bucket connection from setup", async ({ page }) => { const bucket = new FakeBucket(); bucket.seedMeta([]); await installFakeS3(page, bucket); await blockModelDownloads(page); await page.goto("/"); - await expect(page.getByTestId("app-shell")).toBeVisible({ timeout: 15_000 }); - - await page.getByRole("complementary", { name: "Folders" }).getByRole("button", { name: /Storage/i }).click(); + await expect(page.getByTestId("setup-screen")).toBeVisible({ timeout: 15_000 }); await page.getByTestId("s3-endpoint").fill(FAKE_ENDPOINT); await page.getByTestId("s3-bucket").fill(FAKE_BUCKET); @@ -25,8 +23,13 @@ test.describe("storage setup", () => { await page.getByTestId("s3-password-repeat").fill("test-password-123"); await page.getByTestId("s3-save-keys").click(); - await expect(page.getByTestId("s3-status")).toContainText(/Saved/i, { timeout: 60_000 }); + await expect(page.getByTestId("app-shell")).toBeVisible({ timeout: 60_000 }); + // Settings → Storage still exposes Save keys / Test for returning edits + await page.getByRole("complementary", { name: "Folders" }).getByRole("button", { name: /Storage/i }).click(); + await expect(page.getByRole("dialog", { name: /Settings/i })).toBeVisible(); + await expect(page.getByTestId("s3-endpoint")).toHaveValue(FAKE_ENDPOINT); + await expect(page.getByTestId("s3-test")).toBeVisible(); await page.getByTestId("s3-test").click(); await expect(page.getByTestId("s3-status")).toContainText(/Connected/i, { timeout: 15_000 }); }); diff --git a/e2e/unlock.spec.ts b/e2e/unlock.spec.ts index e766592..f2a89d4 100644 --- a/e2e/unlock.spec.ts +++ b/e2e/unlock.spec.ts @@ -13,7 +13,7 @@ test.describe("unlock", () => { await blockModelDownloads(page); await page.goto("/"); - await expect(page.getByTestId("app-shell").or(page.getByTestId("unlock-screen")).or(page.getByTestId("app-booting"))).toBeVisible({ timeout: 15_000 }); + await expect(page.getByTestId("app-shell").or(page.getByTestId("unlock-screen")).or(page.getByTestId("setup-screen")).or(page.getByTestId("app-booting"))).toBeVisible({ timeout: 15_000 }); await seedStorageSettings(page); await seedVault(page); diff --git a/src/App.tsx b/src/App.tsx index 641f319..320e1b2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,9 +1,11 @@ -/* App shell: boot settings + vault, then unlock gate or the main document UI. */ +/* App shell: boot settings + vault, then unlock / setup gate or the main document UI. */ import { useEffect, useState } from "react"; import { MainScreen } from "./app/MainScreen"; +import { Setup } from "./components/Setup"; import { Unlock } from "./components/Unlock"; import { cleanupOldData } from "./lib/db"; -import { initSettings } from "./lib/settings"; +import { initSettings, useSettings } from "./lib/settings"; +import { storageConfigured } from "./lib/files"; import { initVault, startIdleLock, useVault } from "./lib/vault"; export type { Toast } from "./app/MainScreen"; @@ -11,6 +13,7 @@ export type { Toast } from "./app/MainScreen"; export default function App() { const [ready, setReady] = useState(false); const vault = useVault(); + useSettings(); // re-render when storage settings change during setup useEffect(() => { (async () => { await initSettings(); @@ -22,5 +25,6 @@ export default function App() { }, []); if (!ready) return
; if (vault.hasVault && !vault.unlocked) return ; + if (!storageConfigured() || !vault.hasVault) return ; return ; } diff --git a/src/components/ModelsCard.tsx b/src/components/ModelsCard.tsx index b8bee88..f88de2c 100644 --- a/src/components/ModelsCard.tsx +++ b/src/components/ModelsCard.tsx @@ -22,8 +22,13 @@ export function ModelsCard() { { use: "📝 OCR", kind: "ocr", key: ocr.key, name: ocr.emoji + " " + ocr.name, size: ocr.approx, runs: "✅" }, ...(["title", "from", "date", "labels"] as const).map((f) => { const m = LLM_BY_KEY[s.metaModels[f]]; - return { use: { title: "📝 Title", from: "📨 From", date: "📅 Date", labels: "🏷️ Labels" }[f], kind: "meta" as const, key: m.key, name: m.emoji + " " + m.name, size: m.approx, - runs: !gpu ? "…" : !gpu.webgpu ? "❌ no WebGPU" : isPhone() && m.desktopOnly ? "❌ too big for a phone" : m.phoneRisk && isPhone() ? "⚠️ may crash" : "✅" }; + const runs = !gpu ? "…" + : isPhone() && m.desktopOnly ? "❌ too big for a phone" + : m.phoneRisk && isPhone() ? "⚠️ may crash" + : m.runtime === "transformers" + ? (gpu.webgpu ? "✅" : "✅ WASM (slower)") + : !gpu.webgpu ? "❌ no WebGPU" : "✅"; + return { use: { title: "📝 Title", from: "📨 From", date: "📅 Date", labels: "🏷️ Labels" }[f], kind: "meta" as const, key: m.key, name: m.emoji + " " + m.name, size: m.approx, runs }; }), (() => { const m = SEARCH_BY_KEY[s.searchModel]; return { use: "🔍 Search", kind: "search" as const, key: m.key, name: m.emoji + " " + m.name, size: m.approx, runs: "✅" }; })(), ]; diff --git a/src/components/SettingsSheet.tsx b/src/components/SettingsSheet.tsx index ddebd3c..27b24a8 100644 --- a/src/components/SettingsSheet.tsx +++ b/src/components/SettingsSheet.tsx @@ -5,11 +5,10 @@ import { ModelsCard } from "./ModelsCard"; import { DEFAULT_PROMPTS, PAGES_MAX, PAGES_MIN, updateSettings, useSavedAt, useSettings } from "../lib/settings"; import { LLM_MODELS, OCR_ENGINES, SEARCH_MODELS, type OcrKey } from "../lib/catalog"; import { META_FIELDS, type MetaField } from "../lib/types"; -import { forgetKeys, lock, saveKeys, useVault } from "../lib/vault"; -import { testConnection } from "../lib/store"; import { rebuildIndex, useIndexStatus } from "../search/vectors"; import { allDocs, ensureFull } from "../lib/docs"; import { userState } from "../lib/userstate"; +import { StorageForm } from "./StorageForm"; const SECTIONS = [ ["models", "🧠 Models"], ["ocr", "📝 OCR"], ["meta", "🧾 Metadata"], ["search", "🔍 Search"], ["storage", "☁️ Storage"], ["labels", "🏷️ Labels"], ["advanced", "🐞 Advanced"], @@ -140,68 +139,17 @@ function RebuildRow() { } function SyncCard() { - const s = useSettings(); - const v = useVault(); - const [keyId, setKeyId] = useState(""); - const [secret, setSecret] = useState(""); - const [pw, setPw] = useState(""); - const [pw2, setPw2] = useState(""); - const [msg, setMsg] = useState(""); - const set = (k: keyof typeof s.s3, val: string | boolean | number) => updateSettings((x) => ({ s3: { ...x.s3, [k]: val } })); - const cryptoOk = () => typeof crypto !== "undefined" && !!crypto.subtle; - const noCrypto = "⚠️ This page is not a secure address, so the browser blocks encryption. Open it as https://… or http://localhost:5173 (not a LAN IP like http://192.168…)."; - const save = async () => { - setMsg(""); - if (!keyId.trim()) return setMsg("⚠️ Enter the access key ID first."); - if (!secret.trim()) return setMsg("⚠️ Enter the secret key first."); - if (!pw) return setMsg("⚠️ Enter a password first (it encrypts the keys)."); - if (pw.length < 8) return setMsg("⚠️ The password needs at least 8 characters."); - if (!pw2) return setMsg("⚠️ Repeat the password in the Repeat field."); - if (pw !== pw2) return setMsg("⚠️ The two passwords do not match."); - if (!cryptoOk()) return setMsg(noCrypto); - setMsg("⏳ Encrypting and saving…"); - try { await saveKeys({ accessKeyId: keyId, secretAccessKey: secret }, pw); setKeyId(""); setSecret(""); setPw(""); setPw2(""); setMsg("✅ Saved. Keys are encrypted on this device. Tap ✅ Test to check the connection."); } - catch (e) { setMsg("❌ Could not save the keys: " + ((e as Error)?.message || String(e))); } - }; - const test = async () => { - setMsg(""); - if (!s.s3.endpoint.trim()) return setMsg("⚠️ Enter the endpoint first, e.g. https://.r2.cloudflarestorage.com"); - try { new URL(s.s3.endpoint.trim()); } catch { return setMsg("⚠️ The endpoint must be a full address starting with https://"); } - if (!s.s3.bucket.trim()) return setMsg("⚠️ Enter the bucket name first."); - if (!v.hasVault) return setMsg("⚠️ Save your keys first (fill in the key fields and a password, then 💾 Save keys)."); - if (!v.unlocked) return setMsg("⚠️ The keys are locked. Reload the app and unlock it with your password."); - setMsg("⏳ Testing…"); - try { await testConnection(); setMsg("✅ Connected"); } - catch (e) { - const m = (e as Error)?.message || String(e); - const cors = /fetch|network|load failed|cors/i.test(m) ? " — The browser could not reach the bucket. This is usually a missing CORS rule: allow this page's address (" + location.origin + ") with GET, PUT, DELETE, HEAD and expose ETag (see README). Also check the endpoint and Path-style setting." : ""; - setMsg("❌ " + m + cors); - } - }; return ( - -

Works with any S3-compatible service: AWS S3, Cloudflare R2, MinIO, Backblaze B2, Wasabi… The bucket needs a CORS rule for this app's address (see README).

-

Use a key that can only read and write this one bucket. The keys are encrypted with your password (PBKDF2 + AES-GCM) and stored only in this browser. The app asks for the password on every open and locks after 15 minutes idle.

-

Documents are read from and saved to the bucket directly; nothing is stored on this device. Use 🔄 Refresh to load changes made elsewhere.

- }> -
set("endpoint", e.target.value)} />
-
set("bucket", e.target.value)} />
-
set("region", e.target.value)} />
-
set("prefix", e.target.value)} />
-
set("pathStyle", e.target.checked)} />
-

🔑 Keys {v.hasVault && saved {v.keyIdHint} · {v.unlocked ? "🔓 unlocked" : "🔒 locked"}}

-
setKeyId(e.target.value)} />
-
setSecret(e.target.value)} />
-
setPw(e.target.value)} />
-
setPw2(e.target.value)} />
-
- - - {v.unlocked && } - {v.hasVault && } -
- {msg &&

{msg}

} -
+ +

Works with any S3-compatible service: AWS S3, Cloudflare R2, MinIO, Backblaze B2, Wasabi… The bucket needs a CORS rule for this app's address (see README).

+

Use a key that can only read and write this one bucket. The keys are encrypted with your password (PBKDF2 + AES-GCM) and stored only in this browser. The app asks for the password on every open and locks after 15 minutes idle.

+

Documents are read from and saved to the bucket directly; nothing is stored on this device. Use 🔄 Refresh to load changes made elsewhere.

+ + } + /> ); } diff --git a/src/components/Setup.tsx b/src/components/Setup.tsx new file mode 100644 index 0000000..8445bbc --- /dev/null +++ b/src/components/Setup.tsx @@ -0,0 +1,34 @@ +/* ☁️ First-run: welcome + storage setup before the main document UI. */ +import { StorageForm } from "./StorageForm"; + +export function Setup() { + return ( +
+
+

📂 Documents Manager

+

+ Scan bills and letters in your browser. OCR and AI run on this device; files live in an + S3-compatible bucket you control. +

+
+ What you need beforehand +
+

1. An S3-compatible bucket (AWS S3, Cloudflare R2, MinIO, …).

+

2. An access key that can only read and write that bucket.

+

+ 3. A CORS rule for this page ({location.origin}) allowing GET, PUT, DELETE, HEAD and + exposing ETag — see the README. +

+
+
+

+ ☁️ Connect your storage +

+ +
+
+ ); +} diff --git a/src/components/StorageForm.tsx b/src/components/StorageForm.tsx new file mode 100644 index 0000000..a4abb55 --- /dev/null +++ b/src/components/StorageForm.tsx @@ -0,0 +1,318 @@ +/* Shared S3 bucket + keys form for first-run Setup and Settings → Storage. */ +import { useState, type ReactNode } from "react"; +import { S3 } from "../lib/s3"; +import { updateSettings, useSettings } from "../lib/settings"; +import { forgetKeys, lock, saveKeys, useVault } from "../lib/vault"; +import { testConnection } from "../lib/store"; + +const noCrypto = + "⚠️ This page is not a secure address, so the browser blocks encryption. Open it as https://… or http://localhost:5173 (not a LAN IP like http://192.168…)."; + +const cryptoOk = () => typeof crypto !== "undefined" && !!crypto.subtle; + +function corsHint(message: string): string { + return /fetch|network|load failed|cors/i.test(message) + ? " — The browser could not reach the bucket. This is usually a missing CORS rule: allow this page's address (" + + location.origin + + ") with GET, PUT, DELETE, HEAD and expose ETag (see README). Also check the endpoint and Path-style setting." + : ""; +} + +export type StorageFormMode = "settings" | "setup"; + +export function StorageForm({ + mode = "settings", + onReady, + help, +}: { + mode?: StorageFormMode; + /** Called after keys are saved and the connection test succeeds (setup flow). */ + onReady?: () => void; + help?: ReactNode; +}) { + const s = useSettings(); + const v = useVault(); + const [keyId, setKeyId] = useState(""); + const [secret, setSecret] = useState(""); + const [pw, setPw] = useState(""); + const [pw2, setPw2] = useState(""); + const [msg, setMsg] = useState(""); + const [busy, setBusy] = useState(false); + const setup = mode === "setup"; + + const set = (k: keyof typeof s.s3, val: string | boolean | number) => + updateSettings((x) => ({ s3: { ...x.s3, [k]: val } })); + + const validateKeys = (): string | null => { + if (!keyId.trim()) return "⚠️ Enter the access key ID first."; + if (!secret.trim()) return "⚠️ Enter the secret key first."; + if (!pw) return "⚠️ Enter a password first (it encrypts the keys)."; + if (pw.length < 8) return "⚠️ The password needs at least 8 characters."; + if (!pw2) return "⚠️ Repeat the password in the Repeat field."; + if (pw !== pw2) return "⚠️ The two passwords do not match."; + if (!cryptoOk()) return noCrypto; + return null; + }; + + const validateBucket = (): string | null => { + if (!s.s3.endpoint.trim()) + return "⚠️ Enter the endpoint first, e.g. https://.r2.cloudflarestorage.com"; + try { + new URL(s.s3.endpoint.trim()); + } catch { + return "⚠️ The endpoint must be a full address starting with https://"; + } + if (!s.s3.bucket.trim()) return "⚠️ Enter the bucket name first."; + return null; + }; + + const save = async (): Promise => { + setMsg(""); + const err = validateKeys(); + if (err) { + setMsg(err); + return false; + } + setMsg("⏳ Encrypting and saving…"); + try { + await saveKeys({ accessKeyId: keyId, secretAccessKey: secret }, pw); + setKeyId(""); + setSecret(""); + setPw(""); + setPw2(""); + setMsg( + setup + ? "✅ Keys saved." + : "✅ Saved. Keys are encrypted on this device. Tap ✅ Test to check the connection." + ); + return true; + } catch (e) { + setMsg("❌ Could not save the keys: " + ((e as Error)?.message || String(e))); + return false; + } + }; + + const test = async (): Promise => { + setMsg(""); + const bucketErr = validateBucket(); + if (bucketErr) { + setMsg(bucketErr); + return false; + } + if (!v.hasVault) { + setMsg("⚠️ Save your keys first (fill in the key fields and a password, then 💾 Save keys)."); + return false; + } + if (!v.unlocked) { + setMsg("⚠️ The keys are locked. Reload the app and unlock it with your password."); + return false; + } + setMsg("⏳ Testing…"); + try { + await testConnection(); + setMsg("✅ Connected"); + return true; + } catch (e) { + const m = (e as Error)?.message || String(e); + setMsg("❌ " + m + corsHint(m)); + return false; + } + }; + + /** Setup primary action: validate, test with the form keys, then encrypt and save. */ + const saveAndContinue = async () => { + setBusy(true); + try { + const bucketErr = validateBucket(); + if (bucketErr) { + setMsg(bucketErr); + return; + } + const keyErr = validateKeys(); + if (keyErr) { + setMsg(keyErr); + return; + } + setMsg("⏳ Testing…"); + try { + const client = new S3(s.s3, { accessKeyId: keyId.trim(), secretAccessKey: secret.trim() }); + await client.list(`${client.prefix}meta/`); + } catch (e) { + const m = (e as Error)?.message || String(e); + setMsg("❌ " + m + corsHint(m)); + return; + } + setMsg("⏳ Encrypting and saving…"); + try { + await saveKeys({ accessKeyId: keyId, secretAccessKey: secret }, pw); + setKeyId(""); + setSecret(""); + setPw(""); + setPw2(""); + setMsg("✅ Connected"); + onReady?.(); + } catch (e) { + setMsg("❌ Could not save the keys: " + ((e as Error)?.message || String(e))); + } + } finally { + setBusy(false); + } + }; + + const fields = ( + <> +
+ + set("endpoint", e.target.value)} + /> +
+
+ + set("bucket", e.target.value)} /> +
+
+ + set("region", e.target.value)} + /> +
+
+ + set("prefix", e.target.value)} + /> +
+
+ + set("pathStyle", e.target.checked)} + /> +
+

+ 🔑 Keys{" "} + {v.hasVault && ( + + saved {v.keyIdHint} · {v.unlocked ? "🔓 unlocked" : "🔒 locked"} + + )} +

+
+ + setKeyId(e.target.value)} + /> +
+
+ + setSecret(e.target.value)} + /> +
+
+ + setPw(e.target.value)} + /> +
+
+ + setPw2(e.target.value)} + /> +
+
+ {setup ? ( + + ) : ( + <> + + + {v.unlocked && ( + + )} + {v.hasVault && ( + + )} + + )} +
+ {msg && ( +

+ {msg} +

+ )} + + ); + + if (setup) return fields; + + return ( +
+

☁️ Storage (S3-compatible)

+ {fields} + {help && ( +
+ ℹ️ More info +
{help}
+
+ )} +
+ ); +} diff --git a/src/lib/catalog.ts b/src/lib/catalog.ts index 27cf05f..4a3e5bb 100644 --- a/src/lib/catalog.ts +++ b/src/lib/catalog.ts @@ -40,13 +40,10 @@ export const OCR_ENGINES: OcrEngine[] = [ export const OCR_BY_KEY = Object.fromEntries(OCR_ENGINES.map((m) => [m.key, m])) as Record; -export interface LlmModel { +type LlmCommon = { key: string; name: string; emoji: string; - /** WebLLM prebuilt model_id (q4f16_1); `f32` is the fallback for GPUs without shader-f16. */ - id: string; - f32?: string; approx: string; bytes: number; ram: string; @@ -54,16 +51,44 @@ export interface LlmModel { phoneRisk?: boolean; desktopOnly?: boolean; note: string; -} +}; + +/** WebLLM (Qwen) or transformers.js (Granite Nano) — both run on-device for filing-card fields. */ +export type LlmModel = LlmCommon & ( + | { + runtime: "webllm"; + /** WebLLM prebuilt model_id (q4f16_1); `f32` is the fallback for GPUs without shader-f16. */ + id: string; + f32?: string; + } + | { + runtime: "transformers"; + /** Hugging Face / onnx-community repo id for transformers.js text-generation. */ + hf: string; + dtype: "q4f16" | "q4" | "fp16"; + } +); -export const DEFAULT_LLM = "qwen25-1.5b"; +export const DEFAULT_LLM = "granite-350m"; /** After a crash while generating, the app switches every metadata field to this model. */ -export const SAFE_LLM = "qwen25-0.5b"; +export const SAFE_LLM = "granite-350m"; export const LLM_MODELS: LlmModel[] = [ - { key: "qwen25-0.5b", name: "Qwen2.5 0.5B", emoji: "🌱", id: "Qwen2.5-0.5B-Instruct-q4f16_1-MLC", f32: "Qwen2.5-0.5B-Instruct-q4f32_1-MLC", approx: "≈ 295 MB", bytes: 295_433_659, ram: "4 GB RAM is enough", note: "Smallest and fastest. The safe choice on phones." }, - { key: "qwen35-0.8b", name: "Qwen3.5 0.8B", emoji: "🆕", id: "Qwen3.5-0.8B-q4f16_1-MLC", f32: "Qwen3.5-0.8B-q4f32_1-MLC", approx: "≈ 454 MB", bytes: 454_367_158, ram: "4–6 GB RAM", note: "Newest small Qwen, multilingual. Small download." }, - { key: "qwen25-1.5b", name: "Qwen2.5 1.5B", emoji: "✨", id: "Qwen2.5-1.5B-Instruct-q4f16_1-MLC", f32: "Qwen2.5-1.5B-Instruct-q4f32_1-MLC", approx: "≈ 887 MB", bytes: 886_511_609, ram: "6 GB RAM recommended", badge: "⭐ Default", note: "A good everyday choice. Downloads from the model host on first use (q4f16; q4f32 still downloads if the GPU needs it)." }, + { + key: "granite-350m", name: "Granite 4.0 350M", emoji: "🪨", runtime: "transformers", + hf: "onnx-community/granite-4.0-350m-ONNX-web", dtype: "q4f16", + approx: "≈ 334 MB", bytes: 350_484_597, ram: "4 GB RAM is enough", badge: "⭐ Default · Apache-2.0", + note: "IBM Granite Nano via transformers.js (WebGPU, WASM fallback). Strong instruction following for a tiny download; good on phones.", + }, + { + key: "granite-1b", name: "Granite 4.0 1B", emoji: "🏔️", runtime: "transformers", + hf: "onnx-community/granite-4.0-1b-ONNX-web", dtype: "q4f16", + approx: "≈ 1.2 GB", bytes: 1_247_480_087, ram: "8 GB RAM recommended", phoneRisk: true, + note: "Larger Granite Nano instruct model. Better at following tight title/from/date/label prompts; heavier download.", + }, + { key: "qwen25-0.5b", name: "Qwen2.5 0.5B", emoji: "🌱", runtime: "webllm", id: "Qwen2.5-0.5B-Instruct-q4f16_1-MLC", f32: "Qwen2.5-0.5B-Instruct-q4f32_1-MLC", approx: "≈ 295 MB", bytes: 295_433_659, ram: "4 GB RAM is enough", note: "Smallest Qwen via WebLLM. Needs WebGPU." }, + { key: "qwen35-0.8b", name: "Qwen3.5 0.8B", emoji: "🆕", runtime: "webllm", id: "Qwen3.5-0.8B-q4f16_1-MLC", f32: "Qwen3.5-0.8B-q4f32_1-MLC", approx: "≈ 454 MB", bytes: 454_367_158, ram: "4–6 GB RAM", note: "Newest small Qwen via WebLLM, multilingual. Needs WebGPU." }, + { key: "qwen25-1.5b", name: "Qwen2.5 1.5B", emoji: "✨", runtime: "webllm", id: "Qwen2.5-1.5B-Instruct-q4f16_1-MLC", f32: "Qwen2.5-1.5B-Instruct-q4f32_1-MLC", approx: "≈ 887 MB", bytes: 886_511_609, ram: "6 GB RAM recommended", note: "Everyday Qwen via WebLLM (q4f16; q4f32 if the GPU needs it). Needs WebGPU." }, ]; export const LLM_BY_KEY = Object.fromEntries(LLM_MODELS.map((m) => [m.key, m])) as Record; diff --git a/src/meta/gen.worker.ts b/src/meta/gen.worker.ts new file mode 100644 index 0000000..3f1e0d6 --- /dev/null +++ b/src/meta/gen.worker.ts @@ -0,0 +1,137 @@ +/* 🧾 Metadata text-generation with transformers.js (Granite Nano ONNX-web). + Messages: {id,type:"init",hf,dtype,device,remoteHost} → {id,result:{ok}}; + {id,type:"generate",messages,max_new_tokens,temperature,top_p} → {id,result:string}; + {id,type:"dispose"}. */ +import { env, pipeline, type TextGenerationPipeline } from "@huggingface/transformers"; + +let gen: TextGenerationPipeline | null = null; +let cur = ""; + +/** Drop Cache Storage entries for this model that are HTML (SPA shell). */ +async function purgeHtmlModelCache(hf: string) { + if (!("caches" in self)) return; + for (const name of await caches.keys()) { + if (!/transformers/i.test(name)) continue; + const cache = await caches.open(name); + for (const req of await cache.keys()) { + if (!req.url.includes(hf)) continue; + const res = await cache.match(req); + if (!res) continue; + const ct = res.headers.get("content-type") || ""; + if (/html/i.test(ct)) { + await cache.delete(req); + continue; + } + try { + const head = (await res.clone().text()).slice(0, 64); + if (/^\s* { + const host = remoteHost.replace(/\/+$/, "") + "/"; + const base = onnxBase(dtype); + const url = (name: string) => `${host}${hf}/resolve/main/onnx/${name}`; + const ok = async (name: string) => { + try { + const r = await fetch(url(name), { method: "HEAD", cache: "no-store" }); + if (r.ok) return true; + const g = await fetch(url(name), { method: "GET", headers: { Range: "bytes=0-0" }, cache: "no-store" }); + return g.ok || g.status === 206; + } catch { + return false; + } + }; + if (!(await ok(`${base}.onnx_data`))) return 0; + let n = 1; + while (n < 64 && (await ok(`${base}.onnx_data_${n}`))) n++; + return n; +} + +async function loadPipeline(hf: string, dtype: string, device: string, remoteHost: string | undefined, id: unknown) { + env.allowLocalModels = false; + env.useBrowserCache = true; + if (remoteHost) env.remoteHost = String(remoteHost).replace(/\/+$/, "") + "/"; + else env.remoteHost = "https://huggingface.co/"; + if (gen) { await gen.dispose(); gen = null; } + const chunks = await countExternalDataChunks(hf, dtype, env.remoteHost); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const make = pipeline as unknown as (task: string, model: string, opts: Record) => Promise; + return (await make("text-generation", hf, { + dtype, + device, + ...(chunks > 0 ? { use_external_data_format: chunks } : {}), + progress_callback: (p: { status?: string; loaded?: number; total?: number; file?: string }) => { + if (p.status === "progress") self.postMessage({ id, progress: { kind: "download", file: p.file, loaded: p.loaded, total: p.total } }); + }, + })) as TextGenerationPipeline; +} + +function replyText(out: unknown): string { + const first = Array.isArray(out) ? out[0] : out; + const gt = (first as { generated_text?: unknown })?.generated_text; + if (typeof gt === "string") return gt; + if (Array.isArray(gt) && gt.length) { + const last = gt[gt.length - 1] as { content?: unknown }; + if (typeof last?.content === "string") return last.content; + } + return String(gt ?? ""); +} + +self.onmessage = async (ev: MessageEvent) => { + const m = ev.data || {}; + const id = m.id; + try { + if (m.type === "init") { + const key = [m.hf, m.dtype, m.device, m.remoteHost || ""].join("|"); + if (!gen || cur !== key) { + await purgeHtmlModelCache(String(m.hf)); + try { + gen = await loadPipeline(String(m.hf), String(m.dtype || "q4f16"), String(m.device || "webgpu"), m.remoteHost, id); + } catch (e) { + const msg = String((e as Error)?.message || e); + if (/ 0, + temperature: temperature > 0 ? temperature : undefined, + top_p: temperature > 0 ? Number(m.top_p) || 0.9 : undefined, + }); + self.postMessage({ id, result: replyText(out) }); + } else if (m.type === "dispose") { + if (gen) { await gen.dispose(); gen = null; cur = ""; } + self.postMessage({ id, result: { ok: true } }); + } + } catch (e) { + self.postMessage({ id, error: { name: (e as Error)?.name || "Error", message: String((e as Error)?.message || e) } }); + } +}; diff --git a/src/meta/llm.ts b/src/meta/llm.ts index eebf49a..a1c30fd 100644 --- a/src/meta/llm.ts +++ b/src/meta/llm.ts @@ -1,8 +1,10 @@ -/* 🧾 Metadata extraction with WebLLM. One model per field (📝 Title, 📨 From, 📅 Date, 🏷️ Labels), the same on every +/* 🧾 Metadata extraction. One model per field (📝 Title, 📨 From, 📅 Date, 🏷️ Labels), the same on every device. Only one model is in memory at a time: switching fields to a different model unloads the previous one, - and OCR / search models are unloaded first (see lib/hub.ts). Model files download from Hugging Face (or your - configured mirror) into WebLLM's Cache Storage (meta/llmcache.ts) — never from the document bucket, and - downloading never puts the model on the GPU. */ + and OCR / search models are unloaded first (see lib/hub.ts). + + Runtimes: + - webllm (Qwen): MLC builds into WebLLM Cache Storage (meta/llmcache.ts) + - transformers (Granite Nano): ONNX-web via transformers.js (same cache family as search) */ import { CreateWebWorkerMLCEngine, hasModelInCache, prebuiltAppConfig, type AppConfig, type ModelRecord, type WebWorkerMLCEngine } from "@mlc-ai/web-llm"; import { LLM_BY_KEY, type LlmModel } from "../lib/catalog"; import { hub } from "../lib/hub"; @@ -19,14 +21,14 @@ const OVERRIDES: Record> = { "qwen35-0.8b": { conv_config: { stop_token_ids: [248046, 248044] } } as never, }; -async function pickId(m: LlmModel): Promise { +async function pickWebllmId(m: Extract): Promise { const g = await probeGpu(); if (!g.webgpu) throw new Error("This device has no WebGPU, so the metadata models cannot run here (" + (g.why || "") + ")"); return !g.f16 && m.f32 ? m.f32 : m.id; } /** WebLLM's own record for the model, with download URLs moved to the configured model host / libs URL. */ -export function appConfigFor(m: LlmModel, id: string): AppConfig { +export function appConfigFor(m: Extract, id: string): AppConfig { const base = prebuiltAppConfig.model_list.find((r) => r.model_id === id); if (!base) throw new Error("WebLLM has no prebuilt record for " + id); const { huggingFace, webllmLibs } = getSettings().sources; @@ -41,20 +43,28 @@ export function appConfigFor(m: LlmModel, id: string): AppConfig { }; } +type Runtime = "webllm" | "transformers"; +let runtime: Runtime | null = null; let engine: WebWorkerMLCEngine | null = null; let worker: Worker | null = null; let loadedKey = ""; let idleT: ReturnType | undefined; let chain: Promise = Promise.resolve(); let abortLoad: ((e: Error) => void) | null = null; +let tfSeq = 0; +let tfBytes = 0; +const tfPending = new Map void; reject: (e: Error) => void; dl?: string; files?: Map }>(); const within = (p: Promise, ms: number) => Promise.race([p, new Promise((r) => setTimeout(r, ms))]); async function unload() { clearTimeout(idleT); - const e = engine, w = worker; - engine = null; worker = null; loadedKey = ""; + const e = engine, w = worker, rt = runtime; + engine = null; worker = null; loadedKey = ""; runtime = null; abortLoad?.(new Error("the metadata model was unloaded while loading")); abortLoad = null; - // a busy or broken worker may never answer unload(): never wait more than a moment, then end it anyway + if (rt === "transformers") { + for (const p of tfPending.values()) { if (p.dl) hub.downloadDone(p.dl); p.reject(new Error("metadata model unloaded")); } + tfPending.clear(); + } try { await within(e?.unload() ?? Promise.resolve(), 3000); } catch { /* ignore */ } try { w?.terminate(); } catch { /* ignore */ } hub.setUnloaded("meta"); @@ -69,31 +79,110 @@ function fillCache(id: string, cfg: AppConfig, name: string): Promise { } hub.register("meta", unload); -async function load(key: string): Promise { - if (engine && loadedKey === key) return engine; - const m = LLM_BY_KEY[key]; - if (!m) throw new Error("unknown model " + key); - if (isPhone() && m.desktopOnly) throw new Error(m.name + " is too big for a phone. Pick a smaller model in ⚙️ Settings → 🧾 Metadata."); - if (engine) await unload(); +function failTf(msg: string) { + try { worker?.terminate(); } catch { /* ignore */ } + worker = null; loadedKey = ""; runtime = null; + for (const p of tfPending.values()) { if (p.dl) hub.downloadDone(p.dl); p.reject(new Error(msg)); } + tfPending.clear(); + hub.setUnloaded("meta"); +} + +function tfCall(msg: Record, dl?: { id: string; name: string }): Promise { + if (!worker || runtime !== "transformers") throw new Error("metadata transformers worker not ready"); + const id = ++tfSeq; + return new Promise((resolve, reject) => { + tfPending.set(id, { resolve: resolve as (v: unknown) => void, reject, dl: dl?.id }); + worker!.postMessage({ id, ...msg }); + }); +} + +function ensureTfWorker() { + if (worker && runtime === "transformers") return; + const w = new Worker(new URL("./gen.worker.ts", import.meta.url), { type: "module" }); + worker = w; + runtime = "transformers"; + w.onmessage = (ev) => { + const m = ev.data || {}; + const p = tfPending.get(m.id); + if (!p) return; + if (m.progress) { + if (p.dl && m.progress.loaded != null) { + const f = (p.files ||= new Map()); + f.set(String(m.progress.file || ""), Number(m.progress.loaded) || 0); + let l = 0; for (const v of f.values()) l += v; + const t = Math.max(tfBytes, Number(m.progress.total) || 0, l + 1); + hub.downloadProgress(p.dl, LLM_BY_KEY[loadedKey]?.name || "metadata model", l, t); + } + return; + } + tfPending.delete(m.id); + if (p.dl) hub.downloadDone(p.dl); + if (m.error) p.reject(new Error(m.error.message)); + else p.resolve(m.result); + }; + w.onerror = (ev) => { ev.preventDefault?.(); failTf("The metadata model stopped (" + (ev.message || "worker error, maybe out of memory") + ")."); }; + w.onmessageerror = () => failTf("The metadata model sent a message that could not be read."); +} + +async function loadTransformers(m: Extract): Promise { + if (runtime === "transformers" && loadedKey === m.key && worker) return; + if (engine || worker) await unload(); await hub.makeRoom("meta"); - const id = await pickId(m); + const g = await probeGpu(); + const device = g.webgpu ? "webgpu" : "wasm"; + hub.setLoaded("meta", m.key, m.name, "loading"); + loadedKey = m.key; // so progress can resolve the name + tfBytes = m.bytes; + ensureTfWorker(); + try { + const remoteHost = getSettings().sources.huggingFace; + if (typeof caches !== "undefined") { + for (const name of await caches.keys()) { + if (!/transformers/i.test(name)) continue; + const c = await caches.open(name); + for (const req of await c.keys()) { + if (!req.url.includes(m.hf)) continue; + const res = await c.match(req); + if (!res) continue; + const ct = res.headers.get("content-type") || ""; + if (/html/i.test(ct)) { await c.delete(req); continue; } + try { + if (/^\s*): Promise { + if (runtime === "webllm" && engine && loadedKey === m.key) return engine; + if (engine || worker) await unload(); + await hub.makeRoom("meta"); + const id = await pickWebllmId(m); const cfg = appConfigFor(m, id); let cached = await hasModelInCache(id, cfg).catch(() => false); if (!cached) { - // download first (bucket, else Hugging Face) with real progress; WebLLM then only reads its cache try { await fillCache(id, cfg, m.name); cached = true; } catch (e) { console.warn("model download, letting WebLLM fetch it:", e); } } - const dlId = "llm-load-" + key; - hub.setLoaded("meta", key, m.name, "loading"); + const dlId = "llm-load-" + m.key; + hub.setLoaded("meta", m.key, m.name, "loading"); const w = new Worker(new URL("./llm.worker.ts", import.meta.url), { type: "module" }); worker = w; + runtime = "webllm"; try { const aborted = new Promise((_, rej) => { abortLoad = rej; }); w.onerror = (ev) => abortLoad?.(new Error("The metadata model stopped (" + (ev.message || "worker error, maybe out of memory") + ").")); engine = await Promise.race([CreateWebWorkerMLCEngine(w, id, { appConfig: cfg, initProgressCallback: (r) => { - // "Fetching param cache[3/29]: 120MB fetched…" = downloading; "Loading model from cache[…]" = into memory if (!cached && r.progress < 1 && /fetch|download/i.test(r.text)) hub.downloadProgress(dlId, m.name, Math.round(r.progress * 1000), 1000); else hub.downloadDone(dlId); }, @@ -106,11 +195,23 @@ async function load(key: string): Promise { throw e; } hub.downloadDone(dlId); - loadedKey = key; - hub.setLoaded("meta", key, m.name, "ready"); + loadedKey = m.key; + hub.setLoaded("meta", m.key, m.name, "ready"); return engine; } +async function load(key: string): Promise { + const m = LLM_BY_KEY[key]; + if (!m) throw new Error("unknown model " + key); + if (isPhone() && m.desktopOnly) throw new Error(m.name + " is too big for a phone. Pick a smaller model in ⚙️ Settings → 🧾 Metadata."); + if (m.runtime === "transformers") { + await loadTransformers(m); + return m; + } + await loadWebllm(m); + return m; +} + export interface FieldResult { title?: string; sender?: string; @@ -119,13 +220,35 @@ export interface FieldResult { model: string; } +async function complete(m: LlmModel, field: MetaField, messages: { role: "user"; content: string }[], temp: number): Promise { + if (m.runtime === "transformers") { + return await tfCall({ + type: "generate", + messages, + max_new_tokens: maxTokensFor(field), + temperature: temp, + top_p: temp > 0 ? 0.9 : 1, + }); + } + const eng = engine; + if (!eng) throw new Error("metadata model not loaded"); + const r = await eng.chat.completions.create({ + messages, + temperature: temp, + top_p: temp > 0 ? 0.9 : 1, + max_tokens: maxTokensFor(field), + ...( /qwen3/i.test(m.key) ? { extra_body: { enable_thinking: false } } : {}), + }); + return r.choices[0]?.message?.content || ""; +} + /** Generate one field from THIS document's first N pages. Runs one at a time. */ export function generateField(field: MetaField, pages: string[], avoid?: string[]): Promise { const job = chain.then(async () => { clearTimeout(idleT); const s = getSettings(); const key = s.metaModels[field]; - const eng = await load(key); + const m = await load(key); const metaPages = pages.slice(0, s.metaPages); const text = rawText(metaPages, metaCharBudget()); const recipients = s.recipientNames.split(/[,;\n]/).map((x) => x.trim()).filter(Boolean); @@ -133,26 +256,18 @@ export function generateField(field: MetaField, pages: string[], avoid?: string[ setGenerating(true, key); let out = ""; try { - // like the original app (fitRun): when the prompt does not fit the context window — the 🏷️ labels prompt also - // lists every label, so it is the longest — try again with 60 %, then 35 % of the document text + // when the prompt does not fit the context window — the 🏷️ labels prompt also lists every label — + // try again with 60 %, then 35 % of the document text for (let i = 0; ; i++) { const t = i === 0 ? text : text.slice(0, Math.floor(text.length * (i === 1 ? 0.6 : 0.35))); const messages = messagesFor(field, { prompt: promptFor(field), pages: metaPages, text: t, labels: s.labels, recipients, avoid }); try { - // Qwen3 / 3.5 think by default; with a tiny max_tokens budget the answer is empty after . - const r = await eng.chat.completions.create({ - messages, - temperature: temp, - top_p: temp > 0 ? 0.9 : 1, - max_tokens: maxTokensFor(field), - ...( /qwen3/i.test(key) ? { extra_body: { enable_thinking: false } } : {}), - }); - out = r.choices[0]?.message?.content || ""; + out = await complete(m, field, messages, temp); if (s.debug) console.debug("[meta]", field, key, JSON.stringify(out).slice(0, 240)); break; } catch (e) { if (i >= 2 || !/context window|ContextWindowSizeExceeded|prompt tokens/i.test(String((e as Error)?.message || e))) throw e; - try { await within(eng.resetChat(), 3000); } catch { /* ignore */ } + try { await within(engine?.resetChat() ?? Promise.resolve(), 3000); } catch { /* ignore */ } } } } catch (e) { @@ -174,24 +289,41 @@ export function generateField(field: MetaField, pages: string[], avoid?: string[ return job; } +async function transformersCached(m: Extract): Promise { + if (!("caches" in self)) return false; + try { + const keys = await caches.open("transformers-cache").then((c) => c.keys()); + return keys.some((r) => r.url.includes(m.hf) && /\.onnx(_data)?(_\d+)?$/.test(r.url)); + } catch { + return false; + } +} + /** For the 🧠 Models card: is this metadata model already on the device? */ export async function llmCached(key: string): Promise { const m = LLM_BY_KEY[key]; if (!m) return false; + if (m.runtime === "transformers") return transformersCached(m); try { - const id = await pickId(m); + const id = await pickWebllmId(m); return await hasModelInCache(id, appConfigFor(m, id)); } catch { return false; } } -/** Download a metadata model ahead of time — files only, straight into the cache; nothing is loaded onto the GPU. */ +/** Download a metadata model ahead of time — files only into cache when possible; transformers warms via init. */ export async function prefetchLlm(key: string): Promise { const m = LLM_BY_KEY[key]; if (!m) return; if (isPhone() && m.desktopOnly) return; - const id = await pickId(m); + if (m.runtime === "transformers") { + if (await transformersCached(m)) return; + await loadTransformers(m); + await unload(); + return; + } + const id = await pickWebllmId(m); const cfg = appConfigFor(m, id); if (await hasModelInCache(id, cfg).catch(() => false)) return; await fillCache(id, cfg, m.name);