+ Searching document text · {progress.done} / {progress.total} pages
+
}
{context && (
p. {context.page}: “{context.text.length > 90 ? context.text.slice(0, 90) + "…" : context.text}”
@@ -474,6 +460,7 @@ export function AiPanel({ pdf, docId, persist, docName, context, onClearContext,
ref={inputRef}
value={input}
rows={2}
+ maxLength={MAX_QUESTION}
disabled={!ready}
placeholder={placeholder}
onChange={(e) => setInput(e.target.value)}
diff --git a/src/App.tsx b/src/App.tsx
index c3829eb..cce0ea2 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -23,7 +23,7 @@ import { Icon, type IconName } from "./icons";
import { Welcome } from "./Welcome";
import { Sidebar, type SidebarTab } from "./Sidebar";
import { MarkupController, type Mark, type MarkupState } from "./markup";
-import { HighlightMenu, NoteBox, SelectionPopover, useTextSelection, type SelectionInfo } from "./Selection";
+import { HighlightMenu, NoteBox, selectedPages, SelectionPopover, useTextSelection, type SelectionInfo } from "./Selection";
import { NotesPanel } from "./NotesPanel";
import { notesJson, notesMarkdown } from "./noteExport";
import { copyText } from "./clipboard";
@@ -111,6 +111,7 @@ interface OpenDoc {
/** Original library entry while content edits are held in memory. */
sourceId?: string;
historyAllowed: boolean;
+ encrypted: boolean;
edits?: { original?: Blob; changes: PdfChange[] };
}
@@ -511,8 +512,9 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
const id = await contentKey(data);
signal.throwIfAborted();
const existing = revision ? undefined : await getRecent(id);
- const historyAllowed = !password && data.byteLength <= MAX_RECENT_FILE_BYTES && (revision ? revision.historyAllowed :
- await pdf.getMetadata().then(({ info }) => !(info as { EncryptFilterName?: string }).EncryptFilterName).catch(() => false));
+ const encrypted = !!password || await pdf.getMetadata()
+ .then(({ info }) => !!(info as { EncryptFilterName?: string }).EncryptFilterName).catch(() => true);
+ const historyAllowed = !encrypted && data.byteLength <= MAX_RECENT_FILE_BYTES && (revision?.historyAllowed ?? true);
const edits = edit && { original: edit.doc.edits?.original ?? (historyAllowed ? pdfBlob(await edit.doc.pdf.getData()) : undefined),
changes: [...changesForCopy(edit.doc, edit.doc.pdf.annotationStorage.size > 0), edit.change] };
signal.throwIfAborted();
@@ -548,7 +550,7 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
}
persistRef.current = !password && !revision;
const markupReady = markupRef.current!.load(id, persistRef.current, reading);
- const next: OpenDoc = { id, name, size: data.byteLength, pdf, password, markupReady, sourceId: revision?.sourceId ?? revision?.id, historyAllowed, edits };
+ const next: OpenDoc = { id, name, size: data.byteLength, pdf, password, encrypted, markupReady, sourceId: revision?.sourceId ?? revision?.id, historyAllowed, edits };
docRef.current = next;
setNoteBox(null);
setPinned(null);
@@ -958,8 +960,8 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
flash("Highlight removed");
};
- const askAbout = (text: string, pageNumber: number) => {
- setAiContext({ text, page: pageNumber });
+ const askAbout = (text: string, pageNumber: number, passages?: AiContext["passages"]) => {
+ setAiContext({ text, page: passages?.[0]?.page ?? pageNumber, passages });
setAiOpen(true);
setHistoryOpen(false);
document.getSelection()?.removeAllRanges();
@@ -1729,7 +1731,11 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
colors={HIGHLIGHTS}
current={highlightColor}
onHighlight={(hex, note) => void quickHighlight(hex, note)}
- onAsk={() => { setPinned(null); askAbout(selection.text, selection.page); }}
+ onAsk={() => {
+ const passages = container && selectedPages(selection.range, container);
+ setPinned(null);
+ askAbout(selection.text, selection.page, passages?.length ? passages : undefined);
+ }}
onPin={() => setPinned(selection)}
onDismiss={dismissSelection}
/>
@@ -1787,12 +1793,13 @@ export default function App({ tabs, tabKey, upgradeNotes }: { tabs: DocumentTabs
onOpen={(v, blob) => tabs.open([{ kind: "blob", name: v.name, blob }])}
onDownload={(v, blob) => saveBlob(blob, v.name.replace(/\.pdf$/i, "") + ` (v${v.number}).pdf`)}
onClose={() => setHistoryOpen(false)} />}
- {doc && aiOpen && !focus && (
+ {doc && active && aiOpen && !focus && (
setAiContext(null)}
diff --git a/src/Selection.test.ts b/src/Selection.test.ts
new file mode 100644
index 0000000..a6e30e7
--- /dev/null
+++ b/src/Selection.test.ts
@@ -0,0 +1,15 @@
+// @vitest-environment jsdom
+import { expect, it } from "vitest";
+import { selectedPages } from "./Selection";
+
+it("maps a cross-page range to the selected fragment on each physical page", () => {
+ const viewer = document.createElement("div");
+ viewer.innerHTML = ''
+ + ''
+ + '';
+ const [first, second] = viewer.querySelectorAll("span");
+ const range = document.createRange();
+ range.setStart(first.firstChild!, 5);
+ range.setEnd(second.firstChild!, 3);
+ expect(selectedPages(range, viewer)).toEqual([{ page: 7, text: "start" }, { page: 8, text: "end" }]);
+});
diff --git a/src/Selection.tsx b/src/Selection.tsx
index dde154a..5bc4e4d 100644
--- a/src/Selection.tsx
+++ b/src/Selection.tsx
@@ -17,6 +17,21 @@ export interface SelectionInfo {
const POPOVER_H = 86;
+/** Clip the selection to each rendered text layer so Ask AI can cite the correct page. */
+export function selectedPages(range: Range, container: HTMLElement) {
+ return Array.from(container.querySelectorAll(".page[data-page-number] .textLayer")).flatMap(layer => {
+ if (!range.intersectsNode(layer)) return [];
+ const page = Number(layer.closest(".page")?.dataset.pageNumber);
+ if (!Number.isSafeInteger(page) || page < 1) return [];
+ const clipped = document.createRange();
+ clipped.selectNodeContents(layer);
+ if (layer.contains(range.startContainer)) clipped.setStart(range.startContainer, range.startOffset);
+ if (layer.contains(range.endContainer)) clipped.setEnd(range.endContainer, range.endOffset);
+ const text = clipped.toString().replace(/\s+/gu, " ").trim();
+ return text ? [{ page, text }] : [];
+ });
+}
+
/** Tracks the reader's text selection inside the document (hidden while the mouse is still dragging). */
export function useTextSelection(container: HTMLElement | null, enabled: boolean, pdf: PDFDocumentProxy | undefined) {
const [info, setInfo] = useState<(SelectionInfo & { pdf: PDFDocumentProxy }) | null>(null);
diff --git a/src/desktop.d.ts b/src/desktop.d.ts
index fdf7dca..3eb50d6 100644
--- a/src/desktop.d.ts
+++ b/src/desktop.d.ts
@@ -61,7 +61,6 @@ interface AiStatus {
interface AiMessage {
role: "user" | "assistant";
content: string;
- context?: { text: string; page: number };
}
interface AiEvent {
@@ -87,7 +86,7 @@ interface FolioAi {
geminiModels(): Promise<{ ok: boolean; models?: OpenRouterModel[]; error?: string }>;
customEndpoint(action: "save" | "check" | "remove", input?: { baseUrl: string; key: string }): Promise<{ ok: boolean; status?: CustomEndpointStatus; error?: string }>;
customModels(): Promise<{ ok: boolean; models?: OpenRouterModel[]; error?: string }>;
- ask(request: { id: string; provider: "chatgpt" | "claude" | "agy" | "gemini" | "openrouter" | "custom"; model: string; document: { name: string; text: string; truncated: boolean; recognized: boolean };
+ ask(request: { id: string; provider: "chatgpt" | "claude" | "agy" | "gemini" | "openrouter" | "custom"; model: string; document: import("./lib/ai-context/planner").EvidenceDocument;
messages: AiMessage[] }): Promise;
cancel(id: string): Promise;
onEvent(callback: (event: AiEvent) => void): () => void;
diff --git a/src/lib/ai-context/context.test.ts b/src/lib/ai-context/context.test.ts
new file mode 100644
index 0000000..6532777
--- /dev/null
+++ b/src/lib/ai-context/context.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, it, vi } from "vitest";
+import type { PDFDocumentProxy } from "../../pdf";
+import { OcrSession } from "../ocr/session/OcrSession";
+import { prepareDocument } from "./document";
+import { extractPage, MAX_PAGE_CHARS } from "./extraction";
+import { passages } from "./passages";
+import { estimatedTokens, planContext } from "./planner";
+import { PassageIndex } from "./search";
+
+const signal = () => new AbortController().signal;
+type Item = { str: string; hasEOL?: boolean; transform?: number[] };
+const line = (str: string) => ({ str, hasEOL: true });
+
+function fixture(pages: (string | Item[] | Error)[]) {
+ const getPage = vi.fn(async (page: number) => {
+ const value = pages[page - 1];
+ if (value instanceof Error) throw value;
+ const items = typeof value === "string" ? [line(value)] : value;
+ return { streamTextContent: () => new ReadableStream({ start(controller) {
+ controller.enqueue({ items });
+ controller.close();
+ } }) };
+ });
+ return { pdf: { numPages: pages.length, getPage } as unknown as PDFDocumentProxy, getPage };
+}
+
+const noProgress = () => {};
+const plan = (pdf: PDFDocumentProxy, question: string, options: Partial[0]> = {}) =>
+ planContext({ pdf, question, name: "Fixture.pdf", provider: "custom", history: [], signal: signal(), progress: noProgress, ...options });
+
+describe("structured extraction and lifecycle", () => {
+ it("keeps lines, logical RTL order and native text while merging recognized lines", async () => {
+ const { pdf } = fixture([[line("A header"), line("السلام عليكم"), line("漢字と数式 𝛑")], []]);
+ const session = new OcrSession(pdf, null);
+ session.record(1, [line("A HEADER"), line("A result from the scanned image.")]);
+ const result = await extractPage(pdf, 1, signal(), session);
+ expect(result).toEqual({
+ text: "A header\nالسلام عليكم\n漢字と数式 𝛑\n\nA result from the scanned image.",
+ ocrOffset: "A header\nالسلام عليكم\n漢字と数式 𝛑\n\n".length,
+ incomplete: false,
+ });
+ expect(await extractPage(pdf, 2, signal(), session)).toEqual({ text: "", incomplete: false });
+ session.embedded.add(1);
+ expect(await extractPage(pdf, 1, signal(), session)).toMatchObject({ ocrOffset: 0 });
+ });
+
+ it("uses horizontal PDF geometry when explicit line breaks are missing", async () => {
+ const { pdf } = fixture([[
+ { str: "Table", transform: [10, 0, 0, 10, 10, 400] },
+ { str: "Header", transform: [10, 0, 0, 10, 65, 400] },
+ { str: "100", transform: [10, 0, 0, 10, 10, 388] },
+ { str: "Next column", transform: [10, 0, 0, 10, 250, 440] },
+ ]]);
+ expect((await extractPage(pdf, 1, signal())).text).toBe("Table Header\n100\n\nNext column");
+ });
+
+ it("reports failed and capped pages, retries failures, and leaves other pages usable", async () => {
+ const pages = [new Error("unreadable"), "台".repeat(MAX_PAGE_CHARS + 2), "Library catalogue"];
+ const { pdf } = fixture(pages);
+ expect(await prepareDocument(pdf, signal(), noProgress)).toMatchObject({ readable: 2, partial: true });
+ pages[0] = "Recovered page";
+ const result = await prepareDocument(pdf, signal(), noProgress);
+ expect(result.index.pages.get(1)?.text).toBe("Recovered page");
+ expect(result.index.pages.get(3)?.text).toBe("Library catalogue");
+ expect(result.index.pages.get(2)?.text).toHaveLength(MAX_PAGE_CHARS);
+ });
+
+ it("updates just the changed OCR page, invalidates it on language change, and isolates PDFs", async () => {
+ const { pdf, getPage } = fixture(["Printed header", "Revision notes"]);
+ const session = new OcrSession(pdf, null);
+ await prepareDocument(pdf, signal(), noProgress);
+ session.record(1, [line("satellite authorization")]);
+ const updated = await prepareDocument(pdf, signal(), noProgress);
+ expect((await updated.index.search("satellite", signal())).map(match => match.page)).toEqual([1]);
+ expect(getPage.mock.calls).toEqual([[1], [2], [1]]);
+ const other = await prepareDocument(fixture(["An unrelated PDF"]).pdf, signal(), noProgress);
+ expect(await other.index.search("satellite", signal())).toEqual([]);
+ await session.setLanguages(["deu"]);
+ expect(await updated.index.search("satellite", signal())).toEqual([]);
+ await prepareDocument(pdf, signal(), noProgress);
+ expect(getPage.mock.calls).toEqual([[1], [2], [1], [1]]);
+ });
+
+ it("cancels an active PDF.js stream and never opens the next page", async () => {
+ const controller = new AbortController();
+ let started!: () => void;
+ const ready = new Promise(resolve => { started = resolve; });
+ const cancel = vi.fn();
+ const getPage = vi.fn(async () => ({ streamTextContent: () => new ReadableStream({ start: started, cancel }) }));
+ const pdf = { getPage, numPages: 2 } as unknown as PDFDocumentProxy;
+ const pending = prepareDocument(pdf, controller.signal, noProgress);
+ await ready;
+ controller.abort();
+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(getPage).toHaveBeenCalledOnce();
+ });
+
+ it("refreshes a page when OCR finishes while native extraction is pending", async () => {
+ let started!: () => void, resume!: () => void;
+ const ready = new Promise(resolve => { started = resolve; });
+ const wait = new Promise(resolve => { resume = resolve; });
+ const getPage = vi.fn(async () => {
+ started();
+ await wait;
+ return { streamTextContent: () => new ReadableStream({ start: c => c.close() }) };
+ });
+ const pdf = { getPage, numPages: 1 } as unknown as PDFDocumentProxy;
+ const session = new OcrSession(pdf, null);
+ const pending = prepareDocument(pdf, signal(), noProgress);
+ await ready;
+ session.record(1, [line("recognized while extracting")]);
+ resume();
+ const prepared = await pending;
+ expect(prepared.index.pages.get(1)?.text).toBe("recognized while extracting");
+ expect(getPage).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("chunking and retrieval", () => {
+ it("preserves core text, offsets, and stable IDs with limited overlap", () => {
+ const original = (" Heading\n\n Item 1 53\nItem 2 76\n𝛑 = 3.14.\n").repeat(80);
+ const found = passages(8, original);
+ expect(found.map(p => original.slice(p.coreStart, p.coreEnd)).join("")).toBe(original);
+ expect(found.map(p => p.key)).toEqual(passages(8, original).map(p => p.key));
+ for (const p of found) {
+ expect(p.page).toBe(8);
+ expect(p.text).toBe(original.slice(p.start, p.end));
+ expect(p.text.length).toBeLessThanOrEqual(1941);
+ }
+ expect(passages(9, "\t \n")).toEqual([]);
+ expect(passages(9, "short")).toMatchObject([{ page: 9, start: 0, end: 5, text: "short" }]);
+ });
+
+ it("ranks quoted and multilingual evidence, and removes repeated excerpts", async () => {
+ const index = new PassageIndex();
+ for (const [i, text] of ["Authentication was excluded from retry attempts.", "Authentication retries use a fallback.",
+ "Authentication retries use a fallback.", "京都の国際会議は六月です。", "التعليمات باللغة العربية"].entries()) {
+ index.replace(i + 1, { text, incomplete: false });
+ }
+ expect((await index.search('What do "authentication retries" use?', signal())).map(p => p.page)).toEqual([2, 1]);
+ expect((await index.search("国際会議", signal()))[0].page).toBe(4);
+ expect((await index.search("العربية", signal()))[0].page).toBe(5);
+ });
+
+ it("bounds posting links independently of character count", async () => {
+ const index = new PassageIndex(4);
+ expect(index.replace(1, { text: "first note", incomplete: false })).toBe(true);
+ expect(index.replace(2, { text: "second note", incomplete: false })).toBe(false);
+ expect([...index.pages.keys()]).toEqual([1]);
+ index.replace(1);
+ expect(index.replace(2, { text: "second note", incomplete: false })).toBe(true);
+ expect(await index.search("first", signal())).toEqual([]);
+ });
+
+ it("finds a unique answer past 400,000 characters and reuses the extracted pages", async () => {
+ const { pdf, getPage } = fixture([...Array(150).fill("Routine archival register. ".repeat(110)), "The quasar relay uses shutdown code CEDAR-74."]);
+ const result = await plan(pdf, "What is the quasar relay shutdown code?");
+ expect(result).toMatchObject({ document: { scope: "targeted", evidence: [{ id: "S1", page: 151, text: expect.stringContaining("CEDAR-74") }] } });
+ expect(getPage).toHaveBeenCalledTimes(151);
+ expect(await plan(pdf, "What is the quasar relay shutdown code?")).toEqual(result);
+ expect(getPage).toHaveBeenCalledTimes(151);
+ });
+});
+
+describe("context planning", () => {
+ it.each(["chatgpt", "agy", "gemini", "claude", "openrouter", "custom"] as const)("isolates selected passages for %s", async provider => {
+ const { pdf, getPage } = fixture(["Do not send this", "Selected words"]);
+ const result = await plan(pdf, "Explain this", { provider, selection: { page: 2, text: "Selected words" },
+ history: [{ role: "user", content: "Earlier question" }, { role: "assistant", content: "Do not send this" }] });
+ expect(result).toEqual({ document: { name: "Fixture.pdf", totalPages: 2, coverage: "full",
+ scope: "selection", evidence: [{ id: "S1", page: 2, text: "Selected words", recognized: false }] },
+ messages: [{ role: "user", content: "Explain this" }], notice: undefined });
+ expect(getPage).not.toHaveBeenCalled();
+ });
+
+ it("retains the page of each fragment in a multi-page selection", async () => {
+ const { pdf, getPage } = fixture(["Page one", "Page two", "Page three"]);
+ const selection = { page: 1, text: "end of one start of two", passages: [
+ { page: 1, text: "end of one" }, { page: 2, text: "start of two" },
+ ] };
+ expect(await plan(pdf, "Explain this", { selection })).toMatchObject({
+ document: { scope: "selection", evidence: [{ page: 1, text: "end of one" }, { page: 2, text: "start of two" }] },
+ });
+ expect(getPage).not.toHaveBeenCalled();
+ });
+
+ it("uses full coverage for a small summary and explicit broad sampling for a long summary", async () => {
+ const small = await plan(fixture(["First page", "Last page"]).pdf, "Summarize this document");
+ expect(small).toMatchObject({ document: { scope: "summary", coverage: "full", evidence: [{ page: 1 }, { page: 2 }] } });
+ const { pdf } = fixture(Array.from({ length: 100 }, (_, i) => `Page ${i + 1}: ` + " a sentence for this section.".repeat(90)));
+ const result = await plan(pdf, "Summarize this entire paper");
+ expect(result).toMatchObject({ document: { scope: "summary", coverage: "sampled" }, notice: expect.stringContaining("does not cover every passage") });
+ expect(result.document.evidence[0].page).toBe(1);
+ expect(result.document.evidence.at(-1)?.page).toBe(100);
+ });
+
+ it("bounds long history and rejects oversized selections", async () => {
+ const { pdf } = fixture(["Authentication uses a key."]);
+ const result = await plan(pdf, "How does authentication work?", { history: Array(40).fill({ role: "user", content: "history ".repeat(300) }) });
+ expect(result).toMatchObject({ document: { evidence: [{ page: 1 }] } });
+ expect(estimatedTokens({ document: result.document, messages: result.messages })).toBeLessThanOrEqual(4096 - 900 - 1024);
+ expect(result.messages.length).toBeLessThan(5);
+ await expect(plan(pdf, "Explain", { selection: { text: "界".repeat(10_000), page: 1 } })).rejects.toThrow(/selection won’t fit/);
+ });
+});
diff --git a/src/lib/ai-context/document.ts b/src/lib/ai-context/document.ts
new file mode 100644
index 0000000..2028485
--- /dev/null
+++ b/src/lib/ai-context/document.ts
@@ -0,0 +1,75 @@
+import type { PDFDocumentProxy } from "../../pdf";
+import { ocrSession, type OcrSession } from "../ocr/session/OcrSession";
+import { extractPage } from "./extraction";
+import { PassageIndex, timeSlice } from "./search";
+
+const MAX_PAGES = 10_000;
+const MAX_DOCUMENT_CHARS = 12_000_000;
+const indexes = new WeakMap();
+
+class DocumentIndex {
+ readonly index = new PassageIndex();
+ #limited = new Map();
+ #pending = Promise.resolve();
+
+ constructor(private session?: OcrSession) {
+ session?.onPage(page => {
+ const released = this.index.pages.has(page);
+ this.index.replace(page);
+ this.#limited.delete(page);
+ if (released) {
+ for (const [other, size] of this.#limited) if (size === Infinity) this.#limited.delete(other);
+ }
+ });
+ }
+
+ update(pdf: PDFDocumentProxy, signal: AbortSignal, onProgress: (done: number, total: number) => void) {
+ const job = this.#pending.then(async () => {
+ const session = this.session;
+ const total = Math.min(pdf.numPages, MAX_PAGES);
+ const pause = timeSlice(signal);
+ // A second pass can recover pages invalidated by OCR during indexing.
+ for (let pass = 0; pass < 2; pass++) {
+ const version = session?.version;
+ for (let n = 1; n <= total; n++) {
+ signal.throwIfAborted();
+ const page = n;
+ const ocr = session?.pages.get(page);
+ const knownSize = this.#limited.get(page) ?? 0;
+ if (!this.index.pages.has(page) && this.index.chars + knownSize <= MAX_DOCUMENT_CHARS) {
+ try {
+ const data = await extractPage(pdf, page, signal, session);
+ signal.throwIfAborted();
+ if (ocr === session?.pages.get(page)) {
+ if (this.index.chars + data.text.length > MAX_DOCUMENT_CHARS) this.#limited.set(page, data.text.length);
+ else if (!this.index.replace(page, data)) this.#limited.set(page, Infinity);
+ else this.#limited.delete(page);
+ }
+ } catch (error) {
+ if (signal.aborted) throw error;
+ // An unreadable page stays absent and can be retried on the next question.
+ }
+ }
+ if (pass === 0 && (n % 8 === 0 || n === total)) onProgress(n, total);
+ await pause();
+ }
+ if (version === session?.version) break;
+ }
+ });
+ this.#pending = job.catch(() => {});
+ return job;
+ }
+}
+
+export async function prepareDocument(pdf: PDFDocumentProxy, signal: AbortSignal, progress: (done: number, total: number) => void) {
+ let document = indexes.get(pdf);
+ if (!document) indexes.set(pdf, document = new DocumentIndex(ocrSession(pdf)));
+ await document.update(pdf, signal, progress);
+ signal.throwIfAborted();
+ const index = document.index;
+ const scope = [...index.pages.values()];
+ const total = pdf.numPages;
+ const readable = scope.filter(data => data?.text).length;
+ const partial = scope.length < total || scope.some(data => !data || data.incomplete);
+ return { index, total, readable, partial };
+}
diff --git a/src/lib/ai-context/evidence.ts b/src/lib/ai-context/evidence.ts
new file mode 100644
index 0000000..f8bb478
--- /dev/null
+++ b/src/lib/ai-context/evidence.ts
@@ -0,0 +1,7 @@
+import type { EvidenceReference } from "./planner";
+
+export function evidenceSource(sources: readonly EvidenceReference[], id: string, pages: number) {
+ if (!/^S(?:[1-9]|1\d|2[0-4])$/.test(id)) return undefined;
+ return sources.find(source => source?.id === id && Number.isSafeInteger(source.page)
+ && source.page > 0 && source.page <= pages);
+}
diff --git a/src/lib/ai-context/extraction.ts b/src/lib/ai-context/extraction.ts
new file mode 100644
index 0000000..920a2b9
--- /dev/null
+++ b/src/lib/ai-context/extraction.ts
@@ -0,0 +1,95 @@
+import type { PDFDocumentProxy } from "../../pdf";
+import type { OcrSession } from "../ocr/session/OcrSession";
+
+export const MAX_PAGE_CHARS = 80_000;
+export type PageText = { text: string; ocrOffset?: number; incomplete: boolean };
+
+type TextItem = { str: string; hasEOL?: boolean; transform?: number[]; dir?: string; width?: number };
+const isText = (item: unknown): item is TextItem =>
+ !!item && typeof (item as TextItem).str === "string";
+
+// Keep PDF.js's logical order, including RTL. Geometry only supplies missing breaks in
+// horizontal text. Reordering two columns from positions alone can scramble tables.
+function pageBuilder(limit: number) {
+ let text = "";
+ let incomplete = false;
+ let previous: TextItem | undefined;
+ return {
+ add(items: unknown[]) {
+ for (const item of items) {
+ if (!isText(item) || (!item.str && !item.hasEOL)) continue;
+ const a = previous?.transform, b = item.transform;
+ const horizontal = a && b && Math.abs(a[1]) < 0.01 && Math.abs(b[1]) < 0.01;
+ const height = horizontal ? Math.max(Math.abs(a[3]), Math.abs(b[3]), 1) : 1;
+ const gap = horizontal ? Math.abs(a[5] - b[5]) : 0;
+ const distance = horizontal && previous?.dir === "ltr" && item.dir === "ltr" && typeof previous.width === "number"
+ ? b[4] - a[4] - previous.width : undefined;
+ let breakBefore = "";
+ if (text && !text.endsWith("\n")) {
+ if (gap > height * 1.8 || (distance ?? 0) > height * 4) breakBefore = "\n\n";
+ else if (gap > height * 0.6) breakBefore = "\n";
+ else if (!/\s/u.test(text.at(-1)!) && !/^\s/u.test(item.str) && !(distance !== undefined && Math.abs(distance) < height * 0.1)) breakBefore = " ";
+ }
+ const suffix = item.hasEOL ? "\n" : "";
+ const remaining = limit - text.length;
+ if (breakBefore.length + item.str.length + suffix.length > remaining) {
+ text += breakBefore.slice(0, remaining) + item.str.slice(0, Math.max(0, remaining - breakBefore.length));
+ incomplete = true;
+ return false;
+ }
+ text += breakBefore + item.str + suffix;
+ previous = item;
+ }
+ return true;
+ },
+ finish() {
+ if (incomplete && /[\uD800-\uDBFF]/.test(text.at(-1) ?? "")) text = text.slice(0, -1);
+ return { text: text.replace(/[\t ]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim(), incomplete };
+ },
+ };
+}
+
+const lineKey = (line: string) => line.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
+
+export async function extractPage(pdf: PDFDocumentProxy, pageNumber: number, signal: AbortSignal, session?: OcrSession): Promise {
+ signal.throwIfAborted();
+ const pending = pdf.getPage(pageNumber);
+ const page = await new Promise>((resolve, reject) => {
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) abort();
+ void pending.then(resolve, reject).then(() => signal.removeEventListener("abort", abort));
+ });
+ signal.throwIfAborted();
+ const native = pageBuilder(MAX_PAGE_CHARS);
+ const reader = (session ? session.nativeTextStream(page) : page.streamTextContent()).getReader();
+ const cancel = () => { void reader.cancel().catch(() => {}); };
+ signal.addEventListener("abort", cancel, { once: true });
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ signal.throwIfAborted();
+ if (done || !native.add(value.items)) break;
+ }
+ } finally {
+ signal.removeEventListener("abort", cancel);
+ cancel();
+ reader.releaseLock();
+ }
+ const result = native.finish();
+ if (session?.embedded.has(pageNumber)) return { ...result, ocrOffset: 0 };
+
+ const recognized = session?.pages.get(pageNumber);
+ if (!recognized?.length) return result;
+ const ocr = pageBuilder(Math.max(0, MAX_PAGE_CHARS - result.text.length - 2));
+ ocr.add(recognized);
+ const extra = ocr.finish();
+ const nativeLines = new Set(result.text.split("\n").map(lineKey));
+ const text = extra.text.split("\n").filter(line => !line.trim() || !nativeLines.has(lineKey(line))).join("\n").trim();
+ const separator = result.text ? "\n\n" : "";
+ return {
+ text: text ? result.text + separator + text : result.text,
+ ocrOffset: text ? result.text.length + separator.length : undefined,
+ incomplete: result.incomplete || extra.incomplete,
+ };
+}
diff --git a/src/lib/ai-context/passages.ts b/src/lib/ai-context/passages.ts
new file mode 100644
index 0000000..62c0d65
--- /dev/null
+++ b/src/lib/ai-context/passages.ts
@@ -0,0 +1,37 @@
+export type Passage = { key: string; page: number; start: number; end: number; coreStart: number; coreEnd: number; text: string; recognized: boolean };
+
+// Overlap excerpts for context while scoring each word only once.
+export function passages(page: number, text: string, ocrOffset?: number, size = 1600, overlap = 170): Passage[] {
+ const result: Passage[] = [];
+ let start = 0;
+ while (start < text.length) {
+ let end = Math.min(text.length, start + size);
+ if (end < text.length) {
+ const tailStart = start + Math.floor(size * 0.55);
+ const tail = text.slice(tailStart, end);
+ const paragraph = tail.lastIndexOf("\n\n");
+ const sentence = Array.from(tail.matchAll(/[.!?。!?](?:\s+|$)/gu)).at(-1);
+ const space = Array.from(tail.matchAll(/\s+/gu)).at(-1);
+ const split = sentence ?? space;
+ if (paragraph >= 0) end = tailStart + paragraph + 2;
+ else if (split) end = tailStart + split.index + split[0].length;
+ if (/[\uDC00-\uDFFF]/.test(text[end])) end++;
+ }
+ const core = text.slice(start, end);
+ if (core.trim()) result.push({ key: `${page}:${start}`, page, start, end, coreStart: start, coreEnd: end, text: core,
+ recognized: ocrOffset !== undefined && end > ocrOffset });
+ start = end;
+ }
+ return result.map(passage => {
+ if (overlap <= 0) return passage;
+ let from = Math.max(0, passage.start - overlap);
+ let to = Math.min(text.length, passage.end + overlap);
+ const boundary = from ? text.slice(from, passage.start).search(/\s/u) : -1;
+ if (boundary >= 0) from += boundary + 1;
+ const nextBoundary = to < text.length ? text.slice(passage.end, to).search(/\s+\S*$/u) : -1;
+ if (nextBoundary >= 0) to = passage.end + nextBoundary;
+ if (/[\uDC00-\uDFFF]/.test(text[from])) from++;
+ if (/[\uDC00-\uDFFF]/.test(text[to])) to--;
+ return { ...passage, start: from, end: to, text: text.slice(from, to), recognized: ocrOffset !== undefined && to > ocrOffset };
+ });
+}
diff --git a/src/lib/ai-context/planner.ts b/src/lib/ai-context/planner.ts
new file mode 100644
index 0000000..a20bbbc
--- /dev/null
+++ b/src/lib/ai-context/planner.ts
@@ -0,0 +1,173 @@
+import type { AiProvider } from "../../ai";
+import type { PDFDocumentProxy } from "../../pdf";
+import { ocrSession } from "../ocr/session/OcrSession";
+import { prepareDocument } from "./document";
+import { passages, type Passage } from "./passages";
+
+export type EvidenceSource = { id: string; page: number; text: string; recognized: boolean };
+export type SelectedPassage = { text: string; page: number };
+type SelectionScope = SelectedPassage & { passages?: SelectedPassage[] };
+export type EvidenceScope = "selection" | "targeted" | "summary";
+export type EvidenceDocument = {
+ name: string;
+ totalPages: number;
+ scope: EvidenceScope;
+ evidence: EvidenceSource[];
+ coverage: "full" | "sampled" | "partial" | "relevant";
+};
+export type EvidenceReference = Pick;
+export type EvidenceRegistry = { revision: string; sources: EvidenceReference[] };
+export class ContextError extends Error {}
+
+const MAX_SOURCES = 24;
+const MAX_NAME = 512;
+export const MAX_QUESTION = 4_000;
+const MAX_MESSAGE = 12_000;
+const FALLBACK_WINDOW: Record = { chatgpt: 8192, agy: 8192, gemini: 8192, claude: 8192, openrouter: 8192, custom: 4096 };
+
+// JSON escaping and Unicode affect the wire size. This deliberately conservative
+// estimate leaves room for provider wrappers, system instructions and the answer.
+export function estimatedTokens(value: unknown) {
+ const json = JSON.stringify(value);
+ return 8 + Math.ceil(json.replace(/[^\x00-\x7f]/g, "").length / 3) + json.replace(/[\x00-\x7f]/g, "").length;
+}
+
+function queryStrategy(question: string, selection?: SelectedPassage | null) {
+ if (selection) return "selection";
+ const summary = /^(?:please\s+)?(?:(?:summari[sz]e|(?:give me\s+)?(?:an?\s+)?(?:overview|summary)\s+of)\s+(?:(?:(?:this|the)\s+)?(?:entire|whole|full)\b|(?:this|the)\s+(?:document|paper|book|article|report|pdf)\b(?!['’]s\b))|what are the (?:key|main) (?:takeaways|points)\s*\??\s*$)/i;
+ return summary.test(question.trim()) ? "summary" : "targeted";
+}
+
+function source(passage: Passage, index: number): EvidenceSource {
+ return { id: `S${index + 1}`, page: passage.page, text: passage.text, recognized: passage.recognized };
+}
+
+function sample(items: Passage[], count: number) {
+ if (items.length <= count) return items;
+ if (count === 1) return [items[Math.floor(items.length / 2)]];
+ return Array.from({ length: count }, (_, i) => items[Math.round(i * (items.length - 1) / (count - 1))]);
+}
+
+export async function planContext(args: {
+ pdf: PDFDocumentProxy;
+ name: string;
+ provider: AiProvider | "agy";
+ history: AiMessage[];
+ question: string;
+ selection?: SelectionScope | null;
+ signal: AbortSignal;
+ progress: (done: number, total: number) => void;
+}) {
+ const { pdf, name, provider, history, question, selection, signal, progress } = args;
+ signal.throwIfAborted();
+ const strategy = queryStrategy(question, selection);
+ const latest: AiMessage = { role: "user", content: question };
+ const window = FALLBACK_WINDOW[provider];
+ const budget = window - 900 - Math.min(1800, Math.floor(window / 4));
+ if (question.length > MAX_QUESTION) throw new ContextError("Shorten your question to 4,000 characters or fewer.");
+ const messages = [latest];
+ const document: EvidenceDocument = {
+ name: name.slice(0, MAX_NAME), totalPages: pdf.numPages,
+ scope: strategy,
+ coverage: "full", evidence: [],
+ };
+ const notices: string[] = [];
+ if (estimatedTokens({ document, messages }) > budget) {
+ throw new ContextError("This question exceeds the model’s context budget. Try a shorter question or another model.");
+ }
+ let candidates: Passage[];
+ let exhaustive = false;
+ if (strategy === "selection" && selection) {
+ // Never index or inspect another page for this scope.
+ const session = ocrSession(pdf);
+ const selected = selection.passages ?? [selection];
+ if (selected.length > MAX_SOURCES || selected.reduce((sum, part) => sum + part.text.length, 0) > MAX_SOURCES * 1800) {
+ throw new ContextError("This selection is too long. Select a shorter passage and try again.");
+ }
+ candidates = selected.flatMap(({ text, page }) => {
+ const recognized = session?.embedded.has(page) || !!session?.pages.get(page)?.length;
+ return passages(page, text, recognized ? 0 : undefined, 1800, 0);
+ });
+ exhaustive = true;
+ } else {
+ const { index, total, readable, partial } = await prepareDocument(pdf, signal, progress);
+ if (partial) notices.push("Some pages or parts of pages could not be searched.");
+ if (readable < total) notices.push(`Searchable text was available on ${readable} of ${total} ${total === 1 ? "page" : "pages"}.`);
+ if (partial || readable < total) document.coverage = "partial";
+ const version = ocrSession(pdf)?.version;
+ const checkOcr = () => {
+ if (version === ocrSession(pdf)?.version) return;
+ document.coverage = "partial";
+ notices.push("Recognized text changed while preparing this question. Ask again for the latest text.");
+ };
+ if (strategy === "summary") {
+ const pages = [...index.pages.keys()].sort((a, b) => a - b);
+ candidates = pages.flatMap(number => {
+ const data = index.pages.get(number);
+ return data?.entries.map(({ passage }) => ({
+ ...passage, start: passage.coreStart, end: passage.coreEnd, text: data.text.slice(passage.coreStart, passage.coreEnd),
+ recognized: data.ocrOffset !== undefined && passage.coreEnd > data.ocrOffset,
+ })) ?? [];
+ });
+ exhaustive = true;
+ } else {
+ const found = await index.search(question, signal);
+ checkOcr();
+ candidates = found;
+ if (document.coverage === "full") document.coverage = "relevant";
+ if (!found.length) notices.push("No matching passages were found in the available text.");
+ }
+ }
+ signal.throwIfAborted();
+
+ const baseCost = estimatedTokens({ document, messages });
+ const costOf = (passage: Passage) => estimatedTokens(source(passage, MAX_SOURCES)) + 1;
+ let left = budget - baseCost;
+ const hadEvidence = candidates.length > 0;
+ if (exhaustive && (candidates.length > MAX_SOURCES || candidates.reduce((sum, candidate) => sum + costOf(candidate), 0) > left)) {
+ if (strategy === "selection") throw new ContextError("This selection won’t fit in the model’s context. Select a shorter passage or choose another model.");
+ if (document.coverage === "full") document.coverage = "sampled";
+ notices.push("This summary samples passages across the document. It does not cover every passage.");
+ for (let count = Math.min(MAX_SOURCES, candidates.length); count >= 1; count--) {
+ const sampled = sample(candidates, count);
+ if (sampled.reduce((sum, candidate) => sum + costOf(candidate), 0) <= left) {
+ candidates = sampled;
+ break;
+ }
+ if (count === 1) candidates = [];
+ }
+ }
+
+ const chosen: Passage[] = [];
+ let skipped = false;
+ for (const passage of candidates) {
+ const cost = costOf(passage);
+ if (cost > left || chosen.length === MAX_SOURCES) { skipped = true; continue; }
+ chosen.push(passage);
+ left -= cost;
+ }
+ document.evidence = chosen.map((passage, i) => {
+ const adjacent = chosen.filter(other => other.page === passage.page && other !== passage);
+ const start = adjacent.some(other => other.coreEnd === passage.coreStart) ? passage.coreStart : passage.start;
+ const end = adjacent.some(other => other.coreStart === passage.coreEnd) ? passage.coreEnd : passage.end;
+ return source({ ...passage, text: passage.text.slice(start - passage.start, end - passage.start) }, i);
+ });
+ if (skipped) notices.push("Some matching passages were omitted to fit the model’s context.");
+ if ((hadEvidence || selection) && !document.evidence.length) {
+ throw new ContextError("The available passage won’t fit in the model’s context. Try a shorter question or choose another model.");
+ }
+ // Earlier replies may quote pages outside the selection.
+ if (strategy === "targeted" || strategy === "summary") {
+ for (const item of history.slice(-12).reverse()) {
+ if (!item.content || item.content.length > MAX_MESSAGE) break;
+ const prior = { role: item.role, content: item.content };
+ const cost = estimatedTokens(prior) + 1;
+ if (cost > left) break;
+ messages.unshift(prior);
+ left -= cost;
+ }
+ const firstUser = messages.findIndex(message => message.role === "user");
+ if (firstUser > 0) messages.splice(0, firstUser);
+ }
+ return { document, messages, notice: notices.join(" ") || undefined };
+}
diff --git a/src/lib/ai-context/search.ts b/src/lib/ai-context/search.ts
new file mode 100644
index 0000000..058ffe7
--- /dev/null
+++ b/src/lib/ai-context/search.ts
@@ -0,0 +1,141 @@
+import { passages, type Passage } from "./passages";
+import type { PageText } from "./extraction";
+
+export const normalize = (text: string) => text.normalize("NFKC").toLowerCase().replace(/\s+/gu, " ").trim();
+const segmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity: "word" }) : undefined;
+const unspaced = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
+const stop = new Set("a an about are as at be by can did do does for from has how i in is it me of on or that the their this to was were what when where which who why will with would you your".split(" "));
+// Equal scores should not crowd out later pages in a long document.
+const pageOrder = (page: number) => Math.imul(page, 2_654_435_761) >>> 0;
+
+function* terms(text: string) {
+ for (const match of normalize(text).matchAll(/[\p{L}\p{M}\p{N}]+/gu)) {
+ const token = match[0];
+ if (unspaced.test(token)) {
+ if (segmenter) {
+ for (const part of segmenter.segment(token)) if (part.isWordLike && part.segment.length <= 64) yield part.segment;
+ }
+ // Single-character queries and compounds can cross dictionary boundaries.
+ let previous = "";
+ for (const character of token) {
+ if (!segmenter) yield character;
+ if (previous) yield previous + character;
+ previous = character;
+ }
+ if (token.length <= 2) yield token;
+ } else if (token.length > 64) {
+ yield token.slice(0, 48) + "…" + token.slice(-16);
+ } else if (!stop.has(token)) {
+ yield token;
+ // Lower-weight stems can match related inflections without outranking exact words.
+ const stem = /^conclu(?:d|s)/.test(token) ? "conclu"
+ : token.replace(/(?:ations?|ings?|ers?|edly|ed|s)$/u, "");
+ if (/^[a-z]+$/.test(token) && stem.length >= 4) yield "~" + stem;
+ }
+ }
+}
+
+export function timeSlice(signal: AbortSignal) {
+ let started = performance.now();
+ return async () => {
+ signal.throwIfAborted();
+ if (performance.now() - started < 10) return;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ signal.throwIfAborted();
+ started = performance.now();
+ };
+}
+
+type Entry = { passage: Passage; frequencies: Map; length: number };
+type IndexedPage = PageText & { entries: Entry[] };
+
+export class PassageIndex {
+ readonly pages = new Map();
+ #postings = new Map>();
+ #links = 0;
+ #length = 0;
+ #count = 0;
+ chars = 0;
+
+ constructor(private readonly maxLinks = 500_000) {}
+
+ replace(page: number, data?: PageText): boolean {
+ const old = this.pages.get(page);
+ if (old) {
+ for (const entry of old.entries) {
+ for (const term of entry.frequencies.keys()) {
+ const posting = this.#postings.get(term)!;
+ posting.delete(entry);
+ if (!posting.size) this.#postings.delete(term);
+ }
+ this.#count--;
+ this.#length -= entry.length;
+ this.#links -= entry.frequencies.size;
+ }
+ this.pages.delete(page);
+ this.chars -= old.text.length;
+ }
+ if (!data) return true;
+ const entries = passages(page, data.text, data.ocrOffset).map(passage => {
+ const frequencies = new Map();
+ let length = 0;
+ for (const term of terms(data.text.slice(passage.coreStart, passage.coreEnd))) {
+ frequencies.set(term, (frequencies.get(term) ?? 0) + 1);
+ length++;
+ }
+ return { passage, frequencies, length };
+ });
+ const links = entries.reduce((sum, entry) => sum + entry.frequencies.size, 0);
+ if (this.#links + links > this.maxLinks) return false;
+ for (const entry of entries) {
+ for (const [term, frequency] of entry.frequencies) {
+ let posting = this.#postings.get(term);
+ if (!posting) this.#postings.set(term, posting = new Map());
+ posting.set(entry, frequency);
+ }
+ this.#length += entry.length;
+ this.#count++;
+ }
+ this.#links += links;
+ this.chars += data.text.length;
+ this.pages.set(page, { ...data, entries });
+ return true;
+ }
+
+ async search(query: string, signal: AbortSignal, limit = 24): Promise {
+ const scores = new Map();
+ const pause = timeSlice(signal);
+ const average = this.#length / (this.#count || 1) || 1;
+ const literal = normalize(query.match(/["“]([^"”]+)["”]/u)?.[1] ?? query);
+ let visited = 0;
+ for (const term of new Set(terms(query))) {
+ const posting = this.#postings.get(term);
+ if (!posting) continue;
+ const idf = Math.log1p((this.#count - posting.size + 0.5) / (posting.size + 0.5));
+ for (const [entry, frequency] of posting) {
+ const bonus = idf * frequency * 2.2 / (frequency + 1.2 * (0.25 + 0.75 * entry.length / average));
+ scores.set(entry, (scores.get(entry) ?? 0) + bonus * (term.startsWith("~") ? 0.35 : 1));
+ if (++visited % 256 === 0) await pause();
+ }
+ }
+ if (literal.includes(" ") && literal.length <= 240) {
+ for (const [entry, score] of scores) {
+ if (normalize(entry.passage.text).includes(literal)) scores.set(entry, score * 1.6);
+ if (++visited % 64 === 0) await pause();
+ }
+ }
+ const found: Passage[] = [], seen = new Set();
+ for (const [entry] of [...scores].sort(([a, x], [b, y]) => y - x
+ || pageOrder(a.passage.page) - pageOrder(b.passage.page) || a.passage.start - b.passage.start)) {
+ if (!this.pages.get(entry.passage.page)?.entries.includes(entry)) continue;
+ const key = normalize(entry.passage.text);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ found.push(entry.passage);
+ if (found.length === limit) break;
+ }
+ signal.throwIfAborted();
+ return found;
+ }
+
+}
diff --git a/src/lib/ocr/session/OcrSession.ts b/src/lib/ocr/session/OcrSession.ts
index 6c90ccd..a00fd41 100644
--- a/src/lib/ocr/session/OcrSession.ts
+++ b/src/lib/ocr/session/OcrSession.ts
@@ -21,6 +21,7 @@ export class OcrSession {
#key: string | null;
#epoch: string | null;
#pageListeners = new Set<(page: number) => void>();
+ #nativeStreams = new WeakMap