Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(library): read many conversations' apps through messages_app (#7206)
Milind Soni66a5c0860acb
diff --git a/server/bot-library.test.ts b/server/bot-library.test.tsindex 1971df6dae..c8d6352475 100644--- a/server/bot-library.test.ts+++ b/server/bot-library.test.ts@@ -1,7 +1,7 @@import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { describe, expect, it } from "vitest";-import { collectBotLibrary, LIBRARY_FILE_REPLIES_SQL, messageRows, replyFileLinks } from "./bot-library.ts";+import { APPS_BY_THREAD_MAX, collectBotLibrary, LIBRARY_APPS_BY_THREAD_SQL, LIBRARY_APPS_SQL, 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";@@ -89,6 +89,32 @@ describe("Library file replies", () => {});});+describe("Library apps", () => {+ // The query before apps were read from messages_app: the result must stay the same, row for row.+ const THREAD_SCAN_SQL = `SELECT thread_id AS threadId, id AS messageId, at, json_extract(json, '$.app.title') AS title FROM messages+ WHERE thread_id IN (SELECT value FROM json_each(?)) AND kind = 'app' AND coalesce(json_extract(json, '$.app.doc'), '') <> '' ORDER BY at DESC, rowid LIMIT ?`;++ it("reads many conversations' apps through messages_app, a few row by row, with the rows and order of the conversation scan", () => {+ importThread("apps-a", [app("pa1", 500, "Same time"), reply("pr1", 505, "[plan](./plan.md)"), app("pa2", 500, "Same time too"), app("pa3", 510, "Empty", "")], "pa3");+ importThread("apps-b", [app("pb1", 500, "Other thread, same time"), app("pb2", 520, "Newest")], "pb2");+ importThread("apps-hidden", [app("ph1", 530, "Hidden from this viewer")], "ph1");+ importThread("apps-none", [reply("pn1", 540, "No apps here.")], "pn1");+ // Past APPS_BY_THREAD_MAX conversations the other plan runs; conversations with no rows pad the list.+ const many = (ids: string[]) => [...ids, ...Array.from({ length: APPS_BY_THREAD_MAX }, (_, i) => `apps-gone-${i}`)];+ for (const ids of [["apps-a", "apps-b"], ["apps-none"], ["apps-gone"], []]) {+ for (const threadIds of [ids, many(ids)]) {+ for (const limit of [400, 2]) expect(messageRows.apps(threadIds, limit)).toEqual(prepared(THREAD_SCAN_SQL).all(JSON.stringify(threadIds), limit));+ }+ }+ expect(messageRows.apps(many(["apps-a", "apps-b"]), 400).map((row) => row.messageId)).toEqual(["pb2", "pa1", "pa2", "pb1"]);+ expect(messageRows.apps(["apps-a", "apps-b"], 400).map((row) => row.messageId)).toEqual(["pb2", "pa1", "pa2", "pb1"]);+ expect(messageRows.apps(["apps-none"], 400)).toEqual([]);+ const plan = (sql: string) => prepared(`EXPLAIN QUERY PLAN ${sql}`).all(JSON.stringify(["apps-a"]), 400).map((row) => row.detail).join("\n");+ expect(plan(LIBRARY_APPS_SQL)).toContain("USING INDEX messages_app");+ expect(plan(LIBRARY_APPS_BY_THREAD_SQL)).toContain("USING INDEX messages_thread");+ });+});+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 d266e2d316..d1151f1dca 100644--- a/server/bot-library.ts+++ b/server/bot-library.ts@@ -23,11 +23,18 @@ export const LIBRARY_FILE_REPLIES_SQL = `WHERE ${IN_THREADS} AND ${LIBRARY_FILE_REPLY_FILTER}ORDER BY at DESC, rowid LIMIT ?`;+const APPS_WHERE = "kind = 'app' AND coalesce(json_extract(json, '$.app.doc'), '') <> '' ORDER BY at DESC, rowid LIMIT ?";+const APPS_SELECT = "SELECT thread_id AS threadId, id AS messageId, at, json_extract(json, '$.app.title') AS title FROM messages";+/** A few conversations are read row by row (messages_thread). Past APPS_BY_THREAD_MAX of them that reads far more rows+ * than there are apps (10 s for 1,000 conversations of a 2 GB store), so the apps are read from their own partial+ * index (messages_app), newest first; the unary + keeps SQLite from choosing messages_thread. Same rows, same order. */+export const APPS_BY_THREAD_MAX = 32;+export const LIBRARY_APPS_BY_THREAD_SQL = `${APPS_SELECT} WHERE ${IN_THREADS} AND ${APPS_WHERE}`;+export const LIBRARY_APPS_SQL = `${APPS_SELECT} WHERE +${IN_THREADS} AND ${APPS_WHERE}`;+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 messages- WHERE ${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"]>,+ apps: (threadIds, limit) => prepared(threadIds.length > APPS_BY_THREAD_MAX ? LIBRARY_APPS_SQL : LIBRARY_APPS_BY_THREAD_SQL)+ .all(JSON.stringify(threadIds), limit) as ReturnType<BotLibraryRows["apps"]>,fileReplies: (threadIds, limit) =>prepared(LIBRARY_FILE_REPLIES_SQL).all(JSON.stringify(threadIds), limit) as ReturnType<BotLibraryRows["fileReplies"]>,};