Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

feat(shortcuts): run Start fresh from the keyboard

TuanNancy7101f691ab4a
diff --git a/src/App.start-fresh.test.ts b/src/App.start-fresh.test.ts
new file mode 100644
index 0000000000..64f597ebea
--- /dev/null
+++ b/src/App.start-fresh.test.ts
@@ -0,0 +1,96 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { initialState, type Action, type AppState, type Bot, type Message } from "./state/store";
+
+const text: Message = { id: "m1", role: "user", kind: "text", text: "hello", at: 1 };
+const fresh: Message = {
+ id: "m2", role: "bot", kind: "compaction", at: 2, parentId: "m1",
+ compaction: { summary: "", firstKeptId: "", foldedThroughId: "m1", tokensBefore: 0, by: "person", fresh: true },
+};
+const bot: Bot = {
+ id: "pepper", threadId: "side", name: "Pepper", title: "", description: "", color: "green",
+ notifications: true, unread: false, busy: false, messages: [text], activeLeafId: "m1",
+ modelSelection: { instanceId: "test", model: "m" },
+};
+
+let state: AppState;
+let dispatched: Action[];
+vi.mock("./state/store", async (original) => ({
+ ...await original<typeof import("./state/store")>(),
+ StoreProvider: ({ children }: { children: unknown }) => children,
+ useStore: () => ({ state, dispatch: (action: Action) => { dispatched.push(action); }, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} }),
+}));
+vi.mock("./lib/analytics", () => ({ initAnalytics: () => {}, track: () => {}, emailGateDone: () => true }));
+const { default: App } = await import("./App");
+
+let fetched: ReturnType<typeof vi.fn>;
+let container: HTMLDivElement;
+let root: Root;
+
+const render = () => {
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ rerender();
+};
+const rerender = () => flushSync(() => root.render(createElement(App)));
+const press = async (init: KeyboardEventInit = {}) => {
+ window.dispatchEvent(new KeyboardEvent("keydown", { key: "K", metaKey: true, shiftKey: true, bubbles: true, ...init }));
+ await Promise.resolve();
+};
+const startFreshCalls = () => fetched.mock.calls.filter(([url]) => String(url).includes("/start-fresh"));
+
+beforeEach(() => {
+ state = { ...initialState, connected: true, hydrated: true, selectedId: bot.id, bots: [bot] };
+ dispatched = [];
+ fetched = vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } }));
+ vi.stubGlobal("fetch", fetched);
+ (window as { ogb?: unknown }).ogb = { environments: { onOpenSettings: () => () => {} } };
+ render();
+});
+afterEach(() => {
+ root.unmount();
+ container.remove();
+ delete (window as { ogb?: unknown }).ogb;
+ vi.unstubAllGlobals();
+});
+
+it("starts the selected chat fresh on ⌘⇧K", async () => {
+ await press();
+ expect(startFreshCalls()).toHaveLength(1);
+ const [url, init] = startFreshCalls()[0]!;
+ expect(url).toBe("/api/bots/pepper/start-fresh");
+ expect(init?.method).toBe("POST");
+ expect(JSON.parse(String(init?.body))).toEqual({ threadId: "side" });
+});
+
+it("leaves the shortcut alone while busy, empty, already fresh, read-only or with the shortcut sheet open", async () => {
+ for (const change of [
+ { bots: [{ ...bot, busy: true }] },
+ { bots: [{ ...bot, messages: [] }] },
+ { bots: [{ ...bot, messages: [text, fresh], activeLeafId: "m2" }] },
+ { bots: [{ ...bot, yourAccess: "view" as const }] },
+ { activeView: "routines" as const },
+ { shortcutsOpen: true },
+ ]) {
+ state = { ...state, ...change };
+ rerender();
+ await press();
+ }
+ expect(startFreshCalls()).toHaveLength(0);
+});
+
+it("sends one request for presses made before the first settles", async () => {
+ let release: (value: Response) => void = () => {};
+ fetched.mockImplementation(() => new Promise<Response>((resolve) => { release = resolve; }));
+ await press();
+ await press({ repeat: true });
+ expect(startFreshCalls()).toHaveLength(1);
+ release(new Response("{}", { status: 200, headers: { "content-type": "application/json" } }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await press();
+ expect(startFreshCalls()).toHaveLength(2);
+});
diff --git a/src/App.tsx b/src/App.tsx
index f09cdafaa0..9747ebd98d 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -77,6 +77,7 @@ import { engineReady } from "@/components/EngineLibrary";
import { CommandPalette } from "@/components/CommandPalette";
import { t } from "@/lib/i18n";
import { botCycleStep, shouldOpenKeyboardShortcuts } from "@/lib/keyboard-shortcuts";
+import { isStartFreshShortcut, startFreshRefusal } from "@/lib/start-fresh";
import { useThreadCycleKeys } from "@/components/thread-cycle";
import { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";
import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";
@@ -103,6 +104,7 @@ import { FilePreviewPanel } from "@/components/FilePreviewPanel";
import { refreshPublishedApps } from "@/lib/own-published-apps";
import { serverFetch } from "@/lib/relay-server";
import { replaceUrl } from "@/lib/replace-url";
+import { api } from "@/state/api";
function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const { state, dispatch } = useStore();
@@ -180,6 +182,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const [localVmWorkspaceBotId, setLocalVmWorkspaceBotId] = useState<string | null>(null);
const menuButtonRef = useRef<HTMLButtonElement>(null);
const previousViewRef = useRef(state.activeView);
+ const freshPending = useRef(new Set<string>());
const calendarOriginRef = useRef<"chat" | "team-map" | "web-panel">("chat");
const loading = loadingLine({ connected: state.connected, hydrated: state.hydrated === true, developer: import.meta.env.DEV });
const group = state.groups.find((g) => g.id === state.selectedId);
@@ -258,6 +261,24 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const bots = shortcutBots(state.bots.filter((b) => !b.hidden), shownBotIds(document.querySelector("[data-sidebar-root]")));
const step = e.shiftKey ? botCycleStep(e) : null;
const newThreadKey = e.key.toLowerCase() === "t" && !e.shiftKey && !e.altKey;
+ if (isStartFreshShortcut(e)) {
+ const selected = state.bots.find((bot) => bot.id === state.selectedId && !bot.hidden);
+ if (
+ !e.repeat && selected && chatBot && state.activeView === "chat"
+ && selected.yourAccess !== "view" && startFreshRefusal(chatBot) === null
+ && !freshPending.current.has(selected.id)
+ ) {
+ e.preventDefault();
+ freshPending.current.add(selected.id);
+ void api(`/api/bots/${selected.id}/start-fresh`, {
+ method: "POST",
+ body: JSON.stringify({ threadId: chatBot.threadId }),
+ })
+ .catch((cause: unknown) => dispatch({ type: "error", message: cause instanceof Error ? cause.message : String(cause) }))
+ .finally(() => freshPending.current.delete(selected.id));
+ }
+ return;
+ }
if ((e.key.toLowerCase() === "n" || newThreadKey) && !e.altKey) {
e.preventDefault();
if (e.shiftKey || newThreadKey) {
@@ -282,7 +303,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
- }, [state.bots, state.selectedId, state.shortcutsOpen, showThreads, dispatch]);
+ }, [state.bots, state.selectedId, state.activeView, state.shortcutsOpen, chatBot, showThreads, dispatch]);
useThreadCycleKeys();
useReadShownChatOnFocus();
diff --git a/src/components/ChatMoreMenu.test.ts b/src/components/ChatMoreMenu.test.ts
index 33636166ae..3048d17e43 100644
--- a/src/components/ChatMoreMenu.test.ts
+++ b/src/components/ChatMoreMenu.test.ts
@@ -127,6 +127,22 @@ describe("ChatMoreMenu, the round ⋯ for the bot panel", () => {
} finally {
delete win.ogb;
}
+ });
+
+ it("shows the platform Start fresh chord beside the menu item", () => {
+ const win = globalThis.window as { ogb?: { platform?: string } };
+ try {
+ for (const [platform, expected] of [["darwin", "⌘ ⇧ K"], ["win32", "Ctrl Shift K"]] as const) {
+ win.ogb = { platform };
+ const item = menuOf(createElement(ChatMoreMenu, { bot })).items.find((one) => one.key === "start-fresh")!;
+ expect(renderToStaticMarkup(createElement("div", null, item.trailing))).toContain(expected);
+ }
+ } finally {
+ delete win.ogb;
+ }
+ });
+
+ it("starts a new thread with the bot", () => {
const menu = menuOf(createElement(ChatMoreMenu, { bot }));
menu.items.find((item) => item.key === "new-thread")!.onSelect();
expect(fixture.dispatch).toHaveBeenCalledWith({ type: "newTask", botId: "pepper" });
diff --git a/src/components/ChatMoreMenu.tsx b/src/components/ChatMoreMenu.tsx
index a452603fbe..e2018d7b01 100644
--- a/src/components/ChatMoreMenu.tsx
+++ b/src/components/ChatMoreMenu.tsx
@@ -129,6 +129,7 @@ export function useChatMoreItems(profile: Bot, phoneHeader = false): { items: Si
icon: <RotateCcw size={16} />,
disabled: bot.busy || contextAction.pending || !hasMessages || atFreshStart,
title: t(bot.busy ? "contextWarning.busy" : "chat.startFresh.hint"),
+ trailing: <ShortcutHint id="start-fresh" />,
onSelect: () => contextAction.run(`/api/bots/${profile.id}/start-fresh`, { threadId: bot.threadId }),
},
...shareItems,
diff --git a/src/components/ComposerContextMenu.test.ts b/src/components/ComposerContextMenu.test.ts
index ce3aba995d..304168c7f3 100644
--- a/src/components/ComposerContextMenu.test.ts
+++ b/src/components/ComposerContextMenu.test.ts
@@ -31,7 +31,12 @@ const render = (props: Parameters<typeof ComposerContextMenu>[0]) => act(async (
const trigger = () => host.querySelector<HTMLButtonElement>("[data-composer-context] > button")!;
const panel = () => host.querySelector<HTMLElement>("[data-context-panel]");
const press = (element: HTMLElement) => act(async () => { element.click(); await new Promise((resolve) => setTimeout(resolve, 0)); });
-const words = () => panel()!.textContent!.replace(/\s+/g, " ");
+const withoutHints = (node: HTMLElement) => {
+ const clone = node.cloneNode(true) as HTMLElement;
+ for (const hidden of clone.querySelectorAll('[aria-hidden="true"]')) hidden.remove();
+ return clone.textContent ?? "";
+};
+const words = () => withoutHints(panel()!).replace(/\s+/g, " ");
const requests = () => fetched.mock.calls.map(([url, init]) => [String(url).replace(/^.*(?=\/api\/)/, ""), JSON.parse(String((init as RequestInit).body))]);
const advancedMode = () => localStorage.setItem(ADVANCED_MODE_KEY, "1");
const posted = () => requests().filter(([path]) => !path.endsWith("/context"));
@@ -76,13 +81,27 @@ describe("the composer's context button", () => {
expect(trigger().getAttribute("aria-expanded")).toBe("true");
expect(words()).toBe("Context68% usedCompact contextStart fresh");
expect(panel()!.querySelector("[data-context-meter]")!.getAttribute("data-context-meter")).toBe("68");
- expect([...panel()!.querySelectorAll("button")].map((button) => [button.textContent, button.disabled]))
+ expect([...panel()!.querySelectorAll("button")].map((button) => [withoutHints(button).trim(), button.disabled]))
.toEqual([["Compact context", false], ["Start fresh", false]]);
expect(requests()).toEqual([]);
await act(async () => { window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); });
expect(panel()).toBeNull();
});
+ it("names the Start fresh chord on its menu row", async () => {
+ const win = globalThis.window as unknown as { ogb?: { platform?: string } };
+ win.ogb = { platform: "win32" };
+ try {
+ await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });
+ await press(trigger());
+ const row = panel()!.querySelector<HTMLButtonElement>("[data-context-fresh]")!;
+ expect(row.getAttribute("aria-keyshortcuts")).toBe("Meta+Shift+K Control+Shift+K");
+ expect(row.querySelector("kbd")!.textContent).toBe("Ctrl Shift K");
+ } finally {
+ delete win.ogb;
+ }
+ });
+
it("compacts through the chat's own route and stays open; starting fresh closes it", async () => {
await render({ bot: chat({ tokens: 136_000, window: 200_000 }) });
await press(trigger());
diff --git a/src/components/ComposerContextMenu.tsx b/src/components/ComposerContextMenu.tsx
index 1e5fe2e9dd..cbf04b85a5 100644
--- a/src/components/ComposerContextMenu.tsx
+++ b/src/components/ComposerContextMenu.tsx
@@ -13,6 +13,7 @@ import { visibleMessages, type Bot, type Group, type Message } from "@/state/sto
import type { ContextBreakdown } from "../../shared/context-breakdown";
import { useContextAction } from "./ContextWarning";
import { MENU_ICON, MENU_LABEL, MENU_NOTE, MENU_ROW, MENU_SEPARATOR, MENU_SHEET } from "./menu-recipe";
+import { ShortcutHint } from "./ShortcutHint";
const TONE_INK: Record<ContextTone, string> = { quiet: "", warning: "text-warning", danger: "text-danger" };
const TONE_FILL: Record<ContextTone, string> = { quiet: "bg-ink-tertiary", warning: "bg-warning", danger: "bg-danger" };
@@ -162,9 +163,11 @@ function ChatContext({ bot, reading, breakdown, detailed, onDone }: { bot: Bot;
</button>
<button type="button" data-context-fresh className={MENU_ROW} disabled={!idle}
title={t(bot.busy ? "contextWarning.busy" : "chat.startFresh.hint")}
+ aria-keyshortcuts="Meta+Shift+K Control+Shift+K"
onClick={() => { fresh.run(`/api/bots/${bot.id}/start-fresh`, { threadId: bot.threadId }); onDone(); }}>
<RotateCcw size={16} className={MENU_ICON} />
<span className="min-w-0 truncate">{t("chat.startFresh")}</span>
+ <span className="ms-auto"><ShortcutHint id="start-fresh" /></span>
</button>
</>
);
diff --git a/src/lib/keyboard-shortcuts.test.ts b/src/lib/keyboard-shortcuts.test.ts
index df8d350b52..93adb42fe0 100644
--- a/src/lib/keyboard-shortcuts.test.ts
+++ b/src/lib/keyboard-shortcuts.test.ts
@@ -12,6 +12,7 @@ import {
shortcutDescription,
} from "./keyboard-shortcuts";
import { setLocale } from "./i18n";
+import { en } from "@/locales";
afterEach(() => setLocale("en"));
@@ -41,6 +42,13 @@ describe("keyboard-shortcuts", () => {
expect(isSidebarToggle({ ...chord, defaultPrevented: true })).toBe(false);
});
+ it("lists Start fresh with its chord and a catalogued description", () => {
+ const item = SHORTCUT_GROUPS.flatMap((group) => group.items).find((entry) => entry.id === "start-fresh")!;
+ expect(item).toMatchObject({ macKeys: ["⌘", "⇧", "K"], winKeys: ["Ctrl", "Shift", "K"] });
+ expect(Object.hasOwn(en, "shortcuts.start-fresh")).toBe(true);
+ expect(shortcutDescription(item)).toBe("Start fresh in this conversation (keeps the messages)");
+ });
+
it("defines unique IDs and non-empty key lists for all shortcuts", () => {
const ids = new Set<string>();
diff --git a/src/lib/keyboard-shortcuts.ts b/src/lib/keyboard-shortcuts.ts
index c081b2459a..79c8d8d1fb 100644
--- a/src/lib/keyboard-shortcuts.ts
+++ b/src/lib/keyboard-shortcuts.ts
@@ -1,4 +1,5 @@
import type { SendKey } from "./send-key";
+import { START_FRESH_KEYS } from "./start-fresh";
import { t } from "@/lib/i18n";
import { en, type LocaleKey } from "@/locales";
@@ -95,6 +96,12 @@ export const SHORTCUT_GROUPS: readonly ShortcutGroup[] = [
macKeys: ["↑"],
winKeys: ["↑"],
},
+ {
+ id: "start-fresh",
+ description: "Start fresh in this conversation (keeps the messages)",
+ macKeys: [...START_FRESH_KEYS.mac],
+ winKeys: [...START_FRESH_KEYS.win],
+ },
{
id: "dictation-toggle",
description: "Start or stop dictation",
diff --git a/src/lib/start-fresh.test.ts b/src/lib/start-fresh.test.ts
new file mode 100644
index 0000000000..29e005f097
--- /dev/null
+++ b/src/lib/start-fresh.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest";
+import type { Bot, Message } from "@/state/store";
+import { isStartFreshShortcut, startFreshRefusal } from "./start-fresh";
+
+const chord = (init: Partial<Parameters<typeof isStartFreshShortcut>[0]> = {}) => ({
+ key: "K", metaKey: false, ctrlKey: false, shiftKey: false, altKey: false,
+ defaultPrevented: false, isComposing: false, ...init,
+});
+
+const message: Message = { id: "m1", role: "bot", kind: "text", text: "Hello", at: 1 };
+const fresh: Message = {
+ id: "m2", role: "bot", kind: "compaction", at: 2, parentId: "m1",
+ compaction: { summary: "", firstKeptId: "", foldedThroughId: "m1", tokensBefore: 0, by: "person", fresh: true },
+};
+const bot = (messages: Message[], activeLeafId: string | null = messages.at(-1)?.id ?? null, busy = false): Pick<Bot, "busy" | "messages" | "activeLeafId"> => ({ busy, messages, activeLeafId });
+
+describe("isStartFreshShortcut", () => {
+ it("matches ⌘⇧K and Ctrl+Shift+K", () => {
+ expect(isStartFreshShortcut(chord({ metaKey: true, shiftKey: true }))).toBe(true);
+ expect(isStartFreshShortcut(chord({ ctrlKey: true, shiftKey: true }))).toBe(true);
+ expect(isStartFreshShortcut(chord({ key: "k", metaKey: true, shiftKey: true }))).toBe(true);
+ });
+
+ it("leaves plain K, ⌘K and other modifiers alone", () => {
+ expect(isStartFreshShortcut(chord())).toBe(false);
+ expect(isStartFreshShortcut(chord({ metaKey: true }))).toBe(false);
+ expect(isStartFreshShortcut(chord({ metaKey: true, shiftKey: true, altKey: true }))).toBe(false);
+ expect(isStartFreshShortcut(chord({ metaKey: true, shiftKey: true, defaultPrevented: true }))).toBe(false);
+ expect(isStartFreshShortcut(chord({ metaKey: true, shiftKey: true, isComposing: true }))).toBe(false);
+ });
+});
+
+describe("startFreshRefusal", () => {
+ it("refuses a busy bot, an empty chat and a chat already at a fresh start", () => {
+ expect(startFreshRefusal(bot([message], "m1", true))).toBe("busy");
+ expect(startFreshRefusal(bot([]))).toBe("empty");
+ expect(startFreshRefusal(bot([message, fresh]))).toBe("fresh");
+ });
+
+ it("allows a chat with messages whose last one is not a fresh start", () => {
+ expect(startFreshRefusal(bot([message]))).toBeNull();
+ expect(startFreshRefusal(bot([message, fresh], "m1"))).toBeNull();
+ });
+});
diff --git a/src/lib/start-fresh.ts b/src/lib/start-fresh.ts
new file mode 100644
index 0000000000..683b5d5e80
--- /dev/null
+++ b/src/lib/start-fresh.ts
@@ -0,0 +1,25 @@
+import { visibleMessages } from "@/state/snapshot-navigation";
+import type { Bot } from "@/state/store";
+
+// Electron 43 uses ⌘⇧R for force reload, so Start fresh uses K instead.
+export const START_FRESH_KEYS = {
+ mac: ["⌘", "⇧", "K"],
+ win: ["Ctrl", "Shift", "K"],
+} as const;
+
+type KeyEvent = Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "defaultPrevented" | "isComposing">;
+
+export function isStartFreshShortcut(event: KeyEvent): boolean {
+ return !event.defaultPrevented && !event.isComposing
+ && (event.metaKey || event.ctrlKey) && event.shiftKey && !event.altKey
+ && event.key.toLowerCase() === "k";
+}
+
+export type StartFreshRefusal = "busy" | "empty" | "fresh";
+
+export function startFreshRefusal(bot: Pick<Bot, "busy" | "messages" | "activeLeafId">): StartFreshRefusal | null {
+ if (bot.busy) return "busy";
+ const messages = visibleMessages(bot);
+ if (messages.length === 0) return "empty";
+ return messages.at(-1)?.compaction?.fresh === true ? "fresh" : null;
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 74c6dc3157..e30c1d4ebe 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -9283,6 +9283,7 @@
"shortcuts.command-palette": "Open command palette (switcher & transcript search)",
"shortcuts.new-bot": "Create a new bot",
"shortcuts.new-thread": "Start a new thread with the selected bot",
+ "shortcuts.start-fresh": "Start fresh in this conversation (keeps the messages)",
"shortcuts.jump-bot": "Jump to bot 1–9 in the roster",
"shortcuts.switch-bot": "Switch to previous / next bot",
"shortcuts.switch-thread": "Switch to the bot's next / previous thread",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index a53a377251..82120d14e0 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -6223,5 +6223,6 @@
"server.github.card.description": "Kết nối GitHub để {bot} có thể đẩy công việc lên kho mã của bạn.",
"server.github.card.connectInApps": "Kết nối GitHub từ thẻ này trong ứng dụng trên máy tính, hoặc trong Ứng dụng.",
"githubSignIn.title": "Đăng nhập GitHub",
- "githubSignIn.tokenPlaceholder": "github_pat_…"
+ "githubSignIn.tokenPlaceholder": "github_pat_…",
+ "shortcuts.start-fresh": "Bắt đầu lại cuộc trò chuyện này (giữ nguyên tin nhắn)"
}