TaskListItem.tsx 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. /* eslint-disable max-lines -- task item 同时承载默认列表和 timeline 两行布局的共享交互,先保持动作链路集中避免归档/置顶回归。 */
  2. import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
  3. import {
  4. Archive,
  5. Clock,
  6. CloudUpload,
  7. ListTree,
  8. LoaderIcon,
  9. Moon,
  10. Pin,
  11. Smartphone,
  12. } from "lucide-react";
  13. import { isCronTask, isOffPeakTask, type ZCodeTaskMeta } from "@zcode/shared";
  14. import { TID_TASK_ARCHIVE, TID_TASK_ITEM, testId } from "@zcode/shared";
  15. import { Badge } from "@/components/ui/badge.js";
  16. import { Button } from "@/components/ui/button.js";
  17. import { cn } from "@/components/lib/utils.js";
  18. import { ControlHintTooltip } from "@/ControlHintTooltip.js";
  19. import { getPathLeaf } from "@/lib/path.js";
  20. import { formatTaskTitleWithChanges, getTaskChangeSummary } from "@/lib/taskChangeSummary.js";
  21. import {
  22. deriveTaskLeadingIndicator,
  23. formatTaskRelativeTime,
  24. } from "@/lib/taskListItemPresentation.js";
  25. import { getTaskListAttention, getTaskListRowActivity } from "@/v4/taskListRowActivity.js";
  26. import { TaskListItemContextMenu } from "@/TaskListItemContextMenu.js";
  27. import { TaskInteractionBadge } from "@/TaskInteractionBadge.js";
  28. import { useTaskListItemContextActions } from "@/useTaskListItemContextActions.js";
  29. import { useFeedbackStore } from "@/feedback/feedbackStore.js";
  30. import { useModelTrajectoryStore } from "@/store/modelTrajectoryStore.js";
  31. import { buildTaskFeedbackDescription } from "@/lib/taskFeedbackDraft.js";
  32. import { toast } from "@/components/ui/toast.js";
  33. import { buildTaskWorkspaceKey } from "@/lib/taskQueryCache.js";
  34. import { useV4SplitPaneEntry } from "@/v4/splitPaneEntryContext.js";
  35. import { buildWorkbenchSessionKey, useWorkbenchGroupStore } from "@/v4/workbenchGroupStore.js";
  36. import { useTaskInteractionAutoResolutionSnooze } from "@/hooks/useTaskInteractionAutoResolutionSnooze.js";
  37. import {
  38. WORKBENCH_SESSION_DRAG_MIME,
  39. clearActiveWorkbenchSessionDragPayload,
  40. serializeWorkbenchSessionDragPayload,
  41. setActiveWorkbenchSessionDragPayload,
  42. } from "@/v4/workbenchDragDrop.js";
  43. import { useOptionalTabStore } from "@/store/TabStoreProvider.js";
  44. import { isWorkspaceReadOnly } from "@/store/tabStore.js";
  45. import { TaskTitleOverflowText } from "@/components/TaskTitleOverflowText.js";
  46. import { createTaskWorkbenchDragPreview } from "@/lib/taskWorkbenchDragPreview.js";
  47. import { runUserAction } from "@/lib/userActionTelemetry.js";
  48. import { TaskRowActionButton } from "@/workspace-grouped-tasks/task-row-action-button.js";
  49. import { TaskWorkflowRunLines } from "@/components/workflow-run-line/TaskWorkflowRunLines.js";
  50. type TaskListItemIntl = {
  51. formatMessage: (desc: { id: string }, values?: Record<string, string>) => string;
  52. };
  53. interface TaskListItemProps {
  54. workspacePath: string;
  55. remoteSessionId?: string;
  56. task: ZCodeTaskMeta;
  57. isPinned: boolean;
  58. isActive: boolean;
  59. isMobileActive?: boolean;
  60. onSelectTask: (taskId: string) => void;
  61. onArchiveTaskInline: (e: React.MouseEvent, taskId: string) => void;
  62. onCancelArchiveConfirm: () => void;
  63. isArchiveConfirming: boolean;
  64. onTogglePinTask: (taskId: string, pinned: boolean) => void;
  65. onStartRenameTask: (taskId: string, currentTitle: string) => void;
  66. onArchiveTask: (taskId: string) => void;
  67. onMarkTaskAsUnread: (taskId: string) => void;
  68. onOpenTaskContextMenu?: (taskId: string) => void;
  69. onOpenFileTree?: (task: ZCodeTaskMeta) => void;
  70. variant?: "default" | "timeline";
  71. showPinAction?: boolean;
  72. intl: TaskListItemIntl;
  73. actionsDisabled?: boolean;
  74. actionsDisabledReason?: string;
  75. }
  76. function areJsonFieldsEqual(left: unknown, right: unknown) {
  77. return JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
  78. }
  79. function getTaskAutomationIdentity(task: ZCodeTaskMeta): string | undefined {
  80. return task.cronAutomationId ?? (task as ZCodeTaskMeta & { automationId?: string }).automationId;
  81. }
  82. function areTaskListItemTaskFieldsEqual(left: ZCodeTaskMeta, right: ZCodeTaskMeta) {
  83. if (left === right) {
  84. return true;
  85. }
  86. return (
  87. left.taskId === right.taskId &&
  88. left.workspacePath === right.workspacePath &&
  89. left.workspaceIdentity === right.workspaceIdentity &&
  90. left.provider === right.provider &&
  91. left.title === right.title &&
  92. left.forkedFromTaskId === right.forkedFromTaskId &&
  93. left.updatedAt === right.updatedAt &&
  94. left.unreadAt === right.unreadAt &&
  95. getTaskAutomationIdentity(left) === getTaskAutomationIdentity(right) &&
  96. left.status === right.status &&
  97. areJsonFieldsEqual(left.pendingInteraction, right.pendingInteraction) &&
  98. areJsonFieldsEqual(getTaskListRowActivity(left), getTaskListRowActivity(right)) &&
  99. areJsonFieldsEqual(left.changeSummary, right.changeSummary)
  100. );
  101. }
  102. function areTaskListItemPropsEqual(left: TaskListItemProps, right: TaskListItemProps) {
  103. return (
  104. left.workspacePath === right.workspacePath &&
  105. left.remoteSessionId === right.remoteSessionId &&
  106. areTaskListItemTaskFieldsEqual(left.task, right.task) &&
  107. left.isPinned === right.isPinned &&
  108. left.isActive === right.isActive &&
  109. left.isMobileActive === right.isMobileActive &&
  110. left.isArchiveConfirming === right.isArchiveConfirming &&
  111. left.variant === right.variant &&
  112. left.showPinAction === right.showPinAction &&
  113. left.intl === right.intl &&
  114. left.actionsDisabled === right.actionsDisabled &&
  115. left.actionsDisabledReason === right.actionsDisabledReason &&
  116. left.onSelectTask === right.onSelectTask &&
  117. left.onArchiveTaskInline === right.onArchiveTaskInline &&
  118. left.onCancelArchiveConfirm === right.onCancelArchiveConfirm &&
  119. left.onTogglePinTask === right.onTogglePinTask &&
  120. left.onStartRenameTask === right.onStartRenameTask &&
  121. left.onArchiveTask === right.onArchiveTask &&
  122. left.onMarkTaskAsUnread === right.onMarkTaskAsUnread &&
  123. left.onOpenTaskContextMenu === right.onOpenTaskContextMenu &&
  124. left.onOpenFileTree === right.onOpenFileTree
  125. );
  126. }
  127. export const MemoTaskItem = memo(function TaskListItem({
  128. workspacePath,
  129. remoteSessionId,
  130. task,
  131. isPinned,
  132. isActive,
  133. isMobileActive = false,
  134. onSelectTask,
  135. onArchiveTaskInline,
  136. onCancelArchiveConfirm,
  137. isArchiveConfirming,
  138. onTogglePinTask,
  139. onOpenTaskContextMenu,
  140. onOpenFileTree,
  141. variant = "default",
  142. showPinAction = true,
  143. intl,
  144. actionsDisabled = false,
  145. actionsDisabledReason,
  146. }: TaskListItemProps) {
  147. const [hoverActionsVisible, setHoverActionsVisible] = useState(false);
  148. const [focusActionsVisible, setFocusActionsVisible] = useState(false);
  149. const [isHoverNone] = useState(
  150. () =>
  151. typeof window !== "undefined" &&
  152. typeof window.matchMedia === "function" &&
  153. window.matchMedia("(hover: none)").matches,
  154. );
  155. const itemRef = useRef<HTMLLIElement | null>(null);
  156. const workspaceActionsDisabled = useOptionalTabStore(
  157. (state) =>
  158. actionsDisabled || isWorkspaceReadOnly(state, task.workspacePath, task.workspaceIdentity),
  159. );
  160. const workspaceActionsDisabledReason = workspaceActionsDisabled
  161. ? (actionsDisabledReason ??
  162. intl.formatMessage({ id: "workspaceSidebar.unavailableLocalDirectory" }))
  163. : undefined;
  164. const snoozeInteractionAutoResolution = useTaskInteractionAutoResolutionSnooze({
  165. workspacePath,
  166. ...(task.workspaceIdentity ? { workspaceIdentity: task.workspaceIdentity } : {}),
  167. ...(remoteSessionId ? { remoteSessionId } : {}),
  168. sessionId: task.taskId,
  169. });
  170. useEffect(() => {
  171. if (!isArchiveConfirming) {
  172. return;
  173. }
  174. function handleKeyDown(event: KeyboardEvent) {
  175. if (event.key === "Escape") {
  176. onCancelArchiveConfirm();
  177. }
  178. }
  179. function handlePointerDown(event: PointerEvent) {
  180. const target = event.target;
  181. if (target instanceof Node && itemRef.current?.contains(target)) {
  182. return;
  183. }
  184. onCancelArchiveConfirm();
  185. }
  186. // 全局时间线和置顶列表的确认 key 含 workspacePath,Windows
  187. // 反斜杠拼进 CSS selector 后会被当作转义,确认按钮因此被误判为条目外点击。
  188. // 确认项直接使用自身 ref 判断事件边界,避免业务 key 与 CSS 语法耦合。
  189. window.addEventListener("keydown", handleKeyDown, true);
  190. window.addEventListener("pointerdown", handlePointerDown, true);
  191. return () => {
  192. window.removeEventListener("keydown", handleKeyDown, true);
  193. window.removeEventListener("pointerdown", handlePointerDown, true);
  194. };
  195. }, [isArchiveConfirming, onCancelArchiveConfirm]);
  196. const splitPaneEntryEnabled = useV4SplitPaneEntry().enabled;
  197. const taskWorkspaceScope = useMemo(
  198. () => ({
  199. workspacePath,
  200. ...(task.workspaceIdentity?.trim() ? { workspaceIdentity: task.workspaceIdentity } : {}),
  201. ...(remoteSessionId ? { remoteSessionId } : {}),
  202. }),
  203. [remoteSessionId, task.workspaceIdentity, workspacePath],
  204. );
  205. const taskWorkbenchSessionKey = useMemo(
  206. () => buildWorkbenchSessionKey(taskWorkspaceScope, task.taskId),
  207. [task.taskId, taskWorkspaceScope],
  208. );
  209. const isSessionInWorkbenchGroup = useWorkbenchGroupStore((state) =>
  210. Boolean(state.sessionIndex[taskWorkbenchSessionKey]),
  211. );
  212. const canDragToWorkbench =
  213. !workspaceActionsDisabled && splitPaneEntryEnabled && !isSessionInWorkbenchGroup;
  214. // V4 runtime/interaction 已由 sessions-index 投影,旧 Zustand map 不再接收
  215. // 后台会话 delta。row 直接消费随列表条目到达的 activity sidecar,避免 spinner/attention 假静止。
  216. const taskActivity = getTaskListRowActivity(task);
  217. const taskAttention = getTaskListAttention(task);
  218. const hasPendingInteraction = Boolean(task.pendingInteraction) || taskAttention !== null;
  219. const taskAttentionLabel = taskAttention
  220. ? intl.formatMessage({
  221. id: taskAttention.kind === "userInput" ? "taskList.userInputTag" : "taskList.permissionTag",
  222. })
  223. : null;
  224. const taskAttentionDisplay =
  225. taskAttention && taskAttentionLabel && taskAttention.count > 1
  226. ? intl.formatMessage(
  227. { id: "taskList.attentionCount" },
  228. { label: taskAttentionLabel, count: String(taskAttention.count) },
  229. )
  230. : taskAttentionLabel;
  231. const taskTitle =
  232. task.title ||
  233. intl.formatMessage({
  234. id: task.forkedFromTaskId ? "taskList.forkedUntitled" : "taskList.untitled",
  235. });
  236. const handleSelect = useCallback(() => {
  237. runUserAction({
  238. input: { featureId: "task.lifecycle", action: "open", trigger: "button" },
  239. operation: () => onSelectTask(task.taskId),
  240. completed: { resultSource: "optimistic_projection" },
  241. failureStage: "task_open",
  242. });
  243. }, [onSelectTask, task.taskId]);
  244. const handleDragStart = useCallback(
  245. (event: React.DragEvent<HTMLLIElement>) => {
  246. if (!canDragToWorkbench) {
  247. event.preventDefault();
  248. return;
  249. }
  250. event.dataTransfer.effectAllowed = "copy";
  251. const payload = {
  252. kind: "zcode/session" as const,
  253. workspacePath,
  254. ...(task.workspaceIdentity?.trim() ? { workspaceIdentity: task.workspaceIdentity } : {}),
  255. ...(remoteSessionId ? { remoteSessionId } : {}),
  256. sessionId: task.taskId,
  257. };
  258. setActiveWorkbenchSessionDragPayload(payload);
  259. event.dataTransfer.setData(
  260. WORKBENCH_SESSION_DRAG_MIME,
  261. serializeWorkbenchSessionDragPayload(payload),
  262. );
  263. event.dataTransfer.setData("text/plain", taskTitle);
  264. // 浏览器默认 drag preview 背景透明、边界不清晰;保留原行内容,
  265. // 只补齐 Grouped drag overlay 使用的背景、边框和阴影。
  266. const cleanupDragPreview = createTaskWorkbenchDragPreview({
  267. clientX: event.clientX,
  268. clientY: event.clientY,
  269. dataTransfer: event.dataTransfer,
  270. source: event.currentTarget,
  271. });
  272. const ownerWindow = event.currentTarget.ownerDocument.defaultView;
  273. if (ownerWindow) {
  274. ownerWindow.requestAnimationFrame(cleanupDragPreview);
  275. } else {
  276. cleanupDragPreview();
  277. }
  278. },
  279. [
  280. canDragToWorkbench,
  281. remoteSessionId,
  282. task.taskId,
  283. task.workspaceIdentity,
  284. taskTitle,
  285. workspacePath,
  286. ],
  287. );
  288. const handleDragEnd = useCallback(() => {
  289. clearActiveWorkbenchSessionDragPayload();
  290. }, []);
  291. const handleContextMenu = useCallback(() => {
  292. onOpenTaskContextMenu?.(task.taskId);
  293. }, [onOpenTaskContextMenu, task.taskId]);
  294. const handleOpenFileTree = useCallback(
  295. (event: React.MouseEvent) => {
  296. event.preventDefault();
  297. event.stopPropagation();
  298. if (workspaceActionsDisabled) {
  299. return;
  300. }
  301. runUserAction({
  302. input: { featureId: "workbench.file", action: "open_tree", trigger: "button" },
  303. operation: () => onOpenFileTree?.(task),
  304. completed: { resultSource: "local_commit" },
  305. failureStage: "file_tree_open",
  306. });
  307. },
  308. [onOpenFileTree, task, workspaceActionsDisabled],
  309. );
  310. const handleArchive = useCallback(
  311. (event: React.MouseEvent) => {
  312. if (workspaceActionsDisabled) {
  313. event.preventDefault();
  314. event.stopPropagation();
  315. return;
  316. }
  317. runUserAction({
  318. input: { featureId: "task.lifecycle", action: "archive", trigger: "button" },
  319. operation: () => onArchiveTaskInline(event, task.taskId),
  320. completed: { resultSource: "optimistic_projection" },
  321. failureStage: "task_archive",
  322. });
  323. },
  324. [onArchiveTaskInline, task.taskId, workspaceActionsDisabled],
  325. );
  326. const handleTogglePin = useCallback(
  327. (event: React.MouseEvent) => {
  328. event.preventDefault();
  329. event.stopPropagation();
  330. if (workspaceActionsDisabled) {
  331. return;
  332. }
  333. onTogglePinTask(task.taskId, !isPinned);
  334. },
  335. [isPinned, onTogglePinTask, task.taskId, workspaceActionsDisabled],
  336. );
  337. const handleMouseEnter = useCallback(() => {
  338. setHoverActionsVisible(true);
  339. }, []);
  340. const handleMouseLeave = useCallback(() => {
  341. setHoverActionsVisible(false);
  342. // 归档二次确认依赖用户第二次点击确认;鼠标离开 row 时清理 hover 展示即可。
  343. // 如果同步取消确认,用户移动鼠标稍微离开任务行后确认按钮会消失,导致二次确认无法稳定完成。
  344. }, []);
  345. const leadingIndicator = useMemo(
  346. () => deriveTaskLeadingIndicator(task, taskActivity),
  347. [task, taskActivity],
  348. );
  349. const isTaskCron = isCronTask(task);
  350. // 月亮身份改为持久 meta 标记判断;off-peak store 反查在任务被删除后会丢失
  351. // 会话溯源,且让每一行多背一个全局 store 订阅。
  352. const isTaskOffPeak = isOffPeakTask(task);
  353. const showTimelineIdleIndicator =
  354. variant === "timeline" && leadingIndicator === "none" && !isPinned;
  355. // 手机远控标记和置顶状态共用左侧 leading 槽。
  356. // 已置顶任务如果继续常显 Pin,会和绝对定位的手机图标重叠;手机激活态默认让手机图标优先,hover 时再显示 Pin 操作。
  357. const showPinnedState = isPinned && leadingIndicator === "none" && !isMobileActive;
  358. const shouldMountWorkspaceTaskActions = hoverActionsVisible || focusActionsVisible || isHoverNone;
  359. // hover:none 只代表触屏端需要常驻 action,不代表应永久隐藏时间、状态和变更摘要。
  360. // 元信息仅在真实 hover / focus 交互时让位,保持旧触屏布局的“元信息 + action”语义。
  361. const shouldSuppressWorkspaceTaskMetadata = hoverActionsVisible || focusActionsVisible;
  362. const taskTimeLabel = formatTaskRelativeTime(task.updatedAt, intl);
  363. const taskChangeSummary = getTaskChangeSummary(task);
  364. const isRemoteTask = Boolean(task.workspaceIdentity?.trim());
  365. const archiveLabel = intl.formatMessage({
  366. id: isArchiveConfirming ? "common.confirm" : "taskList.archive",
  367. });
  368. const taskTitleWithChanges = formatTaskTitleWithChanges(taskTitle, taskChangeSummary, intl);
  369. const workspaceLabel = getPathLeaf(task.workspacePath);
  370. const taskItemKey = `${buildTaskWorkspaceKey(task.workspacePath, task.workspaceIdentity)}:${task.taskId}`;
  371. // 工作流运行行:标题下的第二条通道,
  372. // 与前置 16px 槽(error > unread > spinner)互不占位。只在会话带 run 摘要时挂组件。
  373. const hasWorkflowRunLines = taskActivity?.workflowActivity !== undefined;
  374. const workflowRunLinesNode = hasWorkflowRunLines ? (
  375. <TaskWorkflowRunLines
  376. activity={taskActivity.workflowActivity}
  377. isActive={isActive}
  378. intl={intl}
  379. session={{
  380. workspacePath: task.workspacePath,
  381. ...(task.workspaceIdentity ? { workspaceIdentity: task.workspaceIdentity } : {}),
  382. sessionId: task.taskId,
  383. }}
  384. />
  385. ) : null;
  386. const changeSummaryNode =
  387. !hasPendingInteraction && taskChangeSummary ? (
  388. <span className="shrink-0 text-ui-base">
  389. {taskChangeSummary.added > 0 ? (
  390. <span className="text-diff-added">+{taskChangeSummary.added}</span>
  391. ) : null}
  392. {taskChangeSummary.removed > 0 ? (
  393. <span className="ml-1 text-diff-removed">-{taskChangeSummary.removed}</span>
  394. ) : null}
  395. </span>
  396. ) : null;
  397. const shouldRenderArchiveAction =
  398. !workspaceActionsDisabled &&
  399. !hasPendingInteraction &&
  400. (shouldMountWorkspaceTaskActions || isArchiveConfirming);
  401. const archiveActionVisibilityClassName = isArchiveConfirming ? "flex" : "flex";
  402. const archiveActionNode = shouldRenderArchiveAction ? (
  403. /* 交互调整:任务进入“等待归档确认”后,右侧 hover 区不再显示归档按钮。
  404. 否则一个 item 同时出现“待确认状态”和“可归档操作”,视觉重心会互相打架。 */
  405. <div className={cn("items-center gap-0.5", archiveActionVisibilityClassName)}>
  406. {isArchiveConfirming ? (
  407. <ControlHintTooltip title={archiveLabel} side="top" align="center">
  408. <Button
  409. type="button"
  410. variant="destructive"
  411. size="sm"
  412. onMouseDown={(event) => {
  413. event.preventDefault();
  414. event.stopPropagation();
  415. }}
  416. onClick={handleArchive}
  417. data-testid={testId(TID_TASK_ARCHIVE, task.taskId)}
  418. // 归档确认态是显式等待用户决策的状态,必须持续显示 destructive 按钮。
  419. className={cn("shrink-0 border-destructive/20 px-2", archiveActionVisibilityClassName)}
  420. aria-label={archiveLabel}
  421. >
  422. <span>{intl.formatMessage({ id: "common.confirm" })}</span>
  423. </Button>
  424. </ControlHintTooltip>
  425. ) : (
  426. // Project / Pinned 的普通归档按钮曾覆盖 hover:bg-background/90,
  427. // 与同一行文件树 action 不一致;普通态统一复用共享 bg-hover action。
  428. <TaskRowActionButton
  429. label={archiveLabel}
  430. onClick={handleArchive}
  431. showTooltip
  432. testId={testId(TID_TASK_ARCHIVE, task.taskId)}
  433. >
  434. {isRemoteTask ? (
  435. // 本地和远端 task 混排时,统一 archive 图标无法提示操作会落在哪个 sqlite。
  436. // 远端任务使用 cloud 语义图标,避免用户误把远端归档当成本地归档。
  437. <CloudUpload className="h-3.5 w-3.5" />
  438. ) : (
  439. <Archive className="h-3.5 w-3.5" />
  440. )}
  441. </TaskRowActionButton>
  442. )}
  443. </div>
  444. ) : null;
  445. // 远端 task 的 session 未就绪时 resolver 会拒绝打开;渲染层同步隐藏入口,
  446. // 避免展示一个点击后无反馈的按钮。本地 task 不依赖已打开 tab,仍可直接按路径打开。
  447. const canOpenFileTree =
  448. Boolean(onOpenFileTree) && (!task.workspaceIdentity?.trim() || Boolean(remoteSessionId));
  449. const fileTreeActionNode =
  450. canOpenFileTree &&
  451. !workspaceActionsDisabled &&
  452. !hasPendingInteraction &&
  453. (shouldMountWorkspaceTaskActions || isMobileActive) ? (
  454. <span className="inline-flex shrink-0">
  455. {/* Pinned 文件树按钮曾手写 hover 背景和 tooltip,导致与 Grouped task
  456. 的同一操作视觉不一致。直接复用共享 action,统一 bg-hover、尺寸和 pointer 行为。 */}
  457. <TaskRowActionButton
  458. label={intl.formatMessage({ id: "git.action.showTree" })}
  459. onClick={handleOpenFileTree}
  460. showTooltip
  461. >
  462. <ListTree className="size-3.5" />
  463. </TaskRowActionButton>
  464. </span>
  465. ) : null;
  466. const taskActionGroupNode =
  467. fileTreeActionNode || archiveActionNode ? (
  468. <span data-task-row-actions="true" className="flex shrink-0 items-center gap-0.5">
  469. {fileTreeActionNode}
  470. {archiveActionNode}
  471. </span>
  472. ) : null;
  473. const pinActionButton = (
  474. <Button
  475. type="button"
  476. variant="ghost"
  477. size="icon-xs"
  478. disabled={workspaceActionsDisabled}
  479. onMouseDown={(event) => {
  480. event.preventDefault();
  481. event.stopPropagation();
  482. }}
  483. onClick={handleTogglePin}
  484. className="inline-flex size-4 min-w-0 rounded-sm p-0 text-foreground-subtle !bg-transparent hover:text-foreground"
  485. aria-label={intl.formatMessage({
  486. id: isPinned ? "taskList.unpin" : "taskList.pin",
  487. })}
  488. >
  489. <Pin className="size-4" />
  490. </Button>
  491. );
  492. // hover:none 只让右侧 task actions 常驻;如果也用它接管 leading 槽,
  493. // 触屏端的错误、未读和 loading 状态会被 Pin 永久替换。
  494. const shouldRenderPinAction =
  495. showPinAction && (showPinnedState || shouldSuppressWorkspaceTaskMetadata);
  496. return (
  497. <li
  498. ref={itemRef}
  499. data-testid={testId(TID_TASK_ITEM, task.taskId)}
  500. data-task-item-key={taskItemKey}
  501. data-mobile-active-task={isMobileActive ? "true" : undefined}
  502. data-archive-confirming-task-id={isArchiveConfirming ? task.taskId : undefined}
  503. onClick={handleSelect}
  504. onContextMenu={handleContextMenu}
  505. draggable={canDragToWorkbench}
  506. onDragStart={handleDragStart}
  507. onDragEnd={handleDragEnd}
  508. onMouseEnter={handleMouseEnter}
  509. onMouseLeave={handleMouseLeave}
  510. onFocusCapture={() => setFocusActionsVisible(true)}
  511. onBlurCapture={(event) => {
  512. if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
  513. setFocusActionsVisible(false);
  514. }
  515. }}
  516. tabIndex={0}
  517. onKeyDown={(event) => {
  518. if (event.target !== event.currentTarget) {
  519. return;
  520. }
  521. if (event.key === "Enter" || event.key === " ") {
  522. event.preventDefault();
  523. handleSelect();
  524. }
  525. }}
  526. className={cn(
  527. "group/task-item flex cursor-pointer gap-2 rounded-lg pl-2.5 pr-1 py-1 transition-[background-color,border-color,box-shadow]",
  528. // 默认行 32px 时前置槽整行居中;长出工作流运行行后行体是两行的纵向列,槽改为对齐首行。
  529. variant === "timeline"
  530. ? "items-start py-1.5"
  531. : hasWorkflowRunLines
  532. ? "items-start"
  533. : "items-center",
  534. isActive ? "bg-selected" : "hover:bg-surface-hover",
  535. )}
  536. >
  537. {/* 之前任务列表依赖 divide-y 画分隔线,深色侧栏里每个 item 上下都会出现明显黑线,
  538. 视觉上像被两条边框夹住。这里改成“列表留白 + item 自己带圆角态”,
  539. 让 hover/active 的层级由卡片背景承担,不再依赖分隔线。 */}
  540. <div
  541. className={cn(
  542. "relative flex size-4 shrink-0 items-center justify-center",
  543. // 行体是纵向列(标题行 + 运行行)时前置槽对齐首行而不是整行:默认 24px 首行居中 = 上留 4px。
  544. variant === "timeline" ? "mt-0.5" : hasWorkflowRunLines ? "mt-1" : undefined,
  545. )}
  546. >
  547. <span
  548. aria-hidden="true"
  549. className={cn(
  550. "flex size-4 items-center justify-center transition-opacity",
  551. shouldRenderPinAction && "hidden",
  552. isMobileActive && "invisible",
  553. )}
  554. >
  555. {leadingIndicator === "error" ? (
  556. <span data-error-indicator="true" className="h-1.5 w-1.5 rounded-full bg-destructive" />
  557. ) : leadingIndicator === "unread" ? (
  558. <span
  559. data-unread-indicator="true"
  560. className="h-1.5 w-1.5 rounded-full bg-sky-500 dark:bg-sky-400"
  561. />
  562. ) : leadingIndicator === "loading" ? (
  563. <LoaderIcon className="size-4 animate-spin text-foreground-subtle" />
  564. ) : showTimelineIdleIndicator ? (
  565. <span data-idle-indicator="true" className="h-1.5 w-1.5 rounded-full bg-border" />
  566. ) : null}
  567. </span>
  568. {shouldRenderPinAction ? (
  569. <ControlHintTooltip
  570. title={
  571. workspaceActionsDisabledReason ??
  572. intl.formatMessage({
  573. id: isPinned ? "taskList.unpin" : "taskList.pin",
  574. })
  575. }
  576. side="top"
  577. align="center"
  578. >
  579. {pinActionButton}
  580. </ControlHintTooltip>
  581. ) : null}
  582. </div>
  583. {variant === "timeline" ? (
  584. <div className="relative flex min-w-0 flex-1 flex-col gap-0.5">
  585. <div className="flex min-w-0 items-center gap-1.5">
  586. {isMobileActive && !shouldSuppressWorkspaceTaskMetadata ? (
  587. <ControlHintTooltip
  588. title={intl.formatMessage({ id: "taskList.mobileActive" })}
  589. side="right"
  590. align="center"
  591. triggerClassName="absolute -left-6 top-2 z-10 -translate-y-1/2"
  592. >
  593. <span
  594. data-mobile-active-task="true"
  595. className="inline-flex size-4 items-center justify-center rounded-sm text-success"
  596. aria-label={intl.formatMessage({
  597. id: "taskList.mobileActive",
  598. })}
  599. >
  600. <Smartphone className="size-3.5" />
  601. </span>
  602. </ControlHintTooltip>
  603. ) : null}
  604. <TaskTitleOverflowText
  605. className="text-ui-base text-foreground"
  606. title={taskTitleWithChanges}
  607. >
  608. {/* workspace/timeline task 标题之前使用 truncate,会在长标题末尾显示省略号;
  609. grouped task 已改为右侧渐隐。这里统一 task 列表标题溢出策略,避免同一侧栏里出现两种截断语义。 */}
  610. {taskTitle}
  611. </TaskTitleOverflowText>
  612. {task.pendingInteraction ? (
  613. <TaskInteractionBadge
  614. interaction={task.pendingInteraction}
  615. formatMessage={(id) => intl.formatMessage({ id })}
  616. onSnoozeCountdown={snoozeInteractionAutoResolution}
  617. />
  618. ) : taskAttentionDisplay ? (
  619. <Badge className="h-5 shrink-0 border-transparent bg-success/14 px-2 text-ui-base font-medium text-success dark:bg-success/18">
  620. {taskAttentionDisplay}
  621. </Badge>
  622. ) : null}
  623. </div>
  624. <div className="flex min-w-0 items-center justify-between gap-2 text-ui-base text-foreground-subtle h-6">
  625. <div className="flex min-w-0 items-center gap-1.5">
  626. <span className="truncate">{workspaceLabel}</span>
  627. </div>
  628. <div className="ml-auto flex shrink-0 items-center justify-end gap-1.5">
  629. {!hasPendingInteraction ? (
  630. <span
  631. data-task-row-metadata="true"
  632. className={cn(
  633. "flex items-center gap-1.5",
  634. isArchiveConfirming || shouldSuppressWorkspaceTaskMetadata
  635. ? "hidden"
  636. : undefined,
  637. )}
  638. >
  639. {changeSummaryNode}
  640. {changeSummaryNode ? (
  641. <span aria-hidden="true" className="shrink-0 text-foreground-subtlest">
  642. ·
  643. </span>
  644. ) : null}
  645. {isTaskCron ? (
  646. // 定时任务 icon 不能占用左侧状态槽;未读、运行中、置顶 hover 都会接管那里。
  647. // 放在时间前面,和 grouped task row 的元信息位置一致,状态变化时也不会丢。
  648. <Clock
  649. data-cron-task-icon="true"
  650. aria-label={intl.formatMessage({
  651. id: "taskList.cronTaskLabel",
  652. })}
  653. className="size-3.5 shrink-0"
  654. />
  655. ) : isTaskOffPeak ? (
  656. <Moon
  657. data-off-peak-task-icon="true"
  658. aria-label={intl.formatMessage({ id: "taskList.offPeakTaskLabel" })}
  659. className="size-3.5 shrink-0"
  660. />
  661. ) : null}
  662. <span className="mr-1">{taskTimeLabel}</span>
  663. </span>
  664. ) : null}
  665. {taskActionGroupNode}
  666. </div>
  667. </div>
  668. {workflowRunLinesNode}
  669. </div>
  670. ) : (
  671. <div className="flex min-w-0 flex-1 flex-col">
  672. <div className="flex min-w-0 items-center gap-2">
  673. <div className="relative min-w-0 flex h-6 flex-1 flex-wrap items-center gap-1.5">
  674. {isMobileActive && !shouldSuppressWorkspaceTaskMetadata ? (
  675. <ControlHintTooltip
  676. title={intl.formatMessage({ id: "taskList.mobileActive" })}
  677. side="right"
  678. align="center"
  679. triggerClassName="absolute -left-6 top-1/2 z-10 -translate-y-1/2"
  680. >
  681. <span
  682. data-mobile-active-task="true"
  683. className="inline-flex size-4 items-center justify-center rounded-sm text-success"
  684. aria-label={intl.formatMessage({
  685. id: "taskList.mobileActive",
  686. })}
  687. >
  688. {/* mobileViewState 已经能告诉桌面端手机正在看的 task,
  689. 但列表未消费这个状态,用户会误以为只有桌面端在操作。上一版把图标作为标题前的 flex 子项,
  690. 会把当前行标题往右挤,造成上下 task 标题不对齐;这里改成绝对定位到原有 leading 槽,
  691. 标题文本仍从既有位置开始;同时 hover 时隐藏手机标记,把置顶按钮还给用户。 */}
  692. <Smartphone className="size-3.5" />
  693. </span>
  694. </ControlHintTooltip>
  695. ) : null}
  696. <TaskTitleOverflowText
  697. className="text-ui-base text-foreground"
  698. title={taskTitleWithChanges}
  699. >
  700. {/* 默认 workspace task item 和 timeline item 共享标题溢出规则;
  701. 使用 mask 渐隐而不是省略号,和 grouped task row 保持一致。 */}
  702. {taskTitle}
  703. </TaskTitleOverflowText>
  704. {changeSummaryNode ? (
  705. <span
  706. className={cn(
  707. isArchiveConfirming || shouldSuppressWorkspaceTaskMetadata
  708. ? "hidden"
  709. : undefined,
  710. )}
  711. >
  712. {changeSummaryNode}
  713. </span>
  714. ) : null}
  715. {task.pendingInteraction ? (
  716. <TaskInteractionBadge
  717. interaction={task.pendingInteraction}
  718. formatMessage={(id) => intl.formatMessage({ id })}
  719. onSnoozeCountdown={snoozeInteractionAutoResolution}
  720. />
  721. ) : taskAttentionDisplay ? (
  722. <Badge className="h-5 shrink-0 border-transparent bg-success/14 px-2 text-ui-sm font-medium text-success dark:bg-success/18">
  723. {taskAttentionDisplay}
  724. </Badge>
  725. ) : null}
  726. </div>
  727. {!hasPendingInteraction ? (
  728. // 交互胶囊已经占用右侧状态位;继续显示相对时间会和“等待确认”并排挤压标题。
  729. <span
  730. data-task-row-metadata="true"
  731. className={cn(
  732. "mr-0.5 flex shrink-0 items-center gap-1 text-ui-sm text-foreground-subtle",
  733. isArchiveConfirming || shouldSuppressWorkspaceTaskMetadata ? "hidden" : undefined,
  734. )}
  735. >
  736. {isTaskCron ? (
  737. // 定时任务 icon 归属时间元信息,而不是左侧状态位;否则 unread/loading 会把 icon 顶掉。
  738. <Clock
  739. data-cron-task-icon="true"
  740. aria-label={intl.formatMessage({
  741. id: "taskList.cronTaskLabel",
  742. })}
  743. className="size-3.5 shrink-0"
  744. />
  745. ) : isTaskOffPeak ? (
  746. <Moon
  747. data-off-peak-task-icon="true"
  748. aria-label={intl.formatMessage({ id: "taskList.offPeakTaskLabel" })}
  749. className="size-3.5 shrink-0"
  750. />
  751. ) : null}
  752. {taskTimeLabel}
  753. </span>
  754. ) : null}
  755. {taskActionGroupNode}
  756. </div>
  757. {workflowRunLinesNode}
  758. </div>
  759. )}
  760. </li>
  761. );
  762. }, areTaskListItemPropsEqual);
  763. MemoTaskItem.displayName = "MemoTaskItem";
  764. export function TaskListItemContextMenuContent({
  765. workspacePath,
  766. remoteSessionId,
  767. task,
  768. isPinned,
  769. intl,
  770. onTogglePinTask,
  771. onStartRenameTask,
  772. onArchiveTask,
  773. onMarkTaskAsUnread,
  774. disableTaskActions = false,
  775. disabledReason,
  776. }: {
  777. workspacePath: string;
  778. remoteSessionId?: string;
  779. task: ZCodeTaskMeta;
  780. isPinned: boolean;
  781. intl: TaskListItemIntl;
  782. onTogglePinTask: (taskId: string, pinned: boolean) => void;
  783. onStartRenameTask: (taskId: string, currentTitle: string) => void;
  784. onArchiveTask: (taskId: string) => void;
  785. onMarkTaskAsUnread: (taskId: string) => void;
  786. disableTaskActions?: boolean;
  787. disabledReason?: string;
  788. }) {
  789. const workspaceActionsDisabled = useOptionalTabStore(
  790. (state) =>
  791. disableTaskActions || isWorkspaceReadOnly(state, task.workspacePath, task.workspaceIdentity),
  792. );
  793. const workspaceActionsDisabledReason = workspaceActionsDisabled
  794. ? (disabledReason ?? intl.formatMessage({ id: "workspaceSidebar.unavailableLocalDirectory" }))
  795. : undefined;
  796. // 收尾:「在分屏打开」仅桌面 shell(context 由 WorkspaceShellLayout 提供;
  797. // 手机远控/无 Provider 环境默认 false → 菜单项整体不渲染)。
  798. const splitPaneEntry = useV4SplitPaneEntry();
  799. const splitPaneEntryEnabled = splitPaneEntry.enabled;
  800. const splitPaneTarget = useMemo(
  801. () => ({
  802. workspacePath,
  803. ...(task.workspaceIdentity?.trim() ? { workspaceIdentity: task.workspaceIdentity } : {}),
  804. ...(remoteSessionId ? { remoteSessionId } : {}),
  805. sessionId: task.taskId,
  806. }),
  807. [remoteSessionId, task.taskId, task.workspaceIdentity, workspacePath],
  808. );
  809. // 当前 focused session、已有 group 与 pane 上限统一由 shell owner 裁决;row 不再直接写 layout store。
  810. const canOpenInSplitPane = splitPaneEntry.canOpenSession(splitPaneTarget);
  811. const openFeedbackSubmit = useFeedbackStore((state) => state.openSubmit);
  812. const {
  813. taskSessionFile,
  814. taskNativeSessionLogFile,
  815. fileManagerLabel,
  816. handleCopyText,
  817. handleOpenTaskPathInFileManager,
  818. } = useTaskListItemContextActions({
  819. workspacePath,
  820. remoteSessionId,
  821. workspaceIdentity: task.workspaceIdentity,
  822. taskId: task.taskId,
  823. provider: task.provider,
  824. intl,
  825. // row 级菜单已收敛为列表级单例,只有菜单真正打开时才挂载此组件。
  826. // 因此路径探测和 provider 配置探测可以直接随打开态运行,避免每个 idle row 订阅和计算。
  827. loadTaskPaths: true,
  828. });
  829. const taskTitle =
  830. task.title ||
  831. intl.formatMessage({
  832. id: task.forkedFromTaskId ? "taskList.forkedUntitled" : "taskList.untitled",
  833. });
  834. const handleOpenTaskFeedback = useCallback(async () => {
  835. // 任务右键菜单之前只能复制日志/路径,反馈时缺少任务上下文。
  836. // 这里复用反馈中心 draft,只预填脱敏后的任务线索,附件由用户主动选择。
  837. openFeedbackSubmit({
  838. title: intl
  839. .formatMessage(
  840. { id: "feedback.submit.template.section.taskFeedbackTitle" },
  841. { title: taskTitle },
  842. )
  843. .slice(0, 80),
  844. type: "bug",
  845. module: "Agent任务执行失败",
  846. severity: "P2-中",
  847. includeLogs: false,
  848. description: buildTaskFeedbackDescription({
  849. taskTitle,
  850. taskId: task.taskId,
  851. workspacePath,
  852. taskSessionPath: taskSessionFile.path,
  853. taskLogPath: taskNativeSessionLogFile.path,
  854. formatMessage: (id: string, values?: Record<string, string>) =>
  855. intl.formatMessage({ id }, values),
  856. }),
  857. screenshots: [],
  858. });
  859. toast(intl.formatMessage({ id: "taskList.feedbackOpened" }));
  860. }, [
  861. intl,
  862. openFeedbackSubmit,
  863. task.taskId,
  864. taskNativeSessionLogFile.path,
  865. taskSessionFile.path,
  866. taskTitle,
  867. workspacePath,
  868. ]);
  869. return (
  870. <TaskListItemContextMenu
  871. intl={intl}
  872. isPinned={isPinned}
  873. fileManagerLabel={fileManagerLabel}
  874. taskSessionFile={taskSessionFile}
  875. activeSessionId={task.taskId}
  876. taskNativeSessionLogFile={taskNativeSessionLogFile}
  877. disableTaskActions={workspaceActionsDisabled}
  878. disabledReason={workspaceActionsDisabledReason}
  879. onTogglePinTask={() => {
  880. onTogglePinTask(task.taskId, !isPinned);
  881. }}
  882. onStartRenameTask={() => {
  883. onStartRenameTask(task.taskId, task.title);
  884. }}
  885. onArchiveTask={() => {
  886. onArchiveTask(task.taskId);
  887. }}
  888. onMarkTaskAsUnread={() => {
  889. onMarkTaskAsUnread(task.taskId);
  890. }}
  891. onOpenInSplitPane={
  892. splitPaneEntryEnabled
  893. ? () => {
  894. // 旧入口直接写 paneLayout,绕过 active group 与 shell navigation,
  895. // draft split 后下一次普通点击会把 session 灌进 primary。统一交给 shell controller。
  896. splitPaneEntry.openSession(splitPaneTarget);
  897. }
  898. : undefined
  899. }
  900. openInSplitPaneDisabled={workspaceActionsDisabled || !canOpenInSplitPane}
  901. onOpenTaskFeedback={() => {
  902. void handleOpenTaskFeedback();
  903. }}
  904. onOpenTaskPathInFileManager={() => {
  905. void handleOpenTaskPathInFileManager();
  906. }}
  907. onCopyWorkspacePath={() => {
  908. void handleCopyText(intl.formatMessage({ id: "appHeader.copyPath" }), workspacePath);
  909. }}
  910. onCopyTaskPath={() => {
  911. void handleCopyText(
  912. intl.formatMessage({ id: "appHeader.copyTaskPath" }),
  913. taskSessionFile.path,
  914. );
  915. }}
  916. onCopyTaskLogPath={() => {
  917. void handleCopyText(
  918. intl.formatMessage({ id: "appHeader.copyLogPath" }),
  919. taskNativeSessionLogFile.path,
  920. );
  921. }}
  922. onCopySessionId={() => {
  923. void handleCopyText(intl.formatMessage({ id: "appHeader.copySessionId" }), task.taskId);
  924. }}
  925. onViewModelTrajectory={() => {
  926. // 通过单例 store 把“打开轨迹”请求交给所属 workspace 的侧边栏控制器(useAppPanels)。
  927. useModelTrajectoryStore.getState().requestOpen({
  928. taskId: task.taskId,
  929. workspaceKey: task.workspaceIdentity?.trim() || workspacePath,
  930. title: taskTitle,
  931. });
  932. }}
  933. />
  934. );
  935. }