Skip to content

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

Simple view: New thread, View threads and Set as main thread in the bot menu (#4225)

Aditya Umaled38e0f3c79a3
diff --git a/server/index.ts b/server/index.ts
index ba3f50c352..68376be824 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2962,7 +2962,7 @@ const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threads
/** Strips provider session ids (resumeCursors) here, not at call sites, so no broadcast or paired phone ever gets them. */
const wireBot = (bot: BotRecord): WireBot => {
- const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, ...rest } = bot;
+ const { resumeCursors: _resumeCursors, tasks, approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
// Clients see Ask while an elevated grant awaits the desktop's confirmation, never a grant that may still roll back.
const visible = approvalGrant && !approvalGrant.threadOnly
? { ...rest, approvalMode: "ask" as const, autoApprove: false }
@@ -2982,7 +2982,7 @@ function toolScopeForTurn(botId: string) {
}
const wireTrustedApprovalBot = (bot: NonNullable<ReturnType<typeof store.bot>>) => {
- const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, ...rest } = bot;
+ const { resumeCursors: _resumeCursors, tasks, approvalGrant: _approvalGrant, lastProfileRequestId: _lastProfileRequestId, lastTeamSetupReceipt: _lastTeamSetupReceipt, packageBase: _packageBase, assignedSkills: _assignedSkills, mainThreadChoice: _mainThreadChoice, ...rest } = bot;
const awaiting = threadsAwaitingTeammates();
return { ...rest, approvalMode: approvalModeFor(rest), mainThreadId: botMainThread(bot.id), avatarUrl: rest.avatarUrl ?? null, ...(tasks ? { tasks: tasks.map((task) => wireTask(task, bot.modelSelection, awaiting)) } : {}) };
};
@@ -8776,9 +8776,9 @@ function routineSourceOwner(run: Pick<RoutineRun, "botId" | "sourceThreadId" | "
return group?.memberIds.includes(bot.id) ? { bot, group, threadId } : null;
}
+function mainThreadTasks(botId: string) { const tasks = store.tasks(botId); return CLOUD_TEAM ? tasks.filter((task) => teamHost.audienceOf(task.threadId) === "team") : CLOUD_HOME ? tasks.filter((task) => !cloudGuestOpened(task.threadId)) : tasks; }
function botMainThread(botId: string): string | undefined {
- const tasks = store.tasks(botId);
- return mainThread(CLOUD_TEAM ? tasks.filter((task) => teamHost.audienceOf(task.threadId) === "team") : CLOUD_HOME ? tasks.filter((task) => !cloudGuestOpened(task.threadId)) : tasks, store.bot(botId)?.threadId);
+ return mainThread(mainThreadTasks(botId), store.bot(botId)?.threadId, store.bot(botId)?.mainThreadChoice);
}
function routineSourceThread(run: RoutineRun): string | null {
@@ -12300,7 +12300,7 @@ ROUTES.push(createBotPatchRoutes({
hostedWorkspace: HOSTED_WORKSPACE, hostedFullAccessRefusal: HOSTED_FULL_ACCESS_REFUSAL, desktopManaged: DESKTOP_MANAGED, maxWorkspaceBots: MAX_WORKSPACE_BOTS,
broadcast, wireBot, publicGroupState, audienceChanged, storedAvatarExists, requestedTaskBot, threadBusy, activeGroupTurnForBot,
checkedModelSelection, engineSwitchNeedsAsk, currentBrowserSession, interruptAllDirectThreads, cancelGroupTurnOperations,
- revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM),
+ revokeInternalCapabilitiesForThread, runningTurnInstance, closeOpenApprovals, assertTeamComputerChangeIdle, forgetTemporaryBrowser, levelOf, team: Boolean(CLOUD_TEAM), mainThreadTasks,
}));
ROUTES.push(createBotLifecycleRoutes({
store, routines: () => routines, interruptAllDirectThreads, cancelDirectTurnDispatch, revokeInternalCapabilitiesForThread,
diff --git a/server/main-thread.test.ts b/server/main-thread.test.ts
index 7d9f28fbfe..6f13c2cff0 100644
--- a/server/main-thread.test.ts
+++ b/server/main-thread.test.ts
@@ -13,6 +13,14 @@ describe("a bot's main thread", () => {
expect(mainThread(tasks)).toBe("later");
});
+ it("is the thread the person chose while it is open, else the usual pick", () => {
+ const tasks = [{ ...latest, askedAt: 10 }, { ...later, askedAt: 30 }, { ...first, askedAt: 20 }];
+ expect(mainThread(tasks, "later", "first")).toBe("first");
+ expect(mainThread([{ ...latest, archivedAt: 5 }, { ...later, askedAt: 30 }], "later", "latest")).toBe("later");
+ expect(mainThread([{ ...latest, routineRunId: "run" }, later], "later", "latest")).toBe("later");
+ expect(mainThread(tasks, "later", "deleted")).toBe("later");
+ });
+
it("is never a routine run or an archived thread, however recently written in", () => {
const tasks = [
{ ...latest, askedAt: 50, routineRunId: "run" },
diff --git a/server/main-thread.ts b/server/main-thread.ts
index d937b05127..df587d806f 100644
--- a/server/main-thread.ts
+++ b/server/main-thread.ts
@@ -19,8 +19,11 @@ export function wasOldestThread(tasks: readonly MainThreadCandidate[], threadId:
return saved !== undefined && !tasks.some((task) => !task.routineRunId && task.archivedAt === undefined && task.createdAt < saved.createdAt);
}
-export function mainThread(tasks: readonly MainThreadCandidate[], selectedId?: string): string | undefined {
+/** The thread a bot opens to when threads are hidden: the one the person chose (while it is open), else the open thread
+ * they last wrote in, else the selected one, else the oldest. */
+export function mainThread(tasks: readonly MainThreadCandidate[], selectedId?: string, chosenId?: string): string | undefined {
const open = tasks.filter((task) => !task.routineRunId && task.archivedAt === undefined);
+ if (chosenId && open.some((task) => task.threadId === chosenId)) return chosenId;
const asked = open.reduce<MainThreadCandidate | undefined>(
(latest, task) => ((task.askedAt ?? -1) > (latest?.askedAt ?? -1) ? task : latest), undefined,
);
diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.ts
index d93bb0a884..544f09d5a8 100644
--- a/server/routes/bot-patch.test.ts
+++ b/server/routes/bot-patch.test.ts
@@ -45,6 +45,7 @@ function fixture() {
const bot = store.createBot({ name: "Scout" });
const cfg = { vps: { sshAlias: "production-vps" } } as AppConfig;
const activeVpsThreads = new Set<string>();
+ const privateThreads = new Set<string>();
// Only what a vpsAlias patch touches; any other dependency is absent, and a route that reached for one would throw.
const deps = {
store,
@@ -58,6 +59,7 @@ function fixture() {
routines: () => null,
// A member's session may chat with this bot: the level that still can't move it or change what it may do.
levelOf: () => "chat",
+ mainThreadTasks: (botId: string) => store.tasks(botId).filter((task) => !privateThreads.has(task.threadId)),
} as unknown as BotPatchRouteDeps;
const handler = createBotPatchRoutes(deps);
const patch = async (botId: string, body: Record<string, unknown>, as: { auth?: RequestAuth; headers?: Record<string, string> } = {}) => {
@@ -78,7 +80,7 @@ function fixture() {
expect(sent).toHaveLength(1);
return sent[0]!;
};
- return { store, bot, activeVpsThreads, patch };
+ return { store, bot, activeVpsThreads, privateThreads, patch };
}
describe("PATCH /api/bots/:id vpsAlias relocation guard", () => {
@@ -313,6 +315,14 @@ describe("PATCH /api/bots/:id phoneApps", () => {
expect(store.bot(bot.id)?.phoneApps).toEqual({});
});
+ it("refuses an archived conversation, which the main-thread resolver skips", async () => {
+ const { store, bot, patch } = fixture();
+ const archived = store.createTask(bot.id, "Done", false)!;
+ store.patchTask(bot.id, archived.threadId, { archivedAt: Date.now() });
+ expect((await patch(bot.id, { mainThreadChoice: archived.threadId })).status).toBe(400);
+ expect(store.bot(bot.id)?.mainThreadChoice).toBeUndefined();
+ });
+
it("refuses a client session and a paired device", async () => {
const { store, bot, patch } = fixture();
@@ -324,3 +334,44 @@ describe("PATCH /api/bots/:id phoneApps", () => {
expect(store.bot(bot.id)?.phoneApps).toBeUndefined();
});
});
+
+describe("PATCH /api/bots/:id mainThreadChoice", () => {
+ it("stores the conversation the person chose, clears it with null, and refuses a routine run or another bot's thread", async () => {
+ const { store, bot, patch } = fixture();
+ const chosen = store.createTask(bot.id, "Chosen", false)!;
+ const run = store.createTask(bot.id, "Run", false)!;
+ store.patchTask(bot.id, run.threadId, { routineRunId: "run-1" });
+ const other = store.createBot({ name: "Other" });
+
+ expect((await patch(bot.id, { mainThreadChoice: chosen.threadId })).status).toBe(200);
+ expect(store.bot(bot.id)?.mainThreadChoice).toBe(chosen.threadId);
+
+ for (const refused of [run.threadId, other.threadId, "missing", 7]) {
+ expect((await patch(bot.id, { mainThreadChoice: refused })).status).toBe(400);
+ }
+ expect(store.bot(bot.id)?.mainThreadChoice).toBe(chosen.threadId);
+
+ expect((await patch(bot.id, { mainThreadChoice: null })).status).toBe(200);
+ expect(store.bot(bot.id)?.mainThreadChoice).toBeUndefined();
+ });
+
+ it("refuses a conversation the main-thread resolver can't pick, the same way as an unknown id", async () => {
+ const { store, bot, patch, privateThreads } = fixture();
+ const hidden = store.createTask(bot.id, "Private", false)!;
+ privateThreads.add(hidden.threadId);
+ const refused = await patch(bot.id, { mainThreadChoice: hidden.threadId });
+ const unknown = await patch(bot.id, { mainThreadChoice: "missing" });
+ expect(refused).toEqual(unknown);
+ expect(refused.status).toBe(400);
+ expect(store.bot(bot.id)?.mainThreadChoice).toBeUndefined();
+ });
+
+ it("refuses a client session and a paired device", async () => {
+ const { store, bot, patch } = fixture();
+ const client = await patch(bot.id, { mainThreadChoice: bot.threadId }, { auth: { kind: "session", via: "bearer", scopes: ["client"], session: { id: "s-member", email: "[email protected]", label: "Front desk" } } as unknown as RequestAuth });
+ const paired = await patch(bot.id, { mainThreadChoice: bot.threadId }, { headers: { "x-openmausbot-companion": "1" } });
+ expect(client.status).toBe(403);
+ expect(paired.status).toBe(403);
+ expect(store.bot(bot.id)?.mainThreadChoice).toBeUndefined();
+ });
+});
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 1c61f8e60f..11d0499e0e 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -29,7 +29,7 @@ import { memberBotPatchViolation, requestSource, type RequestAuth } from "../req
import type { RoutineManager } from "../routines.ts";
import type { SessionRegistry } from "../sessions.ts";
import { parseConnectorTools } from "../connector-tools.ts";
-import { sectionKey, type BotRecord, type GroupRecord, type Store } from "../store.ts";
+import { sectionKey, type BotRecord, type GroupRecord, type Store, type TaskRecord } from "../store.ts";
import * as vps from "../vps-computer.ts";
import { vpsSshAliasForBot } from "../vps-hosts.ts";
import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";
@@ -76,6 +76,8 @@ export interface BotPatchRouteDeps {
levelOf(auth: RequestAuth, botId: string): "none" | "view" | "chat" | "edit";
/** A Team Cloud, where a bot's sharing follows its visibility. */
team: boolean;
+ /** The bot's conversations the main-thread resolver may pick: a Team Cloud keeps only team-visible ones. */
+ mainThreadTasks(botId: string): readonly TaskRecord[];
}
export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
@@ -214,6 +216,14 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
patch.pinnedMessageId = body.pinnedMessageId;
} else return json(res, 400, { error: "pinnedMessageId must be a message id" });
}
+ // null clears the choice; otherwise an open conversation the main-thread resolver may pick, never a routine run or archived.
+ // Same 400 for unknown and ineligible ids, so a private thread's existence is not revealed.
+ if (body.mainThreadChoice !== undefined) {
+ const chosen = typeof body.mainThreadChoice === "string" ? deps.mainThreadTasks(m[1]).find((task) => task.threadId === body.mainThreadChoice) : null;
+ if (body.mainThreadChoice === null) patch.mainThreadChoice = undefined;
+ else if (chosen && !chosen.routineRunId && chosen.archivedAt === undefined) patch.mainThreadChoice = chosen.threadId;
+ else return json(res, 400, { error: "mainThreadChoice must be one of this bot's conversations" });
+ }
if (section !== undefined) patch.section = section ?? undefined;
if (body.chiefOfStaff === false) patch.chiefOfStaff = false;
if (body.fallback !== undefined) {
diff --git a/server/store.ts b/server/store.ts
index 1f839ce68b..9e863a8825 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -168,7 +168,7 @@ export function titleFromLlm(raw: string): string | null {
export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {
tasks?: TaskRecord[];
avatarUrl?: string;
- resumeCursors: Record<string, unknown>;
+ resumeCursors: Record<string, unknown>; mainThreadChoice?: string; // mainThreadChoice ("Set as main thread") is host-only; clients get mainThreadId.
/** Elevation journal: Full/Custom runs as Ask until Electron confirms the prepared reply; a marker surviving a restart is revoked on load. */
approvalGrant?: {
requestId: string;
@@ -185,7 +185,7 @@ export interface BotRecord extends Omit<WireBot, "avatarUrl" | "tasks"> {
assignedSkills?: string[];
}
-export type BotWirePrivateKeys = "resumeCursors" | "tasks" | "avatarUrl" | "approvalGrant" | "lastProfileRequestId" | "lastTeamSetupReceipt" | "packageBase" | "assignedSkills";
+export type BotWirePrivateKeys = "resumeCursors" | "mainThreadChoice" | "tasks" | "avatarUrl" | "approvalGrant" | "lastProfileRequestId" | "lastTeamSetupReceipt" | "packageBase" | "assignedSkills";
export type BotWireProjection = Pick<BotRecord, Exclude<keyof BotRecord, BotWirePrivateKeys>>;
export type BotWireProjectionIsExact = AssertExact<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection> & AssertSameKeys<Omit<WireBot, "avatarUrl" | "tasks">, BotWireProjection>;
export const botWireProjectionIsExact: BotWireProjectionIsExact = true;
diff --git a/src/components/Sidebar.simple-mode.test.ts b/src/components/Sidebar.simple-mode.test.ts
index 549698c57b..28941c5b56 100644
--- a/src/components/Sidebar.simple-mode.test.ts
+++ b/src/components/Sidebar.simple-mode.test.ts
@@ -4,12 +4,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { initialState, type AppState, type Bot, type Group } from "@/state/store";
import type { SidebarDensity } from "@/lib/sidebar-preferences";
-const fixture = vi.hoisted(() => ({ advanced: false, showThreads: true, state: {} as Partial<AppState>, dispatch: vi.fn() }));
+const fixture = vi.hoisted(() => ({ advanced: false, showThreads: true, admin: true as boolean | null, state: {} as Partial<AppState>, dispatch: vi.fn() }));
vi.mock("@/lib/interface-mode", async (original) => ({
...await original<typeof import("@/lib/interface-mode")>(),
useAdvancedMode: () => fixture.advanced,
}));
vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.showThreads }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => fixture.admin }));
vi.mock("./DesktopCapabilities", () => ({ useDesktopCapabilities: () => ({}) }));
vi.mock("react-dom", () => ({ createPortal: (node: ReactNode) => node }));
vi.mock("@/state/store", async (importOriginal) => {
@@ -56,6 +57,7 @@ function findElement(tree: ReactNode, attribute: string, value: string): ReactEl
beforeEach(() => {
fixture.advanced = false;
fixture.showThreads = true;
+ fixture.admin = true;
fixture.state = { bots: [bot], selectedId: "other-bot", activeView: "chat", pendingQueued: { queued: [{ queueId: "q", text: "next" }] } };
fixture.dispatch.mockClear();
vi.stubGlobal("window", { innerWidth: 1024, innerHeight: 768 });
@@ -395,6 +397,76 @@ describe("bot-first sidebar", () => {
expect(disabled).toContain("Move to department");
});
+ it("gives the Simple bot menu New thread, View threads and Set as main thread", () => {
+ let tree: ReactNode;
+ function Capture() {
+ tree = BotContextMenu({
+ menu: { botId: bot.id, x: 0, y: 0 }, onClose: vi.fn(), onArchive: vi.fn(), onDelete: vi.fn(), onMoveToSection: vi.fn(), onNewFolder: vi.fn(), onNewTaskFolder: vi.fn(),
+ });
+ return tree;
+ }
+ const items = () => {
+ const found: ReactElement<ElementProps>[] = [];
+ const walk = (node: ReactNode) => {
+ for (const child of Children.toArray(node)) {
+ if (!isValidElement<ElementProps>(child)) continue;
+ if (child.props.role === "menuitem") found.push(child);
+ walk(child.props.children);
+ }
+ };
+ walk(tree);
+ return found;
+ };
+ const named = (label: string) => items().find((item) => Children.toArray(item.props.children).includes(label));
+ fixture.state = { ...fixture.state, bots: [{ ...bot, mainThreadId: "idle-history" }], selectedId: bot.id };
+ renderToStaticMarkup(createElement(Capture));
+
+ named("New thread")!.props.onClick!({} as MouseEvent);
+ expect(fixture.dispatch.mock.calls).toEqual([[{ type: "newTask", botId: bot.id }]]);
+
+ fixture.dispatch.mockClear();
+ named("View threads")!.props.onClick!({} as MouseEvent);
+ expect(fixture.dispatch.mock.calls).toEqual([
+ [{ type: "select", id: bot.id }],
+ [{ type: "toggleSettings", open: true, section: "history", botId: bot.id }],
+ ]);
+
+ fixture.dispatch.mockClear();
+ const setMain = named("Set as main thread")!;
+ expect(setMain.props.disabled).toBeFalsy();
+ setMain.props.onClick!({} as MouseEvent);
+ expect(fixture.dispatch.mock.calls).toEqual([[{ type: "updateBot", botId: bot.id, patch: { mainThreadChoice: "last-selected" } }]]);
+
+ // Not offered until the person is known to be the owner or an admin.
+ for (const admin of [null, false]) {
+ fixture.admin = admin;
+ renderToStaticMarkup(createElement(Capture));
+ expect(named("Set as main thread")).toBeUndefined();
+ }
+ fixture.admin = true;
+
+ // Already main: offered but off. Another bot's open thread, or a routine run, is never offered.
+ fixture.state = { ...fixture.state, bots: [{ ...bot, mainThreadId: "last-selected" }] };
+ renderToStaticMarkup(createElement(Capture));
+ expect(named("Set as main thread")!.props.disabled).toBe(true);
+ fixture.state = { ...fixture.state, selectedId: "other-bot" };
+ renderToStaticMarkup(createElement(Capture));
+ expect(named("Set as main thread")).toBeUndefined();
+ expect(named("New thread")).toBeDefined();
+ fixture.state = { ...fixture.state, selectedId: bot.id, bots: [{ ...bot, threadId: "run", tasks: [...bot.tasks!, { threadId: "run", title: "Run", createdAt: 9, routineRunId: "r" }] }] };
+ renderToStaticMarkup(createElement(Capture));
+ expect(named("Set as main thread")).toBeUndefined();
+ // A Team Cloud private thread can't be the main thread either (the host refuses it).
+ fixture.state = { ...fixture.state, selectedId: bot.id, bots: [{ ...bot, threadId: "mine", tasks: [...bot.tasks!, { threadId: "mine", title: "Mine", createdAt: 9, private: true }] }] };
+ renderToStaticMarkup(createElement(Capture));
+ expect(named("Set as main thread")).toBeUndefined();
+ // A view-only teammate can look at the threads but not start one.
+ fixture.state = { ...fixture.state, bots: [{ ...bot, yourAccess: "view" }] };
+ renderToStaticMarkup(createElement(Capture));
+ expect(named("New thread")).toBeUndefined();
+ expect(named("View threads")).toBeDefined();
+ });
+
it("Edit profile opens the panel without naming a section", () => {
fixture.advanced = true;
let tree: ReactNode;
diff --git a/src/components/Sidebar.working-folder.test.ts b/src/components/Sidebar.working-folder.test.ts
index 97cae2d127..e8a105ec7d 100644
--- a/src/components/Sidebar.working-folder.test.ts
+++ b/src/components/Sidebar.working-folder.test.ts
@@ -87,7 +87,7 @@ describe("working folder through the rendered sidebar", () => {
access.advanced = false;
render();
openMenu();
- expect(menuItem("New thread")).toBeUndefined();
+ expect(menuItem("New thread")).toBeDefined();
expect(menuItem("New thread in a working folder…")).toBeUndefined();
});
});
diff --git a/src/components/SidebarBotMenu.tsx b/src/components/SidebarBotMenu.tsx
index 4362f73f08..388531e9db 100644
--- a/src/components/SidebarBotMenu.tsx
+++ b/src/components/SidebarBotMenu.tsx
@@ -1,6 +1,6 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
-import { Archive, BellDot, Check, CheckCheck, ChevronRight, ClipboardCopy, Copy, Crown, FolderMinus, FolderOpen, FolderPlus, Loader2, MoreHorizontal, Pencil, Pin, PinOff, SquarePen, Trash2, Users } from "lucide-react";
+import { Archive, BellDot, Check, CheckCheck, ChevronRight, ClipboardCopy, Copy, Crown, FolderMinus, FolderOpen, FolderPlus, Loader2, MessagesSquare, MoreHorizontal, Pencil, Pin, PinOff, SquarePen, Star, Trash2, Users } from "lucide-react";
import { api, useStore, openBot, type Bot } from "@/state/store";
import { cn } from "@/lib/cn";
import { useHeldMenuMotion } from "./MenuMotion";
@@ -21,6 +21,8 @@ import { useAdvancedMode } from "@/lib/interface-mode";
import { useMoveToTeam } from "./MoveToTeam";
import type { MenuState } from "./Sidebar";
import { departmentNames, moveBotsToSection, useMayMoveBots } from "./bot-sections";
+import { openBotSettings } from "./bot-panel/panel-link";
+import { isArchived } from "./SidebarThreadRow";
type Flyout = "more" | "move";
@@ -261,6 +263,19 @@ export function BotContextMenu({
...moveToTeam.items(bot, item),
...deleteAll,
];
+ // Simple view hides the thread list: start one, see them all (the panel's Conversations), and choose the one it opens.
+ const newThread = bot.yourAccess === "view" ? null : item(<SquarePen size={16} className="text-ink-secondary" />, t("task.newShort"), () => dispatch({ type: "newTask", botId: bot.id }));
+ const viewThreads = item(<MessagesSquare size={16} className="text-ink-secondary" />, t("sidebar.bot.simple.viewThreads"), () => {
+ openForSettings();
+ openBotSettings(dispatch, "history", { botId: bot.id, anchor: "conversations" });
+ });
+ const openTask = state.selectedId === bot.id ? bot.tasks?.find((task) => task.threadId === bot.threadId) : undefined;
+ const setMain = remoteClient || admin !== true || !openTask || openTask.routineRunId || openTask.private || isArchived(openTask) ? null : item(
+ <Star size={16} className="text-ink-secondary" />, t("sidebar.bot.simple.setMainThread"),
+ () => dispatch({ type: "updateBot", botId: bot.id, patch: { mainThreadChoice: bot.threadId } }),
+ bot.mainThreadId === bot.threadId ? { disabled: true, hint: t("sidebar.bot.simple.isMainThread") } : undefined,
+ );
+ const threads = [divider("threads"), newThread, viewThreads, setMain];
const moreRow = flyoutButton("more", moreRef, <MoreHorizontal size={16} className="text-ink-secondary" />, t("sidebar.bot.more"));
const leave = bot.defaultBot ? [<HideDefaultBotItem key="hide" bot={bot} onDone={onClose} className={MENU_ITEM} />] : member ? [] : [
item(<Archive size={16} className="text-ink-secondary" />, t("sidebar.bot.archive"), () => onArchive(bot), { disabled: archiveBlocked, hint: archiveHint }),
@@ -293,7 +308,7 @@ export function BotContextMenu({
style={{ top: shown.y, left: shown.x }}
className={cn("fixed z-40 max-h-[calc(100dvh-16px)] w-max min-w-[198px] max-w-[calc(100vw-16px)] overflow-y-auto overscroll-contain", MENU_SHEET, motion.className)} {...motion.exitProps}
>
- {remoteClient ? [moveToSection, ...(rename ? [divider("rename"), rename] : []), divider("copy"), copyId, moreRow] : [
+ {remoteClient ? [moveToSection, ...threads, ...(rename ? [divider("rename"), rename] : []), divider("copy"), copyId, moreRow] : [
item(
bot.pinned ? <PinOff size={16} className="text-ink-secondary" /> : <Pin size={16} className="text-ink-secondary" />,
bot.pinned ? t("sidebar.bot.unpin") : t("sidebar.bot.pin"),
@@ -301,6 +316,7 @@ export function BotContextMenu({
),
moveToSection,
readState,
+ ...threads,
...(rename ? [divider("rename"), rename] : []),
divider("copy"),
copyId,
diff --git a/src/components/SidebarBotRead.test.ts b/src/components/SidebarBotRead.test.ts
index 01a56ada0d..6e01febb09 100644
--- a/src/components/SidebarBotRead.test.ts
+++ b/src/components/SidebarBotRead.test.ts
@@ -130,13 +130,13 @@ describe("Simple mode's bot menu", () => {
const point = (target: Element, y: number) => target.dispatchEvent(new MouseEvent("pointerover", { bubbles: true, clientX: 60, clientY: y }));
beforeEach(() => { mode.advanced = false; });
- it("leads with Pin, Move and Mark as read, then Rename, then Copy conversation ID and More, and ends with Archive and Delete", () => {
+ it("leads with Pin, Move and Mark as read, then the thread items, then Rename, then Copy conversation ID and More, and ends with Archive and Delete", () => {
draw();
expect([...sheet().querySelectorAll("button")].map((node) => node.textContent)).toEqual([
- "Pin", "Move to department", "Mark as read", "Rename", "Copy conversation ID", "More", "Archive", "Delete",
+ "Pin", "Move to department", "Mark as read", "New thread", "View threads", "Rename", "Copy conversation ID", "More", "Archive", "Delete",
]);
expect([...sheet().children].map((node) => node.getAttribute("role") === "separator" ? "|" : node.textContent)).toEqual([
- "Pin", "Move to department", "Mark as read", "|", "Rename", "|", "Copy conversation ID", "More", "|", "Archive", "Delete",
+ "Pin", "Move to department", "Mark as read", "|", "New thread", "View threads", "|", "Rename", "|", "Copy conversation ID", "More", "|", "Archive", "Delete",
]);
flushSync(() => button("Rename").click());
expect(onRename).toHaveBeenCalledWith(bot.id);
diff --git a/src/locales/en.json b/src/locales/en.json
index 4e278b6334..ba0e708772 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2068,6 +2068,9 @@
"sidebar.bot.simple.editProfile": "Edit profile",
"sidebar.bot.simple.markRead": "Mark as read",
"sidebar.bot.simple.markUnread": "Mark as unread",
+ "sidebar.bot.simple.viewThreads": "View threads",
+ "sidebar.bot.simple.setMainThread": "Set as main thread",
+ "sidebar.bot.simple.isMainThread": "This is already the main thread",
"sidebar.bot.duplicate": "Duplicate",
"sidebar.bot.archive": "Archive",
"sidebar.bot.archiveAria": "Archive {name}",
diff --git a/src/state/bot-patch-queue.test.ts b/src/state/bot-patch-queue.test.ts
index 2e3c50c6f3..11fcb59ce9 100644
--- a/src/state/bot-patch-queue.test.ts
+++ b/src/state/bot-patch-queue.test.ts
@@ -340,6 +340,25 @@ describe("bot patch queue", () => {
for (const overlay of overlays) expect(overlay).not.toHaveProperty("threadId");
});
+ it("shows a pending main-thread choice as mainThreadId and keeps the choice itself on the wire only", async () => {
+ const sent: BotUpdatePatch[] = [];
+ const queue = createBotPatchQueue({
+ send: async (_botId, patch) => {
+ sent.push(patch);
+ return bot();
+ },
+ reconcile: async () => bot(),
+ onAuthoritative: vi.fn(),
+ onError: vi.fn(),
+ });
+
+ queue.enqueue("bot-1", { mainThreadChoice: "thread-2" }, bot());
+ expect(queue.overlayFor("bot-1")).toEqual({ mainThreadId: "thread-2" });
+ await vi.advanceTimersByTimeAsync(400);
+ await queue.flush("bot-1");
+ expect(sent).toEqual([{ mainThreadChoice: "thread-2" }]);
+ });
+
it("carries acknowledgeLocalAuto to the wire but never into a state overlay", async () => {
const sent: BotUpdatePatch[] = [];
const overlays: BotUpdatePatch[] = [];
diff --git a/src/state/bot-patch-queue.ts b/src/state/bot-patch-queue.ts
index 441c077a2f..8bb8265ea6 100644
--- a/src/state/bot-patch-queue.ts
+++ b/src/state/bot-patch-queue.ts
@@ -56,12 +56,15 @@ export type BotUpdatePatch = Partial<
keepThreadModels?: boolean;
/** With modelSelection: the thread this client shows. Body only: Bot.threadId is the server's selection. */
threadId?: string;
+ /** The conversation to make main ("Set as main thread"); null clears it. Body only: the bot shows it as mainThreadId. */
+ mainThreadChoice?: string | null;
};
export type BotStatePatch = Omit<
BotUpdatePatch,
- "computer" | "connectorTools" | "connectorScopes" | "phoneApps" | "peers" | "acknowledgeLocalAuto" | "applyToAllThreads" | "keepThreadModels" | "threadId"
+ "computer" | "connectorTools" | "connectorScopes" | "phoneApps" | "peers" | "acknowledgeLocalAuto" | "applyToAllThreads" | "keepThreadModels" | "threadId" | "mainThreadChoice"
> & {
+ mainThreadId?: string;
peers?: string[];
computer?: Bot["computer"];
connectorTools?: Bot["connectorTools"];
@@ -120,6 +123,7 @@ const stateOverlay = (patch: BotUpdatePatch): BotStatePatch => {
applyToAllThreads: _allThreads,
keepThreadModels: _keepThreadModels,
threadId: _threadId,
+ mainThreadChoice,
computer,
connectorTools,
connectorScopes,
@@ -137,6 +141,8 @@ const stateOverlay = (patch: BotUpdatePatch): BotStatePatch => {
if (phoneApps === null) normalized.phoneApps = undefined;
else if (phoneApps !== undefined) normalized.phoneApps = phoneApps;
if (peers !== undefined) normalized.peers = peers ?? undefined;
+ // A pending choice shows as the bot's main thread, so a broadcast during the save does not revert it.
+ if (typeof mainThreadChoice === "string") normalized.mainThreadId = mainThreadChoice;
return normalized;
};
diff --git a/src/state/store.tsx b/src/state/store.tsx
index a72c430285..a8ee3f835c 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -1584,13 +1584,13 @@ export function reducer(state: AppState, action: Action): AppState {
const {
acknowledgeLocalAuto: _localAck,
applyToAllThreads: _allThreads,
- keepThreadModels: _keepThreadModels, threadId: _threadId,
+ keepThreadModels: _keepThreadModels, threadId: _threadId, mainThreadChoice,
computer,
connectorTools,
connectorScopes, phoneApps, peers,
...rest
} = action.patch;
- const botPatch: Partial<Bot> = { ...rest, ...(phoneApps !== undefined && { phoneApps: phoneApps ?? undefined }), ...(peers !== undefined && { peers: peers ?? undefined }) };
+ const botPatch: Partial<Bot> = { ...rest, ...(phoneApps !== undefined && { phoneApps: phoneApps ?? undefined }), ...(peers !== undefined && { peers: peers ?? undefined }), ...(typeof mainThreadChoice === "string" && { mainThreadId: mainThreadChoice }) };
if (computer === null) botPatch.computer = undefined;
else if (computer !== undefined) botPatch.computer = computer;
if (connectorTools === null) botPatch.connectorTools = undefined;