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
+1
View File
@@ -20,6 +20,7 @@ It then has a tab, **Chat** (对话, 對話, チャット), under Plugins in the
- **magpie's models.** The list comes from the gateway's `/v1/models`. Models with reasoning levels get an effort picker. Each model shows its brand icon (OpenAI, Claude, Gemini, DeepSeek, Qwen, Kimi, GLM, MiniMax and more) in the picker and next to its name in the transcript. The icons come from [@lobehub/icons](https://github.com/lobehub/lobe-icons) (MIT); see `chat/icons/models/NOTICE`. - **magpie's models.** The list comes from the gateway's `/v1/models`. Models with reasoning levels get an effort picker. Each model shows its brand icon (OpenAI, Claude, Gemini, DeepSeek, Qwen, Kimi, GLM, MiniMax and more) in the picker and next to its name in the transcript. The icons come from [@lobehub/icons](https://github.com/lobehub/lobe-icons) (MIT); see `chat/icons/models/NOTICE`.
- **magpie's library.** Tick instructions and skills from `~/.config/magpie/library/` (folded into the system prompt), and MCP servers from `library.json` (their tools run as real `tool_calls`, at most 8 rounds, Streamable HTTP and stdio). The switch "使用 magpie 的全部 MCP 服务器" at the top of the MCP list uses every server in the library instead, one added to magpie later too; it is off by default, and turning it off brings back the servers you ticked. magpie's own MCP servers (web search, image recognition, image generation, plugin tools) are in the list beside the library's while they are on in magpie (asked of the gateway's `/v1/magpie/mcp`, magpie v0.1.2397 and later; an older magpie lists none); one turned off in magpie's Settings is left out, and a library server of the same name, such as an installed `magpie-image`, is used in its place. - **magpie's library.** Tick instructions and skills from `~/.config/magpie/library/` (folded into the system prompt), and MCP servers from `library.json` (their tools run as real `tool_calls`, at most 8 rounds, Streamable HTTP and stdio). The switch "使用 magpie 的全部 MCP 服务器" at the top of the MCP list uses every server in the library instead, one added to magpie later too; it is off by default, and turning it off brings back the servers you ticked. magpie's own MCP servers (web search, image recognition, image generation, plugin tools) are in the list beside the library's while they are on in magpie (asked of the gateway's `/v1/magpie/mcp`, magpie v0.1.2397 and later; an older magpie lists none); one turned off in magpie's Settings is left out, and a library server of the same name, such as an installed `magpie-image`, is used in its place.
- **EPUB books.** Chat reads selectable text in chapter order when you send a message. An EPUB already in the conversation history also works. Each follow-up sends the text again while the attachment is in history, so it counts toward the selected model's input limit each time. Attaching the same file twice sends one copy of the text. Chat does not transcribe images.
- **Images and files.** Pick, drop or paste them. Images go to the model as `image_url`. Replies can carry base64 data-URI images, which render inline and open full size on click. Remote `![alt](https://…)` images are shown as a link instead of being loaded — fetching them automatically would let a reply make the page request an arbitrary URL. - **Images and files.** Pick, drop or paste them. Images go to the model as `image_url`. Replies can carry base64 data-URI images, which render inline and open full size on click. Remote `![alt](https://…)` images are shown as a link instead of being loaded — fetching them automatically would let a reply make the page request an arbitrary URL.
- **Streaming.** Reasoning unfolds while it arrives, then collapses. While the answer streams, the page follows it down unless you scroll up yourself; scroll back to the bottom and it resumes. - **Streaming.** Reasoning unfolds while it arrives, then collapses. While the answer streams, the page follows it down unless you scroll up yourself; scroll back to the bottom and it resumes.
- **Model status.** Every reply ends with a line saying what the model is doing: `Magpie正在觅食ing… · 2s` with a running timer while it generates, green `Magpie找到了食物! · 2s` when done, red `Magpie没有找到食物` on failure. The elapsed time is kept with the conversation. - **Model status.** Every reply ends with a line saying what the model is doing: `Magpie正在觅食ing… · 2s` with a running timer while it generates, green `Magpie找到了食物! · 2s` when done, red `Magpie没有找到食物` on failure. The elapsed time is kept with the conversation.
+74
View File
@@ -6,6 +6,7 @@
import { afterAll, beforeAll, expect, test } from "bun:test" import { afterAll, beforeAll, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { request } from "node:http" import { request } from "node:http"
import { runInNewContext } from "node:vm"
import { tmpdir } from "node:os" import { tmpdir } from "node:os"
import { join } from "node:path" import { join } from "node:path"
@@ -150,6 +151,79 @@ test("with the token, a chat streams from the gateway with the caller key", asyn
expect(got.body.messages.at(-1)).toEqual({ role: "user", content: "hi" }) expect(got.body.messages.at(-1)).toEqual({ role: "user", content: "hi" })
}) })
function chatPage(setup = "") {
const page = {
document: { readyState: "loading", querySelector: () => ({ getAttribute: () => token }), addEventListener() {} },
TextDecoder,
fetch: (path, init) => {
if (path !== "api/chat") throw new Error("unexpected request: " + path)
return fetch(`http://127.0.0.1:${port}/api/chat`, init)
},
window: { addEventListener() {} }, location: { search: "" },
MagpieEpub: { isEpub: f => f.name?.endsWith(".epub") },
}
runInNewContext(readFileSync(join(dir, "chat/app.js"), "utf8") + "\n" + setup, page)
return page
}
test("a saved EPUB reaches the gateway once, including on a follow-up", async () => {
const page = chatPage("toast = message => globalThis.warnings.push(message);")
page.warnings = []
const chapters = "The lamp is blue.\n\nThe lamp goes out."
const file = { name: "lamp.epub", kind: "file", data: "data:;base64,Ym9vaw==" }
const image = { name: "lamp.png", kind: "image", data: "data:image/png;base64,cG5n" }
const broken = { ...file, name: "broken.epub", data: "data:;base64,YmFk" }
const h = { ...json, "x-magpie-chat-token": token }
page.MagpieEpub.read = async data => {
if (data === broken.data) throw new Error("damaged")
expect(data).toBe(file.data)
return { text: chapters, imagePages: 1 }
}
const past = [
{ role: "user", content: "", files: [file, image] },
{ role: "assistant", content: "A blue lamp." },
{ role: "user", content: "What changed?", files: [{ ...file, name: "copy.epub" }, broken] },
]
const saved = JSON.parse((await raw("POST", "/api/conversations", h, { messages: past })).body)
const history = JSON.parse((await raw("GET", "/api/conversations/" + saved.id, h)).body).messages
const events = []
await page.streamChat({ ...chatBody, messages: history }, event => events.push(event))
expect(events.at(-1).type).toBe("done")
const sent = seen.at(-1).body.messages
expect(sent.at(-3).content[0].text).toContain(chapters)
expect(sent.at(-3).content[0].text).toContain("1 个章节仅含图片")
expect(sent.at(-3).content[1]).toEqual({ type: "image_url", image_url: { url: image.data } })
expect(sent.at(-1).content).toContain("What changed?")
expect(sent.at(-1).content).toContain("broken.epub:damaged")
expect(page.warnings).toEqual(["旧附件未发送。broken.epub:damaged"])
expect(JSON.stringify(sent).match(/The lamp goes out/g)).toHaveLength(1)
expect(JSON.stringify(sent)).not.toContain("Ym9vaw==")
expect(history[0].content).toBe("")
expect(history[0].files[0].data).toBe(file.data)
})
test("switching chats discards a book that is still being read", async () => {
const page = chatPage(`
updateSend = renderAttachments = renderMessages = renderSessions = scrollBottom = () => {};
api = async () => ({ id: "other", messages: [] });
readAsDataURL = () => globalThis.reading;
globalThis.pending = () => pendingBooks;
`)
const reading = Promise.withResolvers()
page.reading = reading.promise
page.MagpieEpub.read = async () => ({ text: "A page", characters: 5 })
page.state.attachments.push({ name: "ready.epub" })
const job = page.addFiles([{ name: "first.epub", type: "application/epub+zip", size: 12 }])
expect(page.pending()).toBe(1)
page.openConversation("other")
await Promise.resolve()
reading.resolve("data:;base64,Ym9vaw==")
await job
expect(page.state.convId).toBe("other")
expect(page.state.attachments).toHaveLength(0)
expect(page.pending()).toBe(0)
})
test("conversations save and list with the token", async () => { test("conversations save and list with the token", async () => {
const h = { ...json, origin: "null", "x-magpie-chat-token": token } const h = { ...json, origin: "null", "x-magpie-chat-token": token }
const saved = JSON.parse((await raw("POST", "/api/conversations", h, { title: "t", messages: [{ role: "user", content: "x" }] })).body) const saved = JSON.parse((await raw("POST", "/api/conversations", h, { title: "t", messages: [{ role: "user", content: "x" }] })).body)
+77 -28
View File
@@ -672,7 +672,8 @@ function parseEventBlock(block) {
return data; 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", { return fetch("api/chat", {
method: "POST", method: "POST",
headers: authHeaders({ "content-type": "application/json" }), headers: authHeaders({ "content-type": "application/json" }),
@@ -972,14 +973,26 @@ function readAsDataURL(file) {
function guessType(file) { function guessType(file) {
if (file.type) return file.type; if (file.type) return file.type;
var ext = String(file.name || "").split(".").pop().toLowerCase(); 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"; return map[ext] || "application/octet-stream";
} }
// 一批 File → 加入待发送列表 // 一批 File → 加入待发送列表
var attachmentContext = 0, pendingBooks = 0;
function clearPendingAttachments() {
attachmentContext++;
pendingBooks = 0;
state.attachments = [];
renderAttachments();
}
function addFiles(files) { function addFiles(files) {
var list = Array.from(files || []).slice(0, 8); var list = Array.from(files || []).slice(0, 8);
if (!list.length) return Promise.resolve(); 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 jobs = list.map(function (file) {
var type = guessType(file); var type = guessType(file);
var isImage = /^image\//.test(type); var isImage = /^image\//.test(type);
@@ -987,7 +1000,11 @@ function addFiles(files) {
toast((isImage ? "图片" : "文件") + "太大:" + (file.name || ""), true); toast((isImage ? "图片" : "文件") + "太大:" + (file.name || ""), true);
return null; 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", { return api("api/upload", {
method: "POST", method: "POST",
body: { name: file.name || "file", type: type, data: data, clientType: type } body: { name: file.name || "file", type: type, data: data, clientType: type }
@@ -995,11 +1012,19 @@ function addFiles(files) {
// 上传接口挂了也还能本地显示:直接按 data URL 用 // 上传接口挂了也还能本地显示:直接按 data URL 用
return { name: file.name || "file", type: type, kind: isImage ? "image" : "file", size: data.length, data: data }; 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); }).filter(Boolean);
return Promise.all(jobs).then(function (out) { return Promise.all(jobs).then(function (out) {
if (context !== attachmentContext) return;
out.forEach(function (f) { if (f && f.data) state.attachments.push(f); }); out.forEach(function (f) { if (f && f.data) state.attachments.push(f); });
renderAttachments(); 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 || "" })); 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() })); 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 || "文件" })); 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": "移除" }); var rm = el("button", { class: "rm", type: "button", title: "移除", "aria-label": "移除" });
rm.appendChild(el("span", { text: "\u00d7" })); rm.appendChild(el("span", { text: "\u00d7" }));
rm.addEventListener("click", function () { rm.addEventListener("click", function () {
@@ -1461,6 +1487,7 @@ function askDelete(id, title) {
state.settings.pinned = pinned; state.settings.pinned = pinned;
api("api/settings", { method: "POST", body: { pinned: pinned } }).catch(function () {}); api("api/settings", { method: "POST", body: { pinned: pinned } }).catch(function () {});
if (state.convId === id) { if (state.convId === id) {
clearPendingAttachments();
state.convId = null; state.convId = null;
state.title = "新对话"; state.title = "新对话";
state.messages = []; state.messages = [];
@@ -1488,6 +1515,7 @@ function openConversation(id) {
dropBlankDraft(); // 切换到别的对话时,空着的"新对话"不该留在列表里 dropBlankDraft(); // 切换到别的对话时,空着的"新对话"不该留在列表里
api("api/conversations/" + encodeURIComponent(id)).then(function (conv) { api("api/conversations/" + encodeURIComponent(id)).then(function (conv) {
if (!conv) return; if (!conv) return;
if (state.convId !== conv.id) clearPendingAttachments();
state.convId = conv.id; state.convId = conv.id;
state.title = conv.title || "新对话"; state.title = conv.title || "新对话";
state.messages = (conv.messages || []).map(normalizeMessage); state.messages = (conv.messages || []).map(normalizeMessage);
@@ -1789,7 +1817,7 @@ function mediaBlock(files, opts) {
} else { } else {
wrap.appendChild(el("span", { class: "msg-file", title: f.name || "" }, wrap.appendChild(el("span", { class: "msg-file", title: f.name || "" },
el("span", { class: "nm", text: 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 btn = $("#send");
var input = $("#input"); var input = $("#input");
$("#app").classList.toggle("busy", state.busy); $("#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 ? "停止生成" : "发送"); btn.setAttribute("aria-label", state.busy ? "停止生成" : "发送");
input.title = state.busy ? "生成中…(Esc 停止)" : "Enter 发送 · Shift+Enter 换行"; 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() { function send() {
if (state.busy) { stop(); return; } if (state.busy) { stop(); return; }
if (pendingBooks) { toast("电子书还在读取,请稍候。"); return; }
var input = $("#input"); var input = $("#input");
var text = input.value.trim(); var text = input.value.trim();
if (!text && !(state.attachments || []).length) return; if (!text && !(state.attachments || []).length) return;
if (!state.settings.model) { toast("先选一个模型", true); return; } if (!state.settings.model) { toast("先选一个模型", true); return; }
var files = (state.attachments || []).map(function (f) { 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 }; var userMsg = { role: "user", content: text, reasoning: "", toolCalls: [], files: files };
state.attachments = []; state.attachments = [];
@@ -2150,7 +2218,7 @@ function send() {
state.messages.push(userMsg, asstMsg); state.messages.push(userMsg, asstMsg);
if (!state.convId && state.title === "新对话") { 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)。 // 等保存成功再把它换成真正的对话条目(见 persistConversation)。
@@ -2177,28 +2245,8 @@ function send() {
updateSend(); updateSend();
scrollBottom(true); 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 = { var payload = {
messages: history, messages: state.messages.slice(0, -1),
model: state.settings.model, model: state.settings.model,
effort: state.settings.effort || "", effort: state.settings.effort || "",
system: state.settings.systemEnabled === false ? "" : (state.settings.system || ""), system: state.settings.systemEnabled === false ? "" : (state.settings.system || ""),
@@ -2461,6 +2509,7 @@ function newChat() {
if (state.busy) { toast("正在生成,先停止再新建对话", true); return; } if (state.busy) { toast("正在生成,先停止再新建对话", true); return; }
// 已经在一个空白的新对话里了:再点"新对话"就保持原样,别叠出第二个 // 已经在一个空白的新对话里了:再点"新对话"就保持原样,别叠出第二个
if (isBlankDraft()) { $("#input").focus(); return; } if (isBlankDraft()) { $("#input").focus(); return; }
clearPendingAttachments();
state.draft = { id: DRAFT_ID, title: "新对话", updated: Date.now() }; state.draft = { id: DRAFT_ID, title: "新对话", updated: Date.now() };
state.convId = null; state.convId = null;
state.title = "新对话"; 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 class="toast" id="toast" role="status" aria-live="polite" hidden><span id="toastText"></span></div>
</div> </div>
<script src="vendor/katex/katex.min.js" defer></script> <script src="vendor/katex/katex.min.js" defer></script>
<script src="epub-reader.js" defer></script>
<script src="app.js" defer></script> <script src="app.js" defer></script>
</body> </body>
</html> </html>
+140
View File
@@ -0,0 +1,140 @@
import { expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { crc32, deflateRawSync } from "node:zlib";
import "./chat/epub-reader.js";
function zip(files) {
const local = [], central = [];
let offset = 0;
for (const [path, contents, method = 8, declaredSize] of files) {
const name = Buffer.from(path), body = Buffer.from(contents);
const data = method === 8 ? deflateRawSync(body) : body;
const l = Buffer.alloc(30), c = Buffer.alloc(46);
l.writeUInt32LE(0x04034b50); c.writeUInt32LE(0x02014b50);
for (const [header, shift] of [[l, 0], [c, 2]]) {
header.writeUInt16LE(20, 4 + shift);
header.writeUInt16LE(method, 8 + shift);
header.writeUInt32LE(crc32(body), 14 + shift);
header.writeUInt32LE(data.length, 18 + shift);
header.writeUInt32LE(declaredSize ?? body.length, 22 + shift);
header.writeUInt16LE(name.length, 26 + shift);
}
c.writeUInt32LE(offset, 42);
local.push(l, name, data); central.push(c, name);
offset += l.length + name.length + data.length;
}
const index = Buffer.concat(central), end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50);
end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16);
return "data:application/epub+zip;base64," + Buffer.concat([...local, index, end]).toString("base64");
}
function book(chapters, extras = []) {
const manifest = chapters.map(([href, , type = "application/xhtml+xml"], i) =>
`<item id="c${i}" href="${href}" media-type="${type}"/>`).join("");
const spine = chapters.map((_, i) => `<itemref idref="c${i}"/>`).join("");
return zip([
["mimetype", "application/epub+zip", 0],
["META-INF/container.xml", '<container><rootfiles><rootfile full-path="OPS/package/book.opf"/></rootfiles></container>'],
["OPS/package/book.opf", `<package><manifest>${manifest}</manifest><spine>${spine}</spine></package>`],
...[...chapters].reverse().filter(([, source]) => source != null).map(([href, source, , method]) =>
[decodeURIComponent(new URL(href, "https://archive/OPS/package/book.opf").pathname).slice(1), source, method]),
...extras
]);
}
test("EPUB recognition, malformed ZIPs and false uncompressed sizes", async () => {
const { isEpub, read } = globalThis.MagpieEpub;
expect(isEpub({ name: "文章.EPUB", type: "application/octet-stream" })).toBe(true);
expect(isEpub({ type: "application/epub+zip" })).toBe(true);
expect(isEpub({ name: "文章.pdf" })).toBe(false);
await expect(read("data:;base64,UEs=")).rejects.toThrow("损坏");
await expect(read("data:;base64," + "A".repeat(4 * Math.ceil((8 * 1024 * 1024) / 3) + 4))).rejects.toThrow("8 MiB");
const stored = zip([["META-INF/container.xml", "original", 0]]);
const bytes = Buffer.from(stored.split(",")[1], "base64");
bytes[bytes.indexOf("original")] ^= 1;
await expect(read("data:;base64," + bytes.toString("base64"))).rejects.toThrow("损坏");
await expect(read(zip([["META-INF/container.xml", "x".repeat(50000), 8, 1]]))).rejects.toThrow("损坏");
await expect(read(zip([["META-INF/container.xml", "x", 8, 25 * 1024 * 1024]]))).rejects.toThrow("太大");
});
// CI uses its installed browser; EPUB_TEST_BROWSER can select another Chromium executable.
const browserPath = process.env.EPUB_TEST_BROWSER || ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
.map(name => Bun.which(name)).find(Boolean);
test.skipIf(!browserPath && !process.env.CI)("reads complete books in spine order without loading external resources", async () => {
if (!browserPath) throw new Error("Browser tests need Chrome or Chromium in PATH, or EPUB_TEST_BROWSER.");
const xhtml = text => `<html xmlns="http://www.w3.org/1999/xhtml"><body>${text}</body></html>`;
const first = "../text/第%20一.xhtml#start", second = "../text/2.html";
const fixtures = {
mixed: book([
[first, xhtml('<p>红<b>楼</b>梦𠀀。</p><img src="/unexpected"/><script>window.injected = true</script><style>隐藏</style>'), undefined, 0],
[second, '<html><head><title>书名不该进入正文</title></head><body><p>次<b>章</b>。<p>有 空格<br>下一行<img src="/unexpected"><iframe src="/unexpected"></iframe></body></html>', "text/html"]
], [["META-INF/encryption.xml", '<encryption><CipherReference URI="OPS/font.otf"/></encryption>']]),
duplicates: book([[first, xhtml("<p>同文</p>")], ["../text/./第%20一.xhtml#end", null],
["../text/second.xhtml", xhtml("<p>同文</p>")]]),
hybrid: book([
["../cover.xhtml", xhtml('<svg xmlns="http://www.w3.org/2000/svg"><image href="cover.jpg"/></svg>')],
[first, xhtml("<p>可读正文</p>")],
["../text/scanned.html", '<img src="/unexpected">', "text/html"],
["../text/scanned.html#bottom", null, "text/html"],
["../text/blank.xhtml", xhtml("<p> </p>")]
]),
legacy: book([[first, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "/unexpected"><html><body><p>古&nbsp;籍&mdash;𠀀&#133;完</p><p><![CDATA[&nbsp;]]></p></body></html>']]),
long: book([[first, xhtml("<p>" + "文".repeat(100000) + "末</p>")]]),
missing: book([[first, xhtml("<p>第一页</p>")], [second, null]]),
locked: book([[first, xhtml("<p>加密章节</p>")]], [["META-INF/encryption.xml",
'<encryption><CipherReference URI="OPS/text/第%20一.xhtml"/></encryption>']]),
invalid: book([[first, "<html><body><p>坏了</body></html>"]]),
unterminated: book([[first, "<html><body>" + "<!--".repeat(50000) + "&nbsp;"]]),
empty: book([[first, xhtml('<img src="/unexpected"/>')]]),
oversized: book([[first, xhtml("<p>" + "x".repeat(2 * 1024 * 1024 + 1) + "</p>")]])
};
const { promise, resolve } = Promise.withResolvers();
const requested = [];
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) {
const path = new URL(req.url).pathname;
if (path === "/reader.js") return new Response(Bun.file(join(import.meta.dir, "chat/epub-reader.js")));
if (path === "/result") { resolve(await req.json()); return new Response("ok"); }
if (path === "/") return new Response(`<!DOCTYPE html><meta charset="utf-8"><script src="/reader.js"></script><script>
(async () => {
const result = {};
for (const [name, url] of Object.entries(${JSON.stringify(fixtures)})) {
try {
const { text, characters, imagePages } = await MagpieEpub.read(url);
result[name] = { text: text.length > 1000 ? text.slice(-1) : text, characters, imagePages };
} catch (e) { result[name] = e.message; }
}
result.injected = !!window.injected;
await fetch('/result', {method:'POST', body:JSON.stringify(result)});
})();
</script>`, { headers: { "Content-Type": "text/html" } });
requested.push(path);
return new Response("", { status: 404 });
} });
const profile = mkdtempSync(join(tmpdir(), "magpie-epub-browser-"));
const proc = Bun.spawn([browserPath, "--headless", "--disable-gpu", "--disable-background-networking",
"--no-first-run", "--user-data-dir=" + profile, String(server.url)], { stdout: "ignore", stderr: "ignore" });
try {
const result = await Promise.race([promise, proc.exited.then(() => { throw new Error("browser exited"); }),
new Promise((_, reject) => setTimeout(() => reject(new Error("browser timed out")), 15000).unref())]);
expect(result.mixed).toEqual({ text: "红楼梦𠀀。\n\n次章。\n\n有 空格\n\n下一行", characters: 14, imagePages: 0 });
expect(result.duplicates).toEqual({ text: "同文\n\n同文", characters: 4, imagePages: 0 });
expect(result.hybrid).toEqual({ text: "可读正文", characters: 4, imagePages: 2 });
expect(result.legacy).toEqual({ text: "古 籍—𠀀 完\n\n&nbsp;", characters: 11, imagePages: 0 });
expect(result.long).toEqual({ text: "末", characters: 100001, imagePages: 0 });
expect(result.missing).toContain("损坏");
expect(result.locked).toContain("已加密");
expect(result.invalid).toContain("损坏");
expect(result.unterminated).toContain("损坏");
expect(result.empty).toContain("没有可读取的文字");
expect(result.oversized).toContain("太大");
expect(result.injected).toBe(false);
expect(requested).not.toContain("/unexpected");
} finally {
proc.kill(); await proc.exited; await server.stop(true);
rmSync(profile, { recursive: true, force: true });
}
}, 20000);
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@magpie-community/page-chat", "name": "@magpie-community/page-chat",
"version": "0.1.8", "version": "0.1.9",
"description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.", "description": "在 magpie 窗口里加一个「对话」页面:用 magpie 自己的模型、MCP 服务器、指令和技能聊天,支持图片与 LaTeX。A chat page inside magpie's window: talk with magpie's own models, MCP servers, instructions and skills, with images and LaTeX.",
"author": "Magic_zero (https://github.com/Magiczerowxy)", "author": "Magic_zero (https://github.com/Magiczerowxy)",
"files": [ "files": [