Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(titles): preserve turn outcomes and explicit renames
skygunnere09ce784abe1
diff --git a/server/host/handed-thread-title.test.ts b/server/host/handed-thread-title.test.tsindex 0281918e9f..3b5572cd27 100644--- a/server/host/handed-thread-title.test.ts+++ b/server/host/handed-thread-title.test.ts@@ -28,21 +28,26 @@ describe("a thread a teammate opened", () => {const p = place();p.title("dana", "work-1", "Implement the CSV export", "@Clive · ");p.titles.turnStarted("work-1", "current");- p.titles.turnEnded("work-1", "previous", "An earlier reply");+ p.titles.assistantReply("work-1", "previous", "An earlier reply");+ p.titles.turnEnded("work-1", "previous", true);expect(p.generate).not.toHaveBeenCalled();- p.titles.turnEnded("work-1", "current", "Added accounting CSV support.");+ p.titles.assistantReply("work-1", "current", "Added accounting CSV support.");+ expect(p.generate).not.toHaveBeenCalled();+ p.titles.turnEnded("work-1", "current", true);await vi.waitFor(() => expect(p.task.title).toBe("@Clive · CSV export build"));expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "User: Implement the CSV export\nBot: Added accounting CSV support.", "first-reply");});- it("accepts a room summary reply from the next speaker after an empty turn", async () => {+ it("uses the next room speaker's reply after a failed turn", async () => {const p = place();p.title("dana", "work-1", "Implement it", "@Clive · ");p.titles.turnStarted("work-1", "first", true);- p.titles.turnStarted("work-1", "reask", true);- p.titles.turnEnded("work-1", "first", "Old progress message");+ p.titles.assistantReply("work-1", "first", "Old progress message");+ p.titles.turnEnded("work-1", "first", false, true);expect(p.generate).not.toHaveBeenCalled();- p.titles.turnEnded("work-1", "reask", "Implemented.");+ p.titles.turnStarted("work-1", "reask", true);+ p.titles.assistantReply("work-1", "reask", "Implemented.");+ p.titles.turnEnded("work-1", "reask", true, true);await vi.waitFor(() => expect(p.task.title).toBe("@Clive · CSV export build"));expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "User: Implement it\nBot: Implemented.", "first-reply");});@@ -54,7 +59,8 @@ describe("a thread a teammate opened", () => {return "New name";});p.title("dana", "work-1", "Implement it", "@Clive · ");- p.titles.turnEnded("work-1", "current", "Implemented.");+ p.titles.assistantReply("work-1", "current", "Implemented.");+ p.titles.turnEnded("work-1", "current", true);await Promise.resolve();expect(p.generate).toHaveBeenCalledOnce();expect(p.task.title).toBe("@Clive · work");@@ -66,11 +72,13 @@ describe("a thread a teammate opened", () => {const p = place();p.titles.start("thread", { request: "Export", currentTitle: "Reports", model: () => ({ ok: true, instance: {} }), stillCurrent: () => true, apply: vi.fn() });p.titles.turnStarted("thread", "turn");+ p.titles.assistantReply("thread", "turn", " ");+ p.titles.assistantReply("thread", "turn", "First reply");+ p.titles.assistantReply("thread", "turn", "Last reply");await vi.advanceTimersByTimeAsync(TITLE_REPLY_WAIT_MS);expect(p.generate).not.toHaveBeenCalled();- expect(p.generate).not.toHaveBeenCalled();- p.titles.turnEnded("thread", "turn", "Last reply");- expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, expect.stringContaining("Last reply"), "follow-up");+ p.titles.turnEnded("thread", "turn", true);+ expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "Current title: Reports\nUser: Export\nBot: First reply", "follow-up");} finally {vi.useRealTimers();}@@ -85,7 +93,8 @@ describe("a thread a teammate opened", () => {expect(p.generate).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(1);expect(p.generate).toHaveBeenCalledExactlyOnceWith({}, "User: Implement it", "first-message");- p.titles.turnEnded("work-1", "current", "Implemented.");+ p.titles.assistantReply("work-1", "current", "Implemented.");+ p.titles.turnEnded("work-1", "current", true);expect(p.generate).toHaveBeenCalledOnce();expect(p.task.title).toBe("@Clive · CSV export build");} finally {diff --git a/server/host/thread-titles.ts b/server/host/thread-titles.tsindex 9dec7283e0..ec126650c5 100644--- a/server/host/thread-titles.ts+++ b/server/host/thread-titles.ts@@ -18,6 +18,7 @@ export function createAutomaticThreadTitles(generate = generateThreadTitle) {attempt: AutomaticTitle;timer: ReturnType<typeof setTimeout> | undefined;turnId?: string;+ firstReply?: string;generating?: true;}>();@@ -27,9 +28,14 @@ export function createAutomaticThreadTitles(generate = generateThreadTitle) {pending.delete(threadId);}- async function finish(threadId: string, turnId?: string, reply?: string) {+ async function finish(threadId: string, turnId?: string, successful = false, room = false) {const current = pending.get(threadId);if (!current || current.generating || (turnId !== undefined && current.turnId !== undefined && current.turnId !== turnId)) return;+ const reply = successful ? current.firstReply : undefined;+ if (room && !reply) {+ current.firstReply = undefined;+ return;+ }clearTimeout(current.timer);current.generating = true;try {@@ -62,9 +68,17 @@ export function createAutomaticThreadTitles(generate = generateThreadTitle) {generating: (threadId: string) => pending.get(threadId)?.generating === true,turnStarted(threadId: string, turnId?: string, room = false) {const current = pending.get(threadId);- if (current && turnId && (room || current.turnId === undefined)) current.turnId = turnId;+ if (current && turnId && turnId !== current.turnId && (room || current.turnId === undefined)) {+ current.turnId = turnId;+ current.firstReply = undefined;+ }+ },+ assistantReply(threadId: string, turnId: string | undefined, text: string) {+ const current = pending.get(threadId);+ if (!current || current.generating || current.firstReply || (turnId && current.turnId && turnId !== current.turnId)) return;+ current.firstReply = text.trim() || undefined;},- turnEnded: (threadId: string, turnId?: string, reply?: string) => void finish(threadId, turnId, reply?.trim() || undefined),+ turnEnded: (threadId: string, turnId?: string, successful = false, room = false) => void finish(threadId, turnId, successful, room),drop,};}diff --git a/server/index.test.ts b/server/index.test.tsindex 3a766a5442..1ffe5cce3b 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -2433,16 +2433,21 @@ describe("harness HTTP API", () => {await expect.poll(title, { timeout: 5_000 }).toBe("Login | timeout fix");await expect.poll(async () => (await api("GET", "/api/bots?messages=0")).body.groups.find((candidate: { id: string }) => candidate.id === room.id)?.working, { timeout: 10_000 }).toBe(false);rmSync(fakeClaudeRelease, { force: true });- const pinned = await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { pinned: true, title: "Fix the login timeout" });- expect(pinned.body.task).toMatchObject({ pinned: true, title: "Login | timeout fix" });- expect((await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { title: "My room title" })).status).toBe(200);+ const pinned = await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { pinned: true, title: "Login | timeout fix" });+ expect(pinned.body.task).toMatchObject({ pinned: true, title: "Login | timeout fix", titleMode: "automatic" });+ const unpinned = await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { pinned: false });+ expect(unpinned.body.task).toMatchObject({ title: "Login | timeout fix", titleMode: "automatic" });+ expect(unpinned.body.task.pinned).toBeUndefined();+ const renamed = await api("PATCH", `/api/groups/${room.id}/tasks/${room.threadId}`, { title: "Login | timeout fix" });+ expect(renamed.status).toBe(200);+ expect(renamed.body.task).toMatchObject({ title: "Login | timeout fix", titleMode: "manual" });writeFileSync(oneShotTextFile, "Unwanted title\n");rmSync(oneShotTextDump, { force: true });expect((await api("POST", `/api/groups/${room.id}/messages`, { text: "Now check the tax export" })).status).toBe(202);writeFileSync(fakeClaudeRelease, "release");await expect.poll(async () => (await api("GET", "/api/bots?messages=0")).body.groups.find((candidate: { id: string }) => candidate.id === room.id)?.working, { timeout: 10_000 }).toBe(false);expect(existsSync(oneShotTextDump)).toBe(false);- expect(await title()).toBe("My room title");+ expect(await title()).toBe("Login | timeout fix");} finally {rmSync(fakeClaudeRelease, { force: true });await api("PATCH", "/api/config", { threadTitles: { followUp: false } }).catch(() => undefined);@@ -2608,6 +2613,22 @@ describe("harness HTTP API", () => {}});+ it.each([true, false])("sets a room thread's pinned state to %s and renames it in the same PATCH", async (pinned) => {+ const bot = (await api("POST", "/api/bots")).body.bot;+ const room = (await api("POST", "/api/groups", { name: "Room", memberIds: [bot.id] })).body.group;+ const path = `/api/groups/${room.id}/tasks/${room.threadId}`;+ try {+ expect((await api("PATCH", path, { pinned: !pinned })).status).toBe(200);+ const updated = await api("PATCH", path, { pinned, title: "Release plan" });+ expect(updated.status).toBe(200);+ expect(updated.body.task).toMatchObject({ title: "Release plan", titleMode: "manual" });+ expect(updated.body.task.pinned).toBe(pinned ? true : undefined);+ } finally {+ await api("DELETE", `/api/groups/${room.id}`);+ await api("DELETE", `/api/bots/${bot.id}`);+ }+ });+it("saves how many turns each room member takes, from 1 to 5, and refuses it on a direct-message channel", async () => {const bot = (await api("POST", "/api/bots")).body.bot;const room = (await api("POST", "/api/groups", { name: "Rounds", memberIds: [bot.id] })).body.group;diff --git a/server/index.ts b/server/index.tsindex 39b9489922..f3cbbd1477 100644--- a/server/index.ts+++ b/server/index.ts@@ -6346,7 +6346,8 @@ bus.subscribe((event: RuntimeEvent) => {pushStoppedTurn(turnId);return;}- pushMessage({ role: "bot", kind: "text", text: spoken.text, turnId, ...(event.type === "item.completed" && event.itemId ? { itemId: event.itemId } : {}) });+ const message = pushMessage({ role: "bot", kind: "text", text: spoken.text, turnId, ...(event.type === "item.completed" && event.itemId ? { itemId: event.itemId } : {}) });+ if (!replayed && message.text) automaticTitles.assistantReply(event.threadId, turnId, message.text);lastReply.set(event.threadId, spoken.text);};const landParkedFiles = () => {@@ -6645,8 +6646,8 @@ bus.subscribe((event: RuntimeEvent) => {.map((message) => message.text ?? "").join("\n"));}if (bot) void replyVoiceNotes.turnSettled({ bot, threadId: event.threadId, turnId: completedTurnId, stoppedByPerson: personStops.stopped(event.threadId, completedTurnId), internal, ...(event.ok ? {} : { ending: { stop: turnStops.read(event.threadId, completedTurnId), cause: turnStops.failureCause(event), interrupted: event.stopReason === "interrupted" } }) });- const reply = lastReply.get(event.threadId) ?? "", titleReply = event.ok && !stopped && !replayed ? reply.trim() : "";- if (!replayed && (bot || titleReply)) automaticTitles.turnEnded(event.threadId, completedTurnId, titleReply);+ const reply = lastReply.get(event.threadId) ?? "";+ if (!replayed) automaticTitles.turnEnded(event.threadId, completedTurnId, event.ok && !stopped, Boolean(group));if (personStops.stopped(event.threadId, completedTurnId)) pushStoppedTurn(completedTurnId);personStops.turnEnded(event.threadId, completedTurnId);lastReply.delete(event.threadId);diff --git a/server/routes/channels.ts b/server/routes/channels.tsindex 2aace55973..f48bd8d5a4 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -284,8 +284,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {}const parsedLimit = limiting ? parseConversationTurnTimeout(body.turnTimeoutMinutes) : null;if (parsedLimit && !parsedLimit.ok) return json(res, 400, { error: parsedLimit.error });- // Clients echo a cached title when pinning for compatibility with older servers.- const titleChange = !pinning && renaming && body.title !== existing.title;+ // Older clients echo the title with a pin or unpin request.+ const titleChange = renaming && (!pinning || body.title !== existing.title);const notYours = titleChange ? cloudThreadRefusal(auth, m[2]) : null;if (notYours) return json(res, 403, { error: notYours });if (titleChange && groupThreadIsWorking(group.id, m[2])) {diff --git a/server/thread-title-auto.e2e.test.ts b/server/thread-title-auto.e2e.test.tsindex 3ba0041ca9..60ec3fe6d2 100644--- a/server/thread-title-auto.e2e.test.ts+++ b/server/thread-title-auto.e2e.test.ts@@ -1,14 +1,19 @@-import { mkdtempSync, readFileSync, rmdirSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { expect, it } from "vitest";import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";-it("names a real fixture conversation from both its request and reply", async () => {+it("names a successful fixture conversation from the request and first visible reply", async () => {const dir = mkdtempSync(join(tmpdir(), "omb-title-e2e-"));- const title = join(dir, "title.txt"), dump = join(dir, "title-dump.json");+ const title = join(dir, "title.txt"), dump = join(dir, "title-dump.json"), script = join(dir, "stream.json");writeFileSync(title, "Payroll | export fix");- const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_TEXT_FILE: title, FAKE_CLAUDE_TEXT_DUMP: dump });+ writeFileSync(script, JSON.stringify({ "Fix payroll export": [+ { think: "Private reasoning about the ledger." },+ { say: "I found a mismatch in the payroll schema." },+ { say: "The export is ready." },+ ] }));+ const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_TEXT_FILE: title, FAKE_CLAUDE_TEXT_DUMP: dump, FAKE_STREAM_SCRIPT: script, FAKE_STREAM_CADENCE: "100:1" });const control = (...args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;try {const { bot } = await control("new-bot", "--name", "Title fixture");@@ -20,12 +25,12 @@ it("names a real fixture conversation from both its request and reply", async ()}, { timeout: 15_000 }).toBe("Payroll | export fix");const { prompt } = JSON.parse(readFileSync(dump, "utf8"));expect(prompt).toContain("User: Fix payroll export");- expect(prompt).toContain("Bot:");+ expect(prompt).toContain("Bot: I found a mismatch in the payroll schema.");+ expect(prompt).not.toContain("The export is ready.");+ expect(prompt).not.toContain("Private reasoning about the ledger.");} finally {await fixture.close();- rmSync(title, { force: true });- rmSync(dump, { force: true });- rmdirSync(dir);+ rmSync(dir, { recursive: true, force: true });}}, 120_000);diff --git a/src/components/SidebarBotActivity.test.ts b/src/components/SidebarBotActivity.test.tsindex 9fe12dfdb3..3806c377c0 100644--- a/src/components/SidebarBotActivity.test.ts+++ b/src/components/SidebarBotActivity.test.ts@@ -319,7 +319,7 @@ describe("attentionUnpinAction", () => {it("unpins a room thread via pinGroupTask", () => {const room = group("g", "Crew", "g0", { tasks: [{ threadId: "g0", title: "Crew", createdAt: 0, pinned: true }] });const [entry] = crossBotPinnedThreads([], [room], {});- expect(attentionUnpinAction(entry)).toEqual({ type: "pinGroupTask", groupId: "g", threadId: "g0", pinned: false, title: "Crew" });+ expect(attentionUnpinAction(entry)).toEqual({ type: "pinGroupTask", groupId: "g", threadId: "g0", pinned: false });});});diff --git a/src/components/SidebarBotActivity.tsx b/src/components/SidebarBotActivity.tsxindex 6753870b45..3669ddb019 100644--- a/src/components/SidebarBotActivity.tsx+++ b/src/components/SidebarBotActivity.tsx@@ -122,9 +122,9 @@ export function attentionJump(dispatch: Dispatch<Action>, entry: AttentionThreadexport function attentionUnpinAction(entry: AttentionThread):| { type: "updateTask"; botId: string; threadId: string; patch: { pinned: boolean } }- | { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean; title: string } {+ | { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean } {if (entry.kind === "bot") return { type: "updateTask", botId: entry.botId, threadId: entry.task.threadId, patch: { pinned: false } };- return { type: "pinGroupTask", groupId: entry.groupId, threadId: entry.task.threadId, pinned: false, title: entry.task.title };+ return { type: "pinGroupTask", groupId: entry.groupId, threadId: entry.task.threadId, pinned: false };}/** aria-label replaces the button's contents, so the count must be in the name or a screen reader never hears it. */diff --git a/src/components/SidebarGroupThreadList.tsx b/src/components/SidebarGroupThreadList.tsxindex 7286ddba0e..e44a2edf24 100644--- a/src/components/SidebarGroupThreadList.tsx+++ b/src/components/SidebarGroupThreadList.tsx@@ -11,7 +11,7 @@ export function roomThreadRowActions(groupId: string, dispatch: Dispatch<Action>return {onRename: (task: { threadId: string }, title: string) => dispatch({ type: "renameGroupTask", groupId, threadId: task.threadId, title }),onDelete: (task: { threadId: string }) => dispatch({ type: "deleteGroupTask", groupId, threadId: task.threadId }),- onPin: (task: { threadId: string; title: string }, pinned: boolean) => dispatch({ type: "pinGroupTask", groupId, threadId: task.threadId, pinned, title: task.title }),+ onPin: (task: { threadId: string }, pinned: boolean) => dispatch({ type: "pinGroupTask", groupId, threadId: task.threadId, pinned }),onArchive: (task: { threadId: string }, archivedAt: number | null) => dispatch({ type: "archiveGroupTask", groupId, threadId: task.threadId, archivedAt }),onSetClosed: (task: { threadId: string }, closed: boolean) => setRoomThreadClosed(groupId, task.threadId, closed, dispatch),};diff --git a/src/components/TaskPicker.tsx b/src/components/TaskPicker.tsxindex 0dafaf01a8..898b780948 100644--- a/src/components/TaskPicker.tsx+++ b/src/components/TaskPicker.tsx@@ -487,10 +487,7 @@ export function GroupTaskPicker({ group }: { group: Group }) {onSwitch={(threadId) => dispatch({ type: "switchGroupTask", groupId: group.id, threadId })}onRename={(threadId, title) => dispatch({ type: "renameGroupTask", groupId: group.id, threadId, title })}onDelete={(threadId) => dispatch({ type: "deleteGroupTask", groupId: group.id, threadId })}- onPin={(threadId, pinned) => {- const title = group.tasks?.find((task) => task.threadId === threadId)?.title ?? "";- dispatch({ type: "pinGroupTask", groupId: group.id, threadId, pinned, title });- }}+ onPin={(threadId, pinned) => dispatch({ type: "pinGroupTask", groupId: group.id, threadId, pinned })}/>);}diff --git a/src/state/store.tsx b/src/state/store.tsxindex 7d97bc8cdb..626ad5cd1f 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -646,7 +646,7 @@ export type Action =| ForkPanelAction | MakeNewChatAction| { type: "switchGroupTask"; groupId: string; threadId: string }| { type: "renameGroupTask"; groupId: string; threadId: string; title: string }- | { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean; title: string }+ | { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean }| { type: "archiveGroupTask"; groupId: string; threadId: string; archivedAt: number | null }| { type: "setConversationTurnLimit"; groupId: string; threadId: string; minutes: number | null; dm: boolean }| { type: "deleteGroupTask"; groupId: string; threadId: string }@@ -2778,7 +2778,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {case "archiveGroupTask":case "setConversationTurnLimit": {const body = action.type === "renameGroupTask" ? { title: action.title }- : action.type === "pinGroupTask" ? { pinned: action.pinned, title: action.title }+ : action.type === "pinGroupTask" ? { pinned: action.pinned }: action.type === "archiveGroupTask" ? { archivedAt: action.archivedAt } : { turnTimeoutMinutes: action.minutes };const path = action.type === "setConversationTurnLimit" && action.dm ? `/api/groups/${action.groupId}` : `/api/groups/${action.groupId}/tasks/${action.threadId}`;api(path, { method: "PATCH", body: JSON.stringify(body) }).catch(showSavedState({ groupId: action.groupId }));