ConversationQueuePanel.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import { BotChannelMessageContent } from "@/v4/ChannelMentionContent.js";
  2. import { parsePromptConversationSelections } from "@/lib/conversationSelectionReference.js";
  3. import { ConversationSelectionReferenceChip } from "@/v4/composer/ConversationSelectionReferenceChip.js";
  4. import { BotGroupSourceLabel } from "@/v4/BotGroupSourceLabel.js";
  5. import {
  6. closestCenter,
  7. DndContext,
  8. PointerSensor,
  9. useSensor,
  10. useSensors,
  11. type DragEndEvent,
  12. type Modifier,
  13. } from "@dnd-kit/core";
  14. import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
  15. import { CSS } from "@dnd-kit/utilities";
  16. import { memo, useCallback, useMemo, useState, type CSSProperties } from "react";
  17. import {
  18. TID_V4_QUEUE,
  19. TID_V4_QUEUE_ITEM,
  20. TID_V4_QUEUE_ITEM_DELETE,
  21. TID_V4_QUEUE_ITEM_EDIT,
  22. TID_V4_QUEUE_ITEM_SEND_NOW,
  23. TID_V4_QUEUE_PAUSED_BANNER,
  24. TID_V4_QUEUE_RESUME,
  25. testId,
  26. } from "@zcode/shared";
  27. import type { QueueState } from "@zcode/shared/zcode-protocol-v4";
  28. import { ArrowUpFromLine, GripVertical, PencilIcon, Trash2Icon } from "lucide-react";
  29. import { ControlHintTooltip } from "@/ControlHintTooltip.js";
  30. import { Button } from "@/components/ui/button.js";
  31. import { cn } from "@/components/lib/utils.js";
  32. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  33. import { runUserAction, runUserActionAsync } from "@/lib/userActionTelemetry.js";
  34. export interface ConversationQueuePanelProps {
  35. queue: QueueState;
  36. /** 删除队列项(deleteQueueItem command)。 */
  37. onDeleteItem?: (queueItemId: string) => void;
  38. /** 撤回队列项到发起端 composer;权威删除成功后才恢复草稿。 */
  39. onEditItem?: (queueItemId: string) => Promise<void> | void;
  40. /** 正在等待 delete ACK / composer restore 的目标项;仅锁该 row。 */
  41. pendingEditQueueItemId?: string | null;
  42. /** 立即发送队列项(sendQueuedNow command,stop 当前 + 消费该项)。 */
  43. onSendNow?: (queueItemId: string) => void;
  44. /** 拖拽排序项(reorderQueueItem,移动到锚点前;null=队尾)。 */
  45. onMoveItem?: (queueItemId: string, beforeQueueItemId: string | null) => void;
  46. /** 暂停队列恢复:CLI setAutoDrain(true),idle 立即消费、busy 仅武装。 */
  47. onResume?: () => Promise<void> | void;
  48. }
  49. type QueueItem = QueueState["items"][number];
  50. export interface V4QueueReorderAnchor {
  51. beforeQueueItemId: string | null;
  52. queueItemId: string;
  53. }
  54. export function resolveV4QueueReorderAnchor(
  55. items: readonly QueueItem[],
  56. activeQueueItemId: string,
  57. overQueueItemId: string,
  58. ): V4QueueReorderAnchor | null {
  59. if (activeQueueItemId === overQueueItemId) {
  60. return null;
  61. }
  62. const fromIndex = items.findIndex((item) => item.queueItemId === activeQueueItemId);
  63. const overIndex = items.findIndex((item) => item.queueItemId === overQueueItemId);
  64. if (fromIndex < 0 || overIndex < 0) {
  65. return null;
  66. }
  67. if (fromIndex < overIndex) {
  68. const itemsAfterRemoval = items.filter((item) => item.queueItemId !== activeQueueItemId);
  69. const overIndexAfterRemoval = itemsAfterRemoval.findIndex(
  70. (item) => item.queueItemId === overQueueItemId,
  71. );
  72. const nextItem = itemsAfterRemoval[overIndexAfterRemoval + 1];
  73. return {
  74. beforeQueueItemId: nextItem?.queueItemId ?? null,
  75. queueItemId: activeQueueItemId,
  76. };
  77. }
  78. return {
  79. beforeQueueItemId: overQueueItemId,
  80. queueItemId: activeQueueItemId,
  81. };
  82. }
  83. const restrictQueueDragToPanel: Modifier = ({
  84. transform,
  85. draggingNodeRect,
  86. activeNodeRect,
  87. containerNodeRect,
  88. windowRect,
  89. }) => {
  90. const nodeRect = draggingNodeRect ?? activeNodeRect;
  91. const boundaryRect = containerNodeRect ?? windowRect;
  92. if (!nodeRect || !boundaryRect) {
  93. return {
  94. ...transform,
  95. x: 0,
  96. };
  97. }
  98. const minY = boundaryRect.top - nodeRect.top;
  99. const maxY = boundaryRect.bottom - nodeRect.bottom;
  100. return {
  101. ...transform,
  102. x: 0,
  103. y: Math.min(Math.max(transform.y, minY), maxY),
  104. };
  105. };
  106. interface QueueRowProps {
  107. item: QueueItem;
  108. index: number;
  109. intl: ReturnType<typeof useZCodeIntl>["intl"];
  110. sortable: boolean;
  111. onDeleteItem?: (queueItemId: string) => void;
  112. onEditItem?: (queueItemId: string) => Promise<void> | void;
  113. editPending: boolean;
  114. onSendNow?: (queueItemId: string) => void;
  115. }
  116. const QueueRow = memo(function QueueRow({
  117. item,
  118. index,
  119. intl,
  120. sortable,
  121. onDeleteItem,
  122. onEditItem,
  123. onSendNow,
  124. editPending,
  125. }: QueueRowProps) {
  126. const dispatchLocked = item.dispatch.state !== "queued";
  127. const rowLocked = dispatchLocked || editPending;
  128. const isCompact = item.kind === "compact";
  129. const parsedInput = {
  130. ...parsePromptConversationSelections(item.text),
  131. ...(item.conversationQuotes ? { references: item.conversationQuotes } : {}),
  132. };
  133. const attachmentNames = item.attachments.map((attachment) =>
  134. attachment.sourceKind === "topic-history"
  135. ? intl.formatMessage(
  136. { id: "chat.attachments.topicHistory" },
  137. { count: attachment.messageCount ?? 0 },
  138. )
  139. : attachment.fileName,
  140. );
  141. const {
  142. attributes,
  143. isDragging,
  144. listeners,
  145. setActivatorNodeRef,
  146. setNodeRef,
  147. transform,
  148. transition,
  149. } = useSortable({
  150. disabled: !sortable || rowLocked,
  151. id: item.queueItemId,
  152. });
  153. const style = useMemo<CSSProperties>(
  154. () => ({
  155. transform: CSS.Transform.toString(
  156. transform
  157. ? {
  158. ...transform,
  159. // dnd-kit 排序时会按 over 节点尺寸附带 scale;
  160. // 队列行是固定触控目标,缩放会让拖拽中的按钮和文本短暂变形。
  161. scaleX: 1,
  162. scaleY: 1,
  163. }
  164. : null,
  165. ),
  166. transition,
  167. zIndex: isDragging ? 10 : undefined,
  168. }),
  169. [isDragging, transition, transform],
  170. );
  171. return (
  172. <li
  173. ref={setNodeRef}
  174. data-testid={testId(TID_V4_QUEUE_ITEM, item.queueItemId)}
  175. data-queue-item-id={item.queueItemId}
  176. data-index={index}
  177. data-kind={item.kind}
  178. data-dispatch-state={item.dispatch.state}
  179. data-edit-pending={editPending ? "true" : "false"}
  180. className={cn(
  181. "relative flex items-center gap-2 rounded-xl px-1.5 py-1 pr-1 transition-colors hover:bg-hover/30",
  182. isDragging ? "bg-hover/40 shadow-sm" : null,
  183. editPending ? "opacity-60" : null,
  184. )}
  185. style={style}
  186. >
  187. <ControlHintTooltip title={intl.formatMessage({ id: "chat.queue.drag" })}>
  188. <Button
  189. ref={setActivatorNodeRef}
  190. type="button"
  191. variant="ghost"
  192. size="icon-md"
  193. data-v4-queue-drag-handle="true"
  194. data-queue-item-id={item.queueItemId}
  195. aria-label={intl.formatMessage({ id: "chat.queue.drag" })}
  196. className="shrink-0 cursor-grab touch-none text-foreground-subtlest active:cursor-grabbing"
  197. disabled={rowLocked}
  198. {...attributes}
  199. {...listeners}
  200. >
  201. <GripVertical className="size-4" />
  202. </Button>
  203. </ControlHintTooltip>
  204. <span
  205. className={cn(
  206. "flex min-w-0 flex-1 items-center gap-2 truncate text-ui-base text-foreground",
  207. isCompact ? "font-mono" : null,
  208. )}
  209. title={parsedInput.visibleContent}
  210. >
  211. <span className="flex min-w-0 flex-col">
  212. <BotGroupSourceLabel source={item.botGroupSource} />
  213. <span className="truncate">
  214. <BotChannelMessageContent
  215. source={isCompact ? undefined : item.botGroupSource}
  216. text={isCompact ? "/compact" : parsedInput.visibleContent}
  217. />
  218. </span>
  219. {parsedInput.references.length ? (
  220. <ConversationSelectionReferenceChip references={parsedInput.references} />
  221. ) : null}
  222. {item.attachments.length > 0 ? (
  223. <span
  224. className="truncate text-ui-sm text-foreground-subtle"
  225. title={attachmentNames.join(", ")}
  226. >
  227. {attachmentNames.join(", ")}
  228. </span>
  229. ) : null}
  230. </span>
  231. </span>
  232. {onSendNow ? (
  233. <Button
  234. type="button"
  235. variant="secondary"
  236. size="default"
  237. data-icon="inline-start"
  238. data-testid={testId(TID_V4_QUEUE_ITEM_SEND_NOW, item.queueItemId)}
  239. data-queue-item-id={item.queueItemId}
  240. disabled={rowLocked}
  241. onClick={() =>
  242. runUserAction({
  243. input: {
  244. featureId: "conversation.queue.item",
  245. action: "send_now",
  246. trigger: "button",
  247. },
  248. operation: () => onSendNow(item.queueItemId),
  249. completed: { resultSource: "optimistic_projection" },
  250. failureStage: "queue_send_now",
  251. })
  252. }
  253. >
  254. <ArrowUpFromLine className="size-3.5" />
  255. {intl.formatMessage({ id: isCompact ? "chat.queue.runNow" : "chat.queue.sendNow" })}
  256. </Button>
  257. ) : null}
  258. {onEditItem && !isCompact ? (
  259. <ControlHintTooltip title={intl.formatMessage({ id: "chat.queue.edit" })}>
  260. <Button
  261. type="button"
  262. variant="ghost"
  263. size="icon-md"
  264. data-testid={testId(TID_V4_QUEUE_ITEM_EDIT, item.queueItemId)}
  265. data-queue-item-id={item.queueItemId}
  266. aria-label={intl.formatMessage({ id: "chat.queue.edit" })}
  267. disabled={rowLocked}
  268. onClick={() => void onEditItem(item.queueItemId)}
  269. >
  270. <PencilIcon className="size-4" />
  271. </Button>
  272. </ControlHintTooltip>
  273. ) : null}
  274. {onDeleteItem ? (
  275. <ControlHintTooltip title={intl.formatMessage({ id: "chat.queue.remove" })}>
  276. <Button
  277. type="button"
  278. variant="ghost"
  279. size="icon-md"
  280. data-testid={testId(TID_V4_QUEUE_ITEM_DELETE, item.queueItemId)}
  281. data-queue-item-id={item.queueItemId}
  282. aria-label={intl.formatMessage({ id: "chat.queue.remove" })}
  283. disabled={rowLocked}
  284. onClick={() => onDeleteItem(item.queueItemId)}
  285. >
  286. <Trash2Icon className="size-4" />
  287. </Button>
  288. </ControlHintTooltip>
  289. ) : null}
  290. </li>
  291. );
  292. });
  293. /**
  294. * 竖切 queue 面板:渲染 projection.queue.items + 单项删除入口。
  295. * queue 在运行中的 turn 期间存在(sendText 排队),是 CLI 投影权威态(非 renderer-local)。
  296. */
  297. function ConversationQueuePanelImpl({
  298. queue,
  299. onDeleteItem,
  300. onEditItem,
  301. pendingEditQueueItemId = null,
  302. onSendNow,
  303. onMoveItem,
  304. onResume,
  305. }: ConversationQueuePanelProps) {
  306. const { intl } = useZCodeIntl();
  307. const [resumePending, setResumePending] = useState(false);
  308. const sensors = useSensors(
  309. useSensor(PointerSensor, {
  310. activationConstraint: { distance: 6 },
  311. }),
  312. );
  313. const itemIds = useMemo(() => queue.items.map((item) => item.queueItemId), [queue.items]);
  314. const handleDragEnd = useCallback(
  315. (event: DragEndEvent) => {
  316. const overId = event.over?.id;
  317. if (!overId) return;
  318. const anchor = resolveV4QueueReorderAnchor(
  319. queue.items,
  320. String(event.active.id),
  321. String(overId),
  322. );
  323. if (!anchor) return;
  324. onMoveItem?.(anchor.queueItemId, anchor.beforeQueueItemId);
  325. },
  326. [onMoveItem, queue.items],
  327. );
  328. const handleResume = useCallback(async () => {
  329. if (!onResume || resumePending) return;
  330. setResumePending(true);
  331. try {
  332. await runUserActionAsync({
  333. input: { featureId: "conversation.queue.policy", action: "resume", trigger: "button" },
  334. operation: () => Promise.resolve(onResume()),
  335. completed: { resultSource: "authority_ack" },
  336. failureStage: "queue_resume",
  337. });
  338. } finally {
  339. setResumePending(false);
  340. }
  341. }, [onResume, resumePending]);
  342. if (queue.items.length === 0) return null;
  343. // 补回 v4 视觉迁移时漏掉的旧队列面板 blur 层,让列表保持贴合 composer 的磨砂背景。
  344. return (
  345. <div
  346. data-testid={TID_V4_QUEUE}
  347. data-queue-count={queue.items.length}
  348. data-queue-auto-drain={queue.autoDrain ? "true" : "false"}
  349. className={cn(
  350. "relative z-0 w-full overflow-hidden rounded-t-2xl border border-border bg-surface p-1 backdrop-blur-md",
  351. "-mb-7 pb-7",
  352. )}
  353. >
  354. {!queue.autoDrain ? (
  355. <div
  356. data-testid={TID_V4_QUEUE_PAUSED_BANNER}
  357. className="mb-1 flex min-h-10 items-center gap-3 rounded-xl border border-border/70 bg-surface-raised px-3 py-2 text-ui-base text-foreground"
  358. >
  359. <span className="min-w-0 flex-1">
  360. {intl.formatMessage({
  361. id:
  362. queue.pauseReason === "stopped"
  363. ? "chat.queue.paused.stopped"
  364. : queue.pauseReason === "error"
  365. ? "chat.queue.paused.error"
  366. : "chat.queue.paused.generic",
  367. })}
  368. </span>
  369. {onResume ? (
  370. <Button
  371. type="button"
  372. variant="ghost"
  373. size="sm"
  374. data-testid={TID_V4_QUEUE_RESUME}
  375. aria-label={intl.formatMessage({ id: "chat.queue.resume.description" })}
  376. disabled={resumePending}
  377. className="shrink-0 text-foreground-subtle hover:text-foreground"
  378. onClick={() => void handleResume()}
  379. >
  380. {intl.formatMessage({ id: "chat.queue.resume" })}
  381. </Button>
  382. ) : null}
  383. </div>
  384. ) : null}
  385. <DndContext
  386. sensors={sensors}
  387. collisionDetection={closestCenter}
  388. modifiers={[restrictQueueDragToPanel]}
  389. onDragEnd={handleDragEnd}
  390. >
  391. <SortableContext items={itemIds} strategy={verticalListSortingStrategy}>
  392. <ul className="space-y-0.5">
  393. {queue.items.map((item, index) => (
  394. <QueueRow
  395. key={item.queueItemId}
  396. item={item}
  397. index={index}
  398. intl={intl}
  399. sortable={Boolean(onMoveItem)}
  400. onDeleteItem={onDeleteItem}
  401. onEditItem={onEditItem}
  402. onSendNow={onSendNow}
  403. editPending={pendingEditQueueItemId === item.queueItemId}
  404. />
  405. ))}
  406. </ul>
  407. </SortableContext>
  408. </DndContext>
  409. </div>
  410. );
  411. }
  412. export const ConversationQueuePanel = memo(ConversationQueuePanelImpl);