Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Threads: archive group chat threads and bot-panel conversations (#4224)
Aditya Umale3d71548cec27
diff --git a/server/group-tasks.test.ts b/server/group-tasks.test.tsindex 9eee8152d3..fe60916836 100644--- a/server/group-tasks.test.ts+++ b/server/group-tasks.test.ts@@ -180,6 +180,20 @@ describe("channel tasks", () => {expect(reloaded.patchGroup(dm.id, { turnTimeoutMinutes: null })?.turnTimeoutMinutes).toBeUndefined();});+ it("archives a channel thread, keeps it on reload, and unarchives it", async () => {+ const { store, Store } = await freshStore();+ const bot = store.createBot();+ const channel = store.createGroup("Product", [bot.id]);+ const original = channel.threadId;+ const sibling = store.createGroupTask(channel.id)!;+ expect(store.patchGroupTask(channel.id, sibling.threadId, { archivedAt: 1234 })?.archivedAt).toBe(1234);+ expect(store.groupTaskByThread(channel.id, original)?.archivedAt).toBeUndefined();++ const reloaded = new Store(() => ({ instanceId: "claude", model: "m" }));+ expect(reloaded.groupTaskByThread(channel.id, sibling.threadId)?.archivedAt).toBe(1234);+ expect(reloaded.patchGroupTask(channel.id, sibling.threadId, { archivedAt: null })).not.toHaveProperty("archivedAt");+ });+it("adopts a legacy channel thread without losing its folder or pin", async () => {const { store, Store } = await freshStore();const bot = store.createBot();diff --git a/server/index.test.ts b/server/index.test.tsindex 0a828f7f4d..af79613b3b 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -2441,6 +2441,14 @@ describe("harness HTTP API", () => {expect(renamed.status).toBe(200);expect(renamed.body.task.title).toBe("Release plan");+ const archived = await api("PATCH", `/api/groups/${room.id}/tasks/${newThread}`, { archivedAt: 1234 });+ expect(archived.status).toBe(200);+ expect(archived.body.task.archivedAt).toBe(1234);+ expect((await api("PATCH", `/api/groups/${room.id}/tasks/${newThread}`, { archivedAt: "soon" })).status).toBe(400);+ const unarchived = await api("PATCH", `/api/groups/${room.id}/tasks/${newThread}`, { archivedAt: null });+ expect(unarchived.status).toBe(200);+ expect(unarchived.body.task).not.toHaveProperty("archivedAt");+const switched = await api("POST", `/api/groups/${room.id}/tasks/${originalThread}`);expect(switched.status).toBe(200);expect(switched.body.group.threadId).toBe(originalThread);diff --git a/server/routes/channels.ts b/server/routes/channels.tsindex 9b8b5aaa44..b1af1d5af4 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -205,16 +205,20 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {if (!body || typeof body !== "object" || Array.isArray(body)) {return json(res, 400, { error: "body must be a JSON object" });}- const allowed = new Set(["title", "pinned", "turnTimeoutMinutes"]);+ const allowed = new Set(["title", "pinned", "turnTimeoutMinutes", "archivedAt"]);if (Object.keys(body).some((key) => !allowed.has(key))) return json(res, 400, { error: "unsupported channel thread setting" });const existing = store.groupTaskByThread(group.id, m[2]);if (!existing) return json(res, 404, { error: "no such channel task" });const pinning = body.pinned !== undefined;const renaming = body.title !== undefined;const limiting = Object.prototype.hasOwnProperty.call(body, "turnTimeoutMinutes");- if (!pinning && !renaming && !limiting) return json(res, 400, { error: "unsupported channel thread setting" });+ const archiving = body.archivedAt !== undefined;+ if (!pinning && !renaming && !limiting && !archiving) return json(res, 400, { error: "unsupported channel thread setting" });if (pinning && typeof body.pinned !== "boolean") return json(res, 400, { error: "pinned must be a boolean" });if (renaming && typeof body.title !== "string") return json(res, 400, { error: "title must be a string" });+ if (archiving && body.archivedAt !== null && !(typeof body.archivedAt === "number" && Number.isFinite(body.archivedAt) && body.archivedAt >= 0)) {+ return json(res, 400, { error: "archivedAt must be a timestamp, or null to unarchive" });+ }const parsedLimit = limiting ? parseConversationTurnTimeout(body.turnTimeoutMinutes) : null;if (parsedLimit && !parsedLimit.ok) return json(res, 400, { error: parsedLimit.error });// Echoing the current title is not a rename: newer clients send it so an older server keeps the title.@@ -227,6 +231,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {const patch: GroupTaskPatch = {...(parsedLimit?.ok ? { turnTimeoutMinutes: parsedLimit.minutes } : {}),...(pinning ? { pinned: body.pinned === true } : {}),+ ...(archiving ? { archivedAt: body.archivedAt as number | null } : {}),...(titleChange ? { title: body.title } : {}),};const task = Object.keys(patch).length ? store.patchGroupTask(group.id, m[2], patch) : existing;diff --git a/server/store.ts b/server/store.tsindex 9e863a8825..9cde89b0b6 100644--- a/server/store.ts+++ b/server/store.ts@@ -108,7 +108,7 @@ const TASK_PATCH_FIELDS = [] as const satisfies readonly (keyof TaskRecord)[];export type TaskPatch = Partial<Pick<TaskRecord, typeof TASK_PATCH_FIELDS[number]>>;-export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null };+export type GroupTaskPatch = Partial<Pick<GroupTaskRecord, "title" | "pinned">> & { turnTimeoutMinutes?: number | null; archivedAt?: number | null };function mirrorActiveGroupTask(group: GroupRecord, task: GroupTaskRecord): void {Object.assign(group, { threadId: task.threadId, pinnedCwd: task.pinnedCwd, pinnedMessageId: task.pinnedMessageId });@@ -1051,8 +1051,7 @@ export class Store {if (patch.title !== undefined) task.title = patch.title.trim().slice(0, 80) || UNTITLED_TASK;if (patch.pinned) task.pinned = true;else if (patch.pinned === false) delete task.pinned;- if (patch.turnTimeoutMinutes === null) delete task.turnTimeoutMinutes;- else if (patch.turnTimeoutMinutes !== undefined) task.turnTimeoutMinutes = patch.turnTimeoutMinutes;+ for (const key of ["turnTimeoutMinutes", "archivedAt"] as const) if (patch[key] === null) delete task[key]; else if (patch[key] !== undefined) task[key] = patch[key];});this.emit({ type: "group", groupId });return task;diff --git a/shared/wire.ts b/shared/wire.tsindex a53c5508b7..eb927ec28d 100644--- a/shared/wire.ts+++ b/shared/wire.ts@@ -817,6 +817,8 @@ export interface GroupTask {/** This conversation's own turn limit: whole minutes a turn may go without progress. Absent uses* the global group turn limit. Direct chats do not use this limit. */turnTimeoutMinutes?: number;+ /** Epoch ms when the person archived this thread; absent while it is in the list. */+ archivedAt?: number;/** Epoch ms of the newest message, or createdAt when the thread has none. */updatedAt?: number;lastThreadOrderAt?: number;diff --git a/src/components/BotThreads.test.ts b/src/components/BotThreads.test.tsindex 75ddc37b3a..51469c92f4 100644--- a/src/components/BotThreads.test.ts+++ b/src/components/BotThreads.test.ts@@ -140,5 +140,9 @@ describe("sidebar bot threads", () => {expect(picker).not.toContain("Tasks");const working = renderToStaticMarkup(createElement(StoreProvider, null, createElement(GroupThreadList, { group: { ...group, working: true }, selected: true })));expect(working).toContain(`title="Launch plan · ${formatUpdatedAt(3)} · Working"`);+ const archived = { ...group, tasks: [group.tasks![0]!, { ...group.tasks![1]!, archivedAt: 5 }] };+ const withArchived = renderToStaticMarkup(createElement(StoreProvider, null, createElement(GroupThreadList, { group: archived, selected: true })));+ expect(withArchived).not.toContain("Previous review");+ expect(withArchived).toContain("Show all");});});diff --git a/src/components/SidebarGroupThreadList.tsx b/src/components/SidebarGroupThreadList.tsxindex 03c0acac19..59846b8f6a 100644--- a/src/components/SidebarGroupThreadList.tsx+++ b/src/components/SidebarGroupThreadList.tsx@@ -32,6 +32,7 @@ export function GroupThreadList({ group, selected, query = "" }: { group: Group;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 }),+ onArchive: (task: { threadId: string }, archivedAt: number | null) => dispatch({ type: "archiveGroupTask", groupId, threadId: task.threadId, archivedAt }),}), [groupId, dispatch]);const locale = activeLocale();return <div className="mb-2 space-y-0.5" role="group" aria-label={t("task.namedList", { name: group.name })}>diff --git a/src/components/bot-panel/Conversations.dom.test.ts b/src/components/bot-panel/Conversations.dom.test.tsindex a7ac1d02ea..3856669330 100644--- a/src/components/bot-panel/Conversations.dom.test.ts+++ b/src/components/bot-panel/Conversations.dom.test.ts@@ -225,14 +225,51 @@ describe("a bot's conversations in its panel", () => {expect(fixture.dispatch.mock.calls).toEqual([[{ type: "newTask", botId: "research" }]]);});- it("pins, renames and deletes through the thread menu the sidebar uses", () => {+ it("pins, archives, renames and deletes through the thread menu the sidebar uses", () => {render(research());- click(row("launch").querySelector('[aria-label="Actions for Translate the launch post"]'));- const menu = document.querySelector('[data-thread-overlay][aria-label="Actions for Translate the launch post"]')!;- const items = [...menu.querySelectorAll("button")].map((button) => button.textContent);- expect(items).toEqual(expect.arrayContaining(["Copy link", "Rename thread", "Pin", "Delete thread"]));- expect(items).not.toContain("Archive");- click([...menu.querySelectorAll("button")].find((button) => button.textContent === "Pin")!);+ const menuFor = (title: string) => {+ click(host.querySelector(`[aria-label="Actions for ${title}"]`));+ return [...document.querySelector(`[data-thread-overlay][aria-label="Actions for ${title}"]`)!.querySelectorAll("button")];+ };+ const items = menuFor("Translate the launch post");+ expect(items.map((button) => button.textContent)).toEqual(expect.arrayContaining(["Copy link", "Rename thread", "Pin", "Archive", "Delete thread"]));+ click(items.find((button) => button.textContent === "Pin")!);expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "research", threadId: "launch", patch: { pinned: true } }]]);+ fixture.dispatch.mockReset();+ click(menuFor("Translate the launch post").find((button) => button.textContent === "Archive")!);+ expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "research", threadId: "launch", patch: { archivedAt: expect.any(Number) } }]]);+ });++ it("keeps the search open when archiving leaves one conversation listed", () => {+ const two = [task("who", "Who am I?", 2), task("deck", "Summarise the board deck", 4)];+ render(research({ tasks: two }));+ click(host.querySelector("[data-conversations-search]"));+ type(host.querySelector<HTMLInputElement>("[data-conversations-query]")!, "deck");+ render(research({ tasks: [two[0]!, { ...two[1]!, archivedAt: now - 1000 }] }));+ expect(host.querySelector("[data-conversations-query]")).not.toBeNull();+ expect(host.querySelector("[data-conversations-search]")).not.toBeNull();+ expect(host.textContent).toContain("Nothing matches “deck”");+ });++ it("keeps the open conversation listed when it is archived and the only one left", () => {+ const two = [task("who", "Who am I?", 2, { archivedAt: now - 1000 }), task("deck", "Summarise the board deck", 4, { archivedAt: now - 2000 })];+ render(research({ tasks: two }));+ expect(listed()).toEqual(["who"]);+ expect(host.querySelector("[data-conversations-archived]")!.textContent).toBe("Archived (1)");+ });++ it("lists archived conversations under Archived (N), where they can be unarchived", () => {+ render(research({ tasks: tasks.map((task) => task.threadId === "launch" || task.threadId === "deck" ? { ...task, archivedAt: now - 1000 } : task) }));+ expect(listed()).toEqual(["hiring", "who", "pricing"]);+ const archivedToggle = host.querySelector("[data-conversations-archived]")!;+ expect(archivedToggle.textContent).toBe("Archived (2)");+ expect(archivedToggle.getAttribute("aria-expanded")).toBe("false");+ click(archivedToggle);+ expect(listed()).toEqual(["hiring", "who", "pricing", "launch", "deck"]);+ click(host.querySelector('[aria-label="Actions for Summarise the board deck"]'));+ const unarchive = [...document.querySelector('[data-thread-overlay][aria-label="Actions for Summarise the board deck"]')!.querySelectorAll("button")]+ .find((button) => button.textContent === "Unarchive")!;+ click(unarchive);+ expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateTask", botId: "research", threadId: "deck", patch: { archivedAt: null } }]]);});});diff --git a/src/components/bot-panel/Conversations.tsx b/src/components/bot-panel/Conversations.tsxindex 921a243b54..1ef21baae2 100644--- a/src/components/bot-panel/Conversations.tsx+++ b/src/components/bot-panel/Conversations.tsx@@ -59,14 +59,15 @@ export function BotConversations({ bot }: { bot: Bot }) {const [query, setQuery] = useState("");const [searching, setSearching] = useState(false);const [expanded, setExpanded] = useState(false);+ const [showArchived, setShowArchived] = useState(false);const generatedTitles = llmThreadTitlesEnabled(state.config);const actions = useMemo(() => {- const { onRename, onRegenerateTitle, onDelete, onMove, onPin } = threadRowActions(bot.id, dispatch, generatedTitles);- return { onRename, onRegenerateTitle, onDelete, onMove, onPin };+ const { onRename, onRegenerateTitle, onDelete, onMove, onPin, onArchive } = threadRowActions(bot.id, dispatch, generatedTitles);+ return { onRename, onRegenerateTitle, onDelete, onMove, onPin, onArchive };}, [bot.id, dispatch, generatedTitles]);- const conversations = orderedThreadList((bot.tasks ?? [{ threadId: bot.threadId, title: t("task.newShort"), createdAt: 0 }])- .filter((task) => !task.routineRunId && (!isArchived(task) || task.threadId === bot.threadId)))+ const threads = (bot.tasks ?? [{ threadId: bot.threadId, title: t("task.newShort"), createdAt: 0 }])+ .filter((task) => !task.routineRunId).map((task) => {const thread = currentTaskBot(bot, task.threadId);return {@@ -74,9 +75,11 @@ export function BotConversations({ bot }: { bot: Bot }) {turnStartedAt: thread.turnStartedAt ?? undefined, queued: Boolean(state.pendingQueued[task.threadId]?.length),};});+ const conversations = orderedThreadList(threads.filter((task) => !isArchived(task) || task.threadId === bot.threadId));+ const archived = orderedThreadList(threads.filter((task) => isArchived(task) && task.threadId !== bot.threadId));const needle = query.trim();const collapsed = conversations.filter((task, index) => index < CONVERSATIONS_SHOWN || task.threadId === bot.threadId);- const recent = useRecentMessages(bot, needle || expanded ? conversations : collapsed);+ const recent = useRecentMessages(bot, [...(needle || expanded ? conversations : collapsed), ...(showArchived ? archived : [])]);const preview = (threadId: string) => {const messages = recent(threadId);return messages ? lastLine(currentTaskBot(bot, threadId), messages, state.instances, false) : undefined;@@ -105,7 +108,15 @@ export function BotConversations({ bot }: { bot: Bot }) {setSearching(false);};- const listed = conversations.length >= 2;+ // An open search stays up even if archiving leaves one conversation, so it can still be cleared.+ // An archived open conversation stays listed too, so it is not hidden while it is open.+ const listed = conversations.length >= 2 || searching || conversations.some((task) => task.threadId === bot.threadId && isArchived(task));+ const row = (task: (typeof threads)[number]) => (+ <div role="listitem" key={task.threadId} data-conversation={task.threadId}>+ <SidebarThreadRow panel preview={preview(task.threadId)} task={task} ownerId={bot.id} current={task.threadId === bot.threadId}+ folders={bot.projects} now={stampClock(threadRecency(task), now)} locale={activeLocale()} onSelect={select} {...actions} />+ </div>+ );return (<section data-panel-card="conversations" aria-label={t("botPanel.conversations.title")} className="mt-3.5">@@ -155,22 +166,7 @@ export function BotConversations({ bot }: { bot: Bot }) {/>)}{listed && <div role="list" aria-label={t("botPanel.conversations.title")} className={cn("flex flex-col gap-px", PANEL_ROW_LOOK)}>- {shown.map((task) => (- <div role="listitem" key={task.threadId} data-conversation={task.threadId}>- <SidebarThreadRow- panel- preview={preview(task.threadId)}- task={task}- ownerId={bot.id}- current={task.threadId === bot.threadId}- folders={bot.projects}- now={stampClock(threadRecency(task), now)}- locale={activeLocale()}- onSelect={select}- {...actions}- />- </div>- ))}+ {shown.map(row)}</div>}{listed && needle && shown.length === 0 && (<p className="px-3 py-3 text-[13px] text-ink-secondary">{t("task.noMatch", { query: needle })}</p>@@ -187,6 +183,23 @@ export function BotConversations({ bot }: { bot: Bot }) {{expanded ? t("botPanel.conversations.showFewer") : t("botPanel.conversations.showMore", { count: hidden })}</button>)}+ {!needle && archived.length > 0 && (+ <button+ type="button"+ data-conversations-archived+ aria-expanded={showArchived}+ onClick={() => setShowArchived((open) => !open)}+ className="mt-0.5 flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] text-ink-secondary hover:bg-ink/[0.04] hover:text-ink"+ >+ {showArchived ? <ChevronUp size={14} aria-hidden="true" /> : <ChevronDown size={14} aria-hidden="true" />}+ {t("task.archivedList", { count: archived.length })}+ </button>+ )}+ {!needle && showArchived && archived.length > 0 && (+ <div role="list" aria-label={t("task.archivedList", { count: archived.length })} className={cn("flex flex-col gap-px", PANEL_ROW_LOOK)}>+ {archived.map(row)}+ </div>+ )}</section>);}diff --git a/src/state/store.test.ts b/src/state/store.test.tsindex cd926410db..ec559bb743 100644--- a/src/state/store.test.ts+++ b/src/state/store.test.ts@@ -1134,6 +1134,17 @@ describe("task rename", () => {expect(next.groups[0]?.tasks?.find((task) => task.threadId === "room-task-1")?.title).toBe("Renamed");expect(next.groups[0]?.tasks?.find((task) => task.threadId === "room-task-2")?.title).toBe("Other");});++ it("archives and unarchives a channel task in local state immediately", () => {+ const group = {+ id: "room", threadId: "room-task-1", name: "Launch", memberIds: [], defaultResponder: { kind: "everyone" }, bulletin: "", unread: false, createdAt: 1, messages: [],+ tasks: [{ threadId: "room-task-1", title: "Open", createdAt: 1 }, { threadId: "room-task-2", title: "Done", createdAt: 2 }],+ } satisfies Group;+ const archived = reducer({ ...initialState, groups: [group] }, { type: "archiveGroupTask", groupId: "room", threadId: "room-task-2", archivedAt: 1234 });+ expect(archived.groups[0]?.tasks?.map((task) => task.archivedAt)).toEqual([undefined, 1234]);+ const unarchived = reducer(archived, { type: "archiveGroupTask", groupId: "room", threadId: "room-task-2", archivedAt: null });+ expect(unarchived.groups[0]?.tasks?.[1]?.archivedAt).toBeUndefined();+ });});describe("config status", () => {diff --git a/src/state/store.tsx b/src/state/store.tsxindex a8ee3f835c..76da45cbb8 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -200,6 +200,7 @@ export interface GroupTask {pinned?: boolean;updatedAt?: number;turnTimeoutMinutes?: number;+ archivedAt?: number;lastThreadOrderAt?: number;working?: boolean;busyBotId?: string | null;@@ -696,6 +697,7 @@ export type Action =| { 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: "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 }| { type: "interruptGroup"; groupId: string; threadId?: string; onError?: () => void }@@ -1748,6 +1750,8 @@ export function reducer(state: AppState, action: Action): AppState {return patchGroupTask(state, action.groupId, action.threadId, { title: action.title });case "pinGroupTask":return patchGroupTask(state, action.groupId, action.threadId, { pinned: action.pinned ? true : undefined });+ case "archiveGroupTask":+ return patchGroupTask(state, action.groupId, action.threadId, { archivedAt: action.archivedAt ?? undefined });case "setConversationTurnLimit":if (!action.dm) return patchGroupTask(state, action.groupId, action.threadId, { turnTimeoutMinutes: action.minutes ?? undefined });return { ...state, groups: state.groups.map((group) => group.id === action.groupId ? { ...group, turnTimeoutMinutes: action.minutes ?? undefined } : group) };@@ -2879,23 +2883,16 @@ export function StoreProvider({ children }: { children: ReactNode }) {.catch(showError);break;case "renameGroupTask":- api(`/api/groups/${action.groupId}/tasks/${action.threadId}`, {- method: "PATCH",- body: JSON.stringify({ title: action.title }),- }).catch(showSavedState({ groupId: action.groupId }));- break;case "pinGroupTask":- api(`/api/groups/${action.groupId}/tasks/${action.threadId}`, {- method: "PATCH",- body: JSON.stringify({ pinned: action.pinned, title: action.title }),- }).catch(showSavedState({ groupId: action.groupId }));- break;- case "setConversationTurnLimit":- api(action.dm ? `/api/groups/${action.groupId}` : `/api/groups/${action.groupId}/tasks/${action.threadId}`, {- method: "PATCH",- body: JSON.stringify({ turnTimeoutMinutes: action.minutes }),- }).catch(showSavedState({ groupId: action.groupId }));+ case "archiveGroupTask":+ case "setConversationTurnLimit": {+ const body = action.type === "renameGroupTask" ? { title: action.title }+ : action.type === "pinGroupTask" ? { pinned: action.pinned, title: action.title }+ : 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 }));break;+ }case "deleteGroupTask":api<{ group?: Partial<Group> & { id: string } }>(`/api/groups/${action.groupId}/tasks/${action.threadId}`, { method: "DELETE" }).then(roomAnswer(action.groupId, false))