Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
New conversation opens a blank chat; the first send makes it (#6763)
Milind Soni21ed317d41d1
diff --git a/src/App.tsx b/src/App.tsxindex 2deb456449..4dbd05d555 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,4 +1,4 @@-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { ChevronLeft, Loader2, Menu } from "lucide-react";import { CLOUD_LINK_SETTINGS, openBot, StoreProvider, useStore } from "@/state/store";import { nextShortcutBot, shortcutBots, shownBotIds } from "@/lib/sidebar-shortcut-order";@@ -45,6 +45,7 @@ import { CloudSendStrip } from "@/components/CloudSendStrip";import { HomeLine } from "@/components/HomeLine";import { useTeamChats } from "@/state/team-chats";import { needsYouVersion, useTeamPeopleLoader } from "@/state/team-people";+import { newChatBot } from "@/state/new-chat";import { useTeamPresence } from "@/state/team-presence";import { inboxVersion, useInboxLoader, useInboxPanel, useInboxReady } from "@/state/inbox";import { PlacesRail } from "@/components/PlacesRail";@@ -171,7 +172,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {const group = state.groups.find((g) => g.id === state.selectedId);const chiefStep = useChiefStepOpen();const bot = group || chiefStep ? undefined : (state.bots.find((b) => b.id === state.selectedId) ?? state.bots[0]);- const { open: drawerOpen, show: openDrawer, hide: hideDrawer, noteAction: noteDrawerAction } = useBotListDrawer({ selectedId: state.selectedId, botThread: bot?.threadId, groupThread: group?.threadId,+ const chatBot = useMemo(() => bot && newChatBot(bot, state.newChat), [bot, state.newChat]);+ const { open: drawerOpen, show: openDrawer, hide: hideDrawer, noteAction: noteDrawerAction } = useBotListDrawer({ selectedId: state.selectedId, botThread: chatBot?.threadId, groupThread: group?.threadId,view: state.activeView, pluginsOpen: state.pluginsOpen, settingsOpen: state.settingsOpen });const closeDrawer = useCallback(() => { hideDrawer(); menuButtonRef.current?.focus(); }, [hideDrawer]);const notificationFeed = useNotificationFeed() && !remoteClient;@@ -430,7 +432,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {) : group ? (<GroupView key={group.id} group={group} />) : bot ? (- <ChatView bot={bot} />+ <ChatView bot={chatBot ?? bot} />) : noEngines ? (<NoEngines />) : (diff --git a/src/components/CallView.tsx b/src/components/CallView.tsxindex e54d279445..98a543d30d 100644--- a/src/components/CallView.tsx+++ b/src/components/CallView.tsx@@ -5,7 +5,7 @@ import { useCallback, useEffect, useId, useRef, useState } from "react";import { AudioLines, Check, ChevronDown, Loader2, Phone, PhoneOff, X } from "lucide-react";import { useShowThreads } from "@/lib/thread-preferences";-import { openBot, useStore, visibleMessages, type Bot } from "@/state/store";+import { openBot, useStore, visibleMessages, type Bot } from "@/state/store"; import { isNewChatThread } from "@/state/new-chat";import { cn } from "@/lib/cn";import { useMenuMotion } from "./MenuMotion";import { currentCall, deferCallCleanup, endCall, startCall, useOnCall } from "@/lib/call";@@ -96,7 +96,7 @@ export function CallTargetButton({const showThreads = useShowThreads();const { capabilities, ready: capabilitiesReady } = useDesktopCapabilities();const media = useLiveMedia();- const liveThreadId = liveCapable ? threadId : undefined;+ const liveThreadId = liveCapable && !isNewChatThread(threadId) ? threadId : undefined;const canLive = liveThreadId !== undefined;// Check Live first: startCall also marks the target as on a call.const liveRunning = isLiveCallRunning(media.phase);diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 059978ef60..830b634ff1 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -95,7 +95,7 @@ import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffimport { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { HeaderShare } from "./bot-access/HeaderShare"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref"; import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { sameDrawnBots } from "@/lib/drawn-bots"; import { ChatActivityControls, chatActivityMessages, useChatActivity } from "./ChatActivity";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";import { ModelPicker } from "./ModelPicker"; import { useFailedTurnFix } from "./FailedTurnFix";-import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats";+import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats"; import { isNewChatThread } from "@/state/new-chat";import { useChatFindRequests, useChatFindShortcut } from "@/lib/chat-find";import { CitationSelectionToolbar, SentCitations } from "./CitationUI";import { SpeakButton, speakReady } from "./SpeakButton";@@ -874,7 +874,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = fal() => ({ botId: bot.id, threadId: bot.threadId, botName: bot.name, botColor: bot.color, voiceId: bot.voice, tts, localVoice, hasMore, bots, mentionPeers, mentionPerson: { profileName: state.config?.profile?.name }, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, conversational: isConversational(bot.replyStyle), simple: !advanced, canReact: mayWrite, openedAt, speakerViewer, phone }),[bot.id, bot.threadId, bot.name, bot.color, bot.voice, tts, localVoice, hasMore, bots, mentionPeers, state.config?.profile?.name, focus, showToolCalls, locale, dispatch, onBranch, bubbleStyle, bot.replyStyle, advanced, mayWrite, openedAt, speakerViewer, phone],);- const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && (currentTask?.private === true || (ownChatStarted(bot.threadId) && !currentTask?.shared)), ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;+ const currentTask = bot.tasks?.find((task) => task.threadId === bot.threadId), place = effectivePlace(bot, currentTask), team = state.config?.team, privateChat = Boolean(team) && (currentTask?.private === true || isNewChatThread(bot.threadId) || (ownChatStarted(bot.threadId) && !currentTask?.shared)), ownHelper = Boolean(team) && !privateChat && Boolean(bot.defaultBot?.person), sharedChat = Boolean(team) && !privateChat && !ownHelper;const [editingId, setEditingId] = useState<string | null>(null);useEffect(() => setEditingId(null), [bot.id, bot.threadId]);diff --git a/src/components/Sidebar.plus-menu.test.ts b/src/components/Sidebar.plus-menu.test.tsindex 2d074d029d..4c8e5d092c 100644--- a/src/components/Sidebar.plus-menu.test.ts+++ b/src/components/Sidebar.plus-menu.test.ts@@ -2,7 +2,7 @@import { Children, isValidElement, type ReactElement, type ReactNode } from "react";import { describe, expect, it, vi } from "vitest";-const fixture = vi.hoisted(() => ({ values: [] as unknown[], index: 0, admin: true as boolean | null, team: false, state: {} as Record<string, unknown> }));+const fixture = vi.hoisted(() => ({ values: [] as unknown[], index: 0, admin: true as boolean | null, team: false, state: {} as Record<string, unknown>, dispatch: vi.fn() }));vi.mock("react", async (original) => ({...await original<typeof import("react")>(),useState: (initial: unknown) => {@@ -37,7 +37,7 @@ vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => false, setAdvancvi.mock("@/state/store-select", async (importOriginal) => (await import("@/testing/plain-store-select")).plainStoreSelect(await importOriginal()));vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();- return { ...original, useStore: () => ({ state: { ...original.initialState, ...fixture.team ? { config: { team: { id: "acme", name: "Acme" } } } : {}, ...fixture.state }, dispatch: vi.fn() }) };+ return { ...original, useStore: () => ({ state: { ...original.initialState, ...fixture.team ? { config: { team: { id: "acme", name: "Acme" } } } : {}, ...fixture.state }, dispatch: fixture.dispatch }) };});import { Sidebar } from "./Sidebar";@@ -108,6 +108,12 @@ describe("the sidebar's + menu with a long bot name (simple mode)", () => {expect(root({ computerOpen: true }).props.className).toContain("md:max-w-[var(--sidebar-max)]");});+ it("starts a blank conversation with the open bot and makes nothing itself", () => {+ fixture.dispatch.mockClear();+ withLongBot().filter((node) => node.props.role === "menuitem")[0]!.props.onClick!();+ expect(fixture.dispatch.mock.calls).toEqual([[{ type: "newTask", botId: "long" }]]);+ });+it("truncates the bot's name in New conversation with … and keeps the full name on hover", () => {const item = withLongBot().filter((node) => node.props.role === "menuitem")[0];const label = nodes(item.props.children).find((node) => node.type === "span" && node.props.title === longName);diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex f0abddd9a5..882185f1f8 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -448,7 +448,7 @@ export function currentArchivableBot(bots: readonly Bot[], id: string): Bot | unconst NO_FOLDERS: BotProject[] = [];-export function BotThreadList({ bot, selected, query, pendingQueued, routineRuns, reveal, locale, dispatch, activityLabel, hidden = false }: BotRowProps & {+export function BotThreadList({ bot, selected, drafting, query, pendingQueued, routineRuns, reveal, locale, dispatch, activityLabel, hidden = false }: BotRowProps & {activityLabel?: string;hidden?: boolean;}) {@@ -512,7 +512,7 @@ export function BotThreadList({ bot, selected, query, pendingQueued, routineRuns}), [botId, dispatch]);const renderThread = (task: (typeof tasks)[number]) => {const thread = currentTaskBot(bot, task.threadId);- return <SidebarThreadRow key={task.threadId} task={{ ...task, busy: thread.busy, activity: thread.activity, waitingForTeammates: thread.waitingForTeammates }} ownerId={bot.id} current={selected && task.threadId === bot.threadId} folders={projects}+ return <SidebarThreadRow key={task.threadId} task={{ ...task, busy: thread.busy, activity: thread.activity, waitingForTeammates: thread.waitingForTeammates }} ownerId={bot.id} current={selected && !drafting && task.threadId === bot.threadId} folders={projects}activityLabel={task.threadId === bot.threadId ? activityLabel : undefined} now={stampClock(threadRecency(task), now)} locale={locale} {...actions}selectMode={bulk.active} checked={selection.has(task.threadId)} onToggleSelect={bulk.toggle} />;};@@ -645,7 +645,7 @@ export function BotThreadList({ bot, selected, query, pendingQueued, routineRunsexport interface BotRowProps {bot: Bot;- selected: boolean;+ selected: boolean; drafting?: boolean;deleting: boolean;mascotMotion: AppState["mascotMotion"];reveal: AppState["revealThread"];@@ -664,7 +664,7 @@ export interface BotRowProps {botDragging?: boolean;}-export function botRowProps<State extends Pick<AppState, "activeView" | "selectedId" | "revealThread" | "deletingBots" | "mascotMotion" | "pendingQueued" | "routineRuns" | "instances" | "liveCall" | "config">>(+export function botRowProps<State extends Pick<AppState, "activeView" | "selectedId" | "revealThread" | "deletingBots" | "mascotMotion" | "pendingQueued" | "routineRuns" | "instances" | "liveCall" | "config" | "newChat">>(state: State,dispatch: Dispatch<Action>,bot: Bot,@@ -675,7 +675,7 @@ export function botRowProps<State extends Pick<AppState, "activeView" | "selectereturn {...layout,bot,- selected,+ selected, drafting: state.newChat?.botId === bot.id,deleting: state.deletingBots[bot.id] === true,mascotMotion: selected && state.mascotMotion?.botId === bot.id ? state.mascotMotion : null,reveal: reveal && (bot.threadId === reveal.threadId || bot.tasks?.some((task) => task.threadId === reveal.threadId)) ? reveal : null,diff --git a/src/components/sidebar-state.ts b/src/components/sidebar-state.tsindex bbed71e37d..12e49fa3ae 100644--- a/src/components/sidebar-state.ts+++ b/src/components/sidebar-state.ts@@ -2,7 +2,7 @@ import type { AppState } from "@/state/store";/** What the sidebar list draws: a change anywhere else in the store leaves it alone. */export const sidebarState = (s: AppState) => ({- bots: s.bots, groups: s.groups, sections: s.sections, pendingQueued: s.pendingQueued, instances: s.instances, config: s.config, selectedId: s.selectedId,+ bots: s.bots, groups: s.groups, sections: s.sections, pendingQueued: s.pendingQueued, instances: s.instances, config: s.config, selectedId: s.selectedId, newChat: s.newChat,activeView: s.activeView, computerOpen: s.computerOpen, inspectorOpen: s.inspectorOpen, deletingBots: s.deletingBots, revealThread: s.revealThread,liveCall: s.liveCall, cloudHowTo: s.cloudHowTo, routineRuns: s.routineRuns, mascotMotion: s.activeView === "chat" && s.mascotMotion?.botId === s.selectedId ? s.mascotMotion : null,});diff --git a/src/hooks/use-presence.ts b/src/hooks/use-presence.tsindex f205e69ded..cb2f6c1b1f 100644--- a/src/hooks/use-presence.ts+++ b/src/hooks/use-presence.ts@@ -11,7 +11,7 @@ const ACTIVITY = ["focus", "pointerdown", "keydown"] as const;function selection(state: AppState): string {const bot = state.bots.find((candidate) => candidate.id === state.selectedId);const threadId = bot ? bot.switchingTo ?? bot.threadId : state.groups.find((group) => group.id === state.selectedId)?.threadId;- return `${state.selectedId}\n${threadId ?? ""}`;+ return `${state.selectedId}\n${threadId ?? ""}\n${state.newChat?.session ?? ""}`;}/** The bot conversation open in front of the person, if one is. */@@ -42,7 +42,7 @@ export function usePresence(state: AppState, dispatch: (action: Action) => void)void api("/api/presence/active", { method: "POST", body: JSON.stringify(body) }).then((answer) => {const live = latest.current;const target = existingThreadTarget(openTarget(answer), live.state);- if (target && selection(live.state) === sentFrom) openThread(live.dispatch, target, live.state, live.showThreads);+ if (target && !live.state.newChat && selection(live.state) === sentFrom) openThread(live.dispatch, target, live.state, live.showThreads);}, () => {});};const onActivity = () => ping();diff --git a/src/hooks/use-read-shown-chat.ts b/src/hooks/use-read-shown-chat.tsindex 153aa614dd..b139375bcf 100644--- a/src/hooks/use-read-shown-chat.ts+++ b/src/hooks/use-read-shown-chat.ts@@ -10,8 +10,8 @@ export function useReadShownChatOnFocus(): void {latest.current = state;useEffect(() => {const readShownChat = () => {- const { selectedId } = latest.current;- if (selectedId && shownChatIsUnread(latest.current)) dispatch({ type: "select", id: selectedId });+ const { selectedId, newChat } = latest.current;+ if (selectedId && newChat?.botId !== selectedId && shownChatIsUnread(latest.current)) dispatch({ type: "select", id: selectedId });};window.addEventListener("focus", readShownChat);return () => window.removeEventListener("focus", readShownChat);diff --git a/src/state/new-chat.test.ts b/src/state/new-chat.test.tsnew file mode 100644index 0000000000..89ff0b956b--- /dev/null+++ b/src/state/new-chat.test.ts@@ -0,0 +1,296 @@+// @vitest-environment happy-dom+import { createElement, type Dispatch } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { StoreProvider, useStore, type Action, type AppState, type Bot, type Message } from "./store";+import { newChatBot, newChatThreadId } from "./new-chat";++class FixtureEventSource {+ static current: FixtureEventSource;+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ constructor() { FixtureEventSource.current = this; }+ close() {}+ send(frame: object) { this.onmessage?.({ data: JSON.stringify(frame) }); }+}++const line = (id: string): Message => ({ id, at: 1, role: "user", kind: "text", text: id, parentId: null });+const bot = (threadId: string, threads: string[]): Bot => ({+ id: "bot", threadId, name: "Pepper", title: "", description: "", notifications: false,+ unread: false, color: "green", modelSelection: { instanceId: "fake", model: "fixture" },+ tasks: threads.map((id) => ({ threadId: id, title: id, createdAt: 1 })), messages: [line(`said-in-${threadId}`)], activeLeafId: `said-in-${threadId}`,+});+const other: Bot = { ...bot("x", ["x"]), id: "other", name: "Other" };+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });+const DRAFT = newChatThreadId("bot");++let state!: AppState;+let dispatch!: Dispatch<Action>;+function Probe() {+ ({ state, dispatch } = useStore());+ return null;+}+let root: Root;+let container: HTMLDivElement;+let creates: Array<{ projectId?: string }>;+let sends: Array<{ threadId?: string; text: string }>;+let taskPatches: string[];+let createAnswer: Promise<Response> | null;+let switchAnswer: Promise<Response> | null;++const send = (text: string, extra: Partial<Extract<Action, { type: "send" }>> = {}) =>+ flushSync(() => dispatch({ type: "send", botId: "bot", threadId: DRAFT, text, sendId: `send-${text}`, ...extra }));+const openBlank = (projectId?: string) => flushSync(() => dispatch({ type: "newTask", botId: "bot", ...(projectId ? { projectId } : {}) }));++beforeEach(async () => {+ creates = [];+ sends = [];+ taskPatches = [];+ createAnswer = null;+ switchAnswer = null;+ const stored = new Map<string, string>();+ vi.stubGlobal("localStorage", {+ getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => { stored.set(key, String(value)); },+ removeItem: (key: string) => { stored.delete(key); }, clear: () => stored.clear(),+ });+ vi.stubGlobal("EventSource", FixtureEventSource);+ vi.stubGlobal("fetch", async (path: string, init?: RequestInit) => {+ if (path.startsWith("/api/bots?")) return json({ bots: [bot("a", ["a"]), other], groups: [] });+ if (path === "/api/bots/bot/tasks") {+ creates.push(JSON.parse(String(init?.body)));+ return createAnswer ?? json({ bot: { ...bot("made", ["a", "made"]), messages: [] } }, 201);+ }+ if (path === "/api/bots/bot/messages") {+ const body = JSON.parse(String(init?.body));+ sends.push(body);+ return json({ threadId: body.threadId, message: { ...line(body.sendId), sendId: body.sendId } });+ }+ if (/^\/api\/bots\/bot\/tasks\/[^/]+$/.test(path) && init?.method === "PATCH") taskPatches.push(path);+ if (path === "/api/bots/bot/tasks/a") return json({ bot: bot("a", ["a"]) });+ if (path.startsWith("/api/bots/bot/tasks/b")) return switchAnswer ?? json({ bot: bot("b", ["a", "b"]) });+ if (path === "/api/instances") return json({ instances: [] });+ if (path.startsWith("/api/routines?since=")) return json({ routines: [], runs: [] });+ if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });+ return json({});+ });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));+ FixtureEventSource.current.send({ kind: "hello", resumed: false, cursor: "fixture:0" });+ await vi.waitFor(() => expect(state.hydrated).toBe(true));+ flushSync(() => dispatch({ type: "select", id: "bot" }));+});+afterEach(() => {+ flushSync(() => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++const pepper = () => state.bots.find((candidate) => candidate.id === "bot")!;+const settle = () => new Promise((resolve) => setTimeout(resolve, 20));++describe("a new conversation opens blank and is made by its first send", () => {+ it("opens a blank chat for the bot and makes nothing", async () => {+ openBlank();+ await settle();++ expect(creates).toEqual([]);+ expect(pepper().tasks?.map((task) => task.threadId)).toEqual(["a"]);+ expect(state.selectedId).toBe("bot");+ const shown = newChatBot(pepper(), state.newChat);+ expect(shown.threadId).toBe(DRAFT);+ expect(shown.messages).toEqual([]);+ });++ it("makes exactly one conversation on the first send and sends the message into it", async () => {+ openBlank();+ send("Plan my week");+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ expect(creates).toHaveLength(1);+ expect(sends[0]).toMatchObject({ threadId: "made", text: "Plan my week" });+ expect(pepper().threadId).toBe("made");+ expect(pepper().tasks?.map((task) => task.threadId)).toEqual(["a", "made"]);+ expect(state.newChat).toBeNull();+ expect(newChatBot(pepper(), state.newChat).threadId).toBe("made");+ });++ it("never sends the first message into the conversation that was open before", async () => {+ openBlank();+ send("First");+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ expect(sends.map((body) => body.threadId)).not.toContain("a");+ });++ it("sends a message aimed at the bot's open conversation into the blank chat that covers it", async () => {+ openBlank();+ flushSync(() => dispatch({ type: "send", botId: "bot", text: "No thread named", sendId: "unnamed" }));+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ expect(creates).toHaveLength(1);+ expect(sends[0]).toMatchObject({ threadId: "made", text: "No thread named" });+ });++ it("stays open when a conversation switch started before it answers afterwards", async () => {+ let answer!: () => void;+ switchAnswer = new Promise((resolve) => { answer = () => resolve(json({ bot: bot("b", ["a", "b"]) })); });+ flushSync(() => dispatch({ type: "switchTask", botId: "bot", threadId: "b" }));+ openBlank();+ answer();+ await settle();++ expect(state.newChat?.botId).toBe("bot");+ expect(newChatBot(pepper(), state.newChat).threadId).toBe(DRAFT);+ });++ it("makes one conversation for sends that arrive while it is being made", async () => {+ let answer!: () => void;+ createAnswer = new Promise((resolve) => { answer = () => resolve(json({ bot: { ...bot("made", ["a", "made"]), messages: [] } }, 201)); });+ openBlank();+ send("one");+ send("two");+ await settle();+ answer();+ await vi.waitFor(() => expect(sends).toHaveLength(2));++ expect(creates).toHaveLength(1);+ expect(sends.map((body) => [body.threadId, body.text])).toEqual([["made", "one"], ["made", "two"]]);+ });++ it("leaves nothing behind when the person goes elsewhere without sending", async () => {+ openBlank();+ flushSync(() => dispatch({ type: "select", id: "other" }));+ flushSync(() => dispatch({ type: "select", id: "bot" }));+ await settle();++ expect(creates).toEqual([]);+ expect(state.newChat).toBeNull();+ expect(pepper().threadId).toBe("a");+ expect(pepper().tasks?.map((task) => task.threadId)).toEqual(["a"]);+ expect(newChatBot(pepper(), state.newChat).messages.map((message) => message.id)).toEqual(["said-in-a"]);+ });++ it.each<[string, Action]>([+ ["opens another conversation", { type: "switchTask", botId: "bot", threadId: "a" }],+ ["opens Routines", { type: "showRoutines" }],+ ["opens Files", { type: "showFiles" }],+ ])("closes the blank chat when the person %s", async (_, leave) => {+ openBlank();+ flushSync(() => dispatch(leave));+ await settle();++ expect(state.newChat).toBeNull();+ expect(creates).toEqual([]);+ });++ it("reuses the open blank chat for the same bot instead of opening another", () => {+ openBlank();+ flushSync(() => dispatch({ type: "setModel", botId: "bot", threadId: DRAFT, selection: { instanceId: "fake", model: "picked" } }));+ const first = state.newChat;+ openBlank();++ expect(state.newChat).toBe(first);+ expect(state.newChat?.held).toHaveLength(1);+ expect(creates).toEqual([]);+ });++ it("keeps a model picked in the blank chat for the conversation the first send makes", async () => {+ openBlank();+ const picked = { instanceId: "fake", model: "picked" };+ flushSync(() => dispatch({ type: "setModel", botId: "bot", threadId: DRAFT, selection: picked }));+ await settle();++ expect(taskPatches).toEqual([]);+ expect(pepper().modelSelection.model).toBe("fixture");+ expect(newChatBot(pepper(), state.newChat).modelSelection).toEqual(picked);++ send("Go");+ await vi.waitFor(() => expect(sends).toHaveLength(1));+ expect(pepper().tasks?.find((task) => task.threadId === "made")?.modelSelection).toEqual(picked);+ await vi.waitFor(() => expect(taskPatches).toEqual(["/api/bots/bot/tasks/made"]));+ });++ it("keeps the conversation the person moved to while the first send was making one, and still sends into the new one", async () => {+ let answer!: () => void;+ createAnswer = new Promise((resolve) => { answer = () => resolve(json({ bot: { ...bot("made", ["a", "made"]), messages: [] } }, 201)); });+ openBlank();+ send("First");+ await settle();+ flushSync(() => dispatch({ type: "switchTask", botId: "bot", threadId: "a" }));+ await vi.waitFor(() => expect(pepper().switchingTo).toBeUndefined());+ answer();+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ expect(pepper().threadId).toBe("a");+ expect(sends[0]).toMatchObject({ threadId: "made", text: "First" });+ });++ it("applies a model picked while the first send is making the conversation", async () => {+ let answer!: () => void;+ createAnswer = new Promise((resolve) => { answer = () => resolve(json({ bot: { ...bot("made", ["a", "made"]), messages: [] } }, 201)); });+ const picked = { instanceId: "fake", model: "late" };+ openBlank();+ send("First");+ await settle();+ flushSync(() => dispatch({ type: "setModel", botId: "bot", threadId: DRAFT, selection: picked }));+ answer();+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ expect(pepper().tasks?.find((task) => task.threadId === "made")?.modelSelection).toEqual(picked);+ });++ it("applies a model picked during creation even when the person left before it was made", async () => {+ let answer!: () => void;+ createAnswer = new Promise((resolve) => { answer = () => resolve(json({ bot: { ...bot("made", ["a", "made"]), messages: [] } }, 201)); });+ openBlank();+ send("First");+ await settle();+ flushSync(() => dispatch({ type: "setModel", botId: "bot", threadId: DRAFT, selection: { instanceId: "fake", model: "late" } }));+ flushSync(() => dispatch({ type: "select", id: "other" }));+ answer();+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ await vi.waitFor(() => expect(taskPatches).toEqual(["/api/bots/bot/tasks/made"]));+ });++ it("makes a separate conversation for a blank chat opened again while the last one's was still being made", async () => {+ let answer!: () => void;+ createAnswer = new Promise((resolve) => { answer = () => resolve(json({ bot: { ...bot("made", ["a", "made"]), messages: [] } }, 201)); });+ openBlank("folder-1");+ send("In folder one");+ await settle();+ flushSync(() => dispatch({ type: "select", id: "other" }));+ createAnswer = null;+ openBlank("folder-2");+ send("In folder two");+ await vi.waitFor(() => expect(creates).toHaveLength(2));+ answer();+ await vi.waitFor(() => expect(sends).toHaveLength(2));++ expect(creates).toEqual([{ projectId: "folder-1" }, { projectId: "folder-2" }]);+ });++ it("makes the conversation in the folder the blank chat was opened from", async () => {+ openBlank("folder-1");+ send("Hi");+ await vi.waitFor(() => expect(sends).toHaveLength(1));++ expect(creates).toEqual([{ projectId: "folder-1" }]);+ });++ it("gives the message back when the conversation cannot be made, and makes nothing", async () => {+ createAnswer = Promise.resolve(json({ error: "no room for another" }, 409));+ const failed = vi.fn();+ openBlank();+ send("Hi", { onError: failed });+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));++ expect(sends).toEqual([]);+ expect(pepper().threadId).toBe("a");+ expect(state.newChat?.botId).toBe("bot");+ });+});diff --git a/src/state/new-chat.ts b/src/state/new-chat.tsnew file mode 100644index 0000000000..682220343b--- /dev/null+++ b/src/state/new-chat.ts@@ -0,0 +1,107 @@+import type { Dispatch } from "react";+import type { Action, AppState, Bot } from "./store";++/** A blank new chat with one bot: shown in place of its open conversation and made into one by the first send. */+export type NewChat = { session: number; botId: string; projectId?: string; held: HeldAction[] };+type HeldAction = Extract<Action, { type: "setModel" } | { type: "updateTask" }>;++const THREAD_PREFIX = "new-chat-";+export const newChatThreadId = (botId: string) => `${THREAD_PREFIX}${botId}`;+export const isNewChatThread = (threadId: unknown): threadId is string => typeof threadId === "string" && threadId.startsWith(THREAD_PREFIX);++const LEAVING = new Set<Action["type"]>(["select", "switchTask", "taskSwitched", "newGroupTask", "switchGroupTask", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps", "showTeamFiles", "showAnnouncements"]);++/** The reducer's first step: `done` when the action belongs to the blank chat alone and the rest of the reducer must not+ * see it. */+export function reduceNewChat(state: AppState, action: Action): [state: AppState, done: boolean] {+ const open = state.newChat ?? null;+ if (action.type === "newTask" && action.cwd === undefined) {+ if (open?.botId !== action.botId) return [{ ...state, newChat: { session: action.blankChat ?? 0, botId: action.botId, projectId: action.projectId, held: [] } }, false];+ return [open.projectId === action.projectId ? state : { ...state, newChat: { ...open, projectId: action.projectId } }, false];+ }+ if ("threadId" in action && isNewChatThread(action.threadId)) {+ const held = open && action.threadId === newChatThreadId(open.botId) && (action.type === "setModel" || action.type === "updateTask");+ return [held ? { ...state, newChat: { ...open, held: [...open.held, action] } } : state, true];+ }+ if (open && LEAVING.has(action.type) && (action.type !== "taskSwitched" || action.bot.id === open.botId)) return [{ ...state, newChat: null }, false];+ return [state, false];+}++/** The bot as the chat draws it while its blank chat is open: no messages, not busy, the choices made so far. */+export function newChatBot(bot: Bot, open: NewChat | null | undefined): Bot {+ if (open?.botId !== bot.id) return bot;+ let shown: Bot = {+ ...bot, threadId: newChatThreadId(bot.id), messages: [], activeLeafId: null, hasMore: false, busy: false, activity: undefined,+ turnStartedAt: null, waitingForTeammates: false, pinnedMessageId: undefined, awaitingThreadSnapshot: false, switchingTo: undefined,+ };+ for (const held of open.held) {+ if (held.type === "setModel") shown = { ...shown, modelSelection: held.selection };+ else {+ const { modelSelection, approvalMode, autoApprove } = held.patch;+ shown = { ...shown, ...(modelSelection ? { modelSelection } : {}), ...(approvalMode ? { approvalMode } : {}), ...(autoApprove === undefined ? {} : { autoApprove }) };+ }+ }+ return shown;+}++type Effects = {+ state: () => AppState;+ rawDispatch: Dispatch<Action>;+ dispatch: Dispatch<Action>;+ create: (botId: string, projectId: string | undefined) => Promise<{ bot: Bot }>;+ navigated: (botId: string) => void;+ showError: (error: unknown) => void;+};++/** The store's effects for the blank chat, answering true for an action they took. While a bot's blank chat is open, a+ * send to the conversation it covers goes into the blank chat too. The first send makes the conversation, once per blank+ * chat however many arrive while it is being made, then each is sent into it. The conversation opens only if the person+ * is still in that blank chat when it is made. */+export function createNewChat(effects: Effects) {+ const making = new Map<number, Promise<string>>(), heldWhileMaking = new Map<number, HeldAction[]>();+ let sessions = 0;+ const make = (open: NewChat) => {+ heldWhileMaking.set(open.session, open.held);+ const made = effects.create(open.botId, open.projectId).then(({ bot }) => {+ const now = effects.state().newChat;+ if (now?.session === open.session && now.botId === open.botId) effects.dispatch({ type: "taskSwitched", bot });+ for (const held of heldWhileMaking.get(open.session) ?? open.held) effects.dispatch({ ...held, threadId: bot.threadId });+ return bot.threadId;+ });+ making.set(open.session, made);+ void made.finally(() => { making.delete(open.session); heldWhileMaking.delete(open.session); }).catch(() => {});+ return made;+ };+ return (action: Action): boolean => {+ if (action.type === "newTask" && action.cwd === undefined) {+ effects.navigated(action.botId);+ effects.rawDispatch({ ...action, blankChat: ++sessions });+ focusComposer();+ return true;+ }+ const state = effects.state(), open = state.newChat;+ const intoBlank = action.type === "send" && open?.botId === action.botId && action.threadId === state.bots.find((bot) => bot.id === action.botId)?.threadId;+ if (!intoBlank && !("threadId" in action && isNewChatThread(action.threadId))) return false;+ if (action.type !== "send") {+ effects.rawDispatch(action);+ const after = effects.state().newChat;+ if (after && heldWhileMaking.has(after.session)) heldWhileMaking.set(after.session, after.held);+ return true;+ }+ const made = open?.botId === action.botId ? making.get(open.session) ?? make(open) : null;+ if (!made) {+ action.onError?.();+ return true;+ }+ made.then((threadId) => effects.dispatch({ ...action, threadId }), (error: unknown) => {+ effects.showError(error);+ action.onError?.();+ });+ return true;+ };+}++function focusComposer() {+ if (typeof requestAnimationFrame !== "function" || window.matchMedia?.("(hover: none) and (pointer: coarse)").matches) return;+ requestAnimationFrame(() => requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>('main[data-look="chat"] textarea')?.focus()));+}diff --git a/src/state/new-task-once.test.ts b/src/state/new-task-once.test.tsindex 4a2ea1dd2c..32bdf60509 100644--- a/src/state/new-task-once.test.ts+++ b/src/state/new-task-once.test.ts@@ -19,12 +19,12 @@ it("makes one conversation for a double or triple click on New conversation", aslet dispatch!: Dispatch<Action>;function Capture() { dispatch = useStore().dispatch; return null; }renderToStaticMarkup(createElement(StoreProvider, null, createElement(Capture)));- for (let click = 0; click < 3; click++) dispatch({ type: "newTask", botId: "bot" });+ for (let click = 0; click < 3; click++) dispatch({ type: "newTask", botId: "bot", cwd: "/work" });await flush();expect(requests.mock.calls.filter(([path]) => path === CREATE)).toHaveLength(1);answer();await flush();- dispatch({ type: "newTask", botId: "bot" });+ dispatch({ type: "newTask", botId: "bot", cwd: "/work" });await flush();expect(requests.mock.calls.filter(([path]) => path === CREATE)).toHaveLength(2);});@@ -60,8 +60,8 @@ it("tells a click that came while the conversation was being made that it was mafunction Capture() { dispatch = useStore().dispatch; return null; }renderToStaticMarkup(createElement(StoreProvider, null, createElement(Capture)));const created = vi.fn();- dispatch({ type: "newTask", botId: "bot", onCreated: created });- dispatch({ type: "newTask", botId: "bot", onCreated: created });+ dispatch({ type: "newTask", botId: "bot", cwd: "/work", onCreated: created });+ dispatch({ type: "newTask", botId: "bot", cwd: "/work", onCreated: created });await flush();answer();await flush();diff --git a/src/state/snapshot-navigation.test.ts b/src/state/snapshot-navigation.test.tsindex 7328128dba..a2e7ef5101 100644--- a/src/state/snapshot-navigation.test.ts+++ b/src/state/snapshot-navigation.test.ts@@ -4,6 +4,7 @@ import { flushSync } from "react-dom";import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { StoreProvider, useStore, type Action, type AppState, type Bot, type Group, type Message } from "./store";+import { newChatThreadId } from "./new-chat";class FixtureEventSource {static current: FixtureEventSource;@@ -108,8 +109,9 @@ describe("navigation while a reconnect snapshot is in flight", () => {it.each(["bot", "group"])("keeps a new %s task entry without restoring tasks omitted by the server", async owner => {await resync();newTaskResponse = deferred();+ if (owner === "bot") flushSync(() => dispatch({ type: "newTask", botId: "bot" }));flushSync(() => dispatch(owner === "bot"- ? { type: "newTask", botId: "bot" }+ ? { type: "send", botId: "bot", threadId: newChatThreadId("bot"), text: "First", sendId: "first" }: { type: "newGroupTask", groupId: "room" }));const createdBot = bot("c", "created"), createdRoom = room("c", "created");createdBot.tasks = [...tasks, { threadId: "c", title: "Created", createdAt: 2 }];@@ -120,7 +122,7 @@ describe("navigation while a reconnect snapshot is in flight", () => {await applySnapshot("a", ["a"]);expect(current().threadId).toBe(owner === "bot" ? "c" : "room-c");- expect(current().messages.map(message => message.id)).toEqual(["created"]);+ expect(current().messages[0]?.id).toBe("created");expect(current().tasks?.map(task => task.threadId)).toEqual(owner === "bot" ? ["a", "c"] : ["room-a", "room-c"]);});diff --git a/src/state/store.tsx b/src/state/store.tsxindex 3f491d43de..90efe8b7b5 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -63,7 +63,7 @@ import { useShowThreads } from "@/lib/thread-preferences";import { speechOwner, spokenReplyStream } from "@/lib/spoken-reply-stream";import { t } from "@/lib/i18n";export { formatTime } from "@/lib/clock-time";-import { createBotPatchQueue, flushWhenLeaving, keepaliveFits, type BotUpdatePatch } from "./bot-patch-queue"; import { createNewTaskOnce } from "./new-task-once";+import { createBotPatchQueue, flushWhenLeaving, keepaliveFits, type BotUpdatePatch } from "./bot-patch-queue"; import { createNewTaskOnce } from "./new-task-once"; import { createNewChat, reduceNewChat, type NewChat } from "./new-chat";import { liveCallFromFrame, nextLiveCallLookup } from "./live-call";import { isNoAiRefusal, useChatErrorClear } from "./chat-error";import { openLiveEvents, publishLiveFrame, publishMissedFrames, withoutScreenPixels } from "@/lib/live-events";@@ -557,6 +557,7 @@ export interface AppState {error: string | null;notice: { kind: "thread-gone" | "bot-gone" | "steer-images" | "note"; botName: string | null; text?: string; threadId?: string } | null;revealThread: { threadId: string; nonce: number } | null;+ newChat?: NewChat | null;mascotMotion: {botId: string;nonce: number;@@ -690,7 +691,7 @@ export type Action =rememberCommand?: boolean;onError?: (message: string) => void;}- | { type: "newTask"; botId: string; projectId?: string; cwd?: string; onCreated?: () => void; onError?: (message: string) => void }+ | { type: "newTask"; botId: string; projectId?: string; cwd?: string; onCreated?: () => void; onError?: (message: string) => void; blankChat?: number }| { type: "switchTask"; botId: string; threadId: string; whole?: true }| { type: "switchTaskFailed"; botId: string; threadId: string }| { type: "taskSwitched"; bot: Bot }@@ -855,6 +856,7 @@ function dismissOnboardingCard(state: AppState, botId: string): AppState {export const CLOUD_LINK_SETTINGS = { type: "toggleAppSettings", open: true, section: "cloudAccount", cloudLink: true } as const satisfies Action;export function reducer(state: AppState, action: Action): AppState {+ const [newChatState, newChatOnly] = reduceNewChat(state, action); if (newChatOnly) return newChatState; state = newChatState;if (action.type === "optimisticMessageRemoved") state = removeForkOptimistic(state, action);if (action.type === "messageAdded" || action.type === "messagePatched" || action.type === "threadActive" || action.type === "optimisticMessageRemoved") {const owner = state.bots.find((bot) => (bot.threadId !== action.threadId || bot.awaitingThreadSnapshot) && bot.tasks?.some((task) => task.threadId === action.threadId));@@ -2093,7 +2095,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {const navigation = new Map<string, number>();const roomAnswer = roomAnswers(() => stateRef.current, rawDispatch);const olderPagesInFlight = new Set<string>();- const newTaskOnce = createNewTaskOnce();+ const newTaskOnce = createNewTaskOnce(), runNewChat = createNewChat({ state: () => store.getState(), rawDispatch, dispatch: (action) => wrapped(action), showError: (error) => showError(error),+ navigated: (botId) => navigation.set(botId, (navigation.get(botId) ?? 0) + 1), create: (botId, projectId) => botPatchQueue.flush(botId).then(() => api<{ bot: Bot }>(`/api/bots/${botId}/tasks`, { method: "POST", body: JSON.stringify({ projectId }) })) });let creatingBot = false;let noticeTimer: ReturnType<typeof setTimeout> | undefined;const showError = (e: unknown) => { if (isBotLimitRefusal(e)) return; if (isNoAiRefusal(e)) wrapped({ type: "notice", notice: { kind: "note", botName: null, text: e.message } }); else rawDispatch({ type: "error", message: e instanceof Error ? e.message : String(e) }); };@@ -2197,7 +2200,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const wrapped: React.Dispatch<Action> = (action) => {store.flushFrames(); if (["select", "newTask", "switchTask", "newGroupTask", "switchGroupTask", "showChat", "showRoutines", "showTeamMap", "showFiles", "showWebPanel", "showPublishedApps", "showTeamFiles", "showAnnouncements"].includes(action.type)) selectionRevision.current++;// Pin before any await or optimistic state change.- action = pinBotThreadAction(action, stateRef.current.bots);+ action = pinBotThreadAction(action, stateRef.current.bots); if (runNewChat(action)) return;if (action.type === "taskSwitched") action = { ...action, bot: withTaskWrites(action.bot) as Bot };if (action.type === "botPatched") action = { ...action, bot: withTaskWrites(action.bot) };if (action.type === "openForkPanel" && !action.loadId) action = { ...action, loadId: randomUuid() };@@ -2206,14 +2209,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {action.type === "updateBot" || action.type === "setModel"? stateRef.current.bots.find((candidate) => candidate.id === action.botId): undefined;- const botBeforeSend =- action.type === "send"- ? stateRef.current.bots.find((candidate) => candidate.id === action.botId)- : undefined;- const leafBeforeEdit =- action.type === "editMessage"- ? stateRef.current.bots.find((candidate) => candidate.id === action.botId)?.activeLeafId ?? null- : null;+ const botBeforeSend = action.type === "send" ? stateRef.current.bots.find((candidate) => candidate.id === action.botId) : undefined;+ const leafBeforeEdit = action.type === "editMessage" ? stateRef.current.bots.find((candidate) => candidate.id === action.botId)?.activeLeafId ?? null : null;const executionBotsBeforeAction = (() => {if (action.type === "editMessage" || action.type === "answerCard") {const bot = stateRef.current.bots.find((candidate) => candidate.id === action.botId);