Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Add slash commands to check and compact conversation context
skygunnere975031fd64f
diff --git a/docs/verification/context-compaction.md b/docs/verification/context-compaction.mdindex 6f75be563b..090bc66a70 100644--- a/docs/verification/context-compaction.md+++ b/docs/verification/context-compaction.md@@ -69,6 +69,10 @@ From 80% of a known window, the bot's 1:1 header shows the figure with a**Compact now** button that calls this route (hidden again once a compactionrecord is newer than the last reply).+In an existing bot conversation, enter `/context` by itself in the composer to+open that conversation's reading. Enter `/compact` by itself to run **Compact+context**. The commands stay out of the transcript.+## Warm summaries: summarizing while the conversation is idleBoth kinds of compaction above run when the next turn starts, on the person'sdiff --git a/src/components/Composer.slash.test.ts b/src/components/Composer.slash.test.tsindex d770251154..dbbfce08f9 100644--- a/src/components/Composer.slash.test.ts+++ b/src/components/Composer.slash.test.ts@@ -48,6 +48,7 @@ describe("the / menu in the composer", () => {beforeEach(() => {dispatch.mockClear();announceArchiveNotice.mockClear();+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({})));vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});restoreComposerDraft(draftId, { text: "", attachments: [] });@@ -81,7 +82,57 @@ describe("the / menu in the composer", () => {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"]);+ expect(labels()).toEqual(["/goal", "/learn", "/setup", "/burst", "/fork", "/archive", "/delete", "/compact", "/context", "/fork-release", "/standup"]);+ });++ it("opens the current conversation's context reading without sending a message", () => {+ const withUsage = { ...bot, tasks: [{ ...bot.tasks![0]!, usage: { turns: 1, input: 0, output: 0, costUsd: null, context: { tokens: 25_000, window: 100_000 } } }] };+ flushSync(() => root.render(createElement(Composer, { bot: withUsage })));+ const input = fill("/context");+ press(input, "Enter");+ expect(input.value).toBe("");+ expect(container.querySelector("[data-context-panel] [data-context-meter]")?.getAttribute("data-context-meter")).toBe("25");+ expect(dispatch).not.toHaveBeenCalled();+ });++ it("compacts the chosen conversation without sending a message", () => {+ const withHistory: Bot = { ...bot, messages: [{ id: "visible-leaf", role: "user", kind: "text", text: "Earlier", at: 1 }] };+ flushSync(() => root.render(createElement(Composer, { bot: withHistory })));+ const fetch = vi.fn(async () => Response.json({ ok: true }, { status: 202 }));+ vi.stubGlobal("fetch", fetch);+ const input = fill("/compact");+ press(input, "Enter");+ expect(input.value).toBe("");+ expect(fetch).toHaveBeenCalledWith(expect.stringContaining(`/api/bots/${bot.id}/compact`), expect.objectContaining({ method: "POST", body: JSON.stringify({ threadId: bot.threadId }) }));+ expect(dispatch).not.toHaveBeenCalled();+ });++ it("leaves a reply draft in place when inspecting context", () => {+ const earlier = { id: "visible-leaf", role: "user" as const, kind: "text" as const, text: "Earlier", at: 1 };+ const onConsumeReply = vi.fn();+ flushSync(() => root.render(createElement(Composer, { bot, replyTo: earlier, onConsumeReply })));+ const input = fill("/context");+ press(input, "Enter");+ expect(input.value).toBe("");+ expect(container.textContent).toContain("Earlier");+ expect(onConsumeReply).not.toHaveBeenCalled();+ });++ it("does not request compaction while the bot is busy", () => {+ flushSync(() => root.render(createElement(Composer, { bot: { ...bot, busy: true } })));+ const fetch = vi.fn(async () => Response.json({}));+ vi.stubGlobal("fetch", fetch);+ const input = fill("/compact");+ press(input, "Enter");+ expect(input.value).toBe("/compact");+ expect(fetch.mock.calls).toEqual([]);+ expect(dispatch).toHaveBeenCalledWith({ type: "error", message: "Stop this bot's turn first" });+ });++ it("leaves a provider command with arguments in the message path", () => {+ const input = fill("/compact keep the design decisions");+ press(input, "Enter");+ expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ type: "send", text: "/compact keep the design decisions" }));});it("leaves the conversation commands out of a blank New thread", () => {diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex cacefe20c9..a35909194e 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -103,7 +103,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";+import { conversationCommands, useComposerThreadCommand } from "./use-composer-thread-command";const supportsAgents = (instances: InstanceInfo[], candidate?: Bot) =>Boolean(candidate && instances.find((instance) => instance.instanceId === candidate.modelSelection.instanceId)?.capabilities?.agentsMcp);@@ -306,9 +306,11 @@ export function Composer({const effectiveText = typedGoalText ?? text;// A room's threads are managed from the room, and a blank New thread has no conversation to act on yet.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 { command: threadCommand, run: runThreadCommand, dialog: threadCommandDialog, contextMenu } = useComposerThreadCommand({+ text, bot: threadCommandAvailable ? bot : undefined, threadId, mainThreadId: profile?.mainThreadId, threads: profile?.tasks,+ title: composerTask?.title, busy, dispatch, returnFocusRef: inputRef,+ clearText: () => { stopDictation(); editText(""); picks.clear(); setCaret(0); },+ onCleared: () => { editText(""); setAttachments([]); picks.clear(); setCaret(0); setDismissedSlashAt(null); onConsumeReply?.(); setChannelMode("chat"); },});const effectiveChannelMode = typedGoalText !== null ? "goal" : channelMode;const engineSupportsImages = imageTargetsSupport(effectiveText, effectiveChannelMode);@@ -343,11 +345,11 @@ 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, composerTask, canLearn, state.instances, locale, slashSkills, forkOwnerId]);+ if (builtIns && threadCommandAvailable && bot) available.push(...conversationCommands());+ available.push(...skillSlashCommands(slashSkills).filter((command) => !available.some((builtIn) => builtIn.id === command.id)));+ return available.filter((command) => slashCommandMatches(command, slash.query))+ .sort((a, b) => Number(b.id === slash.query.toLowerCase()) - Number(a.id === slash.query.toLowerCase()));+ }, [slash, dismissedSlashAt, group, bot, threadCommandAvailable, canLearn, state.instances, locale, slashSkills, forkOwnerId]);const commandPickerOpen = commandCandidates.length > 0;const mention = mentionQueryAt(text, caret); const teammates = useTeammates(); const viewer = useViewerEmail();@@ -844,7 +846,6 @@ export function Composer({// An input method's confirming Enter and arrows pick its own candidates, not a mention or command.if (imeComposing(e.nativeEvent) || suggestion.onKeyDown(e)) return;const submitsFork = fork.command && commandCandidates[highlight]?.id === "fork" && sendsMessage(e.nativeEvent, sendKey);- // 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") {@@ -959,7 +960,7 @@ export function Composer({<Square size={simpleDock ? 10 : 14} className="fill-current" /></button>)}- {!locked && <ComposerContextMenu bot={bot} group={group} members={members} className={cn(simpleDock ? "size-7" : "size-8", advanced || singleRow ? "text-ink-secondary hover:bg-raised hover:text-ink" : SIMPLE_CONTROL)} />}+ {!locked && <ComposerContextMenu bot={bot} group={group} members={members} handle={contextMenu} className={cn(simpleDock ? "size-7" : "size-8", advanced || singleRow ? "text-ink-secondary hover:bg-raised hover:text-ink" : SIMPLE_CONTROL)} />}{micShown && (<buttononClick={toggleMic}diff --git a/src/components/ComposerContextMenu.tsx b/src/components/ComposerContextMenu.tsxindex b6e798d02c..520fd5c49a 100644--- a/src/components/ComposerContextMenu.tsx+++ b/src/components/ComposerContextMenu.tsx@@ -1,9 +1,9 @@-import { useEffect, useRef, useState } from "react";+import { useEffect, useImperativeHandle, useRef, useState, type Ref } from "react";import { Gauge, RotateCcw, Shrink } from "lucide-react";import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";import { cn } from "@/lib/cn";-import { compactedSinceReading } from "@/lib/context-warning";+import { canCompactConversation, compactedSinceReading } from "@/lib/context-warning";import { contextReading, contextRowLabel, contextRows, roomContextReadings, type ContextReading, type ContextRow } from "@/lib/context-usage";import { t } from "@/lib/i18n";import { useAdvancedMode } from "@/lib/interface-mode";@@ -155,7 +155,7 @@ function ChatContext({ bot, reading, breakdown, detailed, onDone }: { bot: Bot;{rows && <Breakdown rows={rows} />}{breakdown?.autoCompact === true && <p className={MENU_NOTE}>{t("contextMenu.providerCompacts")}</p>}<div className={MENU_SEPARATOR} />- <button type="button" data-context-compact className={MENU_ROW} disabled={!idle || compactedSinceReading(messages)}+ <button type="button" data-context-compact className={MENU_ROW} disabled={compact.pending || fresh.pending || !canCompactConversation(bot, messages)}title={t(bot.busy ? "contextWarning.busy" : "contextMenu.compactHint")}onClick={() => compact.run(`/api/bots/${bot.id}/compact`, { threadId: bot.threadId })}><Shrink size={16} className={MENU_ICON} />@@ -197,8 +197,9 @@ function RoomContext({ group, members, detailed }: { group: Group; members: read);}-export function ComposerContextMenu({ bot, group, members, className }: { bot?: Bot; group?: Group; members?: readonly Bot[]; className?: string }) {+export function ComposerContextMenu({ bot, group, members, className, handle }: { bot?: Bot; group?: Group; members?: readonly Bot[]; className?: string; handle?: Ref<{ open: () => void }> }) {const [open, setOpen] = useState(false);+ useImperativeHandle(handle, () => ({ open: () => setOpen(true) }), []);const root = useRef<HTMLSpanElement>(null);const trigger = useRef<HTMLButtonElement>(null);const panel = useRef<HTMLDivElement>(null);diff --git a/src/components/use-composer-thread-command.tsx b/src/components/use-composer-thread-command.tsxindex 3265cc9877..cfe69016bb 100644--- a/src/components/use-composer-thread-command.tsx+++ b/src/components/use-composer-thread-command.tsx@@ -1,16 +1,25 @@-import { useState, type RefObject } from "react";+import { useRef, useState, type RefObject } from "react";import { t } from "@/lib/i18n";-import { threadCommandFromComposer } from "@/lib/composer-commands";-import type { Action } from "@/state/store";+import { canCompactConversation } from "@/lib/context-warning";+import { threadCommandFromComposer, type ComposerSlashCommand } from "@/lib/composer-commands";+import { visibleMessages, type Action, type Bot } from "@/state/store";import { announceArchiveNotice } from "./bot-archive";import { ConfirmDialog } from "./ConfirmDialog";+import { useContextAction } from "./ContextWarning";-/** 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 }: {+export function conversationCommands(): ComposerSlashCommand[] {+ return [+ { kind: "command", id: "archive", label: "/archive", description: t("composer.command.archiveDesc") },+ { kind: "command", id: "delete", label: "/delete", description: t("composer.command.deleteDesc") },+ { kind: "command", id: "compact", label: "/compact", description: t("contextMenu.compact") },+ { kind: "command", id: "context", label: "/context", description: t("contextMenu.title") },+ ];+}++export function useComposerThreadCommand({ text, bot, threadId, mainThreadId, threads, title, busy, dispatch, returnFocusRef, clearText, onCleared }: {text: string;- botId: string | undefined;+ bot: Bot | 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;@@ -20,11 +29,14 @@ export function useComposerThreadCommand({ text, botId, threadId, mainThreadId,busy: boolean;dispatch: (action: Action) => void;returnFocusRef?: RefObject<HTMLTextAreaElement | null>;- /** Clears the command out of the composer once it has run. */+ clearText: () => void;onCleared: () => void;}) {+ const botId = bot?.id;const command = botId ? threadCommandFromComposer(text) : null;const [confirming, setConfirming] = useState(false);+ const contextMenu = useRef<{ open: () => void }>(null);+ const compact = useContextAction();const nextThread = () => {if (!botId) return;@@ -35,7 +47,23 @@ export function useComposerThreadCommand({ text, botId, threadId, mainThreadId,if (target) dispatch({ type: "switchTask", botId, threadId: target });};const run = () => {- if (!command || !botId) return;+ if (!command || !bot || !botId) return;+ if (command === "context") {+ clearText();+ contextMenu.current?.open();+ return;+ }+ if (command === "compact") {+ if (compact.pending) return;+ if (busy) {+ dispatch({ type: "error", message: t("contextWarning.busy") });+ return;+ }+ clearText();+ if (canCompactConversation(bot, visibleMessages(bot))) compact.run(`/api/bots/${bot.id}/compact`, { threadId });+ else contextMenu.current?.open();+ return;+ }if (busy) {dispatch({ type: "error", message: t(command === "archive" ? "composer.command.archiveBusy" : "composer.command.deleteBusy") });return;@@ -73,5 +101,5 @@ export function useComposerThreadCommand({ text, botId, threadId, mainThreadId,returnFocusRef={returnFocusRef}/>);- return { command, run, dialog };+ return { command, run, dialog, contextMenu };}diff --git a/src/lib/composer-commands.ts b/src/lib/composer-commands.tsindex 8a3909d21c..94f7b738a7 100644--- a/src/lib/composer-commands.ts+++ b/src/lib/composer-commands.ts@@ -1,9 +1,9 @@import { blankCode, offersSkillCommand } from "../../shared/skill-command";-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 ComposerThreadCommand = "archive" | "delete" | "compact" | "context";++export type ComposerSlashCommandId = "goal" | "learn" | "setup" | "burst" | "fork" | ComposerThreadCommand;export type ComposerSlashCommand =| { kind: "command"; id: ComposerSlashCommandId; label: `/${ComposerSlashCommandId}`; description: string }@@ -47,9 +47,8 @@ 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);+ const match = /^\/(archive|delete|compact|context)\s*$/i.exec(text);return match ? (match[1]!.toLowerCase() as ComposerThreadCommand) : null;}diff --git a/src/lib/context-warning.ts b/src/lib/context-warning.tsindex 18fd154707..97f9593ae2 100644--- a/src/lib/context-warning.ts+++ b/src/lib/context-warning.ts@@ -3,6 +3,10 @@ import { contextShare } from "./usage";export const CONTEXT_WARNING_PERCENT = 80;+export function canCompactConversation(bot: Pick<Bot, "busy" | "switchingTo">, messages: readonly Message[]): boolean {+ return !bot.busy && !bot.switchingTo && messages.length > 0 && !messages.at(-1)?.compaction?.fresh && !compactedSinceReading(messages);+}+export function compactedSinceReading(messages: readonly Pick<Message, "role" | "kind">[]): boolean {const compaction = messages.findLastIndex((message) => message.kind === "compaction");if (compaction < 0) return false;