Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

38.4 KB
Raw Blame
import type { TranslationKey } from '@/i18n/types';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom';
import {
  Activity,
  Archive,
  Bot,
  ChevronDown,
  ChevronRight,
  CodeXml,
  Ellipsis,
  FileText,
  Folder,
  FolderOpen,
  FolderPlus,
  Inbox,
  KeyRound,
  Loader2,
  Pencil,
  Plus,
  Search,
  Settings2,
  WandSparkles,
} from 'lucide-react';
import clsx from 'clsx';
import type { LucideIcon } from 'lucide-react';

import { useSidebarSectionOpen } from '../../lib/sidebarSectionsMemory';
import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
import { useLatestRef } from '../../lib/useLatestRef';

import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsActions, useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { SessionPinAction } from './SessionPinAction';
import {
  SESSION_ROW_INDENT_CLASS,
  SESSION_ROW_MENU_POSITION_CLASS,
  SESSION_STATUS_DOT_MOTION_CLASS,
} from './sessionRowLayout';
import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';
import { useSessionActions } from './useSessionActions';
import { canCreateLocalProject } from '../../lib/sessionInfo';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { NewProjectDialog } from './NewProjectDialog';
import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
import { ProjectSettingsDialog } from './ProjectSettingsDialog';
import { SortableProjectList, type ProjectDragHandle } from './SortableProjectList';
import { BotStrip } from './bots/BotStrip';
import { InboxHoverPopover } from './InboxHoverPopover';
import logoImg from '../../assets/logo.png';

interface CapabilityNavItem {
  to: string;
  i18nKey: TranslationKey;
  icon: LucideIcon;
}

const CAPABILITY_NAV: CapabilityNavItem[] = [
  { to: '/agents', i18nKey: 'workbench.nav.agents', icon: Bot },
  { to: '/skills', i18nKey: 'workbench.nav.skills', icon: WandSparkles },
  { to: '/harness', i18nKey: 'workbench.nav.harness', icon: Activity },
  { to: '/vaults', i18nKey: 'workbench.nav.vaults', icon: KeyRound },
];

// One capability row, in the approved compact treatment: a 13px medium label
// behind a 16px icon on a rounded-lg row, with mint reserved for the selected
// state. The mint and foreground opacities are the approved reference's own and
// already follow the theme; they are not interchangeable with the nav tokens.
const SidebarNavRow: React.FC<{
  to: string;
  end?: boolean;
  icon: LucideIcon;
  label: string;
}> = ({ to, end, icon: Icon, label }) => (
  <NavLink
    to={to}
    end={end}
    className={({ isActive }) =>
      clsx(
        'group flex items-center gap-2.5 rounded-lg border px-3 py-2 text-[13px] font-medium transition-colors',
        isActive
          ? 'border-mint/30 bg-mint/[0.08] text-foreground shadow-glow-sm-mint'
          : 'border-transparent text-muted hover:bg-foreground/[0.04] hover:text-foreground',
      )
    }
  >
    {({ isActive }) => (
      <>
        <Icon
          className={clsx(
            'size-4 shrink-0',
            isActive ? 'text-mint-ink' : 'text-muted group-hover:text-foreground',
          )}
        />
        <span className="truncate">{label}</span>
      </>
    )}
  </NavLink>
);

// Session status dot colours. Maps the agent-runtime status to the user's
// gray / green / red: idle → muted (gray), running → mint (green) + glow,
// failed → destructive (red) + glow. Tokens resolve from src/index.css.
// Running also pulses — keyed on nothing but the status, so selection, unread
// count, hover and focus cannot start or stop the motion.
const STATUS_DOT_CLASS: Record<string, string> = {
  running: `bg-mint shadow-glow-dot-mint ${SESSION_STATUS_DOT_MOTION_CLASS}`,
  failed: 'bg-destructive shadow-glow-dot-destructive',
  idle: 'bg-muted',
};

// One session row under a project. Left-click opens the chat; the hover-revealed
// ⋯ (and right-click anywhere on the row) opens the shared session action menu —
// see sessionActions.tsx, which owns the items and the writes for every surface.
// Rename is inline here: the commit calls the provider, whose session.activity
// 'updated' event patches the title in this list, so no manual local patch.
// Exported for the row-level test: the rail's controls only exist when the row's
// Popover can actually open, and that pairing is what a test has to hold onto.
export const SessionRow: React.FC<{
  projectId: string;
  session: WorkbenchSession;
  unread: number;
  canChat: boolean;
  canManageMetadata: boolean;
}> = ({ projectId, session, unread, canChat, canManageMetadata }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { renameSession } = useWorkbenchProjectsActions();
  const location = useLocation();
  const active = location.pathname === `/chat/${session.id}`;
  const [menuOpen, setMenuOpen] = useState(false);
  const [renaming, setRenaming] = useState(false);
  const [draft, setDraft] = useState(session.title ?? '');
  const surfaceActiveRef = useLatestRef(useRouteSurfaceActive());
  const inputRef = useRef<HTMLInputElement | null>(null);
  // Guards a double commit: Enter (or click-away) commits, then the input
  // unmounts and its onBlur would fire commitRename again; Escape cancels and
  // must NOT let that trailing blur commit the stale draft (Codex P2).
  const handledRef = useRef(false);

  const { actions, archiveDialog } = useSessionActions({
    session,
    writable: canManageMetadata,
    lifecycleWritable: canChat,
    projectId,
    onRenameStart: () => {
      setDraft(session.title ?? '');
      handledRef.current = false;
      setRenaming(true);
    },
    // Forking navigates, and useSessionActions runs the unsaved-changes guard
    // itself — before the fork request, so a cancelled prompt writes nothing.
    onOpenSession: (sessionId) => navigate(`/chat/${encodeURIComponent(sessionId)}`),
    // Archiving the chat we are currently viewing leaves it directly — don't rely
    // solely on the replay-less SSE 'archived' event to navigate away.
    onArchived: () => {
      if (active) navigate('/inbox');
    },
  });
  const pinAction = actions.find((action) => action.id === 'pin');

  useEffect(() => {
    if (renaming) inputRef.current?.focus();
  }, [renaming]);

  const commitRename = async () => {
    // Inerting the retained sidebar blurs its input; suspension is not a save.
    if (!surfaceActiveRef.current) return;
    if (handledRef.current) return;
    handledRef.current = true;
    const trimmed = draft.trim();
    setRenaming(false);
    // No-op when unchanged; an empty name clears to "untitled" like the header.
    if (trimmed === (session.title ?? '').trim()) return;
    try {
      await renameSession(projectId, session.id, trimmed);
    } catch {
      // The shared apiFetch layer already surfaced the error toast.
    }
  };

  const cancelRename = () => {
    handledRef.current = true; // suppress the input's trailing onBlur commit
    setRenaming(false);
  };

  if (renaming) {
    return (
      <div
        className={clsx(
          'flex items-center gap-2 border-transparent py-1.5 pr-2.5',
          SESSION_ROW_INDENT_CLASS,
        )}
      >
        <span
          className={clsx(
            'size-[5px] shrink-0 rounded-full',
            STATUS_DOT_CLASS[session.agent_status] ?? STATUS_DOT_CLASS.idle,
          )}
        />
        <Input
          ref={inputRef}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onBlur={commitRename}
          onKeyDown={(e) => {
            if (e.key === 'Enter') commitRename();
            if (e.key === 'Escape') cancelRename();
          }}
          placeholder={t('workbench.sessionRenamePlaceholder')}
          className="h-7 flex-1 px-1.5 text-[12px]"
        />
      </div>
    );
  }

  const displayName = session.title?.trim() || t('workbench.untitledSession');
  return (
    <>
    <Popover open={canManageMetadata && menuOpen} onOpenChange={(open) => canManageMetadata && setMenuOpen(open)}>
      <PopoverAnchor asChild>
        <div
          data-settings-interaction-owner="true"
          onContextMenu={(e) => {
            if (!canManageMetadata) return;
            e.preventDefault();
            setMenuOpen(true);
          }}
          className={clsx(
            'group/sess relative flex items-center gap-2 rounded-md py-1.5 text-left transition-colors duration-150 ease-out motion-reduce:transition-none',
            SESSION_ROW_INDENT_CLASS,
            canManageMetadata ? 'pr-11' : 'pr-2.5',
            // Only the accent's colour turns on with selection; its width is
            // already reserved above, so the row's contents do not move.
            active
              ? 'border-mint bg-mint-soft font-semibold text-foreground'
              : 'border-transparent hover:bg-foreground/[0.04]',
          )}
        >
          <button
            type="button"
            data-settings-interaction-owner="true"
            onClick={() => navigate(`/chat/${encodeURIComponent(session.id)}`)}
            className="flex min-w-0 flex-1 items-center gap-2 text-left focus-visible:outline-none"
          >
            <span
              title={t(`workbench.sessionStatus.${session.agent_status}`)}
              className={clsx(
                'size-[5px] shrink-0 rounded-full',
                STATUS_DOT_CLASS[session.agent_status] ?? STATUS_DOT_CLASS.idle,
              )}
            />
            <span
              className={clsx(
                'flex-1 truncate text-[12px]',
                active ? 'font-semibold text-foreground' : 'font-medium text-foreground',
              )}
            >
              {displayName}
            </span>
            {unread > 0 && (
              <span className="inline-flex min-w-[1.1rem] items-center justify-center rounded-full bg-mint px-1.5 font-mono text-[9px] font-bold text-primary-foreground">
                {unread > 99 ? '99+' : unread}
              </span>
            )}
          </button>
          {canManageMetadata && (
            <>
              {pinAction && (
                <SessionPinAction
                  pinned={session.pinned}
                  pending={Boolean(pinAction.pending)}
                  pinLabel={t('workbench.sessionPin')}
                  unpinLabel={t('workbench.sessionUnpin')}
                  onToggle={pinAction.onSelect}
                />
              )}
              <span className={clsx('absolute inset-y-0 flex items-center', SESSION_ROW_MENU_POSITION_CLASS)}>
                <PopoverTrigger asChild>
                  <SessionActionsTrigger label={t('workbench.sessionActions')} open={menuOpen} />
                </PopoverTrigger>
              </span>
            </>
          )}
        </div>
      </PopoverAnchor>
      <SessionActionMenuContent
        actions={actions}
        label={t('workbench.sessionActions')}
        align="start"
        onClose={() => setMenuOpen(false)}
      />
    </Popover>
    {archiveDialog}
    </>
  );
};

// One project row + (when expanded) the session list under it. Mirrors
// design.pen N96dsm/C68Ul (project row) and C7clY/R2C8U (session row).
const ProjectRow: React.FC<{
  project: WorkbenchProject;
  expanded: boolean;
  sessions: WorkbenchSession[] | null;
  loading: boolean;
  loadingMore: boolean;
  hasMore: boolean;
  onLoadMore: () => void;
  onToggle: () => void;
  onCreateSession: () => void;
  creatingSession: boolean;
  canChat: boolean;
  canManageMetadata: boolean;
  canManageProjects: boolean;
  /** Whether the current runtime policy admits Project archiving. */
  canArchive: boolean;
  /** Whether the current runtime policy admits opening the Project in Editor. */
  canOpenInEditor: boolean;
  /** Whether the current runtime policy admits saving a Project's AGENTS.md. */
  canEditAgentsMd: boolean;
  unreadBySession: Record<string, number>;
  onRename: (next: string) => Promise<void>;
  dragHandle?: ProjectDragHandle;
  onArchive: () => Promise<void>;
}> = ({
  project,
  expanded,
  sessions,
  loading,
  loadingMore,
  hasMore,
  onLoadMore,
  onToggle,
  onCreateSession,
  creatingSession,
  canChat,
  canManageMetadata,
  canManageProjects,
  canArchive,
  canOpenInEditor,
  canEditAgentsMd,
  unreadBySession,
  onRename,
  dragHandle,
  onArchive,
}) => {
  const { t } = useTranslation();
  const wm = useWindowManager();
  const Chevron = expanded ? ChevronDown : ChevronRight;
  const [renaming, setRenaming] = useState(false);
  const [renameDraft, setRenameDraft] = useState(project.display_name);
  const surfaceActiveRef = useLatestRef(useRouteSurfaceActive());
  const [menuOpen, setMenuOpen] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [agentsMdOpen, setAgentsMdOpen] = useState(false);
  const renameInputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (renaming) renameInputRef.current?.focus();
  }, [renaming]);

  const commitRename = async () => {
    // Inerting the retained sidebar blurs its input; suspension is not a save.
    if (!surfaceActiveRef.current) return;
    const trimmed = renameDraft.trim();
    if (!trimmed || trimmed === project.display_name) {
      setRenaming(false);
      setRenameDraft(project.display_name);
      return;
    }
    await onRename(trimmed);
    setRenaming(false);
  };

  return (
    <div className="flex flex-col gap-0.5">
      <div
        data-settings-interaction-owner="true"
        className="group flex items-center gap-1.5 rounded-md py-1.5 pl-1 pr-2 transition hover:bg-foreground/[0.04]"
        title={project.folder_path}
        onContextMenu={(e) => {
          // Right-click opens the same menu as the ⋯ button (anchored to it).
          if (renaming || !canManageProjects) return;
          e.preventDefault();
          setMenuOpen(true);
        }}
      >
        {renaming ? (
          <div className="flex flex-1 items-center gap-1.5">
            {expanded ? (
              <FolderOpen className="size-3.5 shrink-0 text-muted" />
            ) : (
              <Folder className="size-3.5 shrink-0 text-muted" />
            )}
            <Input
              ref={renameInputRef}
              value={renameDraft}
              onChange={(e) => setRenameDraft(e.target.value)}
              onBlur={commitRename}
              onKeyDown={(e) => {
                if (e.key === 'Enter') commitRename();
                if (e.key === 'Escape') {
                  setRenameDraft(project.display_name);
                  setRenaming(false);
                }
              }}
              placeholder={t('workbench.projectRenamePlaceholder')}
              className="h-7 flex-1 px-1.5 text-[12px] font-medium"
            />
          </div>
        ) : (
          <button
            {...dragHandle}
            type="button"
            onClick={onToggle}
            className="project-drag-header flex min-w-0 flex-1 items-center gap-1.5 text-left"
          >
            <Chevron className="project-drag-icon size-3 shrink-0 text-muted" />
            {expanded ? (
              <FolderOpen className="project-drag-icon size-3.5 shrink-0 text-muted" />
            ) : (
              <Folder className="project-drag-icon size-3.5 shrink-0 text-muted" />
            )}
            <span className="flex-1 truncate text-[12px] font-medium text-foreground">
              {project.display_name}
            </span>
          </button>
        )}
        {!renaming && (
          <>
            {canManageProjects && <Popover open={menuOpen} onOpenChange={setMenuOpen}>
              <PopoverTrigger asChild>
                <button
                  type="button"
                  data-settings-interaction-owner="true"
                  aria-label={t('workbench.projectActions')}
                  className={clsx(
                    'flex size-5 shrink-0 items-center justify-center rounded-md text-muted transition',
                    'opacity-0 group-hover:opacity-100 hover:text-foreground hover:bg-foreground/[0.06]',
                    menuOpen && 'opacity-100',
                  )}
                >
                  <Ellipsis className="size-3" />
                </button>
              </PopoverTrigger>
              <PopoverContent
                align="end"
                data-settings-interaction-owner="true"
                className="w-[160px] p-1"
              >
                <button
                  type="button"
                  onClick={() => {
                    setMenuOpen(false);
                    setRenaming(true);
                    setRenameDraft(project.display_name);
                  }}
                  className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
                >
                  <Pencil className="size-3 text-muted" />
                  {t('workbench.projectRename')}
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setMenuOpen(false);
                    setSettingsOpen(true);
                  }}
                  className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
                >
                  <Settings2 className="size-3 text-muted" />
                  {t('workbench.projectSettings')}
                </button>
                {project.folder_path && canEditAgentsMd && (
                  <button
                    type="button"
                    onClick={() => {
                      setMenuOpen(false);
                      setAgentsMdOpen(true);
                    }}
                    className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
                  >
                    <FileText className="size-3 text-muted" />
                    {t('workbench.projectEditAgents')}
                  </button>
                )}
                {project.folder_path && canOpenInEditor && (
                  <button
                    type="button"
                    onClick={() => {
                      setMenuOpen(false);
                      // Open the Editor rooted at the project folder, no file tab open (rootDir sets
                      // the explorer root only). Desktop-only surface, so the floating window is right.
                      wm.openApp('editor', { title: project.display_name, params: { rootDir: project.folder_path } });
                    }}
                    className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
                  >
                    <CodeXml className="size-3 text-muted" />
                    {t('workbench.projectOpenInEditor')}
                  </button>
                )}
                {canArchive && (
                  <button
                    type="button"
                    onClick={async () => {
                      setMenuOpen(false);
                      const ok = window.confirm(
                        t('workbench.projectArchiveConfirm', { name: project.display_name }),
                      );
                      if (ok) await onArchive();
                    }}
                    className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-pink-ink transition hover:bg-pink/[0.08]"
                  >
                    <Archive className="size-3" />
                    {t('workbench.projectArchive')}
                  </button>
                )}
              </PopoverContent>
            </Popover>}
            {canChat && <button
              type="button"
              data-settings-interaction-owner="true"
              aria-label={t('workbench.addSession')}
              onClick={onCreateSession}
              disabled={creatingSession}
              className={clsx(
                'flex size-5 shrink-0 items-center justify-center rounded-md text-muted transition',
                'opacity-0 group-hover:opacity-100 hover:text-foreground hover:bg-foreground/[0.06]',
                creatingSession && 'opacity-100',
              )}
            >
              {creatingSession ? <Loader2 className="size-3 animate-spin" /> : <Plus className="size-3" />}
            </button>}
          </>
        )}
      </div>

      {expanded && (
        <div className="flex flex-col gap-0.5 pb-0.5">
          {loading && sessions === null && (
            <div className="px-3 py-2 pl-[30px] text-[11px] italic text-muted">{t('workbench.sessionsLoading')}</div>
          )}
          {sessions !== null && sessions.length === 0 && !loading && (
            <div className="px-3 py-2 pl-[30px] text-[11px] italic text-muted">{t('workbench.sessionsEmpty')}</div>
          )}
          {sessions !== null &&
            sessions.map((session) => (
              <SessionRow
                key={session.id}
                projectId={project.id}
                session={session}
                unread={unreadBySession[session.id] || 0}
                canChat={canChat}
                canManageMetadata={canManageMetadata}
              />
            ))}
          {hasMore && (
            <button
              type="button"
              onClick={onLoadMore}
              disabled={loadingMore}
              className="flex items-center gap-1.5 rounded-md py-1.5 pl-[30px] pr-2.5 text-left text-[11px] font-medium text-muted transition hover:bg-foreground/[0.04] hover:text-foreground disabled:cursor-default disabled:opacity-60"
            >
              {loadingMore ? <Loader2 className="size-3 animate-spin" /> : <ChevronDown className="size-3" />}
              {t('workbench.sessionsLoadMore')}
            </button>
          )}
        </div>
      )}

      {canManageProjects && (
        <>
          <ProjectSettingsDialog
            project={project}
            open={settingsOpen}
            onClose={() => setSettingsOpen(false)}
          />
          <ProjectAgentsMdDialog
            project={project}
            open={agentsMdOpen}
            onClose={() => setAgentsMdOpen(false)}
          />
        </>
      )}
    </div>
  );
};

export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOpenSearch }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const surfaceActive = useRouteSurfaceActive();
  const authorizeRouteAction = useUnsavedChangesActionGuard();
  const {
    capabilities,
  } = useInstanceAuthorization();
  const canUseApps = capabilities.can_chat;
  const canManageProjects = capabilities.can_manage_projects;
  const canChat = capabilities.can_chat;
  const canCreateProject = canCreateLocalProject(capabilities);
  const capabilityNav = CAPABILITY_NAV.filter(({ to }) => {
    if (to === '/harness') return capabilities.can_chat;
    if (to === '/agents') return capabilities.can_use_agents;
    if (to === '/skills') return capabilities.can_use_skills;
    if (to === '/vaults') return capabilities.can_use_vault_secrets;
    return false;
  });
  const { totalUnread, badgeTotal, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox({
    feed: surfaceActive,
  });
  // Projects/sessions tree — shared with the mobile ProjectsPage via the provider
  // (one EventSource + one cache, not a per-component reimplementation). The
  // sidebar owns only its inbox popover + the New Project dialog trigger.
  const {
    projects,
    projectsError,
    sessionsOf,
    isExpanded,
    toggleExpanded,
    loadMore,
    creatingSession,
    createSessionForProject,
    renameProject,
    archiveProject,
    reorderProjects,
    isReorderingProjects,
  } = useWorkbenchProjectsTree({ active: surfaceActive });
  const [popoverOpen, setPopoverOpen] = useState(false);
  const closeTimer = useRef<number | null>(null);
  const [showNewProject, setShowNewProject] = useState(false);
  // Both groups remember, per browser, whether the user left them open.
  const [capabilitiesOpen, setCapabilitiesOpen] = useSidebarSectionOpen('capabilities');
  const [projectsOpen, setProjectsOpen] = useSidebarSectionOpen('projects');

  // Small open/close delays so the popover doesn't flicker as the cursor
  // brushes through the inbox row on its way somewhere else, and survives
  // the gap between the row and the popover body.
  const openPopover = () => {
    if (closeTimer.current !== null) {
      window.clearTimeout(closeTimer.current);
      closeTimer.current = null;
    }
    setPopoverOpen(true);
  };
  const queueClose = () => {
    if (closeTimer.current !== null) {
      window.clearTimeout(closeTimer.current);
    }
    closeTimer.current = window.setTimeout(() => {
      setPopoverOpen(false);
      closeTimer.current = null;
    }, 180);
  };
  useEffect(() => {
    return () => {
      if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
    };
  }, []);

  const onItemClick = (session: InboxSession) => {
    setPopoverOpen(false);
    navigate(`/chat/${encodeURIComponent(session.session_id)}`);
  };

  const onMarkAllRead = async () => {
    // Mark every session that still has unread agent replies. The unread map is
    // pagination-independent, so this clears sessions beyond the first page too.
    const ids = Object.entries(unreadBySession)
      .filter(([, n]) => (n || 0) > 0)
      .map(([id]) => id);
    await Promise.all(ids.map((id) => markRead(id)));
  };

  // The number counts only categories whose notifications are on; unread that
  // is all in muted categories shows as a grey dot instead, so it is there to
  // find but asks for nothing (docs/plans/workbench-refinements.md §1).
  const badge = useMemo(() => {
    if (badgeTotal <= 0) return null;
    return badgeTotal > 99 ? '99+' : String(badgeTotal);
  }, [badgeTotal]);
  const quietUnread = !badge && totalUnread > 0;

  // Fill the sidebar column and cap its height so the project list (and only the
  // project list) scrolls; the brand row, Inbox and Capabilities stay pinned. The
  // Inbox hover popover stays OUT of any overflow box below, so it is never clipped.
  return (
    <div className="flex min-h-0 flex-1 flex-col gap-2.5">
      {/* Brand row tLDP1 — the whole brand opens the new-conversation home. The
          mark keeps the approved chip treatment (32px, mint hairline over a
          mint well, resting glow that strengthens on hover) inside this
          sidebar's own padding, so the adjustable width still governs the
          column. The Inbox is the icon at the row's right end (docs/plans/bots.md
          D5): hover opens the same floating popover, a click the full Inbox. At
          zero unread there is no badge node at all and the icon stays
          uncoloured; both reads come from the same real counter. */}
      <div className="flex shrink-0 items-center gap-2 pb-3">
        <Link
          to="/"
          className="group flex min-w-0 items-center gap-2.5 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"
        >
          {/* Decorative: the link's accessible name is the localized brand text
              beside it, so naming the image too would read the destination twice. */}
          <img
            src={logoImg}
            alt=""
            aria-hidden="true"
            className="size-8 shrink-0 rounded-lg border border-mint/35 bg-mint/[0.08] object-cover shadow-glow-sm-mint transition-shadow group-hover:shadow-glow-md-mint"
          />
          <div className="min-w-0 leading-tight">
            <div className="truncate text-[13px] font-semibold text-foreground">{t('appShell.title')}</div>
            <div className="truncate text-[11px] text-muted">{t('appShell.subtitle')}</div>
          </div>
        </Link>
        <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>
          <PopoverAnchor asChild>
            <div className="ml-auto shrink-0" onMouseEnter={openPopover} onMouseLeave={queueClose}>
              <NavLink
                to="/inbox"
                aria-label={
                  badge
                    ? t('workbench.inbox.navUnread', { count: badgeTotal })
                    : quietUnread
                      ? t('workbench.inbox.navQuiet')
                      : t('workbench.nav.inbox')
                }
                title={t('workbench.nav.inbox')}
                className={({ isActive }) =>
                  clsx(
                    'relative grid size-8 place-items-center rounded-lg border transition-colors',
                    // Cyan active state per design.pen ze15A — mint is reserved
                    // for sessions / projects so the two reads stay distinct.
                    isActive
                      ? 'border-cyan/40 bg-cyan-soft shadow-glow-sm-cyan'
                      : 'border-transparent hover:bg-foreground/[0.04]',
                  )
                }
              >
                {({ isActive }) => (
                  <>
                    {/* Cyan is what unread means here, so the counter colours the
                        icon on any route — not only while Inbox is the open one. */}
                    <Inbox className={clsx('size-[18px]', badge || isActive ? 'text-cyan-ink' : 'text-foreground')} />
                    {badge ? (
                      <span className="absolute -right-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-cyan px-1 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">
                        {badge}
                      </span>
                    ) : quietUnread ? (
                      <span
                        aria-hidden="true"
                        className="absolute right-0.5 top-0.5 size-[7px] rounded-full bg-muted ring-2 ring-[var(--sidebar-background)]"
                      />
                    ) : null}
                  </>
                )}
              </NavLink>
            </div>
          </PopoverAnchor>
          <InboxHoverPopover
            sessions={inboxSessions}
            unreadBySession={unreadBySession}
            unreadSessions={unreadSessions}
            totalUnread={totalUnread}
            canMarkRead={canChat}
            onItemClick={onItemClick}
            onMarkAllRead={onMarkAllRead}
            onMouseEnter={openPopover}
            onMouseLeave={queueClose}
            onClose={() => setPopoverOpen(false)}
          />
        </Popover>
      </div>

      {/* Bots — the Owner's standing members take the Inbox row's old place
          (docs/plans/bots.md D5). Nobody else sees the strip. */}
      <BotStrip unreadBySession={unreadBySession} />

      {/* Capabilities m8K59 — a collapsible group, so a long project list can
          reclaim the rows. The label leads and the chevron closes the row on the
          right, matching the Projects header below. Only the destinations the
          current authorization admits are rendered, and the header disappears
          with them. */}
      {capabilityNav.length > 0 && (
        <div className="flex shrink-0 flex-col gap-1.5">
          <button
            type="button"
            className="group flex items-center gap-1 px-1 font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted transition-colors hover:text-foreground"
            aria-expanded={capabilitiesOpen}
            aria-controls="workbench-capability-nav"
            onClick={() => setCapabilitiesOpen(!capabilitiesOpen)}
          >
            <span className="flex-1 text-left">{t('nav.capabilities')}</span>
            <ChevronDown className={clsx('size-3.5 shrink-0 transition-transform', !capabilitiesOpen && '-rotate-90')} />
          </button>
          {capabilitiesOpen && (
            <nav id="workbench-capability-nav" className="flex flex-col gap-0.5">
              {capabilityNav.map(({ to, i18nKey, icon }) => (
                <SidebarNavRow key={to} to={to} icon={icon} label={t(i18nKey)} />
              ))}
            </nav>
          )}
        </div>
      )}

      {/* Projects section t7o96 — collapses like Capabilities: the label and the
          chevron closing the row both toggle it, and the chevron sits in the same
          right-edge column as the Capabilities one. The borderless search + add
          icons stay between them, so they remain reachable while the list is
          hidden. Search sits immediately before add and stays reachable for
          everyone who could reach it before, including the people this instance
          does not let create a project; ⌘K still opens the same palette from
          anywhere. */}
      <div className="flex min-h-0 flex-1 flex-col gap-1.5">
        <div className="flex items-center px-1">
          <button
            type="button"
            className="flex h-7 min-w-0 flex-1 items-center text-left font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted transition-colors hover:text-foreground"
            aria-expanded={projectsOpen}
            aria-controls="workbench-project-list"
            onClick={() => setProjectsOpen(!projectsOpen)}
          >
            <span className="truncate">{t('workbench.projectsLabel')}</span>
          </button>
          <div className="flex items-center gap-0.5">
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="size-7 shrink-0 text-muted hover:text-foreground"
              aria-label={t('workbench.search.entry')}
              onClick={onOpenSearch}
            >
              <Search className="size-4" />
            </Button>
            {canCreateProject && <Button
              type="button"
              variant="ghost"
              size="icon"
              className="size-7 shrink-0 text-muted hover:text-foreground"
              aria-label={t('workbench.addProject')}
              onClick={() => setShowNewProject(true)}
            >
              <FolderPlus className="size-4" />
            </Button>}
          </div>
          {/* A second pointer target for the label's toggle, so it is hidden from
              assistive tech and the tab order: the label button is the control. */}
          <button
            type="button"
            tabIndex={-1}
            aria-hidden="true"
            className="ml-0.5 flex h-7 w-3.5 shrink-0 items-center justify-center text-muted transition-colors hover:text-foreground"
            onClick={() => setProjectsOpen(!projectsOpen)}
          >
            <ChevronDown className={clsx('size-3.5 shrink-0 transition-transform', !projectsOpen && '-rotate-90')} />
          </button>
        </div>

        {projectsOpen && <div id="workbench-project-list" className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto pr-0.5">
          {projects === null && !projectsError && (
            <div className="flex items-center gap-2 rounded-md border border-dashed border-border px-3 py-3 text-[11px] text-muted">
              <Loader2 className="size-3 animate-spin" />
              {t('workbench.projectsLoading')}
            </div>
          )}
          {projectsError && (
            <div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[11px] text-destructive-ink">
              {t('workbench.projectsLoadError')}
            </div>
          )}
          {/* True empty state e5Kplg — a real row, not a centered illustration. */}
          {projects !== null && projects.length === 0 && (
            <div className="flex items-center gap-[7px] rounded-md px-1.5 py-[7px]">
              <FolderPlus className="size-[14px] shrink-0 text-muted" />
              <span className="min-w-0 truncate text-[11px] text-muted">{t('workbench.projectsEmpty')}</span>
            </div>
          )}
          {projects !== null && <SortableProjectList
            projects={projects}
            disabled={!canManageProjects || isReorderingProjects}
            onReorder={reorderProjects}
          >
            {(project, dragHandle) => {
              const state = sessionsOf(project.id);
              return (
                <ProjectRow
                  key={project.id}
                  dragHandle={dragHandle}
                  project={project}
                  expanded={isExpanded(project.id)}
                  sessions={state.sessions}
                  loading={state.loading}
                  loadingMore={state.loadingMore}
                  hasMore={!!state.cursor}
                  onLoadMore={() => loadMore(project.id)}
                  onToggle={() => toggleExpanded(project.id)}
                  onCreateSession={async () => {
                    const authorization = authorizeRouteAction();
                    if (!authorization) return;
                    // The provider creates + caches; navigation stays here since
                    // it's mounted above the router.
                    const session = await createSessionForProject(project.id);
                    if (session) {
                      authorization.runNavigation(() => navigate(`/chat/${encodeURIComponent(session.id)}`));
                    }
                  }}
                  creatingSession={creatingSession(project.id)}
                  canChat={canChat && project.capabilities.can_chat}
                  canManageMetadata={canManageProjects || project.capabilities.can_chat}
                  canManageProjects={canManageProjects}
                  canArchive={canManageProjects}
                  canOpenInEditor={canUseApps}
                  canEditAgentsMd={canManageProjects}
                  unreadBySession={unreadBySession}
                  onRename={(next) => renameProject(project.id, next)}
                  onArchive={() => archiveProject(project.id)}
                />
              );
            }}
          </SortableProjectList>}
        </div>}
      </div>

      {showNewProject && canCreateProject && (
        <NewProjectDialog
          onClose={() => setShowNewProject(false)}
          onCreated={() => {
            setShowNewProject(false);
            // A project just created must be visible, even if the list was collapsed.
            setProjectsOpen(true);
          }}
        />
      )}
    </div>
  );
};

// Re-export for tests / future inbox-specific UIs.
export { InboxHoverPopover };