AssistantPreviewCards.tsx 12 KB

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