Skip to content

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

Keep /new type-safe, and send its attachments with a way back.

Shreerama9b59f722bcdaf
diff --git a/src/components/Composer.slash.test.ts b/src/components/Composer.slash.test.ts
index b92254b001..ee326a43ba 100644
--- a/src/components/Composer.slash.test.ts
+++ b/src/components/Composer.slash.test.ts
@@ -4,8 +4,8 @@ import { createElement } 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 type { Bot } from "@/state/store";
-import { restoreComposerDraft } from "@/lib/drafts";
+import type { Bot, Group } from "@/state/store";
+import { getDraft, getDraftAttachments, restoreComposerDraft } from "@/lib/drafts";
import { newChatThreadId } from "@/state/new-chat";
const dispatch = vi.hoisted(() => vi.fn());
@@ -254,6 +254,39 @@ describe("the / menu in the composer", () => {
expect(dispatch.mock.calls.some(([action]) => action.type === "newTask")).toBe(false);
});
+ it("sends an attached file with the /new prompt, and puts both back when the send fails", () => {
+ const started: Bot = { ...bot, messages: [{ id: "visible-leaf", role: "user", kind: "text", text: "Earlier", at: 1 }] };
+ flushSync(() => root.render(createElement(Composer, { bot: started })));
+ const input = fill("/new ship the notes");
+ const file = { kind: "file" as const, id: "note", path: "/tmp/notes.txt", name: "notes.txt", size: 4 };
+ flushSync(() => restoreComposerDraft(draftId, { text: "/new ship the notes", attachments: [file] }));
+ press(input, "Enter");
+ const sent = dispatch.mock.calls.map(([action]) => action).find((action) => action.type === "send");
+ expect(sent).toEqual(expect.objectContaining({
+ threadId: newChatThreadId(bot.id),
+ text: "ship the notes\n\n<attached-file path=\"/tmp/notes.txt\" name=\"notes.txt\" />",
+ }));
+ flushSync(() => sent.onError());
+ const nextDraft = `bot:${bot.id}:${newChatThreadId(bot.id)}`;
+ expect(getDraft(localStorage, nextDraft)).toBe("ship the notes");
+ expect(getDraftAttachments(localStorage, nextDraft)).toEqual([file]);
+ expect(input.value).toBe("");
+ });
+
+ it("clears a bare /new in a room and does not post it", () => {
+ const room: Group = {
+ id: "room", threadId: "room-thread", name: "Launch", memberIds: [bot.id],
+ defaultResponder: { kind: "member", botId: bot.id }, bulletin: "", unread: false, createdAt: 1, messages: [],
+ };
+ flushSync(() => root.render(createElement(Composer, { group: room, members: [bot] })));
+ const roomDraft = `group:${room.id}:${room.threadId}`;
+ const input = fill("/new", 4, roomDraft);
+ press(input, "Enter");
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(input.value).toBe("");
+ restoreComposerDraft(roomDraft, { text: "", attachments: [] });
+ });
+
it("archives the conversation on /archive, with Undo", () => {
const input = fill("/archive");
press(input, "Enter");
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index fd1c5fbe85..6007626d9c 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -2,7 +2,7 @@ import { directMessageSent, roomMessageSent } from "@/lib/product-events";
import { TeamAudienceLabel } from "./TeamSideSwitch";
import { useComposerDictation } from "@/lib/use-composer-dictation"; import { isPlaceId } from "@/lib/place-chat";
import { ComposerForkError, useComposerFork } from "./ComposerFork";
-import { isNewChatThread } from "@/state/new-chat";
+import { isNewChatThread, newChatThreadId } from "@/state/new-chat";
import { useCallback, useEffect, useMemo, useRef, useState, type SetStateAction } from "react";
import { Mic, Square } from "lucide-react";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select"; import { useStoreRef } from "@/state/store-ref"; import { sameDrawnBots } from "@/lib/drawn-bots";
@@ -304,10 +304,9 @@ export function Composer({
};
const typedGoalText = !group?.dm ? goalTextFromComposer(text) : null;
const effectiveText = typedGoalText ?? text;
- // A room's threads are managed from the room, and a blank New thread has no conversation to act on yet.
const threadCommandAvailable = !group && Boolean(composerTask);
- const startedThread = Boolean(bot) && threadCommandAvailable && !isNewChatThread(threadId) && visibleMessages(bot).length > 0;
- const { command: threadCommand, run: runThreadCommand, dialog: threadCommandDialog, contextMenu } = useComposerThreadCommand({
+ const startedThread = Boolean(bot && threadCommandAvailable && !isNewChatThread(threadId) && visibleMessages(bot).length > 0);
+ const { command: threadCommand, freshPrompt, run: runThreadCommand, dialog: threadCommandDialog, contextMenu } = useComposerThreadCommand({
text, bot: !group ? bot : undefined, threadId, mainThreadId: profile?.mainThreadId, threads: profile?.tasks, threadActions: threadCommandAvailable, started: startedThread,
title: composerTask?.title, busy, dispatch, returnFocusRef: inputRef,
clearText: () => { stopDictation(); editText(""); picks.clear(); setCaret(0); },
@@ -580,7 +579,7 @@ export function Composer({
};
const send = (followUp: FollowUp | undefined = followUpFor(false)) => {
if (locked || attachmentPending) return;
- if (threadCommand) { setDismissedSlashAt(slash?.start ?? 0); runThreadCommand(); return; }
+ if (threadCommand && !freshPrompt) { setDismissedSlashAt(slash?.start ?? 0); runThreadCommand(); return; }
if (fork.command) {
setDismissedSlashAt(slash?.start ?? 0);
fork.submit();
@@ -593,21 +592,22 @@ export function Composer({
dispatch({ type: "error", message: t("composer.error.noImages") });
return;
}
- const composed = composeMessage(serializeThreadRefs(effectiveText, threads, currentBotId), attachments);
+ const composed = composeMessage(serializeThreadRefs(freshPrompt || effectiveText, threads, currentBotId), attachments);
if (!composed) return;
stopDictation();
const body = restoredRequestText(draftId) ?? composed;
- const dataContext = dataContextFor(body, store.state().computerOpen ? store.state().dataView : null, !group && bot ? { botId: bot.id, threadId } : undefined);
+ const sentThread = freshPrompt && startedThread && bot ? newChatThreadId(bot.id) : threadId, sentDraftId = sentThread === threadId ? draftId : `bot:${bot?.id ?? ""}:${sentThread}`;
+ const dataContext = dataContextFor(body, store.state().computerOpen ? store.state().dataView : null, !group && bot ? { botId: bot.id, threadId: sentThread } : undefined);
const sentDraft: ComposerDraftSnapshot = {
- draftId,
- revision: draftRevision(draftId),
- sendId: restoredSendId(draftId) ?? randomUuid(),
- text,
+ draftId: sentDraftId,
+ revision: draftRevision(sentDraftId),
+ sendId: restoredSendId(sentDraftId) ?? randomUuid(),
+ text: freshPrompt || text,
requestText: body,
attachments: [...attachments],
reply: replyTo ?? null,
replyToId: replyTo?.id,
- threadId,
+ threadId: sentThread,
channelMode: effectiveChannelMode, mentions: picks.ids(body), followUp,
};
if (group) {
@@ -625,10 +625,10 @@ export function Composer({
});
roomMessageSent(effectiveChannelMode, busy);
} else if (bot) {
- const points = effectiveChannelMode === "goal" ? null : takePointedChips(threadId);
- const page = effectiveChannelMode === "goal" ? undefined : openPageFor(threadId);
+ if (freshPrompt && startedThread) dispatch({ type: "newTask", botId: bot.id }); const points = effectiveChannelMode === "goal" ? null : takePointedChips(sentThread);
+ const page = effectiveChannelMode === "goal" ? undefined : openPageFor(sentThread);
dispatch({
- type: "send", botId: bot.id, text: body, sendId: sentDraft.sendId, replyToId: replyTo?.id, threadId, dataContext, mode: effectiveChannelMode, mentions: sentDraft.mentions,
+ type: "send", botId: bot.id, text: body, sendId: sentDraft.sendId, replyToId: replyTo?.id, threadId: sentThread, dataContext, mode: effectiveChannelMode, mentions: sentDraft.mentions,
...(points ? { pointed: points.pointed } : {}), ...(page ? { openPage: page } : {}), ...(followUp ? { followUp } : {}),
onError: () => { points?.restore(); restoreDraft(sentDraft); },
});
diff --git a/src/components/use-composer-thread-command.tsx b/src/components/use-composer-thread-command.tsx
index 8fe296510c..050c1b8697 100644
--- a/src/components/use-composer-thread-command.tsx
+++ b/src/components/use-composer-thread-command.tsx
@@ -3,7 +3,6 @@ import { useRef, useState, type RefObject } from "react";
import { t } from "@/lib/i18n";
import { canCompactConversation } from "@/lib/context-warning";
import { newThreadPrompt, threadCommandFromComposer, type ComposerSlashCommand } from "@/lib/composer-commands";
-import { newChatThreadId } from "@/state/new-chat";
import { visibleMessages, type Action, type Bot } from "@/state/store";
import { announceArchiveNotice } from "./bot-archive";
import { ConfirmDialog } from "./ConfirmDialog";
@@ -39,8 +38,11 @@ export function useComposerThreadCommand({ text, bot, threadId, mainThreadId, th
onCleared: () => void;
}) {
const botId = bot?.id;
- const parsed = botId ? threadCommandFromComposer(text) : null;
- const command = parsed === "new" || threadActions ? parsed : null;
+ const parsed = threadCommandFromComposer(text);
+ const newPrompt = parsed === "new" ? newThreadPrompt(text) : "";
+ // A room has no bot. A bare /new there clears the box. /new plus text stays a normal room message.
+ const command = parsed !== "new" ? (botId && threadActions ? parsed : null) : (newPrompt && !botId ? null : "new");
+ const freshPrompt = command === "new" ? newPrompt : "";
const [confirming, setConfirming] = useState(false);
const contextMenu = useRef<{ open: () => void }>(null);
const compact = useContextAction();
@@ -54,18 +56,12 @@ export function useComposerThreadCommand({ text, bot, threadId, mainThreadId, th
if (target) dispatch({ type: "switchTask", botId, threadId: target });
};
const run = () => {
- if (!command || !bot || !botId) return;
if (command === "new") {
- const prompt = newThreadPrompt(text);
onCleared();
- if (!started) {
- if (prompt) dispatch({ type: "send", botId, threadId, text: prompt, mode: "chat" });
- return;
- }
- dispatch({ type: "newTask", botId });
- if (prompt) dispatch({ type: "send", botId, threadId: newChatThreadId(botId), text: prompt, mode: "chat" });
+ if (botId && started) dispatch({ type: "newTask", botId });
return;
}
+ if (!command || !bot || !botId) return;
if (command === "context") {
clearText();
contextMenu.current?.open();
@@ -119,5 +115,5 @@ export function useComposerThreadCommand({ text, bot, threadId, mainThreadId, th
returnFocusRef={returnFocusRef}
/>
);
- return { command, run, dialog, contextMenu };
+ return { command, freshPrompt, run, dialog, contextMenu };
}