message-assets.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /**
  2. * Message-level asset collection helpers.
  3. *
  4. * Extracted from the UI's `WorkspacePanel/workspace-collector.ts` so the
  5. * local-runtime session asset indexer and the UI Workspace collector share
  6. * the same wrapper extraction, path filtering, normalization, and dedupe
  7. * semantics. Keep behavior in sync with the UI collector tests.
  8. */
  9. import {
  10. type DeliverAssetItem,
  11. type ParseDeliverAssetsOptions,
  12. isBlobUrl,
  13. isHttpUrl,
  14. maskMarkdownProtectedRanges,
  15. parseDeliverAssetsContent,
  16. } from './deliver-assets.js';
  17. import { isDataUrl } from './data-url.js';
  18. const DELIVER_ASSETS_WRAPPER_RE = /<(deliver-assets|deliver_assets)>([\s\S]*?)<\/\1>/g;
  19. export interface CollectMessageAssetItemsOptions extends ParseDeliverAssetsOptions {
  20. /**
  21. * Collect standalone `<media />` tags outside `<deliver-assets>` wrappers.
  22. * Local-runtime keeps this on for all runtimes (the indexer owns the rule);
  23. * the UI collector still threads its own flag for the streaming fallback.
  24. */
  25. includeStandaloneMedia?: boolean;
  26. }
  27. /** Strip line number suffix (:42) from a file path. */
  28. function stripLineNumber(p: string): string {
  29. return p.replace(/:\d+$/, '');
  30. }
  31. export function extractDeliverAssetsWrappers(content: string): string {
  32. const wrappers: string[] = [];
  33. DELIVER_ASSETS_WRAPPER_RE.lastIndex = 0;
  34. let match: RegExpExecArray | null;
  35. while ((match = DELIVER_ASSETS_WRAPPER_RE.exec(content)) !== null) {
  36. wrappers.push(match[0]);
  37. }
  38. return wrappers.join('\n');
  39. }
  40. export function stripDeliverAssetsWrappers(content: string): string {
  41. DELIVER_ASSETS_WRAPPER_RE.lastIndex = 0;
  42. return content.replace(DELIVER_ASSETS_WRAPPER_RE, '');
  43. }
  44. /**
  45. * Normalize a path into the dedupe key used by Workspace and the session
  46. * asset index: strip `:line`, unify separators, drop trailing slashes, and
  47. * lowercase Windows drive letters.
  48. */
  49. export function normalizeAssetPathKey(path: string): string {
  50. const trimmed = stripLineNumber(path.trim()).replace(/\\/g, '/');
  51. const withoutTrailingSlash = trimmed.length > 1 ? trimmed.replace(/\/+$/u, '') : trimmed;
  52. return /^[A-Z]:\//u.test(withoutTrailingSlash)
  53. ? withoutTrailingSlash[0]!.toLowerCase() + withoutTrailingSlash.slice(1)
  54. : withoutTrailingSlash;
  55. }
  56. /** Remote URLs, virtual URLs, and app API paths never enter the workspace. */
  57. export function shouldSkipAssetPath(path: string): boolean {
  58. const trimmed = path.trim();
  59. return (
  60. isDataUrl(trimmed) ||
  61. isHttpUrl(trimmed) ||
  62. isBlobUrl(trimmed) ||
  63. /^\/(?:mavis\/api|api)\//u.test(trimmed)
  64. );
  65. }
  66. /** Prefer entries carrying more metadata (name/type) on dedupe collisions. */
  67. export function hasRicherAssetMetadata(a: DeliverAssetItem, b: DeliverAssetItem): boolean {
  68. const aScore = (a.name ? 1 : 0) + (a.type ? 1 : 0) + (a.nodeId ? 1 : 0) + (a.coverPath ? 1 : 0);
  69. const bScore = (b.name ? 1 : 0) + (b.type ? 1 : 0) + (b.nodeId ? 1 : 0) + (b.coverPath ? 1 : 0);
  70. return aScore > bScore;
  71. }
  72. /** Add item to map keyed by normalized path, preferring richer metadata. */
  73. export function addAssetItemToMap(
  74. map: Map<string, DeliverAssetItem>,
  75. item: DeliverAssetItem,
  76. ): void {
  77. if (shouldSkipAssetPath(item.path)) return;
  78. const key = normalizeAssetPathKey(item.path);
  79. const existing = map.get(key);
  80. const normalizedItem = item.path === key ? item : { ...item, path: key };
  81. if (!existing || hasRicherAssetMetadata(item, existing)) {
  82. map.set(key, normalizedItem);
  83. }
  84. }
  85. function collectFromAssetMarkup(
  86. map: Map<string, DeliverAssetItem>,
  87. content: string,
  88. options: ParseDeliverAssetsOptions,
  89. ): void {
  90. const segments = parseDeliverAssetsContent(content, options);
  91. for (const seg of segments) {
  92. if (seg.type === 'deliver-assets' || seg.type === 'image-gallery') {
  93. for (const item of seg.items) addAssetItemToMap(map, item);
  94. }
  95. }
  96. }
  97. /**
  98. * Collect asset items from one complete assistant message body.
  99. *
  100. * Sources match the UI Workspace collector:
  101. * 1. `<deliver-assets>` / `<deliver_assets>` wrapper blocks (always)
  102. * 2. standalone `<media />` tags (when `includeStandaloneMedia`, default on)
  103. *
  104. * Plain-text paths, inline-code paths, and code-fence content are ignored;
  105. * remote/virtual URLs and app API paths are filtered; results are deduped by
  106. * normalized path with richer metadata winning. Order follows first
  107. * appearance in the message.
  108. */
  109. export function collectMessageAssetItems(
  110. msgContent: string,
  111. options: CollectMessageAssetItemsOptions = {},
  112. ): DeliverAssetItem[] {
  113. const { includeStandaloneMedia = true, ...parseOptions } = options;
  114. const byPath = new Map<string, DeliverAssetItem>();
  115. // Mask code fences / inline code before wrapper extraction so fenced
  116. // example markup never indexes. (The UI collector extracts wrappers from
  117. // the raw content for streaming display; the persisted index is stricter.)
  118. const searchableContent = maskMarkdownProtectedRanges(msgContent);
  119. const workspaceMarkup = extractDeliverAssetsWrappers(searchableContent);
  120. if (workspaceMarkup) {
  121. collectFromAssetMarkup(byPath, workspaceMarkup, parseOptions);
  122. }
  123. if (includeStandaloneMedia) {
  124. const standaloneMarkup = stripDeliverAssetsWrappers(searchableContent);
  125. if (standaloneMarkup.trim()) {
  126. collectFromAssetMarkup(byPath, standaloneMarkup, parseOptions);
  127. }
  128. }
  129. return [...byPath.values()];
  130. }