AssistantPreviewCards.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import { FileTextIcon, GlobeIcon } from "lucide-react";
  2. import { useEffect, useMemo, useRef, useState, type CSSProperties } from "react";
  3. import type { MessageFileLinkTarget } from "@/components/ai-elements/message.js";
  4. import { useWorkspaceServices } from "@/hooks/useWorkspaceServices.js";
  5. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  6. import {
  7. type AssistantPreviewCard,
  8. type AssistantPreviewCardFileStatService,
  9. type AssistantPreviewCardsAutoOpenRequest,
  10. getAssistantPreviewCardFilePath,
  11. shouldOpenAssistantHtmlInBrowser,
  12. } from "@/lib/assistantPreviewCards.js";
  13. import {
  14. getAssistantPreviewCardsValidationSignature,
  15. resolveAssistantPreviewCardsWithoutFileStat,
  16. resolveValidatedAssistantPreviewCards,
  17. } from "@/lib/assistantPreviewCardValidation.js";
  18. import type { CodeViewerSource } from "@/lib/codeViewer.js";
  19. import { FileDisplayIcon, resolveFileDisplayDescriptor } from "@/lib/fileDisplay.js";
  20. import { OpenSplitButton } from "@/OpenSplitButton.js";
  21. interface AssistantPreviewCardValidationResult {
  22. visibleCards: AssistantPreviewCard[];
  23. settled: boolean;
  24. }
  25. function buildAssistantPreviewCardFileSource(
  26. card: Extract<AssistantPreviewCard, { type: "markdown" | "file" }>,
  27. scope: {
  28. workspacePath?: string;
  29. workspaceIdentity?: string;
  30. workspaceRemoteSessionId?: string;
  31. },
  32. ): CodeViewerSource {
  33. return {
  34. type: "file",
  35. title: card.title,
  36. path: card.path,
  37. ...(scope.workspacePath ? { workspacePath: scope.workspacePath } : {}),
  38. ...(scope.workspaceIdentity ? { workspaceIdentity: scope.workspaceIdentity } : {}),
  39. ...(scope.workspaceRemoteSessionId
  40. ? { workspaceRemoteSessionId: scope.workspaceRemoteSessionId }
  41. : {}),
  42. };
  43. }
  44. function buildAssistantPreviewPptxAutoOpenRequest(
  45. visibleCards: readonly AssistantPreviewCard[],
  46. baseKey: string,
  47. scope: {
  48. workspacePath?: string;
  49. workspaceIdentity?: string;
  50. workspaceRemoteSessionId?: string;
  51. },
  52. ): AssistantPreviewCardsAutoOpenRequest | null {
  53. const pptxCards = visibleCards.filter(
  54. (card): card is Extract<AssistantPreviewCard, { type: "file" }> =>
  55. card.type === "file" && card.kind === "pptx",
  56. );
  57. if (pptxCards.length === 0) return null;
  58. return {
  59. // stat 结果对应的最终卡片签名必须进入一次性 key;同一 turn 的候选若晚到,
  60. // 不会把旧的校验投影误当成已经消费的新结果。
  61. key: JSON.stringify([baseKey, getAssistantPreviewCardsValidationSignature(pptxCards)]),
  62. sources: pptxCards.map((card) => buildAssistantPreviewCardFileSource(card, scope)),
  63. };
  64. }
  65. interface AssistantPreviewCardsProps {
  66. cards: AssistantPreviewCard[];
  67. workspacePath?: string;
  68. workspaceIdentity?: string;
  69. workspaceRemoteSessionId?: string;
  70. onOpenBrowserUrl?: (url: string) => void;
  71. onOpenFileLink?: (target: MessageFileLinkTarget) => void;
  72. onOpenCodeViewer?: (source: CodeViewerSource) => void;
  73. /** Desktop 完成态生成产物:批量打开本轮已通过校验的 PPTX。 */
  74. autoOpenPptxKey?: string;
  75. onAutoOpenPptx?: (request: AssistantPreviewCardsAutoOpenRequest) => void;
  76. }
  77. function shouldRenderAssistantPreviewCardAsFile(
  78. card: AssistantPreviewCard,
  79. scope: {
  80. workspaceIdentity?: string;
  81. workspaceRemoteSessionId?: string;
  82. },
  83. ): boolean {
  84. const filePath = getAssistantPreviewCardFilePath(card);
  85. return (
  86. card.type !== "website" ||
  87. (card.url.startsWith("file://") &&
  88. filePath !== null &&
  89. !shouldOpenAssistantHtmlInBrowser({ path: filePath, ...scope }))
  90. );
  91. }
  92. function useAssistantPreviewCardValidation(
  93. cards: AssistantPreviewCard[],
  94. scope: {
  95. workspacePath?: string;
  96. workspaceIdentity?: string;
  97. workspaceRemoteSessionId?: string;
  98. } = {},
  99. ): AssistantPreviewCardValidationResult {
  100. const { fileService } = useWorkspaceServices(
  101. scope.workspacePath,
  102. scope.workspaceRemoteSessionId,
  103. scope.workspaceIdentity,
  104. );
  105. const cardsSignature = useMemo(() => getAssistantPreviewCardsValidationSignature(cards), [cards]);
  106. const validationCardsRef = useRef({ cards, signature: cardsSignature });
  107. // timeline 重建时会传入内容相同但引用不同的 cards 数组,effect 若依赖数组引用会重复发起 RPC。
  108. // 只在语义签名变化时替换校验快照;workspace fileService 变化仍会使用同一快照重新校验。
  109. if (validationCardsRef.current.signature !== cardsSignature) {
  110. validationCardsRef.current = { cards, signature: cardsSignature };
  111. }
  112. const validationCards = validationCardsRef.current.cards;
  113. const statFreeVisibleCards = useMemo(
  114. () => resolveAssistantPreviewCardsWithoutFileStat(validationCards),
  115. [validationCards],
  116. );
  117. const [validationResult, setValidationResult] = useState<{
  118. fileService: AssistantPreviewCardFileStatService | null;
  119. signature: string;
  120. visibleCards: AssistantPreviewCard[];
  121. }>(() => ({
  122. fileService: null,
  123. signature: "",
  124. visibleCards: [],
  125. }));
  126. useEffect(() => {
  127. if (statFreeVisibleCards) {
  128. return;
  129. }
  130. let disposed = false;
  131. // 历史消息切换时,上一条消息的已通过 stat 结果会在 effect 清理前短暂复用。
  132. // 这里按当前候选签名批量二次校验,全部算完后一次发布,避免文件卡先闪一批再被替换。
  133. void resolveValidatedAssistantPreviewCards(validationCards, fileService).then(
  134. (visibleCards) => {
  135. if (disposed) return;
  136. setValidationResult({
  137. fileService,
  138. signature: cardsSignature,
  139. visibleCards,
  140. });
  141. },
  142. () => {
  143. if (disposed) return;
  144. setValidationResult({
  145. fileService,
  146. signature: cardsSignature,
  147. visibleCards: [],
  148. });
  149. },
  150. );
  151. return () => {
  152. disposed = true;
  153. };
  154. }, [cardsSignature, fileService, statFreeVisibleCards, validationCards]);
  155. if (statFreeVisibleCards) {
  156. return {
  157. visibleCards: statFreeVisibleCards,
  158. settled: true,
  159. };
  160. }
  161. const hasCurrentValidation =
  162. validationResult.fileService === fileService && validationResult.signature === cardsSignature;
  163. return {
  164. visibleCards: hasCurrentValidation ? validationResult.visibleCards : [],
  165. settled: hasCurrentValidation,
  166. };
  167. }
  168. export function AssistantPreviewCards({
  169. cards,
  170. workspacePath,
  171. workspaceIdentity,
  172. workspaceRemoteSessionId,
  173. onOpenBrowserUrl,
  174. onOpenFileLink,
  175. onOpenCodeViewer,
  176. autoOpenPptxKey,
  177. onAutoOpenPptx,
  178. }: AssistantPreviewCardsProps) {
  179. const { intl } = useZCodeIntl();
  180. const { visibleCards, settled } = useAssistantPreviewCardValidation(cards, {
  181. workspacePath,
  182. workspaceIdentity,
  183. workspaceRemoteSessionId,
  184. });
  185. useEffect(() => {
  186. if (!settled || !autoOpenPptxKey || !onAutoOpenPptx) return;
  187. const request = buildAssistantPreviewPptxAutoOpenRequest(visibleCards, autoOpenPptxKey, {
  188. workspacePath,
  189. workspaceIdentity,
  190. workspaceRemoteSessionId,
  191. });
  192. if (!request) return;
  193. // 自动打开只能消费最终可见卡片;这样与 15 个候选、10 张上限和 Host stat
  194. // 完全同源,不会打开卡片中并不存在的文件。
  195. onAutoOpenPptx(request);
  196. }, [
  197. autoOpenPptxKey,
  198. onAutoOpenPptx,
  199. settled,
  200. visibleCards,
  201. workspaceIdentity,
  202. workspacePath,
  203. workspaceRemoteSessionId,
  204. ]);
  205. if (!settled || visibleCards.length === 0) {
  206. return null;
  207. }
  208. return (
  209. <div className="flex w-full flex-col gap-3">
  210. {visibleCards.map((card, index) => (
  211. <AssistantPreviewCardRow
  212. key={card.id}
  213. card={card}
  214. animationDelayMs={Math.min(index * 36, 240)}
  215. subtitle={intl.formatMessage({ id: card.subtitleId })}
  216. workspacePath={workspacePath}
  217. workspaceIdentity={workspaceIdentity}
  218. workspaceRemoteSessionId={workspaceRemoteSessionId}
  219. onOpenBrowserUrl={onOpenBrowserUrl}
  220. onOpenFileLink={onOpenFileLink}
  221. onOpenCodeViewer={onOpenCodeViewer}
  222. />
  223. ))}
  224. </div>
  225. );
  226. }
  227. function AssistantPreviewCardRow({
  228. card,
  229. animationDelayMs,
  230. subtitle,
  231. workspacePath,
  232. workspaceIdentity,
  233. workspaceRemoteSessionId,
  234. onOpenBrowserUrl,
  235. onOpenFileLink,
  236. onOpenCodeViewer,
  237. }: {
  238. card: AssistantPreviewCard;
  239. animationDelayMs: number;
  240. subtitle: string;
  241. workspacePath?: string;
  242. workspaceIdentity?: string;
  243. workspaceRemoteSessionId?: string;
  244. onOpenBrowserUrl?: (url: string) => void;
  245. onOpenFileLink?: (target: MessageFileLinkTarget) => void;
  246. onOpenCodeViewer?: (source: CodeViewerSource) => void;
  247. }) {
  248. const filePath = getAssistantPreviewCardFilePath(card);
  249. const renderAsFile = shouldRenderAssistantPreviewCardAsFile(card, {
  250. workspaceIdentity,
  251. workspaceRemoteSessionId,
  252. });
  253. const descriptor = filePath ? resolveFileDisplayDescriptor(filePath) : null;
  254. const fileSource =
  255. renderAsFile && filePath
  256. ? {
  257. type: "file" as const,
  258. title: card.title,
  259. path: filePath,
  260. ...(workspacePath ? { workspacePath } : {}),
  261. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  262. ...(workspaceRemoteSessionId ? { workspaceRemoteSessionId } : {}),
  263. }
  264. : null;
  265. return (
  266. <div
  267. className="flex w-full items-center gap-3 rounded-xl border border-card-border bg-card p-3 pr-4 text-foreground"
  268. data-zcode-stream-animate="true"
  269. style={
  270. {
  271. "--zcode-stream-animation-delay": `${animationDelayMs}ms`,
  272. } as CSSProperties
  273. }
  274. >
  275. <div className="flex size-11 shrink-0 items-center justify-center rounded-md bg-background text-foreground-subtle">
  276. {!renderAsFile && card.type === "website" ? (
  277. <GlobeIcon className="size-6" />
  278. ) : descriptor ? (
  279. <FileDisplayIcon src={descriptor.fileIconSrc} size={24} />
  280. ) : (
  281. <FileTextIcon className="size-6" />
  282. )}
  283. </div>
  284. <div className="min-w-0 flex flex-1 flex-col gap-1">
  285. <div className="truncate text-ui-base font-medium leading-5">{card.title}</div>
  286. <div className="truncate text-ui-base leading-5 text-foreground-subtlest">{subtitle}</div>
  287. </div>
  288. <OpenSplitButton
  289. target={
  290. !renderAsFile && card.type === "website"
  291. ? {
  292. type: "website",
  293. url: card.url,
  294. // website 卡有两个来源——html 引用卡(file://)与 localhost
  295. // 预览卡(http(s) 活服务)。localPath 直开只对前者生效;localhost 卡
  296. // 必须继续把 URL 交给浏览器,否则丢路由/动态内容。
  297. localPath: card.url.startsWith("file:") ? card.filePath : undefined,
  298. }
  299. : {
  300. type: "file",
  301. path: filePath!,
  302. title: card.title,
  303. label: card.title,
  304. // Preview Card 以前没有 CodeViewer scope,远程 Linux path
  305. // 会被 OpenSplitButton 当成本地路径交给宿主编辑器。
  306. previewSource:
  307. card.type === "website"
  308. ? fileSource!
  309. : buildAssistantPreviewCardFileSource(card, {
  310. workspacePath,
  311. workspaceIdentity,
  312. workspaceRemoteSessionId,
  313. }),
  314. }
  315. }
  316. onOpenBrowserUrl={onOpenBrowserUrl}
  317. onOpenFileLink={onOpenFileLink}
  318. onOpenCodeViewer={onOpenCodeViewer}
  319. />
  320. </div>
  321. );
  322. }