Skip to content

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

Rooms: resume the last viewed thread from the sidebar

RinKokawa7852a1ef565c
diff --git a/DESIGN.md b/DESIGN.md
index 92592f2fad..69f1d040d8 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -199,7 +199,10 @@ element's job and never a pixel value:
thread's first line, its reply count, who replied and when; a row, a room
thread opened from anywhere, and an Inbox line open their thread in a panel
beside the chat (`ForkPanel`), never by moving the room's current thread,
- which is everyone's. The feed's composer starts a new thread; the room's
+ which is everyone's. Returning from the sidebar reopens the thread that person
+ last viewed in the room on this device. Closing the panel leaves just the feed
+ on the next visit, as does a thread that was archived or deleted.
+ The feed's composer starts a new thread; the room's
"+" in the sidebar brings the room up with the cursor in that composer. A row carries
the sidebar thread row's menu behind a quiet More (hover, focus and touch),
a pin mark when pinned, and its unread or waiting dot; the thread beside the
diff --git a/docs/verification/evidence/room-thread-resume/daylight.png b/docs/verification/evidence/room-thread-resume/daylight.png
new file mode 100644
index 0000000000..eda09553ce
Binary files /dev/null and b/docs/verification/evidence/room-thread-resume/daylight.png differ
diff --git a/docs/verification/evidence/room-thread-resume/midnight.png b/docs/verification/evidence/room-thread-resume/midnight.png
new file mode 100644
index 0000000000..1c68a1cd39
Binary files /dev/null and b/docs/verification/evidence/room-thread-resume/midnight.png differ
diff --git a/docs/verification/evidence/room-thread-resume/navigation.mp4 b/docs/verification/evidence/room-thread-resume/navigation.mp4
new file mode 100644
index 0000000000..26725b2b37
Binary files /dev/null and b/docs/verification/evidence/room-thread-resume/navigation.mp4 differ
diff --git a/scripts/testing/room-feed-ui.e2e.test.ts b/scripts/testing/room-feed-ui.e2e.test.ts
index a3628c487c..c071ccfd34 100644
--- a/scripts/testing/room-feed-ui.e2e.test.ts
+++ b/scripts/testing/room-feed-ui.e2e.test.ts
@@ -106,6 +106,19 @@ async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 3
expect(await current()).toBe(room.threadId);
await ui("screenshot", "--out", join(evidenceDir, "room-feed-thread.png"));
+ const revisitRoom = async () => {
+ await evaluate(`document.querySelector('[data-sidebar-bot-row="${basil.id}"]').click(); true`);
+ await until(() => evaluate("!document.querySelector('[data-room-feed], [data-thread-panel]')"), "leaving the room");
+ await evaluate(`document.querySelector('[data-sidebar-group-row="${room.id}"]').click(); true`);
+ await until(() => evaluate(`Boolean(document.querySelector('[data-room-feed="${room.id}"]'))`), "returning to the room");
+ };
+ await revisitRoom();
+ await until(() => evaluate(`Boolean(document.querySelector('[data-thread-panel="${opened}"]'))`), "the last viewed thread beside the feed");
+ expect(await current()).toBe(room.threadId);
+ await browse("click", "[data-thread-panel] button[aria-label='Close thread']");
+ await revisitRoom();
+ expect(await evaluate("Boolean(document.querySelector('[data-thread-panel]'))")).toBe(false);
+
await browse("click", "[data-room-feed-composer] textarea");
await browse("type", "[data-room-feed-composer] textarea", "Draft the outage email");
await browse("press", "Enter");
diff --git a/src/components/ForkPanel.focus.test.ts b/src/components/ForkPanel.focus.test.ts
index 874a39b542..113481a106 100644
--- a/src/components/ForkPanel.focus.test.ts
+++ b/src/components/ForkPanel.focus.test.ts
@@ -6,6 +6,7 @@ import { expect, it, vi } from "vitest";
const store = vi.hoisted(() => ({ state: {} as Record<string, unknown>, dispatch: vi.fn() }));
vi.mock("@/state/store", () => ({ useStore: () => store, currentTaskBot: (bot: object) => bot }));
+vi.mock("@/lib/default-bot", () => ({ useViewerEmail: () => null }));
vi.mock("./ChatView", () => ({ ChatView: () => createElement("div", { "data-tour": "composer" }, createElement("textarea")) }));
vi.mock("./GroupView", () => ({ GroupView: () => createElement("div", { "data-tour": "composer" }, createElement("textarea")) }));
diff --git a/src/components/ForkPanel.tsx b/src/components/ForkPanel.tsx
index 13a1abbf72..418d1c72cb 100644
--- a/src/components/ForkPanel.tsx
+++ b/src/components/ForkPanel.tsx
@@ -1,5 +1,8 @@
import { ArrowLeft, X } from "lucide-react";
-import { useLayoutEffect, useRef } from "react";
+import { useEffect, useLayoutEffect, useRef } from "react";
+import { useViewerEmail } from "@/lib/default-bot";
+import { rememberRoomThread } from "@/lib/last-room-thread";
+import { roomFeedShows } from "@/lib/room-feed";
import { cn } from "@/lib/cn";
import { useInboxPanel } from "@/state/inbox";
import { currentTaskBot, useStore } from "@/state/store";
@@ -34,6 +37,12 @@ export function ForkPanel({ full = false }: { full?: boolean }) {
(aside.querySelector<HTMLTextAreaElement>('[data-tour="composer"] textarea:not([disabled])') ?? aside).focus();
}, [panel?.focusComposer, panel?.loadId, panel?.loading]);
const panelGroup = panel?.kind === "group" ? state.groups.find((candidate) => candidate.id === panel.ownerId) : undefined;
+ const viewer = useViewerEmail();
+ const feedRoomId = panelGroup && roomFeedShows(state.config, panelGroup) ? panelGroup.id : undefined;
+ const threadId = panel?.threadId;
+ useEffect(() => {
+ if (feedRoomId && threadId) rememberRoomThread(viewer, feedRoomId, threadId);
+ }, [viewer, feedRoomId, threadId]);
const turnStartedAt = useThreadTurnStart(panelGroup, panelGroup?.tasks?.find((candidate) => candidate.threadId === panel?.threadId));
if (!panel) return null;
const bot = panel.kind === "bot" ? state.bots.find((candidate) => candidate.id === panel.ownerId) : undefined;
@@ -47,7 +56,10 @@ export function ForkPanel({ full = false }: { full?: boolean }) {
turnStartedAt, pinnedCwd: groupTask.pinnedCwd, pinnedMessageId: groupTask.pinnedMessageId } : null;
const fork = !beside || Boolean(task?.origin);
const label = fork ? t("chat.forkPanel") : t("room.thread.panel");
- const close = () => dispatch({ type: "closeForkPanel" });
+ const close = () => {
+ if (feedRoomId) rememberRoomThread(viewer, feedRoomId, null);
+ dispatch({ type: "closeForkPanel" });
+ };
const roomThread = beside && !fork && Boolean(group);
const inPlace = full && roomThread;
@@ -78,7 +90,7 @@ export function ForkPanel({ full = false }: { full?: boolean }) {
<header className="flex shrink-0 items-center gap-2 py-2.5 ps-4 pe-3">
{inPlace && group && <button type="button" aria-label={t("room.thread.backToFeed", { name: group.name })} title={t("room.thread.backToFeed", { name: group.name })}
data-thread-back="" className="ui-icon-button shrink-0" onClick={close}><ArrowLeft size={16} aria-hidden="true" /></button>}
- {!fork && group && groupTask ? <ThreadPanelHeading group={group} task={groupTask} messages={panel.messages} working={Boolean(openedGroup?.working || openedGroup?.busyBotId)} /> : <div className="min-w-0 flex-1">
+ {!fork && group && groupTask ? <ThreadPanelHeading group={group} task={groupTask} messages={panel.messages} working={Boolean(openedGroup?.working || openedGroup?.busyBotId)} onClose={close} /> : <div className="min-w-0 flex-1">
<h2 dir="auto" title={task?.title} className="truncate text-[15px] font-semibold leading-5 text-ink">{fork ? task?.title ?? label : label}</h2>
<p dir="auto" className="truncate text-[12px] leading-4 text-ink-secondary">{group?.name ?? bot?.name}</p>
</div>}
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 4a5f162314..ab82a48d8d 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -8,6 +8,7 @@ import { approvalModeFor } from "../../shared/approval-mode";
import { liveActivityLabel, sidebarMessage } from "@/lib/live-activity";
import { SidebarWorkingStep } from "./SidebarWorkingStep"; import { FadeLine } from "./FadeLine";
import { openBotRow } from "@/state/thread-navigation";
+import { openRoomRow } from "@/lib/last-room-thread";
import { BotAvatar } from "./Avatar"; import { useMotionBeat } from "./mascot-beat";
import { BotEngineMark, BotModelBadge, botTooltip } from "./BotModelBadge"; import { SidebarBotRole } from "./BotRole";
@@ -137,18 +138,15 @@ export function openBotContextMenu(onMenu: (menu: MenuState) => void, botId: str
onMenu({ botId, x: event.clientX, y: event.clientY });
}
-export const GroupListItem = memo(function GroupListItem({
- group,
- density,
- query = "",
- onMenu,
-}: {
+export const GroupListItem = memo(function GroupListItem({ group, viewerEmail, density, query = "", onMenu }: {
group: Group;
+ viewerEmail?: string | null;
density: SidebarDensity;
query?: string;
onMenu: (menu: { groupId: string; x: number; y: number }) => void;
}) {
- const dispatch = useStoreDispatch(), bots = useStoreSelector((s) => s.bots, sameDrawnBots), instances = useStoreSelector((s) => s.instances);
+ const store = useStoreRef(), { dispatch } = store;
+ const bots = useStoreSelector((s) => s.bots, sameDrawnBots), instances = useStoreSelector((s) => s.instances);
const advanced = useAdvancedMode(), feed = useRoomFeed(group);
const selected = useStoreSelector((s) => s.activeView === "chat" && s.selectedId === group.id);
const [threadsOpen, setThreadsOpen] = useSearchDisclosure(`group:${group.id}`, query ?? "", searchMatchesThreads(query ?? "", group.tasks), selected);
@@ -172,7 +170,7 @@ export const GroupListItem = memo(function GroupListItem({
<button
data-sidebar-group-row={group.id}
aria-current={selected && !expanded ? "page" : undefined}
- onClick={() => dispatch({ type: "select", id: group.id })}
+ onClick={() => openRoomRow(dispatch, group, store.state(), viewerEmail)}
onContextMenu={(e) => {
e.preventDefault();
onMenu({ groupId: group.id, x: e.clientX, y: e.clientY });
@@ -1431,6 +1429,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
<GroupListItem
key={group.id}
group={group}
+ viewerEmail={viewerEmail}
density={density}
query={q}
onMenu={setRoomMenu}
diff --git a/src/components/room-feed/ThreadPanelHeading.dom.test.ts b/src/components/room-feed/ThreadPanelHeading.dom.test.ts
index 72f125a12f..95eeb2a90c 100644
--- a/src/components/room-feed/ThreadPanelHeading.dom.test.ts
+++ b/src/components/room-feed/ThreadPanelHeading.dom.test.ts
@@ -24,7 +24,7 @@ let root: Root | null = null;
afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; fixture.dispatch.mockClear(); fixture.find.mockClear(); });
const open = () => {
root = createRoot(document.body.appendChild(document.createElement("header")));
- act(() => root!.render(createElement(ThreadPanelHeading, { group, task, messages: [], working: false })));
+ act(() => root!.render(createElement(ThreadPanelHeading, { group, task, messages: [], working: false, onClose: vi.fn() })));
act(() => document.querySelector<HTMLButtonElement>("button[aria-expanded]")!.click());
};
const menuItem = (label: string) => [...document.querySelectorAll<HTMLButtonElement>("[data-thread-overlay] button")].find((button) => button.textContent?.trim() === label);
diff --git a/src/components/room-feed/ThreadPanelHeading.tsx b/src/components/room-feed/ThreadPanelHeading.tsx
index de87a50242..d8df98e2dc 100644
--- a/src/components/room-feed/ThreadPanelHeading.tsx
+++ b/src/components/room-feed/ThreadPanelHeading.tsx
@@ -17,7 +17,7 @@ const ITEM = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left te
/** The title of a room thread open beside its feed, and its menu: what the feed row's menu offers, and what the room's
* header and menu offered for its one thread before the feed: find, the export (its lines are loaded here) and its
* time per turn. */
-export function ThreadPanelHeading({ group, task, messages, working }: { group: Group; task: GroupTask; messages: readonly Message[]; working: boolean }) {
+export function ThreadPanelHeading({ group, task, messages, working, onClose }: { group: Group; task: GroupTask; messages: readonly Message[]; working: boolean; onClose: () => void }) {
const store = useStoreRef();
const dispatch = store.dispatch;
const [menu, setMenu] = useState<ThreadMenuAt | null>(null);
@@ -29,7 +29,6 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
[task.threadId, task.title, task.pinned, task.archivedAt, working, closer]);
const now = useRelativeNow();
const actions = useMemo(() => roomThreadRowActions(group.id, dispatch), [group.id, dispatch]);
- const close = () => dispatch({ type: "closeForkPanel" });
const markdown = () => formatTranscriptMarkdown({ title: task.title, messages, isGroup: true });
const limit = useConversationTurnLimit({ ...group, threadId: task.threadId });
const limits: Array<{ key: string; minutes: number | null; label: string }> = [
@@ -40,10 +39,10 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
const menuSheet = useThreadRowMenu({
task: row, displayTitle: title, ownerId: group.id, menu, setMenu, actionRef: moreRef,
onStartRename: () => { setMenu(null); setRenaming(true); },
- onDelete: (thread) => { close(); actions.onDelete(thread); },
+ onDelete: (thread) => { onClose(); actions.onDelete(thread); },
onPin: actions.onPin,
onSetClosed: actions.onSetClosed,
- onArchive: (thread, archivedAt) => { if (archivedAt !== null) close(); actions.onArchive(thread, archivedAt); },
+ onArchive: (thread, archivedAt) => { if (archivedAt !== null) onClose(); actions.onArchive(thread, archivedAt); },
deletable: (group.tasks?.length ?? 1) > 1,
extra: (done) => <>
<button type="button" data-thread-find="" className={ITEM} onClick={() => { done(); requestChatFind(task.threadId); }}>
diff --git a/src/lib/last-room-thread.test.ts b/src/lib/last-room-thread.test.ts
new file mode 100644
index 0000000000..e199fc99f4
--- /dev/null
+++ b/src/lib/last-room-thread.test.ts
@@ -0,0 +1,75 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from "vitest";
+import { initialState, type AppState, type Group } from "@/state/store";
+import { openThreadBeside } from "./room-feed";
+import { openRoomRow, rememberRoomThread } from "./last-room-thread";
+
+const state = { ...initialState, config: { features: { roomFeed: true } } as AppState["config"] };
+const room = (id: string): Group => ({ id, threadId: `${id}-main`, name: id, memberIds: [], messages: [], bulletin: "", createdAt: 1,
+ unread: false, defaultResponder: { kind: "mentions" }, tasks: ["main", "side"].map((suffix) => ({ threadId: `${id}-${suffix}`, title: suffix, createdAt: 1 })) });
+const a = room("a"), b = room("b");
+const visit = (group: Group, viewer: string | null | undefined = null, place = state) => {
+ const dispatch = vi.fn();
+ openRoomRow(dispatch, group, place, viewer);
+ return dispatch.mock.calls.flat();
+};
+const select = (id: string) => ({ type: "select", id });
+const opened = (ownerId: string, threadId: string) => ({ type: "openForkPanel", kind: "group", ownerId, threadId });
+afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); localStorage.clear(); });
+
+it("resumes each room's own last viewed thread, not its shared current thread or another viewer's choice", () => {
+ expect(visit(a)).toEqual([select("a")]);
+ rememberRoomThread(null, "a", "a-side");
+ rememberRoomThread(null, "b", "b-main");
+ rememberRoomThread("[email protected]", "a", "a-main");
+ expect(visit(a)).toEqual([select("a"), opened("a", "a-side")]);
+ expect(visit(b)).toEqual([select("b"), opened("b", "b-main")]);
+ expect(visit(a, "[email protected]")).toEqual([select("a"), opened("a", "a-main")]);
+ rememberRoomThread(null, "a", null);
+ expect(visit(a)).toEqual([select("a")]);
+ expect(visit(b)).toEqual([select("b"), opened("b", "b-main")]);
+});
+
+it("keeps the already open panel, without reloading it or resetting its composer", () => {
+ const panel: AppState["forkPanel"] = { kind: "group", ownerId: "a", threadId: "a-side", messages: [], loading: false, loadId: "load", activeLeafId: null, loadFailed: false };
+ expect(visit(a, null, { ...state, selectedId: "a", activeView: "chat", forkPanel: panel })).toEqual([]);
+});
+
+it.each(["archived", "deleted", "owned by another room"])("keeps the feed when the remembered thread is %s", (why) => {
+ rememberRoomThread(null, "a", why === "owned by another room" ? "b-side" : "a-side");
+ const tasks = why === "deleted" ? a.tasks!.slice(0, 1) : a.tasks!.map((t) => t.threadId === "a-side" && why === "archived" ? { ...t, archivedAt: 2 } : t);
+ expect(visit({ ...a, tasks })).toEqual([select("a")]);
+ expect(visit(a)).toEqual([select("a")]);
+});
+
+it("keeps normal selection for old homes, bot-to-bot rooms and phones without forgetting the desktop choice", () => {
+ rememberRoomThread(null, "a", "a-side");
+ expect(visit(a, null, { ...state, config: null })).toEqual([select("a")]);
+ expect(visit({ ...a, dm: true })).toEqual([select("a")]);
+ vi.spyOn(window, "matchMedia").mockReturnValue({ matches: false } as MediaQueryList);
+ expect(visit(a)).toEqual([select("a")]);
+ vi.restoreAllMocks();
+ expect(visit(a)).toEqual([select("a"), opened("a", "a-side")]);
+});
+
+it("opens only the thread named by an Inbox entry", () => {
+ rememberRoomThread(null, "a", "a-side");
+ const dispatch = vi.fn();
+ expect(openThreadBeside(dispatch, "a-main", { ...state, groups: [a], selectedId: "b" })).toBe(true);
+ expect(dispatch.mock.calls.flat()).toEqual([select("a"), opened("a", "a-main")]);
+});
+
+it("does not borrow the local person's selection while the viewer is still unknown", () => {
+ rememberRoomThread(null, "a", "a-main");
+ rememberRoomThread(undefined, "a", "a-side");
+ const dispatch = vi.fn();
+ openRoomRow(dispatch, a, state, undefined);
+ expect(dispatch.mock.calls.flat()).toEqual([select("a")]);
+ expect(visit(a)).toEqual([select("a"), opened("a", "a-main")]);
+});
+
+it("still opens the room if browser storage is unavailable", () => {
+ vi.stubGlobal("localStorage", { getItem() { throw new Error("blocked"); }, setItem() { throw new Error("blocked"); } });
+ rememberRoomThread(null, "a", "a-side");
+ expect(visit(a)).toEqual([select("a")]);
+});
diff --git a/src/lib/last-room-thread.ts b/src/lib/last-room-thread.ts
new file mode 100644
index 0000000000..be24c29e0c
--- /dev/null
+++ b/src/lib/last-room-thread.ts
@@ -0,0 +1,31 @@
+import type { Action, AppState, Group } from "@/state/store";
+import { openFeedThread, roomFeedShows } from "./room-feed";
+
+type Viewer = string | null | undefined;
+const key = (viewer: string | null, roomId: string) => `omb.lastRoomThread:${JSON.stringify([viewer, roomId])}`;
+
+export function rememberRoomThread(viewer: Viewer, roomId: string, threadId: string | null): void {
+ if (viewer === undefined) return;
+ try {
+ if (threadId === null) localStorage.removeItem(key(viewer, roomId));
+ else localStorage.setItem(key(viewer, roomId), threadId);
+ } catch {}
+}
+
+function lastRoomThread(viewer: Viewer, roomId: string): string | null {
+ if (viewer === undefined) return null;
+ try { return localStorage.getItem(key(viewer, roomId)); } catch { return null; }
+}
+
+export function openRoomRow(dispatch: (action: Action) => void, group: Group,
+ state: Pick<AppState, "config" | "activeView" | "selectedId" | "forkPanel">, viewer: Viewer): void {
+ const feed = roomFeedShows(state.config, group);
+ const panel = state.forkPanel;
+ const available = (id: string) => group.tasks?.some((task) => task.threadId === id && task.archivedAt === undefined);
+ if (feed && state.activeView === "chat" && state.selectedId === group.id && panel?.kind === "group" && panel.ownerId === group.id && available(panel.threadId)) return;
+ dispatch({ type: "select", id: group.id });
+ const last = feed && lastRoomThread(viewer, group.id);
+ if (!last) return;
+ if (available(last)) dispatch(openFeedThread(group.id, last));
+ else if (group.tasks) rememberRoomThread(viewer, group.id, null);
+}