Skip to content

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

merge: 同步上游 main 并解决会话分叉冲突

Zhehui Bib2c03f7320fb
diff --cc server/host/room-reads.test.ts
index 0083b11d16,e7425dc923..8f2e111f0a
--- a/server/host/room-reads.test.ts
+++ b/server/host/room-reads.test.ts
@@@ -3,7 -3,7 +3,8 @@@ import { tmpdir } from "node:os"
import { join } from "node:path";
import { expect, it } from "vitest";
+import type { WireGroup } from "../../shared/wire.ts";
+ import { personKey } from "../person-key.ts";
import { createPersonRooms, createRoomReads, roomUnreadFor } from "./room-reads.ts";
const path = [{ id: "m1", role: "user" }, { id: "m2", role: "bot" }, { id: "m3", role: "user" }];
@@@ -54,26 -51,37 +55,61 @@@ it("forgets a person's lines in every r
expect([reloaded.readUpTo("a", "p_ada"), reloaded.readUpTo("b", "p_ada")]).toEqual([undefined, undefined]);
});
+it("keeps a person's background fork unread after they read the room's main conversation", () => {
+ const dir = mkdtempSync(join(tmpdir(), "room-fork-reads-"));
+ const reads = createRoomReads(dir);
+ const paths = new Map([
+ ["main", [{ id: "main-user", role: "user" }, { id: "main-reply", role: "bot" }]],
+ ["fork", [{ id: "fork-user", role: "user" }, { id: "fork-reply", role: "bot" }]],
+ ]);
+ const group = { id: "room", threadId: "main", unread: true, tasks: [
+ { threadId: "main", unread: true }, { threadId: "fork", unread: true },
+ ] } as WireGroup;
+ const rooms = createPersonRooms({ reads, store: () => ({
- activePath: (threadId) => paths.get(threadId) ?? [], messagesFor: (threadId) => paths.get(threadId) ?? [],
++ activePath: (threadId) => paths.get(threadId) ?? [], messagesFor: (threadId) => paths.get(threadId) ?? [], botByThread: () => null,
+ }), newestMessageId: (threadId) => paths.get(threadId)?.at(-1)?.id,
- publicGroupState: () => group, broadcast: () => {},
++ shared: () => false, wireBot: () => null, publicGroupState: () => group, broadcast: () => {},
+ });
+ reads.read("room", "ada", "main-reply", "main");
+ expect(rooms.groupForPerson(group, "ada")).toMatchObject({ unread: true, tasks: [
+ { threadId: "main", unread: false }, { threadId: "fork", unread: true },
+ ] });
+ reads.read("room", "ada", "fork-reply", "fork");
+ expect(rooms.groupForPerson(group, "ada").unread).toBe(false);
+ expect(rooms.groupForPerson(group, "ben").unread).toBe(true);
+});
++
+ it("reads a bot's shared chat per person, leaves a private chat's one mark alone, and marks unread before the newest reply", () => {
+ const dir = mkdtempSync(join(tmpdir(), "room-reads-"));
+ const thread = [{ id: "m1", role: "user" }, { id: "m2", role: "bot" }, { id: "m3", role: "user" }, { id: "m4", role: "bot" }];
+ const frames: Array<{ person: string }> = [];
+ const rooms = createPersonRooms({
+ reads: createRoomReads(dir),
+ store: () => ({ activePath: () => thread, messagesFor: () => thread, botByThread: () => ({ id: "scout" }) }),
+ shared: (threadId) => threadId === "main",
+ wireBot: (id) => ({ id }),
+ newestMessageId: () => "m4",
+ publicGroupState: (room) => room as never,
+ broadcast: (_payload, options) => frames.push(options),
+ });
+ const ada = { kind: "session", session: { id: "s1", email: "[email protected]" } } as never;
+ const adaKey = personKey({ id: "", email: "[email protected]" }), cleoKey = personKey({ id: "", email: "[email protected]" });
+ const main = { threadId: "main", unread: true, lastReadMessageId: "m2" };
+ expect(rooms.taskForPerson(main, cleoKey), "never read: the chat's own mark, without anyone's read line").toEqual({ threadId: "main", unread: true });
+ expect(rooms.personMarkThread!(ada, "main", false)).toBe(true);
+ expect(rooms.taskForPerson(main, adaKey)).toEqual({ threadId: "main", unread: false, lastReadMessageId: "m4" });
+ expect(rooms.taskForPerson(main, cleoKey).unread).toBe(true);
+ expect(frames, "told to Ada's streams alone").toEqual([{ person: adaKey }]);
+ expect(rooms.personMarkThread!(ada, "main", true)).toBe(true);
+ expect(rooms.taskForPerson(main, adaKey)).toEqual({ threadId: "main", unread: true, lastReadMessageId: "m3" });
+ const own = { threadId: "mine", unread: true, lastReadMessageId: "m2" };
+ expect(rooms.personMarkThread!(ada, "mine", false), "a private chat keeps its one mark").toBe(false);
+ expect(rooms.taskForPerson(own, adaKey)).toBe(own);
+ });
+
+ it("forgets a person's other marks of their own with their read lines", () => {
+ const forgotten: string[] = [];
+ const reads = createRoomReads(mkdtempSync(join(tmpdir(), "room-reads-")), (person) => forgotten.push(person));
+ reads.forgetPerson("p_ada");
+ expect(forgotten, "even with no read line of theirs").toEqual(["p_ada"]);
+ });
diff --cc server/host/room-reads.ts
index be7faadb7d,48e323aa9e..af959cad46
--- a/server/host/room-reads.ts
+++ b/server/host/room-reads.ts
@@@ -98,21 -108,22 +109,32 @@@ export function createPersonRooms(deps
/** A room's unread mark and read line as this person has read it, on a Team Cloud; the room as it is anywhere else. */
function groupForPerson(group: WireGroup, person: string | null): WireGroup {
if (!reads || !person) return group;
- const readUpTo = reads.readUpTo(group.id, person);
- const unread = roomUnreadFor(deps.store().activePath(group.threadId), readUpTo, group.unread, atOf(group.threadId));
- if (unread === group.unread && readUpTo === group.lastReadMessageId) return group;
+ const currentPath = deps.store().activePath(group.threadId);
+ const legacyRead = reads.readUpTo(group.id, person);
+ const currentRead = reads.readUpTo(group.id, person, group.threadId)
+ ?? (legacyRead && currentPath.some((message) => message.id === legacyRead) ? legacyRead : undefined);
+ const tasks = group.tasks?.map((task) => {
+ const path = deps.store().activePath(task.threadId);
+ const readUpTo = task.threadId === group.threadId ? currentRead : reads.readUpTo(group.id, person, task.threadId);
- const unread = roomUnreadFor(path, readUpTo, task.unread ?? false,
- (id) => deps.store().messagesFor(task.threadId).find((message) => message.id === id)?.at);
++ const unread = roomUnreadFor(path, readUpTo, task.unread ?? false, atOf(task.threadId));
+ return { ...task, unread };
+ });
- const unread = tasks ? tasks.some((task) => task.unread) : roomUnreadFor(currentPath, currentRead, group.unread);
++ const unread = tasks ? tasks.some((task) => task.unread) : roomUnreadFor(currentPath, currentRead, group.unread, atOf(group.threadId));
++ if (unread === group.unread && currentRead === group.lastReadMessageId &&
++ (!tasks || tasks.every((task, index) => task.unread === group.tasks?.[index]?.unread))) return group;
const { lastReadMessageId: _shared, ...rest } = group;
- return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}) };
+ return { ...rest, tasks, unread, ...(currentRead ? { lastReadMessageId: currentRead } : {}) };
}
+ /** A bot's shared conversation's unread mark and read line as this person read it, on a Team Cloud; the task as it is
+ * anywhere else and for a private chat. Nobody's read line but their own goes out. */
+ function taskForPerson<T extends { threadId: string; unread?: boolean; lastReadMessageId?: string }>(task: T, person: string): T {
+ if (!reads || !deps.shared(task.threadId)) return task;
+ const readUpTo = reads.readUpTo(threadReadKey(task.threadId), person);
+ const unread = roomUnreadFor(deps.store().activePath(task.threadId), readUpTo, task.unread === true, atOf(task.threadId));
+ if (unread === (task.unread === true) && readUpTo === task.lastReadMessageId) return task;
+ const { lastReadMessageId: _shared, ...rest } = task;
+ return { ...rest, unread, ...(readUpTo ? { lastReadMessageId: readUpTo } : {}) } as T;
+ }
return {
reads,
groupForPerson,
diff --cc server/index.ts
index f7ba9d703c,bd7121190d..c16e242f76
--- a/server/index.ts
+++ b/server/index.ts
@@@ -298,13 -295,12 +295,13 @@@ import { createRoomAccess, PRIVATE_CHAT
import { outsideRoomNote, sentRow, teammateResultRow, WAIT_CARD_CLOSED_REASON } from "./host/handoff-sent.ts";
import { createWebhookRoomPost } from "./host/webhook-room-deps.ts";
import { createRoomJobs, parallelRoomJobsEnabled, type RoomRoundLine } from "./host/room-jobs.ts";
+import { markGroupThreadUnreadAfterTurn } from "./group-task-state.ts";
import { createDelegatedLevel } from "./host/delegated-level.ts";
import { createLiveApprovalMode } from "./host/live-approval.ts";
- import { CONSENT_RULE, continuedOrigin, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProvenanceNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts"; import { lineNote, PROVENANCE_PROMPT } from "./provenance-label.ts"; import { openRoomThread } from "./host/room-new-thread.ts"; import { createLineLabels } from "./host/line-labels.ts";
+ import { CONSENT_RULE, continuedOrigin, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProvenanceNote, quoteInNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts"; import { lineNote, PROVENANCE_PROMPT } from "./provenance-label.ts"; import { openRoomThread } from "./host/room-new-thread.ts"; import { createLineLabels } from "./host/line-labels.ts";
import { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";
import { messagePages, pageSize, slimMessage } from "./host/message-pages.ts";
- import { coordinateResultMessage, createAsksActingPerson, createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";
+ import { coordinateResultMessage, createAsksActingPerson, createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createPersonalReach } from "./host/personal-reach.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";
import { createQueuedReason } from "./host/queued-reason.ts";
import { ReplayBuffer } from "./host/sse-replay.ts";
import {
diff --cc server/routes/channels.ts
index 171b441966,abb2511692..02649c22f0
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@@ -39,9 -41,12 +41,12 @@@ import { readThreadNotifications, type
export type MessagePage = { messages: Array<Message | Record<string, unknown>>; hasMore?: boolean; activeLeafId: string | null };
export interface ChannelRouteDeps {
+ /** Whoever asked owns the run, where several people write. */
+ runOwners?: RouteRunOwners;
+ runActor?(auth: RequestAuth): Actor;
store: Pick<Store,
- | "group" | "groupTaskByThread" | "bot" | "switchGroupTask" | "patchGroupTask" | "patchGroup" | "messagesFor" | "groupTasks" | "deleteGroupTasks" | "deleteGroup"
- | "createGroupTask" | "appendMessage">;
+ | "group" | "groupTaskByThread" | "bot" | "switchGroupTask" | "patchGroupTask" | "patchGroup" | "markGroupThreadUnread" | "messagesFor" | "groupTasks" | "deleteGroupTasks" | "deleteGroup"
+ | "createGroupTask" | "forkGroupTask" | "appendMessage">;
cfg: Pick<AppConfig, "budgets">;
/** What people's lines are called in this conversation (replies.ts PersonName). */
userName(threadId: string): PersonName;
diff --cc server/store.ts
index 9e124008df,9dbfa4a5f0..a3b1ab56e8
--- a/server/store.ts
+++ b/server/store.ts
@@@ -2277,10 -2267,10 +2265,10 @@@ export class Store
const deleted = unique.filter((id) => present.has(id));
const missing = unique.filter((id) => !present.has(id));
if (!deleted.length) return { bot, deleted, missing };
- const doomed = new Set(deleted);
+ const doomed = new Set(deleted); this.threadsGoing(deleted);
mdb.deleteThreads(deleted, () => this.commitBotChange(bot, "the thread deletion", () => {
const kept = bot.tasks!.filter((t) => !doomed.has(t.threadId));
- const visible = nextOpenThread(kept) ?? this.buildTask(bot);
+ const visible = nextOpenThread(kept) ?? buildTask(bot);
bot.tasks = kept.includes(visible) ? kept : [visible, ...kept];
if (doomed.has(bot.threadId) || this.taskByThread(botId, bot.threadId)?.routineRunId) this.mirrorActiveTask(bot, visible);
bot.unread = bot.tasks.some(taskCountsAsBotUnread);
diff --cc shared/task-provenance.ts
index 577756acbf,0000000000..f08c97af82
mode 100644,000000..100644
--- a/shared/task-provenance.ts
+++ b/shared/task-provenance.ts
@@@ -1,31 -1,0 +1,33 @@@
+/** The bot that opened a thread on itself or a teammate. */
+export interface TaskOpenedBy {
+ botId: string;
+ name: string;
+ delegationId?: string;
+ /** What kind of conversation the opener made this: "pair" is the one
+ * durable conversation between two bots; "work" closes itself once its
+ * result has been reported. */
+ kind?: "pair" | "work";
++ /** The burst this thread is one part of: it is listed under that burst's card. */
++ burstId?: string;
+ /** The opener's own conversation this "work" thread was opened from.
+ * Everything that conversation later sends this bot continues here. */
+ threadId?: string;
+ /** A parallel room job's thread: `threadId` is the room thread it came from, and the member must stay in that room. */
+ roomLane?: true;
+ /** Security invariant: harness-set only when the opening turn could use the owner's lent computer. */
+ forOwner?: true;
+ at: number;
+}
+
+/** The bot that closed a thread it opened (or one of its own). */
+export interface TaskClosedBy {
+ botId: string;
+ name: string;
+ at: number;
+}
+
+/** The completed message whose visible history seeded an independent conversation. */
+export interface ForkOrigin {
+ threadId: string;
+ messageId: string;
+}
diff --cc src/components/ChatView.tsx
index 95c25ce6d1,d595e1bbf7..7808107f36
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@@ -92,11 -92,11 +92,11 @@@ import { AttachmentGallery, collectMess
import { ScreenFrame } from "./ScreenFrame";
import { CompactionChip, DigestChip } from "./DigestChip";
import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";
- import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { useStoreRef } from "@/state/store-ref";
+ import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { ThreadPresenceFaces } from "./TeamPresence"; import { useStoreRef } from "@/state/store-ref";
import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";
import { ModelPicker } from "./ModelPicker";
- import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine";
+ import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine"; import { ownChatStarted } from "@/state/team-chats";
-import { useChatFindRequests } from "@/lib/chat-find";
+import { useChatFindRequests, useChatFindShortcut } from "@/lib/chat-find";
import { CitationSelectionToolbar, SentCitations } from "./CitationUI";
import { SpeakButton } from "./SpeakButton";
import { CallOverlay } from "./CallView";
@@@ -898,10 -910,10 +898,10 @@@ export function ChatView({ bot: profile
const reactor = useReactor();
const speakerViewer = state.config?.team && reactor !== "user" ? reactor : null;
const rows = useMemo<ChatRows>(
- () => ({ 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: canWrite !== false, openedAt, speakerViewer }),
- [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, canWrite, openedAt, speakerViewer],
+ () => ({ 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: canWrite !== false, 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, canWrite, 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, 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 || ownChatStarted(bot.threadId)), 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 --cc src/components/GroupView.tsx
index 7912d870e0,b42635c50f..83ae52761b
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@@ -1015,10 -1020,10 +1015,10 @@@ export function GroupView({ group, inFo
membersTriggerRef={membersTriggerRef}
/>
- {findOpen && <ChatFindBar threadId={group.threadId} onClose={() => setFindOpen(false)} />}
+ {findOpen && <ChatFindBar threadId={group.threadId} inForkPanel={inForkPanel} onClose={() => setFindOpen(false)} />}
<ChatErrorBanner message={state.error} onDismiss={() => dispatch({ type: "error", message: null })} />
<ChatNotice notice={state.notice} />
- {!setupPending && <RoomContextWarnings group={group} members={members} />}
+ {!setupPending && <RoomContextWarnings group={group} members={members} />}{!setupPending && !remoteClient && <RoomChiefAbsent group={group} />}
{!setupPending && !group.dm && !remoteClient && state.config && group.defaultResponder.kind === "auto" && !jevRoomRoutingOn(state.config) && (
<div className="w-full px-5">
diff --cc src/state/store.tsx
index 794e61873e,6a105f88a8..3569597792
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@@ -221,10 -215,9 +221,10 @@@ export interface ModelSelection
variant?: string;
}
- export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks"> {
+ export interface Task extends Pick<WireTask, "private" | "setupRequest" | "inbox" | "openAsks" | "askedBy"> {
waitingForTeammates?: boolean; sharedChat?: true;
threadId: string;
+ origin?: import("../../shared/wire").ForkOrigin;
routineRunId?: string;
projectId?: string;
title: string;
diff --cc tsconfig.json
index fe66f710c3,fe66f710c3..4ec06e0377
--- a/tsconfig.json
+++ b/tsconfig.json
@@@ -1,7 -1,7 +1,7 @@@
{
"compilerOptions": {
"target": "ES2022",
-- "lib": ["ES2022", "DOM", "DOM.Iterable"],
++ "lib": ["ES2024", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",