A local-first multi-agent app development platform, built on PenguinHarness
/**
* Single-column sidebar, top to bottom:
* Project switcher -> nav: New chat (a draft on the Project's new-chat defaults), always pinned
* in its fixed slot above the scroll area, then Agents → Evaluation Center. Each page entry is
* pinned (always shown) or collapsible (folded away by a nav-row-wide chevron button under the
* collapsible area: arrow up = click to collapse, arrow down while collapsed = the way back);
* Agents, Models and Plugins are pinned by default, a row's hover pin button or a drag across
* the areas moves an entry, and both the fold and the pin choices persist in localStorage
* (nav-group-collapse.ts) -> Session area with three grouping
* modes (chosen in the section header's list options; the
* choice and each Project's group collapse and pin state persist in localStorage): by Workspace
* (the default; groups loaded Sessions by their
* Workspace path, temporary workspaces merged into one trailing group, header "+" starts a
* draft in that Workspace), by Agent (group header = Agent name + new chat + Agent settings;
* shows all Agents, including empty groups), or by time (last day / last month / earlier,
* bucketed on last activity; the buckets span every Agent, so the Subagents / Scheduled /
* Archived folders and the paging row sit below them as one Project-wide set). Groups can
* be pinned via the header's hover pin toggle: pinned groups sort before unpinned within
* their mode, keeping each partition's own order — the time buckets excepted, whose order
* IS the timeline and which therefore carry no pin. Conversations can be pinned too (row
* context menu; persisted per Project in
* localStorage): pinned rows bubble to the top of their group's active list. Each row's
* trailing slot shows the compact last-active time at rest and swaps to archive + delete
* icon buttons on hover/focus; the full set (pin, rename, archive, delete) opens as a
* context menu on right-click, Shift+F10, or a press-and-hold on touch. The header's
* batch control beside the search turns the rows into pickers — ticked rows raise a bar
* above the list that archives, unarchives or deletes them together (the requirement
* box's own batch bar), and leaving the mode drops the ticks.
* -> bottom user row, which opens the shared account menu (user-menu.tsx).
* In company mode the shape holds but the objects change: the organization switcher stands
* where the Project switcher stands, "New channel" where "New chat" is, the organization's
* six pages in the nav group, and the channel list where the conversation list is, followed
* by the organization's own 工位 group — one row per employee
* (features/company/channel-sidebar.tsx, features/company/org-session-groups.tsx). The
* development list is the user's OWN conversations only: an organization's desk, ticket and
* sub-sessions are left out of its fetches and totals by the server, and out of every group,
* bucket and folder here should one still arrive.
* Desktop keeps it pinned as the left column; mobile puts the whole thing in a drawer.
* New chats always enter draft state (/chat/new; a group header's "+" names its group's Agent or
* Workspace in route state): Model / Workspace / approval mode are all chosen on the draft input
* card, so there's no longer a separate "quick / advanced" pair of new-chat dialogs.
* The column's look — its frame, page rows, list header, controls and conversation rows — is the
* UI package's (SidebarFrame, NavRow, SessionRow); this file binds them to the app's state. On the
* column's muted surface a hover and a selection are washes of the ink (NAV_FILL), and a running
* status is a small mark, never a block of colour.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import type { DragEvent as ReactDragEvent, ReactNode } from "react";
import { useLocation, useMatch, useNavigate } from "react-router";
import type { SessionCategory, SessionCategoryCounts, SessionInfo } from "@adelie/server/api";
import {
AgentAvatar,
Badge,
Button,
ConfirmModal,
Dropdown,
FolderSection,
GlyphIcon,
GroupHeader,
ICONS,
ICON_SIZE,
Input,
Menu,
MenuItem,
MenuLabel,
MenuRadioItem,
MenuSeparator,
Modal,
MoreRow,
NAV_FILL,
NavRow,
SearchInput,
Segmented,
SessionRow,
SidebarAccountButton,
SidebarControl,
SidebarFrame,
SidebarListHeader,
SidebarNavArea,
SidebarNavEntry,
SidebarNavGroup,
SidebarSwitcherButton,
SkeletonList,
UpdateDot,
UserAvatar,
toastInfo,
toastSuccess,
} from "@adelie/ui";
import type { SidebarDropTarget } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { formatRelativeShort } from "../../lib/format";
import { onCommand } from "../../lib/shortcuts/dispatcher";
import { useShortcutTitle } from "../../lib/shortcuts/use-keymap";
import {
sessionActivityLabel,
sessionBackgroundTasks,
sessionRowActivity,
} from "../../lib/session-activity";
import type { SessionActivity } from "../../lib/session-activity";
import { forgetSession, noteSessionSeen, useSessionSeen } from "../../lib/session-seen";
import { apiErrorText } from "../../lib/api-error";
import { splitBatchOutcome } from "../../lib/batch-outcome";
import { toneInk } from "../../lib/tone";
import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { agentDisplayName, projectDisplayName, useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
import {
FOLDER_CATEGORIES,
SIDEBAR_PAGE_SIZE,
TIME_FOLDERS_GROUP_KEY,
aggregateWorkspaceCounts,
aggregateWorkspaceLatest,
clampGroupPage,
completeWorkspaceGroups,
cutAtWatermark,
foldedShare,
groupPageCount,
groupPageOf,
groupPageSlice,
groupSessionsByTime,
groupSessionsByWorkspace,
isFolderOnly,
matchesSessionQuery,
partitionSessions,
revealPlan,
sessionCategory,
totalCategoryCounts,
withoutOrgSessions,
workspaceGroupKey,
workspaceLabel,
} from "../../lib/session-grouping";
import type { FolderCategory, SessionPartition } from "../../lib/session-grouping";
import { machineForSession } from "../../lib/session-machines";
import { backgroundSourceMark } from "../../lib/session-source-mark";
import { nameOnMachine } from "../../lib/workspace-machines";
import {
initialNavGroupCollapsed,
initialNavPinOverrides,
isNavPinned,
navEntryKeysFor,
splitNavEntries,
storeNavGroupCollapsed,
storeNavPinOverrides,
withNavPinned,
} from "../../lib/nav-group-collapse";
import type { NavEntryKey, NavGroupKey } from "../../lib/nav-group-collapse";
import {
loadPinnedSessions,
removePinnedSession,
savePinnedSessions,
togglePinnedSession,
} from "../../lib/pinned-sessions";
import {
dropHiddenWorkspaces,
hideWorkspace,
loadWorkspaceRegistry,
mergeRegisteredWorkspaces,
registerWorkspace,
saveWorkspaceRegistry,
setWorkspaceAlias,
} from "../../lib/workspace-registry";
import type { WorkspaceEntry } from "../../lib/workspace-registry";
import {
applyManualReorder,
initialSessionSortMode,
loadSessionOrder,
moveInSequence,
orderSessionRows,
removeFromSessionOrder,
saveSessionOrder,
storeSessionSortMode,
} from "../../lib/session-order";
import type { SessionSortMode } from "../../lib/session-order";
import {
commitGroupOrder,
isOrderableGroupMode,
loadGroupOrder,
orderGroups,
saveGroupOrder,
} from "../../lib/group-order";
import { HOVER_ROW_ACTIONS, contextMenuActions, sessionRowActions } from "../ui/session-row-menu";
import type { SessionRowAction } from "../ui/session-row-menu";
import { NAV_ICONS } from "../../lib/nav-icons";
import {
GROUP_MODE_ICONS,
SORT_MODE_ICONS,
GroupPager,
Icon,
initialGroupMode,
newEntityForGroupMode,
storeGroupMode,
} from "../ui/group-list";
import type { GroupMode } from "../ui/group-list";
import { writeClipboard } from "../../lib/clipboard";
import { Truncated } from "../ui/truncated";
import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";
import { MessagingBindingModal } from "../../features/messaging/messaging-binding-modal";
import { WorkspaceSelect } from "../../features/chat/workspace-select";
import { clearDraft, sessionDraftKey } from "../../features/chat/draft-cache";
import {
draftSessionTitle,
removeDraftSession,
useDraftSessions,
} from "../../features/chat/draft-sessions";
import type { DraftSessionEntry } from "../../features/chat/draft-sessions";
import { prepareNewChatDraft } from "../../features/chat/new-chat";
import { docksOnScreen, openPanel } from "../../features/dock/dock-state";
import { dockWorkspace } from "../../features/dock/dock-terminal";
import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";
import { UserMenu } from "./user-menu";
import { PinnedBalanceBadge } from "../../features/models/group-balance";
import { isCurrentPath, renderRouterLink } from "./router-link";
import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";
import { useProjectSchedules } from "../../features/schedules/schedule-store";
import { useCompany } from "../../state/company";
import { NoOrganizationsSidebar, OrgSwitcher } from "../../features/company/org-switcher";
import { CompanyBetaBadge } from "../../features/company/company-beta";
import { ChannelSidebar } from "../../features/company/channel-sidebar";
import { OrgSessionGroups } from "../../features/company/org-session-groups";
import { COMPANY_NAV_ICONS } from "../../features/company/company-nav-icons";
import {
COMPANY_NAV_KEYS,
isOrgRoute,
orgPagePath,
parseOrgKey,
} from "../../features/company/company-nav";
import type { WorkMode } from "../../features/company/company-nav";
/** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */
export const NEW_CHAT_ICON = "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";
/** The workspace group's overflow-menu trigger: three FILLED dots (the stroke version read too faint at this size). */
function EllipsisGlyph({ size = 16 }: { size?: number }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
<circle cx="5" cy="12" r="2" />
<circle cx="12" cy="12" r="2" />
<circle cx="19" cy="12" r="2" />
</svg>
);
}
/**
* Private drag payload type of a manual session reorder. Deliberately NOT `text/plain`:
* the composer is a controlled textarea with no drop guard, and a native text drop
* mutates its value and fires `input` — a mis-aimed reorder would paste a session id
* into the user's message. Nothing outside these rows reads this type.
*/
const SESSION_DRAG_MIME = "application/x-penguin-session-id";
/** Private drag payload type of a group reorder (same reasoning as SESSION_DRAG_MIME: never text/plain). */
const GROUP_DRAG_MIME = "application/x-penguin-group-key";
/**
* Is the drag in flight one of our group reorders? `types` is readable during dragover
* (unlike getData), so the payload GROUP_DRAG_MIME carries is what authorizes the drop
* rather than React state alone: a `dragGroup` left behind by a source header that
* unmounted mid-drag can no longer make the sidebar swallow an unrelated drag — a file
* from the desktop, a Session row — paint a phantom drop line, and commit on release.
*/
const isGroupDrag = (e: ReactDragEvent): boolean => e.dataTransfer.types.includes(GROUP_DRAG_MIME);
/** Private drag payload type of a nav entry moved between the pinned and collapsible areas (never text/plain, as above). */
const NAV_DRAG_MIME = "application/x-penguin-nav-entry";
/** Is the drag in flight a nav entry of ours? Authorizes a nav drop the way isGroupDrag authorizes a group drop. */
const isNavDrag = (e: ReactDragEvent): boolean => e.dataTransfer.types.includes(NAV_DRAG_MIME);
/** The two nav areas a dragged entry can be dropped into. */
type NavArea = "pinned" | "collapsible";
/** A page entry of the development nav: every entry but New chat, which keeps its fixed slot. */
const isNavPage = (key: NavEntryKey): key is NavGroupKey => key !== "newChat";
/** Manual drag-reordering needs a pointer that can drag (HTML5 DnD never fires from touch) — the outline rail's query. */
const DRAG_POINTER_QUERY = "(hover: hover) and (pointer: fine)";
/**
* Mode-dependent create glyph: the entity's own icon (folder / robot) shrunk toward
* the top-left, with a plus badge in the freed bottom-right corner — no knockout disc
* needed (a background-colored punch would mismatch the hover pill), so it stays
* legible at icon size in both themes. Stroke style matches the shared Icon set.
*/
function AddBadgeIcon({ base, size = 15 }: { base: string; size?: number }) {
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.7"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
>
<g transform="translate(-1 -1) scale(0.82)">
<path d={base} />
</g>
<path d="M18.5 15.5v6M15.5 18.5h6" strokeWidth="2" />
</svg>
);
}
/**
* A group header's trailing action (new chat, Agent settings): a square on the column's hover
* wash, the subtle glyph deepening under the pointer.
*/
const GROUP_ACTION_CLASS =
"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-fg-subtle transition-colors duration-150 hover:bg-fg/7 hover:text-fg";
/**
* Collapsed-group and pinned-group persistence (survives a refresh), one storage key
* per Project and concern — group keys are Agent ids / Workspace paths, which are
* Project-scoped. Both grouping modes share one set per concern (their key spaces
* never collide); stray keys left by deleted Agents or Workspaces are harmless
* (never matched) and the per-Project sets stay tiny.
*/
const collapsedGroupsKey = (projectId: string) => `penguin.sidebarCollapsedGroups.${projectId}`;
const pinnedGroupsKey = (projectId: string) => `penguin.sidebarPinnedGroups.${projectId}`;
/**
* Opened folder-only groups, in a set of their own because the two say opposite things: a
* group that opens by default stores the keys the user CLOSED, while a folder-only group
* (collapsed by default — session-grouping.ts's isFolderOnly) stores the keys the user
* OPENED. A group that gains an active row stops being folder-only and is simply read out of
* the other set again, which is why neither set ever has to be rewritten.
*/
const expandedFolderOnlyGroupsKey = (projectId: string) =>
`penguin.sidebarExpandedFolderGroups.${projectId}`;
/** Reads a persisted group-key set (no Project yet / corrupted storage degrade to empty). */
function loadGroupSet(storageKey: string | null): ReadonlySet<string> {
if (!storageKey) return new Set();
try {
const parsed: unknown = JSON.parse(localStorage.getItem(storageKey) ?? "[]");
return new Set(
Array.isArray(parsed) ? parsed.filter((x): x is string => typeof x === "string") : [],
);
} catch {
return new Set();
}
}
function saveGroupSet(storageKey: string | null, next: ReadonlySet<string>): void {
if (!storageKey) return;
try {
localStorage.setItem(storageKey, JSON.stringify([...next]));
} catch {
/* best-effort persistence (quota/private mode) */
}
}
/**
* Open-state key of a collapsed folder (background / archived) inside a group: each folder has its
* own state. "\0" never appears in Agent ids or Workspace paths, so the composite never collides
* across groups or with plain group keys.
*/
const folderKey = (groupKey: string, category: FolderCategory) => `${category}\0${groupKey}`;
/** Collapse-state key of the parked-drafts group ("\0" keeps it clear of Agent ids and Workspace paths). */
const DRAFTS_GROUP_KEY = "\0drafts";
/**
* One group's active and folded shares — what decides whether it is folder-only, and the
* count its dimmed header then carries. The server's exact per-category totals are raised,
* category by category, by the rows already in memory: the counts are taken at fetch time, so
* a conversation created since exists only as a loaded row (the rule a workspace group's
* header count already applies to its active share).
*/
const groupShares = (
totals: SessionCategoryCounts | undefined,
rows: readonly SessionInfo[],
): { active: number; folded: number } => {
const counts: SessionCategoryCounts = { active: 0, background: 0, archived: 0 };
for (const s of rows) {
const category = sessionCategory(s);
if (category !== null) counts[category] += 1;
}
counts.active = Math.max(counts.active, totals?.active ?? 0);
for (const category of FOLDER_CATEGORIES)
counts[category] = Math.max(counts[category], totals?.[category] ?? 0);
return { active: counts.active, folded: foldedShare(counts) };
};
/** Standing "no Session is scheduled", so the first render has something to hold before any answer. */
const NO_SCHEDULED_SESSIONS: ReadonlySet<string> = new Set();
export function Sidebar({
onNavigate,
onCollapse,
initialSearchOpen = false,
}: {
onNavigate?: () => void;
onCollapse?: () => void;
/** Mount with the session search open and focused: the search shortcut pressed on the collapsed rail. */
initialSearchOpen?: boolean;
}) {
const navigate = useNavigate();
const location = useLocation();
const { user, sessionVia } = useAuth();
const { locale } = useLocale();
const {
projects,
currentProject,
setCurrentProjectId,
reloadProjects,
agents,
setCurrentAgentId,
} = useProject();
const {
sessions: allSessions,
byAgent: allByAgent,
countsByAgent,
workspaceCountsByAgent,
workspaceLatestByAgent,
machineLabels,
isLoadedFor,
hasMoreFor,
activityWatermarkFor,
loadMoreFor,
loading,
remove,
replace,
} = useSessions();
const chatMatch = useMatch("/chat/:sessionId");
const activeSessionId = chatMatch?.params.sessionId ?? null;
const [projectOpen, setProjectOpen] = useState(false);
const [createProjectOpen, setCreateProjectOpen] = useState(false);
const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);
/** The badges over the update and to-do trails (use-update-badges.ts); the avatar's dot follows the update flow's offer / restart states. */
const badges = useUpdateBadges();
const company = useCompany();
/** Company mode swaps the Project switcher, the page nav and the session list for their organization forms. */
const inCompany = company.workMode === "company";
/** The organization the company nav points at: the open one, else the one last opened (the switcher names the same). */
const navOrg = parseOrgKey(company.currentOrgKey ?? company.lastOrgKey);
/**
* The rows this list renders: the user's OWN conversations. An organization's desk and
* ticket Sessions (`company` Sessions, marked by `orgId` too, and by the durable
* `client === "org"` stamp that outlives the organization) are driven by its scheduler and
* are reached as themselves in company
* mode — a desk from the 工位 group, a ticket session from its ticket. The store's own
* fetches already leave them out, totals and Workspace stamps included (the server's
* `excludeOrg`), so the counts below are the list's exact share; this filter is for a row
* that entered by another door (the chat page's deep-link self-heal), applied once, at the
* source, or the dropped row would still conjure the Workspace group, Agent group or time
* bucket it belongs to. It applies whatever the company-mode switches say (see
* withoutOrgSessions): this list is the user's conversations, and a switch about the shell
* does not turn a scheduler's Session into one.
*/
const sessions = useMemo(() => withoutOrgSessions(allSessions), [allSessions]);
const byAgent = useMemo(() => {
const map = new Map<string, SessionInfo[]>();
for (const [agentId, rows] of allByAgent) map.set(agentId, withoutOrgSessions(rows));
return map;
}, [allByAgent]);
const currentProjectId = currentProject?.projectId ?? null;
/** This Project's read markers; re-renders the rows whenever one is stamped. */
const sessionSeen = useSessionSeen(currentProjectId);
// The Project's scheduled tasks, shared with the dock's schedules panel through one store, so
// that neither surface can take the other's answer away. The scope is the Project, not the
// current Agent: this list draws every Agent's Sessions in every grouping mode, so whether a
// row wears the mark must not depend on which Agent is current — the chat page moves that to
// whatever conversation is open, and with a per-Agent list every other Agent's rows lost their
// marks until the user came back to them. Re-read on every navigation: opening a conversation
// is the moment a task may just have been created or switched off.
const { items: projectSchedules } = useProjectSchedules(currentProjectId, activeSessionId ?? "");
// The Sessions wearing the alarm clock: one bound task with a next fire time is enough. The
// store re-renders these rows on every refresh (a navigation, a schedule event, a turn ending,
// the panel's poll), and the server recomputes `nextFireAt` on each listing, so a task that
// fired for the last time loses its mark at the next refresh.
const pendingScheduled = useMemo(
() => (projectSchedules === null ? null : pendingScheduleSessions(projectSchedules)),
[projectSchedules],
);
// A null list means "this Project has not been read yet", never "this Project has no tasks":
// reading it as the second blanks every alarm in the list for as long as a request takes. The
// marks on screen stand until a real answer replaces them, which is the standing the pin and
// the relay glyph get for free by being fields of the row itself.
const lastScheduledRef = useRef<ReadonlySet<string>>(NO_SCHEDULED_SESSIONS);
useEffect(() => {
if (pendingScheduled !== null) lastScheduledRef.current = pendingScheduled;
}, [pendingScheduled]);
const scheduledSessions = pendingScheduled ?? lastScheduledRef.current;
const collapseStoreKey = currentProjectId === null ? null : collapsedGroupsKey(currentProjectId);
const pinStoreKey = currentProjectId === null ? null : pinnedGroupsKey(currentProjectId);
const folderOnlyStoreKey =
currentProjectId === null ? null : expandedFolderOnlyGroupsKey(currentProjectId);
/** Folded collapsible nav area (company mode: the whole nav group); expanded by default, the choice persists across sessions. */
const [navCollapsed, setNavCollapsed] = useState(initialNavGroupCollapsed);
/** The user's changes to which nav entries are pinned (the defaults live in nav-group-collapse.ts); persisted like the fold. */
const [navPins, setNavPins] = useState(initialNavPinOverrides);
/** Nav entry being dragged across the areas, and the area a drop would move it into. */
const [navDrag, setNavDrag] = useState<NavEntryKey | null>(null);
const [navDropArea, setNavDropArea] = useState<NavArea | null>(null);
/**
* The entry whose pin button takes focus once its row re-mounts in the other area. Moving
* an entry moves its row to another container, and the button that had focus goes with the
* old one — a keyboard user would be dropped onto <body>.
*/
const pinFocusRef = useRef<NavEntryKey | null>(null);
/** The chevron toggle: where focus goes when the moved row lands in a folded (inert) area. */
const navToggleRef = useRef<HTMLButtonElement | null>(null);
/** Grouping mode of the Session list (Workspace by default; the choice persists across sessions). */
const [groupMode, setGroupModeState] = useState<GroupMode>(initialGroupMode);
/** Collapsed groups (expanded by default), keyed by Agent id or Workspace group key depending on the mode; persisted per Project. */
const [collapsedGroups, setCollapsedGroups] = useState<ReadonlySet<string>>(() =>
loadGroupSet(collapseStoreKey),
);
/** Pinned groups (sorted before unpinned within their mode), keyed like collapsedGroups; persisted per Project. */
const [pinnedGroups, setPinnedGroups] = useState<ReadonlySet<string>>(() =>
loadGroupSet(pinStoreKey),
);
/** Folder-only groups the user has opened (they render collapsed by default), keyed like collapsedGroups but persisted in their own set — the two record opposite choices (see expandedFolderOnlyGroupsKey). */
const [expandedFolderOnlyGroups, setExpandedFolderOnlyGroups] = useState<ReadonlySet<string>>(
() => loadGroupSet(folderOnlyStoreKey),
);
/** Pinned conversations (bubbled to the top of their group's active list), Session ids; persisted per Project frontend-side (lib/pinned-sessions.ts). */
const [pinnedSessions, setPinnedSessions] = useState<ReadonlySet<string>>(() =>
loadPinnedSessions(currentProjectId),
);
/** Row sort mode ("recent" default / "manual" drag order; the choice persists across sessions like the grouping mode). */
const [sortMode, setSortModeState] = useState<SessionSortMode>(initialSessionSortMode);
/** Manual row order (Session ids; only relative order within a co-rendered partition matters); persisted per Project AND grouping mode — the modes cut different partitions. */
const [sessionOrder, setSessionOrder] = useState<readonly string[]>(() =>
loadSessionOrder(currentProjectId, initialGroupMode()),
);
/**
* Manual GROUP order (Workspace keys / Agent ids), persisted per Project and grouping
* mode like the row order. Independent of `sortMode`: dragging a group is itself the
* intent, so there is no second toggle — an empty array is the identity and the list
* keeps its automatic sort. Empty in time mode, whose buckets are chronological
* (group-order.ts).
*/
const [groupOrder, setGroupOrder] = useState<readonly string[]>(() =>
loadGroupOrder(currentProjectId, initialGroupMode()),
);
/** Manually-added Workspaces (header 新建工作区; render as empty groups until Sessions exist, with optional display aliases); persisted per Project. */
const [registeredWorkspaces, setRegisteredWorkspaces] = useState<readonly WorkspaceEntry[]>(() =>
loadWorkspaceRegistry(currentProjectId),
);
/** Registered Workspace being renamed (alias edit; null = none) and the alias being typed. The machine is half of which directory this is. */
const [renamingWorkspace, setRenamingWorkspace] = useState<{
path: string;
machineId: string | null;
} | null>(null);
const [workspaceAliasText, setWorkspaceAliasText] = useState("");
/** Registered Workspace pending removal confirmation (null = none); label = the group's displayed name for the confirm copy. */
const [deletingWorkspace, setDeletingWorkspace] = useState<{
path: string;
machineId: string | null;
label: string;
} | null>(null);
/** Live title search: the input's visibility and its query (transient — never persisted). */
const [searchOpen, setSearchOpen] = useState(initialSearchOpen);
const searchInputRef = useRef<HTMLInputElement | null>(null);
const rootRef = useRef<HTMLDivElement | null>(null);
const searchTitle = useShortcutTitle(S.chat.searchSessions, "sessions.search");
const newChatTitle = useShortcutTitle(S.chat.newSessionMenu, "chat.new");
const collapseTitle = useShortcutTitle(S.nav.collapseSidebar, "sidebar.toggle");
// The sessions.search command: open the field, or put the caret back into an open one. It
// declines (the browser's own key runs) when the field could not be seen: company mode has
// no session list, and the pinned sidebar is `display: none` below the `md` breakpoint while
// still mounted. Re-registered when the field opens or closes so the handler reads the state.
useEffect(
() =>
onCommand("sessions.search", () => {
if (inCompany) return false;
if (rootRef.current !== null && rootRef.current.getClientRects().length === 0) return false;
if (searchOpen) searchInputRef.current?.focus();
else setSearchOpen(true);
}),
[searchOpen, inCompany],
);
const [searchQuery, setSearchQuery] = useState("");
/** Header list-settings dropdown (grouping + sort radios). */
const [listSettingsOpen, setListSettingsOpen] = useState(false);
/**
* Whether a pointer that can drag is present (the outline rail's HOVER_QUERY idiom).
* HTML5 drag-and-drop never fires from touch, and the sort mode is one GLOBAL
* preference: offering 手动排序 in the mobile drawer would freeze that list in an
* order the phone has no gesture to change — and flip the desktop too. The option is
* hidden there; an already-stored "manual" degrades to recency on such a device.
*/
const [canDrag, setCanDrag] = useState(() => window.matchMedia(DRAG_POINTER_QUERY).matches);
useEffect(() => {
const mq = window.matchMedia(DRAG_POINTER_QUERY);
const onChange = (e: MediaQueryListEvent) => setCanDrag(e.matches);
mq.addEventListener("change", onChange);
return () => mq.removeEventListener("change", onChange);
}, []);
/** Row being dragged (manual sort only) and the current drop hint (target row + which edge). */
const [dragSession, setDragSession] = useState<{ scope: string; id: string } | null>(null);
const [dropHint, setDropHint] = useState<{ id: string; after: boolean } | null>(null);
/** Group header being dragged (its key) and the current group drop hint (target group + which edge). */
const [dragGroup, setDragGroup] = useState<string | null>(null);
const [groupDropHint, setGroupDropHint] = useState<{ key: string; after: boolean } | null>(null);
/** Expanded folders (background / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */
const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());
/** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` — the row disables and reads "loading" so a page that lands entirely in other groups still visibly did something. */
const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());
/** Per-group display cap for active rows (keyed by group key; absent = SIDEBAR_PAGE_SIZE). "More" raises it a page at a time. */
const [groupCaps, setGroupCaps] = useState<ReadonlyMap<string, number>>(new Map());
/** The same display cap per folder (keyed by folderKey; absent = SIDEBAR_PAGE_SIZE), so an expanded folder reveals a page at a time instead of everything a fetch returned. */
const [folderCaps, setFolderCaps] = useState<ReadonlyMap<string, number>>(new Map());
/** Which PAGE of groups renders (#139: dozens of Agents/Workspaces made the list too tall to scan), 0-based; reset per Project and on a mode switch, and clamped at render to the pages that still exist. */
const [groupPage, setGroupPage] = useState(0);
// Project resolved on first load / switched: swap in that Project's persisted collapse/pin
// sets, row and group orders and registered Workspaces — in the render that sees the switch
// (React re-renders before committing), not in an effect: an effect runs a commit late, and
// that commit would draw the new Project's list with the previous Project's groups.
const [setsFor, setSetsFor] = useState(currentProjectId);
if (setsFor !== currentProjectId) {
setSetsFor(currentProjectId);
setCollapsedGroups(loadGroupSet(collapseStoreKey));
setPinnedGroups(loadGroupSet(pinStoreKey));
setExpandedFolderOnlyGroups(loadGroupSet(folderOnlyStoreKey));
setPinnedSessions(loadPinnedSessions(currentProjectId));
setSessionOrder(loadSessionOrder(currentProjectId, groupMode));
setGroupOrder(loadGroupOrder(currentProjectId, groupMode));
setRegisteredWorkspaces(loadWorkspaceRegistry(currentProjectId));
setGroupPage(0);
// The other Project's groups are gone, and so is any meaning their reveal state had.
setGroupCaps(new Map());
setFolderCaps(new Map());
}
/** Session pending delete confirmation (null = none). */
const [deletingSession, setDeletingSession] = useState<SessionInfo | null>(null);
const [deletingBusy, setDeletingBusy] = useState(false);
/**
* Why the last confirmed deletion was refused, in the server's own words. It belongs to the
* dialog, not to a toast: nothing was deleted, so the conversation is still there and the only
* next step is the same button again — the rename dialog above answers a refused write the very
* same way.
*/
const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);
/**
* Batch processing (the header control beside 搜索会话): while it is on every row is a picker and
* the bar above the list acts on the ticked ones. Both are transient — leaving the mode drops the
* ticks — because a selection left behind in localStorage would act on rows the reader picked in
* another session of the app. The delete confirmation is the batch's own (one dialog over N rows,
* rather than N dialogs).
*/
const [batchMode, setBatchMode] = useState(false);
const [batchSelected, setBatchSelected] = useState<ReadonlySet<string>>(new Set());
const [batchBusy, setBatchBusy] = useState(false);
const [batchConfirmDelete, setBatchConfirmDelete] = useState(false);
/**
* Why the last confirmed batch delete did not finish — the server's own words with the number of
* rows it refused. Same rule as the single delete above (the reason belongs beside the button
* that retries it), and a batch needs it even more: its refusal is partial, and what is left
* ticked is exactly what did not go.
*/
const [batchDeleteRefusal, setBatchDeleteRefusal] = useState<string | null>(null);
/**
* Why the last batch archive / unarchive did not finish — the same rule, one host further out:
* those two act straight from the bar (no card asks first), so the bar is what a refusal has to
* be read from, under the buttons that sent it. The ticks it left behind are the retry.
*/
const [batchArchiveRefusal, setBatchArchiveRefusal] = useState<string | null>(null);
/** Parked draft conversation pending delete confirmation (null = none). */
const [deletingDraft, setDeletingDraft] = useState<DraftSessionEntry | null>(null);
/** Parked draft conversations of this user × Project, newest first (reactive module store). */
const draftEntries = useDraftSessions(user?.userId ?? null, currentProjectId);
/** Session currently being renamed (null = none) and the title being typed. */
const [renamingSession, setRenamingSession] = useState<SessionInfo | null>(null);
const [renameText, setRenameText] = useState("");
const [renameBusy, setRenameBusy] = useState(false);
const [renameError, setRenameError] = useState<string | null>(null);
/** Session whose messaging-binding dialog is open (null = none). */
const [messagingSession, setMessagingSession] = useState<SessionInfo | null>(null);
const setGroupMode = (mode: GroupMode) => {
storeGroupMode(mode);
setGroupModeState(mode);
// The modes have unrelated group lists: go back to the first page, drop the per-group
// reveal state (a cap keyed by an Agent id means nothing to a Workspace group), and
// swap in this mode's own manual order (the stored sequence is read within partitions,
// whose boundaries are exactly what the mode decides — one shared array would scramble).
setSessionOrder(loadSessionOrder(currentProjectId, mode));
setGroupOrder(loadGroupOrder(currentProjectId, mode));
setGroupPage(0);
setGroupCaps(new Map());
setFolderCaps(new Map());
};
/** Collapse/expand the page-nav group (same store-then-set convention as setGroupMode). */
const toggleNavGroup = () => {
const next = !navCollapsed;
storeNavGroupCollapsed(next);
setNavCollapsed(next);
};
/** Pin or unpin one nav entry: the pin button and a drop across the areas both land here. */
const setNavPinned = (key: NavEntryKey, pinned: boolean) => {
const next = withNavPinned(navPins, key, pinned);
if (next === navPins) return;
storeNavPinOverrides(next);
setNavPins(next);
};
/**
* Drag wiring of one development-mode nav entry: the row is its own handle. Offered only
* where a pointer that can drag exists (HTML5 drag-and-drop never fires from touch); the
* pin button is the way everywhere, and the only one there.
*/
const navEntryDragProps = (key: NavEntryKey) =>
canDrag
? {
draggable: true,
onDragStart: (e: ReactDragEvent) => {
e.dataTransfer.setData(NAV_DRAG_MIME, key);
e.dataTransfer.effectAllowed = "move";
setNavDrag(key);
},
onDragEnd: () => {
setNavDrag(null);
setNavDropArea(null);
},
}
: {};
/**
* Drop wiring of one nav area. Only a drag that would move the entry to this side is
* accepted, so dropping a row back into its own area is not a drop at all; where inside the
* area it lands is not asked, since both areas keep manifest order.
*/
const navAreaDrop = (area: NavArea): SidebarDropTarget => ({
over: navDropArea === area,
onDragOver: (e) => {
if (navDrag === null || !isNavDrag(e)) return;
if (isNavPinned(navDrag, navPins) === (area === "pinned")) return;
e.preventDefault();
// The effect must be one effectAllowed permits, or the drop never fires (groupDragProps).
e.dataTransfer.dropEffect = "move";
setNavDropArea(area);
},
// Crossing onto one of the area's own rows fires dragleave too; still inside is no change.
onDragLeave: (e) => {
const to = e.relatedTarget;
if (to instanceof Node && e.currentTarget.contains(to)) return;
setNavDropArea((prev) => (prev === area ? null : prev));
},
onDrop: (e) => {
if (navDrag === null || !isNavDrag(e)) return;
e.preventDefault();
setNavPinned(navDrag, area === "pinned");
setNavDrag(null);
setNavDropArea(null);
},
});
/** Workspace-mode per-group exact server totals (folded from the per-Agent per-Workspace counts). */
const workspaceGroupCounts = useMemo(
() => aggregateWorkspaceCounts(workspaceCountsByAgent),
[workspaceCountsByAgent],
);
/** Workspace-mode per-group newest-Session stamps (folded the same way): a group's recency before any of its rows are loaded. */
const workspaceGroupLatest = useMemo(
() => aggregateWorkspaceLatest(workspaceLatestByAgent),
[workspaceLatestByAgent],
);
/**
* Workspace groups (workspace mode): the loaded rows' groups, completed with every
* Workspace the server's counts know (empty until their rows page in — the initial load
* is each Agent's ten newest conversations, which touch only a few of dozens of
* Workspaces), by recency with the temp group last, plus the manually-added Workspaces
* as empty groups behind them (newest registration first) — and minus the ones the user
* removed from the sidebar (删除工作区), which takes a group with Sessions with it and
* gives it back the moment a chat is created there again (dropHiddenWorkspaces).
*/
const workspaceGroups = useMemo(
() =>
dropHiddenWorkspaces(
mergeRegisteredWorkspaces(
completeWorkspaceGroups(
// A Workspace is a directory on a machine: rows from two machines that share a path
// string are two groups, and the "+" of each opens a chat on its own machine.
groupSessionsByWorkspace(sessions, (s) => machineForSession(s.sessionId)),
workspaceGroupCounts,
workspaceGroupLatest,
),
registeredWorkspaces,
),
registeredWorkspaces,
(s) => s.createdAt,
),
[sessions, workspaceGroupCounts, workspaceGroupLatest, registeredWorkspaces],
);
/**
* The folder-only groups of each mode: group key → the conversations folded inside it. A
* group with no active conversation of its own but rows inside its folders — a Workspace
* only subagents ever ran in, an Agent that has only ever been evaluated — folds up, sorts
* behind the other groups of its mode and wears a dimmed header carrying that count. (The
* Test Workspaces an evaluation creates per Case × Run never form groups of their own: they
* fold into the merged temp group, see session-grouping.ts's isTempWorkspace.)
*
* Read off the group lists BEFORE they are ordered: the ordering consumes this, so it
* cannot be what feeds it. The search query is deliberately not part of it either — a query
* hides rows rather than emptying a group, and a list that folded and reshuffled itself as
* the user typed would be unreadable.
*/
const folderOnlyAgents = useMemo(() => {
const out = new Map<string, number>();
for (const agent of agents) {
const shares = groupShares(
countsByAgent.get(agent.agentId),
byAgent.get(agent.agentId) ?? [],
);
if (isFolderOnly(shares.active, shares.folded)) out.set(agent.agentId, shares.folded);
}
return out;
}, [agents, countsByAgent, byAgent]);
const folderOnlyWorkspaceGroups = useMemo(() => {
const out = new Map<string, number>();
for (const group of workspaceGroups) {
const shares = groupShares(workspaceGroupCounts.get(group.key)?.totals, group.sessions);
if (isFolderOnly(shares.active, shares.folded)) out.set(group.key, shares.folded);
}
return out;
}, [workspaceGroups, workspaceGroupCounts]);
// Pinned groups first within each mode, then the manual drag order within each pin
// partition, and the folder-only groups behind the rest of the unpinned cluster (a pinned
// one stays where it was pinned). Nothing dragged yet = an empty order = the automatic
// sort untouched (recency for Workspace groups with the temp group last, the configured
// Agent order for Agents), which is also what a group with no stored place falls back to.
// The stored array belongs to the mode it was loaded for: handing an Agent list an
// order of Workspace keys is a no-op only as long as the two key namespaces cannot
// collide, and it costs the empty-order fast path on every render of the other mode.
const orderedAgents = useMemo(
() =>
orderGroups(agents, (a) => a.agentId, {
pinned: pinnedGroups,
order: groupMode === "agent" ? groupOrder : [],
demote: (a) => folderOnlyAgents.has(a.agentId),
}),
[agents, pinnedGroups, groupOrder, groupMode, folderOnlyAgents],
);
const orderedWorkspaceGroups = useMemo(
() =>
orderGroups(workspaceGroups, (g) => g.key, {
pinned: pinnedGroups,
order: groupMode === "workspace" ? groupOrder : [],
demote: (g) => folderOnlyWorkspaceGroups.has(g.key),
}),
[workspaceGroups, pinnedGroups, groupOrder, groupMode, folderOnlyWorkspaceGroups],
);
// The FULL displayed group sequences a drop commits — every group of the mode, not the
// page of groups on screen (see groupDragProps).
const agentGroupSequence = useMemo(() => orderedAgents.map((a) => a.agentId), [orderedAgents]);
const workspaceGroupSequence = useMemo(
() => orderedWorkspaceGroups.map((g) => g.key),
[orderedWorkspaceGroups],
);
/** Group key a Session's FOLDERS hang off under the current mode (the archived-open state); time mode keeps one shared set for the whole Project. */
const sessionGroupKey = (s: SessionInfo) =>
groupMode === "agent"
? s.agentId
: groupMode === "time"
? TIME_FOLDERS_GROUP_KEY
: workspaceGroupKey(s.workspace, machineForSession(s.sessionId));
/**
* Collapse/expand a group. A folder-only group flips the OTHER set: it is collapsed by
* default, so what persists is the fact that the user opened it (expandedFolderOnlyGroupsKey).
*/
const toggleGroup = (key: string, folderOnly = false) => {
// Inert while searching: groups render force-opened then, so a click would change
// nothing on screen while silently rewriting the persisted collapse state — the user
// would find groups flipped once the query clears.
if (searching) return;
// Computed outside the state updater (theme.tsx convention): the persistence write is a
// side effect, and updaters must stay pure (double-invoked in StrictMode).
const next = new Set(folderOnly ? expandedFolderOnlyGroups : collapsedGroups);
if (next.has(key)) next.delete(key);
else next.add(key);
if (folderOnly) {
setExpandedFolderOnlyGroups(next);
saveGroupSet(folderOnlyStoreKey, next);
} else {
setCollapsedGroups(next);
saveGroupSet(collapseStoreKey, next);
}
};
/** Pin / unpin a group (same toggle-and-persist convention as toggleGroup). */
const togglePin = (key: string) => {
const next = new Set(pinnedGroups);
if (next.has(key)) next.delete(key);
else next.add(key);
setPinnedGroups(next);
saveGroupSet(pinStoreKey, next);
};
/** Pin / unpin one conversation (row menu; same toggle-and-persist convention). */
const toggleSessionPin = (sessionId: string) => {
const next = togglePinnedSession(pinnedSessions, sessionId);
setPinnedSessions(next);
savePinnedSessions(currentProjectId, next);
};
/** Switch the row sort mode (store-then-set convention). Leaving manual KEEPS the stored order — toggling back restores it. */
const setSortMode = (mode: SessionSortMode) => {
storeSessionSortMode(mode);
setSortModeState(mode);
};
/** Search active = a non-blank query is live-filtering the list. */
const searching = searchQuery.trim() !== "";
/**
* Group pagination (Workspace / Agent modes — time mode has at most three buckets and
* pages nothing). A pure display window: the manual group order still commits over the
* FULL sequence (see groupDragProps), and no group's data loading depends on which page
* it sits on. Search bypasses paging entirely — a match on page 3 would read as no match
* at all, which is the same reason a collapsed group is forced open while searching.
*/
const pagedGroupTotal =
groupMode === "agent"
? orderedAgents.length
: groupMode === "workspace"
? orderedWorkspaceGroups.length
: 0;
const groupPageTotal = groupPageCount(pagedGroupTotal);
/** The page actually on screen: the stored one, pinned inside the pages that still exist. */
const shownGroupPage = clampGroupPage(groupPage, pagedGroupTotal);
/** The groups to render: this page's slice, or every match while searching. */
const groupsOnPage = <T,>(groups: T[]): T[] =>
searching ? groups : groupPageSlice(groups, shownGroupPage);
/** Pager below the group list — rendered only once the groups overflow a single page. */
const groupPagerRow = () =>
!searching && groupPageTotal > 1 ? (
<GroupPager page={shownGroupPage} pageCount={groupPageTotal} onChange={setGroupPage} />
) : null;
/** The sort actually applied: a stored "manual" needs a drag-capable pointer to mean anything (see canDrag). */
const effectiveSortMode: SessionSortMode = sortMode === "manual" && canDrag ? "manual" : "recent";
/** Title filter of one group's loaded rows (search only sees loaded pages — there is no server-side search). */
const filterRows = (rows: SessionInfo[]) =>
searching ? rows.filter((s) => matchesSessionQuery(s, searchQuery)) : rows;
/**
* Time mode's split of the loaded rows: the buckets take the active conversations, the
* shared folders below take the rest. Deliberately NOT memoized — the bucket boundary is
* `Date.now()`, and a memo would freeze it at its last dependency change; the compact
* relative timestamps rendered beside these rows are recomputed every render for exactly
* the same reason. Null outside time mode, so no other mode pays for the two passes.
*/
const timeParts = groupMode === "time" ? partitionSessions(filterRows(sessions)) : null;
/** Time mode's exact server share, Project-wide: its buckets span every Agent, so the shared folders read the summed counts. */
const projectCounts = totalCategoryCounts(countsByAgent);
/** Agents holding rows of a category anywhere in this Project — time mode's fetch fan-out (the counts are kept in step locally, so they cover freshly added rows too). */
const projectAgentsFor = (category: SessionCategory) =>
[...countsByAgent].filter(([, counts]) => counts[category] > 0).map(([agentId]) => agentId);
/**
* Time mode's rows, cut at the list's watermark BEFORE bucketing. Every Agent (on every
* machine) pages its own stream, so only the rows above the most recent cursor that still
* has more are a true prefix of the Project's activity order; the rows below it stay in
* memory until "load more" lowers it. That is what makes the list grow only at its bottom —
* a fetched page can no longer land rows in "Last day" above an "Earlier" the user is
* reading. A search sees every loaded row (a hidden match would read as no match), and the
* open conversation always shows.
*/
const timeVisible =
timeParts === null
? []
: cutAtWatermark(
timeParts.active,
searching ? null : activityWatermarkFor(projectAgentsFor("active"), "active"),
activeSessionId,
);
const timeGroups = timeParts === null ? [] : groupSessionsByTime(timeVisible, Date.now());
/** Agents with an unfetched active page left; the whole-list "More" of time mode pages all of them at once. */
const timeMoreAgents = projectAgentsFor("active").filter((id) => hasMoreFor(id, "active"));
/** A time bucket's rows as a group partition: the buckets carry active conversations only. */
const bucketPartition = (rows: SessionInfo[]): SessionPartition => ({
active: rows,
background: [],
archived: [],
});
/** Close the search row and drop the filter (the toggle button, the clear ×, and Escape all land here). */
const closeSearch = () => {
setSearchOpen(false);
setSearchQuery("");
};
/**
* Drop of a manual drag: commit the reordered partition sequence into the stored
* order (the sequence moves to the array's front; only relative order within a
* co-rendered partition is ever read, so other groups' ids are unaffected).
*/
const commitManualDrop = (partitionIds: readonly string[], targetId: string, after: boolean) => {
if (!dragSession) return;
const seq = moveInSequence(partitionIds, dragSession.id, targetId, after);
// Identity guard: a drop that changes nothing (self-drop, or landing where the row
// already sat) must not rewrite and persist a fresh array.
if (seq === partitionIds) return;
const next = applyManualReorder(sessionOrder, seq);
setSessionOrder(next);
saveSessionOrder(currentProjectId, groupMode, next);
};
/**
* Drop of a group drag: splice the dragged group in beside its target and persist.
*
* `sequence` is the mode's FULL rendered key list — every group of the mode, not the
* page of groups on screen — and commitGroupOrder folds it into the stored array
* where those groups already render, so a Workspace whose Sessions have not paged in
* yet keeps its stored place instead of being pushed behind the ones that have.
*
* Nothing prunes here. Deciding a stored key is DEAD needs the mode's complete live
* key set, and this component cannot prove one — the per-Workspace counts that look
* like a proof are filtered by the "show CLI sessions" preference, and a settled Agent
* fetch may simply have failed. Stale keys are inert (group-order.ts), so the cost of
* keeping them is a map entry; the cost of a wrong proof is an arrangement the user
* cannot get back.
*/
const commitGroupDrop = (sequence: readonly string[], targetKey: string, after: boolean) => {
if (dragGroup === null) return;
const next = commitGroupOrder(groupOrder, sequence, dragGroup, targetKey, after);
// Identity guard, as for rows: a drop that changes nothing must not persist a fresh array.
if (next === groupOrder) return;
setGroupOrder(next);
saveGroupOrder(currentProjectId, groupMode, next);
};
/**
* Drag-reorder wiring of one group header, given the mode's FULL ordered key list
* (not the page of groups on screen — committing only the visible groups would drop
* the hidden ones out of the stored sequence and bring them back as newcomers).
*
* Offered only where the groups have an order to change (isOrderableGroupMode: time
* mode's buckets are a fixed chronological ladder), never on a search-filtered view,
* and only where a pointer that can drag exists — HTML5 drag-and-drop never fires
* from touch. A stored order still APPLIES on such a device: unlike the rows' global
* sort mode, a group order is per Project and implicit, so there is nothing to
* degrade — a phone renders the arrangement its owner made at a desk.
*
* A drop stays inside the dragged group's own pin partition, so dragging can reorder
* but never pin or unpin (the rows' rule, one axis up).
*/
const groupDragProps = (key: string, sequence: readonly string[]) => {
if (!canDrag || searching || !isOrderableGroupMode(groupMode)) {
return { header: {}, dropEdge: null as "above" | "below" | null };
}
const dragging = dragGroup;
const samePartition =
dragging !== null && dragging !== key && pinnedGroups.has(dragging) === pinnedGroups.has(key);
/** Which half of the header the pointer is in — the edge the drop would land on. */
const edgeOf = (e: ReactDragEvent) => {
const rect = e.currentTarget.getBoundingClientRect();
return e.clientY - rect.top > rect.height / 2;
};
return {
header: {
draggable: true,
onDragStart: (e: ReactDragEvent) => {
e.dataTransfer.setData(GROUP_DRAG_MIME, key);
e.dataTransfer.effectAllowed = "move" as const;
setDragGroup(key);
},
onDragEnd: () => {
setDragGroup(null);
setGroupDropHint(null);
},
onDragOver: (e: ReactDragEvent) => {
if (!samePartition || !isGroupDrag(e)) return;
e.preventDefault();
// preventDefault alone only says "a drop may land here"; the effect still has
// to be one effectAllowed permits, or a modifier held during the drag resolves
// it to "none" and the drop event never fires (drop-zone.tsx sets it too).
e.dataTransfer.dropEffect = "move";
const after = edgeOf(e);
setGroupDropHint((prev) =>
prev?.key === key && prev.after === after ? prev : { key, after },
);
},
// dragleave also fires when the pointer merely crosses onto one of the header's
// OWN children — the collapse toggle spans most of the row, and up to three
// action buttons follow it — so clearing unconditionally strobes the indicator.
// relatedTarget is where the drag is going: still inside means nothing changed
// (the idiom features/chat/drop-zone.tsx already uses).
onDragLeave: (e: ReactDragEvent) => {
const to = e.relatedTarget;
if (to instanceof Node && e.currentTarget.contains(to)) return;
setGroupDropHint((prev) => (prev?.key === key ? null : prev));
},
onDrop: (e: ReactDragEvent) => {
if (!samePartition || dragging === null || !isGroupDrag(e)) return;
e.preventDefault();
// The FULL sequence, not the drag's pin partition: commitGroupOrder splices
// within one array, and samePartition has already refused a cross-boundary
// drop, so filtering here would only hide the other partition's keys from the
// splice and cost them their stored positions.
commitGroupDrop(sequence, key, edgeOf(e));
setDragGroup(null);
setGroupDropHint(null);
},
},
dropEdge:
samePartition && groupDropHint?.key === key
? groupDropHint.after
? ("below" as const)
: ("above" as const)
: null,
};
};
/** Parked drafts through the live search (matched on their first-line title). */
const shownDrafts = searching
? draftEntries.filter((e) =>
draftSessionTitle(e).toLowerCase().includes(searchQuery.trim().toLowerCase()),
)
: draftEntries;
/** Whether the active search hits anything anywhere (drafts included) — drives the quiet no-match line. */
const hasSearchMatches =
shownDrafts.length > 0 ||
(groupMode === "agent"
? orderedAgents.some((a) => filterRows(byAgent.get(a.agentId) ?? []).length > 0)
: groupMode === "time"
? timeParts !== null && Object.values(timeParts).some((rows) => rows.length > 0)
: orderedWorkspaceGroups.some((g) => filterRows(g.sessions).length > 0));
/** In-flight key of one group's category "More" (folderKey shares the same composite for folder categories). */
const loadKey = (groupKey: string, category: SessionCategory) => `${category}\0${groupKey}`;
/**
* The server stream a group's fetches walk: its own, under Workspace grouping, or the
* Agent's whole one otherwise. Only Workspace groups need their own — an Agent group IS
* the whole stream, and a time bucket is cut from rows that are already loaded, so it
* fetches nothing of its own at all.
*
* This is what makes the groups independent. Sharing one per-Agent cursor meant a group's
* "load more" consumed the page its siblings were about to read: their rows appeared,
* their reveal counts moved, and the group that asked could grow by less than a page — or
* by nothing at all.
*/
const fetchScope = (groupKey: string): string | undefined =>
groupMode === "workspace" ? groupKey : undefined;
/** loadMoreFor with an in-flight marker for the triggering "More" row (disable + loading text). */
const trackedLoadMore = (groupKey: string, category: SessionCategory, agentIds: string[]) => {
const key = loadKey(groupKey, category);
setPendingLoads((prev) => new Set(prev).add(key));
void loadMoreFor(agentIds, category, fetchScope(groupKey)).finally(() => {
setPendingLoads((prev) => {
const next = new Set(prev);
next.delete(key);
return next;
});
});
};
/**
* Open/close a group's folder. A folder's content is loaded on demand: the first
* expand fetches its category's first page for every contributing Agent that hasn't
* been asked yet (already-loaded rows stay put — re-expanding never refetches; the
* folder's own "More" row does the paging from there).
*/
const toggleFolder = (groupKey: string, category: FolderCategory, agentIds: string[]) => {
// Inert while searching (same reason as toggleGroup): folders render force-opened,
// so a click would only fire a pointless category fetch and desync the open state.
if (searching) return;
const key = folderKey(groupKey, category);
const opening = !openFolders.has(key);
setOpenFolders((prev) => {
const next = new Set(prev);
if (opening) next.add(key);
else next.delete(key);
return next;
});
if (opening) {
const scope = fetchScope(groupKey);
const unloaded = agentIds.filter((id) => !isLoadedFor(id, category, scope));
if (unloaded.length > 0) void loadMoreFor(unloaded, category, scope);
}
};
// The open chat is a background Session (one a program opened): expand the Background folder
// in its group, so the active row is never hidden inside a collapsed folder (mirrors the
// archived expansion on archiving the open chat; archived wins, so an archived Session is left
// to that folder). Auto-expansion fires ONCE per (grouping mode, active session): the ref guard
// keeps list mutations (status ticks, reloads) from re-opening a folder the user explicitly
// collapsed while that chat stays open. `sessions` must remain a dependency — the active
// session may not be in the list yet on first render, and the guard is only set once the
// row is actually found and expanded.
const lastAutoExpandedRef = useRef<string | null>(null);
useEffect(() => {
if (!activeSessionId) return;
const s = sessions.find((x) => x.sessionId === activeSessionId);
if (!s) return;
const category = sessionCategory(s);
if (category === null || category === "active" || category === "archived") return;
const guard = `${groupMode}\0${activeSessionId}`;
if (lastAutoExpandedRef.current === guard) return;
lastAutoExpandedRef.current = guard;
const groupKey =
groupMode === "agent"
? s.agentId
: groupMode === "time"
? TIME_FOLDERS_GROUP_KEY
: workspaceGroupKey(s.workspace, machineForSession(s.sessionId));
const key = folderKey(groupKey, category);
setOpenFolders((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));
// Same on-demand load a click-expand does, for this Session's own Agent (siblings of
// other contributing Agents stay behind the folder's "More"), down the same stream the
// folder itself pages.
const scope = groupMode === "workspace" ? groupKey : undefined;
if (!isLoadedFor(s.agentId, category, scope)) void loadMoreFor([s.agentId], category, scope);
}, [activeSessionId, sessions, groupMode, isLoadedFor, loadMoreFor]);
/**
* Workspace mode: give every rendered group its own first page. The initial load reads
* the Agent's whole stream, which is one stream cut by Workspace — it fills the groups
* unevenly, so a group can come up with two rows while the neighbour it shares an Agent
* with got eight. Any group left short of a full first page (or of its own total, if that
* is smaller) asks for one down its own stream, once: the scoped pair is loaded from then
* on and this is inert.
*
* Only the groups on screen ask — the pager bounds that to one page of groups — and a
* search is left alone, since it renders loaded matches only and fetching cannot find more.
*
* The ask is marked in flight like a "More" click (pendingLoads), for two reasons: a group
* the counts know but no page has loaded rows of starts out empty, and its body must read
* as loading rather than as having no conversations; and the marker is what keeps this
* effect from asking twice — every landed page changes the group list and re-runs it, and
* an in-flight pair is still unloaded, so a second request would start its cursor over and
* the group would later skip a page.
*/
useEffect(() => {
if (groupMode !== "workspace" || searching) return;
for (const group of groupPageSlice(orderedWorkspaceGroups, shownGroupPage)) {
const counts = workspaceGroupCounts.get(group.key);
const total = counts?.totals.active ?? 0;
const agents = [
...new Set([...(counts?.agents.active ?? []), ...group.sessions.map((s) => s.agentId)]),
];
// Counts not in yet (0): nothing is known to be missing, so nothing is asked for. What
// the group SHOWS is what a first page has to fill: rows in memory below its watermark
// (another Agent's stream reached further) are not on screen.
const loaded = cutAtWatermark(
group.sessions.filter((s) => sessionCategory(s) === "active"),
activityWatermarkFor(agents, "active", group.key),
).length;
if (loaded >= Math.min(SIDEBAR_PAGE_SIZE, total)) continue;
const unloaded = agents.filter((id) => !isLoadedFor(id, "active", group.key));
if (unloaded.length === 0) continue;
const key = loadKey(group.key, "active");
if (pendingLoads.has(key)) continue;
setPendingLoads((prev) => new Set(prev).add(key));
void loadMoreFor(unloaded, "active", group.key).finally(() => {
setPendingLoads((prev) => {
const next = new Set(prev);
next.delete(key);
return next;
});
});
}
}, [
groupMode,
searching,
orderedWorkspaceGroups,
shownGroupPage,
workspaceGroupCounts,
isLoadedFor,
activityWatermarkFor,
loadMoreFor,
pendingLoads,
]);
/** Archive / unarchive: persists immediately and updates in place (fails silently; the next list refresh self-corrects). */
const toggleArchive = async (s: SessionInfo) => {
// Archiving the currently open chat: expand the "archived" folder so it doesn't silently vanish from the sidebar with no way back.
if (!s.archived && s.sessionId === activeSessionId) {
setOpenFolders((prev) => new Set(prev).add(folderKey(sessionGroupKey(s), "archived")));
}
try {
const res = await api.patchSession(s.sessionId, { archived: !s.archived });
replace(res.session);
} catch {
/* Ignore: non-critical operation */
}
};
const confirmRename = async () => {
if (!renamingSession) return;
const title = renameText.trim();
if (!title) return;
setRenameBusy(true);
setRenameError(null);
try {
const res = await api.patchSession(renamingSession.sessionId, { title });
replace(res.session);
setRenamingSession(null);
} catch (e) {
setRenameError(apiErrorText(e));
} finally {
setRenameBusy(false);
}
};
/**
* Everything a deleted conversation leaves behind in this column — the store row, its composer
* draft, its pin and its manual-order entry — for one row or for a batch. The pins and the order
* are pruned from ONE pair of reads, so two removals in a single turn cannot write the first one
* back: both state setters would otherwise see the value they had when the turn began.
*/
const forgetDeletedSessions = (targets: readonly SessionInfo[]) => {
let pins: ReadonlySet<string> = pinnedSessions;
let order: readonly string[] = sessionOrder;
for (const target of targets) {
// remove() also tombstones the id (see the store's isDeleted), which is what keeps the
// chat page from re-fetching the Session it is still routed at during the frames before
// the navigate() below lands. Ordering the two is deliberately NOT the mechanism: the
// list lives in a zustand store whose updates are not subject to React's transition
// lanes, so scheduling tricks here cannot be relied on to sequence them.
remove(target.sessionId);
// The session is gone, so clear its input draft too (no orphaned keys left in localStorage; keys are scoped per user, #68).
if (user) clearDraft(sessionDraftKey(user.userId, target.sessionId));
// Prune its pin and manual-order entry as well (both helpers return the same
// reference when the id wasn't present — the write is skipped then).
pins = removePinnedSession(pins, target.sessionId);
forgetSession(currentProjectId, target.sessionId);
order = removeFromSessionOrder(order, target.sessionId);
}
if (pins !== pinnedSessions) {
setPinnedSessions(pins);
savePinnedSessions(currentProjectId, pins);
}
if (order !== sessionOrder) {
setSessionOrder(order);
saveSessionOrder(currentProjectId, groupMode, order);
}
};
const confirmDeleteSession = async () => {
if (!deletingSession) return;
setDeletingBusy(true);
setDeleteRefusal(null);
const target = deletingSession;
try {
await api.deleteSession(target.sessionId);
forgetDeletedSessions([target]);
setDeletingSession(null);
// The deleted session was the one open: jump to this Agent's next conversation, otherwise
// fall back to the chat home page. Only a person's conversation is auto-opened — never an
// archived one (hidden by default — landing there would look like the chat vanished into
// thin air) and never a background one (a program opened it; the user was not in it),
// the rule latestConversation follows.
if (activeSessionId === target.sessionId) {
const rest = (byAgent.get(target.agentId) ?? []).filter(
(s) => s.sessionId !== target.sessionId && sessionCategory(s) === "active",
);
navigate(rest[0] ? `/chat/${rest[0].sessionId}` : "/chat");
}
} catch (e) {
// The dialog stays open (it only closes on a landed DELETE) and says why: a toast would
// dismiss itself above a card the person is still looking at.
setDeleteRefusal(apiErrorText(e));
} finally {
setDeletingBusy(false);
}
};
const go = (to: string) => {
navigate(to);
onNavigate?.();
};
/**
* Batch processing over the conversation list (the header control beside 搜索会话). Leaving the
* mode drops the ticks: a selection means nothing outside it, and it must not survive to act on
* rows picked in some other visit.
*/
const toggleBatchMode = () => {
if (batchMode) {
setBatchMode(false);
setBatchSelected(new Set());
// The bar is gone with the mode, and so is any meaning its last refusal had.
setBatchArchiveRefusal(null);
return;
}
setBatchMode(true);
};
const toggleBatchRow = (sessionId: string) => {
// The bar's refusal counts the rows it refused; ticks that no longer match it make it untrue.
setBatchArchiveRefusal(null);
setBatchSelected((prev) => {
const next = new Set(prev);
if (next.has(sessionId)) next.delete(sessionId);
else next.add(sessionId);
return next;
});
};
/** The ticked conversations, as the objects the column already loaded (the ticks only ever come from its rows). */
const batchTargets = () => sessions.filter((s) => batchSelected.has(s.sessionId));
/**
* 批量归档 / 批量取消归档: one request per ticked conversation, the same per-row PATCH the row's own
* menu runs — the server has no bulk route, and a batch that fails halfway must not hide which
* rows landed. Archiving the conversation on screen opens the archived folder, or its row would
* vanish from the list with no way back (the row menu's toggle does the same).
*
* The outcomes are read per row (`splitBatchOutcome`, the same rule the batch delete follows):
* the rows that landed take the server's own copy, the refused ones stay ticked — they are the
* rows still there — and the bar keeps the count of what is left plus the server's words. That
* bar is the retry, so this reason cannot live in a toast over it.
*/
const batchSetArchived = async (archived: boolean): Promise<void> => {
const targets = batchTargets();
if (targets.length === 0) return;
setBatchBusy(true);
// Another attempt answers the previous one, whatever it says.
setBatchArchiveRefusal(null);
try {
const results = await Promise.allSettled(
targets.map((s) => api.patchSession(s.sessionId, { archived })),
);
const { landed, refused, firstReason } = splitBatchOutcome(targets, results);
// The rows that landed now hold the server's version of themselves (including the archived
// flag that moves them into the folder) — the refused ones are left exactly as they were.
for (const row of landed) replace(row.value.session);
setBatchSelected(new Set(refused.map((s) => s.sessionId)));
const openOne = landed.find((row) => row.target.sessionId === activeSessionId);
if (archived && openOne !== undefined) {
setOpenFolders((prev) =>
new Set(prev).add(folderKey(sessionGroupKey(openOne.target), "archived")),
);
}
if (refused.length === 0) {
toastSuccess(
archived
? S.chat.batchArchiveDone(landed.length)
: S.chat.batchUnarchiveDone(landed.length),
);
return;
}
setBatchArchiveRefusal(
archived
? S.chat.batchArchiveRefused(refused.length, apiErrorText(firstReason))
: S.chat.batchUnarchiveRefused(refused.length, apiErrorText(firstReason)),
);
} finally {
setBatchBusy(false);
}
};
/**
* 批量删除: the row delete's own confirmation, asked once for the whole selection, then the same
* DELETE per row. Deleting the conversation on screen leaves for the next one of its Agent, as the
* single delete does — the others are gone from the list, not from what the reader is looking at.
*
* A batch is N writes, not one, so the outcomes are collected per row (`allSettled`): some can
* land while another is refused. The landed rows leave the list and the ticks; the refused ones
* stay ticked — that is what makes the card's own count name the rows a retry would act on — and
* the card stays open with the server's words in it (a toast would dismiss itself above the
* card the person is still looking at, and it could not say that the rest went through).
*/
const confirmBatchDelete = async () => {
const targets = batchTargets();
if (targets.length === 0) return;
setBatchBusy(true);
setBatchDeleteRefusal(null);
try {
const results = await Promise.allSettled(targets.map((s) => api.deleteSession(s.sessionId)));
// The card shows ONE reason under its sentence, so the first refusal's words are the ones
// kept — the rows themselves say which of them is still there to retry.
const { landed, refused, firstReason } = splitBatchOutcome(targets, results);
const landedRows = landed.map((row) => row.target);
forgetDeletedSessions(landedRows);
setBatchSelected(new Set(refused.map((s) => s.sessionId)));
if (refused.length === 0) {
setBatchConfirmDelete(false);
} else {
setBatchDeleteRefusal(S.chat.batchDeleteRefused(refused.length, apiErrorText(firstReason)));
}
// Only a conversation that actually went away is left for: when the open one was one of the
// refused rows it is still on screen, so there is nowhere to go.
const openOne = landedRows.find((s) => s.sessionId === activeSessionId);
if (openOne !== undefined) {
const deleted = new Set(landedRows.map((s) => s.sessionId));
const rest = (byAgent.get(openOne.agentId) ?? []).filter(
(s) => !deleted.has(s.sessionId) && sessionCategory(s) === "active",
);
navigate(rest[0] ? `/chat/${rest[0].sessionId}` : "/chat");
}
} finally {
setBatchBusy(false);
}
};
/** Clear the ticks, staying in the mode (the bar's own control — leaving is the header's toggle). */
const clearBatchSelection = () => {
setBatchArchiveRefusal(null);
setBatchSelected(new Set());
};
/**
* New chat: enters draft state (/chat/new) without creating a Session — Model / Workspace /
* approval mode are all chosen on the draft input card, and the Session is only actually
* created when the first message is sent. Route state carries only what the clicked entry
* is about: the agent-mode group header's "+" names that group's Agent, the workspace-mode
* group header's "+" names that group's Workspace path ("" = a temporary workspace), and the
* pinned "New chat" and the header's create button name nothing. Every field left unnamed
* starts on the Project's new-chat defaults, then the built-in fallback (new-chat.ts).
*/
const newChat = ({
agentId,
workspace,
machineId,
browseFiles,
}: { agentId?: string; workspace?: string; machineId?: string; browseFiles?: boolean } = {}) => {
// Typed-but-unsent text in the ACTIVE new-chat draft becomes a parked draft
// conversation first (a row in the list below, sendable anytime — draft-sessions.ts),
// so this click always lands on an empty composer and never silently shelves content;
// the selections a text-less earlier visit left behind are released with it.
if (user && currentProjectId) prepareNewChatDraft(user.userId, currentProjectId);
if (agentId) setCurrentAgentId(agentId);
const state = {
...(agentId ? { agentId } : {}),
// The machine travels WITH the path, always — including its absence. A path names a
// different directory on every machine, so handing the composer one without the other
// is handing it a directory it cannot find.
...(workspace !== undefined ? { workspace, machineId } : {}),
// The chat page opens the dock's Files panel on arrival (a group's "Browse files").
...(browseFiles === true ? { browseFiles } : {}),
};
navigate(`/chat/${DRAFT_SESSION_ID}`, Object.keys(state).length > 0 ? { state } : undefined);
onNavigate?.();
};
/**
* A Workspace group's "Browse files": the dock's Files panel on that directory. A page already
* on it — the open conversation's Workspace, or the folder the draft picked, on the same
* machine — only brings the panel up. Anywhere else lands on a new-chat draft for the folder,
* the group's "+", whose Files panel is addressed by the directory itself: the dock belongs to
* the conversation on screen, so a folder another conversation is in has no panel here.
*/
const browseFiles = (path: string, machineId: string | null) => {
const here = dockWorkspace();
if (docksOnScreen() && here !== null && here.path === path && here.machineId === machineId) {
openPanel("workspace");
onNavigate?.();
return;
}
newChat({ workspace: path, ...(machineId ? { machineId } : {}), browseFiles: true });
};
/** Confirmed parked-draft deletion: drops the entry; a deleted draft that is open falls back to the plain new-chat page. */
const confirmDeleteDraft = () => {
if (!deletingDraft) return;
if (user && currentProjectId) {
removeDraftSession(user.userId, currentProjectId, deletingDraft.id);
}
if (activeSessionId === deletingDraft.id) navigate(`/chat/${DRAFT_SESSION_ID}`);
setDeletingDraft(null);
};
/** What the header's create button makes, and its tooltip (the created object follows the grouping mode). */
const newEntity = newEntityForGroupMode(groupMode);
const newEntityLabel =
newEntity === "agent"
? S.agent.create
: newEntity === "chat"
? S.chat.newSessionMenu
: S.chat.newWorkspaceEntity;
/** Persist-if-changed for every registry mutation (register / alias / unregister share the same-reference fast exit). */
const applyRegistryChange = (next: readonly WorkspaceEntry[]) => {
if (next === registeredWorkspaces) return;
setRegisteredWorkspaces(next);
saveWorkspaceRegistry(currentProjectId, next);
};
/**
* 新建工作区: register the browsed pick so it surfaces as a group immediately, Sessions
* or not. An empty registered group is appended and nothing pins or orders it yet, so it
* lands last — turn to the page that now holds it, or to the page of the group that was
* already there. Otherwise, past ten groups, the freshly added Workspace would sit on a
* page the user is not looking at and the click would read as a no-op.
*/
const addWorkspace = (path: string, machineId?: string | null) => {
const next = registerWorkspace(registeredWorkspaces, path, machineId ?? undefined);
if (next === registeredWorkspaces) return;
applyRegistryChange(next);
const key = workspaceGroupKey(path, machineId ?? null);
const existing = orderedWorkspaceGroups.findIndex((g) => g.key === key);
setGroupPage(groupPageOf(existing >= 0 ? existing : orderedWorkspaceGroups.length));
};
/**
* The ssh alias of a group's machine, or null for this server's own groups — what a name
* is qualified with. An unlabelled machine (the list is admin-only, and a machine can also
* drop out of the ssh config) falls back to its id: honest, where inventing a name is not.
*/
const machineNameOf = (machineId: string | null): string | null =>
machineId === null ? null : (machineLabels.get(machineId) ?? machineId);
/** Registered Workspaces by GROUP key — only their groups offer the rename/remove overflow. */
const registeredKeys = useMemo(
() => new Set(registeredWorkspaces.map((e) => workspaceGroupKey(e.path, e.machineId ?? null))),
[registeredWorkspaces],
);
/** Open the alias editor pre-filled with the current alias ("" = following the basename). */
const openRenameWorkspace = (path: string, machineId: string | null) => {
setWorkspaceAliasText(
registeredWorkspaces.find((e) => e.path === path && (e.machineId ?? null) === machineId)
?.alias ?? "",
);
setRenamingWorkspace({ path, machineId });
};
/** Commit the alias (blank reverts the label to the directory basename). Direct save — no server, nothing destructive. */
const confirmRenameWorkspace = () => {
if (!renamingWorkspace) return;
applyRegistryChange(
setWorkspaceAlias(
registeredWorkspaces,
renamingWorkspace.path,
renamingWorkspace.machineId,
workspaceAliasText,
),
);
setRenamingWorkspace(null);
};
/**
* 删除工作区 (confirmed via the shared ConfirmModal, like every destructive-looking
* action): stamps the sidebar registry entry so the group leaves the list — disk and
* Sessions are never touched, the confirm copy says exactly that, and picking the
* directory again in 新建工作区 brings it back. The stamp works on a group the server
* derives from Sessions too (dropHiddenWorkspaces), which is the case that used to
* survive the removal; a chat created in the directory after the removal re-reveals it.
*/
const confirmDeleteWorkspace = () => {
if (!deletingWorkspace) return;
applyRegistryChange(
hideWorkspace(
registeredWorkspaces,
deletingWorkspace.path,
deletingWorkspace.machineId,
new Date().toISOString(),
),
);
setDeletingWorkspace(null);
};
const openSession = (s: SessionInfo) => {
// Opening is what "read" means here: stamp the marker before navigating.
noteSessionSeen(currentProjectId, s.sessionId, s.lastActiveAt);
// Cross-group click: the current Agent follows this Session's own Agent.
setCurrentAgentId(s.agentId);
go(`/chat/${s.sessionId}`);
};
/**
* The mode switch: company mode enters at `/org` (the organization last opened, else the
* first); development mode keeps whatever conversation is open and only leaves an
* organization page, which has no development form.
*/
const switchMode = (mode: WorkMode) => {
if (mode === company.workMode) return;
company.setWorkMode(mode);
if (mode === "company") go("/org");
else if (isOrgRoute(location.pathname)) go("/chat");
};
/** agentId → display name (row hint tooltips in workspace mode). */
const agentNameById = useMemo(
() => new Map(agents.map((a) => [a.agentId, agentDisplayName(a)])),
[agents],
);
/** Session rows shared by both modes; withAgentHint adds a small Agent avatar per row (workspace mode, where the group no longer names the Agent). */
const renderRows = (
rows: SessionInfo[],
withAgentHint: boolean,
/** Manual sort only: the drag scope (group key) plus the group's FULL ordered active list — the drop must commit every loaded row of the partition, not the display-capped slice the user happens to see. */
dragCtx?: { scope: string; fullRows: SessionInfo[] },
/** Whether these rows are the group's ACTIVE list (the only rows pinning can reorder). */
activeList = false,
) => (
<ul className="space-y-px">
{rows.map((s) => {
// Manual-sort drag wiring (active lists only; never while searching — a filtered
// view is not the real order). A drop stays within its own scope AND its own
// pin partition: dragging can reorder but never pin or unpin.
const dragging =
dragCtx !== undefined && dragSession?.scope === dragCtx.scope ? dragSession : null;
const samePartition =
dragging !== null &&
dragging.id !== s.sessionId &&
pinnedSessions.has(dragging.id) === pinnedSessions.has(s.sessionId);
const drag =
dragCtx === undefined || batchMode
? {}
: {
draggable: true,
onDragStart: (e: ReactDragEvent) => {
// Firefox refuses to start a drag without payload data — but the id must
// NOT ride on text/plain: the composer is a controlled textarea with no
// drop guard, so a mis-aimed reorder would paste a session id straight
// into the user's message. A private type is invisible to text drops.
e.dataTransfer.setData(SESSION_DRAG_MIME, s.sessionId);
e.dataTransfer.effectAllowed = "move" as const;
setDragSession({ scope: dragCtx.scope, id: s.sessionId });
},
onDragEnd: () => {
setDragSession(null);
setDropHint(null);
},
onDragOver: (e: ReactDragEvent) => {
if (!dragging || !samePartition) return;
e.preventDefault();
const rect = e.currentTarget.getBoundingClientRect();
const after = e.clientY - rect.top > rect.height / 2;
setDropHint((prev) =>
prev?.id === s.sessionId && prev.after === after
? prev
: { id: s.sessionId, after },
);
},
onDragLeave: () => setDropHint((prev) => (prev?.id === s.sessionId ? null : prev)),
onDrop: (e: ReactDragEvent) => {
if (!dragging || !samePartition) return;
e.preventDefault();
const rect = e.currentTarget.getBoundingClientRect();
const after = e.clientY - rect.top > rect.height / 2;
// The FULL partition (every loaded row of this group on the dragged
// row's side of the pin boundary), not the visible slice: committing
// only the capped rows would drop the hidden ones out of the stored
// sequence, and they would come back as "newcomers" at the top.
const partitionIds = dragCtx.fullRows
.filter(
(r) => pinnedSessions.has(r.sessionId) === pinnedSessions.has(dragging.id),
)
.map((r) => r.sessionId);
commitManualDrop(partitionIds, s.sessionId, after);
setDragSession(null);
setDropHint(null);
},
dropEdge:
samePartition && dropHint?.id === s.sessionId
? dropHint.after
? ("below" as const)
: ("above" as const)
: null,
};
return (
<SidebarSessionRow
key={s.sessionId}
s={s}
active={s.sessionId === activeSessionId}
// Busy / settled / read / never-ran, decided in one place (session-activity.ts) so
// the whole transition sequence is testable without a DOM.
activity={sessionRowActivity(s, sessionSeen, activeSessionId)}
background={sessionBackgroundTasks(s)}
scheduled={scheduledSessions.has(s.sessionId)}
pinned={pinnedSessions.has(s.sessionId)}
// Pinning is an ACTIVE-list priority: folder rows (background / archived) are
// ordered by last activity inside their folder and never pass through
// orderSessionRows, so a pin there would write an id, light the glyph, move nothing
// — and then shift the active list's drag partition.
canPin={activeList}
// Last ACTIVITY, not creation: the server stamps lastActiveAt when a run
// starts and again when it ends, so a running row shows its run-start time
// (it recedes while the run continues — the hourglass beside it is what says
// "active right now"). CLI-adopted and subagent rows are not
// driven by this server, so theirs stays at createdAt.
lastActive={formatRelativeShort(s.lastActiveAt, locale)}
locale={locale}
{...(withAgentHint ? { agentHint: agentNameById.get(s.agentId) ?? s.agentId } : {})}
{...drag}
onOpen={openSession}
onTogglePin={(x) => toggleSessionPin(x.sessionId)}
onRename={(x) => {
setRenameError(null);
setRenameText(x.title ?? "");
setRenamingSession(x);
}}
onMessaging={(x) => setMessagingSession(x)}
onDelete={(x) => {
// The dialog first, then the last attempt's reason: one attempt carries one reason.
setDeletingSession(x);
setDeleteRefusal(null);
}}
onToggleArchive={(x) => void toggleArchive(x)}
{...(batchMode
? {
select: {
checked: batchSelected.has(s.sessionId),
onToggle: () => toggleBatchRow(s.sessionId),
},
}
: {})}
/>
);
})}
</ul>
);
/**
* A folder's "Show N more chats": reveal one more page of the rows it already holds,
* and fetch its next server page only when the reveal actually runs past them and
* somewhere is left to fetch from. Mirrors the active list's showMore — a page already
* in memory spends no request, which in time mode is a fan-out across every
* contributing Agent.
*/
const revealFolderMore = (
groupKey: string,
category: FolderCategory,
agentIds: string[],
loaded: number,
) => {
const key = folderKey(groupKey, category);
const nextCap = (folderCaps.get(key) ?? SIDEBAR_PAGE_SIZE) + SIDEBAR_PAGE_SIZE;
setFolderCaps((prev) => {
const next = new Map(prev);
next.set(key, nextCap);
return next;
});
if (loaded < nextCap && agentIds.some((id) => hasMoreFor(id, category, fetchScope(groupKey)))) {
trackedLoadMore(groupKey, category, agentIds);
}
};
/** A folder's "show less": back to the first page (rows already fetched stay in memory). */
const collapseFolder = (key: string) => {
setFolderCaps((prev) => {
if (!prev.has(key)) return prev;
const next = new Map(prev);
next.delete(key);
return next;
});
};
/**
* Collapsed-by-default lazy folder (background / archived): nothing is fetched until the
* first expand, and once open the folder reveals and pages independently with its own "More"
* and "show less" rows. Everything is driven by the group's **own** exact server share
* (`totals` — the Agent's counts in agent mode, the per-Workspace fold in workspace mode): the
* folder exists only while its share is non-zero, the label shows that share, and "More" shows
* only while something of that share is still hidden — an Agent's content in *other*
* Workspaces can never surface a folder here.
*
* The folder obeys the same display rule the active list does (revealPlan): one page
* of rows shows at a time and "More" reveals one page more, spending a fetch only when
* the reveal runs past what is in memory. In time mode the folders span every contributing
* Agent, so one fetch can return several pages at once; they stay in memory under the
* cap rather than all landing on screen. In workspace mode a fetched page can land rows
* in other groups' folders too, so one click may grow this folder by fewer than a full
* page — the row shows a loading state while the fetch runs.
*/
const renderFolder = (
groupKey: string,
category: FolderCategory,
parts: SessionPartition,
withAgentHint: boolean,
/** Agents that may hold this group's rows of this category (fetch fan-out set). */
agentIds: string[],
totals: SessionCategoryCounts | undefined,
) => {
const loadedRows = parts[category];
// In last-activity order, cut at the folder's watermark: a folder spanning several
// streams (Agents, machines) shows only what they have all reached, so its "More" adds
// rows below the ones on screen and never above them (the active list's rule).
const rows = cutAtWatermark(
loadedRows,
searching || agentIds.length === 0
? null
: activityWatermarkFor(agentIds, category, fetchScope(groupKey)),
activeSessionId,
);
// While searching the folder speaks for its loaded MATCHES only: a match hidden
// behind a collapsed folder would look like a missing result (the models page's
// search-forces-open rationale), so the folder is forced open, labelled by the
// match count, hidden when nothing matches, and never offers "More" or "show less"
// (the server cannot search unloaded rows, and every match is already on screen).
if (searching && rows.length === 0) return null;
// Loaded rows win a disagreement with the totals (counts refresh only on reload).
const total = searching ? rows.length : Math.max(totals?.[category] ?? 0, loadedRows.length);
if (total === 0) return null;
const key = folderKey(groupKey, category);
const cap = folderCaps.get(key) ?? SIDEBAR_PAGE_SIZE;
// The folder's whole share is in memory (every Agent that could hold a row of it is
// fetched out), which is when the loaded rows become the truth — the same clause the
// active list applies, and what keeps a count drifting above reality from leaving a
// reveal row with nothing behind it.
const fullyLoaded =
agentIds.length > 0 && !agentIds.some((id) => hasMoreFor(id, category, fetchScope(groupKey)));
const plan = revealPlan({ cap, loaded: rows.length, total, fullyLoaded });
const shown = searching ? rows : rows.slice(0, plan.shown);
const hidden = searching ? 0 : plan.hidden;
return (
<FolderSection
key={category}
label={S.chat.folderGroups[category](total)}
open={searching || openFolders.has(key)}
onToggle={() => toggleFolder(groupKey, category, agentIds)}
more={hidden > 0}
// The rows past the cap plus the unfetched remainder of this folder's own share —
// the same count, and the same wording, the active list's reveal row names one
// level up.
moreLabel={S.chat.expandRestSessions(hidden)}
pending={pendingLoads.has(loadKey(groupKey, category))}
onMore={() => revealFolderMore(groupKey, category, agentIds, rows.length)}
less={!searching && plan.canCollapse}
onLess={() => collapseFolder(key)}
>
{renderRows(shown, withAgentHint)}
</FolderSection>
);
};
/**
* Active-list "Show N more chats": reveal one more page of this group's already-loaded
* active rows, and fetch the next active server page only when the reveal actually runs
* past what is loaded. A group whose next page is already in memory spends no request —
* in workspace mode a fetch fans out to every Agent contributing to the group and its
* rows may land in other groups entirely, so a pointless one is not free.
*/
const showMore = (groupKey: string, agentIds: string[], loaded: number) => {
const nextCap = (groupCaps.get(groupKey) ?? SIDEBAR_PAGE_SIZE) + SIDEBAR_PAGE_SIZE;
setGroupCaps((prev) => {
const next = new Map(prev);
next.set(groupKey, nextCap);
return next;
});
if (agentIds.length > 0 && loaded < nextCap) trackedLoadMore(groupKey, "active", agentIds);
};
/** "Show less": drop one group's reveal back to the first page (rows already fetched stay in memory). */
const collapseRows = (groupKey: string) => {
setGroupCaps((prev) => {
if (!prev.has(groupKey)) return prev;
const next = new Map(prev);
next.delete(groupKey);
return next;
});
};
/**
* Expanded group body shared by both modes: active user rows (display-capped; "More"
* reveals and loads further **active-only** pages — the folders below never feed it) + the
* collapsed-by-default background / archived folders, each loading on first expand and paging
* on its own. `totals` / `agentsFor` carry the group's exact server share and its fetch
* fan-out set per category.
*/
const renderGroupBody = (
groupKey: string,
parts: SessionPartition,
withAgentHint: boolean,
totals: SessionCategoryCounts | undefined,
agentsFor: (category: SessionCategory) => string[],
) => {
// Row order: the pinned cluster first, then — under manual sort — the stored order
// within each pin partition (lib/session-order.ts). Both reorder only rows already
// FETCHED: a pinned conversation that lives past the loaded pages does not surface
// until "More" pulls its page in (the list has no server-side pin), so the pinned
// cluster leads what is loaded, not the Agent's whole history. Folder rows keep
// their last-activity order: pinning and manual order are active-list concerns.
// While searching, the display cap is bypassed — every loaded match shows, and
// "More" hides (it pages the unfiltered list and would read as "more matches",
// which the server cannot promise).
//
// Before any of that, the rows are cut at the group's watermark: an Agent group on
// several machines and a Workspace group spanning Agents both merge several streams,
// and only the rows above the most recent cursor that still has more are a true prefix
// of the group's activity order. The rest wait in memory, so "More" only ever adds rows
// below the ones on screen. A time bucket has no streams of its own (its rows arrive
// already cut), and a search sees every loaded row.
const activeAgents = agentsFor("active");
const visibleActive = cutAtWatermark(
parts.active,
searching || activeAgents.length === 0
? null
: activityWatermarkFor(activeAgents, "active", fetchScope(groupKey)),
activeSessionId,
);
const orderedActive = orderSessionRows(visibleActive, (s) => s.sessionId, {
pinned: pinnedSessions,
sortMode: effectiveSortMode,
order: sessionOrder,
recencyOf: (s) => s.lastActiveAt,
});
/** Manual sort only (never on a search-filtered view): drag scope + the group's full ordered list, so a drop commits the whole partition. */
const dragCtx =
effectiveSortMode === "manual" && !searching
? { scope: groupKey, fullRows: orderedActive }
: undefined;
// The reveal row counts THIS group's own hidden conversations and nothing else — the
// folders never feed it, and no other group's numbers reach it. `fullyLoaded` says the
// group's whole active share is already in memory (every Agent that could hold a row of
// it is fetched out), which is when the loaded rows become the truth: server counts
// refresh only on reload, so a count drifting above reality would otherwise leave a row
// that reveals nothing behind it.
const fullyLoaded =
activeAgents.length > 0 &&
!activeAgents.some((id) => hasMoreFor(id, "active", fetchScope(groupKey)));
// One page of rows at a time, what the reveal row still hides, and whether "Show less"
// has anything to fold away: the single rule revealPlan states, applied here and by
// every folder below.
const plan = revealPlan({
cap: groupCaps.get(groupKey) ?? SIDEBAR_PAGE_SIZE,
loaded: visibleActive.length,
total: totals?.active ?? 0,
fullyLoaded,
});
const shownActive = searching ? orderedActive : orderedActive.slice(0, plan.shown);
const hiddenActive = searching ? 0 : plan.hidden;
const canCollapse = !searching && plan.canCollapse;
const folders = FOLDER_CATEGORIES.map((category) =>
renderFolder(groupKey, category, parts, withAgentHint, agentsFor(category), totals),
);
const empty = visibleActive.length === 0 && folders.every((f) => f === null);
const activePending = pendingLoads.has(loadKey(groupKey, "active"));
// Rows the server counts that no page has loaded yet — a Workspace group known from
// the counts alone while its own first page is on its way (or, after a failed fetch,
// waiting on the reveal row below to be asked for again). Not "no conversations".
const awaitingRows = !searching && visibleActive.length === 0 && hiddenActive > 0;
return (
<>
{empty ? (
loading || (awaitingRows && activePending) ? (
// The same window the chat pane's skeleton covers: the Agent groups render as
// soon as the Agents arrive, but the session pages are still being fetched —
// "no Sessions yet" is not the honest answer until they land.
<SkeletonList rows={2} />
) : awaitingRows ? null : (
<p className="px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600">
{S.chat.noSessions}
</p>
)
) : (
// Drag-reorder is offered on the active list under manual sort (folders keep
// last-activity order), and never on a search-filtered view.
renderRows(shownActive, withAgentHint, dragCtx, true)
)}
{/* Reveal / collapse this group's own conversations (kept adjacent to the active
list they extend, above the folders). Both rows can stand at once: a group
revealed part-way still has more to show AND something to fold back. */}
{hiddenActive > 0 && (
<MoreRow
label={S.chat.expandRestSessions(hiddenActive)}
ariaLabel={S.chat.expandRestSessions(hiddenActive)}
pending={activePending}
onClick={() => showMore(groupKey, activeAgents, visibleActive.length)}
className="mt-0.5"
/>
)}
{canCollapse && (
<MoreRow
label={S.chat.showLess}
ariaLabel={S.chat.showLess}
onClick={() => collapseRows(groupKey)}
{...(hiddenActive > 0 ? {} : { className: "mt-0.5" })}
/>
)}
{/* Folders (collapsed by default): Background — what programs opened (API,
scheduled, subagent and CLI Sessions), each row marked with its source — then
Archived (archived wins over the source). */}
{folders}
</>
);
};
/**
* Time mode's one shared, Project-wide set of folders (rendered once below the buckets):
* their rows load only on first expand, so an unloaded Session has no known bucket and no
* bucket could honestly claim a share of them. Counts and fetch fan-out are summed over
* every Agent. A null entry means the Project holds no rows of that category at all —
* which is also what tells the empty-list line whether it is telling the truth.
*/
const timeFolders =
timeParts === null
? []
: FOLDER_CATEGORIES.map((category) =>
renderFolder(
TIME_FOLDERS_GROUP_KEY,
category,
timeParts,
true,
projectAgentsFor(category),
projectCounts,
),
);
/**
* Company mode's nav rows: the organization's six pages (COMPANY_NAV_KEYS) — channels are not
* among them, they are the list below — all in the fold, with no pins and no drag. Always
* mounted — the fold animates their height to zero and turns them inert.
*/
const companyNavItems: Array<{
key: string;
/** Where the row leads — null for a row with nowhere to lead, which renders disabled. */
to: string | null;
label: string;
icon: string;
}> = inCompany
? COMPANY_NAV_KEYS.map((key) => ({
key,
// Company mode with no organization keeps its six rows and disables them: the pages
// exist, they just have no organization to show yet, and a nav that empties itself
// reads as a broken shell rather than as an empty one.
to: navOrg === null ? null : orgPagePath(navOrg.projectId, navOrg.orgId, key),
label: S.nav.org[key],
icon: COMPANY_NAV_ICONS[key],
}))
: [];
/**
* Development mode's entries by area (nav-group-collapse.ts): New chat, then the
* NAV_GROUP_KEYS manifest minus the entries this user's role cannot reach, each pinned or
* collapsible, both areas in manifest order. New chat is always pinned and renders in its
* fixed slot above the scroll area, so the pinned rows here are the pages after it.
*/
const navSplit = splitNavEntries(navEntryKeysFor(user?.isAdmin === true), navPins);
const pinnedNavPages = navSplit.pinned.filter(isNavPage);
const collapsibleNavPages = navSplit.collapsible.filter(isNavPage);
/**
* One development-mode page entry: the package's pinnable nav row, bound to its route, its
* badge trail, its pin choice and its drag. Four entries sit on a badge trail — Agents (an
* outdated kernel, fixed on the Agent settings page two clicks down), Plugins, Models and the
* Cost Center (each cleared on the page itself). The row's own label is visible, so the hint
* only adds what the dot means, and the accessible name keeps the label as its prefix. The dot
* hangs at the row's right edge, vertically centred on the row.
*/
const renderNavEntry = (key: NavGroupKey) => {
const to = `/${key}`;
const label = S.nav[key];
const note = navNoteFor(badges, to);
const pinned = isNavPinned(key, navPins);
return (
<SidebarNavEntry
key={key}
label={label}
glyph={NAV_ICONS[key]}
href={to}
active={isCurrentPath(to, location.pathname)}
renderLink={renderRouterLink}
onClick={() => onNavigate?.()}
{...navEntryDragProps(key)}
pin={{
pinned,
label: S.nav.pinEntry,
tooltip: pinned ? S.nav.unpinEntry : S.nav.pinEntry,
onToggle: (e) => {
// A keyboard toggle follows its row into the other area (see pinFocusRef).
if (e.currentTarget.matches(":focus-visible")) pinFocusRef.current = key;
setNavPinned(key, !pinned);
},
buttonRef: (el) => {
if (el === null || pinFocusRef.current !== key) return;
pinFocusRef.current = null;
el.focus();
// A row that lands in the folded area is inert and cannot take focus: the chevron
// that unfolds it is the nearest place to stand. It is read once this commit is
// done, since the commit may be mounting the chevron together with the row.
if (document.activeElement !== el) {
queueMicrotask(() => navToggleRef.current?.focus());
}
},
}}
{...(note !== null
? {
ariaLabel: `${label} · ${note}`,
tooltip: note,
badge: <UpdateDot size="inline" position="right-2.5 top-1/2 -translate-y-1/2" />,
}
: {})}
/>
);
};
/**
* The account row at the column's foot: the trigger for the account menu both this sidebar and
* the collapsed rail open (user-menu.tsx).
*/
const accountRow = (
<UserMenu
menuClass="bottom-full left-0 right-0 mb-1 origin-bottom"
trigger={({ open, toggle }) => (
<SidebarAccountButton
expanded={open}
onClick={toggle}
// The dot alone is mysterious: name what is waiting on the trigger (hover tooltip +
// accessible name), in the update row's own wording.
{...(badges.softwareNote !== null
? {
hint: badges.softwareNote,
label: `${user?.displayName ?? user?.userId ?? ""} · ${badges.softwareNote}`,
}
: {})}
avatar={
<UserAvatar
userId={user?.userId ?? "?"}
{...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}
{...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}
>
{/* Update reminder: the menu behind this trigger holds the row that acts on it,
and the trigger's tooltip/label above say what it is. */}
{badges.software !== null && <UpdateDot />}
</UserAvatar>
}
name={user?.displayName ?? user?.userId}
trailing={<PinnedBalanceBadge />}
{...(user?.isAdmin ? { role: S.auth.admin } : {})}
/>
)}
/>
);
/** The dialogs the column's rows and menus open, mounted after the column. */
const dialogs = (
<>
<CreateProjectDialog
open={createProjectOpen}
onClose={() => setCreateProjectOpen(false)}
onCreated={(projectId) => {
setCreateProjectOpen(false);
void reloadProjects().then(() => setCurrentProjectId(projectId));
}}
/>
{currentProject && (
<ProjectSettingsDialog
open={projectSettingsOpen}
onClose={() => setProjectSettingsOpen(false)}
/>
)}
{/* Rename chat */}
<Modal
open={renamingSession !== null}
title={S.chat.renameSession}
onClose={() => (renameBusy ? undefined : setRenamingSession(null))}
footer={
<>
<Button size="sm" onClick={() => setRenamingSession(null)} disabled={renameBusy}>
{S.common.cancel}
</Button>
<Button
size="sm"
variant="primary"
disabled={renameBusy || !renameText.trim()}
onClick={() => void confirmRename()}
>
{S.common.save}
</Button>
</>
}
>
<Input
size="sm"
label={S.chat.renameSessionLabel}
value={renameText}
error={renameError ?? undefined}
autoFocus
maxLength={120}
onChange={(e) => {
setRenameText(e.target.value);
if (renameError) setRenameError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter" && renameText.trim() && !renameBusy) void confirmRename();
}}
/>
</Modal>
{/* Messaging binding dialog (row menu "Messaging binding…"): the row indicator
updates in place from the dialog's own save/unbind outcome. */}
{messagingSession && (
<MessagingBindingModal
sessionId={messagingSession.sessionId}
onClose={() => setMessagingSession(null)}
onChanged={(sessionId, channel) => {
const current = sessions.find((x) => x.sessionId === sessionId);
if (!current) return;
const updated = { ...current };
if (channel !== null) updated.messagingChannel = channel;
else delete updated.messagingChannel;
replace(updated);
}}
/>
)}
{/* Rename workspace (alias edit, same Modal + Input idiom as rename chat): the alias
replaces the directory basename as the group label; leaving it blank reverts to
the basename — so an empty save is valid here, unlike the chat rename. */}
<Modal
open={renamingWorkspace !== null}
title={S.chat.renameWorkspace}
onClose={() => setRenamingWorkspace(null)}
footer={
<>
<Button size="sm" onClick={() => setRenamingWorkspace(null)}>
{S.common.cancel}
</Button>
<Button size="sm" variant="primary" onClick={confirmRenameWorkspace}>
{S.common.save}
</Button>
</>
}
>
<Input
size="sm"
label={S.chat.renameWorkspaceLabel}
hint={S.chat.renameWorkspaceHint}
value={workspaceAliasText}
placeholder={renamingWorkspace ? workspaceLabel(renamingWorkspace.path) : ""}
autoFocus
maxLength={80}
onChange={(e) => setWorkspaceAliasText(e.target.value)}
onKeyDown={(e) => {
// isComposing guard (the repo's IME convention, cf. workspace-select.tsx):
// accepting a Chinese candidate fires Enter, which would save the raw pinyin.
if (e.key === "Enter" && !e.nativeEvent.isComposing) confirmRenameWorkspace();
}}
/>
</Modal>
{/* Delete chat confirmation (shared ConfirmModal) */}
<ConfirmModal
open={deletingSession !== null}
title={S.chat.deleteSession}
confirmLabel={S.common.delete}
cancelLabel={S.common.cancel}
busy={deletingBusy}
onClose={() => (deletingBusy ? undefined : setDeletingSession(null))}
onConfirm={() => void confirmDeleteSession()}
refusal={deleteRefusal === null ? undefined : S.common.refused(deleteRefusal)}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{deletingSession
? S.chat.deleteSessionConfirm(deletingSession.title ?? S.chat.defaultSessionTitle)
: ""}
</p>
</ConfirmModal>
{/* Batch delete confirmation: the same shared ConfirmModal as the row's own, asked once for
the whole selection instead of once per row. A partially refused batch keeps the card:
its count and the ticks are then exactly the rows still left to delete. */}
<ConfirmModal
open={batchConfirmDelete}
title={S.chat.batchDeleteTitle}
confirmLabel={S.common.delete}
cancelLabel={S.common.cancel}
busy={batchBusy}
onClose={() => (batchBusy ? undefined : setBatchConfirmDelete(false))}
onConfirm={() => void confirmBatchDelete()}
refusal={batchDeleteRefusal === null ? undefined : batchDeleteRefusal}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{S.chat.batchDeleteConfirm(batchSelected.size)}
</p>
</ConfirmModal>
{/* Remove-workspace confirmation (shared ConfirmModal, same stop as the other
destructive-looking actions): the copy is honest about the scope — sidebar
registry entry only, disk and Sessions untouched, re-addable anytime. */}
<ConfirmModal
open={deletingWorkspace !== null}
title={S.chat.deleteWorkspace}
confirmLabel={S.common.delete}
cancelLabel={S.common.cancel}
onClose={() => setDeletingWorkspace(null)}
onConfirm={confirmDeleteWorkspace}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{deletingWorkspace ? S.chat.deleteWorkspaceConfirm(deletingWorkspace.label) : ""}
</p>
</ConfirmModal>
{/* Delete parked-draft confirmation: purely local (localStorage entry), but the typed
content is gone for good, which deserves the same explicit stop as a session. */}
<ConfirmModal
open={deletingDraft !== null}
title={S.chat.deleteDraft}
confirmLabel={S.common.delete}
cancelLabel={S.common.cancel}
onClose={() => setDeletingDraft(null)}
onConfirm={confirmDeleteDraft}
>
<p className="text-sm text-gray-600 dark:text-gray-300">
{deletingDraft
? S.chat.deleteDraftConfirm(draftSessionTitle(deletingDraft) || S.chat.draftUntitled)
: ""}
</p>
</ConfirmModal>
</>
);
return (
<SidebarFrame
rootRef={rootRef}
// The work-mode switch, above the Project switcher: 开发 | 公司. Rendered only while
// company mode is available (the admin master switch and the user's own switch both on);
// the choice persists per user. The 内测版 tag rides on 公司 — the switch is the one
// control that names the mode, so the mark stands on the word it qualifies rather than
// somewhere inside the mode it describes.
{...(company.available
? {
modeSwitch: {
label: S.company.workMode,
control: (
<Segmented
options={[
{ value: "dev" as const, label: S.company.modeDev },
{
value: "company" as const,
label: S.company.modeCompany,
badge: { node: <CompanyBetaBadge />, name: S.company.beta },
},
]}
value={company.workMode}
onChange={switchMode}
cols={2}
/>
),
},
}
: {})}
{...(onCollapse
? {
collapse: { label: S.nav.collapseSidebar, tooltip: collapseTitle, onClick: onCollapse },
}
: {})}
switcher={
// The Project switcher; the organization switcher in company mode.
inCompany ? (
<OrgSwitcher {...(onNavigate ? { onNavigate } : {})} />
) : (
<Dropdown
open={projectOpen}
setOpen={setProjectOpen}
className="min-w-0 flex-1"
menuClass="left-0 right-0 top-full mt-1 origin-top"
button={
<SidebarSwitcherButton
label={currentProject ? projectDisplayName(currentProject) : S.common.loading}
onClick={() => setProjectOpen(!projectOpen)}
/>
}
>
{/* Plain rows rather than a role="menu": the switcher's Project rows are named
like its trigger, and both are reached as buttons. */}
{projects.map((p) => (
<MenuRadioItem
key={p.projectId}
label={<span className="font-sans">{projectDisplayName(p)}</span>}
trailing={<Badge>{p.role}</Badge>}
checked={p.projectId === currentProject?.projectId}
onSelect={() => {
setCurrentProjectId(p.projectId);
setProjectOpen(false);
}}
/>
))}
<MenuSeparator />
<MenuItem
glyph={ICONS.plus}
label={S.project.create}
onSelect={() => {
setProjectOpen(false);
setCreateProjectOpen(true);
}}
/>
{currentProject && (
<MenuItem
glyph={ICONS.gear}
label={S.project.settings}
onSelect={() => {
setProjectOpen(false);
setProjectSettingsOpen(true);
}}
/>
)}
</Dropdown>
)
}
// New chat: always pinned, in the one slot between the switcher above and the scroll area
// below; it has no pin button and cannot be dragged. A page row like the nav's (no fill at
// rest), told apart by its place and its weight, and lit while on the draft page. Its slot
// belongs to the pinned area, so it also takes an entry dragged out of the collapsible
// one. Company mode pins nothing here: a channel is made rarely, so "New channel" is the
// channel list's own header action rather than a permanent row (channel-sidebar.tsx).
{...(inCompany
? {}
: {
pinned: (
<SidebarNavArea drop={navAreaDrop("pinned")}>
<NavRow
surface="muted"
label={S.chat.newSessionMenu}
tooltip={newChatTitle}
// The title adds the shortcut when one is bound.
tooltipExtra={newChatTitle !== S.chat.newSessionMenu}
glyph={NEW_CHAT_ICON}
active={activeSessionId === DRAFT_SESSION_ID}
onClick={() => newChat()}
className="font-medium"
/>
</SidebarNavArea>
),
})}
account={accountRow}
overlays={dialogs}
>
{/* The page nav: in development mode the pinned pages, then the collapsible ones folded
away under the slim toggle (with nothing collapsible there is no toggle); in company
mode the organization's six pages, all under the toggle. The fold persists. Folded rows
stay mounted — the fold animates their height to zero and turns them inert. The nav
and the session list scroll together. Mid-drag, an empty pinned run keeps a row's
height and a hidden toggle band comes back, so either side can take the drop. */}
<SidebarNavGroup
collapsed={navCollapsed}
onToggle={toggleNavGroup}
expandLabel={S.nav.expandGroup}
collapseLabel={S.nav.collapseGroup}
toggleRef={navToggleRef}
{...(inCompany
? {}
: {
pinned:
pinnedNavPages.length > 0 || navDrag !== null ? (
<SidebarNavArea
drop={navAreaDrop("pinned")}
reserve={pinnedNavPages.length === 0}
>
{pinnedNavPages.map(renderNavEntry)}
</SidebarNavArea>
) : undefined,
foldable: collapsibleNavPages.length > 0 || navDrag !== null,
drop: navAreaDrop("collapsible"),
})}
>
{inCompany
? companyNavItems.map((item) => (
/* A row with nowhere to go keeps its place and its glyph, muted, with nothing to
click or tab to. */
<NavRow
key={item.key}
surface="muted"
label={item.label}
glyph={item.icon}
href={item.to ?? ""}
disabled={item.to === null}
active={item.to !== null && isCurrentPath(item.to, location.pathname)}
renderLink={renderRouterLink}
onClick={() => onNavigate?.()}
/>
))
: collapsibleNavPages.map(renderNavEntry)}
</SidebarNavGroup>
{inCompany ? (
navOrg !== null ? (
/* Company mode: the organization's channels, where development mode lists
conversations, and below them its 工位 group — one row per employee's desk. */
<>
<ChannelSidebar
projectId={navOrg.projectId}
orgId={navOrg.orgId}
{...(onNavigate ? { onNavigate } : {})}
/>
<OrgSessionGroups
projectId={navOrg.projectId}
orgId={navOrg.orgId}
activeSessionId={activeSessionId}
{...(onNavigate ? { onNavigate } : {})}
/>
</>
) : (
/* No organization to list: the create block, not an empty channel list. */
<NoOrganizationsSidebar {...(onNavigate ? { onNavigate } : {})} />
)
) : (
<>
{/* The list's header: its label and the controls (icon + tooltip family) — search, list
settings (grouping + sort radios), and the mode-dependent create button (the created
object follows the grouping mode). The search opens in place, over the label's
column, so it costs no extra row; the magnifier becomes the field's leading glyph.
No ruled separator at this boundary — the nav toggle above is the seam. The label
names the grouping: workspaces, agents, or the recent ones by time. */}
<SidebarListHeader label={S.chat.sessionListByMode[groupMode]} searching={searchOpen}>
{searchOpen ? (
/* Expanded field: the magnifier, the input and the clear ×, one bordered
box filling the row (its width rides the column tween). Esc and × both
collapse it and drop the filter, which is why the × stays while it is empty. */
<SearchInput
ref={searchInputRef}
icon
alwaysClearable
autoFocus
className="min-w-0 flex-1"
value={searchQuery}
onChange={setSearchQuery}
onClear={closeSearch}
placeholder={S.chat.searchSessionsPlaceholder}
aria-label={S.chat.searchSessions}
clearLabel={S.chat.searchClear}
/>
) : (
<SidebarControl
label={S.chat.searchSessions}
tooltip={searchTitle}
glyph={ICONS.search}
onClick={() => setSearchOpen(true)}
/>
)}
{/* Batch processing, right beside 搜索会话 (the requirement box's own batch bar is the
model): while it is on the rows are pickers and the bar below acts on the ticked
ones. */}
<SidebarControl
label={S.chat.batchSelect}
glyph={ICONS.listChecks}
active={batchMode}
aria-expanded={batchMode}
onClick={toggleBatchMode}
/>
<Dropdown
open={listSettingsOpen}
setOpen={setListSettingsOpen}
portal={{ direction: "down", align: "right" }}
// Sized to the rows, never to a guess: a fixed narrow width clipped "Group by
// workspace" to "Group by work…", and the rows are the only thing that knows how
// wide they have to be. Same idiom as the finder's own menu.
menuClass="w-max min-w-40 max-w-[calc(100vw-2rem)]"
button={
<SidebarControl
label={S.chat.listSettings}
glyph={ICONS.slidersHorizontal}
active={listSettingsOpen}
aria-haspopup="menu"
aria-expanded={listSettingsOpen}
onClick={() => setListSettingsOpen(!listSettingsOpen)}
/>
}
>
<Menu density="sm">
<MenuLabel>{S.chat.groupModeSection}</MenuLabel>
<MenuRadioItem
glyph={GROUP_MODE_ICONS.workspace}
label={S.chat.groupByWorkspace}
checked={groupMode === "workspace"}
onSelect={() => {
setGroupMode("workspace");
setListSettingsOpen(false);
}}
/>
<MenuRadioItem
glyph={GROUP_MODE_ICONS.agent}
label={S.chat.groupByAgent}
checked={groupMode === "agent"}
onSelect={() => {
setGroupMode("agent");
setListSettingsOpen(false);
}}
/>
<MenuRadioItem
glyph={GROUP_MODE_ICONS.time}
label={S.chat.groupByTime}
checked={groupMode === "time"}
onSelect={() => {
setGroupMode("time");
setListSettingsOpen(false);
}}
/>
<MenuSeparator />
<MenuLabel>{S.chat.sortModeSection}</MenuLabel>
{/* Manual order is offered only where a drag can actually happen (see canDrag). */}
{canDrag && (
<MenuRadioItem
glyph={SORT_MODE_ICONS.manual}
label={S.chat.sortManual}
checked={sortMode === "manual"}
onSelect={() => {
setSortMode("manual");
setListSettingsOpen(false);
}}
/>
)}
<MenuRadioItem
glyph={SORT_MODE_ICONS.recent}
label={S.chat.sortRecent}
checked={sortMode === "recent"}
onSelect={() => {
setSortMode("recent");
setListSettingsOpen(false);
}}
/>
</Menu>
</Dropdown>
{/* Mode-dependent create — 具体新建的对象按分组方式决定, the icon following
suit (folder+ / robot+, a bottom-right plus badge on the entity's glyph):
agent grouping opens the Agents page's existing create dialog (route
state); workspace grouping opens the SAME directory-browse menu the
draft's workspace picker uses — the picked directory registers as a
workspace group immediately, Sessions or not. Time buckets are not
something to create into, so that mode starts a plain new conversation
and wears the compose glyph without a plus badge. */}
{newEntity === "agent" ? (
<SidebarControl
label={newEntityLabel}
glyph={<AddBadgeIcon base={NAV_ICONS.agents} />}
onClick={() => {
navigate("/agents", { state: { create: true } });
onNavigate?.();
}}
/>
) : newEntity === "chat" ? (
<SidebarControl
label={newEntityLabel}
glyph={<GlyphIcon d={NEW_CHAT_ICON} size={ICON_SIZE.iconButton} />}
onClick={() => newChat()}
/>
) : (
<WorkspaceSelect
// Remount per Project: the picker browses lazily and caches the listing
// for its lifetime, so a long-lived instance would show the PREVIOUS
// Project's directories after a switch — and register that path into the
// new Project's registry.
key={currentProjectId ?? "no-project"}
projectId={currentProjectId ?? ""}
workspace=""
onChange={addWorkspace}
// The sidebar's + is where a workspace is CREATED, so it is where the
// machine is chosen; the draft and settings pickers edit a workspace that
// already has one.
chooseMachine
clearable={false}
trigger={(open, toggle) => (
<SidebarControl
label={newEntityLabel}
glyph={<AddBadgeIcon base={ICONS.folder} />}
active={open}
aria-expanded={open}
onClick={toggle}
/>
)}
/>
)}
</SidebarListHeader>
{/* The batch bar: it stands over the list only while something is ticked, so the column
loses no row to a control that has nothing to act on — the same rule the requirement
box's batch bar follows. Every action goes through the route the row's own menu
already uses (one PATCH or DELETE per conversation), and the delete keeps its
confirmation, now asked once for the whole selection. A refused archive / unarchive
answers in the bar itself: it acts without asking, so there is no card to keep. */}
{batchMode && batchSelected.size > 0 && (
<div className="mt-2 flex flex-wrap items-center gap-1 rounded-md border border-line-emphasis px-2 py-1.5">
<span className="mr-auto px-0.5 text-xs text-fg-muted">
{S.chat.batchCount(batchSelected.size)}
</span>
<Button
size="xs"
variant="secondary"
disabled={batchBusy}
onClick={() => void batchSetArchived(true)}
>
{S.chat.batchArchive}
</Button>
<Button
size="xs"
variant="secondary"
disabled={batchBusy}
onClick={() => void batchSetArchived(false)}
>
{S.chat.batchUnarchive}
</Button>
<Button
size="xs"
variant="danger"
disabled={batchBusy}
onClick={() => {
// One attempt, one reason: opening the card again never carries the last one over.
setBatchDeleteRefusal(null);
setBatchConfirmDelete(true);
}}
>
{S.chat.batchDelete}
</Button>
<Button size="xs" variant="link" disabled={batchBusy} onClick={clearBatchSelection}>
{S.chat.batchClear}
</Button>
{/* An archive / unarchive the server refused: nothing else on screen moved, the refused
rows are still ticked right below, and the two buttons above are the retry — so the
reason stays in the bar that sent it (the delete's own card is not involved). */}
{batchArchiveRefusal !== null && (
<p
role="alert"
data-testid="batch-archive-refusal"
data-tooltip={batchArchiveRefusal}
data-tooltip-content="text"
className={`w-full line-clamp-2 break-words px-0.5 text-xs ${toneInk.danger}`}
>
{batchArchiveRefusal}
</p>
)}
</div>
)}
{/* Parked draft conversations (unsent new chats, newest first): pinned above both
grouping modes — they belong to no Agent or Workspace until sent. Hidden
entirely while there are none; the search filter applies to their titles too. */}
{shownDrafts.length > 0 && (
<div className="pt-2.5">
<GroupHeader
open={searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)}
onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}
glyph={NEW_CHAT_ICON}
label={S.chat.draftGroup}
uppercase
count={shownDrafts.length}
/>
{(searching || !collapsedGroups.has(DRAFTS_GROUP_KEY)) && (
<ul className="space-y-px">
{shownDrafts.map((entry) => (
<DraftRow
key={entry.id}
entry={entry}
active={entry.id === activeSessionId}
onOpen={() => go(`/chat/${entry.id}`)}
onDelete={() => setDeletingDraft(entry)}
/>
))}
</ul>
)}
</div>
)}
{groupMode === "agent" ? (
loading && agents.length === 0 ? (
<SkeletonList rows={5} />
) : (
// While searching: every group renders (paging bypassed), zero-match groups
// hide, and the rest are forced open — a hit inside a collapsed group would
// look like a missing result.
groupsOnPage(orderedAgents).map((agent) => {
const groupRows = filterRows(byAgent.get(agent.agentId) ?? []);
if (searching && groupRows.length === 0) return null;
const parts = partitionSessions(groupRows);
/** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
const foldedOnly = folderOnlyAgents.get(agent.agentId);
const collapsed =
!searching &&
(foldedOnly === undefined
? collapsedGroups.has(agent.agentId)
: !expandedFolderOnlyGroups.has(agent.agentId));
const pinned = pinnedGroups.has(agent.agentId);
const drag = groupDragProps(agent.agentId, agentGroupSequence);
return (
<GroupBlock key={agent.agentId} dropEdge={drag.dropEdge}>
{/* Group header: collapse toggle (Agent name) + pin + new chat + Agent settings; also the group's drag handle. */}
<GroupHeader
{...drag.header}
open={!collapsed}
onToggle={() => toggleGroup(agent.agentId, foldedOnly !== undefined)}
icon={
<AgentAvatar
id={agent.agentId}
name={agentDisplayName(agent)}
size={18}
className="shrink-0 rounded"
/>
}
label={agentDisplayName(agent)}
uppercase
{...(foldedOnly === undefined
? {}
: {
// An Agent header carries no count otherwise; a folder-only one says
// what it holds, because everything it holds is behind its folders.
count: foldedOnly,
muted: true,
title: S.chat.folderOnlyGroup(foldedOnly),
})}
actions={
<>
<GroupPinButton
pinned={pinned}
onToggle={() => togglePin(agent.agentId)}
/>
{/* New chat: enters draft state directly with this group's Agent (all options live on the draft input card) */}
<button
type="button"
data-tooltip={S.chat.newSessionMenu}
aria-label={S.chat.newSessionMenu}
onClick={() => newChat({ agentId: agent.agentId })}
className={GROUP_ACTION_CLASS}
>
<Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />
</button>
<button
type="button"
data-tooltip={S.agent.settings}
aria-label={S.agent.settings}
onClick={() => go(`/agents/${agent.agentId}`)}
className={GROUP_ACTION_CLASS}
>
<Icon d={ICONS.gear} size={ICON_SIZE.groupHeaderAction} />
</button>
</>
}
/>
{collapsed
? null
: renderGroupBody(
agent.agentId,
parts,
false,
countsByAgent.get(agent.agentId),
() => [agent.agentId],
)}
</GroupBlock>
);
})
)
) : null}
{groupMode === "agent" ? groupPagerRow() : null}
{groupMode !== "workspace" ? null : loading && sessions.length === 0 ? (
<SkeletonList rows={5} />
) : orderedWorkspaceGroups.length === 0 && !searching ? (
<p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
{S.chat.noSessions}
</p>
) : (
// Same search treatment as agent mode: paging bypassed, zero-match groups hidden, the rest forced open.
groupsOnPage(orderedWorkspaceGroups).map((group) => {
const groupRows = filterRows(group.sessions);
if (searching && groupRows.length === 0) return null;
const parts = partitionSessions(groupRows);
/** Conversations folded inside a folder-only group; undefined = an ordinary group, with active rows of its own. */
const foldedOnly = folderOnlyWorkspaceGroups.get(group.key);
const collapsed =
!searching &&
(foldedOnly === undefined
? collapsedGroups.has(group.key)
: !expandedFolderOnlyGroups.has(group.key));
const pinned = pinnedGroups.has(group.key);
/**
* Header tooltip: the full Workspace path, or — for a folder-only group — the
* sentence that says what the dimmed header and its count mean, which carries that
* same path inside it.
*/
const qualifiedPath =
group.fullPath !== null
? nameOnMachine(group.fullPath, machineNameOf(group.machineId))
: null;
const headerTitle =
foldedOnly === undefined
? qualifiedPath
: S.chat.folderOnlyGroup(foldedOnly, qualifiedPath ?? undefined);
const drag = groupDragProps(group.key, workspaceGroupSequence);
/** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */
const counts = workspaceGroupCounts.get(group.key);
/** Read once so the registry actions below keep the narrowing (null = the merged temp group, which has no single path). */
const fullPath = group.fullPath;
/** The ssh alias qualifying this group's names, or null when it is on this server. */
const machineName = machineNameOf(group.machineId);
const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];
const agentsFor = (category: SessionCategory) => [
...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),
];
return (
<GroupBlock key={group.key} dropEdge={drag.dropEdge}>
{/* Group header: collapse toggle (folder icon + directory basename + count, full
path in the tooltip; the count = the group's active conversations only, exact
server share, loaded rows win a disagreement — the folders never feed it,
except in a folder-only group, where they are all there is to count) +
pin + new chat in this Workspace; also the group's drag handle. */}
<GroupHeader
{...drag.header}
open={!collapsed}
onToggle={() => toggleGroup(group.key, foldedOnly !== undefined)}
// The folder opens and closes with the group.
glyph={collapsed ? ICONS.folder : ICONS.folderOpen}
label={nameOnMachine(
group.temp ? S.chat.tempWorkspaces : group.label,
machineName,
)}
count={
foldedOnly !== undefined
? foldedOnly
: searching
? parts.active.length
: Math.max(counts?.totals.active ?? 0, parts.active.length)
}
muted={foldedOnly !== undefined}
{...(headerTitle !== null ? { title: headerTitle } : {})}
actions={
<>
<GroupPinButton pinned={pinned} onToggle={() => togglePin(group.key)} />
{/* New chat in this Workspace: pre-fills the group's path in the draft ("" = temporary workspace); the Agent is the Project's new-chat default, like any other new chat */}
<button
type="button"
data-tooltip={S.chat.newSessionInWorkspace}
aria-label={S.chat.newSessionInWorkspace}
onClick={() =>
newChat({
workspace: fullPath ?? "",
// The machine travels with the path: this group's rows live on it,
// and the same path here is a different directory (or none).
...(group.machineId ? { machineId: group.machineId } : {}),
})
}
className={GROUP_ACTION_CLASS}
>
<Icon d={ICONS.plus} size={ICON_SIZE.groupHeaderAction} />
</button>
{/* A group that is one directory (not the merged temporary group):
the overflow right of the "+" — browse its files, remove the
group from the sidebar (every Workspace has that, session-derived
ones included: the removal hides the group, it does not delete
anything), and, for a manually-added (registry-backed) Workspace,
rename the alias — an alias lives in the registry entry, which a
session-derived group has none of. */}
{fullPath !== null && (
<GroupOverflowMenu
onBrowse={() => browseFiles(fullPath, group.machineId)}
{...(registeredKeys.has(group.key)
? { onRename: () => openRenameWorkspace(fullPath, group.machineId) }
: {})}
onDelete={() =>
setDeletingWorkspace({
path: fullPath,
machineId: group.machineId,
label: group.label,
})
}
/>
)}
</>
}
/>
{/* A workspace group can span Agents: the group body fans folder loads and "More"
out per category to the Agents whose share of THIS group is non-zero (plus the
Agents already contributing loaded rows) — the active list and each folder
page independently. */}
{collapsed
? null
: renderGroupBody(group.key, parts, true, counts?.totals, agentsFor)}
</GroupBlock>
);
})
)}
{groupMode === "workspace" ? groupPagerRow() : null}
{/* Time mode: last day / last month / earlier, bucketed on each conversation's last
activity — the same stamp the rows' compact timestamps and the recency sort read,
so a row can never sit under a bucket its own timestamp contradicts. Empty buckets
are dropped, and there are at most three, so this mode never paginates its groups.
The buckets span every Agent and every Workspace: a bucket's "More" only reveals
further rows already shown in it, while fetching the next page and reaching the
Subagents / Scheduled / Archived rows happen once for the whole Project, below. */}
{groupMode !== "time" || timeParts === null ? null : loading && sessions.length === 0 ? (
<SkeletonList rows={5} />
) : (
<>
{timeGroups.map((group) => {
const collapsed = !searching && collapsedGroups.has(group.key);
return (
<div key={group.key} className="pt-2.5">
<GroupHeader
open={!collapsed}
onToggle={() => toggleGroup(group.key)}
glyph={GROUP_MODE_ICONS.time}
label={S.chat.timeGroups[group.bucket]}
uppercase
count={group.sessions.length}
/>
{collapsed
? null
: renderGroupBody(
group.key,
bucketPartition(group.sessions),
true,
undefined,
() => [],
)}
</div>
);
})}
{/* Empty only when the shared folders below are empty too (renderGroupBody's own
rule): "no Sessions yet" over an "Archived (3)" row would contradict it. */}
{timeGroups.length === 0 && !searching && timeFolders.every((f) => f === null) && (
<p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
{S.chat.noSessions}
</p>
)}
{/* Whole-list paging: every Agent stream with more advances a page, which lowers
the watermark and adds rows below the last one shown — in whichever bucket
their activity puts them, so the row that pulls them belongs to the list, not
to a bucket, and its label says "conversations" where a bucket's says "more".
It stands while any stream has more (the server's limit+1 answer). */}
{!searching && timeMoreAgents.length > 0 && (
<MoreRow
label={S.chat.loadMoreSessions}
ariaLabel={S.chat.loadMoreSessions}
pending={pendingLoads.has(loadKey(TIME_FOLDERS_GROUP_KEY, "active"))}
onClick={() => trackedLoadMore(TIME_FOLDERS_GROUP_KEY, "active", timeMoreAgents)}
className="mt-1"
/>
)}
{/* The shared, Project-wide folders (see timeFolders). */}
<div className="pt-2.5">{timeFolders}</div>
</>
)}
{/* Quiet no-match line: the search is live and nothing — drafts included — hit. */}
{searching && !hasSearchMatches && (
<p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">
{S.chat.searchNoMatches}
</p>
)}
</>
)}
</SidebarFrame>
);
}
/** Single parked-draft row: first line of the unsent text + delete (opening resumes the draft at `/chat/<draft-id>`). */
function DraftRow({
entry,
active,
onOpen,
onDelete,
}: {
entry: DraftSessionEntry;
active: boolean;
onOpen: () => void;
onDelete: () => void;
}) {
const title = draftSessionTitle(entry) || S.chat.draftUntitled;
return (
<li>
<div
// Same truncated-title scroll reveal as the session rows (#309).
data-title-reveal
className={`group flex items-center rounded-md pr-1 transition-colors duration-150 ${
active ? NAV_FILL.selected : NAV_FILL.hover
}`}
>
<button
type="button"
onClick={onOpen}
className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left"
>
<Truncated
scrollReveal
text={title}
// The conversation rows' inks (SessionRow), so a parked draft reads as one of them.
className={`min-w-0 flex-1 font-sans text-sm ${
active ? "font-medium text-fg" : "text-fg/80"
}`}
/>
</button>
<div className="flex shrink-0 items-center">
{/* Always on below `sm`, hover/focus-revealed from `sm` up — the same rule the message
footer's copy button follows. A parked draft is the ONE row whose only exit is this
button (a Session also has the row menu), and `group-hover` never matches on a touch
screen, so a hover-only button left drafts undeletable on a phone. */}
<button
type="button"
data-tooltip={S.chat.deleteDraft}
aria-label={S.chat.deleteDraft}
onClick={onDelete}
className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-100 transition-[opacity,background-color,color] duration-150 hover:bg-gray-300/60 hover:text-red-600 focus-visible:opacity-100 sm:opacity-0 sm:group-hover:opacity-100 dark:hover:bg-gray-700 dark:hover:text-red-400"
>
<Icon d={ICONS.trash} size={14} />
</button>
</div>
</div>
</li>
);
}
/**
* One group's block — its header and body — carrying the manual group order's drop
* indicator: a thin accent line in the gap the drop would land in, drawn against the
* WHOLE group rather than its header, so "below" reads as "after this group and its
* conversations" instead of "between the header and its own first row".
*
* The line is absolutely positioned and `inset-x-1` (matching the header's `px-1`), so
* it consumes no layout width and cannot push the header's up-to-three action buttons
* out of a narrow drawer.
*/
function GroupBlock({
dropEdge,
children,
}: {
/** Which edge of this group a drop would land on while a group drag hovers it. */
dropEdge: "above" | "below" | null;
children: ReactNode;
}) {
return (
<div className="relative pt-2.5">
{dropEdge !== null && (
<div
aria-hidden
className={`pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent ${
dropEdge === "above" ? "top-1" : "-bottom-1"
}`}
/>
)}
{children}
</div>
);
}
/**
* Group-header pin toggle, shared by both grouping modes: revealed on header hover (or
* keyboard focus) while unpinned; once pinned it stays visible, doubling as the subtle
* pinned indicator. The header row carries the `group/header` scope so the reveal only
* reacts to its own row, not to the session rows' plain `group` scope.
* The accessible name stays STATIC and aria-pressed alone carries the state (the toggle
* pattern the grouping-mode buttons use) — a name that swaps Pin/Unpin alongside
* aria-pressed reads as "Unpin group, pressed", saying the state twice in conflicting
* ways. The title tooltip may still swap: it is presentation for pointer users and does
* not feed the accessible name while aria-label is present.
*/
function GroupPinButton({ pinned, onToggle }: { pinned: boolean; onToggle: () => void }) {
return (
<button
type="button"
data-tooltip={pinned ? S.nav.unpinGroup : S.nav.pinGroup}
aria-label={S.nav.pinGroup}
aria-pressed={pinned}
onClick={onToggle}
className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-md transition-[opacity,background-color,color] duration-150 hover:bg-fg/7 hover:text-fg ${
pinned
? "text-fg-muted"
: "text-fg-subtle opacity-0 focus-visible:opacity-100 group-hover/header:opacity-100"
}`}
>
<Icon d={ICONS.pin} size={ICON_SIZE.groupHeaderAction} />
</button>
);
}
/**
* One conversation row: the package's `SessionRow`, bound to this Session. The row itself — the
* title with its marks, the trailing slot that swaps the last-active time for archive and the
* "more" button on hover or focus, and the context menu a right-click, Shift+F10 or a
* press-and-hold opens — is the package's; this container says which actions each surface
* carries (session-row-menu.tsx), what each one does, and in which words the marks name
* themselves.
*
* The hover pair is the affordance every release up to v0.2.2 shipped (archive as a direct icon
* button), the rest of the set one click further; the full set stays one right-click away.
*
* A truncated title scrolls its tail into view while the row is hovered or keyboard-focused
* (#309; Truncated's scrollReveal, keyed on the row's `data-title-reveal`). No `title` tooltip
* comes with it: it would sit over the very text scrolling past underneath. Under
* prefers-reduced-motion nothing scrolls and the conditional hint returns instead.
*/
function SidebarSessionRow({
s,
active,
activity,
background,
scheduled,
pinned,
canPin = false,
lastActive,
locale,
agentHint,
select,
draggable = false,
dropEdge = null,
onDragStart,
onDragEnd,
onDragOver,
onDragLeave,
onDrop,
onOpen,
onTogglePin,
onRename,
onMessaging,
onDelete,
onToggleArchive,
}: {
s: SessionInfo;
active: boolean;
/** Busy / settled-read / settled-unread / never-ran, already resolved by sessionRowActivity. */
activity: SessionActivity;
/** Background tasks the Session still owns (sessionBackgroundTasks); 0 draws no mark. */
background: number;
/** A scheduled task still to fire is bound to this Session (pendingScheduleSessions); false draws no mark. */
scheduled: boolean;
/** Row is pinned (bubbled to its group's top; small pin glyph on the title). */
pinned: boolean;
/** Whether pinning can actually reorder this row — active-list rows only; folder rows hide the action (see renderRows). */
canPin?: boolean;
/** Preformatted compact last-active time ("" hides the slot's resting text). */
lastActive: string;
/** Interface language: decides the fixed width the time slot reserves (SessionRow's `timeSlot`). */
locale: "zh" | "en";
/** Agent display name; when set (workspace mode) a small avatar keeps the Agent context visible on the row. */
agentHint?: string;
/** Batch mode: the row is a picker, ticked or not (the label names it after the conversation). */
select?: { checked: boolean; onToggle: () => void };
/** Manual sort: the row can be drag-reordered (the sidebar wires the handlers below). */
draggable?: boolean;
/** Drop indicator edge while another row hovers over this one (a thin accent line above/below). */
dropEdge?: "above" | "below" | null;
onDragStart?: (e: ReactDragEvent) => void;
onDragEnd?: () => void;
onDragOver?: (e: ReactDragEvent) => void;
onDragLeave?: () => void;
onDrop?: (e: ReactDragEvent) => void;
onOpen: (s: SessionInfo) => void;
onTogglePin: (s: SessionInfo) => void;
onRename: (s: SessionInfo) => void;
onMessaging: (s: SessionInfo) => void;
onDelete: (s: SessionInfo) => void;
onToggleArchive: (s: SessionInfo) => void;
}) {
/** Run one action on this Session (the row has closed its menu first). */
const run = (action: SessionRowAction) => {
const handler: Record<SessionRowAction, (x: SessionInfo) => void> = {
pin: onTogglePin,
rename: onRename,
// The copy affordance's feedback normally rides on the button itself (copy-button.tsx),
// which a menu row cannot do: the row acts and the panel closes under it. A toast is
// the confirmation that survives that, and it says the same word — once the write
// has landed.
copy: (x) => {
void writeClipboard(x.sessionId).then((ok) => ok && toastSuccess(S.common.copied));
},
messaging: onMessaging,
archive: onToggleArchive,
delete: onDelete,
};
handler[action](s);
};
const rowState = { archived: s.archived, pinned };
return (
<SessionRow
sessionId={s.sessionId}
renderTitle={(className) => (
<Truncated
scrollReveal
text={s.title ?? S.chat.defaultSessionTitle}
className={className}
/>
)}
active={active}
archived={s.archived}
{...(agentHint !== undefined ? { agent: { id: s.agentId, name: agentHint } } : {})}
// The marks for the row's STANDING arrangements, all in one dim cluster: which program
// opened it (a Background row's source), how the row is filed (pinned — only where pinning
// reorders anything), where it can be reached from (the messaging relay, named by its
// channel), whether it runs on its own (a scheduled task still to fire; a paused or ended
// one draws nothing) and whether it owns work that outlives the turn (background tasks,
// live via session_background).
{...(backgroundSourceMark(s) ?? {})}
{...(pinned && canPin ? { pinnedLabel: S.chat.pinnedSession } : {})}
{...(s.messagingChannel !== undefined
? { relayLabel: S.messaging.enabledIndicator[s.messagingChannel] }
: {})}
{...(scheduled ? { scheduledLabel: S.chat.sessionScheduled } : {})}
background={{ count: background, label: S.chat.backgroundTasks(background) }}
activity={
activity === null ? null : { state: activity, label: sessionActivityLabel(activity) }
}
approvals={{
count: s.pendingApprovalCount,
label: S.chat.pendingApprovals(s.pendingApprovalCount),
}}
time={lastActive}
// Sized for the widest compact time each language produces — 「12月31日」 and 「59 分钟前」 in
// zh, "Nov 30" in en.
timeSlot={locale === "zh" ? "wide" : "narrow"}
hoverActions={sessionRowActions(HOVER_ROW_ACTIONS, rowState, run)}
menuActions={sessionRowActions(contextMenuActions(canPin), rowState, run)}
moreLabel={S.chat.moreActions}
onOpen={() => onOpen(s)}
{...(select !== undefined
? {
selection: {
checked: select.checked,
label: S.chat.batchSelectRow(s.title ?? S.chat.defaultSessionTitle),
onToggle: select.onToggle,
},
}
: {})}
draggable={draggable}
dropEdge={dropEdge}
{...(onDragStart ? { onDragStart } : {})}
{...(onDragEnd ? { onDragEnd } : {})}
{...(onDragOver ? { onDragOver } : {})}
{...(onDragLeave ? { onDragLeave } : {})}
{...(onDrop ? { onDrop } : {})}
/>
);
}
/**
* A workspace group's overflow (… to the right of the header's "+"): 打开文件浏览, then — for a
* registry-backed group — 重命名工作区 / 删除工作区, as small Menu rows like the session row's
* menu. Sits among the header's action buttons — outside the header's collapse toggle, so
* opening it never expands/collapses the group. Body-portaled like every menu inside the
* scroller.
*/
function GroupOverflowMenu({
onBrowse,
onRename,
onDelete,
}: {
onBrowse: () => void;
onRename?: () => void;
onDelete?: () => void;
}) {
const [open, setOpen] = useState(false);
/** Close first, then act (the rename modal opens on top; the delete is immediate). */
const item = (fn: () => void) => () => {
setOpen(false);
fn();
};
return (
<Dropdown
open={open}
setOpen={setOpen}
portal={{ direction: "down", align: "right" }}
menuClass="w-max min-w-32"
className="shrink-0"
button={
/* No hover pill on this trigger (user: color, not background, should carry the
hover hint) — feedback is the glyph deepening in light / brightening in dark,
the session-row ellipsis treatment. Geometry: the same h-7 w-7 square as the
sibling "+" and the LAST action in the header, flush at GroupHeader's px-1
inset — which equals the session rows' pr-1, so with the row trigger's 16px
glyph the dot columns line up with the rows' trailing slot below. */
<button
type="button"
data-tooltip={S.chat.workspaceMenu}
aria-label={S.chat.workspaceMenu}
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen(!open)}
className="flex h-7 w-7 shrink-0 items-center justify-center text-gray-500 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-100"
>
<EllipsisGlyph size={16} />
</button>
}
>
<Menu density="sm">
<MenuItem
glyph={ICONS.folderOpen}
label={S.chat.browseWorkspaceFiles}
onSelect={item(onBrowse)}
/>
{onRename !== undefined && (
<MenuItem glyph={ICONS.pencil} label={S.chat.renameWorkspace} onSelect={item(onRename)} />
)}
{onDelete !== undefined && (
<MenuItem
glyph={ICONS.trash}
label={S.chat.deleteWorkspace}
danger
onSelect={item(onDelete)}
/>
)}
</Menu>
</Dropdown>
);
}