Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf: 加快 Bot Library 文件查询
Zhehui Bi5179f8410871
diff --git a/server/bot-library.test.ts b/server/bot-library.test.tsindex 16da7d139a..1971df6dae 100644--- a/server/bot-library.test.ts+++ b/server/bot-library.test.ts@@ -1,6 +1,9 @@+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";import { describe, expect, it } from "vitest";-import { collectBotLibrary, replyFileLinks } from "./bot-library.ts";-import { deleteThread, importThread } from "./message-db.ts";+import { collectBotLibrary, LIBRARY_FILE_REPLIES_SQL, messageRows, replyFileLinks } from "./bot-library.ts";+import { DATA_DIR } from "./config.ts";+import { closeMessageDb, deleteThread, importThread, prepared, updateMessage } from "./message-db.ts";import type { PublishedPageRecord } from "./pages/store.ts";import type { Message } from "./store.ts";@@ -58,6 +61,34 @@ describe("collectBotLibrary", () => {});});+describe("Library file replies", () => {+ it("indexes existing replies on reopen and picks up a file attached to an older reply", () => {+ const attachment = { kind: "file" as const, path: "/work/out.csv", mime: "text/csv", name: "out.csv" };+ const draft = reply("draft", 20, "The report is ready.");+ importThread("file-index-a", [reply("link", 10, "[plan](./plan.md)"), draft], draft.id);+ importThread("file-index-b", [reply("attached", 10, "", { text: undefined, attachments: [attachment] })], "attached");+ importThread("file-index-private", [reply("private", 30, "[notes](./notes.md)")], "private");++ closeMessageDb();+ const previous = new DatabaseSync(join(DATA_DIR, "messages.db"));+ try {+ previous.exec("DROP INDEX IF EXISTS messages_library_file_replies");+ } finally {+ previous.close();+ }++ const threadIds = ["file-index-a", "file-index-b"];+ const plan = prepared(`EXPLAIN QUERY PLAN ${LIBRARY_FILE_REPLIES_SQL}`).all(JSON.stringify(threadIds), 600);+ expect(plan.map((row) => row.detail).join("\n")).toContain("USING INDEX messages_library_file_replies");+ expect(messageRows.fileReplies(threadIds, 600).map((row) => row.messageId)).toEqual(["link", "attached"]);++ updateMessage("file-index-a", { ...draft, attachments: [attachment] });+ expect(messageRows.fileReplies(threadIds, 2).map((row) => row.messageId)).toEqual(["draft", "link"]);+ deleteThread("file-index-a");+ expect(messageRows.fileReplies(threadIds, 600).map((row) => row.messageId)).toEqual(["attached"]);+ });+});+describe("replyFileLinks", () => {it("keeps local links and reference links as authored, never web links, anchors or images", () => {const text = "[a](/Users/me/a.md) [b](<./b c.txt>) [web](https://x.dev/a.md) [top](#top)  [](/work/b.html)"diff --git a/server/bot-library.ts b/server/bot-library.tsindex b2630f1197..b0cdf89dfa 100644--- a/server/bot-library.ts+++ b/server/bot-library.ts@@ -4,7 +4,7 @@import { fromMarkdown } from "mdast-util-from-markdown";import { BOT_LIBRARY_MAX, type BotLibrary, type BotLibraryApp, type BotLibraryFileMessage, type BotLibraryPage } from "../shared/bot-library.ts";import { windowsPathDestinations } from "../shared/markdown-windows-paths.ts";-import { prepared } from "./message-db.ts";+import { LIBRARY_FILE_REPLY_FILTER, prepared } from "./message-db.ts";import type { PublishedPageRecord } from "./pages/store.ts";/** Replies read for file links, newest first; most replies share nothing, so this reads well past the files shown. */@@ -17,17 +17,18 @@ export interface BotLibraryRows {const IN_THREADS = "thread_id IN (SELECT value FROM json_each(?))";+export const LIBRARY_FILE_REPLIES_SQL = `+ SELECT thread_id AS threadId, id AS messageId, at, text, json_extract(json, '$.attachments') AS attachments FROM messages+ WHERE ${IN_THREADS} AND ${LIBRARY_FILE_REPLY_FILTER}+ ORDER BY at DESC, rowid LIMIT ?`;+export const messageRows: BotLibraryRows = {apps: (threadIds, limit) => prepared(`SELECT thread_id AS threadId, id AS messageId, at, json_extract(json, '$.app.title') AS title FROM messagesWHERE ${IN_THREADS} AND kind = 'app' AND coalesce(json_extract(json, '$.app.doc'), '') <> '' ORDER BY at DESC, rowid LIMIT ?`,).all(JSON.stringify(threadIds), limit) as ReturnType<BotLibraryRows["apps"]>,- fileReplies: (threadIds, limit) => prepared(- `SELECT thread_id AS threadId, id AS messageId, at, text, json_extract(json, '$.attachments') AS attachments FROM messages- WHERE ${IN_THREADS} AND role = 'bot' AND kind = 'text'- AND (instr(text, '](') > 0 OR instr(text, ']:') > 0 OR instr(text, '<file:') > 0 OR json_extract(json, '$.attachments') IS NOT NULL)- ORDER BY at DESC, rowid LIMIT ?`,- ).all(JSON.stringify(threadIds), limit) as ReturnType<BotLibraryRows["fileReplies"]>,+ fileReplies: (threadIds, limit) =>+ prepared(LIBRARY_FILE_REPLIES_SQL).all(JSON.stringify(threadIds), limit) as ReturnType<BotLibraryRows["fileReplies"]>,};type MarkdownNode = { type: string; url?: string; identifier?: string; children?: MarkdownNode[] };diff --git a/server/message-db.ts b/server/message-db.tsindex 76e7ddcc9e..455eee0c74 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -22,6 +22,8 @@ const DB_FILE = () => join(DATA_DIR, "messages.db");const WORK_KINDS = "kind IN ('activity', 'digest', 'options')";const CARD_KINDS = "kind IN ('secret', 'signin', 'connector')";const FAILED_CALL = "kind = 'activity' AND instr(json, '\"ok\":false') > 0";+export const LIBRARY_FILE_REPLY_FILTER = `role = 'bot' AND kind = 'text'+ AND (instr(text, '](') > 0 OR instr(text, ']:') > 0 OR instr(text, '<file:') > 0 OR json_extract(json, '$.attachments') IS NOT NULL)`;/** The rows that order the thread list and the time each one counts at. SQLite uses messages_thread_order only for a* statement whose WHERE and MAX repeat these texts exactly. */const ORDERING_ROW = "((role = 'user' AND json_extract(json, '$.peerAsk') IS NULL) OR (role = 'bot' AND kind = 'text' AND (json_extract(json, '$.turnTerminal') = 1 OR json_extract(json, '$.turnId') IS NULL)))";@@ -63,6 +65,7 @@ function open(): DatabaseSync {CREATE INDEX IF NOT EXISTS messages_thread_at ON messages(thread_id, at);-- Partial, so no other query's plan can move onto them: only a statement that repeats the WHERE may use one.CREATE INDEX IF NOT EXISTS messages_thread_bot_text ON messages(thread_id, at) WHERE kind = 'text' AND role = 'bot' AND text IS NOT NULL;+ CREATE INDEX IF NOT EXISTS messages_library_file_replies ON messages(thread_id, role) WHERE ${LIBRARY_FILE_REPLY_FILTER};CREATE INDEX IF NOT EXISTS messages_thread_order ON messages(thread_id, ${ORDERING_AT}) WHERE ${ORDERING_ROW};CREATE INDEX IF NOT EXISTS messages_work_at ON messages(kind, at) WHERE ${WORK_KINDS};CREATE INDEX IF NOT EXISTS messages_cards_at ON messages(kind, at) WHERE ${CARD_KINDS};