Skip to content

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

Room feed review: narrow windows, home gate, per-thread menu, no /fork in the feed, one batched read of old marks

milind-sonia84b7aaac34c
diff --git a/scripts/testing/room-feed-ui.e2e.test.ts b/scripts/testing/room-feed-ui.e2e.test.ts
index 91893409cb..631f2181b2 100644
--- a/scripts/testing/room-feed-ui.e2e.test.ts
+++ b/scripts/testing/room-feed-ui.e2e.test.ts
@@ -7,7 +7,7 @@
// Needs the pinned agent-browser binary: runs when one resolves (tools directory, OMB_AGENT_BROWSER_PATH or PATH) or
// OMB_UI_E2E=1 asks for the verified download; otherwise skipped.
import { spawn } from "node:child_process";
-import { existsSync, mkdtempSync, readFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -169,6 +169,65 @@ async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 3
await until(async () => !(await tasks()).some((task) => task.threadId === logos), "the open thread to be deleted");
await until(() => evaluate("!document.querySelector('[data-thread-panel]')"), "the panel to close");
+ // An Inbox line for a bot's own thread opens in the chat, as before the feed; only room threads use the side panel.
+ await api("POST", `/api/bots/${basil.id}/messages`, { text: "Check the invoices" });
+ await idle();
+ const inboxOpen = () => evaluate("Boolean(document.querySelector('[data-inbox-panel=\"side\"]'))");
+ const toggleInbox = () => evaluate("document.querySelector('[data-sidebar-inbox]').click(); true");
+ if (!(await inboxOpen())) await toggleInbox();
+ await until(() => evaluate("[...document.querySelectorAll('[data-inbox-panel] button[aria-label]')].some((b) => b.getAttribute('aria-label').includes('Basil'))"), "Basil's thread in the Inbox");
+ await evaluate("[...document.querySelectorAll('[data-inbox-panel] button[aria-label]')].find((b) => b.getAttribute('aria-label').includes('Basil')).click(); true");
+ await until(() => evaluate(`document.querySelector('[data-sidebar-bot-row="${basil.id}"]')?.getAttribute('aria-current') === 'page'`), "Basil's chat on screen");
+ expect(await evaluate("Boolean(document.querySelector('[data-thread-panel]'))")).toBe(false);
+ if (await inboxOpen()) await toggleInbox();
+
+ // A room thread sits beside the feed only while the feed keeps 420px; otherwise it takes the feed's place, with a way back.
+ const layouts: Array<Record<string, unknown>> = [];
+ for (const width of ["1100", "900", "800"]) {
+ for (const withInbox of [false, true]) {
+ await browse("set", "viewport", width, "900");
+ await evaluate(`document.querySelector('[data-sidebar-group-row="${room.id}"]')?.click(); true`);
+ await until(() => evaluate("document.querySelectorAll('[data-feed-thread]').length > 0"), `the feed at ${width}px`);
+ if (withInbox !== await inboxOpen()) await toggleInbox();
+ await evaluate("document.querySelector('[data-feed-thread] > button:first-child').click(); true");
+ await until(() => evaluate("Boolean(document.querySelector('[data-thread-panel]'))"), `the thread at ${width}px`);
+ const measure = () => evaluate(`(() => {
+ const feed = document.querySelector('[data-room-feed]'), panel = document.querySelector('[data-thread-panel]');
+ return { width: ${width}, withInbox: ${withInbox}, inboxAfter: Boolean(document.querySelector('[data-inbox-panel="side"]')),
+ inPlace: panel.hasAttribute('data-thread-in-place'), feed: feed ? Math.round(feed.getBoundingClientRect().width) : 0,
+ panel: Math.round(panel.getBoundingClientRect().width), back: Boolean(document.querySelector('[data-thread-back]')) };
+ })()`) as Promise<Record<string, unknown>>;
+ // The sidebar folds and the panel slides in first: read the layout once it holds still.
+ let layout = await measure();
+ for (let tries = 0; tries < 20; tries++) {
+ await new Promise((done) => setTimeout(done, 600));
+ const again = await measure();
+ if (JSON.stringify(again) === JSON.stringify(layout)) break;
+ layout = again;
+ }
+ layouts.push(layout);
+ if (layout.inPlace) {
+ expect(layout, JSON.stringify(layout)).toMatchObject({ feed: 0, back: true });
+ await ui("screenshot", "--out", join(evidenceDir, `room-feed-thread-in-place-${width}${withInbox ? "-inbox" : ""}.png`));
+ await evaluate("document.querySelector('[data-thread-back]').click(); true");
+ await until(() => evaluate("Boolean(document.querySelector('[data-room-feed]')) && !document.querySelector('[data-thread-panel]')"), "back to the feed");
+ } else {
+ expect(layout.feed as number, JSON.stringify(layout)).toBeGreaterThanOrEqual(420);
+ expect(layout.panel as number).toBeGreaterThanOrEqual(360);
+ await evaluate("document.querySelector('[data-thread-panel] header button[aria-label=\"Close thread\"]').click(); true");
+ await until(() => evaluate("!document.querySelector('[data-thread-panel]')"), "the thread to close");
+ }
+ }
+ }
+ writeFileSync(join(evidenceDir, "room-feed-layouts.json"), JSON.stringify(layouts, null, 1));
+ const at = (width: number, withInbox: boolean) => layouts.find((layout) => layout.width === width && layout.withInbox === withInbox);
+ // Opened with the Inbox open, where the Inbox is what leaves too little room, the Inbox closes and the thread sits beside.
+ expect(at(1100, true)).toMatchObject({ inPlace: false, inboxAfter: false });
+ // At 800px the feed and the thread never both fit: the thread takes the feed's place, and an open Inbox stays.
+ expect(at(800, false)).toMatchObject({ inPlace: true });
+ expect(at(800, true)).toMatchObject({ inPlace: true, inboxAfter: true });
+ if (await inboxOpen()) await toggleInbox();
+
await browse("set", "viewport", "700", "900");
await until(() => evaluate("!document.querySelector('[data-room-feed]') && Boolean(document.querySelector('[data-look=\"chat\"] [role=\"log\"]'))"), "the room's transcript below 768px");
const logs = await ui("console");
diff --git a/server/index.ts b/server/index.ts
index 1cc962e6cb..74ea97f43b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -651,7 +651,7 @@ const WEBHOOK_PORT = Number(process.env.OMB_WEBHOOK_PORT || PORT + 1);
const WEBHOOK_PUBLIC_URL = process.env.OMB_WEBHOOK_PUBLIC_URL || undefined;
const STATIC_DIR = process.env.OMB_STATIC_DIR || null;
-dataFormatAtStart("check", DATA_DIR, serverVersion()); ensureDirs();
+dataFormatAtStart("check", DATA_DIR, serverVersion()); ensureDirs(); roomFeedSince(DATA_DIR); // when this place first had the room feed, stamped at start
// Acquire before any durable identity, sessions, config or Store state is loaded.
const dataDirLease = acquireDataDirLeaseForProcess(DATA_DIR); void startEngineRecords(DATA_DIR); const cacheSweeper = createCacheSweepHost(DATA_DIR); // stops what an earlier server left; the cache cap (cache-sweep/), off unless OMB_CACHE_SWEEP
const releaseDataDirLeaseAtExit = releaseOnceAtExit(dataDirLease);
diff --git a/server/room-thread-summaries.e2e.test.ts b/server/room-thread-summaries.e2e.test.ts
index 6807bfe32b..4fb11dd2b5 100644
--- a/server/room-thread-summaries.e2e.test.ts
+++ b/server/room-thread-summaries.e2e.test.ts
@@ -86,6 +86,24 @@ describe("a room's thread summaries", () => {
expect(shown.find((row) => row.threadId === thread)?.first?.text).toBe("Old idea");
});
+ it("reads several of the room's threads for one person in one request", async () => {
+ const threads: string[] = [];
+ for (const text of ["First question", "Second question"]) {
+ const thread = (await as("bob", "POST", `/api/groups/${room}/tasks`, { activate: false })).body.task.threadId as string;
+ expect((await as("bob", "POST", `/api/groups/${room}/messages`, { text, threadId: thread })).status).toBeLessThan(300);
+ threads.push(thread);
+ }
+ const bobsTasks = async () => ((await as("bob", "GET", "/api/bots")).body.groups as Array<{ id: string; tasks: Array<{ threadId: string; unread?: boolean }> }>)
+ .find((group) => group.id === room)!.tasks.filter((task) => threads.includes(task.threadId));
+ await until(async () => (await bobsTasks()).filter((task) => task.unread).length === 2);
+ expect((await as("bob", "POST", `/api/groups/${room}/read`, { threadIds: [threads[0], 7] })).status).toBe(400);
+ expect((await as("eve", "POST", `/api/groups/${room}/read`, { threadIds: threads })).status).toBe(404);
+ const read = await as("bob", "POST", `/api/groups/${room}/read`, { threadIds: [...threads, "no-such-thread"] });
+ expect(read.status, JSON.stringify(read.body)).toBe(200);
+ expect(read.body.read).toBe(2);
+ expect((await bobsTasks()).map((task) => task.unread ?? false)).toEqual([false, false]);
+ });
+
it("answers someone who cannot see the room as if it did not exist", async () => {
expect((await as("eve", "GET", `/api/groups/${room}/threads/summary`)).status).toBe(404);
expect((await as("bob", "GET", "/api/groups/no-such-room/threads/summary")).status).toBe(404);
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index 99ad98cf86..01ab02a33a 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -120,6 +120,8 @@ export interface ChannelRouteDeps {
}
const createGroupTaskRequestSchema = z.object({ title: z.string().optional(), activate: z.boolean().optional() });
+/** The most threads one read request may name. */
+const MAX_READ_THREADS = 500;
type StopAnswer = { status: 200 | 403 | 409; body: { ok: true } | { error: string; code?: "stop_not_yours" } };
@@ -329,6 +331,25 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
const room = store.group(m[1]);
if (!room) return json(res, 404, { error: "no such room" });
const body = await readBody(req);
+ // Several of the room's threads in one request and one frame: the feed reads marks older than itself this way.
+ if (Array.isArray(body?.threadIds)) {
+ const asked: unknown[] = body.threadIds;
+ if (room.dm || asked.length > MAX_READ_THREADS || asked.some((id) => typeof id !== "string")) return json(res, 400, { error: "threadIds must be up to 500 of the room's threads" });
+ const threadIds = [...new Set(asked as string[])].filter((id) => store.groupTaskByThread(room.id, id));
+ let personal: WireGroup | null = null;
+ let shared: GroupRecord | null = null;
+ for (const id of threadIds) {
+ sawThread(id);
+ deps.threadRead?.(auth, id);
+ personal = deps.personMarkRoom?.(auth, room, false, id) ?? null;
+ if (!personal) shared = store.markGroupThreadUnread(room.id, id, false, readCursor(id).lastReadMessageId);
+ readThreadNotifications(id, broadcast, notificationListed(auth));
+ }
+ if (personal) return json(res, 200, { group: personal, read: threadIds.length });
+ const group = shared ?? store.group(room.id)!;
+ if (shared) broadcast({ kind: "group", group: publicGroupState(group) });
+ return json(res, 200, { group: own(publicGroupState(group)), read: threadIds.length });
+ }
const threadId = body?.threadId ?? room.threadId;
if (typeof threadId !== "string" || (room.dm
? threadId !== room.threadId
diff --git a/src/App.tsx b/src/App.tsx
index bd8a45f0aa..f09cdafaa0 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -25,6 +25,7 @@ import { GroupView } from "@/components/GroupView";
import { ForkPanel } from "@/components/ForkPanel";
import { RoomFeedView } from "@/components/room-feed/RoomFeedView";
import { useRoomFeed } from "@/components/room-feed/use-room-feed";
+import { useFeedThreadFull } from "@/components/room-feed/feed-fit";
import { PHONE_LAYOUT, SIDEBAR_AND_BOT_PANEL_FIT, SIDEBAR_AND_NARROW_PANEL_FIT, SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";
import { anySidePanel, botPanelFloats, panelsMovingSidebar, sidebarFoldsForPanel, type OpenSidePanels } from "@/lib/sidebar-fold";
import { preloadConnectedApps } from "@/lib/connected-apps";
@@ -190,6 +191,8 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
const closeDrawer = useCallback(() => { hideDrawer(); menuButtonRef.current?.focus(); }, [hideDrawer]);
const notificationFeed = useNotificationFeed() && !remoteClient;
const advanced = useAdvancedMode(), skillBurger = useFeature("skillBurger"), roomFeed = useRoomFeed(group);
+ // A thread opened from a room's feed sits beside it while both fit, and takes the feed's place when they don't.
+ const feedThreadFull = useFeedThreadFull(group && roomFeed && sidebarInline && state.forkPanel?.kind === "group" && state.forkPanel.ownerId === group.id ? state.forkPanel.threadId : null);
const roomPanelOpen = useRoomPanelShown({ group, state, simple: !advanced && !remoteClient });
const sidePanels: OpenSidePanels = {
simple: !advanced, remoteClient, bot: Boolean(bot) && state.settingsOpen, room: roomPanelOpen, inbox: inboxShown, inboxWide: inboxPanel.wide === true,
@@ -466,7 +469,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
) : chiefStep ? (
<EmptyChatShell />
) : group && roomFeed ? (
- <RoomFeedView key={group.id} group={group} />
+ feedThreadFull ? <ForkPanel full /> : <RoomFeedView key={group.id} group={group} />
) : group ? (
<GroupView key={group.id} group={group} />
) : bot ? (
@@ -505,7 +508,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
)}
<AppPreviewPanel />
<FilePreviewPanel threadId={group?.threadId ?? bot?.threadId} />
- {state.forkPanel && sidebarInline && <ForkPanel />}
+ {state.forkPanel && sidebarInline && !feedThreadFull && <ForkPanel />}
{!state.forkPanel && roomPanelOpen && group && (
<RoomPanel key={`room:${group.id}`} group={group} overlay={notificationFeed && state.notificationsOpen && !twoSidePanelsFit} />
)}
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index 27ae7d0a24..0e1244fc86 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -68,7 +68,7 @@ import {
type PasteAttachment,
} from "@/lib/composer-attachments";
import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRouteForComposer } from "@/lib/group-routing";
-import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton"; import { ComposerContextMenu } from "./ComposerContextMenu";
+import { composerForkOwner, composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton"; import { ComposerContextMenu } from "./ComposerContextMenu";
import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "./PendingApproval";
import { CallButton } from "./CallView";
import { GroupCallButton } from "./GroupCallView";
@@ -178,7 +178,7 @@ export function Composer({
draftId,
!group && bot && !state.config?.team ? `bot:${bot.id}` : undefined,
);
- const forkOwnerId = singleRow || group?.dm || !threadId ? undefined : group?.id ?? bot?.id;
+ const forkOwnerId = composerForkOwner({ phone: singleRow, group, botId: bot?.id, threadId, startsThread: Boolean(onSendGroup) });
const attachmentPending = useDraftAttachmentPending(draftId);
const failedSends = useFailedComposerSends(draftId); const picks = mentionPicksFor(draftId);
const [channelMode, setChannelMode] = useComposerChannelMode(draftId);
diff --git a/src/components/ForkPanel.tsx b/src/components/ForkPanel.tsx
index b6afe0ba0c..13a1abbf72 100644
--- a/src/components/ForkPanel.tsx
+++ b/src/components/ForkPanel.tsx
@@ -1,4 +1,4 @@
-import { X } from "lucide-react";
+import { ArrowLeft, X } from "lucide-react";
import { useLayoutEffect, useRef } from "react";
import { cn } from "@/lib/cn";
import { useInboxPanel } from "@/state/inbox";
@@ -9,18 +9,21 @@ import { GroupView } from "./GroupView";
import { ThreadPanelHeading } from "./room-feed/ThreadPanelHeading";
import { useRoomFeedHere } from "./room-feed/use-room-feed";
import { useThreadTurnStart } from "./room-feed/thread-turn-start";
+import { FEED_MIN_WIDTH } from "./room-feed/feed-fit";
import { PANEL_MIN_WIDTH, useComputerPanelResize } from "./computer-panel-resize";
const BESIDE_INBOX_MAX = 400;
-/** Any thread beside the chat: a fork, and where the server has the room feed, the thread a feed row or the Inbox opened. */
-export function ForkPanel() {
+/** Any thread beside the chat: a fork, and where the server has the room feed, the room thread a feed row or the Inbox
+ * opened. `full`: that room thread takes the feed's place, because the two don't fit side by side; its back button
+ * returns to the feed. */
+export function ForkPanel({ full = false }: { full?: boolean }) {
const { state, dispatch } = useStore();
const panel = state.forkPanel;
const asideRef = useRef<HTMLElement>(null);
const focusedLoad = useRef<string | undefined>(undefined);
const beside = useRoomFeedHere();
- const resize = useComputerPanelResize({ key: "omb-thread-panel-width", defaultWidth: 440 });
+ const resize = useComputerPanelResize({ key: "omb-thread-panel-width", defaultWidth: 440, chatMin: panel?.kind === "group" ? FEED_MIN_WIDTH : undefined });
// Beside the Inbox the chat keeps the 440 it has beside any other side panel.
const width = useInboxPanel().open ? Math.min(resize.panelWidth, BESIDE_INBOX_MAX) : resize.panelWidth;
useLayoutEffect(() => {
@@ -45,14 +48,17 @@ export function ForkPanel() {
const fork = !beside || Boolean(task?.origin);
const label = fork ? t("chat.forkPanel") : t("room.thread.panel");
const close = () => dispatch({ type: "closeForkPanel" });
+ const roomThread = beside && !fork && Boolean(group);
+ const inPlace = full && roomThread;
return (
<aside ref={asideRef} tabIndex={panel.focusComposer ? -1 : undefined} aria-label={label} data-thread-panel={panel.threadId}
- style={beside ? { width, ["--side-panel-w" as string]: `${width}px` } : undefined}
- className={cn("relative flex h-full flex-col bg-app", beside
+ data-feed-area={roomThread ? "" : undefined} data-thread-in-place={inPlace ? "" : undefined}
+ style={beside && !inPlace ? { width, ["--side-panel-w" as string]: `${width}px` } : undefined}
+ className={cn("relative flex h-full flex-col bg-app", inPlace ? "min-w-0 flex-1" : beside
? "shrink-0 border-s-[0.5px] border-edge md:animate-panel-beside-in motion-reduce:animate-none"
: "w-[min(48vw,640px)] min-w-[360px] border-s border-hairline")}>
- {beside && <div
+ {beside && !inPlace && <div
ref={resize.separatorRef}
role="separator"
aria-orientation="vertical"
@@ -70,12 +76,14 @@ export function ForkPanel() {
/>}
{beside ? (
<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">
<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>}
- <button type="button" aria-label={fork ? t("chat.closeForkPanel") : t("room.thread.close")} title={fork ? t("chat.closeForkPanel") : t("room.thread.close")}
- className="ui-icon-button shrink-0" onClick={close}><X size={16} aria-hidden="true" /></button>
+ {!inPlace && <button type="button" aria-label={fork ? t("chat.closeForkPanel") : t("room.thread.close")} title={fork ? t("chat.closeForkPanel") : t("room.thread.close")}
+ className="ui-icon-button shrink-0" onClick={close}><X size={16} aria-hidden="true" /></button>}
</header>
) : (
<div className="flex items-center justify-between border-b border-hairline px-4 py-2 text-sm font-medium text-ink">
diff --git a/src/components/RoomMoreMenu.test.ts b/src/components/RoomMoreMenu.test.ts
index 18ce897f79..cbffdd1940 100644
--- a/src/components/RoomMoreMenu.test.ts
+++ b/src/components/RoomMoreMenu.test.ts
@@ -9,6 +9,7 @@ const fixture = vi.hoisted(() => {
return {
threadsShown: false,
findOpen: false,
+ feed: false,
menus: [] as { ariaLabel: string; items: SidebarMenuItem[]; trigger: string }[],
dispatch: vi.fn(),
find: vi.fn(),
@@ -25,6 +26,7 @@ vi.mock("@/state/store", async (importOriginal) => {
};
});
vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.threadsShown }));
+vi.mock("./room-feed/use-room-feed", () => ({ useRoomFeed: () => fixture.feed }));
vi.mock("@/lib/chat-find", () => ({ requestChatFind: fixture.find, useChatFindOpen: () => fixture.findOpen }));
vi.mock("@/lib/export-transcript", () => ({
copyTranscriptToClipboard: fixture.copy,
@@ -62,6 +64,7 @@ const item = (group: Group, key: string) => menuOf(group).items.find((entry) =>
beforeEach(() => {
fixture.threadsShown = false;
fixture.findOpen = false;
+ fixture.feed = false;
fixture.dispatch.mockClear();
fixture.find.mockClear();
fixture.copy.mockClear();
@@ -89,6 +92,14 @@ describe("RoomMoreMenu, the Room panel's round ⋯", () => {
expect(menuOf(room()).items.find((entry) => entry.key === "copy")).toMatchObject({ label: "Copy as Markdown", heading: "Share", separatorBefore: true });
});
+ it("with the room as its feed, leaves what acts on one thread to that thread's own menu beside the feed", () => {
+ fixture.feed = true;
+ fixture.findOpen = true;
+ const used = room({ usage: { input: 1200, output: 300, costUsd: 0.42, turns: 2 } });
+ expect(menuOf(used).items.map((entry) => entry.key)).toEqual(["new-thread", "threads", "usage"]);
+ expect(menuOf(used).trigger).not.toContain("text-accent");
+ });
+
it("opens the room's find bar for the thread on screen", () => {
item(room(), "find").onSelect();
expect(fixture.find).toHaveBeenCalledWith("launch");
diff --git a/src/components/RoomMoreMenu.tsx b/src/components/RoomMoreMenu.tsx
index 38fa6cd938..7faa7a58a7 100644
--- a/src/components/RoomMoreMenu.tsx
+++ b/src/components/RoomMoreMenu.tsx
@@ -18,6 +18,11 @@ import { groupUsageSummary } from "./GroupUsageChip";
import { ShortcutHint } from "./ShortcutHint";
import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";
import { orderedThreadList } from "./SidebarThreadRow";
+import { useRoomFeed } from "./room-feed/use-room-feed";
+
+/** What acts on the room's current thread. With the feed that thread is one row among many, so these live in the menu
+ * of the thread open beside the feed instead. */
+const THREAD_ITEMS = new Set(["find", "copy", "download", "turn-limit"]);
function turnLimitLabel(minutes: number): string {
if (minutes === 60) return t("room.panel.hour");
@@ -36,6 +41,7 @@ function useRoomMoreItems(group: Group): { items: SidebarMenuItem[]; on: boolean
const transcript = () => conversationTranscript({ threadId: group.threadId, hasMore: group.hasMore, title: group.name, messages, isGroup: true });
const threads = showThreads ? [] : orderedThreadList(group.tasks ?? []);
const usage = groupUsageSummary(group.usage);
+ const feed = useRoomFeed(group);
const items: SidebarMenuItem[] = [
{
key: "find",
@@ -120,7 +126,7 @@ function useRoomMoreItems(group: Group): { items: SidebarMenuItem[]; on: boolean
onSelect: () => {},
} satisfies SidebarMenuItem] : []),
];
- return { items, on: findOpen };
+ return { items: feed ? items.filter((item) => !THREAD_ITEMS.has(item.key)) : items, on: findOpen && !feed };
}
function RoundRoomMoreMenu({ group }: { group: Group }) {
diff --git a/src/components/Sidebar.plus-menu.test.ts b/src/components/Sidebar.plus-menu.test.ts
index 65955b64c7..bc4d2fc0dd 100644
--- a/src/components/Sidebar.plus-menu.test.ts
+++ b/src/components/Sidebar.plus-menu.test.ts
@@ -135,6 +135,19 @@ describe("the sidebar's + menu with a room open", () => {
expect(fixture.dispatch.mock.calls).toEqual([[{ type: "newGroupTask", groupId: "room" }]]);
});
+ it("can't start one while the room is busy where it shows its single transcript, which a new thread would move", () => {
+ const busy = { ...room, busyBotId: "kiwi", working: true };
+ const item = (config: unknown) => openPlusMenu(true, false, { groups: [busy], selectedId: "room", activeView: "chat", config })
+ .find((node) => node.props["data-plus-room-thread"] === "room")!;
+ expect(item({ features: {} }).props.disabled).toBe(true);
+ vi.stubGlobal("matchMedia", () => ({ matches: true, addEventListener() {}, removeEventListener() {} }));
+ try {
+ expect(item({ features: { roomFeed: true, roomFeedSince: 1 } }).props.disabled).toBe(false);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
it("offers none for a bot-to-bot room", () => {
expect(withRoom({ dm: true }).filter((node) => node.props.role === "menuitem").map((node) => words(node.props.children))).not.toContain("New thread in Launch room");
});
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index bdf3e78e44..adf27ba859 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -98,7 +98,7 @@ import { useLiveMedia } from "@/lib/live-call-media";
import { LiveCallPill, liveBadgeFor } from "./LiveCallPill";
import { ShortcutHint } from "./ShortcutHint";
import { usePopoverDismiss } from "@/hooks/use-popover-dismiss";
-import { useAdvancedMode } from "@/lib/interface-mode"; import { useRoomFeed } from "./room-feed/use-room-feed"; import { feedPreview } from "@/lib/room-feed";
+import { useAdvancedMode } from "@/lib/interface-mode"; import { useRoomFeed } from "./room-feed/use-room-feed"; import { feedPreview, roomFeedShows } from "@/lib/room-feed";
import { myDefaultBot, useViewerEmail, useWelcomingBot } from "@/lib/default-bot";
import { PinnedBotRoster, PinnedCircleThreadSection } from "./PinnedCircleThreads";
import { archiveBotWithNotice, onArchiveNotice } from "./bot-archive";
@@ -1128,7 +1128,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
setSearchOpen(true);
toggleCollapsed();
};
- const plusItem = cn(MENU_ITEM, "text-ink hover:bg-menu-hover"), plusBot = state.activeView === "chat" ? state.bots.find((candidate) => candidate.id === state.selectedId) : undefined, plusRoom = state.activeView === "chat" ? state.groups.find((candidate) => candidate.id === state.selectedId && !candidate.dm) : undefined, newBotHere = useNewBotHereLabel();
+ const plusItem = cn(MENU_ITEM, "text-ink hover:bg-menu-hover"), plusBot = state.activeView === "chat" ? state.bots.find((candidate) => candidate.id === state.selectedId) : undefined, plusRoom = state.activeView === "chat" ? state.groups.find((candidate) => candidate.id === state.selectedId && !candidate.dm) : undefined, plusRoomBusy = Boolean(plusRoom && !roomFeedShows(state.config, plusRoom) && (plusRoom.busyBotId || plusRoom.working)), newBotHere = useNewBotHereLabel();
const plusControl = (
<div ref={plusMenuRef} className="contents">
<button
@@ -1161,7 +1161,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
<MessageSquarePlus size={16} className="text-ink-secondary" />
{t("sidebar.newChat.title")}
</button>}
- {!advanced && plusBot && <><button role="menuitem" className={plusItem} onClick={() => { setPlusOpen(false); dispatch({ type: "newTask", botId: plusBot.id }); }}><SquarePen size={16} className="shrink-0 text-ink-secondary" /><span className="min-w-0 truncate" title={plusBot.name}>{t("sidebar.newConversationWith", { name: plusBot.name })}</span></button><div role="separator" className={MENU_ITEM_SEPARATOR} /></>}{plusRoom && <><button role="menuitem" data-plus-room-thread={plusRoom.id} className={plusItem} onClick={() => { setPlusOpen(false); dispatch({ type: "newGroupTask", groupId: plusRoom.id }); }}><SquarePen size={16} className="shrink-0 text-ink-secondary" /><span className="min-w-0 truncate" title={plusRoom.name}>{t("sidebar.newThreadIn", { name: plusRoom.name })}</span></button><div role="separator" className={MENU_ITEM_SEPARATOR} /></>}
+ {!advanced && plusBot && <><button role="menuitem" className={plusItem} onClick={() => { setPlusOpen(false); dispatch({ type: "newTask", botId: plusBot.id }); }}><SquarePen size={16} className="shrink-0 text-ink-secondary" /><span className="min-w-0 truncate" title={plusBot.name}>{t("sidebar.newConversationWith", { name: plusBot.name })}</span></button><div role="separator" className={MENU_ITEM_SEPARATOR} /></>}{plusRoom && <><button role="menuitem" data-plus-room-thread={plusRoom.id} disabled={plusRoomBusy} title={plusRoomBusy ? t("task.newBusy") : undefined} className={cn(plusItem, "disabled:opacity-40")} onClick={() => { setPlusOpen(false); dispatch({ type: "newGroupTask", groupId: plusRoom.id }); }}><SquarePen size={16} className="shrink-0 text-ink-secondary" /><span className="min-w-0 truncate" title={plusRoom.name}>{t("sidebar.newThreadIn", { name: plusRoom.name })}</span></button><div role="separator" className={MENU_ITEM_SEPARATOR} /></>}
{(teamSettingsAllowed !== false || state.config?.team) && <button
onClick={() => { setPlusOpen(false); dispatch({ type: "newBot" }); }}
role="menuitem"
diff --git a/src/components/composer-fork-owner.test.ts b/src/components/composer-fork-owner.test.ts
new file mode 100644
index 0000000000..2af72f8afe
--- /dev/null
+++ b/src/components/composer-fork-owner.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vitest";
+import { composerForkOwner } from "./composer-simple";
+
+describe("/fork in the composer", () => {
+ it("forks the open bot's or room's thread", () => {
+ expect(composerForkOwner({ phone: false, botId: "kiwi", threadId: "t", startsThread: false })).toBe("kiwi");
+ expect(composerForkOwner({ phone: false, group: { id: "room" }, threadId: "t", startsThread: false })).toBe("room");
+ });
+
+ it("is not offered in a room feed's composer, whose line starts a thread that doesn't exist yet", () => {
+ expect(composerForkOwner({ phone: false, group: { id: "room" }, threadId: "feed-room", startsThread: true })).toBeUndefined();
+ });
+
+ it("is not offered on a phone, in a bot-to-bot room or with no thread", () => {
+ expect(composerForkOwner({ phone: true, botId: "kiwi", threadId: "t", startsThread: false })).toBeUndefined();
+ expect(composerForkOwner({ phone: false, group: { id: "dm", dm: true }, threadId: "t", startsThread: false })).toBeUndefined();
+ expect(composerForkOwner({ phone: false, botId: "kiwi", startsThread: false })).toBeUndefined();
+ });
+});
diff --git a/src/components/composer-simple.ts b/src/components/composer-simple.ts
index 7e39a12daf..9dbe6b9cd6 100644
--- a/src/components/composer-simple.ts
+++ b/src/components/composer-simple.ts
@@ -88,3 +88,11 @@ export function sendLabels({ simple, busy, canSteer, name, sendLabel }: { simple
}
return { label: t("composer.send.message"), title: `${t("chat.send")} (${sendLabel})` };
}
+
+/** Whose thread /fork copies from this composer, or none where it isn't offered: on a phone, in a bot-to-bot room, with
+ * no thread yet, and in a room feed's composer, whose line starts a thread that doesn't exist yet. */
+export function composerForkOwner({ phone, group, botId, threadId, startsThread }: {
+ phone: boolean; group?: { id: string; dm?: boolean }; botId?: string; threadId?: string; startsThread: boolean;
+}): string | undefined {
+ return phone || group?.dm || !threadId || startsThread ? undefined : group?.id ?? botId;
+}
diff --git a/src/components/computer-panel-resize.ts b/src/components/computer-panel-resize.ts
index 36183a7103..623f75a350 100644
--- a/src/components/computer-panel-resize.ts
+++ b/src/components/computer-panel-resize.ts
@@ -20,15 +20,17 @@ function readPanelWidth(key: string, fallback: number): number {
/** The panel and the chat beside it share the room in the window's row, so the
* panel can take everything but the chat's minimum width. */
-function measureMaxWidth(panel: HTMLElement, chat: HTMLElement | null): number {
+function measureMaxWidth(panel: HTMLElement, chat: HTMLElement | null, chatMin = CHAT_MIN_WIDTH): number {
if (!chat) return PANEL_MAX_WIDTH;
- return Math.max(PANEL_MIN_WIDTH, panel.offsetWidth + chat.offsetWidth - CHAT_MIN_WIDTH);
+ return Math.max(PANEL_MIN_WIDTH, panel.offsetWidth + chat.offsetWidth - chatMin);
}
/** The computer panel's drag edge: a pointer drag or the arrow keys resize the
* panel up to the room the chat leaves, and the width is remembered across opens
- * (under `key`, for a panel that keeps its own). */
-export function useComputerPanelResize({ key = PANEL_WIDTH_KEY, defaultWidth = PANEL_DEFAULT_WIDTH }: { key?: string; defaultWidth?: number } = {}) {
+ * (under `key`, for a panel that keeps its own). `chatMin` is what the chat beside it keeps at least. */
+export function useComputerPanelResize({ key = PANEL_WIDTH_KEY, defaultWidth = PANEL_DEFAULT_WIDTH, chatMin = CHAT_MIN_WIDTH }: { key?: string; defaultWidth?: number; chatMin?: number } = {}) {
+ const chatMinRef = useRef(chatMin);
+ chatMinRef.current = chatMin;
const [chosenWidth, setChosenWidth] = useState(() => readPanelWidth(key, defaultWidth));
const [maxWidth, setMaxWidth] = useState(PANEL_MAX_WIDTH);
const panelWidth = Math.min(chosenWidth, maxWidth);
@@ -74,7 +76,7 @@ export function useComputerPanelResize({ key = PANEL_WIDTH_KEY, defaultWidth = P
chat = current;
}
setSeparatorWidth(panel.offsetWidth);
- if (panel.offsetWidth > 0) setMaxWidth(measureMaxWidth(panel, chat));
+ if (panel.offsetWidth > 0) setMaxWidth(measureMaxWidth(panel, chat, chatMinRef.current));
};
const resizes = new ResizeObserver(read);
resizes.observe(panel);
diff --git a/src/components/inbox/use-inbox-actions.ts b/src/components/inbox/use-inbox-actions.ts
index 70dc1375ef..14419b79e4 100644
--- a/src/components/inbox/use-inbox-actions.ts
+++ b/src/components/inbox/use-inbox-actions.ts
@@ -48,7 +48,7 @@ export function useInboxActions(view: InboxView | null) {
return { run, answer, openInChat };
}
-/** A conversation listed in the Inbox opens beside the chat where the server has the room feed, and in the chat otherwise. */
+/** A room thread listed in the Inbox opens with its room's feed where the room shows as one; anything else opens in the chat. */
export function useInboxJump() {
const store = useStoreRef(), dispatch = store.dispatch;
const phone = useMediaQuery(PHONE_LAYOUT);
diff --git a/src/components/room-feed/RoomFeedView.tsx b/src/components/room-feed/RoomFeedView.tsx
index 1603f8364d..b9e0a8e338 100644
--- a/src/components/room-feed/RoomFeedView.tsx
+++ b/src/components/room-feed/RoomFeedView.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useAdvancedMode } from "@/lib/interface-mode";
import { t } from "@/lib/i18n";
-import { firstFeedCatchUp, openFeedThread, readStaleUnread, staleUnreadThreads } from "@/lib/room-feed";
+import { catchUpOldMarks, openFeedThread } from "@/lib/room-feed";
import { simpleRoomHeader } from "@/lib/room-panel";
import { roomThreadAttention, roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
import { useComposerDockPad } from "@/lib/composer-dock";
@@ -88,9 +88,8 @@ export function RoomFeedView({ group }: { group: Group }) {
// Unread marks older than the feed are read once, the first time the room shows as its feed on this device.
const since = useStoreSelector((state) => state.config?.features?.roomFeedSince);
useEffect(() => {
- if (typeof since !== "number" || !firstFeedCatchUp(group.id)) return;
- const stale = staleUnreadThreads(store.state().groups.find((candidate) => candidate.id === group.id) ?? group, since);
- if (stale.length > 0) void readStaleUnread(group.id, stale, (patched) => dispatch({ type: "groupPatched", group: patched })).catch(() => {});
+ void catchUpOldMarks(store.state().groups.find((candidate) => candidate.id === group.id) ?? group, since,
+ (patched) => dispatch({ type: "groupPatched", group: patched }));
// Once per room shown, not on every change of its threads.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [group.id, since]);
@@ -129,7 +128,7 @@ export function RoomFeedView({ group }: { group: Group }) {
}, [group.id]);
return (
- <main data-look="chat" data-room-feed={group.id} className="relative flex h-full min-w-0 flex-1 flex-col bg-app">
+ <main data-look="chat" data-room-feed={group.id} data-feed-area="" className="relative flex h-full min-w-0 flex-1 flex-col bg-app">
<ChatBackdrop />
{membersOpen && !remoteClient && <ManageMembersPanel group={group} onClose={closeMembers} triggerRef={membersTriggerRef} />}
<GlassScrollFrame className="flex-1 [--glass-tint:var(--color-app)]">
diff --git a/src/components/room-feed/ThreadPanelHeading.dom.test.ts b/src/components/room-feed/ThreadPanelHeading.dom.test.ts
new file mode 100644
index 0000000000..72f125a12f
--- /dev/null
+++ b/src/components/room-feed/ThreadPanelHeading.dom.test.ts
@@ -0,0 +1,45 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Group, GroupTask } from "@/state/store";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const fixture = vi.hoisted(() => ({ dispatch: vi.fn(), find: vi.fn() }));
+vi.mock("@/state/api", async (original) => ({ ...(await original<typeof import("@/state/api")>()), api: vi.fn(() => new Promise(() => {})) }));
+vi.mock("@/lib/chat-find", async (original) => ({ ...(await original<typeof import("@/lib/chat-find")>()), requestChatFind: fixture.find }));
+vi.mock("@/state/store", async (original) => {
+ const real = await original<typeof import("@/state/store")>();
+ return { ...real, useStore: () => ({ state: { ...real.initialState, config: { rooms: { turnTimeoutMinutes: 5 } } }, dispatch: fixture.dispatch }) };
+});
+vi.mock("@/state/store-ref", () => ({ useStoreRef: () => ({ dispatch: fixture.dispatch, state: () => ({}) }) }));
+
+const { ThreadPanelHeading } = await import("./ThreadPanelHeading");
+
+const task: GroupTask = { threadId: "side", title: "Logo files", createdAt: 2, turnTimeoutMinutes: 60 };
+const group = { id: "room", name: "Launch room", threadId: "current", memberIds: [], messages: [], bulletin: "", unread: false, createdAt: 1,
+ defaultResponder: { kind: "auto" }, tasks: [{ threadId: "current", title: "", createdAt: 1 }, task] } as unknown as Group;
+
+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(() => document.querySelector<HTMLButtonElement>("button[aria-expanded]")!.click());
+};
+const menuItem = (label: string) => [...document.querySelectorAll<HTMLButtonElement>("[data-thread-overlay] button")].find((button) => button.textContent?.trim() === label);
+
+describe("the menu of a room thread beside its feed", () => {
+ it("finds in that thread, not the room's current one", () => {
+ open();
+ act(() => menuItem("Find in conversation")!.click());
+ expect(fixture.find).toHaveBeenCalledWith("side");
+ });
+
+ it("sets that thread's time per turn, showing the one it has", () => {
+ open();
+ expect(menuItem("60 minutes")!.getAttribute("aria-pressed")).toBe("true");
+ act(() => menuItem("120 minutes")!.click());
+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "setConversationTurnLimit", groupId: "room", threadId: "side", minutes: 120, dm: false });
+ });
+});
diff --git a/src/components/room-feed/ThreadPanelHeading.tsx b/src/components/room-feed/ThreadPanelHeading.tsx
index 87b06de057..4c08105a8a 100644
--- a/src/components/room-feed/ThreadPanelHeading.tsx
+++ b/src/components/room-feed/ThreadPanelHeading.tsx
@@ -1,19 +1,22 @@
import { useMemo, useRef, useState } from "react";
-import { Copy, Download, MoreHorizontal } from "lucide-react";
+import { Check, Copy, Download, MoreHorizontal, Search, Timer } from "lucide-react";
+import { requestChatFind } from "@/lib/chat-find";
import { copyTranscriptToClipboard, downloadMarkdownTranscript, formatTranscriptMarkdown, slugifyTranscriptFilename } from "@/lib/export-transcript";
import { t } from "@/lib/i18n";
import { localizedTaskTitle } from "@/lib/task-title";
import type { Group, GroupTask, Message } from "@/state/store";
import { useStoreRef } from "@/state/store-ref";
+import { PRESET_TURN_LIMITS, useConversationTurnLimit } from "../ConversationTurnLimit";
import { roomThreadRowActions } from "../SidebarGroupThreadList";
import { THREAD_MENU_WIDTH, threadMenuAt, useThreadRowMenu, type ThreadMenuAt } from "../SidebarThreadRow";
import { ThreadRenameField } from "./ThreadRenameField";
const ITEM = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-ink hover:bg-menu-hover disabled:opacity-40";
-/** The title of a room thread open beside its feed, and its menu: what the feed row's menu offers, and the thread's
- * export, since its lines are loaded here. */
-export function ThreadPanelHeading({ group, task, messages, working }: { group: Pick<Group, "id" | "name" | "tasks">; task: GroupTask; messages: readonly Message[]; working: boolean }) {
+/** 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 }) {
const store = useStoreRef();
const dispatch = store.dispatch;
const [menu, setMenu] = useState<ThreadMenuAt | null>(null);
@@ -25,6 +28,12 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
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 }> = [
+ { key: "default", minutes: null, label: t("room.turnLimit.default", { minutes: limit.globalMinutes }) },
+ ...PRESET_TURN_LIMITS.map((minutes) => ({ key: String(minutes), minutes, label: t("room.turnLimit.minutes", { minutes }) })),
+ ...(limit.saved !== null && !(PRESET_TURN_LIMITS as readonly number[]).includes(limit.saved) ? [{ key: "custom", minutes: limit.saved, label: t("room.turnLimit.minutes", { minutes: limit.saved }) }] : []),
+ ];
const menuSheet = useThreadRowMenu({
task: row, displayTitle: title, ownerId: group.id, menu, setMenu, actionRef: moreRef,
onStartRename: () => { setMenu(null); setRenaming(true); },
@@ -33,6 +42,9 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
onArchive: (thread, archivedAt) => { if (archivedAt !== null) close(); 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); }}>
+ <Search size={16} aria-hidden="true" />{t("chat.find")}
+ </button>
<button type="button" disabled={messages.length === 0} className={ITEM} onClick={() => { done(); void copyTranscriptToClipboard(markdown()); }}>
<Copy size={16} aria-hidden="true" />{t("chat.export.copy")}
</button>
@@ -40,6 +52,16 @@ export function ThreadPanelHeading({ group, task, messages, working }: { group:
onClick={() => { done(); downloadMarkdownTranscript(slugifyTranscriptFilename(task.title || group.name), markdown()); }}>
<Download size={16} aria-hidden="true" />{t("chat.export.download")}
</button>
+ <div data-thread-turn-limit="" className="px-2 pt-1">
+ <span className="flex items-center gap-2 text-[12px] font-medium text-ink-secondary"><Timer size={16} aria-hidden="true" />{t("room.panel.turnLimit")}</span>
+ <div className="mt-0.5 flex flex-col">
+ {limits.map((option) => (
+ <button key={option.key} type="button" aria-pressed={limit.saved === option.minutes} className={ITEM} onClick={() => { done(); limit.save(option.minutes); }}>
+ <Check size={14} aria-hidden="true" className={limit.saved === option.minutes ? "" : "invisible"} />{option.label}
+ </button>
+ ))}
+ </div>
+ </div>
</>,
});
return <>
diff --git a/src/components/room-feed/feed-fit.test.ts b/src/components/room-feed/feed-fit.test.ts
new file mode 100644
index 0000000000..074a5cf521
--- /dev/null
+++ b/src/components/room-feed/feed-fit.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+import { feedThreadFits, feedThreadPlace } from "./feed-fit";
+
+describe("a thread opened from a room's feed", () => {
+ it("sits beside the feed only when the feed keeps 420px beside a 360px thread", () => {
+ expect(feedThreadFits(780)).toBe(true);
+ expect(feedThreadFits(779)).toBe(false);
+ });
+
+ it("takes the feed's place when the two don't fit, closing the Inbox instead when it is what leaves too little room", () => {
+ // 1100px window: 280px sidebar, 320px Inbox, 500px for the feed and the thread.
+ expect(feedThreadPlace(500, { inboxBeforeThread: true, inboxWidth: 320 })).toBe("close-inbox");
+ // The Inbox opened later, with the thread already open: the thread takes the feed's place and the Inbox stays.
+ expect(feedThreadPlace(500, { inboxBeforeThread: false, inboxWidth: 320 })).toBe("full");
+ // 900px window, 72px icon rail and the Inbox: 508px, 828px without the Inbox.
+ expect(feedThreadPlace(508, { inboxBeforeThread: true, inboxWidth: 320 })).toBe("close-inbox");
+ // 800px window, rail and Inbox: 408px, and 728px without the Inbox still isn't enough, so the Inbox stays.
+ expect(feedThreadPlace(408, { inboxBeforeThread: true, inboxWidth: 320 })).toBe("full");
+ expect(feedThreadPlace(728, { inboxBeforeThread: true, inboxWidth: 0 })).toBe("full");
+ expect(feedThreadPlace(1160, { inboxBeforeThread: true, inboxWidth: 0 })).toBe("beside");
+ });
+});
diff --git a/src/components/room-feed/feed-fit.ts b/src/components/room-feed/feed-fit.ts
new file mode 100644
index 0000000000..5e551c2bf3
--- /dev/null
+++ b/src/components/room-feed/feed-fit.ts
@@ -0,0 +1,57 @@
+import { useLayoutEffect, useRef, useState } from "react";
+import { closeInbox } from "@/state/inbox";
+import { PANEL_MIN_WIDTH } from "../computer-panel-resize";
+
+/** The narrowest a room's feed gets beside the thread open next to it. */
+export const FEED_MIN_WIDTH = 420;
+
+/** Whether a room's feed and the thread open beside it both fit in the width they share. */
+export function feedThreadFits(available: number): boolean {
+ return available >= FEED_MIN_WIDTH + PANEL_MIN_WIDTH;
+}
+
+/** What a thread opened from a room's feed does in the width it has: beside the feed when both fit; otherwise it takes
+ * the feed's place, with a way back to the feed. When the thread was opened with the Inbox already open and the Inbox
+ * is what leaves too little room, the Inbox closes instead; an Inbox opened later, beside the thread, stays. */
+export function feedThreadPlace(available: number, { inboxBeforeThread, inboxWidth }: { inboxBeforeThread: boolean; inboxWidth: number }): "beside" | "full" | "close-inbox" {
+ if (feedThreadFits(available)) return "beside";
+ return inboxBeforeThread && inboxWidth > 0 && feedThreadFits(available + inboxWidth) ? "close-inbox" : "full";
+}
+
+const width = (element: Element) => element.getBoundingClientRect().width;
+/** Widths move while the sidebar folds and the panel slides in; the Inbox is only closed once they have held still. */
+const SETTLE_MS = 300;
+
+/** True while the room thread open beside a feed (`threadId`) has to take the feed's place. It measures the elements
+ * marked `data-feed-area` (the feed's main area and the thread's panel, or the thread alone in the feed's place),
+ * whose widths add up to the same row space either way, so the choice never flips back and forth. */
+export function useFeedThreadFull(threadId: string | null): boolean {
+ const [full, setFull] = useState(false);
+ const opened = useRef<string | null>(null);
+ // The Inbox was open when this thread opened, and hasn't been closed for it yet. Widths settle over the sidebar's and
+ // the panel's own motion, so this holds until then rather than for the first measurement only.
+ const inboxBeforeThread = useRef(false);
+ useLayoutEffect(() => {
+ if (!threadId) { opened.current = null; setFull(false); return; }
+ if (opened.current !== threadId) inboxBeforeThread.current = Boolean(document.querySelector('[data-inbox-panel="side"]'));
+ opened.current = threadId;
+ let settle: ReturnType<typeof setTimeout> | undefined;
+ const read = (settled = false) => {
+ clearTimeout(settle);
+ const parts = [...document.querySelectorAll("[data-feed-area]")];
+ if (parts.length === 0) return;
+ const inbox = document.querySelector('[data-inbox-panel="side"]');
+ const place = feedThreadPlace(parts.reduce((sum, part) => sum + width(part), 0), { inboxBeforeThread: inboxBeforeThread.current, inboxWidth: inbox ? width(inbox) : 0 });
+ if (place === "close-inbox" && settled) { inboxBeforeThread.current = false; closeInbox(); return; }
+ if (place === "close-inbox") settle = setTimeout(() => read(true), SETTLE_MS);
+ setFull(place !== "beside");
+ };
+ const reread = () => read();
+ read();
+ const sizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(reread);
+ for (const part of document.querySelectorAll("[data-feed-area]")) sizes?.observe(part);
+ window.addEventListener("resize", reread);
+ return () => { clearTimeout(settle); sizes?.disconnect(); window.removeEventListener("resize", reread); };
+ }, [threadId, full]);
+ return Boolean(threadId) && full;
+}
diff --git a/src/lib/feature-flags.ts b/src/lib/feature-flags.ts
index 6043e7196f..9d0366f82b 100644
--- a/src/lib/feature-flags.ts
+++ b/src/lib/feature-flags.ts
@@ -106,11 +106,11 @@ export function threadTabsEnabled(config: FeatureFlagConfig | null | undefined):
return config?.features?.threadTabs === true;
}
-/** Whether this server has the room feed's routes: every server from 0.1.181 reports `features.roomFeed` (0.1.181 as
- * its old switch, later ones always true), and an older one, which has neither the thread summaries nor threads made
- * without moving the room's current one, reports nothing, so its rooms keep their single transcript. */
+/** Whether this home shows rooms as their feed: one from this version on reports `features.roomFeedSince` (and
+ * `roomFeed: true`); a 0.1.181 home only where its old switch was turned on. Any other home, including a 0.1.181 one
+ * that never opted in, keeps every room's single transcript until it updates. */
export function roomFeedEnabled(config: FeatureFlagConfig | null | undefined): boolean {
- return typeof config?.features?.roomFeed === "boolean";
+ return config?.features?.roomFeed === true || typeof config?.features?.roomFeedSince === "number";
}
export function teamBoardEnabled(config: FeatureFlagConfig | null | undefined): boolean {
diff --git a/src/lib/room-feed.test.ts b/src/lib/room-feed.test.ts
index 0d7d006614..b4077ddc51 100644
--- a/src/lib/room-feed.test.ts
+++ b/src/lib/room-feed.test.ts
@@ -2,12 +2,13 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { AppState, Group } from "@/state/store";
import { markVisibleGroupThreadsRead } from "@/state/read-visible";
import { openThread, visibleNotificationThread } from "@/state/thread-navigation";
-import { feedPreview, feedThreadAction, openRoomThreadThen, openThreadBeside, firstFeedCatchUp, readStaleUnread, roomFeedShows, staleUnreadThreads, takeFeedComposerWanted } from "./room-feed";
+import { feedPreview, feedThreadAction, openRoomThreadThen, openThreadBeside, catchUpOldMarks, roomFeedShows, staleUnreadThreads, takeFeedComposerWanted } from "./room-feed";
import { roomThreadAttention } from "./room-threads";
-const on = { features: { roomFeed: true } } as AppState["config"];
-/** A 0.1.181 home reports its old switch, off unless set; it has the feed's routes all the same. */
+const on = { features: { roomFeed: true, roomFeedSince: 1 } } as AppState["config"];
+/** A 0.1.181 home reports its old switch, off unless set, and no stamp. */
const home181 = { features: { roomFeed: false } } as AppState["config"];
+const home181OptedIn = { features: { roomFeed: true } } as AppState["config"];
/** A home older than 0.1.181 reports nothing about the feed and has none of its routes. */
const off = { features: {} } as AppState["config"];
const room = (extra: Partial<Group> = {}) => ({ id: "room", name: "Launch", threadId: "current", memberIds: ["kiwi"], messages: [{ id: "m" }],
@@ -22,7 +23,8 @@ afterEach(() => vi.unstubAllGlobals());
describe("the room feed", () => {
it("shows a room's feed wherever the server has it, never for a bot-to-bot room, and not on a phone", () => {
expect(roomFeedShows(on, room())).toBe(true);
- expect(roomFeedShows(home181, room())).toBe(true);
+ expect(roomFeedShows(home181, room())).toBe(false);
+ expect(roomFeedShows(home181OptedIn, room())).toBe(true);
expect(roomFeedShows(off, room())).toBe(false);
expect(roomFeedShows(undefined, room())).toBe(false);
expect(roomFeedShows(on, room({ dm: true }))).toBe(false);
@@ -63,19 +65,21 @@ describe("the room feed", () => {
});
describe("an Inbox line where the server has the room feed", () => {
- it("opens a room's thread or a bot's beside the chat", () => {
+ it("opens a room's thread with its feed, showing the room first when another chat is on screen", () => {
const dispatch = vi.fn();
expect(openThreadBeside(dispatch, "other", state(on, { selectedId: "kiwi" }))).toBe(true);
- expect(dispatch).toHaveBeenLastCalledWith({ type: "openForkPanel", kind: "group", ownerId: "room", threadId: "other" });
- expect(openThreadBeside(dispatch, "kiwi-side", state(on))).toBe(true);
- expect(dispatch).toHaveBeenLastCalledWith({ type: "openForkPanel", kind: "bot", ownerId: "kiwi", threadId: "kiwi-side" });
+ expect(dispatch.mock.calls).toEqual([[{ type: "select", id: "room" }], [{ type: "openForkPanel", kind: "group", ownerId: "room", threadId: "other" }]]);
+ dispatch.mockClear();
+ expect(openThreadBeside(dispatch, "other", state(on))).toBe(true);
+ expect(dispatch.mock.calls).toEqual([[{ type: "openForkPanel", kind: "group", ownerId: "room", threadId: "other" }]]);
});
- it("goes the usual way on an older server, on a phone, for an unknown thread, or for the chat already on screen", () => {
+ it("leaves a bot's thread to the chat, as before, and goes the usual way on an older server, on a phone or for an unknown thread", () => {
const dispatch = vi.fn();
+ expect(openThreadBeside(dispatch, "kiwi-side", state(on))).toBe(false);
+ expect(openThreadBeside(dispatch, "kiwi-main", state(on, { selectedId: "kiwi" }))).toBe(false);
expect(openThreadBeside(dispatch, "other", state(off))).toBe(false);
expect(openThreadBeside(dispatch, "gone", state(on))).toBe(false);
- expect(openThreadBeside(dispatch, "kiwi-main", state(on, { selectedId: "kiwi" }))).toBe(false);
narrow();
expect(openThreadBeside(dispatch, "other", state(on))).toBe(false);
expect(dispatch).not.toHaveBeenCalled();
@@ -157,21 +161,29 @@ describe("unread marks from before the feed", () => {
expect(staleUnreadThreads({ tasks }, undefined)).toEqual([]);
});
- it("are read through the room's read route, one at a time", async () => {
- const calls: unknown[] = [];
- const patched: unknown[] = [];
- const request = (async (path: string, init?: RequestInit) => { calls.push([path, init?.body]); return { group: { id: "room", unread: false } }; }) as never;
- await readStaleUnread("room", ["a", "b"], (group) => patched.push(group), request);
- expect(calls).toEqual([["/api/groups/room/read", JSON.stringify({ threadId: "a" })], ["/api/groups/room/read", JSON.stringify({ threadId: "b" })]]);
- expect(patched).toHaveLength(2);
- });
-
- it("are read once per room on this device, so a thread marked unread again later keeps its mark", () => {
+ it("are read in one request per room, and the room counts as done only once that read succeeded", async () => {
const saved = new Map<string, string>();
const storage = { getItem: (key: string) => saved.get(key) ?? null, setItem: (key: string, value: string) => { saved.set(key, value); } };
- expect(firstFeedCatchUp("room-a", storage)).toBe(true);
- expect(firstFeedCatchUp("room-a", storage)).toBe(false);
- expect(firstFeedCatchUp("room-b", storage)).toBe(true);
- expect(JSON.parse(saved.get("omb-room-feed-old-marks-read")!)).toEqual(["room-a", "room-b"]);
+ const calls: unknown[] = [];
+ let fail = true;
+ const request = (async (path: string, init?: RequestInit) => {
+ calls.push([path, init?.body]);
+ if (fail) throw new Error("offline");
+ return { group: { id: "room", unread: false } };
+ }) as never;
+ const patched: unknown[] = [];
+ const room = { id: "room", tasks };
+ expect(await catchUpOldMarks(room, 100, (group) => patched.push(group), { request, storage })).toBe(false);
+ expect(saved.get("omb-room-feed-old-marks-read")).toBeUndefined();
+ fail = false;
+ expect(await catchUpOldMarks(room, 100, (group) => patched.push(group), { request, storage })).toBe(true);
+ expect(calls).toEqual([0, 1].map(() => ["/api/groups/room/read", JSON.stringify({ threadIds: ["old-unread", "no-stamp"] })]));
+ expect(patched).toEqual([{ id: "room", unread: false }]);
+ expect(JSON.parse(saved.get("omb-room-feed-old-marks-read")!)).toEqual(["room"]);
+ // Done: a thread marked unread on purpose later keeps its mark.
+ expect(await catchUpOldMarks(room, 100, () => {}, { request, storage })).toBe(false);
+ expect(calls).toHaveLength(2);
+ expect(await catchUpOldMarks({ id: "quiet", tasks: [] }, 100, () => {}, { request, storage })).toBe(true);
+ expect(calls).toHaveLength(2);
});
});
diff --git a/src/lib/room-feed.ts b/src/lib/room-feed.ts
index 58defa3d70..d432f62e57 100644
--- a/src/lib/room-feed.ts
+++ b/src/lib/room-feed.ts
@@ -65,19 +65,15 @@ export function openRoomThreadThen(dispatch: (action: Action) => void, state: Pi
dispatch(openFeedThread(groupId, threadId));
}
-/** Where the server has the room feed, a thread opened from the Inbox opens beside whatever is on screen, and the Inbox stays.
- * False where today's way applies: a phone, a room's bot-to-bot chat, a thread no room or bot here holds, or the one
- * already shown in the chat. */
+/** A room thread opened from the Inbox opens with its room's feed, beside it (or in its place when the two don't fit),
+ * and the Inbox stays. False where the usual way applies: a bot's thread (it opens in the chat), a phone, a room that
+ * doesn't show as its feed, or a thread no room here holds. */
export function openThreadBeside(dispatch: (action: Action) => void, threadId: string,
- state: Pick<AppState, "config" | "activeView" | "selectedId"> & { bots: readonly ThreadOwner[]; groups: readonly (ThreadOwner & FeedRoom)[] }): boolean {
- if (!roomFeedEnabled(state.config) || !wideWindow()) return false;
- const owns = (owner: ThreadOwner) => (owner.tasks ?? []).some((task) => task.threadId === threadId);
- const group = state.groups.find(owns), bot = group ? undefined : state.bots.find(owns);
- const owner = group ?? bot;
- if (!owner || group?.dm) return false;
- const inChat = state.activeView === "chat" && state.selectedId === owner.id && owner.threadId === threadId;
- if (inChat && !(group && roomFeedShows(state.config, group))) return false;
- dispatch({ type: "openForkPanel", kind: group ? "group" : "bot", ownerId: owner.id, threadId });
+ state: Pick<AppState, "config" | "activeView" | "selectedId"> & { groups: readonly (ThreadOwner & FeedRoom)[] }): boolean {
+ const group = state.groups.find((owner) => (owner.tasks ?? []).some((task) => task.threadId === threadId));
+ if (!group || !roomFeedShows(state.config, group)) return false;
+ if (state.activeView !== "chat" || state.selectedId !== group.id) dispatch({ type: "select", id: group.id });
+ dispatch({ type: "openForkPanel", kind: "group", ownerId: group.id, threadId });
return true;
}
@@ -97,31 +93,42 @@ export function staleUnreadThreads(group: Pick<Group, "tasks">, since: number |
}
const CAUGHT_UP_KEY = "omb-room-feed-old-marks-read";
-const caughtUpHere = new Set<string>();
-
-/** True the first time a room asks on this device (and, without storage, in this window): its old marks are read once,
- * so a thread the person marks unread again later keeps that mark. */
-export function firstFeedCatchUp(groupId: string, storage: Pick<Storage, "getItem" | "setItem"> | null = safeStorage()): boolean {
- if (caughtUpHere.has(groupId)) return false;
- caughtUpHere.add(groupId);
- try {
- const done = new Set<string>(JSON.parse(storage?.getItem(CAUGHT_UP_KEY) ?? "[]") as string[]);
- if (done.has(groupId)) return false;
- done.add(groupId);
- storage?.setItem(CAUGHT_UP_KEY, JSON.stringify([...done]));
- } catch { /* storage unavailable: once in this window */ }
- return true;
-}
+/** As many threads as the room's read route takes in one request. */
+const READ_BATCH = 500;
+const reading = new Set<string>();
+type Store = Pick<Storage, "getItem" | "setItem">;
function safeStorage(): Storage | null {
try { return typeof localStorage === "undefined" ? null : localStorage; } catch { return null; }
}
-/** Reads those old marks through the room's read route, one at a time, so a failure keeps every read before it. */
-export async function readStaleUnread(groupId: string, threadIds: readonly string[], onGroup: (group: Partial<Group> & { id: string }) => void,
- request: typeof api = api): Promise<void> {
- for (const threadId of threadIds) {
- const result = await request<{ group?: Partial<Group> & { id: string } }>(`/api/groups/${groupId}/read`, { method: "POST", body: JSON.stringify({ threadId }) });
- if (result?.group) onGroup(result.group);
+function caughtUp(storage: Store | null): Set<string> {
+ try { return new Set<string>(JSON.parse(storage?.getItem(CAUGHT_UP_KEY) ?? "[]") as string[]); } catch { return new Set(); }
+}
+
+/** Reads a room's old marks (staleUnreadThreads) the first time it shows as its feed on this device: all of them in one
+ * request to the room's read route, so one answer and one frame. The room counts as done only once that read
+ * succeeded; a failure leaves it to try again the next time the room shows. A thread marked unread on purpose later
+ * keeps its mark. Resolves to whether the room is done. */
+export async function catchUpOldMarks(group: Pick<Group, "id" | "tasks">, since: number | undefined,
+ onGroup: (group: Partial<Group> & { id: string }) => void,
+ { request = api, storage = safeStorage() }: { request?: typeof api; storage?: Store | null } = {}): Promise<boolean> {
+ if (typeof since !== "number" || reading.has(group.id) || caughtUp(storage).has(group.id)) return false;
+ reading.add(group.id);
+ try {
+ const stale = staleUnreadThreads(group, since);
+ for (let at = 0; at < stale.length; at += READ_BATCH) {
+ const result = await request<{ group?: Partial<Group> & { id: string } }>(`/api/groups/${group.id}/read`,
+ { method: "POST", body: JSON.stringify({ threadIds: stale.slice(at, at + READ_BATCH) }) });
+ if (result?.group) onGroup(result.group);
+ }
+ const done = caughtUp(storage);
+ done.add(group.id);
+ try { storage?.setItem(CAUGHT_UP_KEY, JSON.stringify([...done])); } catch { /* read again next time: harmless */ }
+ return true;
+ } catch {
+ return false;
+ } finally {
+ reading.delete(group.id);
}
}
diff --git a/src/locales/de.json b/src/locales/de.json
index 17ee5d359b..a119b828d8 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -4417,6 +4417,7 @@
"room.feed.unreadBelow": "Ungelesener Thread weiter unten",
"room.thread.panel": "Thread",
"room.thread.close": "Thread schließen",
+ "room.thread.backToFeed": "Zurück zu {name}",
"room.thread.resize": "Thread-Breite ändern",
"settings.features.teamBoard": "Board",
"settings.features.teamBoardLine": "Verfolge Arbeit in Gruppenchats als Einträge mit Status, Labels und dem, worauf jeder wartet",
diff --git a/src/locales/en.json b/src/locales/en.json
index b32aec0fd6..db6d27704c 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -12022,6 +12022,7 @@
"room.feed.unreadBelow": "Unread thread below",
"room.thread.panel": "Thread",
"room.thread.close": "Close thread",
+ "room.thread.backToFeed": "Back to {name}",
"room.thread.resize": "Resize thread",
"settings.features.teamBoard": "Board",
"settings.features.teamBoardLine": "Track work in group chats as items with a state, labels and what each one waits for",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3bfafcc26f..c18843f6d3 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -12022,6 +12022,7 @@
"room.feed.unreadBelow": "Conversa não lida abaixo",
"room.thread.panel": "Conversa",
"room.thread.close": "Fechar conversa",
+ "room.thread.backToFeed": "Voltar para {name}",
"room.thread.resize": "Redimensionar conversa",
"settings.features.teamBoard": "Quadro",
"settings.features.teamBoardLine": "Acompanhe o trabalho nos chats em grupo como itens com status, rótulos e o que cada um espera",