assistantPreviewCards.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import {
  2. buildConversationPreviewArtifactCandidatesFromReferences,
  3. CONVERSATION_PREVIEW_CARD_CANDIDATE_LIMIT,
  4. CONVERSATION_PREVIEW_CARD_VISIBLE_LIMIT,
  5. } from "@zcode/shared";
  6. import {
  7. cleanAssistantFilePathCandidate,
  8. getAssistantPreviewFileTypeDefinition,
  9. isAssistantPreviewHtmlPath,
  10. parseAssistantFileUrlPath,
  11. resolveAssistantRawFilePath,
  12. type AssistantFileReference,
  13. type AssistantFilePathResolveOptions,
  14. type AssistantPreviewFileKind,
  15. type AssistantPreviewFileSubtitleId,
  16. } from "@/lib/assistantFileReferences.js";
  17. import { decodeFilePathUriEscapes, getPathLeaf, toFileUrl } from "@/lib/path.js";
  18. import type { CodeViewerSource } from "@/lib/codeViewer.js";
  19. export {
  20. extractAssistantFileReferences,
  21. hasAssistantPreviewFileChangeCandidates,
  22. isAssistantPreviewHtmlPath,
  23. } from "@/lib/assistantFileReferences.js";
  24. export type {
  25. AssistantFileReference,
  26. AssistantPreviewFileKind,
  27. } from "@/lib/assistantFileReferences.js";
  28. export const ASSISTANT_PREVIEW_CARD_CANDIDATE_LIMIT = CONVERSATION_PREVIEW_CARD_CANDIDATE_LIMIT;
  29. export const ASSISTANT_PREVIEW_CARD_VISIBLE_LIMIT = CONVERSATION_PREVIEW_CARD_VISIBLE_LIMIT;
  30. export interface AssistantPreviewCardsAutoOpenRequest {
  31. key: string;
  32. sources: CodeViewerSource[];
  33. }
  34. export type AssistantPreviewCard =
  35. | {
  36. id: string;
  37. type: "website";
  38. title: string;
  39. subtitleId: "chat.previewCards.website" | "chat.previewCards.htmlWebsite";
  40. url: string;
  41. filePath?: string;
  42. }
  43. | {
  44. id: string;
  45. type: "markdown";
  46. kind: "markdown";
  47. title: string;
  48. subtitleId: "chat.previewCards.markdown";
  49. path: string;
  50. }
  51. | {
  52. id: string;
  53. type: "file";
  54. kind: Exclude<AssistantPreviewFileKind, "markdown" | "html">;
  55. title: string;
  56. subtitleId: Exclude<
  57. AssistantPreviewFileSubtitleId,
  58. "chat.previewCards.markdown" | "chat.previewCards.htmlWebsite"
  59. >;
  60. path: string;
  61. };
  62. export interface AssistantPreviewCardFileStatService {
  63. checkFilesExist(params: { paths: string[] }): Promise<Array<{ path: string; exists: boolean }>>;
  64. }
  65. const LOCALHOST_URL_RE =
  66. /\bhttps?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?(?:[/?#][^\s<>()\]`"'*,。!?;:、]*)?/gi;
  67. const STRICT_LOCALHOST_URL_RE =
  68. /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d{1,5})?(?:[/?#][^\s<>()\]`"'*,。!?;:、]*)?$/i;
  69. const STRICT_FILE_HTML_URL_RE =
  70. /^file:\/\/(?:localhost\/|\/|[^/\s<>()\]`"'*,。!?;:、]+\/)[^\s<>()\]`"'*,。!?;:、]+\.html?(?:[?#][^\s<>()\]`"'*,。!?;:、]*)?$/i;
  71. const MARKDOWN_LINK_RE = /\[([^\]\n]*)\]\(([^)\n]+)\)/g;
  72. interface AssistantPreviewCardOptions {
  73. changedFilePaths?: readonly string[];
  74. homePath?: string;
  75. suppressWebRemoteCards?: boolean;
  76. }
  77. interface PositionedCard {
  78. card: AssistantPreviewCard;
  79. position: number;
  80. }
  81. function normalizeTrailingUrlText(url: string): string {
  82. return url.trim().replace(/(?:[*_`]+|[.,;:!?,。!?;:、]+)+$/g, "");
  83. }
  84. export function isValidAssistantPreviewWebsiteUrl(url: string): boolean {
  85. const trimmedUrl = normalizeTrailingUrlText(url.trim());
  86. if (!trimmedUrl) return false;
  87. const isLocalHttpUrl = STRICT_LOCALHOST_URL_RE.test(trimmedUrl);
  88. const isFileHtmlUrl = STRICT_FILE_HTML_URL_RE.test(trimmedUrl);
  89. if (!isLocalHttpUrl && !isFileHtmlUrl) return false;
  90. try {
  91. const parsedUrl = new URL(trimmedUrl);
  92. if (parsedUrl.protocol === "file:") return isFileHtmlUrl;
  93. const port = parsedUrl.port ? Number.parseInt(parsedUrl.port, 10) : null;
  94. return (
  95. (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") &&
  96. parsedUrl.username.length === 0 &&
  97. parsedUrl.password.length === 0 &&
  98. (parsedUrl.hostname === "localhost" || parsedUrl.hostname === "127.0.0.1") &&
  99. (port === null || (port > 0 && port <= 65_535))
  100. );
  101. } catch {
  102. return false;
  103. }
  104. }
  105. function normalizeMarkdownHref(href: string): string {
  106. return href.trim().replace(/^<|>$/g, "");
  107. }
  108. function cleanMarkdownLinkTitle(title: string): string | null {
  109. const normalizedTitle = title.replace(/\s+/g, " ").trim();
  110. if (
  111. !normalizedTitle ||
  112. normalizedTitle.length > 80 ||
  113. /^https?:\/\//i.test(normalizedTitle) ||
  114. /[*_`[\]<>]/.test(normalizedTitle) ||
  115. /^[)"'`,.;:!?,。!?;:、)】》]+/.test(normalizedTitle) ||
  116. !/[a-zA-Z0-9\u4e00-\u9fff]/.test(normalizedTitle)
  117. ) {
  118. return null;
  119. }
  120. return normalizedTitle;
  121. }
  122. export function shouldOpenAssistantHtmlInBrowser(params: {
  123. path: string;
  124. workspaceIdentity?: string;
  125. workspaceRemoteSessionId?: string;
  126. }): boolean {
  127. return (
  128. isAssistantPreviewHtmlPath(params.path) &&
  129. !params.workspaceIdentity?.trim() &&
  130. !params.workspaceRemoteSessionId
  131. );
  132. }
  133. function normalizePathForCompare(path: string): string {
  134. return path.replace(/\\/g, "/").replace(/\/+/g, "/").replace(/\/$/, "");
  135. }
  136. function resolveChangedFilePath(workspacePath: string, path: string): string {
  137. if (/^(?:[a-zA-Z]:[\\/]|\/|\\\\)/.test(path)) {
  138. return cleanAssistantFilePathCandidate(path);
  139. }
  140. return resolveAssistantRawFilePath(workspacePath, path) ?? path;
  141. }
  142. function findMatchingChangedFilePath(
  143. reference: AssistantFileReference,
  144. changedFilePaths: readonly string[],
  145. workspacePath: string,
  146. ): string | null {
  147. const normalizedReferencePath = normalizePathForCompare(reference.path);
  148. const normalizedChangedPaths = changedFilePaths.map((path) => {
  149. const resolvedPath = resolveChangedFilePath(workspacePath, path);
  150. return { path: resolvedPath, normalized: normalizePathForCompare(resolvedPath) };
  151. });
  152. const exact = normalizedChangedPaths.find(
  153. (candidate) => candidate.normalized === normalizedReferencePath,
  154. );
  155. if (exact) return exact.path;
  156. const cleanedRaw = cleanAssistantFilePathCandidate(reference.raw);
  157. if (cleanedRaw.includes("/") || cleanedRaw.includes("\\") || /^file:/i.test(cleanedRaw)) {
  158. return null;
  159. }
  160. const leafMatches = normalizedChangedPaths.filter(
  161. (candidate) => getPathLeaf(candidate.normalized) === cleanedRaw,
  162. );
  163. return leafMatches.length === 1 ? leafMatches[0]!.path : null;
  164. }
  165. function getWebsiteTitleFromMarkdownLink(content: string, url: string): string | null {
  166. for (const match of content.matchAll(MARKDOWN_LINK_RE)) {
  167. const label = match[1] ? cleanMarkdownLinkTitle(match[1]) : null;
  168. const href = match[2] ? normalizeTrailingUrlText(normalizeMarkdownHref(match[2])) : "";
  169. if (label && href === url && !/^https?:\/\//i.test(label)) return label;
  170. }
  171. return null;
  172. }
  173. function getWebsiteFallbackTitle(url: string): string {
  174. try {
  175. const parsedUrl = new URL(url);
  176. const pathLeaf = getPathLeaf(decodeURI(parsedUrl.pathname));
  177. return pathLeaf && pathLeaf !== "/" ? pathLeaf : parsedUrl.host;
  178. } catch {
  179. return url;
  180. }
  181. }
  182. function resolveLocalhostHtmlChangedPath(
  183. url: string,
  184. workspacePath: string,
  185. changedFilePaths: readonly string[],
  186. options: AssistantFilePathResolveOptions = {},
  187. ): string | null {
  188. try {
  189. const parsedUrl = new URL(url);
  190. const pathname = decodeFilePathUriEscapes(parsedUrl.pathname).replace(/^\/+/, "");
  191. if (!isAssistantPreviewHtmlPath(pathname)) return null;
  192. const path = resolveAssistantRawFilePath(workspacePath, pathname, options);
  193. if (!path) return null;
  194. return findMatchingChangedFilePath(
  195. { start: 0, end: 0, kind: "html", path, raw: pathname },
  196. changedFilePaths,
  197. workspacePath,
  198. );
  199. } catch {
  200. return null;
  201. }
  202. }
  203. function buildFileCard(reference: AssistantFileReference): AssistantPreviewCard {
  204. const definition = getAssistantPreviewFileTypeDefinition(reference.path)!;
  205. if (reference.kind === "markdown") {
  206. return {
  207. id: `markdown:${reference.path}`,
  208. type: "markdown",
  209. kind: "markdown",
  210. title: getPathLeaf(reference.path),
  211. subtitleId: "chat.previewCards.markdown",
  212. path: reference.path,
  213. };
  214. }
  215. if (reference.kind === "html") {
  216. return {
  217. id: `website:${toFileUrl(reference.path)}`,
  218. type: "website",
  219. title: getPathLeaf(reference.path),
  220. subtitleId: "chat.previewCards.htmlWebsite",
  221. url: toFileUrl(reference.path),
  222. filePath: reference.path,
  223. };
  224. }
  225. return {
  226. id: `file:${reference.kind}:${reference.path}`,
  227. type: "file",
  228. kind: reference.kind,
  229. title: getPathLeaf(reference.path),
  230. subtitleId: definition.subtitleId as Extract<
  231. AssistantPreviewCard,
  232. { type: "file" }
  233. >["subtitleId"],
  234. path: reference.path,
  235. };
  236. }
  237. function getCardSeenKey(card: AssistantPreviewCard): string {
  238. const filePath = getAssistantPreviewCardFilePath(card);
  239. if (filePath) return `file:${normalizePathForCompare(filePath)}`;
  240. try {
  241. const parsedUrl = new URL(card.type === "website" ? card.url : "");
  242. return parsedUrl.pathname === "/" && !parsedUrl.search && !parsedUrl.hash
  243. ? `url:${parsedUrl.origin}`
  244. : `url:${parsedUrl.href}`;
  245. } catch {
  246. return card.id;
  247. }
  248. }
  249. export function buildAssistantPreviewCardsFromReferences(
  250. content: string,
  251. workspacePath: string,
  252. references: readonly AssistantFileReference[],
  253. options: AssistantPreviewCardOptions = {},
  254. ): AssistantPreviewCard[] {
  255. if (!content.trim()) return [];
  256. const changedFilePaths = options.changedFilePaths ?? [];
  257. const positionedCards: PositionedCard[] = [];
  258. let hasLocalHttpPreview = false;
  259. for (const match of content.matchAll(LOCALHOST_URL_RE)) {
  260. const url = normalizeTrailingUrlText(match[0] ?? "");
  261. if (!isValidAssistantPreviewWebsiteUrl(url)) continue;
  262. // Web 远控没有本地端口转发或 HTML 运行环境;在候选上限前过滤,避免隐藏卡片占位。
  263. if (options.suppressWebRemoteCards) continue;
  264. const filePath = resolveLocalhostHtmlChangedPath(url, workspacePath, changedFilePaths, {
  265. homePath: options.homePath,
  266. });
  267. hasLocalHttpPreview = true;
  268. positionedCards.push({
  269. position: match.index ?? 0,
  270. card: {
  271. id: `website:${url}`,
  272. type: "website",
  273. title:
  274. filePath !== null
  275. ? getPathLeaf(filePath)
  276. : (getWebsiteTitleFromMarkdownLink(content, url) ?? getWebsiteFallbackTitle(url)),
  277. subtitleId: "chat.previewCards.website",
  278. url,
  279. ...(filePath ? { filePath } : {}),
  280. },
  281. });
  282. }
  283. const fileReferences: AssistantFileReference[] = [];
  284. for (const reference of references) {
  285. if (options.suppressWebRemoteCards && reference.kind === "html") continue;
  286. if (reference.kind === "html" && hasLocalHttpPreview) continue;
  287. let resolvedReference = reference;
  288. if (reference.kind === "markdown" || reference.kind === "html") {
  289. const changedPath = findMatchingChangedFilePath(reference, changedFilePaths, workspacePath);
  290. if (!changedPath) continue;
  291. resolvedReference = { ...reference, path: changedPath };
  292. }
  293. fileReferences.push(resolvedReference);
  294. }
  295. const previewCandidates = buildConversationPreviewArtifactCandidatesFromReferences({
  296. references: fileReferences,
  297. productTurnId: "",
  298. workspacePath,
  299. fileChanges: changedFilePaths.map((path) => ({ path, state: "active" as const })),
  300. // Renderer 仍需展示已解析的 Home-relative/file URL 卡片;Share Service 会在自己的
  301. // Host source 上再次执行 workspace 边界校验。
  302. enforceWorkspaceBoundary: false,
  303. });
  304. const referencesByPath = new Map(
  305. fileReferences.map((reference) => [normalizePathForCompare(reference.path), reference]),
  306. );
  307. for (const candidate of previewCandidates) {
  308. const reference = referencesByPath.get(normalizePathForCompare(candidate.sourceRef));
  309. if (!reference) continue;
  310. positionedCards.push({
  311. position: reference.start,
  312. card: buildFileCard({ ...reference, path: candidate.sourceRef }),
  313. });
  314. }
  315. positionedCards.sort((left, right) => right.position - left.position);
  316. const seen = new Set<string>();
  317. const cards: AssistantPreviewCard[] = [];
  318. for (const candidate of positionedCards) {
  319. const key = getCardSeenKey(candidate.card);
  320. if (seen.has(key)) continue;
  321. seen.add(key);
  322. cards.push(candidate.card);
  323. if (cards.length === ASSISTANT_PREVIEW_CARD_CANDIDATE_LIMIT) break;
  324. }
  325. return cards;
  326. }
  327. export function getAssistantPreviewCardFilePath(card: AssistantPreviewCard): string | null {
  328. return card.type === "website"
  329. ? (card.filePath ?? parseAssistantFileUrlPath(card.url))
  330. : card.path;
  331. }
  332. export function requiresAssistantPreviewCardFileStat(card: AssistantPreviewCard): boolean {
  333. return getAssistantPreviewCardFilePath(card) !== null;
  334. }