chat: send an EPUB's text with chat messages (#621, ninondev)

Chat (page-chat 0.1.8 -> 0.1.9) can send an EPUB's text with a message. The book is read in the page (chat/epub-reader.js: its own ZIP reader with size, CRC and encryption checks, DecompressionStream inflate, chapters parsed inert in spine order, no external resource loaded, no script run), never uploaded. Each request to the gateway inlines the text once in the user message that carried it, between 【电子书:name】 and 【电子书结束】; the same book again is a note, a failed read is a note and a toast. Send waits while a book is read, and switching chats drops a book still being read. Image-only user messages now stay in history.

Run at 1cb1ecb400fe31bbc1f58463af09af757374d27e:
- CI (pr.yml, ubuntu): HOME=$(mktemp -d) bun test and bun scripts/check.mjs green; the spawned-Chrome reader test ran and passed there (10.5s).
- mote: packages/chat bun test 34 pass; the reader test's own Chrome spawn gets no page load over ssh on macOS (and in WSL), so its fixtures were run again through Playwright 1.62 Chromium and WebKit: 2 pass, 21 expects, each engine.
- End to end on mote, Chromium and WebKit, 420px: startServer with a sandbox config and HOME, a fake gateway, the real page; attached Project Gutenberg's Alice (132,120 chars) and 紅樓夢 (876,576 chars) EPUBs, sent, then followed up. Each gateway request carried the book once, before the question, with no base64 or EPUB data; the follow-up carried user,assistant,user with the book once. The page made no request outside its own service.

Not changed: the MCP tool pick still scores the last message, which on a book's first message is the whole book (filed as #623).
This commit is contained in:
ninon
2026-11-02 16:01:29 +08:00
committed by GitHub
parent 3944e53b8c
commit 63cd0e4bf9
7 changed files with 561 additions and 29 deletions
+77 -28
View File
@@ -672,7 +672,8 @@ function parseEventBlock(block) {
return data;
}
function streamChat(payload, onEvent, signal) {
async function streamChat(payload, onEvent, signal) {
payload.messages = await requestMessages(payload.messages, function (reason) { toast("旧附件未发送。" + reason, true); });
return fetch("api/chat", {
method: "POST",
headers: authHeaders({ "content-type": "application/json" }),
@@ -972,14 +973,26 @@ function readAsDataURL(file) {
function guessType(file) {
if (file.type) return file.type;
var ext = String(file.name || "").split(".").pop().toLowerCase();
var map = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", pdf: "application/pdf", txt: "text/plain", md: "text/markdown", json: "application/json" };
var map = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml", pdf: "application/pdf", epub: "application/epub+zip", txt: "text/plain", md: "text/markdown", json: "application/json" };
return map[ext] || "application/octet-stream";
}
// 一批 File → 加入待发送列表
var attachmentContext = 0, pendingBooks = 0;
function clearPendingAttachments() {
attachmentContext++;
pendingBooks = 0;
state.attachments = [];
renderAttachments();
}
function addFiles(files) {
var list = Array.from(files || []).slice(0, 8);
if (!list.length) return Promise.resolve();
var context = attachmentContext;
var books = list.filter(MagpieEpub.isEpub).length;
pendingBooks += books;
updateSend();
var jobs = list.map(function (file) {
var type = guessType(file);
var isImage = /^image\//.test(type);
@@ -987,7 +1000,11 @@ function addFiles(files) {
toast((isImage ? "图片" : "文件") + "太大:" + (file.name || ""), true);
return null;
}
return readAsDataURL(file).then(function (data) {
return readAsDataURL(file).then(async function (data) {
var book = MagpieEpub.isEpub(file) ? await MagpieEpub.read(data) : null;
if (book) {
return { name: file.name, type: type, kind: "file", size: file.size, data: data, bookChars: book.characters, imagePages: book.imagePages };
}
return api("api/upload", {
method: "POST",
body: { name: file.name || "file", type: type, data: data, clientType: type }
@@ -995,11 +1012,19 @@ function addFiles(files) {
// 上传接口挂了也还能本地显示:直接按 data URL 用
return { name: file.name || "file", type: type, kind: isImage ? "image" : "file", size: data.length, data: data };
});
}).catch(function (err) {
if (context === attachmentContext) toast((file.name || "文件") + ":" + err.message, true);
return null;
});
}).filter(Boolean);
return Promise.all(jobs).then(function (out) {
if (context !== attachmentContext) return;
out.forEach(function (f) { if (f && f.data) state.attachments.push(f); });
renderAttachments();
}).finally(function () {
if (context !== attachmentContext) return;
pendingBooks -= books;
updateSend();
});
}
@@ -1013,6 +1038,7 @@ function renderAttachments() {
if (f.kind === "image") chip.appendChild(el("img", { src: f.data, alt: f.name || "" }));
else chip.appendChild(el("span", { class: "ic", text: (String(f.name || "F").split(".").pop() || "F").slice(0, 3).toUpperCase() }));
chip.appendChild(el("span", { class: "nm", text: f.name || "文件" }));
if (f.bookChars) chip.appendChild(el("span", { text: "随消息发送 " + f.bookChars.toLocaleString() + " 字" + (f.imagePages ? "(" + f.imagePages + " 个章节仅含图片)" : "") }));
var rm = el("button", { class: "rm", type: "button", title: "移除", "aria-label": "移除" });
rm.appendChild(el("span", { text: "\u00d7" }));
rm.addEventListener("click", function () {
@@ -1461,6 +1487,7 @@ function askDelete(id, title) {
state.settings.pinned = pinned;
api("api/settings", { method: "POST", body: { pinned: pinned } }).catch(function () {});
if (state.convId === id) {
clearPendingAttachments();
state.convId = null;
state.title = "新对话";
state.messages = [];
@@ -1488,6 +1515,7 @@ function openConversation(id) {
dropBlankDraft(); // 切换到别的对话时,空着的"新对话"不该留在列表里
api("api/conversations/" + encodeURIComponent(id)).then(function (conv) {
if (!conv) return;
if (state.convId !== conv.id) clearPendingAttachments();
state.convId = conv.id;
state.title = conv.title || "新对话";
state.messages = (conv.messages || []).map(normalizeMessage);
@@ -1789,7 +1817,7 @@ function mediaBlock(files, opts) {
} else {
wrap.appendChild(el("span", { class: "msg-file", title: f.name || "" },
el("span", { class: "nm", text: f.name || "文件" }),
el("span", { class: "hint", text: f.size ? fmtBytes(f.size) : "" })
el("span", { class: "hint", text: MagpieEpub.isEpub(f) ? "提问时读取正文" : (f.size ? fmtBytes(f.size) : "") })
));
}
});
@@ -2121,20 +2149,60 @@ function updateSend() {
var btn = $("#send");
var input = $("#input");
$("#app").classList.toggle("busy", state.busy);
btn.disabled = state.busy ? false : (!input.value.trim() && !(state.attachments || []).length);
btn.disabled = !state.busy && (pendingBooks > 0 || (!input.value.trim() && !(state.attachments || []).length));
btn.setAttribute("aria-label", state.busy ? "停止生成" : "发送");
input.title = state.busy ? "生成中…(Esc 停止)" : "Enter 发送 · Shift+Enter 换行";
}
async function requestMessages(history, warn) {
var seen = new Set(), messages = [];
for (var m of history) {
var files = (m.files || []).filter(Boolean);
if (m.role === "assistant") {
var calls = (m.toolCalls || []).filter(function (c) { return c && c.name && (c.result || c.isError); });
if (m.content || calls.length) messages.push({ role: m.role, content: m.content, toolCalls: calls, files: files });
continue;
}
var parts = [], otherFiles = [];
for (var f of files) {
if (!MagpieEpub.isEpub(f)) {
if (f.data) otherFiles.push(f);
continue;
}
var bytes = typeof f.data === "string" ? f.data.slice(f.data.indexOf(",") + 1) : "";
if (seen.has(bytes)) {
parts.push("(" + f.name + " 的正文已附在前文。)");
continue;
}
try {
var book = await MagpieEpub.read(f.data);
parts.push("【电子书:" + f.name + "】\n" + book.text + "\n【电子书结束】");
if (book.imagePages) parts.push("(" + book.imagePages + " 个章节仅含图片,未提取文字。)");
seen.add(bytes);
} catch (err) {
var reason = f.name + ":" + err.message;
parts.push("(未附上这本电子书的正文。" + reason + ")");
warn(reason);
}
}
if (String(m.content || "").trim()) parts.push(m.content);
if (parts.length || otherFiles.some(function (f) { return f.kind === "image"; })) {
messages.push({ role: m.role, content: parts.join("\n\n"), files: otherFiles });
}
}
return messages;
}
function send() {
if (state.busy) { stop(); return; }
if (pendingBooks) { toast("电子书还在读取,请稍候。"); return; }
var input = $("#input");
var text = input.value.trim();
if (!text && !(state.attachments || []).length) return;
if (!state.settings.model) { toast("先选一个模型", true); return; }
var files = (state.attachments || []).map(function (f) {
return { name: f.name, type: f.type, kind: f.kind, size: f.size, data: f.data };
return { name: f.name, type: f.type, kind: f.kind, size: f.size, data: f.data, bookChars: f.bookChars, imagePages: f.imagePages };
});
var userMsg = { role: "user", content: text, reasoning: "", toolCalls: [], files: files };
state.attachments = [];
@@ -2150,7 +2218,7 @@ function send() {
state.messages.push(userMsg, asstMsg);
if (!state.convId && state.title === "新对话") {
state.title = text.replace(/\s+/g, " ").slice(0, 30);
state.title = (text || files[0].name || "新对话").replace(/\s+/g, " ").slice(0, 30);
}
// 草稿发了第一条消息:先把列表里那条的标题换成刚输入的内容(不用等服务器),
// 等保存成功再把它换成真正的对话条目(见 persistConversation)。
@@ -2177,28 +2245,8 @@ function send() {
updateSend();
scrollBottom(true);
var history = state.messages.filter(function (m) {
if (m === asstMsg) return false;
if (m.role === "user") return Boolean(String(m.content || "").trim());
return Boolean(m.content) || (m.toolCalls && m.toolCalls.length > 0);
}).map(function (m) {
// 上一轮的工具调用也带上,模型才知道它已经查过什么;服务端会把
// assistant.tool_calls 和对应的 tool 结果一起重放,缺结果的调用它自己丢掉。
var calls = m.role === "assistant" && Array.isArray(m.toolCalls)
? m.toolCalls.filter(function (c) { return c && c.name && (c.result || c.isError); })
: [];
return {
role: m.role,
content: m.content,
toolCalls: calls,
files: (m.files || []).filter(function (f) { return f && f.data; }).map(function (f) {
return { name: f.name, type: f.type, kind: f.kind, size: f.size, data: f.data };
})
};
});
var payload = {
messages: history,
messages: state.messages.slice(0, -1),
model: state.settings.model,
effort: state.settings.effort || "",
system: state.settings.systemEnabled === false ? "" : (state.settings.system || ""),
@@ -2461,6 +2509,7 @@ function newChat() {
if (state.busy) { toast("正在生成,先停止再新建对话", true); return; }
// 已经在一个空白的新对话里了:再点"新对话"就保持原样,别叠出第二个
if (isBlankDraft()) { $("#input").focus(); return; }
clearPendingAttachments();
state.draft = { id: DRAFT_ID, title: "新对话", updated: Date.now() };
state.convId = null;
state.title = "新对话";
+267
View File
@@ -0,0 +1,267 @@
(() => {
"use strict";
const MiB = 1024 * 1024, fileLimit = 8 * MiB, extractLimit = 24 * MiB, textLimit = 2 * MiB;
const damaged = "EPUB 文件损坏或目录不完整。";
const tooLarge = "EPUB 正文太大,请分卷后添加。";
const encrypted = "EPUB 正文已加密,无法读取。";
const fail = message => { throw new Error(message); };
const utf8 = new TextDecoder("utf-8", { fatal: true });
function isEpub(file) {
return !!file && (/\.epub$/i.test(file.name || "") ||
[file.type, file.mime].some(type => /^application\/epub\+zip(?:\s*;|$)/i.test(type || "")));
}
function fileBytes(url) {
if (typeof url !== "string") fail(damaged);
const comma = url.indexOf(",");
if (comma < 0 || !/^data:[^,]*;base64$/i.test(url.slice(0, comma))) fail(damaged);
if (url.length - comma - 1 > 4 * Math.ceil(fileLimit / 3)) fail("EPUB 文件超过 8 MiB,请分卷后添加。");
let binary;
try { binary = atob(url.slice(comma + 1)); } catch { fail(damaged); }
if (binary.length > fileLimit) fail("EPUB 文件超过 8 MiB,请分卷后添加。");
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < bytes.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
const crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
for (let i = 0; i < 8; i++) n = n & 1 ? 0xedb88320 ^ (n >>> 1) : n >>> 1;
return n;
});
function checksum(bytes) {
let crc = -1;
for (const byte of bytes) crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 255];
return (crc ^ -1) >>> 0;
}
async function inflate(packed, size) {
let inflater;
try { inflater = new DecompressionStream("deflate-raw"); }
catch { fail("当前浏览器无法解压 EPUB,请更新后再试。"); }
let pos = 0;
const input = new ReadableStream({ pull(controller) {
if (pos === packed.length) return controller.close();
const next = Math.min(pos + 4096, packed.length);
controller.enqueue(packed.subarray(pos, next));
pos = next;
} });
const reader = input.pipeThrough(inflater).getReader();
const bytes = new Uint8Array(size);
let written = 0;
try {
for (;;) {
const { value, done } = await reader.read();
if (done) break;
if (value.length > size - written) {
await reader.cancel();
fail(damaged);
}
bytes.set(value, written);
written += value.length;
}
} catch { fail(damaged); }
if (written !== size) fail(damaged);
return bytes;
}
function openZip(bytes) {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const u16 = p => view.getUint16(p, true), u32 = p => view.getUint32(p, true);
let end = bytes.length - 22;
for (; end >= Math.max(0, bytes.length - 65557); end--) {
if (u32(end) === 0x06054b50 && end + 22 + u16(end + 20) === bytes.length) break;
}
if (end < Math.max(0, bytes.length - 65557)) fail(damaged);
const count = u16(end + 10), start = u32(end + 16);
if (u16(end + 4) || u16(end + 6) || u16(end + 8) !== count ||
count > 10000 || start + u32(end + 12) !== end) fail(damaged);
const names = new Map();
let pos = start, extracted = 0;
function nameAt(offset, length) {
try { return utf8.decode(bytes.subarray(offset, offset + length)); } catch { fail(damaged); }
}
for (let i = 0; i < count; i++) {
if (pos + 46 > end || u32(pos) !== 0x02014b50 || u16(pos + 34)) fail(damaged);
const length = u16(pos + 28);
const next = pos + 46 + length + u16(pos + 30) + u16(pos + 32);
if (next > end) fail(damaged);
const name = nameAt(pos + 46, length);
if (!name || names.has(name)) fail(damaged);
names.set(name, pos);
pos = next;
}
if (pos !== end) fail(damaged);
return {
has: name => names.has(name),
async read(name, maxSize) {
const c = names.get(name);
if (c === undefined) fail(damaged);
const flags = u16(c + 8), method = u16(c + 10), packed = u32(c + 20), size = u32(c + 24);
if (flags & 0x41) fail(encrypted);
if (size > maxSize || size > extractLimit - extracted) fail(tooLarge);
extracted += size;
const local = u32(c + 42);
if (local + 30 > start || u32(local) !== 0x04034b50 || u16(local + 6) !== flags ||
u16(local + 8) !== method) fail(damaged);
const length = u16(local + 26), data = local + 30 + length + u16(local + 28);
if (data + packed > start || nameAt(local + 30, length) !== name) fail(damaged);
let raw = bytes.subarray(data, data + packed);
if (method === 8) raw = await inflate(raw, size);
else if (method !== 0) fail("这种 EPUB 压缩格式暂不支持。");
if (raw.length !== size || checksum(raw) !== u32(c + 16)) fail(damaged);
let encoding = "utf-8";
if ((raw[0] === 255 && raw[1] === 254) || (raw[0] === 60 && raw[1] === 0)) encoding = "utf-16le";
if ((raw[0] === 254 && raw[1] === 255) || (raw[0] === 0 && raw[1] === 60)) encoding = "utf-16be";
try { return new TextDecoder(encoding, { fatal: true }).decode(raw); } catch { fail(damaged); }
}
};
}
// References are paths within the ZIP. Decode each segment after separating URL fragments.
function pathFor(baseFile, href) {
if (!href || /^(?:[a-z][\w+.-]*:|\/)/i.test(href)) fail(damaged);
const parts = baseFile.split("/");
parts.pop();
for (const segment of href.split(/[?#]/, 1)[0].split("/")) {
let name;
try { name = decodeURIComponent(segment); } catch { fail(damaged); }
if (/[\/\\\0]/.test(name)) fail(damaged);
if (name === "..") {
if (!parts.length) fail(damaged);
parts.pop();
} else if (name && name !== ".") parts.push(name);
}
return parts.join("/");
}
// Older XHTML books use named HTML entities from a DTD. Decode them locally, as numeric
// XML references; CDATA, comments and processing instructions must retain their literal text.
function expandHtmlEntities(source) {
const template = document.createElement("template"), cache = new Map();
return source.replace(/<!\[CDATA\[[\s\S]*?(?:\]\]>|$)|<!--[\s\S]*?(?:-->|$)|<\?[\s\S]*?(?:\?>|$)|&([a-z][a-z0-9]{0,31});/gi, (token, name) => {
if (!name) return token;
if (!cache.has(token)) {
template.innerHTML = '<i data-value="' + token + '"></i>';
const value = template.content.firstChild.getAttribute("data-value");
if (value === token) fail(damaged);
cache.set(token, Array.from(value, c => "&#" + c.codePointAt(0) + ";").join(""));
}
return cache.get(token);
});
}
function xml(source, chapter = false) {
// External declarations are unnecessary for reading text; never resolve entities from the book.
if (/<!ENTITY\s/i.test(source)) fail("EPUB 使用了不支持的 XML 实体声明。");
const start = source.search(/<!DOCTYPE\s/i);
if (start !== -1) {
const decl = /^<!DOCTYPE\s+(?:[^<>"'\[]|"[^"]*"|'[^']*')*>/i.exec(source.slice(start));
if (!decl) fail(damaged);
source = source.slice(0, start) + source.slice(start + decl[0].length);
if (/<!DOCTYPE\s/i.test(source)) fail(damaged);
}
const parser = new DOMParser();
let doc = parser.parseFromString(source, "application/xml");
if (doc.getElementsByTagNameNS("*", "parsererror").length && chapter && source.includes("&")) {
doc = parser.parseFromString(expandHtmlEntities(source), "application/xml");
}
if (doc.getElementsByTagNameNS("*", "parsererror").length) fail(damaged);
return doc;
}
const elements = (root, name) => Array.from(root.getElementsByTagNameNS("*", name));
const blocks = new Set("address article aside blockquote br caption dd div dl dt figcaption figure footer h1 h2 h3 h4 h5 h6 header hr li main nav ol p pre section table td th tr ul".split(" "));
const ignored = new Set("head title script style noscript template iframe object".split(" "));
function chapterText(source, type) {
let body;
if (type === "text/html") {
// The template's owner document has no browsing context, so image and frame URLs stay inert.
const html = document.createElement("template").content.ownerDocument.createElement("html");
html.innerHTML = source;
body = html.querySelector("body");
} else {
body = elements(xml(source, true), "body")[0];
}
if (!body) fail(damaged);
const lines = [];
let pieces = [];
function flush() {
if (!pieces.length) return;
const line = pieces.join("").replace(/\p{White_Space}+/gu, " ").replace(/^ | $/g, "");
if (line) lines.push(line);
pieces = [];
}
for (let node = body.firstChild; node;) {
const tag = node.nodeType === 1 ? node.localName.toLowerCase() : "";
if (node.nodeType === 3 || node.nodeType === 4) pieces.push(node.nodeValue);
if (blocks.has(tag)) flush();
if (!ignored.has(tag) && node.firstChild) {
node = node.firstChild;
continue;
}
while (node !== body) {
if (node.nodeType === 1 && blocks.has(node.localName.toLowerCase())) flush();
if (node.nextSibling) break;
node = node.parentNode;
}
node = node === body ? null : node.nextSibling;
}
flush();
const text = lines.join("\n\n");
const imageOnly = !text && !!body.querySelector("img, picture, svg, image, canvas, object[type^='image/']");
return { text, imageOnly };
}
async function read(dataUrl) {
const archive = openZip(fileBytes(dataUrl));
const locked = new Set();
const encryption = "META-INF/encryption.xml";
if (archive.has(encryption)) {
const doc = xml(await archive.read(encryption, MiB));
for (const el of elements(doc, "CipherReference")) locked.add(pathFor("", el.getAttribute("URI")));
}
function readFile(name, maxSize) {
if (locked.has(name)) fail(encrypted);
return archive.read(name, maxSize);
}
const container = xml(await readFile("META-INF/container.xml", MiB));
const roots = elements(container, "rootfile");
const root = roots.find(el => el.getAttribute("media-type") === "application/oebps-package+xml") || roots[0];
const opfPath = pathFor("", root?.getAttribute("full-path"));
const opf = xml(await readFile(opfPath, MiB));
const manifest = elements(opf, "manifest")[0], spine = elements(opf, "spine")[0];
if (!manifest || !spine) fail(damaged);
const items = new Map();
for (const item of elements(manifest, "item")) {
const id = item.getAttribute("id");
if (!id || items.has(id)) fail(damaged);
items.set(id, item);
}
const chapters = [], seenPaths = new Set();
let length = 0, imagePages = 0;
for (const ref of elements(spine, "itemref")) {
const item = items.get(ref.getAttribute("idref"));
if (!item) fail(damaged);
const name = pathFor(opfPath, item.getAttribute("href"));
if (seenPaths.has(name)) continue;
seenPaths.add(name);
const type = item.getAttribute("media-type");
if (type !== "application/xhtml+xml" && type !== "text/html") fail("EPUB 含有暂不支持的章节格式。");
const { text, imageOnly } = chapterText(await readFile(name, 8 * MiB), type);
if (imageOnly) imagePages++;
if (!text) continue;
length += text.length + (chapters.length ? 2 : 0);
if (length > textLimit) fail(tooLarge);
chapters.push(text);
}
if (!chapters.length) fail("EPUB 中没有可读取的文字,可能是扫描版。");
const text = chapters.join("\n\n");
let characters = 0;
for (const char of text) if (!/\p{White_Space}/u.test(char)) characters++;
return { text, characters, imagePages };
}
globalThis.MagpieEpub = { isEpub, read };
})();
+1
View File
@@ -169,6 +169,7 @@
<div class="toast" id="toast" role="status" aria-live="polite" hidden><span id="toastText"></span></div>
</div>
<script src="vendor/katex/katex.min.js" defer></script>
<script src="epub-reader.js" defer></script>
<script src="app.js" defer></script>
</body>
</html>