Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Composer: /archive and /delete act on the open conversation
erywim731f60d346fb
diff --git a/src/components/Composer.slash.test.ts b/src/components/Composer.slash.test.tsindex 4e40fd201b..52894e2ae2 100644--- a/src/components/Composer.slash.test.ts+++ b/src/components/Composer.slash.test.ts@@ -8,7 +8,9 @@ import type { Bot } from "@/state/store";import { restoreComposerDraft } from "@/lib/drafts";const dispatch = vi.hoisted(() => vi.fn());+const announceArchiveNotice = vi.hoisted(() => vi.fn());const ENGINE = "claude-3f0c2b1e-9d1a-4c55-8a51-0a3a6f1e2b7c";+vi.mock("./bot-archive", () => ({ announceArchiveNotice }));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();return { ...original, useStore: () => ({@@ -34,6 +36,7 @@ const bot: Bot = {id: "slash-bot", threadId: "slash-thread", name: "Atlas", title: "", description: "",color: "blue", notifications: false, unread: false, busy: false, messages: [], activeLeafId: "visible-leaf",modelSelection: { instanceId: ENGINE, model: "fake" },+ tasks: [{ threadId: "slash-thread", title: "A thread", createdAt: 1 }],};const draftId = `bot:${bot.id}:${bot.threadId}`;@@ -43,6 +46,7 @@ describe("the / menu in the composer", () => {beforeEach(() => {dispatch.mockClear();+ announceArchiveNotice.mockClear();vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});restoreComposerDraft(draftId, { text: "", attachments: [] });@@ -60,18 +64,27 @@ describe("the / menu in the composer", () => {vi.unstubAllGlobals();});- function fill(text: string, caret = text.length) {- flushSync(() => restoreComposerDraft(draftId, { text, attachments: [] }));+ function fillOn(draft: string, text: string, caret = text.length) {+ flushSync(() => restoreComposerDraft(draft, { text, attachments: [] }));const input = container.querySelector("textarea")!;input.setSelectionRange(caret, caret);flushSync(() => input.dispatchEvent(new KeyboardEvent("keyup", { key: "/", bubbles: true })));return input;}+ function fill(text: string, caret = text.length) {+ return fillOn(draftId, text, caret);+ }const options = () => [...document.body.querySelectorAll<HTMLElement>('[role="option"]')];const labels = () => options().map((option) => option.querySelector(".truncate")?.textContent);const press = (input: HTMLTextAreaElement, key: string) => flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true })));it("offers the built-in commands and skills at the start of a message", () => {+ fill("/");+ expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/fork", "/archive", "/delete", "/fork-release", "/standup"]);+ });++ it("leaves the conversation commands out of a blank New thread", () => {+ flushSync(() => root.render(createElement(Composer, { bot: { ...bot, tasks: [] } })));fill("/");expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/fork", "/fork-release", "/standup"]);});@@ -131,6 +144,74 @@ describe("the / menu in the composer", () => {expect(input.value).toBe("use /standup later");});+ it("archives the conversation on /archive, with Undo", () => {+ const input = fill("/archive");+ press(input, "Enter");+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({+ type: "updateTask", botId: bot.id, threadId: bot.threadId,+ patch: { archivedAt: expect.any(Number) },+ }));+ expect(input.value).toBe("");+ const notice = announceArchiveNotice.mock.calls.at(-1)?.[0];+ expect(notice.text).toBe("Conversation archived");+ notice.undo();+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({+ type: "updateTask", botId: bot.id, threadId: bot.threadId, patch: { archivedAt: null },+ }));+ });++ it("returns to the bot's main conversation after archiving another one", () => {+ const child = {+ ...bot, threadId: "child-thread", mainThreadId: bot.threadId,+ tasks: [+ { threadId: "child-thread", title: "Child", createdAt: 2 },+ { threadId: bot.threadId, title: "Main", createdAt: 1 },+ ],+ };+ flushSync(() => root.render(createElement(Composer, { bot: child })));+ const input = fillOn("bot:slash-bot:child-thread", "/archive");+ press(input, "Enter");+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "updateTask", threadId: "child-thread" }));+ expect(dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: bot.id, threadId: bot.threadId });+ restoreComposerDraft("bot:slash-bot:child-thread", { text: "", attachments: [] });+ });++ it("opens the next active conversation when the bot has no main one", () => {+ const child = {+ ...bot, threadId: "child-thread",+ tasks: [+ { threadId: "child-thread", title: "Child", createdAt: 1, updatedAt: 1 },+ { threadId: "other-thread", title: "Other", createdAt: 2, updatedAt: 3 },+ ],+ };+ flushSync(() => root.render(createElement(Composer, { bot: child })));+ const input = fillOn("bot:slash-bot:child-thread", "/archive");+ press(input, "Enter");+ expect(dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: bot.id, threadId: "other-thread" });+ restoreComposerDraft("bot:slash-bot:child-thread", { text: "", attachments: [] });+ });++ it("asks before deleting a conversation on /delete", () => {+ const input = fill("/delete");+ press(input, "Enter");+ expect(dispatch).not.toHaveBeenCalled();+ const dialog = document.body.querySelector('[role="alertdialog"]')!;+ expect(dialog.textContent).toContain("Delete thread?");+ const confirm = [...dialog.querySelectorAll("button")].find((button) => button.textContent === "Delete thread")!;+ flushSync(() => confirm.click());+ expect(dispatch).toHaveBeenCalledWith({ type: "deleteTask", botId: bot.id, threadId: bot.threadId });+ expect(document.body.querySelector('[role="alertdialog"]')).toBeNull();+ });++ it("refuses /archive while a turn runs, and keeps the command in place", () => {+ flushSync(() => root.render(createElement(Composer, { bot: { ...bot, busy: true } })));+ const input = fill("/archive");+ press(input, "Enter");+ expect(dispatch).toHaveBeenCalledWith({ type: "error", message: "Stop this conversation before archiving it." });+ expect(dispatch.mock.calls.some(([action]) => action.type === "updateTask")).toBe(false);+ expect(input.value).toBe("/archive");+ });+it("opens nothing inside a path or link", () => {fill("open notes/st");expect(options()).toEqual([]);diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 27ae7d0a24..0838fc706f 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -102,6 +102,7 @@ import {} from "@/lib/composer-commands";import { useSlashSkills } from "@/lib/use-slash-skills";import { randomUuid } from "@/lib/random-uuid";+import { useComposerThreadCommand } from "./use-composer-thread-command";const supportsAgents = (instances: InstanceInfo[], candidate?: Bot) =>Boolean(candidate && instances.find((instance) => instance.instanceId === candidate.modelSelection.instanceId)?.capabilities?.agentsMcp);@@ -303,6 +304,14 @@ export function Composer({};const typedGoalText = !group?.dm ? goalTextFromComposer(text) : null;const effectiveText = typedGoalText ?? text;+ // /archive and /delete act on this conversation; a room's threads are managed from the room, and a blank New thread+ // has no conversation to act on yet, so neither offers the commands.+ const threadCommandAvailable = !group && Boolean(composerTask);+ const { command: threadCommand, run: runThreadCommand, dialog: threadCommandDialog } = useComposerThreadCommand({+ text: threadCommandAvailable ? text : "", botId: threadCommandAvailable ? bot?.id : undefined, threadId, mainThreadId: profile?.mainThreadId, threads: profile?.tasks,+ title: composerTask?.title, busy, dispatch, returnFocusRef: inputRef,+ onCleared: () => { editText(""); setAttachments([]); picks.clear(); setCaret(0); setDismissedSlashAt(null); onConsumeReply?.(); setChannelMode("chat"); },+ });const effectiveChannelMode = typedGoalText !== null ? "goal" : channelMode;const engineSupportsImages = imageTargetsSupport(effectiveText, effectiveChannelMode);@@ -336,9 +345,13 @@ export function Composer({description: t("composer.command.setupDesc"),}, { kind: "command", id: "burst", label: "/burst", description: t("composer.command.burstDesc") });if (builtIns && forkOwnerId) available.push({ kind: "command", id: "fork", label: "/fork", description: t("composer.command.forkDesc") });+ if (builtIns && !group && bot && composerTask) available.push(+ { kind: "command", id: "archive", label: "/archive", description: t("composer.command.archiveDesc") },+ { kind: "command", id: "delete", label: "/delete", description: t("composer.command.deleteDesc") },+ );available.push(...skillSlashCommands(slashSkills).filter((command) => !(builtIns && forkOwnerId && command.id === "fork")));return available.filter((command) => slashCommandMatches(command, slash.query));- }, [slash, dismissedSlashAt, group, bot, canLearn, state.instances, locale, slashSkills, forkOwnerId]);+ }, [slash, dismissedSlashAt, group, bot, composerTask, canLearn, state.instances, locale, slashSkills, forkOwnerId]);const commandPickerOpen = commandCandidates.length > 0;const mention = mentionQueryAt(text, caret); const teammates = useTeammates(); const viewer = useViewerEmail();@@ -566,6 +579,7 @@ export function Composer({};const send = (followUp: FollowUp | undefined = followUpFor(false)) => {if (locked || attachmentPending) return;+ if (threadCommand) { setDismissedSlashAt(slash?.start ?? 0); runThreadCommand(); return; }if (fork.command) {setDismissedSlashAt(slash?.start ?? 0);fork.submit();@@ -832,7 +846,9 @@ export function Composer({// An input method's confirming Enter and arrows pick its own candidates, not a mention or command.if (imeComposing(e.nativeEvent)) return;const submitsFork = fork.command && commandCandidates[highlight]?.id === "fork" && sendsMessage(e.nativeEvent, sendKey);- if (commandPickerOpen && !submitsFork) {+ // A complete /archive or /delete is its own action: Enter runs it instead of only completing the word.+ const submitsThreadCommand = Boolean(threadCommand) && commandCandidates[highlight]?.id === threadCommand && sendsMessage(e.nativeEvent, sendKey);+ if (commandPickerOpen && !submitsFork && !submitsThreadCommand) {if (e.key === "ArrowDown" || e.key === "ArrowUp") {e.preventDefault();const delta = e.key === "ArrowDown" ? 1 : -1;@@ -978,6 +994,7 @@ export function Composer({<div className="pointer-events-auto">{approvalDialogs}</div>+ {threadCommandDialog}</div>);}diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex 09ec7866e4..239f7b1ae5 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -101,7 +101,7 @@ import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";import { useAdvancedMode } from "@/lib/interface-mode"; import { useRoomFeed } from "./room-feed/use-room-feed"; import { feedPreview } from "@/lib/room-feed";import { myDefaultBot, useViewerEmail, useWelcomingBot } from "@/lib/default-bot";import { PinnedBotRoster, PinnedCircleThreadSection } from "./PinnedCircleThreads";-import { archiveBotWithNotice, onArchiveNotice } from "./bot-archive";+import { archiveBotWithNotice, onArchiveNotice, type ArchiveNotice } from "./bot-archive";import { ArchivedBotsPanel, botConfirmProps, type BotConfirmKind } from "./ArchivedBotsPanel"; import { MovedBotRows } from "./MoveToTeam"; import { MovedToMyCloudRow } from "./MoveToMyCloud";import { NewRoomPanel } from "./SidebarNewRoomPanel";import { SectionPicker } from "./SidebarSectionPicker";@@ -974,11 +974,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const [teamLibraryOpen, setTeamLibraryOpen] = useState(false);const [importUrl, setImportUrl] = useState<string | null>(null);const [archivedBotsOpen, setArchivedBotsOpen] = useState(false);- const [teamFeedback, setTeamFeedback] = useState<{- error: boolean;- text: string;- restoreBot?: { id: string; name: string };- } | null>(null);+ const [teamFeedback, setTeamFeedback] = useState<ArchiveNotice | null>(null);const [query, setQuery] = useState("");const storedDensity = useSidebarDensity();const density = collapseToIcons ? "icons" : storedDensity;@@ -1122,7 +1118,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =const archivedEntry = remoteClient ? undefined : { count: archivedBots.length, open: () => setArchivedBotsOpen(true) };const showAttention = (advanced && inboxSupport === "no") || (attentionPinned && density !== "icons");const attention = showAttention ? crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups) : [];- const pendingBotUndo = teamFeedback?.restoreBot;+ const restoreBot = teamFeedback?.restoreBot, pendingUndo = teamFeedback?.undo ?? (restoreBot ? () => void undoBotArchive(restoreBot) : undefined);const botRow = (bot: Bot) => isPlacedBot(bot) ? botRowProps(state, otherPlaceDispatch(bot), bot, { density, query: q, onMenu: NO_MENU, placeHere }) : botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, placeHere, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });const railSearch = () => {if (collapseToIcons) return openCommandPalette();@@ -1640,9 +1636,9 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =><div className="flex items-center gap-3"><span>{teamFeedback.text}</span>- {pendingBotUndo && (+ {pendingUndo && (<button- onClick={() => void undoBotArchive(pendingBotUndo)}+ onClick={() => { setTeamFeedback(null); void pendingUndo(); }}className="rounded-md px-1.5 py-0.5 font-medium text-accent hover:bg-raised">{t("common.undo")}diff --git a/src/components/bot-archive.ts b/src/components/bot-archive.tsindex 0ba5d6d1e2..979d0a70c1 100644--- a/src/components/bot-archive.ts+++ b/src/components/bot-archive.ts@@ -6,6 +6,8 @@ export interface ArchiveNotice {error: boolean;text: string;restoreBot?: { id: string; name: string };+ /** Undo for something other than a bot, such as a conversation archived from the composer. */+ undo?: () => void;}const listeners = new Set<(notice: ArchiveNotice | null) => void>();diff --git a/src/components/use-composer-thread-command.tsx b/src/components/use-composer-thread-command.tsxnew file mode 100644index 0000000000..37185c7752--- /dev/null+++ b/src/components/use-composer-thread-command.tsx@@ -0,0 +1,76 @@+import { useState, type RefObject } from "react";++import { t } from "@/lib/i18n";+import { threadCommandFromComposer } from "@/lib/composer-commands";+import type { Action } from "@/state/store";+import { announceArchiveNotice } from "./bot-archive";+import { ConfirmDialog } from "./ConfirmDialog";++/** A bot conversation's /archive and /delete, as the composer runs them: the command, its action, and the notice and+ * confirmation they show. A room's threads are managed from the room, so text given no bot has no command. */+export function useComposerThreadCommand({ text, botId, threadId, mainThreadId, threads, title, busy, dispatch, returnFocusRef, onCleared }: {+ text: string;+ botId: string | undefined;+ threadId: string;+ /** The conversation the person set as main, opened after this one leaves the list when it is not archived. */+ mainThreadId: string | undefined;+ /** The bot's conversations, for the next active one when there is no main to open. */+ threads: ReadonlyArray<{ threadId: string; updatedAt?: number; createdAt?: number; archivedAt?: number; routineRunId?: string }> | undefined;+ title: string | undefined;+ busy: boolean;+ dispatch: (action: Action) => void;+ returnFocusRef?: RefObject<HTMLTextAreaElement | null>;+ /** Clears the command out of the composer once it has run. */+ onCleared: () => void;+}) {+ const command = botId ? threadCommandFromComposer(text) : null;+ const [confirming, setConfirming] = useState(false);++ const nextThread = () => {+ if (!botId) return;+ const rest = (threads ?? []).filter((thread) => thread.threadId !== threadId && thread.archivedAt === undefined && thread.routineRunId === undefined);+ const target = mainThreadId && mainThreadId !== threadId && rest.some((thread) => thread.threadId === mainThreadId)+ ? mainThreadId+ : rest.sort((a, b) => (b.updatedAt ?? b.createdAt ?? 0) - (a.updatedAt ?? a.createdAt ?? 0))[0]?.threadId;+ if (target) dispatch({ type: "switchTask", botId, threadId: target });+ };+ const run = () => {+ if (!command || !botId) return;+ if (busy) {+ dispatch({ type: "error", message: t(command === "archive" ? "composer.command.archiveBusy" : "composer.command.deleteBusy") });+ return;+ }+ if (command === "delete") { setConfirming(true); return; }+ const archivedThreadId = threadId;+ dispatch({ type: "updateTask", botId, threadId, patch: { archivedAt: Date.now() } });+ onCleared();+ nextThread();+ // The sidebar's notice outlives this composer, which the conversation switch remounts.+ announceArchiveNotice({+ error: false,+ text: t("composer.command.archived"),+ undo: () => dispatch({ type: "updateTask", botId, threadId: archivedThreadId, patch: { archivedAt: null } }),+ });+ };+ const confirmDelete = () => {+ if (!botId) return;+ setConfirming(false);+ dispatch({ type: "deleteTask", botId, threadId });+ onCleared();+ nextThread();+ };++ const dialog = (+ <ConfirmDialog+ open={confirming}+ title={t("task.deleteConfirm")}+ body={t("task.deleteBody", { title: title || t("task.untitledConversation") })}+ confirmLabel={t("task.deleteAria")}+ tone="danger"+ onCancel={() => setConfirming(false)}+ onConfirm={confirmDelete}+ returnFocusRef={returnFocusRef}+ />+ );+ return { command, run, dialog };+}diff --git a/src/lib/composer-commands.test.ts b/src/lib/composer-commands.test.tsindex d640b9f4e5..547a60305f 100644--- a/src/lib/composer-commands.test.ts+++ b/src/lib/composer-commands.test.ts@@ -6,6 +6,7 @@ import {replaceComposerSlashTrigger,skillSlashCommands,slashCommandMatches,+ threadCommandFromComposer,type ComposerSlashCommandId, builtInCommandText } from "./composer-commands";import { enabledSlashSkills } from "./use-slash-skills";@@ -73,6 +74,15 @@ describe("composer slash commands", () => {expect(goalTextFromComposer("discuss /goal later")).toBeNull();});+ it("reads a whole /archive or /delete as a command on the conversation", () => {+ expect(threadCommandFromComposer("/archive")).toBe("archive");+ expect(threadCommandFromComposer("/ARCHIVE ")).toBe("archive");+ expect(threadCommandFromComposer("/delete")).toBe("delete");+ expect(threadCommandFromComposer("/archive this")).toBeNull();+ expect(threadCommandFromComposer("please /delete")).toBeNull();+ expect(threadCommandFromComposer("/deleted")).toBeNull();+ });+it("offers setup as a slash command id and keeps the typed token", () => {const id: ComposerSlashCommandId = "setup";expect(id).toBe("setup");@@ -122,6 +132,8 @@ describe("burst", () => {expect(builtInCommandText("burst")).toBe("/burst ");expect(builtInCommandText("learn")).toBe("/learn ");expect(builtInCommandText("setup")).toBe("/setup ");+ expect(builtInCommandText("archive")).toBe("/archive ");+ expect(builtInCommandText("delete")).toBe("/delete ");expect(builtInCommandText("goal")).toBe("");});});diff --git a/src/lib/composer-commands.ts b/src/lib/composer-commands.tsindex 618f6a82b0..8a3909d21c 100644--- a/src/lib/composer-commands.ts+++ b/src/lib/composer-commands.ts@@ -1,6 +1,9 @@import { blankCode, offersSkillCommand } from "../../shared/skill-command";-export type ComposerSlashCommandId = "goal" | "learn" | "setup" | "burst" | "fork";+export type ComposerSlashCommandId = "goal" | "learn" | "setup" | "burst" | "fork" | "archive" | "delete";++/** A command that acts on the conversation itself instead of sending a message. */+export type ComposerThreadCommand = "archive" | "delete";export type ComposerSlashCommand =| { kind: "command"; id: ComposerSlashCommandId; label: `/${ComposerSlashCommandId}`; description: string }@@ -44,6 +47,12 @@ export function goalTextFromComposer(text: string): string | null {return match ? (match[1] ?? "").trimStart() : null;}+/** A whole `/archive` or `/delete` on its own, which acts on the conversation rather than sending words. */+export function threadCommandFromComposer(text: string): ComposerThreadCommand | null {+ const match = /^\/(archive|delete)\s*$/i.exec(text);+ return match ? (match[1]!.toLowerCase() as ComposerThreadCommand) : null;+}+/** The text a picked built-in leaves in the composer; /goal only flips the composer's mode. */export function builtInCommandText(id: ComposerSlashCommandId): string {return id === "goal" ? "" : `/${id} `;diff --git a/src/locales/en.json b/src/locales/en.jsonindex c86657d93e..95e52cfaaf 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3038,6 +3038,11 @@"composer.command.setupDesc": "Have this bot interview you and set itself up","composer.command.burstDesc": "Run many parts of a job at once, then merge the results","composer.command.forkDesc": "Fork from the latest text message",+ "composer.command.archiveDesc": "Archive this conversation",+ "composer.command.deleteDesc": "Delete this conversation",+ "composer.command.archived": "Conversation archived",+ "composer.command.archiveBusy": "Stop this conversation before archiving it.",+ "composer.command.deleteBusy": "Stop this conversation before deleting it.","burst.title": "Burst: {task}","burst.plan": "{count} tasks · {model} · {parallel} at once · about {minutes} min","burst.moreItems": "+{count} more",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 0840202a50..7445333c11 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -2826,6 +2826,11 @@"composer.command.setupDesc": "Pedir a este bot que entreviste você e se configure sozinho","composer.command.burstDesc": "Executar muitas partes de um trabalho ao mesmo tempo e juntar os resultados","composer.command.forkDesc": "Criar uma bifurcação a partir da mensagem de texto mais recente",+ "composer.command.archiveDesc": "Arquivar esta conversa",+ "composer.command.deleteDesc": "Excluir esta conversa",+ "composer.command.archived": "Conversa arquivada",+ "composer.command.archiveBusy": "Pare esta conversa antes de arquivá-la.",+ "composer.command.deleteBusy": "Pare esta conversa antes de excluí-la.","burst.title": "Burst: {task}","burst.plan": "{count} tarefas · {model} · {parallel} ao mesmo tempo · cerca de {minutes} min","burst.moreItems": "+{count} a mais",