@open-mercato/ui 0.10.1-develop.8278.1.f7f8e5ab1a → 0.10.1-develop.8287.1.7313a0fe67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/ai/AiChat.js +40 -14
  3. package/dist/ai/AiChat.js.map +2 -2
  4. package/dist/ai/LoopTracePanel.js +30 -23
  5. package/dist/ai/LoopTracePanel.js.map +2 -2
  6. package/dist/ai/citations/merge.js +72 -0
  7. package/dist/ai/citations/merge.js.map +7 -0
  8. package/dist/ai/citations/registry.js +97 -0
  9. package/dist/ai/citations/registry.js.map +7 -0
  10. package/dist/ai/conversation-store.js +4 -1
  11. package/dist/ai/conversation-store.js.map +2 -2
  12. package/dist/ai/index.js +40 -1
  13. package/dist/ai/index.js.map +2 -2
  14. package/dist/ai/parts/CitationsPart.js +135 -0
  15. package/dist/ai/parts/CitationsPart.js.map +7 -0
  16. package/dist/ai/parts/index.js +2 -0
  17. package/dist/ai/parts/index.js.map +2 -2
  18. package/dist/ai/run-trace-link.js +33 -0
  19. package/dist/ai/run-trace-link.js.map +7 -0
  20. package/dist/ai/ui-part-registry.js +12 -0
  21. package/dist/ai/ui-part-registry.js.map +2 -2
  22. package/dist/ai/useAiChat.js +7 -3
  23. package/dist/ai/useAiChat.js.map +2 -2
  24. package/dist/backend/DataTable.js +1 -1
  25. package/dist/backend/DataTable.js.map +2 -2
  26. package/dist/backend/detail/AttachmentMetadataDialog.js +137 -101
  27. package/dist/backend/detail/AttachmentMetadataDialog.js.map +2 -2
  28. package/dist/backend/detail/DocumentStructurePanel.js +384 -0
  29. package/dist/backend/detail/DocumentStructurePanel.js.map +7 -0
  30. package/package.json +3 -3
  31. package/src/ai/AiChat.tsx +47 -22
  32. package/src/ai/LoopTracePanel.tsx +44 -10
  33. package/src/ai/__tests__/AiChat.run-trace.test.tsx +264 -0
  34. package/src/ai/citations/__tests__/href-safety-cases.ts +33 -0
  35. package/src/ai/citations/__tests__/registry.test.ts +156 -0
  36. package/src/ai/citations/merge.ts +83 -0
  37. package/src/ai/citations/registry.ts +138 -0
  38. package/src/ai/conversation-store.ts +3 -0
  39. package/src/ai/index.ts +27 -0
  40. package/src/ai/parts/CitationsPart.tsx +146 -0
  41. package/src/ai/parts/__tests__/CitationsPart.test.tsx +105 -0
  42. package/src/ai/parts/index.ts +1 -0
  43. package/src/ai/run-trace-link.ts +33 -0
  44. package/src/ai/ui-part-registry.ts +13 -0
  45. package/src/ai/useAiChat.ts +13 -5
  46. package/src/backend/DataTable.tsx +3 -1
  47. package/src/backend/__tests__/AttachmentMetadataDialog.test.tsx +32 -1
  48. package/src/backend/__tests__/lazy-heavy-libraries.test.ts +7 -0
  49. package/src/backend/detail/AttachmentMetadataDialog.tsx +161 -119
  50. package/src/backend/detail/DocumentStructurePanel.tsx +514 -0
  51. package/src/backend/detail/__tests__/AttachmentMetadataDialog.tabs.test.tsx +89 -0
  52. package/src/backend/detail/__tests__/DocumentStructurePanel.test.tsx +153 -0
@@ -0,0 +1,384 @@
1
+ "use client";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { ChevronDown, ChevronRight, FileSearch, RefreshCw } from "lucide-react";
5
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
6
+ import { hasFeature } from "@open-mercato/shared/security/features";
7
+ import { Button } from "../../primitives/button.js";
8
+ import { IconButton } from "../../primitives/icon-button.js";
9
+ import { EmptyState } from "../../primitives/empty-state.js";
10
+ import { StatusBadge } from "../../primitives/status-badge.js";
11
+ import { apiCall } from "../utils/apiCall.js";
12
+ import { flash } from "../FlashMessages.js";
13
+ import { useGuardedMutation } from "../injection/useGuardedMutation.js";
14
+ import { LoadingMessage } from "./LoadingMessage.js";
15
+ import { ErrorMessage } from "./ErrorMessage.js";
16
+ const OUTLINE_MAX_DEPTH = 2;
17
+ const CHILDREN_PAGE_SIZE = 100;
18
+ const POLL_INTERVAL_MS = 3e3;
19
+ const MAX_POLLS = 60;
20
+ const OUTLINE_KINDS = ["part", "chapter", "section", "article", "clause", "annex", "page_unreadable"].join(",");
21
+ const ACTIVE_STATUSES = /* @__PURE__ */ new Set(["pending", "processing"]);
22
+ const statusVariants = {
23
+ pending: "neutral",
24
+ processing: "info",
25
+ completed: "success",
26
+ partial: "warning",
27
+ failed: "error",
28
+ skipped: "neutral"
29
+ };
30
+ const statusLabels = {
31
+ pending: ["attachments.structure.status.pending", "Queued"],
32
+ processing: ["attachments.structure.status.processing", "Processing"],
33
+ completed: ["attachments.structure.status.completed", "Completed"],
34
+ partial: ["attachments.structure.status.partial", "Partial"],
35
+ failed: ["attachments.structure.status.failed", "Failed"],
36
+ skipped: ["attachments.structure.status.skipped", "Skipped"]
37
+ };
38
+ const skipReasonLabels = {
39
+ unsupported_type: ["attachments.structure.skipReason.unsupported_type", "This file type does not support document structure extraction."],
40
+ no_text_layer_ocr_disabled: ["attachments.structure.skipReason.no_text_layer_ocr_disabled", "The document has no text layer and OCR is disabled."],
41
+ too_large: ["attachments.structure.skipReason.too_large", "The file is too large for document structure extraction."],
42
+ encrypted_pdf: ["attachments.structure.skipReason.encrypted_pdf", "The PDF is encrypted and cannot be read."]
43
+ };
44
+ function structureUrl(attachmentId) {
45
+ return `/api/attachments/structure/${encodeURIComponent(attachmentId)}`;
46
+ }
47
+ function useCanManageStructure(canManage) {
48
+ const [granted, setGranted] = React.useState(false);
49
+ React.useEffect(() => {
50
+ if (canManage !== void 0) return;
51
+ let cancelled = false;
52
+ void apiCall("/api/auth/feature-check", {
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify({ features: ["attachments.manage"] })
56
+ }).then((call) => {
57
+ if (!cancelled) setGranted(hasFeature(call.result?.granted, "attachments.manage"));
58
+ }).catch(() => {
59
+ if (!cancelled) setGranted(false);
60
+ });
61
+ return () => {
62
+ cancelled = true;
63
+ };
64
+ }, [canManage]);
65
+ return canManage ?? granted;
66
+ }
67
+ function OutlineNodeItem({
68
+ node,
69
+ childrenOf,
70
+ isExpanded,
71
+ isLoading,
72
+ onToggle,
73
+ onLoadMore
74
+ }) {
75
+ const t = useT();
76
+ const children = childrenOf(node.id);
77
+ const expandable = !children.known || children.items.length > 0;
78
+ const expanded = expandable && isExpanded(node.id);
79
+ const label = [node.numberLabel, node.heading].filter(Boolean).join(" ") || t("attachments.structure.outline.untitled", "Untitled section");
80
+ const pages = node.pageStart === null ? null : node.pageEnd !== null && node.pageEnd !== node.pageStart ? t("attachments.structure.outline.pageRange", "pp. {start}\u2013{end}", { start: node.pageStart, end: node.pageEnd }) : t("attachments.structure.outline.page", "p. {page}", { page: node.pageStart });
81
+ return /* @__PURE__ */ jsxs("li", { "data-section-id": node.id, children: [
82
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 items-center gap-1", children: [
83
+ expandable ? /* @__PURE__ */ jsx(
84
+ IconButton,
85
+ {
86
+ type: "button",
87
+ variant: "ghost",
88
+ size: "xs",
89
+ "aria-expanded": expanded,
90
+ "aria-label": expanded ? t("attachments.structure.outline.collapse", "Collapse {label}", { label }) : t("attachments.structure.outline.expand", "Expand {label}", { label }),
91
+ onClick: () => onToggle(node.id),
92
+ children: expanded ? /* @__PURE__ */ jsx(ChevronDown, { className: "size-4" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "size-4" })
93
+ }
94
+ ) : /* @__PURE__ */ jsx("span", { className: "size-6 shrink-0", "aria-hidden": "true" }),
95
+ /* @__PURE__ */ jsx("span", { className: "min-w-0 flex-1 truncate text-sm", title: label, children: label }),
96
+ pages ? /* @__PURE__ */ jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: pages }) : null
97
+ ] }),
98
+ expanded ? /* @__PURE__ */ jsxs("ul", { className: "ms-6 space-y-1", children: [
99
+ children.items.map((child) => /* @__PURE__ */ jsx(
100
+ OutlineNodeItem,
101
+ {
102
+ node: child,
103
+ childrenOf,
104
+ isExpanded,
105
+ isLoading,
106
+ onToggle,
107
+ onLoadMore
108
+ },
109
+ child.id
110
+ )),
111
+ isLoading(node.id) ? /* @__PURE__ */ jsx("li", { className: "text-xs text-muted-foreground", children: t("attachments.structure.outline.loading", "Loading sections\u2026") }) : null,
112
+ children.known && children.items.length === 0 && !isLoading(node.id) ? /* @__PURE__ */ jsx("li", { className: "text-xs text-muted-foreground", children: t("attachments.structure.outline.noChildren", "No subsections.") }) : null,
113
+ children.nextCursor !== null && !isLoading(node.id) ? /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", size: "2xs", onClick: () => onLoadMore(node.id), children: t("attachments.structure.actions.loadMore", "Load more") }) }) : null
114
+ ] }) : null
115
+ ] });
116
+ }
117
+ function DocumentStructurePanel({ attachmentId, canManage }) {
118
+ const t = useT();
119
+ const allowManage = useCanManageStructure(canManage);
120
+ const [structure, setStructure] = React.useState(null);
121
+ const [loadError, setLoadError] = React.useState(null);
122
+ const [reloadToken, setReloadToken] = React.useState(0);
123
+ const [pollCount, setPollCount] = React.useState(0);
124
+ const [awaitingFromId, setAwaitingFromId] = React.useState(void 0);
125
+ const [requesting, setRequesting] = React.useState(false);
126
+ const [loadedChildren, setLoadedChildren] = React.useState({});
127
+ const [loadingNodes, setLoadingNodes] = React.useState(/* @__PURE__ */ new Set());
128
+ const [expandedNodes, setExpandedNodes] = React.useState(/* @__PURE__ */ new Set());
129
+ const { runMutation, retryLastMutation } = useGuardedMutation({ contextId: `attachment-structure:${attachmentId}` });
130
+ const extractionId = structure?.extraction?.id ?? null;
131
+ React.useEffect(() => {
132
+ let cancelled = false;
133
+ const load = async () => {
134
+ try {
135
+ const call = await apiCall(
136
+ `${structureUrl(attachmentId)}?includeOutline=true&maxDepth=${OUTLINE_MAX_DEPTH}`
137
+ );
138
+ if (cancelled) return;
139
+ if (!call.ok || !call.result) {
140
+ setLoadError(t("attachments.structure.loadError", "Failed to load the document structure."));
141
+ return;
142
+ }
143
+ setLoadError(null);
144
+ setStructure(call.result);
145
+ } catch {
146
+ if (!cancelled) setLoadError(t("attachments.structure.loadError", "Failed to load the document structure."));
147
+ }
148
+ };
149
+ void load();
150
+ return () => {
151
+ cancelled = true;
152
+ };
153
+ }, [attachmentId, reloadToken, t]);
154
+ React.useEffect(() => {
155
+ setLoadedChildren({});
156
+ setLoadingNodes(/* @__PURE__ */ new Set());
157
+ setExpandedNodes(/* @__PURE__ */ new Set());
158
+ }, [attachmentId, extractionId]);
159
+ const status = structure?.extraction?.status ?? null;
160
+ const awaiting = awaitingFromId !== void 0;
161
+ React.useEffect(() => {
162
+ if (!structure || awaitingFromId === void 0) return;
163
+ const current = structure.extraction;
164
+ if (current && (current.id !== awaitingFromId || ACTIVE_STATUSES.has(current.status))) {
165
+ setAwaitingFromId(void 0);
166
+ }
167
+ }, [awaitingFromId, structure]);
168
+ const shouldPoll = (awaiting || status !== null && ACTIVE_STATUSES.has(status)) && pollCount < MAX_POLLS;
169
+ React.useEffect(() => {
170
+ if (!shouldPoll) return;
171
+ const timer = setTimeout(() => {
172
+ setPollCount((count) => count + 1);
173
+ setReloadToken((token) => token + 1);
174
+ }, POLL_INTERVAL_MS);
175
+ return () => clearTimeout(timer);
176
+ }, [shouldPoll, reloadToken]);
177
+ const outlineIndex = React.useMemo(() => {
178
+ const outline = structure?.outline ?? [];
179
+ const ids = new Set(outline.map((node) => node.id));
180
+ const byParent = /* @__PURE__ */ new Map();
181
+ const roots = [];
182
+ for (const node of outline) {
183
+ if (node.parentId && ids.has(node.parentId)) {
184
+ const siblings = byParent.get(node.parentId) ?? [];
185
+ siblings.push(node);
186
+ byParent.set(node.parentId, siblings);
187
+ } else {
188
+ roots.push(node);
189
+ }
190
+ }
191
+ return { roots, byParent, rootIds: new Set(roots.map((node) => node.id)) };
192
+ }, [structure]);
193
+ const childrenOf = React.useCallback(
194
+ (nodeId) => {
195
+ if (outlineIndex.rootIds.has(nodeId)) {
196
+ return { items: outlineIndex.byParent.get(nodeId) ?? [], known: true, nextCursor: null };
197
+ }
198
+ const loaded = loadedChildren[nodeId];
199
+ if (!loaded) return { items: [], known: false, nextCursor: null };
200
+ return { items: loaded.items, known: true, nextCursor: loaded.nextCursor };
201
+ },
202
+ [loadedChildren, outlineIndex]
203
+ );
204
+ const fetchChildren = React.useCallback(
205
+ async (nodeId, afterOrdinal) => {
206
+ setLoadingNodes((current) => new Set(current).add(nodeId));
207
+ const params = new URLSearchParams({
208
+ parentId: nodeId,
209
+ includeText: "false",
210
+ limit: String(CHILDREN_PAGE_SIZE),
211
+ kinds: OUTLINE_KINDS
212
+ });
213
+ if (afterOrdinal !== null) params.set("afterOrdinal", String(afterOrdinal));
214
+ try {
215
+ const call = await apiCall(`${structureUrl(attachmentId)}/sections?${params.toString()}`);
216
+ if (!call.ok || !call.result) throw new Error("[internal] document sections request failed");
217
+ const page = call.result;
218
+ setLoadedChildren((current) => ({
219
+ ...current,
220
+ [nodeId]: {
221
+ items: [...afterOrdinal !== null ? current[nodeId]?.items ?? [] : [], ...page.items],
222
+ nextCursor: page.nextCursor
223
+ }
224
+ }));
225
+ } catch {
226
+ flash(t("attachments.structure.outline.loadError", "Failed to load subsections."), "error");
227
+ } finally {
228
+ setLoadingNodes((current) => {
229
+ const next = new Set(current);
230
+ next.delete(nodeId);
231
+ return next;
232
+ });
233
+ }
234
+ },
235
+ [attachmentId, t]
236
+ );
237
+ const isExpanded = React.useCallback(
238
+ (nodeId) => outlineIndex.rootIds.has(nodeId) ? !expandedNodes.has(nodeId) : expandedNodes.has(nodeId),
239
+ [expandedNodes, outlineIndex]
240
+ );
241
+ const isLoading = React.useCallback((nodeId) => loadingNodes.has(nodeId), [loadingNodes]);
242
+ const handleToggle = React.useCallback(
243
+ (nodeId) => {
244
+ setExpandedNodes((current) => {
245
+ const next = new Set(current);
246
+ if (next.has(nodeId)) next.delete(nodeId);
247
+ else next.add(nodeId);
248
+ return next;
249
+ });
250
+ if (!outlineIndex.rootIds.has(nodeId) && !loadedChildren[nodeId] && !loadingNodes.has(nodeId)) {
251
+ void fetchChildren(nodeId, null);
252
+ }
253
+ },
254
+ [fetchChildren, loadedChildren, loadingNodes, outlineIndex]
255
+ );
256
+ const handleLoadMore = React.useCallback(
257
+ (nodeId) => {
258
+ const cursor = loadedChildren[nodeId]?.nextCursor;
259
+ if (cursor === null || cursor === void 0) return;
260
+ void fetchChildren(nodeId, cursor);
261
+ },
262
+ [fetchChildren, loadedChildren]
263
+ );
264
+ const handleRefresh = React.useCallback(() => {
265
+ setPollCount(0);
266
+ setReloadToken((token) => token + 1);
267
+ }, []);
268
+ const handleExtract = React.useCallback(async () => {
269
+ const force = Boolean(structure?.extraction);
270
+ const previousId = structure?.extraction?.id ?? null;
271
+ setRequesting(true);
272
+ try {
273
+ const call = await runMutation({
274
+ operation: async () => {
275
+ const response = await apiCall(structureUrl(attachmentId), {
276
+ method: "POST",
277
+ headers: { "content-type": "application/json" },
278
+ body: JSON.stringify({ force })
279
+ });
280
+ if (!response.ok) {
281
+ const serverMessage = typeof response.result?.error === "string" ? response.result.error : null;
282
+ throw new Error(serverMessage ?? t("attachments.structure.flash.requestError", "Failed to request document structure extraction."));
283
+ }
284
+ return response;
285
+ },
286
+ context: { formId: `attachment-structure:${attachmentId}`, attachmentId, retryLastMutation },
287
+ mutationPayload: { force }
288
+ });
289
+ if (call.status === 202) {
290
+ setAwaitingFromId(previousId);
291
+ flash(t("attachments.structure.flash.requested", "Document structure extraction queued."), "success");
292
+ } else {
293
+ flash(t("attachments.structure.flash.current", "The document structure is already up to date."), "success");
294
+ }
295
+ setPollCount(0);
296
+ setReloadToken((token) => token + 1);
297
+ } catch (error) {
298
+ const message = error instanceof Error && error.message && !error.message.startsWith("[internal]") ? error.message : t("attachments.structure.flash.requestError", "Failed to request document structure extraction.");
299
+ flash(message, "error");
300
+ } finally {
301
+ setRequesting(false);
302
+ }
303
+ }, [attachmentId, retryLastMutation, runMutation, structure, t]);
304
+ if (loadError && !structure) {
305
+ return /* @__PURE__ */ jsx(
306
+ ErrorMessage,
307
+ {
308
+ label: loadError,
309
+ action: /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: handleRefresh, children: t("attachments.structure.actions.refresh", "Refresh") })
310
+ }
311
+ );
312
+ }
313
+ if (!structure) {
314
+ return /* @__PURE__ */ jsx(LoadingMessage, { label: t("attachments.structure.loading", "Loading document structure\u2026") });
315
+ }
316
+ const extraction = structure.extraction;
317
+ const displayStatus = awaiting ? "pending" : status;
318
+ const busy = requesting || displayStatus !== null && ACTIVE_STATUSES.has(displayStatus);
319
+ const extractButton = allowManage ? /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => void handleExtract(), disabled: busy, children: extraction ? t("attachments.structure.actions.reextract", "Re-extract") : t("attachments.structure.actions.extract", "Extract structure") }) : null;
320
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-3", "data-testid": "document-structure-panel", children: [
321
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
322
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [
323
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: t("attachments.structure.outline.title", "Document outline") }),
324
+ displayStatus ? /* @__PURE__ */ jsx(StatusBadge, { variant: statusVariants[displayStatus], dot: true, children: t(...statusLabels[displayStatus]) }) : null,
325
+ extraction?.pageCount ? /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("attachments.structure.summary", "{pages} pages \u2014 {sections} sections", {
326
+ pages: extraction.pageCount,
327
+ sections: extraction.sectionCount ?? 0
328
+ }) }) : null
329
+ ] }),
330
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
331
+ /* @__PURE__ */ jsx(
332
+ IconButton,
333
+ {
334
+ type: "button",
335
+ variant: "ghost",
336
+ "aria-label": t("attachments.structure.actions.refresh", "Refresh"),
337
+ onClick: handleRefresh,
338
+ children: /* @__PURE__ */ jsx(RefreshCw, { className: "size-4" })
339
+ }
340
+ ),
341
+ extraction ? extractButton : null
342
+ ] })
343
+ ] }),
344
+ loadError ? /* @__PURE__ */ jsx(ErrorMessage, { label: loadError }) : null,
345
+ extraction?.skipReason && skipReasonLabels[extraction.skipReason] ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t(...skipReasonLabels[extraction.skipReason]) }) : null,
346
+ extraction?.status === "failed" ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("attachments.structure.failedHint", "The extraction failed. Try extracting the structure again.") }) : null,
347
+ !extraction ? /* @__PURE__ */ jsx(
348
+ EmptyState,
349
+ {
350
+ variant: "subtle",
351
+ size: "sm",
352
+ icon: /* @__PURE__ */ jsx(FileSearch, { className: "size-5", "aria-hidden": "true" }),
353
+ title: awaiting ? t("attachments.structure.empty.queuedTitle", "Extraction queued") : t("attachments.structure.empty.title", "Structure not extracted yet"),
354
+ description: t("attachments.structure.empty.description", "Extract the document structure to browse its chapters and sections."),
355
+ actions: extractButton
356
+ }
357
+ ) : outlineIndex.roots.length > 0 ? /* @__PURE__ */ jsx("ul", { className: "max-h-96 space-y-1 overflow-y-auto", children: outlineIndex.roots.map((node) => /* @__PURE__ */ jsx(
358
+ OutlineNodeItem,
359
+ {
360
+ node,
361
+ childrenOf,
362
+ isExpanded,
363
+ isLoading,
364
+ onToggle: handleToggle,
365
+ onLoadMore: handleLoadMore
366
+ },
367
+ node.id
368
+ )) }) : ACTIVE_STATUSES.has(extraction.status) || extraction.status === "skipped" || extraction.status === "failed" ? null : /* @__PURE__ */ jsx(
369
+ EmptyState,
370
+ {
371
+ variant: "subtle",
372
+ size: "sm",
373
+ icon: /* @__PURE__ */ jsx(FileSearch, { className: "size-5", "aria-hidden": "true" }),
374
+ title: t("attachments.structure.outline.empty", "No headings were found in this document.")
375
+ }
376
+ )
377
+ ] });
378
+ }
379
+ var DocumentStructurePanel_default = DocumentStructurePanel;
380
+ export {
381
+ DocumentStructurePanel,
382
+ DocumentStructurePanel_default as default
383
+ };
384
+ //# sourceMappingURL=DocumentStructurePanel.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/backend/detail/DocumentStructurePanel.tsx"],
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { ChevronDown, ChevronRight, FileSearch, RefreshCw } from 'lucide-react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { hasFeature } from '@open-mercato/shared/security/features'\nimport { Button } from '../../primitives/button'\nimport { IconButton } from '../../primitives/icon-button'\nimport { EmptyState } from '../../primitives/empty-state'\nimport { StatusBadge, type StatusMap } from '../../primitives/status-badge'\nimport { apiCall } from '../utils/apiCall'\nimport { flash } from '../FlashMessages'\nimport { useGuardedMutation } from '../injection/useGuardedMutation'\nimport { LoadingMessage } from './LoadingMessage'\nimport { ErrorMessage } from './ErrorMessage'\n\nexport type DocumentStructureStatus = 'pending' | 'processing' | 'completed' | 'partial' | 'failed' | 'skipped'\n\nexport type DocumentStructureExtraction = {\n id: string\n status: DocumentStructureStatus\n pageCount?: number | null\n sectionCount?: number | null\n skipReason?: string | null\n}\n\nexport type DocumentStructureNode = {\n id: string\n parentId: string | null\n kind: string\n numberLabel: string | null\n heading: string | null\n pageStart: number | null\n pageEnd: number | null\n}\n\ntype StructureResponse = {\n attachmentId: string\n extraction: DocumentStructureExtraction | null\n outline: DocumentStructureNode[]\n}\n\ntype SectionsResponse = {\n extractionId: string | null\n items: DocumentStructureNode[]\n nextCursor: number | null\n}\n\ntype RequestResponse = { status?: string; error?: string }\n\ntype LoadedChildren = { items: DocumentStructureNode[]; nextCursor: number | null }\n\nexport type DocumentStructurePanelProps = {\n attachmentId: string\n canManage?: boolean\n}\n\nconst OUTLINE_MAX_DEPTH = 2\nconst CHILDREN_PAGE_SIZE = 100\nconst POLL_INTERVAL_MS = 3000\nconst MAX_POLLS = 60\nconst OUTLINE_KINDS = ['part', 'chapter', 'section', 'article', 'clause', 'annex', 'page_unreadable'].join(',')\nconst ACTIVE_STATUSES: ReadonlySet<DocumentStructureStatus> = new Set(['pending', 'processing'])\n\nconst statusVariants: StatusMap<DocumentStructureStatus> = {\n pending: 'neutral',\n processing: 'info',\n completed: 'success',\n partial: 'warning',\n failed: 'error',\n skipped: 'neutral',\n}\n\nconst statusLabels: Record<DocumentStructureStatus, [string, string]> = {\n pending: ['attachments.structure.status.pending', 'Queued'],\n processing: ['attachments.structure.status.processing', 'Processing'],\n completed: ['attachments.structure.status.completed', 'Completed'],\n partial: ['attachments.structure.status.partial', 'Partial'],\n failed: ['attachments.structure.status.failed', 'Failed'],\n skipped: ['attachments.structure.status.skipped', 'Skipped'],\n}\n\nconst skipReasonLabels: Record<string, [string, string]> = {\n unsupported_type: ['attachments.structure.skipReason.unsupported_type', 'This file type does not support document structure extraction.'],\n no_text_layer_ocr_disabled: ['attachments.structure.skipReason.no_text_layer_ocr_disabled', 'The document has no text layer and OCR is disabled.'],\n too_large: ['attachments.structure.skipReason.too_large', 'The file is too large for document structure extraction.'],\n encrypted_pdf: ['attachments.structure.skipReason.encrypted_pdf', 'The PDF is encrypted and cannot be read.'],\n}\n\nfunction structureUrl(attachmentId: string): string {\n return `/api/attachments/structure/${encodeURIComponent(attachmentId)}`\n}\n\nfunction useCanManageStructure(canManage: boolean | undefined): boolean {\n const [granted, setGranted] = React.useState(false)\n React.useEffect(() => {\n if (canManage !== undefined) return\n let cancelled = false\n void apiCall<{ granted?: string[] }>('/api/auth/feature-check', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ features: ['attachments.manage'] }),\n })\n .then((call) => {\n if (!cancelled) setGranted(hasFeature(call.result?.granted, 'attachments.manage'))\n })\n .catch(() => {\n if (!cancelled) setGranted(false)\n })\n return () => {\n cancelled = true\n }\n }, [canManage])\n return canManage ?? granted\n}\n\nfunction OutlineNodeItem({\n node,\n childrenOf,\n isExpanded,\n isLoading,\n onToggle,\n onLoadMore,\n}: {\n node: DocumentStructureNode\n childrenOf: (nodeId: string) => { items: DocumentStructureNode[]; known: boolean; nextCursor: number | null }\n isExpanded: (nodeId: string) => boolean\n isLoading: (nodeId: string) => boolean\n onToggle: (nodeId: string) => void\n onLoadMore: (nodeId: string) => void\n}) {\n const t = useT()\n const children = childrenOf(node.id)\n const expandable = !children.known || children.items.length > 0\n const expanded = expandable && isExpanded(node.id)\n const label = [node.numberLabel, node.heading].filter(Boolean).join(' ') || t('attachments.structure.outline.untitled', 'Untitled section')\n const pages =\n node.pageStart === null\n ? null\n : node.pageEnd !== null && node.pageEnd !== node.pageStart\n ? t('attachments.structure.outline.pageRange', 'pp. {start}\u2013{end}', { start: node.pageStart, end: node.pageEnd })\n : t('attachments.structure.outline.page', 'p. {page}', { page: node.pageStart })\n return (\n <li data-section-id={node.id}>\n <div className=\"flex min-w-0 items-center gap-1\">\n {expandable ? (\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n size=\"xs\"\n aria-expanded={expanded}\n aria-label={\n expanded\n ? t('attachments.structure.outline.collapse', 'Collapse {label}', { label })\n : t('attachments.structure.outline.expand', 'Expand {label}', { label })\n }\n onClick={() => onToggle(node.id)}\n >\n {expanded ? <ChevronDown className=\"size-4\" /> : <ChevronRight className=\"size-4\" />}\n </IconButton>\n ) : (\n <span className=\"size-6 shrink-0\" aria-hidden=\"true\" />\n )}\n <span className=\"min-w-0 flex-1 truncate text-sm\" title={label}>\n {label}\n </span>\n {pages ? <span className=\"shrink-0 text-xs text-muted-foreground\">{pages}</span> : null}\n </div>\n {expanded ? (\n <ul className=\"ms-6 space-y-1\">\n {children.items.map((child) => (\n <OutlineNodeItem\n key={child.id}\n node={child}\n childrenOf={childrenOf}\n isExpanded={isExpanded}\n isLoading={isLoading}\n onToggle={onToggle}\n onLoadMore={onLoadMore}\n />\n ))}\n {isLoading(node.id) ? (\n <li className=\"text-xs text-muted-foreground\">{t('attachments.structure.outline.loading', 'Loading sections\u2026')}</li>\n ) : null}\n {children.known && children.items.length === 0 && !isLoading(node.id) ? (\n <li className=\"text-xs text-muted-foreground\">{t('attachments.structure.outline.noChildren', 'No subsections.')}</li>\n ) : null}\n {children.nextCursor !== null && !isLoading(node.id) ? (\n <li>\n <Button type=\"button\" variant=\"ghost\" size=\"2xs\" onClick={() => onLoadMore(node.id)}>\n {t('attachments.structure.actions.loadMore', 'Load more')}\n </Button>\n </li>\n ) : null}\n </ul>\n ) : null}\n </li>\n )\n}\n\nexport function DocumentStructurePanel({ attachmentId, canManage }: DocumentStructurePanelProps) {\n const t = useT()\n const allowManage = useCanManageStructure(canManage)\n const [structure, setStructure] = React.useState<StructureResponse | null>(null)\n const [loadError, setLoadError] = React.useState<string | null>(null)\n const [reloadToken, setReloadToken] = React.useState(0)\n const [pollCount, setPollCount] = React.useState(0)\n const [awaitingFromId, setAwaitingFromId] = React.useState<string | null | undefined>(undefined)\n const [requesting, setRequesting] = React.useState(false)\n const [loadedChildren, setLoadedChildren] = React.useState<Record<string, LoadedChildren>>({})\n const [loadingNodes, setLoadingNodes] = React.useState<ReadonlySet<string>>(new Set())\n const [expandedNodes, setExpandedNodes] = React.useState<ReadonlySet<string>>(new Set())\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n attachmentId: string\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: `attachment-structure:${attachmentId}` })\n\n const extractionId = structure?.extraction?.id ?? null\n\n React.useEffect(() => {\n let cancelled = false\n const load = async () => {\n try {\n const call = await apiCall<StructureResponse>(\n `${structureUrl(attachmentId)}?includeOutline=true&maxDepth=${OUTLINE_MAX_DEPTH}`,\n )\n if (cancelled) return\n if (!call.ok || !call.result) {\n setLoadError(t('attachments.structure.loadError', 'Failed to load the document structure.'))\n return\n }\n setLoadError(null)\n setStructure(call.result)\n } catch {\n if (!cancelled) setLoadError(t('attachments.structure.loadError', 'Failed to load the document structure.'))\n }\n }\n void load()\n return () => {\n cancelled = true\n }\n }, [attachmentId, reloadToken, t])\n\n React.useEffect(() => {\n setLoadedChildren({})\n setLoadingNodes(new Set())\n setExpandedNodes(new Set())\n }, [attachmentId, extractionId])\n\n const status = structure?.extraction?.status ?? null\n const awaiting = awaitingFromId !== undefined\n React.useEffect(() => {\n if (!structure || awaitingFromId === undefined) return\n const current = structure.extraction\n if (current && (current.id !== awaitingFromId || ACTIVE_STATUSES.has(current.status))) {\n setAwaitingFromId(undefined)\n }\n }, [awaitingFromId, structure])\n\n const shouldPoll = (awaiting || (status !== null && ACTIVE_STATUSES.has(status))) && pollCount < MAX_POLLS\n React.useEffect(() => {\n if (!shouldPoll) return\n const timer = setTimeout(() => {\n setPollCount((count) => count + 1)\n setReloadToken((token) => token + 1)\n }, POLL_INTERVAL_MS)\n return () => clearTimeout(timer)\n }, [shouldPoll, reloadToken])\n\n const outlineIndex = React.useMemo(() => {\n const outline = structure?.outline ?? []\n const ids = new Set(outline.map((node) => node.id))\n const byParent = new Map<string, DocumentStructureNode[]>()\n const roots: DocumentStructureNode[] = []\n for (const node of outline) {\n if (node.parentId && ids.has(node.parentId)) {\n const siblings = byParent.get(node.parentId) ?? []\n siblings.push(node)\n byParent.set(node.parentId, siblings)\n } else {\n roots.push(node)\n }\n }\n return { roots, byParent, rootIds: new Set(roots.map((node) => node.id)) }\n }, [structure])\n\n const childrenOf = React.useCallback(\n (nodeId: string) => {\n if (outlineIndex.rootIds.has(nodeId)) {\n return { items: outlineIndex.byParent.get(nodeId) ?? [], known: true, nextCursor: null }\n }\n const loaded = loadedChildren[nodeId]\n if (!loaded) return { items: [], known: false, nextCursor: null }\n return { items: loaded.items, known: true, nextCursor: loaded.nextCursor }\n },\n [loadedChildren, outlineIndex],\n )\n\n const fetchChildren = React.useCallback(\n async (nodeId: string, afterOrdinal: number | null) => {\n setLoadingNodes((current) => new Set(current).add(nodeId))\n const params = new URLSearchParams({\n parentId: nodeId,\n includeText: 'false',\n limit: String(CHILDREN_PAGE_SIZE),\n kinds: OUTLINE_KINDS,\n })\n if (afterOrdinal !== null) params.set('afterOrdinal', String(afterOrdinal))\n try {\n const call = await apiCall<SectionsResponse>(`${structureUrl(attachmentId)}/sections?${params.toString()}`)\n if (!call.ok || !call.result) throw new Error('[internal] document sections request failed')\n const page = call.result\n setLoadedChildren((current) => ({\n ...current,\n [nodeId]: {\n items: [...(afterOrdinal !== null ? current[nodeId]?.items ?? [] : []), ...page.items],\n nextCursor: page.nextCursor,\n },\n }))\n } catch {\n flash(t('attachments.structure.outline.loadError', 'Failed to load subsections.'), 'error')\n } finally {\n setLoadingNodes((current) => {\n const next = new Set(current)\n next.delete(nodeId)\n return next\n })\n }\n },\n [attachmentId, t],\n )\n\n const isExpanded = React.useCallback(\n (nodeId: string) => (outlineIndex.rootIds.has(nodeId) ? !expandedNodes.has(nodeId) : expandedNodes.has(nodeId)),\n [expandedNodes, outlineIndex],\n )\n const isLoading = React.useCallback((nodeId: string) => loadingNodes.has(nodeId), [loadingNodes])\n\n const handleToggle = React.useCallback(\n (nodeId: string) => {\n setExpandedNodes((current) => {\n const next = new Set(current)\n if (next.has(nodeId)) next.delete(nodeId)\n else next.add(nodeId)\n return next\n })\n if (!outlineIndex.rootIds.has(nodeId) && !loadedChildren[nodeId] && !loadingNodes.has(nodeId)) {\n void fetchChildren(nodeId, null)\n }\n },\n [fetchChildren, loadedChildren, loadingNodes, outlineIndex],\n )\n\n const handleLoadMore = React.useCallback(\n (nodeId: string) => {\n const cursor = loadedChildren[nodeId]?.nextCursor\n if (cursor === null || cursor === undefined) return\n void fetchChildren(nodeId, cursor)\n },\n [fetchChildren, loadedChildren],\n )\n\n const handleRefresh = React.useCallback(() => {\n setPollCount(0)\n setReloadToken((token) => token + 1)\n }, [])\n\n const handleExtract = React.useCallback(async () => {\n const force = Boolean(structure?.extraction)\n const previousId = structure?.extraction?.id ?? null\n setRequesting(true)\n try {\n const call = await runMutation({\n operation: async () => {\n const response = await apiCall<RequestResponse>(structureUrl(attachmentId), {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ force }),\n })\n if (!response.ok) {\n const serverMessage = typeof response.result?.error === 'string' ? response.result.error : null\n throw new Error(serverMessage ?? t('attachments.structure.flash.requestError', 'Failed to request document structure extraction.'))\n }\n return response\n },\n context: { formId: `attachment-structure:${attachmentId}`, attachmentId, retryLastMutation },\n mutationPayload: { force },\n })\n if (call.status === 202) {\n setAwaitingFromId(previousId)\n flash(t('attachments.structure.flash.requested', 'Document structure extraction queued.'), 'success')\n } else {\n flash(t('attachments.structure.flash.current', 'The document structure is already up to date.'), 'success')\n }\n setPollCount(0)\n setReloadToken((token) => token + 1)\n } catch (error) {\n const message = error instanceof Error && error.message && !error.message.startsWith('[internal]')\n ? error.message\n : t('attachments.structure.flash.requestError', 'Failed to request document structure extraction.')\n flash(message, 'error')\n } finally {\n setRequesting(false)\n }\n }, [attachmentId, retryLastMutation, runMutation, structure, t])\n\n if (loadError && !structure) {\n return (\n <ErrorMessage\n label={loadError}\n action={\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={handleRefresh}>\n {t('attachments.structure.actions.refresh', 'Refresh')}\n </Button>\n }\n />\n )\n }\n if (!structure) {\n return <LoadingMessage label={t('attachments.structure.loading', 'Loading document structure\u2026')} />\n }\n\n const extraction = structure.extraction\n const displayStatus: DocumentStructureStatus | null = awaiting ? 'pending' : status\n const busy = requesting || (displayStatus !== null && ACTIVE_STATUSES.has(displayStatus))\n const extractButton = allowManage ? (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={() => void handleExtract()} disabled={busy}>\n {extraction\n ? t('attachments.structure.actions.reextract', 'Re-extract')\n : t('attachments.structure.actions.extract', 'Extract structure')}\n </Button>\n ) : null\n\n return (\n <div className=\"space-y-3\" data-testid=\"document-structure-panel\">\n <div className=\"flex flex-wrap items-center justify-between gap-2\">\n <div className=\"flex min-w-0 flex-wrap items-center gap-2\">\n <span className=\"text-sm font-semibold\">{t('attachments.structure.outline.title', 'Document outline')}</span>\n {displayStatus ? (\n <StatusBadge variant={statusVariants[displayStatus]} dot>\n {t(...statusLabels[displayStatus])}\n </StatusBadge>\n ) : null}\n {extraction?.pageCount ? (\n <span className=\"text-xs text-muted-foreground\">\n {t('attachments.structure.summary', '{pages} pages \u2014 {sections} sections', {\n pages: extraction.pageCount,\n sections: extraction.sectionCount ?? 0,\n })}\n </span>\n ) : null}\n </div>\n <div className=\"flex items-center gap-2\">\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n aria-label={t('attachments.structure.actions.refresh', 'Refresh')}\n onClick={handleRefresh}\n >\n <RefreshCw className=\"size-4\" />\n </IconButton>\n {extraction ? extractButton : null}\n </div>\n </div>\n {loadError ? <ErrorMessage label={loadError} /> : null}\n {extraction?.skipReason && skipReasonLabels[extraction.skipReason] ? (\n <p className=\"text-sm text-muted-foreground\">{t(...skipReasonLabels[extraction.skipReason])}</p>\n ) : null}\n {extraction?.status === 'failed' ? (\n <p className=\"text-sm text-muted-foreground\">\n {t('attachments.structure.failedHint', 'The extraction failed. Try extracting the structure again.')}\n </p>\n ) : null}\n {!extraction ? (\n <EmptyState\n variant=\"subtle\"\n size=\"sm\"\n icon={<FileSearch className=\"size-5\" aria-hidden=\"true\" />}\n title={\n awaiting\n ? t('attachments.structure.empty.queuedTitle', 'Extraction queued')\n : t('attachments.structure.empty.title', 'Structure not extracted yet')\n }\n description={t('attachments.structure.empty.description', 'Extract the document structure to browse its chapters and sections.')}\n actions={extractButton}\n />\n ) : outlineIndex.roots.length > 0 ? (\n <ul className=\"max-h-96 space-y-1 overflow-y-auto\">\n {outlineIndex.roots.map((node) => (\n <OutlineNodeItem\n key={node.id}\n node={node}\n childrenOf={childrenOf}\n isExpanded={isExpanded}\n isLoading={isLoading}\n onToggle={handleToggle}\n onLoadMore={handleLoadMore}\n />\n ))}\n </ul>\n ) : ACTIVE_STATUSES.has(extraction.status) || extraction.status === 'skipped' || extraction.status === 'failed' ? null : (\n <EmptyState\n variant=\"subtle\"\n size=\"sm\"\n icon={<FileSearch className=\"size-5\" aria-hidden=\"true\" />}\n title={t('attachments.structure.outline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A,MAAC;AAAA;AAAA,QACC,SAAQ;AAAA,QACR,MAAK;AAAA,QACL,MAAM,oBAAC,cAAW,WAAU,UAAS,eAAY,QAAO;AAAA,QACxD,OAAO,EAAE,uCAAuC,0CAA0C;AAAA;AAAA,IAC5F;AAAA,KAEJ;AAEJ;AAEA,IAAO,iCAAQ;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/ui",
3
- "version": "0.10.1-develop.8278.1.f7f8e5ab1a",
3
+ "version": "0.10.1-develop.8287.1.7313a0fe67",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -156,14 +156,14 @@
156
156
  "remark-gfm": "^4.0.1"
157
157
  },
158
158
  "peerDependencies": {
159
- "@open-mercato/shared": "0.10.1-develop.8278.1.f7f8e5ab1a",
159
+ "@open-mercato/shared": "0.10.1-develop.8287.1.7313a0fe67",
160
160
  "react": ">=18.0.0",
161
161
  "react-dom": ">=18.0.0",
162
162
  "react-is": ">=18.0.0"
163
163
  },
164
164
  "devDependencies": {
165
165
  "@figma/code-connect": "^1.3.4",
166
- "@open-mercato/shared": "0.10.1-develop.8278.1.f7f8e5ab1a",
166
+ "@open-mercato/shared": "0.10.1-develop.8287.1.7313a0fe67",
167
167
  "@testing-library/dom": "^10.4.1",
168
168
  "@testing-library/jest-dom": "^7.0.1",
169
169
  "@testing-library/react": "^16.3.3",
package/src/ai/AiChat.tsx CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  Wrench,
35
35
  X,
36
36
  } from 'lucide-react'
37
+ import Link from 'next/link'
37
38
  import ReactMarkdown from 'react-markdown'
38
39
  import { useT } from '@open-mercato/shared/lib/i18n/context'
39
40
  import { cn } from '@open-mercato/shared/lib/utils'
@@ -64,6 +65,7 @@ import {
64
65
  type AiUiPartComponentId,
65
66
  type AiUiPartRegistry,
66
67
  } from './ui-part-registry'
68
+ import { mergeConsecutiveCitationParts } from './citations/merge'
67
69
  import {
68
70
  useAiChat,
69
71
  type AiAgentTaskSnapshot,
@@ -75,6 +77,7 @@ import {
75
77
  import { useAiChatUpload } from './useAiChatUpload'
76
78
  import { useAiShortcuts } from './useAiShortcuts'
77
79
  import { LoopTracePanel, type LoopTracePanelTrace } from './LoopTracePanel'
80
+ import { buildAiRunTraceHref, useCanViewAiRunTrace } from './run-trace-link'
78
81
  import { AiIcon } from './AiIcon'
79
82
  import { readModelPickerValue, writeModelPickerValue } from './modelPickerStorage'
80
83
  import { createLogger } from '@open-mercato/shared/lib/logger'
@@ -840,6 +843,9 @@ function MessageRow({
840
843
  ? t('ai_assistant.chat.ownerRoleLabel', 'Owner')
841
844
  : t('ai_assistant.chat.userRoleLabel', 'You')
842
845
  const Icon = isAssistant ? Bot : User
846
+ const canViewRunTrace = useCanViewAiRunTrace()
847
+ const runTraceHref =
848
+ isAssistant && message.runId && canViewRunTrace ? buildAiRunTraceHref(message.runId) : null
843
849
  const [copied, setCopied] = React.useState(false)
844
850
  const copyTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)
845
851
  const visibleTaskPlan =
@@ -900,27 +906,46 @@ function MessageRow({
900
906
  <div className="flex-1 space-y-1">
901
907
  <div className="flex items-center justify-between gap-2">
902
908
  <div className="text-xs font-medium text-muted-foreground">{label}</div>
903
- {message.content ? (
904
- <IconButton
905
- type="button"
906
- variant="ghost"
907
- size="sm"
908
- onClick={handleCopy}
909
- aria-label={
910
- copied
911
- ? t('ai_assistant.chat.copied', 'Copied')
912
- : t('ai_assistant.chat.copyMessage', 'Copy message')
913
- }
914
- data-ai-chat-copy-button=""
915
- className="opacity-0 transition-opacity group-hover/message:opacity-100 focus-visible:opacity-100"
916
- >
917
- {copied ? (
918
- <Check className="size-3.5 text-status-success-icon" aria-hidden />
919
- ) : (
920
- <Copy className="size-3.5" aria-hidden />
921
- )}
922
- </IconButton>
923
- ) : null}
909
+ <div className="flex items-center gap-1">
910
+ {runTraceHref ? (
911
+ <IconButton
912
+ asChild
913
+ variant="ghost"
914
+ size="sm"
915
+ className="opacity-0 transition-opacity group-hover/message:opacity-100 focus-visible:opacity-100"
916
+ >
917
+ <Link
918
+ href={runTraceHref}
919
+ aria-label={t('ai_assistant.chat.viewRunTrace', 'View run trace')}
920
+ title={t('ai_assistant.chat.viewRunTrace', 'View run trace')}
921
+ data-ai-chat-run-trace-link={message.runId}
922
+ >
923
+ <Activity className="size-3.5" aria-hidden />
924
+ </Link>
925
+ </IconButton>
926
+ ) : null}
927
+ {message.content ? (
928
+ <IconButton
929
+ type="button"
930
+ variant="ghost"
931
+ size="sm"
932
+ onClick={handleCopy}
933
+ aria-label={
934
+ copied
935
+ ? t('ai_assistant.chat.copied', 'Copied')
936
+ : t('ai_assistant.chat.copyMessage', 'Copy message')
937
+ }
938
+ data-ai-chat-copy-button=""
939
+ className="opacity-0 transition-opacity group-hover/message:opacity-100 focus-visible:opacity-100"
940
+ >
941
+ {copied ? (
942
+ <Check className="size-3.5 text-status-success-icon" aria-hidden />
943
+ ) : (
944
+ <Copy className="size-3.5" aria-hidden />
945
+ )}
946
+ </IconButton>
947
+ ) : null}
948
+ </div>
924
949
  </div>
925
950
  {message.files && message.files.length > 0 ? (
926
951
  <div className="flex flex-wrap gap-2 py-1">
@@ -965,7 +990,7 @@ function MessageUiParts({
965
990
  }) {
966
991
  return (
967
992
  <div className="mt-2 flex flex-col gap-2" data-ai-message-ui-parts="">
968
- {parts.map((part) => (
993
+ {mergeConsecutiveCitationParts(parts).map((part) => (
969
994
  <AiUiPartRenderer
970
995
  key={part.key}
971
996
  part={{