Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chat): export the full paged conversation
Afloat2e7ec3c7ab71
diff --git a/src/components/ChatMoreMenu.tsx b/src/components/ChatMoreMenu.tsxindex 379276a6cd..7424590dad 100644--- a/src/components/ChatMoreMenu.tsx+++ b/src/components/ChatMoreMenu.tsx@@ -8,9 +8,9 @@ import { usageSummary } from "@/lib/chat-usage-summary";import {copyTranscriptToClipboard,downloadMarkdownTranscript,- formatTranscriptMarkdown,slugifyTranscriptFilename,} from "@/lib/export-transcript";+import { conversationTranscript } from "@/lib/conversation-transcript";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { localizedTaskTitle } from "@/lib/task-title";@@ -44,7 +44,7 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Siconst hasMessages = messages.length > 0;const contextAction = useContextAction();const atFreshStart = messages.at(-1)?.compaction?.fresh === true;- const transcript = () => formatTranscriptMarkdown({ title: bot.name, messages, botName: bot.name, isGroup: false });+ const transcript = () => conversationTranscript({ threadId: bot.threadId, hasMore: bot.hasMore, title: bot.name, messages, botName: bot.name, isGroup: false });const side = useConversationSide(profile);const threads = showThreads ? [] : orderedThreadList((side ? tasksOfSide(profile, side) : profile.tasks ?? []).filter((task) => !task.routineRunId));const sharing = shareChoices(profile, profile.tasks?.find((task) => task.threadId === bot.threadId), Boolean(useTeamName()));@@ -145,7 +145,12 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Silabel: t("chat.export.download"),icon: <Download size={16} />,disabled: !hasMessages,- onSelect: () => downloadMarkdownTranscript(slugifyTranscriptFilename(bot.name), transcript()),+ onSelect: () => {+ const content = transcript();+ const save = (markdown: string) => downloadMarkdownTranscript(slugifyTranscriptFilename(bot.name), markdown);+ if (typeof content === "string") save(content);+ else void content.then(save).catch((cause) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }));+ },},...(usage ? [{key: "usage",diff --git a/src/components/RoomMoreMenu.tsx b/src/components/RoomMoreMenu.tsxindex 0d0bfc47bf..38fa6cd938 100644--- a/src/components/RoomMoreMenu.tsx+++ b/src/components/RoomMoreMenu.tsx@@ -6,9 +6,9 @@ import { cn } from "@/lib/cn";import {copyTranscriptToClipboard,downloadMarkdownTranscript,- formatTranscriptMarkdown,slugifyTranscriptFilename,} from "@/lib/export-transcript";+import { conversationTranscript } from "@/lib/conversation-transcript";import { t } from "@/lib/i18n";import { localizedTaskTitle } from "@/lib/task-title";import { useShowThreads } from "@/lib/thread-preferences";@@ -33,7 +33,7 @@ function useRoomMoreItems(group: Group): { items: SidebarMenuItem[]; on: booleanconst [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null);const messages = group.messages;const hasMessages = messages.length > 0;- const transcript = () => formatTranscriptMarkdown({ title: group.name, messages, isGroup: true });+ const transcript = () => conversationTranscript({ threadId: group.threadId, hasMore: group.hasMore, title: group.name, messages, isGroup: true });const threads = showThreads ? [] : orderedThreadList(group.tasks ?? []);const usage = groupUsageSummary(group.usage);const items: SidebarMenuItem[] = [@@ -82,7 +82,12 @@ function useRoomMoreItems(group: Group): { items: SidebarMenuItem[]; on: booleanlabel: t("chat.export.download"),icon: <Download size={16} />,disabled: !hasMessages,- onSelect: () => downloadMarkdownTranscript(slugifyTranscriptFilename(group.name), transcript()),+ onSelect: () => {+ const content = transcript();+ const save = (markdown: string) => downloadMarkdownTranscript(slugifyTranscriptFilename(group.name), markdown);+ if (typeof content === "string") save(content);+ else void content.then(save).catch((cause) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }));+ },},{key: "turn-limit",diff --git a/src/components/conversation-export.test.ts b/src/components/conversation-export.test.tsnew file mode 100644index 0000000000..002e7e2156--- /dev/null+++ b/src/components/conversation-export.test.ts@@ -0,0 +1,147 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Bot, Group, Message } from "@/state/store";+import type { SidebarMenuItem } from "./SidebarPopoverMenu";++const fixture = vi.hoisted(() => {+ vi.stubGlobal("window", {});+ return {+ items: [] as SidebarMenuItem[],+ messages: [] as Message[],+ leaf: "",+ api: vi.fn(),+ writeText: vi.fn(async (_text: string) => {}),+ download: vi.fn(),+ dispatch: vi.fn(),+ };+});+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return { ...original, useStore: () => ({ state: original.initialState, dispatch: fixture.dispatch }) };+});+vi.mock("@/state/api", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/state/api")>(), api: fixture.api,+}));+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancedMode: vi.fn() }));+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => false }));+vi.mock("@/lib/chat-find", () => ({ requestChatFind: vi.fn(), useChatFindOpen: () => false }));+vi.mock("./ContextWarning", () => ({ useContextAction: () => ({ pending: false, run: vi.fn() }) }));+vi.mock("@/lib/export-transcript", async (importOriginal) => ({+ ...await importOriginal<typeof import("@/lib/export-transcript")>(), downloadMarkdownTranscript: fixture.download,+}));+vi.mock("./SidebarPopoverMenu", () => ({ SidebarPopoverMenu: ({ items }: { items: SidebarMenuItem[] }) => {+ fixture.items = items;+ return null;+} }));++const { ChatMoreMenu } = await import("./ChatMoreMenu");+const { RoomMoreMenu } = await import("./RoomMoreMenu");++const history = (count: number): Message[] => Array.from({ length: count }, (_, i) => ({+ id: `m-${i}`, parentId: i ? `m-${i - 1}` : null, at: 1_790_000_000_000 + i,+ role: i % 2 ? "bot" : "user", kind: "text", text: `Conversation message ${i.toString().padStart(3, "0")}`,+}));++function action(kind: "bot" | "room", key: "copy" | "download", messages: Message[], hasMore: boolean, identity?: { threadId: string; name: string }) {+ const bot: Bot = { id: "bot", threadId: identity?.threadId ?? "shown-thread", name: identity?.name ?? "Export bot", title: "", description: "", color: "blue",+ notifications: true, unread: false, busy: false, modelSelection: { instanceId: "fixture", model: "fixture" },+ messages, hasMore, activeLeafId: fixture.leaf };+ const room: Group = { id: "room", threadId: identity?.threadId ?? "shown-thread", name: identity?.name ?? "Export room", memberIds: [],+ defaultResponder: { kind: "mentions" }, bulletin: "", unread: false, createdAt: 1, messages, hasMore };+ renderToStaticMarkup(kind === "bot" ? createElement(ChatMoreMenu, { bot }) : createElement(RoomMoreMenu, { group: room }));+ return fixture.items.find((item) => item.key === key)!;+}++beforeEach(() => {+ fixture.messages = history(270);+ fixture.leaf = "m-269";+ fixture.api.mockReset();+ fixture.api.mockImplementation(async (path: string) => {+ const url = new URL(path, "http://fixture");+ expect(url.pathname).toBe("/api/threads/shown-thread/messages");+ const before = url.searchParams.get("before");+ const end = before ? fixture.messages.findIndex((message) => message.id === before) : fixture.messages.length;+ expect(end).toBeGreaterThan(0);+ const start = Math.max(0, end - Number(url.searchParams.get("limit")));+ return { messages: fixture.messages.slice(start, end), hasMore: start > 0, activeLeafId: fixture.leaf };+ });+ fixture.writeText.mockClear();+ fixture.download.mockClear();+ fixture.dispatch.mockClear();+ vi.stubGlobal("navigator", { clipboard: { writeText: fixture.writeText } });+});+afterEach(() => vi.unstubAllGlobals());++async function exported(kind: "bot" | "room", operation: "copy" | "download", messages: Message[], hasMore: boolean) {+ vi.stubGlobal("window", {});+ const item = action(kind, operation, messages, hasMore);+ expect(item.disabled).toBeFalsy();+ item.onSelect();+ const output = operation === "copy" ? fixture.writeText : fixture.download;+ await vi.waitFor(() => expect(output).toHaveBeenCalledOnce());+ return output.mock.calls[0]![operation === "copy" ? 0 : 1] as string;+}++describe("copying and downloading a paged conversation", () => {+ for (const kind of ["bot", "room"] as const) {+ for (const operation of ["copy", "download"] as const) {+ it(`${operation} includes the earlier pages of a ${kind} conversation`, async () => {+ const held = fixture.messages.slice(-80);+ const markdown = await exported(kind, operation, held, true);+ expect(markdown.match(/Conversation message \d{3}/g)).toHaveLength(270);+ expect(markdown.indexOf("Conversation message 000")).toBeLessThan(markdown.indexOf("Conversation message 269"));+ expect(fixture.api).toHaveBeenCalledTimes(2);+ expect(held).toHaveLength(80);+ });++ it(`${operation} uses the held ${kind} conversation when no earlier page exists`, async () => {+ const held = fixture.messages.slice(-2);+ const markdown = await exported(kind, operation, held, false);+ expect(markdown.match(/Conversation message \d{3}/g)).toHaveLength(2);+ expect(fixture.api).not.toHaveBeenCalled();+ });++ it(`${operation} keeps the selected ${kind} metadata when another conversation opens during the read`, async () => {+ const page = Promise.withResolvers<{ messages: Message[]; hasMore: boolean; activeLeafId: string }>();+ fixture.api.mockReturnValueOnce(page.promise);+ vi.stubGlobal("window", {});+ action(kind, operation, fixture.messages.slice(-80), true).onSelect();+ action(kind, operation, [], false, { threadId: "other-thread", name: "Other conversation" });+ page.resolve({ messages: fixture.messages.slice(-200), hasMore: true, activeLeafId: fixture.leaf });+ const output = operation === "copy" ? fixture.writeText : fixture.download;+ await vi.waitFor(() => expect(output).toHaveBeenCalledOnce());+ const markdown = output.mock.calls[0]![operation === "copy" ? 0 : 1] as string;+ expect(markdown).toContain(kind === "bot" ? "# Thread with Export bot" : "# Group: Export room");+ expect(markdown).not.toContain("Other conversation");+ expect(markdown.match(/Conversation message \d{3}/g)).toHaveLength(270);+ expect(fixture.api.mock.calls.every(([path]) => path.startsWith("/api/threads/shown-thread/messages?"))).toBe(true);+ if (operation === "download") expect(output.mock.calls[0]![0]).toMatch(new RegExp(`^export-${kind}-transcript-\\d{4}-\\d{2}-\\d{2}\\.md$`));+ });+ }++ it(`exports only the selected branch after loading all ${kind} pages`, async () => {+ fixture.messages.push({ id: "other-branch", parentId: "m-100", role: "bot", kind: "text", text: "Unselected branch", at: 1_790_000_000_999 });+ const markdown = await exported(kind, "copy", fixture.messages.slice(-80), true);+ expect(markdown.match(/Conversation message \d{3}/g)).toHaveLength(270);+ expect(markdown).not.toContain("Unselected branch");+ });++ it(`keeps screen-capture placeholders in earlier ${kind} pages`, async () => {+ fixture.messages[10] = { ...fixture.messages[10]!, kind: "screen", text: undefined, hasImage: true };+ const markdown = await exported(kind, "copy", fixture.messages.slice(-80), true);+ expect(markdown).toContain("Screen capture (image not included in Markdown export).");+ expect(markdown.match(/Conversation message \d{3}/g)).toHaveLength(269);+ });++ it(`does not download a partial ${kind} conversation after an earlier page fails`, async () => {+ fixture.api.mockResolvedValueOnce({ messages: fixture.messages.slice(-200), hasMore: true, activeLeafId: fixture.leaf });+ fixture.api.mockRejectedValueOnce(new Error("History is unavailable"));+ vi.stubGlobal("window", {});+ action(kind, "download", fixture.messages.slice(-80), true).onSelect();+ await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledWith({ type: "error", message: "History is unavailable" }));+ expect(fixture.download).not.toHaveBeenCalled();+ expect(fixture.writeText).not.toHaveBeenCalled();+ });+ }+});diff --git a/src/lib/conversation-transcript.ts b/src/lib/conversation-transcript.tsnew file mode 100644index 0000000000..20b6b1cd07--- /dev/null+++ b/src/lib/conversation-transcript.ts@@ -0,0 +1,14 @@+import { loadFullThread } from "@/state/message-history";+import { visibleMessages } from "@/state/snapshot-navigation";+import { formatTranscriptMarkdown, type ExportTranscriptOptions } from "./export-transcript";++interface ConversationTranscriptOptions extends ExportTranscriptOptions {+ threadId: string;+ hasMore?: boolean;+}++/** An export reads the whole selected branch without filling the UI's bounded message cache. */+export function conversationTranscript({ threadId, hasMore, ...options }: ConversationTranscriptOptions): string | Promise<string> {+ if (!hasMore) return formatTranscriptMarkdown(options);+ return loadFullThread(threadId).then((thread) => formatTranscriptMarkdown({ ...options, messages: visibleMessages(thread) }));+}diff --git a/src/lib/copy-text-async.test.ts b/src/lib/copy-text-async.test.tsnew file mode 100644index 0000000000..0392eda516--- /dev/null+++ b/src/lib/copy-text-async.test.ts@@ -0,0 +1,111 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { copyText, WEB_WRITE_TIMEOUT_MS } from "./copy-text";++class DeferredClipboardItem {+ constructor(readonly data: Record<string, Promise<Blob>>) {}+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+});++describe("copying a conversation whose earlier messages are still loading", () => {+ it("starts the clipboard write during the click and supplies the full text when it is ready", async () => {+ const content = Promise.withResolvers<string>();+ const written: string[] = [];+ const write = vi.fn(async ([item]: DeferredClipboardItem[]) => {+ written.push(await (await item!.data["text/plain"]).text());+ });+ const writeText = vi.fn();+ vi.stubGlobal("ClipboardItem", DeferredClipboardItem);+ vi.stubGlobal("navigator", { clipboard: { write, writeText } });+ const result = copyText(content.promise);+ expect(write).toHaveBeenCalledOnce();+ expect(written).toEqual([]);+ content.resolve("First page\nLast page");+ expect(await result).toBe("copied");+ expect(written).toEqual(["First page\nLast page"]);+ expect(writeText).not.toHaveBeenCalled();+ });++ it("keeps the existing web path when deferred clipboard items are unavailable", async () => {+ const content = Promise.withResolvers<string>();+ const writeText = vi.fn(async () => {});+ vi.stubGlobal("navigator", { clipboard: { writeText } });+ vi.stubGlobal("ClipboardItem", undefined);+ const result = copyText(content.promise);+ expect(writeText).not.toHaveBeenCalled();+ content.resolve("Full conversation");+ expect(await result).toBe("copied");+ expect(writeText).toHaveBeenCalledWith("Full conversation");+ });++ it("uses the existing desktop fallback after the history has loaded", async () => {+ const bridge = vi.fn(async () => true);+ vi.stubGlobal("navigator", {});+ vi.stubGlobal("window", { ogb: { copyText: bridge } });+ expect(await copyText(Promise.resolve("Full conversation"))).toBe("copied");+ expect(bridge).toHaveBeenCalledWith("Full conversation");+ });++ it("does not replace the clipboard with a partial transcript when loading fails", async () => {+ const content = Promise.withResolvers<string>();+ const write = vi.fn(async ([item]: DeferredClipboardItem[]) => { await item!.data["text/plain"]; });+ const writeText = vi.fn();+ const bridge = vi.fn();+ vi.stubGlobal("ClipboardItem", DeferredClipboardItem);+ vi.stubGlobal("navigator", { clipboard: { write, writeText } });+ vi.stubGlobal("window", { ogb: { copyText: bridge } });+ const result = copyText(content.promise);+ content.reject(new Error("History could not load"));+ expect(await result).toBe("failed");+ expect(writeText).not.toHaveBeenCalled();+ expect(bridge).not.toHaveBeenCalled();+ });++ it("does not write an empty result", async () => {+ const write = vi.fn(async ([item]: DeferredClipboardItem[]) => { await item!.data["text/plain"]; });+ const writeText = vi.fn();+ vi.stubGlobal("ClipboardItem", DeferredClipboardItem);+ vi.stubGlobal("navigator", { clipboard: { write, writeText } });+ expect(await copyText(Promise.resolve(" \n "))).toBe("empty");+ expect(writeText).not.toHaveBeenCalled();+ });++ it("bounds an unsettled clipboard write after the requested history becomes available", async () => {+ vi.useFakeTimers();+ const content = Promise.withResolvers<string>();+ const bridge = vi.fn(async () => true);+ const write = vi.fn(() => new Promise(() => {}));+ const writeText = vi.fn(() => new Promise(() => {}));+ vi.stubGlobal("ClipboardItem", DeferredClipboardItem);+ vi.stubGlobal("navigator", { clipboard: { write, writeText } });+ vi.stubGlobal("window", { ogb: { copyText: bridge } });+ const result = copyText(content.promise);+ await vi.advanceTimersByTimeAsync(WEB_WRITE_TIMEOUT_MS * 2);+ expect(bridge).not.toHaveBeenCalled();+ content.resolve("Full conversation");+ await vi.advanceTimersByTimeAsync(WEB_WRITE_TIMEOUT_MS - 1);+ expect(bridge).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(await result).toBe("copied");+ expect(bridge).toHaveBeenCalledWith("Full conversation");+ expect(write).toHaveBeenCalledOnce();+ expect(writeText).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("does not start a second native write after a deferred clipboard write rejects", async () => {+ const bridge = vi.fn(async () => true);+ const write = vi.fn(async () => { throw new Error("Write denied"); });+ const writeText = vi.fn();+ vi.stubGlobal("ClipboardItem", DeferredClipboardItem);+ vi.stubGlobal("navigator", { clipboard: { write, writeText } });+ vi.stubGlobal("window", { ogb: { copyText: bridge } });+ expect(await copyText(Promise.resolve("Full conversation"))).toBe("copied");+ expect(write).toHaveBeenCalledOnce();+ expect(writeText).not.toHaveBeenCalled();+ expect(bridge).toHaveBeenCalledWith("Full conversation");+ });+});diff --git a/src/lib/copy-text.ts b/src/lib/copy-text.tsindex f2f7f287e5..c57191c720 100644--- a/src/lib/copy-text.ts+++ b/src/lib/copy-text.ts@@ -8,19 +8,36 @@ export const COPY_FEEDBACK_MS = 1200;/** Bounds a web write that never settles; Chromium rejects an unfocused write at once. */export const WEB_WRITE_TIMEOUT_MS = 3000;-function writeWeb(text: string): Promise<boolean> {+function writeWeb(text: string | Promise<string>): Promise<boolean> {return new Promise((resolve) => {let done = false;+ let timer: ReturnType<typeof setTimeout> | undefined;const finish = (ok: boolean) => {if (done) return;done = true;clearTimeout(timer);resolve(ok);};- const timer = setTimeout(() => finish(false), WEB_WRITE_TIMEOUT_MS);+ const startTimeout = () => { if (!done) timer = setTimeout(() => finish(false), WEB_WRITE_TIMEOUT_MS); };try {- if (!navigator.clipboard?.writeText) return finish(false);- Promise.resolve(navigator.clipboard.writeText(text)).then(() => finish(true), () => finish(false));+ if (typeof text === "string") {+ startTimeout();+ if (!navigator.clipboard?.writeText) return finish(false);+ Promise.resolve(navigator.clipboard.writeText(text)).then(() => finish(true), () => finish(false));+ } else {+ // WebKit needs the write inside the click, before asynchronous conversation reads finish.+ if (!navigator.clipboard?.write || typeof ClipboardItem === "undefined") {+ void text.then((content) => content.trim() ? writeWeb(content).then(finish) : finish(false), () => finish(false));+ return;+ }+ const data = text.then((content) => {+ if (!content.trim()) throw new Error("Nothing to copy");+ startTimeout();+ return new Blob([content], { type: "text/plain" });+ });+ void data.catch(() => finish(false));+ Promise.resolve(navigator.clipboard.write([new ClipboardItem({ "text/plain": data })])).then(() => finish(true), () => finish(false));+ }} catch {finish(false);}@@ -54,9 +71,16 @@ function writeLegacy(text: string): boolean {}/** Web Clipboard API, then the desktop bridge, then legacy execCommand (insecure-context mobile). Never throws. */-export async function copyText(text: string): Promise<CopyResult> {+export async function copyText(content: string | Promise<string>): Promise<CopyResult> {+ if (typeof content === "string" && !content.trim()) return "empty";+ if (await writeWeb(content)) return "copied";+ let text: string;+ try {+ text = await content;+ } catch {+ return "failed";+ }if (!text.trim()) return "empty";- if (await writeWeb(text)) return "copied";try {if (typeof window !== "undefined" && (await window.ogb?.copyText?.(text)) === true) return "copied";} catch {diff --git a/src/lib/export-transcript.ts b/src/lib/export-transcript.tsindex 4d45e09d9f..2c748b1218 100644--- a/src/lib/export-transcript.ts+++ b/src/lib/export-transcript.ts@@ -160,6 +160,6 @@ export function downloadMarkdownTranscript(filename: string, content: string): vwindow.setTimeout(() => URL.revokeObjectURL(url), 60_000);}-export async function copyTranscriptToClipboard(content: string): Promise<boolean> {+export async function copyTranscriptToClipboard(content: string | Promise<string>): Promise<boolean> {return (await copyText(content)) === "copied";}