Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

62.9 KB
Raw Blame
import { SessionTaskMenu } from './SessionTaskMenu';
import { getSessionListActivityAt } from '@cindy/maker-shared/session-activity';
import { TaskTagMenuSection, TaskTagEditor, TaskTagDots } from '@/features/task-tags/TaskTags';
import { Button } from '@/components/ui/button';
/**
 * SessionItem — 单条 CCS 会话行
 * ---------------------------------------------------------------------------
 * 从 CCAgentSidebarUpper 抽出,行为 100% 复用:
 *   - 200ms 防抖区分单击导航 / 双击重命名
 *   - 双击或 Pencil 图标进入重命名;Enter 提交、Escape 取消、Blur 提交
 *   - 左侧 status zone 直接渲染 vendor mark(Claude=AA / Codex=六瓣)—— 同一 icon
 *     承担 vendor 标识 + 运行状态:idle 灰、running 切 Thinking Orange + 呼吸、
 *     需关注时叠右上红点、archived 改 Archive icon。**Pin 入口走右键菜单**
 *     (避免与会话菜单内 Pin/Unpin 重复)
 *   - 右键(contextmenu) 弹出 DropdownMenu —— 与 ProjectNode 同款 coordinate-anchored
 *     pattern(fixed-position 隐形 trigger 锚定到鼠标坐标)。
 *     菜单内容按状态分支(F-PJ-9:标准 Pin/Rename/Archived;Pinned Unpin/Rename/Archived;
 *     Draft Rename/Delete;Archived Rename/Unarchive/Delete)
 *   - hover 时右侧显示 Archive 图标按钮(archive 快捷入口),采用 Codex 风的"行内两步
 *     确认"模式:第一次点击 → 按钮就地变成红色 Confirm 胶囊(pending 态,无弹窗);
 *     第二次点击 → 通过 onAction(id, 'archive-now') 走父层的"跳过 ConfirmDialog 直接执行"
 *     分支;4 秒不操作 / 在 pending 期间点击别处任意位置 → 自动撤回到 Archive 图标。
 *     仅对"可归档"的 session 显示(非 archived、非空 draft);其它两种状态隐藏按钮,
 *     用户走右键菜单(Unarchive / Delete,仍保留原 ConfirmDialog 弹窗)。
 *   - 选中态 bg-sidebar-item-active + font-semibold
 *
 * 关于 indented prop(缩进控制):
 *   - indented=true(分组内子 session):`pl-5`,在普通行 12px 内边距上增加 8px 层级缩进。
 *   - indented=false(Pinned / Unclassified / Dialogue 顶层 session):`pl-3`。
 *   2026-07 用户定稿的文字列对齐:状态图标包在 15px 定宽槽内;普通会话行使用
 *   gap-2.5(10px),与顶部导航行 / 项目行同构。自动任务行因中间还有 Timer,
 *   Agent → Timer 沿用原 Clock 的 gap-1.5(6px),Timer → 标题同为 6px。
 */

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
import { Archive, ChevronRight, Crown, EllipsisVertical, Play, Undo } from 'lucide-react';
import { withSidebarNavigation, type SidebarNavigationProps } from './sidebarNavigation';
import { useStableTranslation as useTranslation } from '@/hooks/useStableTranslation';

import { cn } from '@/lib/utils';
import type { Session } from '@/lib/ccAgent.types';
import { makerChatStore } from '@/lib/makerChatStore';
import { SessionStatusIcon } from './SessionStatusIcon';
import { SessionRenameInput } from '../SessionRenameInput';
import { usePrActions, usePrRefsForSession } from '@/contexts/PrRefsContext';
import { SessionTooltip } from './SessionTooltip';
import {
  DropdownMenu,
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { MENU_ITEM_CLASS, MENU_ROW_CLASS } from './menuStyles';
import { toast } from '@/lib/toast';
import { buildSessionDeepLink } from '@/lib/deepLink';
import { createLogger } from '@/lib/logger';
import { buildSessionInfoPieces, SessionInfoMeta } from './SessionInfoMeta';
import { useTaskInfoWorktree } from './sessionWorktreeInfo';
import { useTaskInfoFields } from '../hooks/useTaskInfoFields';
import { highlightSegments } from '../lib/highlightSegments';
import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';
import { isAutomationGeneratedSession } from '../lib/scheduledSessionGrouping';
import {
  canHighlightSessionDisplayTitle,
  getSessionDisplayTitle,
  isEmptyDraftSession,
} from '../lib/sessionDisplayTitle';
import { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';
import {
  findLatestSidebarIndexRunForSession,
  loadScheduleSidebarIndexRuns,
  type ScheduleSidebarIndexRun,
} from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
import { useSchedulesSnapshot } from '@/features/scheduler/lib/schedulesStore';
import { ScheduleBindingBadge } from './ScheduleBindingBadge';
import { SessionOrdinalBadgeKbd, useSessionOrdinalBadge } from './sessionOrdinalBadges';
import { SessionProjectMoveSubmenu } from './SessionProjectMoveSubmenu';
import type { SessionMoveTarget } from './sessionMoveTarget';
import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
import { RemoteProjectIcon } from './RemoteProjectIcon';
import { BotFollowMark, useSessionFollowers } from '@/features/bots/BotFollowMark';
import { SessionShareExportDialog } from './SessionShareExportDialog';
import { isRemoteSessionWriteBlocked } from '../lib/remoteSessionWriteGuard';
import { Tip } from '@/components/ui/tooltip';
import { prefetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import {
  mergeOrcaLeadAttentionKind,
  useOrcaLeadWorkerAttentionKind,
} from '../lib/orcaLeadWorkerAttention';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
import { useRemoteSessionScheduleInfo } from '@/features/device-link/remoteProjectsStore';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
import { useAgentIslandActivity } from '@/state/agentIslandActivity';
import { projectSidebarSessionActivity, resolveSidebarRightStatus } from './sidebarRightStatus';
import { AutomationSessionButton } from './AutomationSessionButton';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
import {
  finishSessionDrag,
  isSplitGroupDragSource,
  needsDedicatedSplitGroupDragHandle,
  startSessionDrag,
} from '../splitGroupDnd';
import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';
import { useCindyMakeActivity } from './useCindyMakeActivity';
import { CINDY_MAKE_SESSION_SOURCE } from '../../../../shared/cindyMakeSession';

// Module-level dedup cache for loadScheduleSidebarIndexRuns.
// When many ungrouped automation rows mount simultaneously they all need the
// same IPC+DB query. Share the in-flight Promise so N mounts → 1 query;
// the cache is cleared after 1 second so a subsequent sidebar change (new
// run recorded, schedule deleted, …) gets fresh data on the next effect run.
let _scheduleIndexPromise: Promise<ScheduleSidebarIndexRun[]> | null = null;
function loadScheduleSidebarIndexRunsCached(): Promise<ScheduleSidebarIndexRun[]> {
  if (!_scheduleIndexPromise) {
    _scheduleIndexPromise = loadScheduleSidebarIndexRuns().finally(() => {
      setTimeout(() => {
        _scheduleIndexPromise = null;
      }, 1000);
    });
  }
  return _scheduleIndexPromise;
}

const SESSION_ROW_INTERACTIVE_SELECTOR = 'button, a, input, select, textarea, [role="button"]';

function isNestedSessionRowAction(target: EventTarget | null, row: Element): boolean {
  if (!(target instanceof Element)) return false;
  const interactive = target.closest(SESSION_ROW_INTERACTIVE_SELECTOR);
  return interactive !== null && interactive !== row;
}

const log = createLogger('SessionItem');

interface SidebarTitleMarqueeProps {
  children: ReactNode;
  className?: string;
  title: string;
}

/**
 * 标题保持原生省略号,只有实际溢出且任务行处于悬浮态时才播放一次横向滚动。
 * 绑在行上而不是标题上:指针移到更多/归档时跑马灯不能停。
 * 通过 DOM 属性和 CSS 变量驱动,避免给高密度侧栏行增加 React 状态订阅。
 */
export function SidebarTitleMarquee({ children, className, title }: SidebarTitleMarqueeProps) {
  const containerRef = useRef<HTMLSpanElement>(null);
  const trackRef = useRef<HTMLSpanElement>(null);
  const isHoveredRef = useRef(false);
  const resizeObserverRef = useRef<ResizeObserver | null>(null);

  const stopMarquee = useCallback(() => {
    const container = containerRef.current;
    if (!container) return;
    delete container.dataset.titleOverflowing;
    container.style.removeProperty('--sidebar-title-marquee-shift');
    container.style.removeProperty('--sidebar-title-marquee-duration');
  }, []);

  const startMarquee = useCallback(() => {
    const container = containerRef.current;
    const track = trackRef.current;
    if (!container || !track) return;

    delete container.dataset.titleOverflowing;
    container.style.removeProperty('--sidebar-title-marquee-shift');
    container.style.removeProperty('--sidebar-title-marquee-duration');
    if (track.scrollWidth <= container.clientWidth + 1) return;

    const viewportCount = Math.max(
      1,
      Math.ceil(track.scrollWidth / Math.max(container.clientWidth, 1)),
    );
    container.style.setProperty(
      '--sidebar-title-marquee-shift',
      `${container.clientWidth - track.scrollWidth}px`,
    );
    container.style.setProperty(
      '--sidebar-title-marquee-duration',
      `calc(var(--motion-sidebar-title-marquee-per-viewport) * ${viewportCount})`,
    );
    container.dataset.titleOverflowing = 'true';
  }, []);

  const stopObserving = useCallback(() => {
    resizeObserverRef.current?.disconnect();
    resizeObserverRef.current = null;
  }, []);

  const startObserving = useCallback(() => {
    stopObserving();
    const container = containerRef.current;
    const track = trackRef.current;
    if (!container || typeof ResizeObserver === 'undefined') return;

    const observer = new ResizeObserver(() => {
      if (isHoveredRef.current) startMarquee();
    });
    observer.observe(container);
    if (track) observer.observe(track);
    resizeObserverRef.current = observer;
  }, [startMarquee, stopObserving]);

  useLayoutEffect(() => {
    if (isHoveredRef.current) startMarquee();
  }, [startMarquee, title]);

  useEffect(() => {
    const row = containerRef.current?.closest('[data-sidebar-session-row="true"], [data-sidebar-navigation-row="true"]');
    if (!(row instanceof HTMLElement)) return undefined;

    const onEnter = () => {
      isHoveredRef.current = true;
      startMarquee();
      startObserving();
    };
    const onLeave = () => {
      isHoveredRef.current = false;
      stopObserving();
      stopMarquee();
    };

    row.addEventListener('mouseenter', onEnter);
    row.addEventListener('mouseleave', onLeave);
    if (row.matches(':hover')) onEnter();
    return () => {
      row.removeEventListener('mouseenter', onEnter);
      row.removeEventListener('mouseleave', onLeave);
      onLeave();
    };
  }, [startMarquee, startObserving, stopMarquee, stopObserving]);

  useEffect(() => () => stopObserving(), [stopObserving]);

  return (
    <span
      ref={containerRef}
      className="sidebar-title-marquee min-w-0 max-w-full shrink overflow-hidden"
      title={title}
    >
      <span className={cn('sidebar-title-marquee__ellipsis', className)}>{children}</span>
      <span
        ref={trackRef}
        aria-hidden="true"
        className={cn('sidebar-title-marquee__track', className)}
      >
        {children}
      </span>
    </span>
  );
}

export interface SessionItemProps {
  /** Shared guests retain navigation and the leave-sharing menu, without owner actions or selection. */
  navigationOnly?: boolean;
  /** Shared-group identity mark. Only owners show a crown; joined tasks match ordinary rows. */
  sharedTaskRole?: 'owned' | 'joined';
  session: Session;
  isActive: boolean;
  /** F-SB-7: Whether this session's agent is currently running. */
  isRunning: boolean;
  /** /ctr 接管中: 左侧 vendor icon 切换为 RadioTower 表"被远程接管"。 */
  isAttached?: boolean;
  /** F-SB-7: Whether this session has an attention notification badge. */
  hasAttentionNotification: boolean;
  /** Multi-select visual state in the sidebar. */
  isSelected?: boolean;
  onClick: SessionClickHandler;
  onAction: (
    sessionId: string,
    action: 'delete' | 'archive' | 'archive-now' | 'unarchive',
    sharedTaskId?: string,
  ) => void;
  onRename: (sessionId: string, newTitle: string) => void;
  onTogglePin: (sessionId: string, currentlyPinned: boolean) => void;
  onMoveSession?: (sessionId: string, target: SessionMoveTarget) => void;
  projectOptions?: readonly FolderPickerOption[];
  /** 在 ProjectNode 内部渲染时为 true,行不再额外缩进(缩进由父容器 padding 承担)。 */
  indented?: boolean;
  /**
   * 模糊搜索命中字符在 title 中的下标数组(严格升序)。
   * 来自 useSessionSearch.matchMap;不传 / undefined → 走原 `<span>` 渲染路径,零成本。
   * 传空数组 [] → 同 undefined(没有命中字符,无需高亮)。
   */
  matchIndices?: readonly number[];
  /**
   * 标题旁的"项目来源"标签(项目 displayName 或"对话")。
   * 仅在平铺视图下由父层注入 —— 项目分组视图里项目名已由 ProjectNode 表头承载,
   * 无需再在会话行重复显示,因此不传。
   */
  sourceLabel?: string;
  /**
   * 是否渲染在 AutomationSessionGroupItem 分组内。true 时不再在行级 hover slot
   * 挂 [Run] 自动化按钮 —— 组头已经承载了同链路的操作,子行再重复一份
   * 属于视觉噪音;仅顶层散落的 automation-generated 会话(未被 group 吸走的)才在
   * 自己行上展示立即运行入口。
   */
  insideAutomationGroup?: boolean;
}

export interface SessionClickModifiers {
  shiftKey: boolean;
  metaKey: boolean;
  ctrlKey: boolean;
}

export type SessionClickHandler = (id: string, modifiers?: SessionClickModifiers) => void;

export function hasSessionSelectionModifier(modifiers?: SessionClickModifiers): boolean {
  return modifiers?.shiftKey === true || modifiers?.metaKey === true || modifiers?.ctrlKey === true;
}

/**
 * ⚠️ 性能不变量(sessionRowRenderIsolation.test 钉住,改动前先读):
 * 侧边栏可能渲染几百个 SessionItem,父层(CCAgentSidebarUpper)一有状态变化就整树
 * 重渲染,本组件靠 memo 兜底 —— 只有自己 props 变的行才真正重画。要维持这个保证:
 *   1. 本组件必须保持 memo 包裹,不要拆掉;
 *   2. 行内新增数据订阅时,禁止订阅"整张表"快照(useSessionAttentionKinds /
 *      useSessionAttentionSnapshot / 整个 Set 的 context 等每次广播都换引用,会让
 *      所有行一起醒)。必须用按 sessionId 取 primitive/稳定引用的精准订阅,
 *      参考 useSessionAttentionKind / useSessionAttentionUrgency 的写法;
 *   3. 上游给本组件传新 props 时保持引用稳定(handler 用 useCallback,集合查询
 *      在父层降成 boolean 再传),否则 memo 直接失效。
 * 背景:2026-07 切换会话卡顿,实测整栏重画单次 80-96ms、每次切换连跑 3 遍,
 * 根源就是行内全表订阅 + 无 memo。
 */
export const SessionItem = withSidebarNavigation<SessionItemProps>(function SessionItem({
  navigate,
  session,
  isActive,
  isRunning,
  isAttached = false,
  hasAttentionNotification,
  isSelected = false,
  onClick,
  onAction,
  onRename,
  onTogglePin,
  onMoveSession,
  projectOptions = [],
  indented = false,
  matchIndices,
  sourceLabel,
  insideAutomationGroup = false,
  navigationOnly = false,
  sharedTaskRole,
}: SessionItemProps & SidebarNavigationProps) {
  const { t } = useTranslation();
  const followers = useSessionFollowers(session);
  const cindyMakeActivity = useCindyMakeActivity(session);
  const cindyMakePreparing = cindyMakeActivity === 'building' ? undefined : cindyMakeActivity;
  const prRefs = usePrRefsForSession(session.id);
  // 任务信息复选(C 期):行右侧信息槽内容,与整理菜单同源共享状态。
  const { fields: taskInfoFields } = useTaskInfoFields();
  // 勾选 pr 且行渲染时注册为 PR 消费者:注册即拉取(远程会话含引用补拉),
  // 此后 Provider 周期/聚焦统一刷新,失败自愈(usePrActions 的 value 恒定)。
  const { registerPrConsumer } = usePrActions();
  const wantsPrInfo = taskInfoFields.includes('pr');
  const remoteDeviceId = session.deviceLinkDeviceId;
  useEffect(() => {
    if (!wantsPrInfo) return undefined;
    return registerPrConsumer(session.id, remoteDeviceId);
  }, [wantsPrInfo, remoteDeviceId, session.id, registerPrConsumer]);
  // mod+1..9 序号徽标:模块 store 按 sessionId 精准订阅(性能不变量第 2 条),
  // 非按住态恒为 null,不惊动 memo。
  const ordinalBadge = useSessionOrdinalBadge(session.id);
  const ordinalBadgeLabel = navigationOnly ? null : ordinalBadge;
  const canOpenTaskMenu = !navigationOnly || isSharedTaskPeer(session.deviceLinkDeviceId ?? '');
  const isPinned = session.pinnedAt != null;
  const isEmpty = isEmptyDraftSession(session);
  // 显示时间与列表排序共用换手时钟,旧端与存量数据沿用回退。
  const activityIso = getSessionListActivityAt(session);
  // PR 信息(C' 期):勾选且有引用时取最新一条(prRefs 已按 lastSeenAt 降序)。
  const infoPrRef = taskInfoFields.includes('pr') ? prRefs[0] : undefined;
  const infoWorktree = useTaskInfoWorktree(session, taskInfoFields.includes('worktree'));
  // 传 hasPrRef / hasWorktree 让它们参与「按勾选顺序」排列。
  const infoPieces = buildSessionInfoPieces(
    session,
    taskInfoFields,
    activityIso,
    t,
    infoPrRef != null,
    infoWorktree != null,
  );
  // 右侧状态指示器五档优先级(高→低),色表全端统一(侧栏 / 卡片 / 灵动岛同一张表):
  //   1. error(出错终止 / 定时任务失败未读)→ 红点   —— 红专职表示"坏了"
  //   2. awaiting(等待回复/权限/计划审阅)→ TapTap 蓝点 —— "在等你",邀请而非告警
  //   3. isRunning → spinner(中性灰,running 的橙色语义由左侧 vendor mark 呼吸表达,
  //      右槽 spinner 保持低调不抢色 —— 2026-07 产品决策不染橙)
  //   4. attention 完成未读(done / 未读定时任务)→ 绿点
  //   5. else → 时间文字
  //
  // 为什么 error / awaiting 最高:用户要一眼看到"哪些会话在等我处理"。running + awaiting
  // 共存(agent 跑到一半弹 ask-user)时,蓝点比 spinner 更重要 —— 用户看到 spinner 只以为
  // "还在跑,不管它",但实际它已停在 ask-user 处等待。
  //
  // 为什么 running 高于完成未读:agent 还在跑就一定要显 spinner,不能被
  // "查看后 attention 清零"落到 time 分支 —— 否则会出现"仍然在跑但看起来已完成"的错觉。
  // error / awaiting 被查看清零后,自然让位给 spinner(而不是 time),流程一致。
  //
  // hasAttentionNotification 有两个来源:
  //   1. useSessionRunningStatus.notifications(有 attentionKind:'done'/'awaiting'/'error')
  //   2. unreadScheduleSessionIds(定时任务未读完成,attentionKind 缺失 —— 语义等同 'done')
  // 因此 attentionKind 缺失时按"完成"处理走绿点,不当作错误。
  //
  // 额外 error 来源:定时任务未读且非成功(failed / aborted / interrupted)结局的 session ——
  // 通过 SessionAttentionUrgencyContext 由上游注入,避免误把失败的 automation 涂成 Completed。
  //
  // Orca Lead 行另并入其 Worker 的出错 / 等待确认(出错 > 等待确认 > Lead 自身),
  // 见 lib/orcaLeadWorkerAttention.ts。
  const ownAttentionKind = useSessionAttentionKind(session.id);
  const orcaWorkerAttentionKind = useOrcaLeadWorkerAttentionKind(session.id);
  const attentionKind = mergeOrcaLeadAttentionKind(ownAttentionKind, orcaWorkerAttentionKind);
  const isUrgentFromContext = useSessionAttentionUrgency(session.id);
  const islandActivity = useAgentIslandActivity(session.id);
  // device-link 远程会话行:本地 attention/running 链路对被控端后台会话是盲区,状态改由
  // 被控端灵动岛 relay 的活动镜像驱动(remoteSessionActivityStore,按行精准订阅;本地
  // 会话恒 undefined 零开销)。镜像只保留活跃态与未读终态,映射与本地五档同一张色表。
  const remoteActivity = useRemoteSessionActivity(session.id, session.deviceLinkDeviceId);
  const remoteSchedule = useRemoteSessionScheduleInfo(session.id);
  const sessionActivity = projectSidebarSessionActivity({
    interruption: session,
    sessionId: session.id,
    title: session.title,
    recordStatus: session.status,
    liveActivity: session.deviceLinkDeviceId ? remoteActivity : islandActivity,
    attentionKind,
    isUrgentFromContext: isUrgentFromContext || remoteSchedule?.hasUnreadFailedRun === true,
    isRunning: session.deviceLinkDeviceId
      ? remoteActivity?.phase === 'running'
      : isRunning || cindyMakeActivity != null,
    hasAttentionNotification:
      hasAttentionNotification ||
      orcaWorkerAttentionKind !== undefined ||
      remoteSchedule?.hasUnreadRun === true,
  });
  const leftIconRunning = sessionActivity.currentTurnActive === true;
  const rightStatusKind = resolveSidebarRightStatus(sessionActivity);
  const showRightStatus = rightStatusKind !== 'time';
  const remoteIconKind = session.deviceLinkDeviceId
    ? 'device-link'
    : session.remoteHostId
      ? 'ssh'
      : null;
  const remoteIconConnectionStatus = session.deviceLinkDeviceId
    ? (session.deviceLinkConnectionStatus ?? 'connected')
    : null;
  const [tagEditorOpen, setTagEditorOpen] = useState(false);
  const tagMenu = (
    <TaskTagMenuSection
      session={session}
      onMore={() => {
        setTagEditorOpen(true);
        setMenuPos(null);
      }}
    />
  );
  const remoteWritesBlocked = isSharedTaskPeer(session.deviceLinkDeviceId ?? '') || isRemoteSessionWriteBlocked(session);
  const isAutomationGenerated = isAutomationGeneratedSession(session);
  // heartbeat schedule 绑定标识(targetSessionId 指向本会话);schedule 删除/过期后
  // schedulesStore 'changed' 刷新 → 列表为空 → 徽章消失。
  const boundSchedules = useSessionBoundSchedules(session.id, session.deviceLinkDeviceId);
  const hasAutomationMeta = boundSchedules.length > 0 || isAutomationGenerated;
  // 单个 automation-generated 会话行的「schedule 反查」:sessionId → scheduleId 走
  // sidebar-index-runs(Session 上没有 scheduleId 字段)。用于两处:
  //   1. 门控 Run 按钮的可见性 —— schedule 已被删除但会话保留(disposition
  //      keep-sessions)的孤儿 run 上,`isAutomationGenerated` 仍为 true,但 Run 会
  //      直接 toast「not found」,索性别显示。
  //   2. Run 按钮点击时直接用 state 里的 scheduleId,免得再查一遍。
  // mount-once + isAutomationGenerated 才启用,普通会话零开销。cancelled guard 防止
  // 组件卸载后 setState。null 明确表示「查过但没映射」,undefined 表示「还没查」——
  // 两者都不显示按钮,避免闪现。
  const shouldResolveSchedule = isAutomationGenerated && !insideAutomationGroup;
  const [resolvedScheduleId, setResolvedScheduleId] = useState<string | null | undefined>(
    undefined,
  );
  useEffect(() => {
    if (!shouldResolveSchedule) return;
    let cancelled = false;
    loadScheduleSidebarIndexRunsCached()
      .then((runs) => {
        if (cancelled) return;
        const hit = findLatestSidebarIndexRunForSession(runs, session.id);
        setResolvedScheduleId(hit?.scheduleId ?? null);
      })
      .catch(() => {
        if (!cancelled) setResolvedScheduleId(null);
      });
    return () => {
      cancelled = true;
    };
  }, [session.id, shouldResolveSchedule]);
  // 实时校验:resolvedScheduleId 是 mount 时的一次性反查,如果之后 schedule 被删除
  // (keep-sessions disposition),这里静默失效。schedulesStore 是 authoritative 列表,
  // 拿它的 live snapshot 校验一遍 —— snapshot 未 load(null)时假设仍存在,一旦 load
  // 完发现 resolvedScheduleId 不在列表里,effectiveScheduleId 归 null,按钮门控立即
  // 收回。SessionItem 已通过 useSessionBoundSchedules 订阅 schedulesStore 快照,新增
  // 这次订阅零边际成本(同一 hook 的多次调用会合并到一次 useSyncExternalStore)。
  const schedulesSnapshot = useSchedulesSnapshot();
  const scheduleStillExists =
    resolvedScheduleId != null &&
    (schedulesSnapshot == null || schedulesSnapshot.some((s) => s.id === resolvedScheduleId));
  const effectiveScheduleId = scheduleStillExists ? resolvedScheduleId : null;
  const handleAutomationRunClick = useCallback(async () => {
    if (!effectiveScheduleId) {
      toast.warning(t('scheduler.toast.runFailed', { error: 'schedule not found' }));
      return;
    }
    try {
      await window.electronAPI.maker.schedule.runNow(effectiveScheduleId);
    } catch (e) {
      toast.error(
        t('scheduler.toast.runFailed', {
          error: e instanceof Error ? e.message : String(e),
        }),
      );
    }
  }, [effectiveScheduleId, t]);
  const displayTitle = getSessionDisplayTitle(
    session,
    t(
      session.source === CINDY_MAKE_SESSION_SOURCE
        ? 'cindyMake.code.taskName'
        : 'ccAgent.common.unnamedSession',
    ),
    t,
  );
  const canHighlightDisplayTitle = canHighlightSessionDisplayTitle(session, t);
  const titleContent =
    matchIndices && matchIndices.length > 0 && canHighlightDisplayTitle
      ? highlightSegments(session.title, matchIndices, {
          highlightClassName: cn(
            'bg-transparent font-semibold',
            isActive
              ? 'text-[var(--sidebar-item-active-foreground)]'
              : 'text-[var(--msg-assistant-text)]',
          ),
        })
      : displayTitle;
  // F-PJ-10:archived 视图下的 session 走特殊视觉/菜单分支
  //   - 左侧 status icon 由 CircleDashed 换成 Archive
  //   - 右侧 ⋮ 菜单只显示 Rename + Unarchive(屏蔽 Pin/Delete/Archive 等无意义项)
  const isArchived = session.status === 'archived';
  const canQuickArchive = !navigationOnly && !isArchived && !isEmpty && !remoteWritesBlocked;

  // 右键菜单弹出位置:null = 关闭;{x,y} = 在该屏幕坐标处弹出(fixed 定位的
  // 隐形 trigger 锚定到这里)。与 ProjectNode 同款 coordinate-anchored 模式。
  const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);
  const [rowTooltipOpen, setRowTooltipOpen] = useState(false);

  // Codex 风行内 archive 确认:archivePending=true 时右侧图标按钮被一个红色
  // "Confirm" 胶囊替换;4s 不动 or 点别处 → 自动撤回。第二次点击 Confirm 才真正
  // 触发 onAction(id, 'archive-now') 跳过 ConfirmDialog 直接归档。
  const [archivePending, setArchivePending] = useState(false);
  // confirm 胶囊 DOM 引用——outside-mousedown 用它判断点击是否落在自己身上。
  const confirmPillRef = useRef<HTMLButtonElement>(null);

  // 归档/删除前那次 dirty-worktree 预检要在 main 侧跑 git status,是"点了归档、
  // 行还没消失"里剩下的最大一块等待。每个入口真正执行前都隔着一次人类操作
  // (亮出 Confirm 胶囊后再点一下 / 打开菜单后再点条目),在那一刻先发出去,
  // 执行时命中缓存即可。TTL 与去重都在 worktreeRemovalWarning 里。
  const prefetchRemovalPreflight = useCallback(() => {
    prefetchDirtyWorktreeForRemoval(session.id, session.deviceLinkDeviceId);
  }, [session.id, session.deviceLinkDeviceId]);

  // 行容器 ref:在 isActive 切到 true 时把当前行滚进 viewport。
  //
  // 覆盖范围:SessionItem 已挂载在 DOM 中、但当前 viewport 外的场景
  // (项目内 sessions 数量超过可视区域,active session 不在视野内)。
  //
  // 不覆盖范围:
  //   1. project 处于 collapsed 态 —— SessionItem 由条件渲染整段移出 DOM,
  //      根本不 mount,本 useEffect 也不会触发。需要调用方先 ensure 展开
  //      (如 ProjectNode 的搜索点击 handler 在 close 前会调 onToggle)
  //   2. 用户重复点击已 active 的 session —— isActive 不变,本 useEffect
  //      也不会触发。这种"用户明确想再看一眼"的语义由调用方通过
  //      imperative 路径(querySelector + scrollIntoNearestView)补一刀
  const rowRef = useRef<HTMLDivElement>(null);
  const dragStartTargetRef = useRef<Element | null>(null);

  // ── Double-click rename ──
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState(displayTitle);
  // Guard: Enter fires commitTitle, then input unmounts → onBlur fires it
  // again. The ref prevents the second call from re-sending the API request.
  const committedRef = useRef(false);

  // raw 由 SessionRenameInput 传入:输入框当前文本(Magic 生成的标题也先填入输入框,用户 Enter 确认后才走到这里)。
  const commitTitle = useCallback(
    (raw: string) => {
      if (committedRef.current) return;
      committedRef.current = true;
      const trimmed = raw.trim();
      setIsEditing(false);
      if (trimmed && trimmed !== displayTitle) {
        onRename(session.id, trimmed);
      }
    },
    [displayTitle, session.id, onRename],
  );

  // 单击 → 立即导航,无延迟。双击 → 浏览器在两次 click 之后再发 dblclick,
  // 进入重命名;首击 navigate 到本 session,第二击因 id===activeSessionId 在
  // handleSessionClick 早 return(参见 CCAgentSidebarUpper handleSessionClick),
  // 不会重复导航。两路并存,无需 200ms 防抖。
  const handleClick = useCallback(
    (e: ReactMouseEvent<HTMLDivElement>) => {
      if (isEditing) return;
      onClick(session.id, {
        shiftKey: e.shiftKey,
        metaKey: e.metaKey,
        ctrlKey: e.ctrlKey,
      });
    },
    [isEditing, onClick, session.id],
  );

  const handleDoubleClick = useCallback(
    (e: React.MouseEvent) => {
      // 已在编辑态时不重复进入:编辑器内部元素漏拦的 dblclick 冒泡到这里会
      // setEditValue 重置草稿(与 handleClick 的 isEditing 守卫对称)。
      if (isEditing || navigationOnly) return;
      e.stopPropagation();
      e.preventDefault();
      if (remoteWritesBlocked) {
        toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
        return;
      }
      setEditValue(displayTitle);
      committedRef.current = false;
      setIsEditing(true);
    },
    [displayTitle, isEditing, navigationOnly, remoteWritesBlocked, t],
  );

  // 置顶段使用原生 Sortable DnD:Sortable 负责侧栏内排序,原生 dragstart 同时写入
  // 分屏 MIME,因此同一整行可以根据落点完成排序或拖入右侧。普通 forceFallback
  // 列表仍保留原来的专用标题起手区,项目子任务则继续由 data-no-drag 隔离。
  // 首帧先按 Sortable 容器处理,避免 ref effect 运行前短暂开启原生拖拽。
  const [dragContainerState, setDragContainerState] = useState({
    inSortableContainer: true,
    sortableDragBlocked: false,
    nativeSortable: false,
  });
  useEffect(() => {
    const row = rowRef.current;
    setDragContainerState({
      inSortableContainer: Boolean(row?.closest('[data-sortable-id]')),
      sortableDragBlocked: Boolean(row?.closest('[data-no-drag]')),
      nativeSortable: Boolean(row?.closest('[data-sortable-native-dnd]')),
    });
  }, []);
  const needsSplitDragHandle = needsDedicatedSplitGroupDragHandle(dragContainerState);
  const splitDragEnabled = !navigationOnly && isSplitGroupDragSource({
    editing: isEditing,
    orcaRole: session.orcaRole,
    ...dragContainerState,
    hasDedicatedHandle: true,
  });
  const splitDragHandleActive = splitDragEnabled && needsSplitDragHandle;

  const handleDragStart = useCallback(
    (event: ReactDragEvent<HTMLDivElement>) => {
      startSessionDrag(event, {
        sessionId: session.id,
        deviceId: session.deviceLinkDeviceId,
        label: displayTitle,
        enabled: splitDragEnabled,
        needsDedicatedHandle: needsSplitDragHandle,
        dragStartTarget: dragStartTargetRef.current,
      });
      dragStartTargetRef.current = null;
    },
    [displayTitle, needsSplitDragHandle, session.deviceLinkDeviceId, session.id, splitDragEnabled],
  );

  // isActive 由 false → true(或初次 mount 时即为 true)→ 把行滚进 viewport。
  // 同 active 重渲染 / 其它字段更新不触发(useEffect deps 只有 isActive)。
  useEffect(() => {
    if (isActive && !navigationOnly) scrollIntoNearestView(rowRef.current);
  // navigationOnly is fixed for the lifetime of a mounted row; shared role switches
  // unmount the old list, so the active-session scroll contract stays isActive-only.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isActive]);

  // archivePending 生命周期:进入 pending → 起 4s 自动撤回 timer + document mousedown
  // 监听(点击不在 confirm 胶囊上就立刻撤回)。退出 pending → 全部清理。这两条退路确保
  // 用户不会因为忘了取消而误归档,也不会让 pending 态滞留把行的 hover 行为锁死。
  useEffect(() => {
    if (!archivePending) return;
    const dismiss = () => {
      setArchivePending(false);
    };
    const timer = setTimeout(dismiss, 4000);
    const onDocMouseDown = (e: MouseEvent) => {
      const pill = confirmPillRef.current;
      if (pill && e.target instanceof Node && pill.contains(e.target)) return;
      dismiss();
    };
    // capture 阶段 —— 早于行自身的 onClick(避免点击行本身触发导航)
    document.addEventListener('mousedown', onDocMouseDown, true);
    return () => {
      clearTimeout(timer);
      document.removeEventListener('mousedown', onDocMouseDown, true);
    };
  }, [archivePending]);

  // 编辑态 / 切换 session 时一并撤回 pending,避免脏状态泄漏到下一次
  useEffect(() => {
    if (isEditing) setArchivePending(false);
  }, [isEditing]);

  // F-PJ-9 menu handlers — Radix DropdownMenu 在 onSelect 后自动关闭菜单
  const handleRenameSelect = useCallback(() => {
    if (remoteWritesBlocked) {
      toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
      return;
    }
    setEditValue(displayTitle);
    committedRef.current = false;
    setIsEditing(true);
  }, [displayTitle, remoteWritesBlocked, t]);

  const handleArchiveSelect = useCallback(() => {
    if (remoteWritesBlocked) {
      toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
      return;
    }
    onAction(session.id, 'archive');
  }, [remoteWritesBlocked, session.id, onAction, t]);

  const handleUnarchiveSelect = useCallback(() => {
    if (remoteWritesBlocked) {
      toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
      return;
    }
    onAction(session.id, 'unarchive');
  }, [remoteWritesBlocked, session.id, onAction, t]);

  const handleDeleteSelect = useCallback(() => {
    if (remoteWritesBlocked) {
      toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
      return;
    }
    onAction(session.id, 'delete');
  }, [remoteWritesBlocked, session.id, onAction, t]);

  const handlePinSelect = useCallback(() => {
    if (remoteWritesBlocked) {
      toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
      return;
    }
    onTogglePin(session.id, isPinned);
  }, [remoteWritesBlocked, session.id, isPinned, onTogglePin, t]);

  const handleMoveToProjectSelect = useCallback(
    (workingDir: string) => {
      onMoveSession?.(session.id, { kind: 'project', workingDir });
    },
    [onMoveSession, session.id],
  );

  const handleMoveToProjectBrowse = useCallback(() => {
    onMoveSession?.(session.id, { kind: 'browseProject' });
  }, [onMoveSession, session.id]);

  const handleMoveToDialogue = useCallback(() => {
    onMoveSession?.(session.id, { kind: 'dialogue' });
  }, [onMoveSession, session.id]);

  // 「导出会话…」—— 打成 .cshare 分享给同事(弹敏感内容确认 + 可选密码,
  // 保存对话框与编排全在 main)。remote / orca / draft 会话不显示此入口
  // (转录在远端或协同关系不可移植,main 侧同样有双保险拒绝)。
  const [shareExportOpen, setShareExportOpen] = useState(false);
  const handleExportShareSelect = useCallback(() => {
    setShareExportOpen(true);
  }, []);

  // 「在新窗口打开」—— 把该会话在一个完整的新窗口里打开(对标 Codex 多开),便于
  // 四角各钉一个会话同时盯。窗口生命周期由 main/secondary-windows.ts 负责。
  const handleOpenInNewWindowSelect = useCallback(() => {
    if (remoteWritesBlocked) {
      toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
      return;
    }
    void window.electronAPI.maker.openSessionInNewWindow(session.id, session.deviceLinkDeviceId);
  }, [remoteWritesBlocked, session.deviceLinkDeviceId, session.id, t]);

  // 复制 cindy://session/<id> 深度链接到剪贴板。三个变体(标准/Pinned/Archived/Draft)
  // 共用此 handler — sessionId 始终存在(draft 也是 DB-backed 的 Session row)。
  // 远程会话把归属设备冻进 `?device=`:发送时的引用解析不再依赖被控端此刻在线。
  const handleCopyDeepLinkSelect = useCallback(async () => {
    const link = buildSessionDeepLink(session.id, { deviceId: session.deviceLinkDeviceId });
    try {
      await navigator.clipboard.writeText(link);
      toast.success(t('ccAgent.sidebar.deepLink.copied'));
    } catch (err) {
      log.warn('clipboard write failed', err);
      toast.warning(t('ccAgent.sidebar.deepLink.copyFailed'));
    }
  }, [session.deviceLinkDeviceId, session.id, t]);

  // 单项「复制任务链接」:直接复制 cindy://session/<id> 深链(可粘贴到聊天里
  // 渲染成会话 chip)。原「复制会话 ID」二级菜单(深度链接 / 仅 ID / Agent)已按
  // 产品决策收敛为这一项;不自带分隔线,分组由各使用点决定,避免菜单被切得过碎。
  const copySessionIdSubmenu = (
    <DropdownMenuItem onSelect={() => void handleCopyDeepLinkSelect()} className={MENU_ITEM_CLASS}>
      {t('ccAgent.sidebar.sessionMenu.copySessionLink')}
    </DropdownMenuItem>
  );
  const canMoveToProject =
    Boolean(onMoveSession) &&
    !isEmpty &&
    !session.remoteHostId &&
    !session.deviceLinkDeviceId &&
    // Agent 在另一台电脑运行的任务也可移动:那台按任务 id 定址 Agent 工作区,与本机路径无关。
    session.status !== 'archived';

  // 导出 .cshare 的可见性:draft 无内容、remote 转录在远端、device-link 数据在
  // 被控端 —— 隐藏入口。Orca lead 可导出(整个协同随包);Worker 不进 sidebar,
  // 无需在此排除。
  const canExportShare =
    !isEmpty &&
    !session.remoteHostId &&
    session.orcaRole !== 'worker' &&
    !session.deviceLinkDeviceId &&
    // Agent 在另一台电脑运行:转录在那台,本机打包不全。
    !session.agentDeviceId;

  const exportShareMenuItem = canExportShare ? (
    <DropdownMenuItem onSelect={handleExportShareSelect} className={MENU_ITEM_CLASS}>
      {t('ccAgent.sidebar.sessionMenu.exportShare')}
    </DropdownMenuItem>
  ) : null;

  const moveToProjectSubmenu = canMoveToProject ? (
    <SessionProjectMoveSubmenu
      projectOptions={projectOptions}
      currentWorkingDir={session.workspaceKind === 'project' ? session.workingDir : null}
      isDialogue={session.workspaceKind === 'dialogue'}
      onSelectProject={handleMoveToProjectSelect}
      onBrowseProject={handleMoveToProjectBrowse}
      onMoveToDialogue={handleMoveToDialogue}
    />
  ) : null;

  const showAutomationRunAction =
    isAutomationGenerated &&
    !insideAutomationGroup &&
    !isArchived &&
    !isEmpty &&
    !remoteWritesBlocked &&
    Boolean(effectiveScheduleId);
  const sessionActionButtons = (
    <>
      {/* 自动化会话专属 Run 直点按钮:仅顶层散落(insideAutomationGroup
          为 false)的 automation-generated 会话可见 —— 分组内 (SessionEntryList
          展开的子行) 组头已经暴露过同链路操作,再挂一份纯属视觉噪音。其它硬边界:
          未归档 + 非 draft + 非远程只读。Edit 与左侧 Timer chip 同链路,不再重复
          暴露;Run 走 main.maker.schedule.runNow,与 AutomationSessionGroupItem
          组头 [Run ▶️][More ⋮] 保持高频直点、低频收纳的同构。 */}
      {showAutomationRunAction && (
        <SessionAction
          label={t('ccAgent.sidebar.automationGroup.menu.runNow')}
          onClick={() => void handleAutomationRunClick()}
          isActive={isActive}
        >
          <Play size={14} strokeWidth={2} />
        </SessionAction>
      )}
      <SessionAction
        label={t('ccAgent.sidebar.sessionMenu.moreActions')}
        onClick={(e) => {
          const rect = e.currentTarget.getBoundingClientRect();
          prefetchRemovalPreflight();
          setMenuPos({ x: rect.left, y: rect.bottom + 2 });
        }}
        isActive={isActive}
      >
        <EllipsisVertical size={14} strokeWidth={2} />
      </SessionAction>
      {isArchived && !remoteWritesBlocked ? (
        <SessionAction
          label={t('ccAgent.sidebar.sessionMenu.unarchive')}
          onClick={() => handleUnarchiveSelect()}
          isActive={isActive}
        >
          <Undo size={14} strokeWidth={2} />
        </SessionAction>
      ) : canQuickArchive ? (
        <SessionAction
          label={t('ccAgent.sidebar.sessionMenu.archived')}
          onClick={() => {
            // 第一步:亮出 Confirm 胶囊,同时把 dirty 预检发出去。用户抬手
            // 再点第二下的间隔足够那次 git status 跑完 → 归档零等待。
            prefetchRemovalPreflight();
            setArchivePending(true);
          }}
          isActive={isActive}
        >
          <Archive size={14} strokeWidth={2} />
        </SessionAction>
      ) : null}
    </>
  );

  const row = (
    // biome-ignore lint/a11y/useSemanticElements: 行内包含菜单和快捷操作按钮,不能改成原生 button。
    <div
      ref={rowRef}
      data-session-id={session.id}
      data-sidebar-session-row={navigationOnly ? undefined : 'true'}
      data-sidebar-navigation-row={navigationOnly ? 'true' : undefined}
      data-split-group-drag-source={splitDragEnabled ? 'true' : undefined}
      draggable={splitDragEnabled && (dragContainerState.nativeSortable || !needsSplitDragHandle)}
      role="button"
      tabIndex={0}
      onPointerOver={(event) => {
        setRowTooltipOpen(!isNestedSessionRowAction(event.target, event.currentTarget));
      }}
      onPointerLeave={() => setRowTooltipOpen(false)}
      onPointerDownCapture={(event) => {
        dragStartTargetRef.current = event.target instanceof Element ? event.target : null;
      }}
      onPointerUpCapture={() => {
        dragStartTargetRef.current = null;
      }}
      onPointerCancelCapture={() => {
        dragStartTargetRef.current = null;
      }}
      onDragStart={handleDragStart}
      onDragEnd={(event) => {
        dragStartTargetRef.current = null;
        finishSessionDrag(event, session.id, session.deviceLinkDeviceId);
      }}
      onPointerDown={(e) => {
        if (!navigationOnly && shouldPrefetchSessionOnPointerDown(e, { isActive, isEditing })) {
          makerChatStore.ensureInitialMessages(session.id);
        }
      }}
      onClick={handleClick}
      onDoubleClick={handleDoubleClick}
      onKeyDown={(e) => {
        // target 守卫:内部按钮(More/Archive/Undo/Edit/Run 等)的 Enter/Space
        // keydown 会冒泡到行级 onKeyDown,而这些按钮的 onClick 只 stopPropagation
        // click 不 stop keydown —— 不加守卫会造成「Tab 到按钮按 Enter 触发按钮动作
        // + 同时进入会话」的双触发。SessionItem 早期只有 More/Archive 时未暴露,
        // PR #658 给 automation 会话行加 Edit/Run 后 P2 review 显性化。
        if (e.target !== e.currentTarget) return;
        if (!isEditing && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          onClick(session.id);
        }
      }}
      onContextMenu={(e) => {
        if (isEditing) {
          // 重命名输入框上的右键交给系统的可编辑菜单(剪切/复制/粘贴,main 侧
          // selection-context-menu),但必须拦下冒泡——否则会穿透到滚动容器的
          // 空白处右键 handler,整理菜单和原生菜单叠着弹(2026-08-13 实机回归)。
          e.stopPropagation();
          return;
        }
        e.preventDefault();
        e.stopPropagation();
        if (!canOpenTaskMenu) return;
        if (!navigationOnly) prefetchRemovalPreflight();
        setMenuPos({ x: e.clientX, y: e.clientY });
      }}
      className={cn(
        // 基础几何:高 32 / 圆角 8。普通会话的 Agent → 标题保持 10px;
        // 自动任务行 Agent → Timer 延续原 Clock 的 6px,Timer → 标题也为 6px。
        // rounded-full:hover/active 底与顶部导航行、项目行同款药丸形。
        'group relative flex h-8 w-full items-center rounded-full',
        !isEditing && hasAutomationMeta ? 'gap-1.5' : 'gap-2.5',
        'select-none',
        // 缩进 + padding(见文件头注释的文字列对齐口径):
        //   indented=true → 左 20px(普通行 12px + 子层级缩进 8px)
        //   indented=false → 左 12px(Pinned / Unclassified / Dialogue 段)
        // 右侧信息槽按内容收缩;hover 时 archive 快捷按钮覆盖同一槽位。
        indented ? 'pl-5 pr-2' : 'pl-3 pr-2',
        // 注意:不加 transition-colors —— 行 bg 的 hover/active 变化要瞬时,
        // 否则归档/取消归档后 DOM 列表重排,原 hover bg 在前一个屏幕位置上要
        // 跑完 150ms 渐变才褪掉,视觉上像是"旧行仍然选中,延迟才切到新行"。
        // 用 ProjectAction 同款瞬时反馈,跟 Cursor / Codex sidebar 的体感一致。
        'text-left text-sm font-medium',
        !isEditing && 'cursor-pointer',
        // active 描边必须画在盒内且不参与布局。真实 border 会让固定宽高的
        // border-box 内容区四边各缩 1px,导致选中行的左侧 icon / 标题整体右移。
        isActive
          ? 'bg-sidebar-item-active [--task-tag-ring-bg:hsl(var(--sidebar-item-active))] text-sidebar-item-active-foreground shadow-[inset_0_0_0_1px_var(--sidebar-item-active-border)]'
          : isSelected
            ? 'bg-[var(--chat-input-chip-bg)] [--task-tag-ring-bg:var(--chat-input-chip-bg)] text-foreground'
            : cn(
                // 标签色球描边不随 hover 换色:CINDY 的 hover 底是半透明叠加色,
                // 用作描边会透出色球本色,描边消失、色球看似变大。
                'text-foreground hover:bg-sidebar-item-hover',
                // 菜单开着时鼠标常会离开行,行底仍保持 hover 色。
                menuPos !== null && 'bg-sidebar-item-hover',
              ),
        isSelected && 'ring-1 ring-inset ring-[var(--focus-ring-soft)]',
      )}
      aria-current={isActive ? 'page' : undefined}
      aria-pressed={isSelected || undefined}
    >
      {/* 左侧状态图标(vendor mark + 运行/需关注/草稿)——与置顶卡片共用 SessionStatusIcon,
          保证两处完全一致。
          外包 15px 定宽槽:状态图标本体 12px,槽宽与顶部导航/文件夹图标(15)一致,
          让会话标题与其它行落在同一文字列(见文件头注释)。 */}
      <span className="flex w-[15px] shrink-0 items-center justify-center">
        <SessionStatusIcon
          session={session}
          isRunning={leftIconRunning}
          isAttached={isAttached}
          hasAttentionNotification={hasAttentionNotification}
          isActive={isActive}
          showAttentionDot={false}
        />
      </span>
      {sharedTaskRole === 'owned' ? (
        <span
          className="flex w-3 shrink-0 items-center justify-center"
          data-testid={`shared-task-role-slot-owned-${session.id}`}
        >
          <Crown
            size={12}
            strokeWidth={1.8}
            className="text-[var(--warning-fg)]"
            aria-label={t('sharedTask.roleHost')}
          />
        </span>
      ) : null}

      {isEditing ? (
        <SessionRenameInput
          sessionId={session.id}
          value={editValue}
          onValueChange={setEditValue}
          onCommit={commitTitle}
          onCancel={() => {
            // Esc 取消视为终态:置 committedRef 拦掉 input 卸载触发的 blur 提交
            // 与生成中迟到的 AI 结果(Codex review P2:取消后不应再被 AI 改名)。
            committedRef.current = true;
            setIsEditing(false);
          }}
          containerClassName="min-w-0 flex-1"
          inputClassName="h-6 text-sm font-medium text-foreground"
          activeForeground={isActive}
        />
      ) : (
        //   matchIndices 由父层(useSessionSearch)注入时,渲染高亮 segments;否则
        //   走原 `<span>` 路径,无开销。highlightSegments 在 indices.length===0 时
        //   也会直接返回原 string,所以两路渲染最终都走 truncate 容器。
        // 远程项目 icon 跟项目标题同口径:直接贴在标题右侧。标题过长时标题截断,
        // icon shrink-0 保持可见;右侧槽位只保留 worktree + 时间 + hover action。
        <span
          data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}
          data-no-drag={splitDragHandleActive ? 'true' : undefined}
          draggable={splitDragHandleActive}
          className="min-w-0 flex flex-1 items-center gap-1.5"
        >
          {/* 绑定徽章优先于普通自动化 Timer:persistentSession 会话两者皆真,
              主图标统一为 Timer,绑定态额外承载频率/暂停信息。 */}
          {boundSchedules.length > 0 ? (
            <ScheduleBindingBadge
              schedules={boundSchedules}
              deviceLinkDeviceId={session.deviceLinkDeviceId}
              activeForeground={isActive}
            />
          ) : isAutomationGenerated ? (
            <AutomationSessionButton sessionId={session.id} size={10} activeForeground={isActive} />
          ) : null}
          <SidebarTitleMarquee
            title={displayTitle}
            className={isActive ? 'text-sidebar-item-active-foreground' : 'text-foreground'}
          >
            {titleContent}
          </SidebarTitleMarquee>
          {/* 任务标签常显、紧跟标题,不属于任务信息复选;标题过长时标题截断让位。 */}
          <TaskTagDots tags={session.tags} />
          {/* 这件任务所在的项目交给了伙伴时,显示伙伴头像(伙伴在跟进)。 */}
          <BotFollowMark followers={followers} />
          {remoteIconKind && (
            <RemoteProjectIcon
              kind={remoteIconKind}
              size={12}
              strokeWidth={1.8}
              connectionStatus={remoteIconConnectionStatus}
              className={cn(
                isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',
              )}
            />
          )}
          {/* Agent 在另一台电脑运行(任务在本机)的标识在左侧 Agent 图标上(信号波纹)。 */}
          {sourceLabel ? (
            <span
              title={sourceLabel}
              className={cn(
                'min-w-0 truncate text-xs font-normal',
                isActive
                  ? 'text-sidebar-item-active-foreground/70'
                  : 'text-[var(--cmd-palette-item-meta)]',
              )}
            >
              {sourceLabel}
            </span>
          ) : null}
        </span>
      )}

      {/* 右侧任务信息 + Archive 快捷按钮。
          时间与 sidebar 排序共用 lastActivityAt 的回退口径。
          worktree 并入任务信息复选,与 PR / 费用同一槽,不再常驻分叉图标。
          archive 快捷按钮 hover/focus 时进同一格文档流,标题 truncate 让位;
          完整菜单仍走右键。槽宽跟可见内容走:平时信息槽有多宽占多宽,「任务信息 =
          无」且无状态、无 worktree 时宽度归零。hover / 菜单打开时按钮入流,
          槽宽取信息层与按钮的较大值——不再绝对定位盖到标题上。 */}
      {!isEditing && (
        <div className="group/slot relative ml-auto flex h-6 shrink-0 items-center justify-end">
          {/* 任务信息同步 fade-out:hover/菜单打开/archivePending 时
              一起让位,确保只有 action buttons 占住右侧。fade 容器复用同一份条件,
              避免两个元素 fade 时机不一致产生闪烁。
              focus 隐藏条件用命名 group(/slot) 收窄到本槽位:行本身是
              role="button" tabIndex=0,点击选中后焦点常驻行内,若用整行的
              group-focus-within,选中态(非 hover)时间会被永久隐藏而 action
              buttons 又不显示,右侧变空白。 */}
          <div className="grid h-6 grid-cols-[max-content] items-center justify-items-end">
            <div
              className={cn(
                'col-start-1 row-start-1 flex items-center gap-1',
                // duration 与 action 按钮组的渐显同拍(120ms),让位/回归一进一出同步。
                'transition-opacity duration-[120ms]',
                !navigationOnly && !archivePending &&
                  'group-hover:opacity-0 group-hover:w-0 group-hover:overflow-hidden group-focus-within/slot:opacity-0 group-focus-within/slot:w-0 group-focus-within/slot:overflow-hidden',
                menuPos !== null && 'opacity-0 w-0 overflow-hidden',
                archivePending && 'opacity-0 w-0 overflow-hidden',
                // mod+1..9 序号徽标出现时同样让位:徽标独占行尾,不与时间/badge 并排。
                ordinalBadgeLabel != null && 'opacity-0 w-0 overflow-hidden',
              )}
            >
              {cindyMakePreparing && rightStatusKind === 'running' ? (
                <span
                  className={cn(
                    'max-w-[9rem] truncate text-xs font-normal',
                    isActive
                      ? 'text-sidebar-item-active-foreground/80'
                      : 'text-[var(--cmd-palette-item-meta)]',
                  )}
                >
                  {t('cindyMake.code.phases.' + cindyMakePreparing)}
                </span>
              ) : showRightStatus ? (
                <SidebarRightStatusIndicator kind={rightStatusKind} isActive={isActive} />
              ) : (
                // 任务信息复选:按用户勾选拼装 pr / worktree / tokens / cost / time;默认仅
                // time,与旧时间槽渲染等价。全不选 → SessionInfoMeta 渲染 null,槽宽归零。
                <SessionInfoMeta
                  pieces={infoPieces}
                  prRef={infoPrRef}
                  worktree={infoWorktree ?? undefined}
                  isActive={isActive}
                />
              )}
            </div>

            {canQuickArchive && archivePending && (
              <span
                aria-hidden
                className="invisible col-start-1 row-start-1 inline-block h-6 w-14"
              />
            )}
            {ordinalBadgeLabel != null && (
              <span aria-hidden className="invisible col-start-1 row-start-1 inline-flex">
                <SessionOrdinalBadgeKbd label={ordinalBadgeLabel} />
              </span>
            )}
            {canQuickArchive && archivePending && (
              <Button
                variant="secondary"
                tone="danger-surface"
                size="xs"
                compact
                ref={confirmPillRef}
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  setArchivePending(false);
                  onAction(session.id, 'archive-now');
                }}
                onPointerDown={(e) => e.stopPropagation()}
                onDoubleClick={(e) => e.stopPropagation()}
                className="absolute right-0 top-0 w-14"
                aria-label={t('ccAgent.sidebar.sessionMenu.archived')}
              >
                {t('ccAgent.sidebar.sessionMenu.archived')}
              </Button>
            )}
            {/* Action 按钮组(hover/menu open 时浮现,archivePending 期间整组让位给红色 pill)。
              尺寸/视觉与 Project Header 的 ProjectAction 同套(size-5 / icon 14 /
              strokeWidth 2 / gap-0.5);普通行 hover 走 sidebar-item-hover,选中行
              则用 active foreground 的半透明叠色保持红色胶囊内的反色体系。
              组装顺序固定为 [Run(automation only), More, Archive | Undo]:
                - 非 archived:More + Archive;Archive pill 撤回(超时/点外面)后
                  按钮立即还原,符合用户对 "撤回 = 回到点击前" 的直觉预期。
                - archived:More + Undo(lucide Undo),单击直接走 unarchive,
                  不像 Archive 那样需要二次确认 pill(unarchive 非破坏性)。 */}
            {!navigationOnly && !archivePending && (
              <>
                {/* 入流占位只负责把标题挤窄;真正的按钮保持可聚焦,不能 display:none。 */}
                <div
                  aria-hidden
                  className={cn(
                    'invisible col-start-1 row-start-1 h-6 items-center gap-0.5',
                    menuPos !== null
                      ? 'flex'
                      : 'hidden group-hover:flex group-focus-within/slot:flex',
                  )}
                >
                  {showAutomationRunAction ? <span className="size-5 shrink-0" /> : null}
                  <span className="size-5 shrink-0" />
                  {isArchived && !remoteWritesBlocked ? (
                    <span className="size-5 shrink-0" />
                  ) : canQuickArchive ? (
                    <span className="size-5 shrink-0" />
                  ) : null}
                </div>
                <div
                  className={cn(
                    'absolute right-0 top-0 flex h-6 items-center gap-0.5',
                    menuPos !== null
                      ? 'opacity-100'
                      : 'pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100',
                  )}
                >
                  {sessionActionButtons}
                </div>
              </>
            )}
          </div>
        </div>
      )}

      {/* mod+1..9 序号徽标(按住修饰键浮现,见 sessionOrdinalBadges):绝对定位
          在右侧时间槽位置(与行 pr-2 对齐),时间/badge 容器同步让位淡出;
          z-20 压过 hover 操作钮,pointer-events-none 不挡点击。前景色给到
          容器:普通行次级灰、active 反色行用 active foreground,kbd 内
          text-current + currentColor 底自动跟随。编辑态让位给重命名输入框。 */}
      {!isEditing && ordinalBadgeLabel != null && (
        <span
          className={cn(
            'pointer-events-none absolute inset-y-0 right-2 z-20 flex items-center',
            isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',
          )}
        >
          <SessionOrdinalBadgeKbd label={ordinalBadgeLabel} />
        </span>
      )}

      {/* 右键菜单:与 ProjectNode 同款 coordinate-anchored DropdownMenu —
          隐形 fixed-position trigger 锚定到 onContextMenu 捕获的鼠标坐标,
          Radix 自动处理打开/关闭、ESC、点外面关闭等行为。 */}
      {canOpenTaskMenu && !isEditing && (
        <DropdownMenu
          open={menuPos !== null}
          onOpenChange={(open) => {
            if (!open) setMenuPos(null);
          }}
        >
          <DropdownMenuTrigger asChild>
            <span
              aria-hidden
              style={{
                position: 'fixed',
                left: menuPos?.x ?? 0,
                top: menuPos?.y ?? 0,
                width: 0,
                height: 0,
                pointerEvents: 'none',
              }}
            />
          </DropdownMenuTrigger>
          <SessionTaskMenu key={`${session.deviceLinkDeviceId ?? ''}:${session.id}`}
            session={session} open={menuPos !== null} sideOffset={2} writeBlocked={remoteWritesBlocked}
            returnFocus={() => rowRef.current?.focus()}
            onRename={handleRenameSelect} onPin={handlePinSelect}
            onArchive={handleArchiveSelect} onUnarchive={handleUnarchiveSelect} onDelete={handleDeleteSelect}
            onOpenInNewWindow={handleOpenInNewWindowSelect}
            move={moveToProjectSubmenu} tags={tagMenu} copy={copySessionIdSubmenu} exportShare={exportShareMenuItem}
          />
        </DropdownMenu>
      )}

      {/* 导出 .cshare 弹窗:仅打开时挂载,避免侧栏每行常驻 Dialog 实例。 */}
      {tagEditorOpen && <TaskTagEditor session={session} onClose={() => setTagEditorOpen(false)} />}
      {shareExportOpen && (
        <SessionShareExportDialog
          open={shareExportOpen}
          sessionId={session.id}
          onOpenChange={setShareExportOpen}
        />
      )}
    </div>
  );

  // PR tips(session-git-pr-context):仅当会话有关联 PR 时整行包零延迟
  // Tooltip——鼠标一到列表项立即显示该对话的 PR 与实时状态(产品要求,
  // 不等全局 500ms 悬停延迟)。无 PR 的行原样返回,保持本文件"密集列表
  // 少挂 Tip"的既有取舍。
  // 统一 hover 浮层:PR 优先;来源标签已写在标题旁,不再用浮层重复。
  // 具体优先级、配色和 orca-lead 回退详见 SessionTooltip.tsx。
  // 单独 automation-generated 会话(未被 AutomationSessionGroupItem 吸走)在 hover 时
  // 显示下次运行或停止状态。分组内子行
  // (insideAutomationGroup=true)由组头承担,这里不再挂 automation 浮层。
  const showAutomationTooltip = isAutomationGenerated && !insideAutomationGroup;
  return (
    <SessionTooltip
      sessionId={session.id}
      prRefs={prRefs}
      isAutomationSession={showAutomationTooltip}
      controlledOpen={rowTooltipOpen}
    >
      {row}
    </SessionTooltip>
  );
});

/** SessionItem 右侧 hover action 图标按钮 —— 尺寸/视觉与 Project Header 的
 *  ProjectAction 基本一致(size-5 / icon 14×14 / strokeWidth 2 / 圆角 md /
 *  普通行 hover 用 sidebar-item-hover + foreground;选中行保持 active foreground,
 *  hover 只叠一层同色半透明高光)。 */
function SessionAction({
  label,
  onClick,
  isActive,
  children,
}: {
  label: string;
  onClick: (e: ReactMouseEvent<HTMLButtonElement>) => void;
  isActive: boolean;
  children: ReactNode;
}) {
  return (
    <Tip text={label}>
      <button
        type="button"
        aria-label={label}
        onClick={(e) => {
          e.stopPropagation();
          onClick(e);
        }}
        onPointerDown={(e) => e.stopPropagation()}
        onDoubleClick={(e) => e.stopPropagation()}
        className={cn(
          'shrink-0 size-5 flex items-center justify-center rounded-md',
          'focus:outline-none',
          isActive
            ? 'text-sidebar-item-active-foreground hover:text-sidebar-item-active-foreground hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'
            : 'text-sidebar-action-icon hover:bg-sidebar-item-hover hover:text-foreground',
        )}
      >
        {children}
      </button>
    </Tip>
  );
}
import { isSharedTaskPeer } from '@cindy/device-link';