Skip to content

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

Room feed: thread actions on each row, a clean header, and two entry points that open beside the feed (#7419)

Milind Soni2a7444753e26
diff --git a/DESIGN.md b/DESIGN.md
index a4822fdcc1..4a046020df 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -198,8 +198,13 @@ 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. Below 768px the
- room is today's single transcript.
+ which is everyone's. The feed's composer starts a new thread. 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
+ feed has the same menu in its header, with its export. Archived threads come
+ back under "Show archived threads" at the top of the feed. The header is plain
+ words, so the feed is masked under it. Below 768px the room is today's single
+ transcript.
- **The sidebar stays open beside a side panel** while the chat keeps 440px:
from 1040px with a 320px panel (a room, Simple's inbox, Notifications), from
1280px with a wider one. Narrower, it folds to its avatars.
diff --git a/packages/phone-protocol/src/room-threads.ts b/packages/phone-protocol/src/room-threads.ts
index e6aec524b8..011825b1f0 100644
--- a/packages/phone-protocol/src/room-threads.ts
+++ b/packages/phone-protocol/src/room-threads.ts
@@ -14,7 +14,7 @@ export interface RoomThreadSummary {
repliers: RoomThreadSpeaker[];
}
-/** GET /api/groups/:id/threads/summary: the room's threads that are not archived. */
+/** GET /api/groups/:id/threads/summary: the room's threads that are not archived, and with ?archived=1 the archived ones too. */
export interface RoomThreadSummariesResponse {
threads: RoomThreadSummary[];
}
diff --git a/scripts/testing/room-feed-ui.e2e.test.ts b/scripts/testing/room-feed-ui.e2e.test.ts
index 2fe1db5533..01b7389151 100644
--- a/scripts/testing/room-feed-ui.e2e.test.ts
+++ b/scripts/testing/room-feed-ui.e2e.test.ts
@@ -1,8 +1,10 @@
// A room as a feed of its threads, in the real renderer: with Settings → Features → Room feed on, a room of two bots
// shows each thread's first line and its replies, a row opens its thread beside the feed, and a line sent from the
-// feed's composer starts a thread of its own there while the room's current thread stays where it was. With the switch
-// off the room is its single transcript again. 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.
+// feed's composer starts a thread of its own there while the room's current thread stays where it was. A row's menu
+// pins, archives and deletes its thread, archived ones come back under Show archived threads, and the panel beside
+// the feed renames and deletes the thread it holds. With the switch off the room is its single transcript again.
+// 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 { tmpdir } from "node:os";
@@ -85,7 +87,7 @@ async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 3
expect(await evaluate(`Boolean(document.querySelector('[aria-expanded][aria-label*="Launch room"]'))`)).toBe(false);
await ui("screenshot", "--out", join(evidenceDir, "room-feed.png"));
- await evaluate("document.querySelectorAll('[data-feed-thread] button')[1].click(); true");
+ await evaluate("document.querySelectorAll('[data-feed-thread] > button:first-child')[1].click(); true");
const opened = await until(() => evaluate("document.querySelector('[data-thread-panel]')?.getAttribute('data-thread-panel')"), "the thread to open beside the feed");
await until(() => evaluate("document.querySelector('[data-thread-panel]').textContent.includes('Who has the logo files?')"), "the thread's lines in the panel");
expect(await current()).toBe(room.threadId);
@@ -105,6 +107,57 @@ 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-new-thread.png"));
+ const row = (threadId: string) => `[data-feed-thread="${threadId}"]`;
+ const menuItem = (label: string) => `[...[...document.querySelectorAll('[data-thread-overlay]')].at(-1)?.querySelectorAll('button') ?? []].find((button) => button.textContent.includes(${JSON.stringify(label)}))`;
+ const tasks = async () => ((await api("GET", "/api/bots")).groups as Array<{ id: string; tasks: Array<{ threadId: string; title: string; pinned?: boolean; archivedAt?: number }> }>).find((group) => group.id === room.id)!.tasks;
+ const [, logos] = await evaluate("[...document.querySelectorAll('[data-feed-thread]')].map((item) => item.getAttribute('data-feed-thread'))") as string[];
+ await evaluate(`document.querySelector('${row(logos!)} button[aria-expanded]').click(); true`);
+ await until(() => evaluate(`Boolean(${menuItem("Pin")})`), "the row's menu");
+ await evaluate(`${menuItem("Pin")}.click(); true`);
+ await until(async () => (await tasks()).find((task) => task.threadId === logos)?.pinned === true, "the thread to be pinned");
+ await until(() => evaluate(`Boolean(document.querySelector('${row(logos!)} [data-feed-pinned]'))`), "the pin on its row");
+
+ await evaluate(`document.querySelector('${row(logos!)} button[aria-expanded]').click(); true`);
+ await until(() => evaluate(`Boolean(${menuItem("Archive")})`), "the row's menu again");
+ await evaluate(`${menuItem("Archive")}.click(); true`);
+ await until(() => evaluate(`!document.querySelector('${row(logos!)}')`), "the archived thread to leave the feed");
+ await evaluate("document.querySelector('[data-feed-archived-toggle]').click(); true");
+ await until(() => evaluate(`Boolean(document.querySelector('${row(logos!)}'))`), "the archived thread to show again");
+ await evaluate(`document.querySelector('${row(logos!)} button[aria-expanded]').click(); true`);
+ await until(() => evaluate(`Boolean(${menuItem("Unarchive")})`), "Unarchive in its menu");
+ await evaluate(`${menuItem("Unarchive")}.click(); true`);
+ await until(async () => (await tasks()).find((task) => task.threadId === logos)?.archivedAt === undefined, "the thread to come back");
+
+ await evaluate(`document.querySelector('${row(logos!)} > button:first-child').click(); true`);
+ await until(() => evaluate(`document.querySelector('[data-thread-panel]')?.getAttribute('data-thread-panel') === ${JSON.stringify(logos)}`), "the thread beside the feed");
+ await browse("click", "[data-thread-panel] header button[aria-expanded]");
+ await until(() => evaluate(`Boolean(${menuItem("Download as .md")})`), "the panel's menu with the thread's export");
+ await evaluate(`${menuItem("Rename thread")}.click(); true`);
+ await until(() => evaluate("document.activeElement === document.querySelector('[data-thread-panel] header input')"), "the title's field");
+ await browse("fill", "[data-thread-panel] header input", "Logo files");
+ await browse("press", "Enter");
+ await until(async () => (await tasks()).find((task) => task.threadId === logos)?.title === "Logo files", "the thread's new title");
+ expect(await evaluate("document.querySelector('[data-thread-panel] h2').textContent")).toBe("Logo files");
+ expect(await evaluate("getComputedStyle(document.querySelector('[data-room-feed] .glass-scroller')).maskImage")).toContain("linear-gradient");
+ await ui("screenshot", "--out", join(evidenceDir, "room-feed-thread-actions.png"));
+
+ const confirmDelete = `[...document.querySelectorAll('[role="alertdialog"] button')].find((button) => button.textContent === "Delete thread")`;
+ const demo = (await evaluate("[...document.querySelectorAll('[data-feed-thread]')].map((item) => item.getAttribute('data-feed-thread'))") as string[])[2]!;
+ await evaluate(`document.querySelector('${row(demo)} button[aria-expanded]').click(); true`);
+ await until(() => evaluate(`Boolean(${menuItem("Delete thread")})`), "Delete in the row's menu");
+ await evaluate(`${menuItem("Delete thread")}.click(); true`);
+ await until(() => evaluate(`Boolean(${confirmDelete})`), "the delete confirmation");
+ await evaluate(`${confirmDelete}.click(); true`);
+ await until(async () => !(await tasks()).some((task) => task.threadId === demo), "the thread to be deleted");
+ await until(() => evaluate(`!document.querySelector('${row(demo)}')`), "its row to leave the feed");
+ await browse("click", "[data-thread-panel] header button[aria-expanded]");
+ await until(() => evaluate(`Boolean(${menuItem("Delete thread")})`), "Delete in the panel's menu");
+ await evaluate(`${menuItem("Delete thread")}.click(); true`);
+ await until(() => evaluate(`Boolean(${confirmDelete})`), "the panel's delete confirmation");
+ await evaluate(`${confirmDelete}.click(); true`);
+ 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");
+
await ui("flag", "--set", "features.roomFeed=false");
await until(() => evaluate("!document.querySelector('[data-room-feed]') && Boolean(document.querySelector('[data-look=\"chat\"] [role=\"log\"]'))"), "the room's transcript to come back");
const logs = await ui("console");
diff --git a/server/room-thread-summaries.e2e.test.ts b/server/room-thread-summaries.e2e.test.ts
index c85fa771b5..6807bfe32b 100644
--- a/server/room-thread-summaries.e2e.test.ts
+++ b/server/room-thread-summaries.e2e.test.ts
@@ -73,7 +73,7 @@ describe("a room's thread summaries", () => {
expect((await as("ada", "POST", `/api/groups/${room}/read`, { threadId: thread })).body.group.threadId).toBe(roomThread);
});
- it("leaves out an archived thread", async () => {
+ it("leaves out an archived thread unless asked for archived ones", async () => {
const created = await as("ada", "POST", `/api/groups/${room}/tasks`, { activate: false });
const thread = created.body.task.threadId as string;
expect((await as("ada", "POST", `/api/groups/${room}/messages`, { text: "Old idea", threadId: thread })).status).toBeLessThan(300);
@@ -82,6 +82,8 @@ describe("a room's thread summaries", () => {
const after = (await as("ada", "GET", `/api/groups/${room}/threads/summary`)).body.threads as RoomThreadSummary[];
expect(after.map((row) => row.threadId)).not.toContain(thread);
expect(after.map((row) => row.threadId)).toContain(roomThread);
+ const shown = (await as("ada", "GET", `/api/groups/${room}/threads/summary?archived=1`)).body.threads as RoomThreadSummary[];
+ expect(shown.find((row) => row.threadId === thread)?.first?.text).toBe("Old idea");
});
it("answers someone who cannot see the room as if it did not exist", async () => {
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index f7597ef168..9de7f5bb5e 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -195,7 +195,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
if (m && method === "GET") {
const group = store.group(m[1]);
if (!group || group.dm) return json(res, 404, { error: "no such room" });
- const threadIds = (group.tasks ?? [{ threadId: group.threadId, archivedAt: undefined }]).filter((task) => task.archivedAt === undefined && (deps.threadShown?.(auth, task.threadId) ?? true))
+ const archived = url.searchParams.get("archived") === "1";
+ const threadIds = (group.tasks ?? [{ threadId: group.threadId, archivedAt: undefined }]).filter((task) => (archived || task.archivedAt === undefined) && (deps.threadShown?.(auth, task.threadId) ?? true))
.map((task) => task.threadId);
return json(res, 200, { threads: roomThreadSummaries(threadIds) } satisfies RoomThreadSummariesResponse);
}
diff --git a/src/components/ForkPanel.tsx b/src/components/ForkPanel.tsx
index b7667e4021..8e2588344d 100644
--- a/src/components/ForkPanel.tsx
+++ b/src/components/ForkPanel.tsx
@@ -7,6 +7,7 @@ import { currentTaskBot, useStore } from "@/state/store";
import { t } from "@/lib/i18n";
import { ChatView } from "./ChatView";
import { GroupView } from "./GroupView";
+import { ThreadPanelHeading } from "./room-feed/ThreadPanelHeading";
import { PANEL_MIN_WIDTH, useComputerPanelResize } from "./computer-panel-resize";
const BESIDE_INBOX_MAX = 400;
@@ -66,10 +67,10 @@ export function ForkPanel() {
/>}
{beside ? (
<header className="flex shrink-0 items-center gap-2 py-2.5 ps-4 pe-3">
- <div className="min-w-0 flex-1">
+ {!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>
+ </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>
</header>
diff --git a/src/components/RoutineCalendarPage.tsx b/src/components/RoutineCalendarPage.tsx
index e8e2070cca..9954a3a775 100644
--- a/src/components/RoutineCalendarPage.tsx
+++ b/src/components/RoutineCalendarPage.tsx
@@ -33,6 +33,7 @@ import { cronChoiceFor, cronDraftFor, cronEditorValue, isCronChoice, type CronCh
import { partlyDone, routineRunLabel, routineRunsOn, routineRunText, routineRunTime, routineScheduleState } from "@/lib/routine-display";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useShowThreads } from "@/lib/thread-preferences";
+import { openRoomThreadThen } from "@/lib/room-feed";
import { intlLocale, t } from "@/lib/i18n";
import { intakeFilesWithNotice } from "@/lib/attach-notice";
import { useModalDialog } from "@/hooks/use-modal-dialog";
@@ -1201,8 +1202,7 @@ export function EventDetails({
const openRunTask = () => {
if (!executionThreadId) return;
if (isRoomGoal && goalGroupId) {
- dispatch({ type: "switchGroupTask", groupId: goalGroupId, threadId: executionThreadId });
- onOpenRoom(goalGroupId);
+ openRoomThreadThen(dispatch, state, goalGroupId, executionThreadId, onOpenRoom);
} else if (primary) {
openBotThread(dispatch, primary, executionThreadId, showThreads);
}
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
index 708c48b416..ad44847780 100644
--- a/src/components/Sidebar.tsx
+++ b/src/components/Sidebar.tsx
@@ -86,7 +86,7 @@ import { isSidebarToggle } from "@/lib/keyboard-shortcuts";
import { SidebarRailSeparator, SimpleRailFooter } from "./SidebarSimpleRail";
import { useShowThreads } from "@/lib/thread-preferences";
import { useBotUnread, useUnreadHold } from "./unread-notice";
-import { attentionHasRunningWork, attentionJumpAction, crossBotAttentionThreads, hasCrossBotRunningWork, runningRoutineRun, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";
+import { attentionHasRunningWork, attentionJump, crossBotAttentionThreads, hasCrossBotRunningWork, runningRoutineRun, SidebarBotActivity, sidebarBotActivityTasks, sidebarBotStatus } from "./SidebarBotActivity";
import { SidebarNoBots, SidebarTileGrid } from "./SidebarTiles";
import { BotContextMenu } from "./SidebarBotMenu";
export { BotContextMenu };
@@ -1334,7 +1334,7 @@ export const Sidebar = memo(function Sidebar({ open, onClose, collapseToIcons =
<SidebarAttentionPanel
entries={attention}
onUnpin={() => setAttentionPinned(false)}
- onJump={(entry) => dispatch(attentionJumpAction(entry))}
+ onJump={(entry) => attentionJump(dispatch, entry, state)}
collapsed={sectionCollapsed(ATTENTION_SECTION_ID)}
onToggle={layoutInteractive ? () => toggleSection(ATTENTION_SECTION_ID) : undefined}
/>
diff --git a/src/components/SidebarBotActivity.test.ts b/src/components/SidebarBotActivity.test.ts
index 2eff8f2ffb..b65375c00a 100644
--- a/src/components/SidebarBotActivity.test.ts
+++ b/src/components/SidebarBotActivity.test.ts
@@ -1,9 +1,9 @@
import { BellDot, CircleAlert, Clock3, Loader2 } from "lucide-react";
-import { describe, expect, it } from "vitest";
-import type { Bot, Group, GroupTask, Task } from "@/state/store";
+import { describe, expect, it, vi } from "vitest";
+import type { AppState, Bot, Group, GroupTask, Task } from "@/state/store";
import { botShowsUnread } from "@/lib/bot-unread";
import { t } from "@/lib/i18n";
-import { attentionHasRunningWork, attentionJumpAction, attentionOwnerName, attentionRowStatus, attentionTriggerLabel, attentionUnpinAction, crossBotAttentionThreads, crossBotPinnedThreads, sidebarBotActivityTasks, sidebarGroupActivityTasks, threadsWaitingOnPerson, threadsWhenTreeHidden } from "./SidebarBotActivity";
+import { attentionHasRunningWork, attentionJump, attentionJumpAction, attentionOwnerName, attentionRowStatus, attentionTriggerLabel, attentionUnpinAction, crossBotAttentionThreads, crossBotPinnedThreads, sidebarBotActivityTasks, sidebarGroupActivityTasks, threadsWaitingOnPerson, threadsWhenTreeHidden } from "./SidebarBotActivity";
const task = (threadId: string, title: string, extra: Partial<Task>): Task =>
({ threadId, title, createdAt: 0, ...extra }) as Task;
@@ -190,6 +190,24 @@ describe("group attention", () => {
expect(attentionJumpAction(side)).toEqual({ type: "switchGroupTask", groupId: "g", threadId: "g1" });
});
+ it("with the room feed on, shows the room and opens its thread beside the feed, its current one too; with it off, as before", () => {
+ vi.stubGlobal("window", { matchMedia: () => ({ matches: true }) });
+ const room = group("g", "Crew", "g0", { messages: [{ id: "m" }], tasks: [{ threadId: "g0", title: "Crew", createdAt: 0 }, { threadId: "g1", title: "Side", createdAt: 0 }] } as never);
+ const entries = crossBotAttentionThreads([], { g0: [{}], g1: [{}] }, undefined, [room]);
+ const sent: unknown[] = [];
+ const on = { config: { features: { roomFeed: true } } as AppState["config"], groups: [room] };
+ for (const entry of entries) attentionJump((action) => sent.push(action), entry, on);
+ expect(sent).toEqual([
+ { type: "select", id: "g" }, { type: "openForkPanel", kind: "group", ownerId: "g", threadId: "g0" },
+ { type: "select", id: "g" }, { type: "openForkPanel", kind: "group", ownerId: "g", threadId: "g1" },
+ ]);
+ sent.length = 0;
+ const off = { config: { features: { roomFeed: false } } as AppState["config"], groups: [room] };
+ for (const entry of entries) attentionJump((action) => sent.push(action), entry, off);
+ expect(sent).toEqual([{ type: "select", id: "g" }, { type: "switchGroupTask", groupId: "g", threadId: "g1" }]);
+ vi.unstubAllGlobals();
+ });
+
it("jumps a bot entry with switchTask", () => {
const alpha = bot("a", "Alpha", "a0", [task("a0", "Unread reply", { unread: true })]);
const [entry] = crossBotAttentionThreads([alpha], {});
diff --git a/src/components/SidebarBotActivity.tsx b/src/components/SidebarBotActivity.tsx
index a6fe695ffd..e61955bfa4 100644
--- a/src/components/SidebarBotActivity.tsx
+++ b/src/components/SidebarBotActivity.tsx
@@ -3,6 +3,7 @@ import type { Dispatch } from "react";
import type { Action, AppState, Bot, Group, Task } from "@/state/store";
import { cn } from "@/lib/cn";
import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
+import { openFeedThread, roomFeedShows } from "@/lib/room-feed";
import { t } from "@/lib/i18n";
import { isArchived, orderedSidebarThreads, orderedThreadList } from "./SidebarThreadRow";
import type { SidebarDensity } from "@/lib/sidebar-preferences";
@@ -106,6 +107,17 @@ export function attentionJumpAction(entry: AttentionThread):
: { type: "switchGroupTask", groupId: entry.groupId, threadId: entry.task.threadId };
}
+/** Opens an activity row's thread; a room that shows its feed comes on screen with the thread beside the feed, its
+ * current thread too. */
+export function attentionJump(dispatch: Dispatch<Action>, entry: AttentionThread, state: Pick<AppState, "config" | "groups">): void {
+ if (entry.kind === "group" && roomFeedShows(state.config, state.groups.find((group) => group.id === entry.groupId))) {
+ dispatch({ type: "select", id: entry.groupId });
+ dispatch(openFeedThread(entry.groupId, entry.task.threadId));
+ return;
+ }
+ dispatch(attentionJumpAction(entry));
+}
+
export function attentionUnpinAction(entry: AttentionThread):
| { type: "updateTask"; botId: string; threadId: string; patch: { pinned: boolean } }
| { type: "pinGroupTask"; groupId: string; threadId: string; pinned: boolean; title: string } {
diff --git a/src/components/SidebarGroupThreadList.tsx b/src/components/SidebarGroupThreadList.tsx
index 18eeb28959..ec50009855 100644
--- a/src/components/SidebarGroupThreadList.tsx
+++ b/src/components/SidebarGroupThreadList.tsx
@@ -1,21 +1,27 @@
-import { useMemo, useRef, useState } from "react";
-import { useStore, type Group } from "@/state/store";
+import { useMemo, useRef, useState, type Dispatch } from "react";
+import { useStore, type Action, type Group } from "@/state/store";
import { activeLocale, t } from "@/lib/i18n";
-import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
+import { roomThreadAttention, roomThreadWorking } from "@/lib/room-threads";
import { BulkSelectFilters, ThreadListFooter, deleteThreadsInBulk, useBulkSelect } from "./BulkSelectBar";
import { orderedThreadList, SidebarThreadRow, stampClock, threadRecency, useRelativeNow, useRevealedThreadRow, visibleSidebarThreads } from "./SidebarThreadRow";
+/** The store actions behind a room's thread-row menu, for every list that draws that room's threads. */
+export function roomThreadRowActions(groupId: string, dispatch: Dispatch<Action>) {
+ return {
+ onRename: (task: { threadId: string }, title: string) => dispatch({ type: "renameGroupTask", groupId, threadId: task.threadId, title }),
+ onDelete: (task: { threadId: string }) => dispatch({ type: "deleteGroupTask", groupId, threadId: task.threadId }),
+ onPin: (task: { threadId: string; title: string }, pinned: boolean) => dispatch({ type: "pinGroupTask", groupId, threadId: task.threadId, pinned, title: task.title }),
+ onArchive: (task: { threadId: string }, archivedAt: number | null) => dispatch({ type: "archiveGroupTask", groupId, threadId: task.threadId, archivedAt }),
+ };
+}
+
export function GroupThreadList({ group, selected, query = "" }: { group: Group; selected: boolean; query?: string }) {
const { state, dispatch } = useStore();
const now = useRelativeNow();
const [showAll, setShowAll] = useState(false);
const tasks = (group.tasks ?? [{ threadId: group.threadId, title: group.name, createdAt: group.createdAt }]).map((task) => {
- const speakerId = roomThreadSpeakerId(group, task.threadId);
- const waiting = Boolean(speakerId) && state.bots.find((bot) => bot.id === speakerId)?.activity === "waiting-on-you";
- return {
- ...task, busy: roomThreadWorking(group, task.threadId), unread: task.unread ?? (task.threadId === group.threadId && group.unread),
- activity: waiting || task.activity === "waiting-on-you" ? "waiting-on-you" as const : undefined,
- };
+ const { waiting, unread } = roomThreadAttention(group, task, state.bots);
+ return { ...task, busy: roomThreadWorking(group, task.threadId), unread, activity: waiting ? "waiting-on-you" as const : undefined };
});
const bulk = useBulkSelect();
const visible = orderedThreadList(visibleSidebarThreads(tasks, group.threadId, query, [], showAll || bulk.active));
@@ -29,10 +35,7 @@ export function GroupThreadList({ group, selected, query = "" }: { group: Group;
if (task.threadId !== latest.current.threadId) dispatch({ type: "switchGroupTask", groupId, threadId: task.threadId });
else dispatch({ type: "select", id: groupId });
},
- onRename: (task: { threadId: string }, title: string) => dispatch({ type: "renameGroupTask", groupId, threadId: task.threadId, title }),
- onDelete: (task: { threadId: string }) => dispatch({ type: "deleteGroupTask", groupId, threadId: task.threadId }),
- onPin: (task: { threadId: string; title: string }, pinned: boolean) => dispatch({ type: "pinGroupTask", groupId, threadId: task.threadId, pinned, title: task.title }),
- onArchive: (task: { threadId: string }, archivedAt: number | null) => dispatch({ type: "archiveGroupTask", groupId, threadId: task.threadId, archivedAt }),
+ ...roomThreadRowActions(groupId, dispatch),
}), [groupId, dispatch]);
const locale = activeLocale();
return <div className="mb-2 space-y-0.5" role="group" aria-label={t("task.namedList", { name: group.name })}>
diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsx
index 0de5394f3b..5cf7fab929 100644
--- a/src/components/SidebarThreadRow.tsx
+++ b/src/components/SidebarThreadRow.tsx
@@ -1,4 +1,4 @@
-import { memo, useEffect, useRef, useState, type Dispatch, type ReactNode } from "react";
+import { memo, useEffect, useRef, useState, type Dispatch, type ReactNode, type RefObject, type SetStateAction } from "react";
import { createPortal } from "react-dom";
import { Archive, ArchiveRestore, BellOff, Brain, Check, ChevronRight, Clock, Clock3, FolderInput, Link2, Link2Off, Loader2, MoreHorizontal, Pencil, Pin, PinOff, RefreshCw, Star, Trash2 } from "lucide-react";
import type { Action, AppState, BotProject, Task } from "@/state/store";
@@ -312,25 +312,11 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
const activityLabel = useHeldText(liveActivity);
// Simple mode's menu keeps what a person needs for a conversation; Advanced adds the rest.
const advanced = useAdvancedMode();
- const [menu, setMenu] = useState<{ left: number; top: number } | null>(null);
- const [webLink, setWebLink] = useState<string | null>(null);
- useEffect(() => {
- setWebLink(null);
- if (!menu) return;
- let active = true;
- void api<{ publicUrl?: string | null }>("/api/settings/custom-domain", { background: true }).then((domain) => {
- if (active) setWebLink(domain.publicUrl ? threadWebRefUrl({ botId: ownerId, threadId: task.threadId }, domain.publicUrl) : null);
- }).catch(() => { if (active) setWebLink(null); });
- return () => { active = false; };
- }, [menu, ownerId, task.threadId]);
- const menuMotion = useHeldMenuMotion(menu);
+ const [menu, setMenu] = useState<ThreadMenuAt | null>(null);
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(task.title);
- const [deleting, setDeleting] = useState(false);
- const [regenerating, setRegenerating] = useState(false);
const displayTitle = localizedTaskTitle(task.title);
const finishing = useRef(false);
- const menuRef = useRef<HTMLDivElement>(null);
const actionRef = useRef<HTMLButtonElement>(null);
const status = task.activity === "waiting-on-you" ? t("task.waiting") : isWaitingOnTeammate(task) ? t("task.waitingOnTeammate") : isWorking(task) ? activityLabel ?? t("chat.activity.working") : task.queued ? t("task.queued") : null;
const byline = threadByline(task);
@@ -343,17 +329,10 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
const tickable = isTickable(task);
const choose = (event: React.MouseEvent) => { if (!selectMode) onSelect(task); else if (tickable) onToggleSelect?.(task, event.shiftKey); };
const contextMenu = (event: React.MouseEvent) => { event.preventDefault(); if (!selectMode) openMenu(event.clientX, event.clientY); };
- const openMenu = (x: number, y: number) => setMenu({ left: Math.max(8, Math.min(x, window.innerWidth - 228)), top: Math.max(8, Math.min(y, window.innerHeight - 230)) });
+ const openMenu = (x: number, y: number) => setMenu(threadMenuAt(x, y));
const startRename = () => { if (task.sharedChat) return; finishing.current = false; setDraft(task.title); setRenaming(true); setMenu(null); };
- const copyLink = () => {
- setMenu(null);
- void copyText(threadRefUrl({ botId: ownerId, threadId: task.threadId }));
- };
- const regenerateTitle = () => {
- if (!onRegenerateTitle || regenerating) return;
- setRegenerating(true);
- onRegenerateTitle(task, (ok) => { setRegenerating(false); if (ok) setMenu(null); });
- };
+ const menuSheet = useThreadRowMenu({ task, displayTitle, ownerId, folders, main, menu, setMenu, actionRef, onStartRename: startRename, onSelect, onRegenerateTitle, onDelete, onMove,
+ onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onMemory });
const finishRename = (save: boolean) => {
if (finishing.current) return;
finishing.current = true;
@@ -361,29 +340,6 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
setRenaming(false);
if (title) onRename(task, title);
};
- useEffect(() => {
- if (!menu) return;
- menuRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
- const outside = (event: MouseEvent) => {
- if (event.target instanceof Node && !menuRef.current?.contains(event.target) && !actionRef.current?.contains(event.target)) setMenu(null);
- };
- window.addEventListener("mousedown", outside);
- return () => window.removeEventListener("mousedown", outside);
- }, [menu]);
- useEffect(() => {
- if (!menu || !menuRef.current) return;
- const keepOnScreen = () => {
- const el = menuRef.current;
- if (!el) return;
- const top = Math.max(8, window.innerHeight - el.offsetHeight - 8);
- setMenu((current) => (current && current.top > top ? { ...current, top } : current));
- };
- keepOnScreen();
- const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(keepOnScreen);
- observer?.observe(menuRef.current);
- window.addEventListener("resize", keepOnScreen);
- return () => { observer?.disconnect(); window.removeEventListener("resize", keepOnScreen); };
- }, [menu]);
const heading = <span className={cn("flex min-w-0 flex-1 items-baseline gap-1.5", panel && "pe-6")}>
<span dir="auto" className={cn("min-w-0 flex-1 max-w-max truncate", task.unread && "font-semibold text-ink", (closed || archived || snoozed) && !current && "text-ink-tertiary")}>{displayTitle}</span>
{main && <MainThreadMark className="self-center" />}
@@ -432,13 +388,90 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
<MoreHorizontal size={13} />
</button>}
</div>
+ {menuSheet}
+ </>;
+}, sameThreadRow);
+
+export type ThreadMenuAt = { left: number; top: number };
+/** The menu's width (`w-[220px]`), for a control that lines the menu up with its own end. */
+export const THREAD_MENU_WIDTH = 220;
+export const threadMenuAt = (x: number, y: number): ThreadMenuAt =>
+ ({ left: Math.max(8, Math.min(x, window.innerWidth - 228)), top: Math.max(8, Math.min(y, window.innerHeight - 230)) });
+
+type ThreadMenuProps = Pick<ThreadRowProps, "task" | "ownerId" | "folders" | "main" | "onRegenerateTitle" | "onDelete" | "onMove" | "onArchive" | "onPin" | "onSetMain"
+ | "onSnooze" | "onLink" | "onRefreshPermissions" | "onMemory"> & {
+ menu: ThreadMenuAt | null;
+ setMenu: Dispatch<SetStateAction<ThreadMenuAt | null>>;
+ /** The control that opened the menu: a click on it is not a click outside, and focus returns to it. */
+ actionRef: RefObject<HTMLButtonElement | null>;
+ onStartRename: () => void;
+ onSelect?: (task: ThreadRowTask) => void;
+ displayTitle: string;
+ /** More rows above Delete; each closes the menu with the function it is given. */
+ extra?: (close: () => void) => ReactNode;
+ /** False for a room's only thread, which a room keeps. */
+ deletable?: boolean;
+};
+
+/** A thread row's menu and its delete confirmation, for every list that draws a thread with its actions. */
+export function useThreadRowMenu({ task, displayTitle, ownerId, folders, main = false, menu, setMenu, actionRef, onStartRename, onSelect, onRegenerateTitle, onDelete, onMove, onArchive, onPin, onSetMain, onSnooze, onLink, onRefreshPermissions, onMemory, extra, deletable = true }: ThreadMenuProps): ReactNode {
+ const advanced = useAdvancedMode();
+ const [webLink, setWebLink] = useState<string | null>(null);
+ useEffect(() => {
+ setWebLink(null);
+ if (!menu) return;
+ let active = true;
+ void api<{ publicUrl?: string | null }>("/api/settings/custom-domain", { background: true }).then((domain) => {
+ if (active) setWebLink(domain.publicUrl ? threadWebRefUrl({ botId: ownerId, threadId: task.threadId }, domain.publicUrl) : null);
+ }).catch(() => { if (active) setWebLink(null); });
+ return () => { active = false; };
+ }, [menu, ownerId, task.threadId]);
+ const menuMotion = useHeldMenuMotion(menu);
+ const [deleting, setDeleting] = useState(false);
+ const [regenerating, setRegenerating] = useState(false);
+ const archived = isArchived(task);
+ const snoozed = isSnoozed(task);
+ const menuRef = useRef<HTMLDivElement>(null);
+ const copyLink = () => {
+ setMenu(null);
+ void copyText(threadRefUrl({ botId: ownerId, threadId: task.threadId }));
+ };
+ const regenerateTitle = () => {
+ if (!onRegenerateTitle || regenerating) return;
+ setRegenerating(true);
+ onRegenerateTitle(task, (ok) => { setRegenerating(false); if (ok) setMenu(null); });
+ };
+ useEffect(() => {
+ if (!menu) return;
+ menuRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
+ const outside = (event: MouseEvent) => {
+ if (event.target instanceof Node && !menuRef.current?.contains(event.target) && !actionRef.current?.contains(event.target)) setMenu(null);
+ };
+ window.addEventListener("mousedown", outside);
+ return () => window.removeEventListener("mousedown", outside);
+ }, [menu, setMenu, actionRef]);
+ useEffect(() => {
+ if (!menu || !menuRef.current) return;
+ const keepOnScreen = () => {
+ const el = menuRef.current;
+ if (!el) return;
+ const top = Math.max(8, window.innerHeight - el.offsetHeight - 8);
+ setMenu((current) => (current && current.top > top ? { ...current, top } : current));
+ };
+ keepOnScreen();
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(keepOnScreen);
+ observer?.observe(menuRef.current);
+ window.addEventListener("resize", keepOnScreen);
+ return () => { observer?.disconnect(); window.removeEventListener("resize", keepOnScreen); };
+ }, [menu, setMenu]);
+ return <>
{menuMotion.shown && menuMotion.value && createPortal(<div ref={menuRef} data-thread-overlay role="group" aria-label={t("task.actions", { title: displayTitle })} style={menuMotion.value}
className={cn("fixed z-50 max-h-[calc(100vh-16px)] w-[220px] overflow-y-auto", MENU_SHEET, menuMotion.className)} {...menuMotion.exitProps}
onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setMenu(null); actionRef.current?.focus(); } }}>
{advanced && <button type="button" onClick={copyLink} className="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"><Link2 size={16} />{t("task.copyLink")}</button>}
{advanced && webLink && <button type="button" onClick={() => { setMenu(null); void copyText(webLink); }} className="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"><Link2 size={16} />{t("task.copyLink")} (HTTP{webLink.startsWith("https:") ? "S" : ""})</button>}
- {!task.sharedChat && <button type="button" onClick={startRename} className="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"><Pencil size={16} />{t("task.renameAria")}</button>}
- {onMemory && <button type="button" data-thread-memory="" onClick={() => { setMenu(null); onSelect(task); onMemory(task); }} className="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"><Brain size={16} />{t("memory.title")}</button>}
+ {!task.sharedChat && <button type="button" onClick={onStartRename} className="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"><Pencil size={16} />{t("task.renameAria")}</button>}
+ {onMemory && <button type="button" data-thread-memory="" onClick={() => { setMenu(null); onSelect?.(task); onMemory(task); }} className="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"><Brain size={16} />{t("memory.title")}</button>}
{advanced && <ShareRowItems botId={ownerId} task={task} onPicked={() => setMenu(null)} />}
{advanced && onRegenerateTitle && !task.sharedChat && <button type="button" disabled={regenerating} aria-busy={regenerating} onClick={regenerateTitle} className="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">{regenerating ? <Loader2 size={16} className="animate-spin" /> : <RefreshCw size={16} />}{regenerating ? t("task.regeneratingTitle") : t("task.regenerateTitle")}</button>}
{advanced && onMove && Boolean(folders?.length) && <label className="block rounded-md px-2 py-1.5 text-[13px] text-ink"><span className="mb-1 flex items-center gap-2 text-ink-secondary"><FolderInput size={16} />{t("folder.move")}</span>
@@ -461,9 +494,10 @@ export const SidebarThreadRow = memo(function SidebarThreadRow({ task, ownerId,
</div>}
{advanced && onSnooze && snoozed && <button type="button" onClick={() => { setMenu(null); onSnooze(task, null); }} className="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"><BellOff size={16} />{t("task.stopSnoozing")}</button>}
{advanced && onRefreshPermissions && <button type="button" disabled={isWorking(task)} title={t("task.refreshPermissionsHint")} onClick={() => { setMenu(null); onRefreshPermissions(task); }} className="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"><RefreshCw size={16} />{t("task.refreshPermissions")}</button>}
- <button type="button" disabled={isWorking(task)} onClick={() => { setMenu(null); setDeleting(true); }} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-danger hover:bg-menu-hover disabled:opacity-40"><Trash2 size={16} />{t("task.deleteAria")}</button>
+ {extra?.(() => setMenu(null))}
+ {deletable && <button type="button" disabled={isWorking(task)} onClick={() => { setMenu(null); setDeleting(true); }} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[14px] leading-[18px] text-danger hover:bg-menu-hover disabled:opacity-40"><Trash2 size={16} />{t("task.deleteAria")}</button>}
</div>, document.body)}
<ConfirmDialog open={deleting} title={t("task.deleteConfirm")} body={t("task.deleteBody", { title: task.title })} confirmLabel={t("task.deleteAria")}
onCancel={() => setDeleting(false)} onConfirm={() => { if (!isWorking(task)) onDelete(task); setDeleting(false); }} returnFocusRef={actionRef} />
</>;
-}, sameThreadRow);
+}
diff --git a/src/components/TaskPicker.tsx b/src/components/TaskPicker.tsx
index 35a625ffeb..caa49bbf3a 100644
--- a/src/components/TaskPicker.tsx
+++ b/src/components/TaskPicker.tsx
@@ -13,7 +13,7 @@ import { nextRename } from "@/lib/rename";
import { imeComposing } from "@/lib/send-key";
import { FolderIcon, NewThreadButton } from "./BotProjects";
import { useShowThreads } from "@/lib/thread-preferences";
-import { attentionJumpAction, attentionOwnerName, AttentionThreadRows, crossBotAttentionThreads, threadsWhenTreeHidden, type AttentionThread } from "./SidebarBotActivity";
+import { attentionJump, attentionOwnerName, AttentionThreadRows, crossBotAttentionThreads, threadsWhenTreeHidden, type AttentionThread } from "./SidebarBotActivity";
import { formatUpdatedAt, orderedThreadList, threadByline, threadRecency, threadUpdatedLabel, useRelativeNow } from "./SidebarThreadRow";
import { Select } from "./Select";
@@ -462,7 +462,7 @@ export function TaskPicker({ bot }: { bot: Bot }) {
onDelete={(threadId) => dispatch({ type: "deleteTask", botId: bot.id, threadId })}
onMove={(threadId, projectId) => dispatch({ type: "updateTask", botId: bot.id, threadId, patch: { projectId } })}
onPin={(threadId, pinned) => dispatch({ type: "updateTask", botId: bot.id, threadId, patch: { pinned } })}
- onAttentionJump={(entry) => dispatch(attentionJumpAction(entry))}
+ onAttentionJump={(entry) => attentionJump(dispatch, entry, state)}
/>
);
}
diff --git a/src/components/room-feed/RoomFeedRow.dom.test.ts b/src/components/room-feed/RoomFeedRow.dom.test.ts
index adf0e54074..712b9dfcec 100644
--- a/src/components/room-feed/RoomFeedRow.dom.test.ts
+++ b/src/components/room-feed/RoomFeedRow.dom.test.ts
@@ -3,9 +3,10 @@ import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Bot } from "@/state/store";
-import { RoomFeedRow, type FeedRowData } from "./RoomFeedRow";
+import { RoomFeedRow, type FeedRowActions, type FeedRowData } from "./RoomFeedRow";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+vi.mock("@/state/api", async (original) => ({ ...(await original<typeof import("@/state/api")>()), api: vi.fn(() => new Promise(() => {})) }));
const NOW = Date.UTC(2026, 10, 24, 12, 0, 0);
const bot = (id: string, name: string, color: Bot["color"]) => ({ id, name, color, threadId: `${id}-main`, messages: [] } as unknown as Bot);
@@ -16,11 +17,13 @@ const row = (extra: Partial<FeedRowData> = {}): FeedRowData => ({
});
let root: Root | null = null;
-const render = (data: FeedRowData, onOpen = vi.fn(), open = false) => {
+const render = (data: FeedRowData, onOpen = vi.fn(), open = false, actions?: FeedRowActions) => {
root = createRoot(document.body.appendChild(document.createElement("ol")));
- act(() => root!.render(createElement(RoomFeedRow, { row: data, bots: BOTS, you: "Sam", now: NOW, open, onOpen })));
+ act(() => root!.render(createElement(RoomFeedRow, { row: data, groupId: "room", bots: BOTS, you: "Sam", now: NOW, open, onOpen, actions })));
return onOpen;
};
+const roomActions = (deletable = true): FeedRowActions => ({ onRename: vi.fn(), onDelete: vi.fn(), onPin: vi.fn(), onArchive: vi.fn(), deletable });
+const menuItem = (label: string) => [...document.querySelectorAll<HTMLButtonElement>("[data-thread-overlay] button")].find((button) => button.textContent?.includes(label));
const item = () => document.querySelector<HTMLElement>("[data-feed-thread]")!;
afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; });
@@ -83,4 +86,45 @@ describe("a room feed row", () => {
expect(item().querySelector("button")!.getAttribute("aria-current")).toBe("true");
expect(item().className).toContain("bg-raised");
});
+
+ it("gives a thread the sidebar row's menu from a quiet More button: pin, archive and rename it there", () => {
+ const actions = roomActions();
+ render(row({ title: "Launch plan" }), vi.fn(), false, actions);
+ const more = item().querySelector<HTMLButtonElement>('button[aria-label="Actions for Launch plan"]')!;
+ expect(more.className).toContain("group-hover:opacity-100");
+ expect(more.className).toContain("focus-visible:opacity-100");
+ expect(more.className).toContain("touch:opacity-70");
+ act(() => more.click());
+ expect(more.getAttribute("aria-expanded")).toBe("true");
+ expect(["Rename thread", "Pin", "Archive", "Delete"].every((label) => menuItem(label))).toBe(true);
+ act(() => menuItem("Pin")!.click());
+ expect(actions.onPin).toHaveBeenCalledWith(expect.objectContaining({ threadId: "t1", title: "Launch plan" }), true);
+ act(() => more.click());
+ act(() => menuItem("Archive")!.click());
+ expect(actions.onArchive).toHaveBeenCalledWith(expect.objectContaining({ threadId: "t1" }), expect.any(Number));
+ act(() => more.click());
+ act(() => menuItem("Rename thread")!.click());
+ const field = item().querySelector<HTMLInputElement>('input[aria-label="Rename thread"]')!;
+ expect(field.value).toBe("Launch plan");
+ act(() => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, "Launch week"); field.dispatchEvent(new Event("input", { bubbles: true })); });
+ act(() => { field.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })); });
+ expect(actions.onRename).toHaveBeenCalledWith(expect.objectContaining({ threadId: "t1" }), "Launch week");
+ });
+
+ it("marks a pinned thread with the pin, an archived one as archived with Unarchive in its menu, keeps a room's only thread, and gives a line on its way no menu", () => {
+ render(row({ title: "Launch plan", pinned: true, archived: true }), vi.fn(), false, roomActions());
+ expect(item().querySelector("[data-feed-pinned]")?.getAttribute("aria-label")).toBe("Pin");
+ expect(item().textContent).toContain("Archived");
+ act(() => item().querySelector<HTMLButtonElement>("button[aria-expanded]")!.click());
+ expect(menuItem("Unpin")).toBeDefined();
+ expect(menuItem("Unarchive")).toBeDefined();
+ act(() => root!.unmount());
+ render(row({ title: "Only thread" }), vi.fn(), false, roomActions(false));
+ act(() => item().querySelector<HTMLButtonElement>("button[aria-expanded]")!.click());
+ expect(menuItem("Archive")).toBeDefined();
+ expect(menuItem("Delete")).toBeUndefined();
+ act(() => root!.unmount());
+ render(row({ threadId: "" }), vi.fn(), false, roomActions());
+ expect(item().querySelector("button[aria-expanded]")).toBeNull();
+ });
});
diff --git a/src/components/room-feed/RoomFeedRow.tsx b/src/components/room-feed/RoomFeedRow.tsx
index 9ebda775d3..a37eff5943 100644
--- a/src/components/room-feed/RoomFeedRow.tsx
+++ b/src/components/room-feed/RoomFeedRow.tsx
@@ -1,17 +1,21 @@
-import { memo, useMemo } from "react";
+import { memo, useMemo, useRef, useState } from "react";
+import { MoreHorizontal, Pin } from "lucide-react";
import type { RoomThreadSpeaker } from "../../../shared/room-threads";
import { splitTranscriptCitations } from "@/lib/citations";
import { cn } from "@/lib/cn";
import { splitTranscriptAttachments } from "@/lib/composer-attachments";
+import { opensRowMenuFromKey } from "@/lib/bulk-select";
import { intlLocale, t } from "@/lib/i18n";
import { MAUS_COLOR_NAMES } from "@/lib/mascot";
import type { Bot } from "@/state/store";
import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";
import { BotAvatar } from "../Avatar";
import { ChatMarkdown } from "../ChatMarkdown";
-import { threadUpdatedLabel } from "../SidebarThreadRow";
+import { THREAD_MENU_WIDTH, threadMenuAt, threadUpdatedLabel, useThreadRowMenu, type ThreadMenuAt } from "../SidebarThreadRow";
+import { ThreadRenameField } from "./ThreadRenameField";
import { PersonFace } from "../TeamOwner";
import { ThreadRefText } from "../ThreadRefs";
+import { localizedTaskTitle } from "@/lib/task-title";
export interface FeedRowData {
threadId: string;
@@ -27,6 +31,20 @@ export interface FeedRowData {
/** The bot answering in it now. */
workingBotId: string | null;
working: boolean;
+ /** Its thread's title, which the row's menu renames; none for a line still on its way. */
+ title?: string;
+ pinned?: boolean;
+ archived?: boolean;
+}
+
+/** What a thread row's menu does, the same as the sidebar's room thread rows. */
+export interface FeedRowActions {
+ onRename: (task: { threadId: string }, title: string) => void;
+ onDelete: (task: { threadId: string }) => void;
+ onPin: (task: { threadId: string; title: string }, pinned: boolean) => void;
+ onArchive: (task: { threadId: string }, archivedAt: number | null) => void;
+ /** False while the room has only this thread, which it keeps. */
+ deletable: boolean;
}
const FACES = 3;
@@ -68,16 +86,28 @@ function previewText(row: FeedRowData, bot: boolean): string {
/** One thread in a room's feed: its first line and who said it, then how many replies it has, who wrote them and when
* the last came. The whole row opens the thread beside the feed. */
-export const RoomFeedRow = memo(function RoomFeedRow({ row, bots, you, now, open, onOpen }: {
+export const RoomFeedRow = memo(function RoomFeedRow({ row, groupId, bots, you, now, open, onOpen, actions }: {
row: FeedRowData;
+ /** The room, which the menu's thread link names. */
+ groupId: string;
bots: readonly Bot[];
/** What a person whose lines carry no name is called: the profile's name. */
you: string;
now: number;
open: boolean;
onOpen: (threadId: string) => void;
+ actions?: FeedRowActions;
}) {
const speaker = who(row.speaker, bots, you);
+ const [menu, setMenu] = useState<ThreadMenuAt | null>(null);
+ const [renaming, setRenaming] = useState(false);
+ const moreRef = useRef<HTMLButtonElement>(null);
+ const titled = row.title !== undefined && row.threadId !== "" && actions ? row.title : undefined;
+ const task = useMemo(() => ({ threadId: row.threadId, title: titled ?? "", pinned: row.pinned, archivedAt: row.archived ? 0 : undefined, busy: row.working }),
+ [row.threadId, titled, row.pinned, row.archived, row.working]);
+ const menuSheet = useThreadRowMenu({ task, displayTitle: localizedTaskTitle(task.title), ownerId: groupId, menu, setMenu, actionRef: moreRef,
+ onStartRename: () => { setMenu(null); setRenaming(true); }, onDelete: actions?.onDelete ?? (() => {}), onPin: actions?.onPin, onArchive: actions?.onArchive,
+ deletable: actions?.deletable !== false });
const fromBot = "botId" in row.speaker;
const text = useMemo(() => previewText(row, fromBot), [row, fromBot]);
const long = text.length > LONG_CHARS || text.split("\n").length > LONG_LINES;
@@ -89,24 +119,42 @@ export const RoomFeedRow = memo(function RoomFeedRow({ row, bots, you, now, open
const replies = row.replies === 1 ? t("room.feed.replyOne") : t("room.feed.replyMany", { count: row.replies });
const markLabel = row.mark === "waiting" ? t("sidebar.preview.waiting") : row.mark === "unread" ? t("task.unread") : null;
const label = [speaker.name, text || t("room.feed.attachment"), row.replies > 0 ? replies : t("room.feed.noReplies"), markLabel].filter(Boolean).join(", ");
+ const openMenuAt = (x: number, y: number) => setMenu(threadMenuAt(x, y));
+ const rename = (title: string | null) => {
+ setRenaming(false);
+ if (title && actions) actions.onRename(task, title);
+ };
return (
<li data-feed-thread={row.threadId} className={cn("group relative flex gap-3 rounded-xl px-3 py-2.5 transition-colors duration-[120ms] motion-reduce:transition-none",
- open ? "bg-raised" : "hover:bg-ink/[0.06] active:bg-ink/[0.08]")}>
- <button type="button" aria-label={label} aria-current={open ? "true" : undefined} onClick={() => onOpen(row.threadId)}
- className="absolute inset-0 z-[1] rounded-xl" />
+ open || menu ? "bg-raised" : "hover:bg-ink/[0.06] active:bg-ink/[0.08]")}>
+ {!renaming && <button type="button" aria-label={label} aria-current={open ? "true" : undefined} onClick={() => onOpen(row.threadId)}
+ onContextMenu={titled === undefined ? undefined : (event) => { event.preventDefault(); openMenuAt(event.clientX, event.clientY); }}
+ onKeyDown={titled === undefined ? undefined : (event) => {
+ if (!opensRowMenuFromKey(event.key, event.shiftKey, false)) return;
+ event.preventDefault();
+ const rect = event.currentTarget.getBoundingClientRect();
+ openMenuAt(rect.left, rect.bottom);
+ }}
+ className="absolute inset-0 z-[1] rounded-xl" />}
<span className="mt-0.5 flex shrink-0"><Face who={speaker} size={32} /></span>
- <div inert className="min-w-0 flex-1">
- <div className="flex min-w-0 items-baseline gap-2 pe-5">
+ <div inert={!renaming} className="min-w-0 flex-1">
+ <div className={cn("flex min-w-0 items-baseline gap-2", titled === undefined ? "pe-5" : "pe-8")}>
<Name who={speaker} />
<time dateTime={new Date(row.at).toISOString()} title={new Date(row.at).toLocaleString(intlLocale())}
className="shrink-0 text-[12px] font-medium leading-4 text-ink-tertiary tabular-nums">{threadUpdatedLabel(row.at, now)}</time>
+ {row.pinned && <Pin size={11} data-feed-pinned="" className="shrink-0 self-center text-ink-secondary" aria-label={t("sidebar.bot.pin")} />}
+ {row.archived && <span className="min-w-0 truncate text-[12px] leading-4 text-ink-tertiary">{t("task.archived")}</span>}
+ {markLabel && <span aria-hidden="true" data-feed-mark={row.mark} title={markLabel}
+ className={cn("size-2 shrink-0 self-center rounded-full", row.mark === "waiting" ? "bg-warning" : "bg-accent")} />}
</div>
- <div dir="auto" className={cn("chat-text mt-0.5 max-h-[110px] overflow-hidden text-[15px] leading-[22px] text-ink [overflow-wrap:anywhere]",
- long && "[mask-image:linear-gradient(to_bottom,black_60%,transparent)]", !text && "text-ink-secondary")}>
- {!text ? t("room.feed.attachment")
- : fromBot ? <ChatMarkdown text={text} mentionPeers={bots} everyone />
- : <div className="whitespace-pre-wrap"><ThreadRefText text={text} peers={bots} everyone /></div>}
- </div>
+ {renaming && titled !== undefined ? <ThreadRenameField title={titled} onDone={rename} className="mt-1 w-full" /> : (
+ <div dir="auto" className={cn("chat-text mt-0.5 max-h-[110px] overflow-hidden text-[15px] leading-[22px] text-ink [overflow-wrap:anywhere]",
+ long && "[mask-image:linear-gradient(to_bottom,black_60%,transparent)]", !text && "text-ink-secondary", row.archived && "text-ink-secondary")}>
+ {!text ? t("room.feed.attachment")
+ : fromBot ? <ChatMarkdown text={text} mentionPeers={bots} everyone />
+ : <div className="whitespace-pre-wrap"><ThreadRefText text={text} peers={bots} everyone /></div>}
+ </div>
+ )}
<div className="mt-1.5 flex min-w-0 items-center gap-2 text-[12px] leading-4">
{row.working ? (
<span className="flex min-w-0 items-center gap-1.5 text-ink-secondary">
@@ -124,8 +172,13 @@ export const RoomFeedRow = memo(function RoomFeedRow({ row, bots, you, now, open
) : <span className="text-ink-tertiary">{t("room.feed.noReplies")}</span>}
</div>
</div>
- {markLabel && <span aria-hidden="true" data-feed-mark={row.mark} title={markLabel}
- className={cn("absolute end-3 top-3.5 size-2 rounded-full", row.mark === "waiting" ? "bg-warning" : "bg-accent")} />}
+ {titled !== undefined && !renaming && <button ref={moreRef} type="button" aria-label={t("task.actions", { title: localizedTaskTitle(titled) })} aria-expanded={Boolean(menu)}
+ onClick={(event) => { if (menu) { setMenu(null); return; } const rect = event.currentTarget.getBoundingClientRect(); openMenuAt(rect.right - THREAD_MENU_WIDTH, rect.bottom); }}
+ className={cn("absolute end-1.5 top-1.5 z-[2] flex size-7 items-center justify-center rounded-md text-ink-secondary opacity-0 transition-opacity duration-[120ms] hover:bg-ink/[0.06] hover:text-ink focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100 max-md:opacity-70 touch:size-10 touch:opacity-70 motion-reduce:transition-none",
+ menu && "opacity-100")}>
+ <MoreHorizontal size={16} aria-hidden="true" />
+ </button>}
+ {menuSheet}
</li>
);
});
diff --git a/src/components/room-feed/RoomFeedView.tsx b/src/components/room-feed/RoomFeedView.tsx
index 936dc042c0..927a6f5f4d 100644
--- a/src/components/room-feed/RoomFeedView.tsx
+++ b/src/components/room-feed/RoomFeedView.tsx
@@ -3,10 +3,11 @@ import { useAdvancedMode } from "@/lib/interface-mode";
import { t } from "@/lib/i18n";
import { openFeedThread } from "@/lib/room-feed";
import { simpleRoomHeader } from "@/lib/room-panel";
-import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
+import { roomThreadAttention, roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
import { useComposerDockPad } from "@/lib/composer-dock";
import { sameDrawnBots } from "@/lib/drawn-bots";
import type { Bot, Group } from "@/state/store";
+import { useStoreRef } from "@/state/store-ref";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
import { ChatErrorBanner, ChatNotice } from "../ChatErrorBanner";
import { ChatBackdrop, GlassBar, GlassScrollFrame } from "../GlassScrollFrame";
@@ -16,9 +17,10 @@ import { RoomChiefAbsent } from "../RoomChiefAbsent";
import { RoomHeader } from "../RoomHeader";
import { RoomHoldsBanner } from "../RoomHoldsBanner";
import { RoomWorkingFolder } from "../RoomWorkingFolder";
-import { useRelativeNow } from "../SidebarThreadRow";
+import { roomThreadRowActions } from "../SidebarGroupThreadList";
+import { isArchived, useRelativeNow } from "../SidebarThreadRow";
import { FeedComposer } from "./FeedComposer";
-import { RoomFeedRow, type FeedRowData } from "./RoomFeedRow";
+import { RoomFeedRow, type FeedRowActions, type FeedRowData } from "./RoomFeedRow";
import { useRoomThreads, type FeedThread } from "./use-room-threads";
/** How near the foot the feed counts as being read there, so a new thread keeps it at the foot. */
@@ -26,24 +28,31 @@ const FOOT_PX = 48;
/** Only the person scrolling takes the feed off its foot; a row opening beside it or a window resize never does. */
const INTENT_MS = 1_000;
-const toRow = (group: Group, { task, summary }: FeedThread): FeedRowData => ({
- threadId: task.threadId,
- speaker: summary.first.speaker,
- text: summary.first.text,
- clipped: summary.first.clipped,
- at: summary.first.at,
- replies: summary.replies,
- lastReplyAt: summary.lastReplyAt,
- repliers: summary.repliers,
- mark: task.activity === "waiting-on-you" ? "waiting" : task.unread ? "unread" : null,
- working: roomThreadWorking(group, task.threadId),
- workingBotId: roomThreadSpeakerId(group, task.threadId),
-});
+function toRow(group: Group, { task, summary }: FeedThread, bots: readonly Bot[]): FeedRowData {
+ const { waiting, unread } = roomThreadAttention(group, task, bots);
+ return {
+ threadId: task.threadId,
+ speaker: summary.first.speaker,
+ text: summary.first.text,
+ clipped: summary.first.clipped,
+ at: summary.first.at,
+ replies: summary.replies,
+ lastReplyAt: summary.lastReplyAt,
+ repliers: summary.repliers,
+ mark: waiting ? "waiting" : unread ? "unread" : null,
+ working: roomThreadWorking(group, task.threadId),
+ workingBotId: roomThreadSpeakerId(group, task.threadId),
+ title: task.title,
+ pinned: task.pinned === true,
+ archived: isArchived(task),
+ };
+}
/** A room as one feed of its threads, oldest at the top and the newest just above the composer, where a line starts a
* new thread. A row opens its thread beside the feed; the room's current thread, which is everyone's, never moves. */
export function RoomFeedView({ group }: { group: Group }) {
const dispatch = useStoreDispatch();
+ const store = useStoreRef();
const bots = useStoreSelector((state) => state.bots, sameDrawnBots);
const you = useStoreSelector((state) => state.config?.profile?.name?.trim()) || t("room.feed.you");
const error = useStoreSelector((state) => state.error);
@@ -60,16 +69,29 @@ export function RoomFeedView({ group }: { group: Group }) {
const composerDockRef = useRef<HTMLDivElement>(null);
const composerDock = useComposerDockPad(composerDockRef);
const now = useRelativeNow();
- const { threads, failed, retry } = useRoomThreads(group);
+ const hasArchived = (group.tasks ?? []).some(isArchived);
+ const deletable = (group.tasks?.length ?? 1) > 1;
+ const [showArchived, setShowArchived] = useState(false);
+ const { threads, failed, retry } = useRoomThreads(group, showArchived && hasArchived);
+ const actions = useMemo<FeedRowActions>(() => {
+ const room = roomThreadRowActions(group.id, dispatch);
+ const leave = (threadId: string) => { if (store.state().forkPanel?.threadId === threadId) dispatch({ type: "closeForkPanel" }); };
+ return {
+ ...room,
+ onDelete: (task) => { leave(task.threadId); room.onDelete(task); },
+ onArchive: (task, archivedAt) => { if (archivedAt !== null) leave(task.threadId); room.onArchive(task, archivedAt); },
+ deletable,
+ };
+ }, [group.id, dispatch, store, deletable]);
const [pending, setPending] = useState<{ text: string; at: number; threadId: string | null } | null>(null);
const rows = useMemo(() => {
if (!threads) return null;
- const listed = threads.map((thread) => toRow(group, thread));
+ const listed = threads.map((thread) => toRow(group, thread, bots));
if (!pending || (pending.threadId && listed.some((row) => row.threadId === pending.threadId))) return listed;
return [...listed, { threadId: pending.threadId ?? "", speaker: { person: {} }, text: pending.text, at: pending.at, replies: 0, lastReplyAt: null,
repliers: [], mark: null, working: false, workingBotId: null } satisfies FeedRowData];
- }, [threads, pending, group]);
+ }, [threads, pending, group, bots]);
const waiting = useCallback((text: string | null) => {
setPending(text === null ? null : { text, at: Date.now(), threadId: null });
@@ -110,13 +132,17 @@ export function RoomFeedView({ group }: { group: Group }) {
{!simpleHeader && <RoomBulletin group={group} remoteClient={remoteClient} />}
{folderOpen && <div className="w-full px-5"><div className="mb-1"><RoomWorkingFolder group={group} /></div></div>}
</GlassBar>
- <div ref={scrollRef} className="glass-scroller h-full overflow-x-hidden overflow-y-auto px-4 [overflow-anchor:none]"
+ <div ref={scrollRef} data-feed-fade="" className="glass-scroller h-full overflow-x-hidden overflow-y-auto px-4 [overflow-anchor:none]"
onWheel={moved} onTouchMove={moved} onKeyDown={moved} onPointerDown={moved}
onScroll={(event) => {
const el = event.currentTarget, foot = el.scrollHeight - el.scrollTop - el.clientHeight < FOOT_PX;
if (foot || Date.now() - scrolledAt.current < INTENT_MS) atFoot.current = foot;
}}>
<div ref={contentRef} className="glass-scroller-content chat-column flex min-h-full w-full flex-col justify-end" style={{ paddingBottom: composerDock.pad }}>
+ {hasArchived && rows !== null && <button type="button" data-feed-archived-toggle="" aria-pressed={showArchived} onClick={() => setShowArchived((shown) => !shown)}
+ className="mt-2 inline-flex h-7 items-center self-center rounded-md px-2 text-[13px] font-medium leading-4 text-ink-secondary hover:text-ink">
+ {showArchived ? t("room.feed.hideArchived") : t("room.feed.showArchived")}
+ </button>}
{rows === null ? (
failed && (
<p role="alert" className="flex items-center justify-center gap-2 py-6 text-[13px] text-ink-secondary">
@@ -129,7 +155,8 @@ export function RoomFeedView({ group }: { group: Group }) {
) : (
<ol aria-label={t("room.feed.aria", { name: group.name })} className="flex flex-col gap-0.5 py-2">
{rows.map((row) => (
- <RoomFeedRow key={row.threadId || "pending"} row={row} bots={bots} you={you} now={now} open={row.threadId !== "" && row.threadId === openThread} onOpen={open} />
+ <RoomFeedRow key={row.threadId || "pending"} row={row} groupId={group.id} bots={bots} you={you} now={now} open={row.threadId !== "" && row.threadId === openThread}
+ onOpen={open} actions={actions} />
))}
</ol>
)}
diff --git a/src/components/room-feed/ThreadPanelHeading.tsx b/src/components/room-feed/ThreadPanelHeading.tsx
new file mode 100644
index 0000000000..87b06de057
--- /dev/null
+++ b/src/components/room-feed/ThreadPanelHeading.tsx
@@ -0,0 +1,59 @@
+import { useMemo, useRef, useState } from "react";
+import { Copy, Download, MoreHorizontal } from "lucide-react";
+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 { 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 }) {
+ const store = useStoreRef();
+ const dispatch = store.dispatch;
+ const [menu, setMenu] = useState<ThreadMenuAt | null>(null);
+ const [renaming, setRenaming] = useState(false);
+ const moreRef = useRef<HTMLButtonElement>(null);
+ const title = localizedTaskTitle(task.title);
+ const row = useMemo(() => ({ threadId: task.threadId, title: task.title, pinned: task.pinned, archivedAt: task.archivedAt, busy: working }),
+ [task.threadId, task.title, task.pinned, task.archivedAt, working]);
+ 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 menuSheet = useThreadRowMenu({
+ task: row, displayTitle: title, ownerId: group.id, menu, setMenu, actionRef: moreRef,
+ onStartRename: () => { setMenu(null); setRenaming(true); },
+ onDelete: (thread) => { close(); actions.onDelete(thread); },
+ onPin: actions.onPin,
+ onArchive: (thread, archivedAt) => { if (archivedAt !== null) close(); actions.onArchive(thread, archivedAt); },
+ deletable: (group.tasks?.length ?? 1) > 1,
+ extra: (done) => <>
+ <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>
+ <button type="button" disabled={messages.length === 0} className={ITEM}
+ onClick={() => { done(); downloadMarkdownTranscript(slugifyTranscriptFilename(task.title || group.name), markdown()); }}>
+ <Download size={16} aria-hidden="true" />{t("chat.export.download")}
+ </button>
+ </>,
+ });
+ return <>
+ <div className="min-w-0 flex-1">
+ {renaming
+ ? <ThreadRenameField title={task.title} className="block h-5 w-full px-1 py-0 text-[15px] font-semibold leading-5" onDone={(next) => { setRenaming(false); if (next) actions.onRename(task, next); }} />
+ : <h2 dir="auto" title={title} className="truncate text-[15px] font-semibold leading-5 text-ink">{title}</h2>}
+ <p dir="auto" className="truncate text-[12px] leading-4 text-ink-secondary">{group.name}</p>
+ </div>
+ <button ref={moreRef} type="button" aria-label={t("task.actions", { title })} title={t("task.actions", { title })} aria-expanded={Boolean(menu)}
+ className="ui-icon-button shrink-0"
+ onClick={(event) => { if (menu) { setMenu(null); return; } const rect = event.currentTarget.getBoundingClientRect(); setMenu(threadMenuAt(rect.right - THREAD_MENU_WIDTH, rect.bottom)); }}>
+ <MoreHorizontal size={16} aria-hidden="true" />
+ </button>
+ {menuSheet}
+ </>;
+}
diff --git a/src/components/room-feed/ThreadRenameField.tsx b/src/components/room-feed/ThreadRenameField.tsx
new file mode 100644
index 0000000000..126e7c6750
--- /dev/null
+++ b/src/components/room-feed/ThreadRenameField.tsx
@@ -0,0 +1,24 @@
+import { useRef, useState } from "react";
+import { t } from "@/lib/i18n";
+import { cn } from "@/lib/cn";
+import { nextRename } from "@/lib/rename";
+import { imeComposing } from "@/lib/send-key";
+
+/** A thread's title being renamed in place, as the sidebar's thread row does it: Enter or leaving the field saves,
+ * Escape keeps the old title. `onDone` gets the new title, or null when nothing changed. */
+export function ThreadRenameField({ title, onDone, className }: { title: string; onDone: (title: string | null) => void; className?: string }) {
+ const [draft, setDraft] = useState(title);
+ const finished = useRef(false);
+ const finish = (save: boolean) => {
+ if (finished.current) return;
+ finished.current = true;
+ onDone(save ? nextRename(title, draft) : null);
+ };
+ return <input autoFocus value={draft} maxLength={80} aria-label={t("task.renameAria")} dir="auto"
+ onFocus={(event) => event.currentTarget.select()} onChange={(event) => setDraft(event.target.value)} onBlur={() => finish(true)}
+ onKeyDown={(event) => {
+ if (imeComposing(event.nativeEvent)) { event.stopPropagation(); return; }
+ if (event.key === "Enter") { event.preventDefault(); finish(true); } else if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); finish(false); }
+ }}
+ className={cn("min-w-0 rounded border border-accent/50 bg-inset px-2 py-1 text-[13px] text-ink outline-none", className)} />;
+}
diff --git a/src/components/room-feed/use-room-threads.test.ts b/src/components/room-feed/use-room-threads.test.ts
new file mode 100644
index 0000000000..6f898f3fc8
--- /dev/null
+++ b/src/components/room-feed/use-room-threads.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import type { RoomThreadSummary } from "../../../shared/room-threads";
+import type { GroupTask } from "@/state/store";
+import { feedThreads } from "./use-room-threads";
+
+const task = (threadId: string, extra: Partial<GroupTask> = {}): GroupTask => ({ threadId, title: threadId, createdAt: 1, ...extra });
+const summary = (threadId: string, at: number): RoomThreadSummary =>
+ ({ threadId, first: { text: threadId, speaker: { person: {} }, at }, replies: 0, lastReplyAt: null, repliers: [] });
+
+describe("the feed's threads", () => {
+ it("leaves archived threads out unless asked for them, oldest first either way", () => {
+ const tasks = [task("old"), task("put-away", { archivedAt: 0 }), task("new")];
+ const summaries = [summary("new", 30), summary("put-away", 20), summary("old", 10)];
+ expect(feedThreads(tasks, summaries).map((thread) => thread.task.threadId)).toEqual(["old", "new"]);
+ expect(feedThreads(tasks, summaries, true).map((thread) => thread.task.threadId)).toEqual(["old", "put-away", "new"]);
+ });
+});
diff --git a/src/components/room-feed/use-room-threads.ts b/src/components/room-feed/use-room-threads.ts
index f83907ea20..ed6e6ce95c 100644
--- a/src/components/room-feed/use-room-threads.ts
+++ b/src/components/room-feed/use-room-threads.ts
@@ -11,9 +11,9 @@ export interface FeedThread {
}
/** The room's threads that have a first line, oldest first, so the newest sits at the foot of the feed and a thread
- * stays in its place when a reply comes in. */
-export function feedThreads(tasks: readonly GroupTask[], summaries: readonly RoomThreadSummary[]): FeedThread[] {
- const byThread = new Map(tasks.filter((task) => task.archivedAt === undefined).map((task) => [task.threadId, task]));
+ * stays in its place when a reply comes in. Archived ones only when asked for. */
+export function feedThreads(tasks: readonly GroupTask[], summaries: readonly RoomThreadSummary[], archived = false): FeedThread[] {
+ const byThread = new Map(tasks.filter((task) => archived || task.archivedAt === undefined).map((task) => [task.threadId, task]));
return summaries.flatMap((summary) => {
const task = byThread.get(summary.threadId);
return task && summary.first ? [{ task, summary: summary as FeedThread["summary"] }] : [];
@@ -25,8 +25,8 @@ const stamps = (tasks: readonly GroupTask[] | undefined) =>
/** The room's thread summaries, asked again whenever one of its threads moves; the last answer stays on screen while
* the next is on its way, and an answer for an older ask is dropped. */
-export function useRoomThreads(group: Pick<Group, "id" | "tasks">) {
- const [answer, setAnswer] = useState<{ groupId: string; threads: RoomThreadSummary[] } | null>(null);
+export function useRoomThreads(group: Pick<Group, "id" | "tasks">, archived = false) {
+ const [answer, setAnswer] = useState<{ groupId: string; archived: boolean; threads: RoomThreadSummary[] } | null>(null);
const [failed, setFailed] = useState(false);
const [attempt, setAttempt] = useState(0);
const signature = stamps(group.tasks);
@@ -36,12 +36,12 @@ export function useRoomThreads(group: Pick<Group, "id" | "tasks">) {
useEffect(() => {
let current = true;
const timer = setTimeout(() => {
- api<RoomThreadSummariesResponse>(`/api/groups/${group.id}/threads/summary`)
- .then((response) => { if (current) { setAnswer({ groupId: group.id, threads: response.threads }); setFailed(false); } })
+ api<RoomThreadSummariesResponse>(`/api/groups/${group.id}/threads/summary${archived ? "?archived=1" : ""}`)
+ .then((response) => { if (current) { setAnswer({ groupId: group.id, archived, threads: response.threads }); setFailed(false); } })
.catch(() => { if (current) setFailed(true); });
}, settled.current ? SETTLE_MS : 0);
return () => { current = false; clearTimeout(timer); };
- }, [group.id, signature, attempt]);
- const threads = useMemo(() => (loaded ? feedThreads(group.tasks ?? [], answer.threads) : null), [loaded, group.tasks, answer]);
+ }, [group.id, signature, attempt, archived]);
+ const threads = useMemo(() => (loaded ? feedThreads(group.tasks ?? [], answer.threads, archived && answer.archived) : null), [loaded, group.tasks, answer, archived]);
return { threads, failed: failed && !loaded, retry: () => setAttempt((count) => count + 1) };
}
diff --git a/src/lib/room-feed.test.ts b/src/lib/room-feed.test.ts
index 3ad00107ec..25b79e9792 100644
--- a/src/lib/room-feed.test.ts
+++ b/src/lib/room-feed.test.ts
@@ -2,7 +2,8 @@ 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, openThreadBeside, roomFeedShows } from "./room-feed";
+import { feedPreview, feedThreadAction, openRoomThreadThen, openThreadBeside, roomFeedShows } from "./room-feed";
+import { roomThreadAttention } from "./room-threads";
const on = { features: { roomFeed: true } } as AppState["config"];
const off = { features: { roomFeed: false } } as AppState["config"];
@@ -102,3 +103,25 @@ describe("a feed room's sidebar line", () => {
expect(feedPreview({ tasks: [tasks[2]!] })).toBeUndefined();
});
});
+
+describe("a room's run opened from the calendar", () => {
+ it("shows the room first and keeps the thread open beside the feed, and keeps today's order with the switch off", () => {
+ const sent: unknown[] = [];
+ const showRoom = (id: string) => sent.push({ type: "select", id });
+ openRoomThreadThen((action) => sent.push(action), state(on), "room", "other", showRoom);
+ expect(sent).toEqual([{ type: "select", id: "room" }, { type: "openForkPanel", kind: "group", ownerId: "room", threadId: "other" }]);
+ sent.length = 0;
+ openRoomThreadThen((action) => sent.push(action), state(off), "room", "other", showRoom);
+ expect(sent).toEqual([{ type: "switchGroupTask", groupId: "room", threadId: "other" }, { type: "select", id: "room" }]);
+ });
+});
+
+describe("a room thread's mark", () => {
+ it("waits on the person when the thread does or the bot speaking in it does, and falls back to the room's unread for its current thread", () => {
+ const busy = room({ tasks: [{ threadId: "current", title: "", createdAt: 1, busyBotId: "kiwi", working: true }, { threadId: "other", title: "", createdAt: 2, activity: "waiting-on-you" }], unread: true });
+ expect(roomThreadAttention(busy, busy.tasks![0]!, [{ id: "kiwi", activity: "waiting-on-you" }])).toEqual({ waiting: true, unread: true });
+ expect(roomThreadAttention(busy, busy.tasks![0]!, [{ id: "kiwi", activity: "working" }])).toEqual({ waiting: false, unread: true });
+ expect(roomThreadAttention(busy, busy.tasks![1]!, [])).toEqual({ waiting: true, unread: false });
+ expect(roomThreadAttention(busy, { ...busy.tasks![1]!, activity: undefined, unread: true }, [])).toEqual({ waiting: false, unread: true });
+ });
+});
diff --git a/src/lib/room-feed.ts b/src/lib/room-feed.ts
index c5ca6d0a66..bacc4636d3 100644
--- a/src/lib/room-feed.ts
+++ b/src/lib/room-feed.ts
@@ -30,6 +30,19 @@ export function feedThreadAction(action: Action, state: Pick<AppState, "config"
return null;
}
+/** A room's thread opened from a page that then shows the room (`showRoom` selects it): with the feed, the room comes
+ * first so the thread stays open beside it. */
+export function openRoomThreadThen(dispatch: (action: Action) => void, state: Pick<AppState, "config" | "groups">, groupId: string, threadId: string,
+ showRoom: (groupId: string) => void): void {
+ if (!roomFeedShows(state.config, state.groups.find((group) => group.id === groupId))) {
+ dispatch({ type: "switchGroupTask", groupId, threadId });
+ showRoom(groupId);
+ return;
+ }
+ showRoom(groupId);
+ dispatch(openFeedThread(groupId, threadId));
+}
+
/** With the room feed on, 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. */
diff --git a/src/lib/room-threads.ts b/src/lib/room-threads.ts
index 8f1fcf82c7..6a67912477 100644
--- a/src/lib/room-threads.ts
+++ b/src/lib/room-threads.ts
@@ -25,6 +25,15 @@ export function roomThreadSpeakerId(group: RoomThreads, threadId: string): strin
return threadId === group.threadId ? group.busyBotId ?? null : null;
}
+/** Waiting when the thread, or the bot speaking in it, waits on the person. A server that marks no thread unread marks
+ * the room, which stands for its current thread. */
+export function roomThreadAttention(group: RoomThreads & Pick<Group, "unread">, task: Pick<GroupTask, "threadId" | "unread" | "activity">,
+ bots: readonly Pick<Bot, "id" | "activity">[]): { waiting: boolean; unread: boolean | undefined } {
+ const speakerId = roomThreadSpeakerId(group, task.threadId);
+ const speakerWaits = Boolean(speakerId) && bots.find((bot) => bot.id === speakerId)?.activity === "waiting-on-you";
+ return { waiting: speakerWaits || task.activity === "waiting-on-you", unread: task.unread ?? (task.threadId === group.threadId && group.unread) };
+}
+
export function roomSpeakerIds(group: RoomThreads): string[] {
const ids = [group.busyBotId, ...(group.tasks ?? []).map((task) => task.busyBotId)]
.filter((id): id is string => typeof id === "string" && id.length > 0);
diff --git a/src/locales/de.json b/src/locales/de.json
index dd41053422..2a81f8bbab 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -4377,6 +4377,8 @@
"room.feed.empty": "Noch keine Threads. Schreib unten, um einen zu beginnen.",
"room.feed.loadFailed": "Die Threads dieses Raums konnten nicht geladen werden.",
"room.feed.startFailed": "Der Thread konnte nicht begonnen werden. Prüfe deine Verbindung und versuche es erneut.",
+ "room.feed.showArchived": "Archivierte Threads anzeigen",
+ "room.feed.hideArchived": "Archivierte Threads ausblenden",
"room.thread.panel": "Thread",
"room.thread.close": "Thread schließen",
"room.thread.resize": "Thread-Breite ändern",
diff --git a/src/locales/en.json b/src/locales/en.json
index 0efb4ccdd6..d66e73d19d 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -11981,6 +11981,8 @@
"room.feed.empty": "No threads yet. Write below to start one.",
"room.feed.loadFailed": "Couldn't load this room's threads.",
"room.feed.startFailed": "Couldn't start a thread. Check your connection and try again.",
+ "room.feed.showArchived": "Show archived threads",
+ "room.feed.hideArchived": "Hide archived threads",
"room.thread.panel": "Thread",
"room.thread.close": "Close thread",
"room.thread.resize": "Resize thread",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 213b6cf5a9..1335fbf219 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -11981,6 +11981,8 @@
"room.feed.empty": "Nenhuma conversa ainda. Escreva abaixo para começar uma.",
"room.feed.loadFailed": "Não foi possível carregar as conversas deste grupo.",
"room.feed.startFailed": "Não foi possível começar a conversa. Verifique sua conexão e tente de novo.",
+ "room.feed.showArchived": "Mostrar conversas arquivadas",
+ "room.feed.hideArchived": "Ocultar conversas arquivadas",
"room.thread.panel": "Conversa",
"room.thread.close": "Fechar conversa",
"room.thread.resize": "Redimensionar conversa",
diff --git a/src/styles.css b/src/styles.css
index 21a2ad7a98..81fdb75294 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -2108,6 +2108,13 @@ body {
-webkit-mask-image: linear-gradient(to bottom, transparent calc(var(--glass-top, 0px) - var(--top-fade)), #000 var(--glass-top, 0px));
mask-image: linear-gradient(to bottom, transparent calc(var(--glass-top, 0px) - var(--top-fade)), #000 var(--glass-top, 0px));
}
+/* A room's feed of threads: its header is plain words, so nothing that scrolls under it shows through. Rows fade in over
+ the last --feed-fade above the bar's edge, where the top row rests; a mask, so any skin's ground shows. */
+.glass-scroller[data-feed-fade] {
+ --feed-fade: 12px;
+ -webkit-mask-image: linear-gradient(to bottom, transparent calc(var(--glass-top, 0px) - var(--feed-fade)), #000 var(--glass-top, 0px));
+ mask-image: linear-gradient(to bottom, transparent calc(var(--glass-top, 0px) - var(--feed-fade)), #000 var(--glass-top, 0px));
+}
[data-chathead-float] {
pointer-events: none;
}