Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: match Unicode case consistently in message search
Afloatab24b7529e71
diff --git a/server/message-search-query.ts b/server/message-search-query.tsindex 2ef713bf66..0f62784722 100644--- a/server/message-search-query.ts+++ b/server/message-search-query.ts@@ -12,15 +12,34 @@ export interface SearchHit {from?: string;}+function matchSpan(text: string, needle: string): { start: number; length: number } | null {+ const folded = text.toLowerCase();+ const hit = folded.indexOf(needle);+ if (hit < 0) return null;+ if (folded.length === text.length) return { start: hit, length: needle.length };+ let at = 0, foldedAt = 0, start: number | undefined;+ for (const character of text) {+ const next = at + character.length;+ const foldedNext = foldedAt + character.toLowerCase().length;+ if (start === undefined && hit < foldedNext) start = at;+ if (hit + needle.length <= foldedNext) return { start: start!, length: next - start! };+ at = next;+ foldedAt = foldedNext;+ }+ return null;+}+export function searchMessagesInDatabase(database: DatabaseSync, query: string, limit = 40, threadId?: string): SearchHit[] {const needle = query.trim().toLowerCase();if (!needle) return [];+ // SQLite's built-in lower() folds ASCII only; match the query and snippet's Unicode lowercase rules.+ database.function("omb_search_lower", { deterministic: true }, (value) => typeof value === "string" ? value.toLowerCase() : null);const pattern = `%${needle.replace(/([\\%_])/g, "\\$1")}%`;const scope = threadId ? "thread_id = ? AND " : "";const statement = database.prepare("SELECT thread_id, id, at, role, kind, text, json_extract(json, '$.tool.name') AS tool_name, json_extract(json, '$.from.name') AS from_name FROM messages " +- `WHERE ${scope}((kind = 'text' AND text IS NOT NULL AND lower(text) LIKE ? ESCAPE '\\') ` +- " OR (kind = 'activity' AND tool_name IS NOT NULL AND lower(tool_name) LIKE ? ESCAPE '\\')) " ++ `WHERE ${scope}((kind = 'text' AND text IS NOT NULL AND omb_search_lower(text) LIKE ? ESCAPE '\\') ` ++ " OR (kind = 'activity' AND tool_name IS NOT NULL AND omb_search_lower(tool_name) LIKE ? ESCAPE '\\')) " +"ORDER BY at DESC LIMIT ?",);const rows = (threadId@@ -37,14 +56,14 @@ export function searchMessagesInDatabase(database: DatabaseSync, query: string,}>;return rows.map((row) => {const haystack = row.kind === "activity" ? (row.tool_name ?? "") : (row.text ?? "");- const hitAt = Math.max(0, haystack.toLowerCase().indexOf(needle));- const start = Math.max(0, hitAt - 60);- const end = Math.min(haystack.length, hitAt + needle.length + 90);+ const hit = matchSpan(haystack, needle) ?? { start: 0, length: 0 };+ const start = Math.max(0, hit.start - 60);+ const end = Math.min(haystack.length, hit.start + hit.length + 90);const head = start > 0 ? "…" : "";const body = haystack.slice(start, end).replace(/\s+/g, " ").trim();const snippet = head + body + (end < haystack.length ? "…" : "");const folded = needle.replace(/\s+/g, " ");- const matchStart = snippet.toLowerCase().indexOf(folded);+ const match = matchSpan(snippet, folded);return {threadId: row.thread_id,messageId: row.id,@@ -52,8 +71,8 @@ export function searchMessagesInDatabase(database: DatabaseSync, query: string,role: row.role,kind: row.kind,snippet,- matchStart: matchStart < 0 ? head.length : matchStart,- matchLength: matchStart < 0 ? 0 : folded.length,+ matchStart: match?.start ?? head.length,+ matchLength: match?.length ?? 0,...(row.from_name ? { from: row.from_name } : {}),};});diff --git a/server/message-search-unicode.test.ts b/server/message-search-unicode.test.tsnew file mode 100644index 0000000000..bdf50a4d92--- /dev/null+++ b/server/message-search-unicode.test.ts@@ -0,0 +1,44 @@+import { mkdirSync, rmSync } from "node:fs";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { DATA_DIR } from "./config.ts";+import { closeMessageDb, closeMessageSearch, insertMessage, searchMessages, searchMessagesAsync } from "./message-db.ts";++beforeEach(async () => {+ await closeMessageSearch();+ closeMessageDb();+ rmSync(DATA_DIR, { recursive: true, force: true });+ mkdirSync(DATA_DIR, { recursive: true });+});+afterEach(async () => { await closeMessageSearch(); closeMessageDb(); });++describe("case-insensitive message search outside ASCII", () => {+ it.each([+ ["ÉCOLE", "école"], ["МОСКВА", "москва"], ["ΑΘΉΝΑ", "αθήνα"], ["ÜBER", "über"],+ ])("finds %s with %s in text and tool names", async (stored, query) => {+ insertMessage("text", { id: "m1", at: 1, role: "user", kind: "text", text: `Discuss ${stored} today` });+ insertMessage("tools", { id: "m2", at: 2, role: "bot", kind: "activity", tool: { name: `Search ${stored}`, ok: true } });+ const hits = searchMessages(query);+ expect(hits.map((one) => one.messageId)).toEqual(["m2", "m1"]);+ expect(hits.map((one) => one.snippet.slice(one.matchStart, one.matchStart + one.matchLength))).toEqual([stored, stored]);+ expect(await searchMessagesAsync(query)).toEqual(hits);+ expect(searchMessages(query, 1, "text").map((one) => one.messageId)).toEqual(["m1"]);+ });++ it("keeps highlights in original string coordinates when lowercasing expands a character", async () => {+ insertMessage("text", { id: "m", at: 1, role: "user", kind: "text", text: "İ prefix İSTANBUL after" });+ for (const [query, match] of [["prefix", "prefix"], ["İSTANBUL", "İSTANBUL"], ["after", "after"]]) {+ const hits = await searchMessagesAsync(query!);+ expect(hits).toHaveLength(1);+ const hit = hits[0]!;+ expect(hit.snippet.slice(hit.matchStart, hit.matchStart + hit.matchLength)).toBe(match);+ }+ });++ it("preserves literal wildcard matching and limits for non-ASCII text", async () => {+ insertMessage("text", { id: "literal", at: 1, role: "user", kind: "text", text: "ÉCOLE 10%_\\ fee" });+ insertMessage("text", { id: "decoy", at: 2, role: "user", kind: "text", text: "ÉCOLE 100xx fee" });+ expect((await searchMessagesAsync("école 10%_\\")).map((one) => one.messageId)).toEqual(["literal"]);+ expect((await searchMessagesAsync("école", 1)).map((one) => one.messageId)).toEqual(["decoy"]);+ });+});