@vibefield/rosetta-room 0.1.1 → 0.1.3

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 (115) hide show
  1. package/README.md +82 -4
  2. package/dist/HistoryRoom.d.ts +15 -2
  3. package/dist/HistoryRoom.js +84 -27
  4. package/dist/TranscriptReader.d.ts +7 -0
  5. package/dist/TranscriptReader.js +4 -4
  6. package/dist/components/ColdStart.js +1 -1
  7. package/dist/components/IngestStatus.d.ts +13 -0
  8. package/dist/components/IngestStatus.js +40 -3
  9. package/dist/components/IngestionControls.d.ts +6 -0
  10. package/dist/components/IngestionControls.js +75 -0
  11. package/dist/components/ListActivityNotice.d.ts +9 -1
  12. package/dist/components/ListActivityNotice.js +9 -2
  13. package/dist/components/SummaryPanels.d.ts +5 -0
  14. package/dist/components/SummaryPanels.js +16 -5
  15. package/dist/components/Transcript.d.ts +5 -0
  16. package/dist/components/Transcript.js +20 -5
  17. package/dist/components/artifacts/ArtifactLibrary.d.ts +14 -0
  18. package/dist/components/artifacts/ArtifactLibrary.js +156 -0
  19. package/dist/components/artifacts/content.d.ts +8 -0
  20. package/dist/components/artifacts/content.js +27 -0
  21. package/dist/components/artifacts/load-all.d.ts +5 -0
  22. package/dist/components/artifacts/load-all.js +31 -0
  23. package/dist/components/artifacts/preview.d.ts +4 -0
  24. package/dist/components/artifacts/preview.js +37 -0
  25. package/dist/components/artifacts/thumbnails.d.ts +13 -0
  26. package/dist/components/artifacts/thumbnails.js +43 -0
  27. package/dist/components/projects/ProjectList.d.ts +9 -3
  28. package/dist/components/projects/ProjectList.js +3 -3
  29. package/dist/components/projects/ProjectListItem.d.ts +9 -3
  30. package/dist/components/projects/ProjectListItem.js +18 -12
  31. package/dist/components/projects/ProjectsColumn.d.ts +4 -1
  32. package/dist/components/projects/ProjectsColumn.js +23 -9
  33. package/dist/components/search/SearchSheet.d.ts +39 -2
  34. package/dist/components/search/SearchSheet.js +82 -17
  35. package/dist/components/sessions/SessionList.d.ts +6 -1
  36. package/dist/components/sessions/SessionList.js +50 -20
  37. package/dist/components/sessions/SessionListItem.d.ts +3 -1
  38. package/dist/components/sessions/SessionListItem.js +17 -7
  39. package/dist/components/sessions/SessionsColumn.d.ts +3 -1
  40. package/dist/components/sessions/SessionsColumn.js +2 -2
  41. package/dist/components/sessions/session-display.d.ts +4 -1
  42. package/dist/components/sessions/session-display.js +13 -2
  43. package/dist/components/transcript/Attachments.js +6 -1
  44. package/dist/components/transcript/Document.d.ts +6 -1
  45. package/dist/components/transcript/Document.js +19 -6
  46. package/dist/components/transcript/ImportState.d.ts +35 -0
  47. package/dist/components/transcript/ImportState.js +86 -0
  48. package/dist/components/transcript/TranscriptLoading.js +15 -5
  49. package/dist/components/transcript/attachment-file-source.d.ts +2 -0
  50. package/dist/components/transcript/attachment-file-source.js +6 -6
  51. package/dist/components/transcript/attachment-gallery.d.ts +2 -1
  52. package/dist/components/transcript/attachment-gallery.js +2 -1
  53. package/dist/components/transcript/detail-parts.js +7 -6
  54. package/dist/components/transcript/timeline-meta-file-source.d.ts +2 -1
  55. package/dist/components/transcript/timeline-meta-file-source.js +45 -5
  56. package/dist/components/ui/EmptyState.d.ts +5 -1
  57. package/dist/components/ui/EmptyState.js +2 -2
  58. package/dist/components/ui/Meter.d.ts +8 -0
  59. package/dist/components/ui/Meter.js +9 -0
  60. package/dist/components/ui/SegmentedControl.d.ts +2 -0
  61. package/dist/components/ui/SegmentedControl.js +1 -1
  62. package/dist/components/ui/Veil.d.ts +2 -1
  63. package/dist/components/ui/Veil.js +9 -2
  64. package/dist/components/ui/index.d.ts +2 -0
  65. package/dist/components/ui/index.js +1 -0
  66. package/dist/fixtures/cold-import-corpus.d.ts +76 -0
  67. package/dist/fixtures/cold-import-corpus.js +349 -0
  68. package/dist/fixtures/cold-import-daemon.d.ts +25 -0
  69. package/dist/fixtures/cold-import-daemon.js +82 -0
  70. package/dist/fixtures/cold-import-schedule.d.ts +74 -0
  71. package/dist/fixtures/cold-import-schedule.js +191 -0
  72. package/dist/fixtures/cold-import.d.ts +151 -0
  73. package/dist/fixtures/cold-import.js +786 -0
  74. package/dist/fixtures/index.d.ts +2 -0
  75. package/dist/fixtures/index.js +21 -2
  76. package/dist/index.d.ts +1 -1
  77. package/dist/index.js +5 -0
  78. package/dist/lib/activity-order.d.ts +15 -0
  79. package/dist/lib/activity-order.js +24 -1
  80. package/dist/lib/conversation-readiness.d.ts +48 -0
  81. package/dist/lib/conversation-readiness.js +149 -0
  82. package/dist/lib/figure-order.d.ts +35 -0
  83. package/dist/lib/figure-order.js +68 -0
  84. package/dist/lib/hooks.d.ts +32 -10
  85. package/dist/lib/hooks.js +122 -55
  86. package/dist/lib/image-media.d.ts +12 -2
  87. package/dist/lib/image-media.js +40 -6
  88. package/dist/lib/import-state.d.ts +98 -0
  89. package/dist/lib/import-state.js +129 -0
  90. package/dist/lib/ingest-activity.d.ts +52 -0
  91. package/dist/lib/ingest-activity.js +127 -12
  92. package/dist/lib/ingest.d.ts +3 -0
  93. package/dist/lib/ingest.js +10 -0
  94. package/dist/lib/model.d.ts +16 -0
  95. package/dist/lib/model.js +27 -1
  96. package/dist/lib/search-sheet.d.ts +43 -0
  97. package/dist/lib/search-sheet.js +56 -7
  98. package/dist/lib/session-activity.d.ts +4 -1
  99. package/dist/lib/session-activity.js +4 -1
  100. package/dist/lib/title-search.d.ts +82 -0
  101. package/dist/lib/title-search.js +194 -0
  102. package/dist/lib/transcript/images.js +2 -2
  103. package/dist/lib/use-deferred-list-order.d.ts +6 -0
  104. package/dist/lib/use-deferred-list-order.js +8 -1
  105. package/dist/lib/use-ingest-activity.d.ts +5 -1
  106. package/dist/lib/use-ingest-activity.js +56 -20
  107. package/dist/ports.d.ts +21 -2
  108. package/dist/room-context.d.ts +1 -0
  109. package/dist/room-context.js +3 -2
  110. package/dist/styles/artifacts.css +66 -0
  111. package/dist/styles/history-room.css +1 -0
  112. package/dist/styles/ingest.css +32 -3
  113. package/dist/styles/room.css +15 -0
  114. package/dist/styles/search.css +17 -0
  115. package/package.json +2 -2
@@ -0,0 +1,75 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { ApiRequestError } from "@vibefield/rosetta-protocol";
4
+ import { useRoom } from "../room-context.js";
5
+ /** A host may supply observation without mutation authority. Pending intent
6
+ * keeps its key, revision and index across uncertain transport outcomes. */
7
+ export function IngestionControls({ run }) {
8
+ const { ingestion } = useRoom();
9
+ const [intent, setIntent] = useState(null);
10
+ const [busy, setBusy] = useState(false);
11
+ const [error, setError] = useState(null);
12
+ const pending = useRef(null);
13
+ useEffect(() => {
14
+ setIntent(null);
15
+ setBusy(false);
16
+ setError(null);
17
+ return () => {
18
+ pending.current?.abort();
19
+ pending.current = null;
20
+ };
21
+ }, [run?.index_id, run?.id, ingestion]);
22
+ useEffect(() => {
23
+ if (!intent || !run || run.revision <= intent.command.expected_revision)
24
+ return;
25
+ const settled = intent.action === "pause" ? run.state === "paused" || run.state === "pausing" : run.state === "running";
26
+ if (settled) {
27
+ pending.current?.abort();
28
+ pending.current = null;
29
+ setIntent(null);
30
+ setBusy(false);
31
+ setError(null);
32
+ }
33
+ }, [intent, run]);
34
+ if (!ingestion || !run)
35
+ return null;
36
+ const action = intent?.action ?? run.allowed_actions[0];
37
+ if (!action)
38
+ return error ? _jsx("p", { role: "alert", children: error }) : null;
39
+ const submit = async () => {
40
+ if (pending.current)
41
+ return;
42
+ const next = intent ?? { id: run.id, action, command: {
43
+ indexId: run.index_id, expected_revision: run.revision, idempotencyKey: crypto.randomUUID(),
44
+ } };
45
+ const request = new AbortController();
46
+ pending.current = request;
47
+ setIntent(next);
48
+ setBusy(true);
49
+ setError(null);
50
+ try {
51
+ await ingestion[next.action](next.id, next.command, request.signal);
52
+ // The ordinary status poll supplies the observed state and progress.
53
+ if (pending.current === request)
54
+ setIntent(null);
55
+ }
56
+ catch (cause) {
57
+ if (pending.current !== request)
58
+ return;
59
+ if (cause instanceof ApiRequestError && cause.status >= 400 && cause.status < 500) {
60
+ setIntent(null);
61
+ setError("Import controls changed. Check the current state and try again.");
62
+ }
63
+ else {
64
+ setError("The service did not confirm this request. Retry to check its outcome.");
65
+ }
66
+ }
67
+ finally {
68
+ if (pending.current === request) {
69
+ pending.current = null;
70
+ setBusy(false);
71
+ }
72
+ }
73
+ };
74
+ return _jsxs("div", { className: "ah-ingest-controls", children: [_jsx("button", { type: "button", disabled: busy, onClick: () => { void submit(); }, children: busy ? "Sending…" : `${intent && error ? "Retry " : ""}${action === "pause" ? "Pause import" : "Resume import"}` }), error && _jsx("p", { role: "alert", children: error })] });
75
+ }
@@ -1,5 +1,13 @@
1
- export declare function ListActivityNotice({ pending, onShow, noun }: {
1
+ import type { ImportArrivals } from "../lib/import-state.js";
2
+ export declare function ListActivityNotice({ pending, onShow, noun, arrivals, importReorder }: {
2
3
  readonly pending: boolean;
3
4
  readonly onShow: () => void;
4
5
  readonly noun: "projects" | "sessions";
6
+ /** Conversations the import opened while the list was held: the pill
7
+ * counts them, and says "older" only when every one lands below the
8
+ * reader's view. */
9
+ readonly arrivals?: ImportArrivals | null;
10
+ /** The waiting order comes from the import opening conversations, not
11
+ * from new activity: the pill names the import as its cause. */
12
+ readonly importReorder?: boolean;
5
13
  }): import("react").JSX.Element;
@@ -1,4 +1,11 @@
1
1
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
- export function ListActivityNotice({ pending, onShow, noun }) {
3
- return (_jsxs(_Fragment, { children: [_jsx("span", { className: "ah-list-update-status", role: "status", children: pending ? `New activity is available in ${noun}.` : "" }), _jsx("button", { type: "button", className: "ah-newpill ah-list-updates", "data-list-updates": "", "data-visible": pending ? "" : undefined, hidden: !pending, onClick: onShow, children: "Show recent activity" })] }));
2
+ import { arrivalsLabel } from "../lib/import-state.js";
3
+ export function ListActivityNotice({ pending, onShow, noun, arrivals = null, importReorder = false }) {
4
+ const imported = pending && arrivals !== null ? arrivalsLabel(arrivals) : null;
5
+ const byImport = pending && imported === null && importReorder;
6
+ const Noun = `${noun.charAt(0).toUpperCase()}${noun.slice(1)}`;
7
+ return (_jsxs(_Fragment, { children: [_jsx("span", { className: "ah-list-update-status", role: "status", children: !pending ? "" : imported !== null
8
+ ? `Newly imported conversations are available in ${noun}.`
9
+ : byImport ? `${Noun} were reordered by the import.`
10
+ : `New activity is available in ${noun}.` }), _jsx("button", { type: "button", className: "ah-newpill ah-list-updates", "data-list-updates": "", "data-visible": pending ? "" : undefined, hidden: !pending, onClick: onShow, children: imported !== null ? `${imported} — show` : byImport ? `${Noun} reordered by the import · show` : "Show recent activity" })] }));
4
11
  }
@@ -20,6 +20,11 @@ export interface ProjectSummaryPanelProps {
20
20
  /** R5: the host's acts, after the head's own (New agent, the primary, last). */
21
21
  readonly hostActs?: readonly RoomAct[] | null | undefined;
22
22
  }
23
+ /** The veil's words while an import runs. Every figure waits on one global
24
+ * gate — the daemon publishes aggregates only once the whole import has
25
+ * finished (http.rs `is_published`) — so it names that gate, never work on
26
+ * this project. */
27
+ export declare const CHARTS_AFTER_IMPORT = "Charts appear when the whole import finishes";
23
28
  export declare function ProjectSummaryPanel({ project, visibleSessionCount, usage, activityGridStartTimestamp, currentTimestamp, ingestActive, censusRunning, isWorktreeVisible, onToggleWorktree, hostActs, }: ProjectSummaryPanelProps): import("react").JSX.Element;
24
29
  export interface PortfolioSummaryPanelProps {
25
30
  readonly projects: readonly ProjectViewModel[];
@@ -17,6 +17,7 @@ import { useRoom } from "../room-context.js";
17
17
  import { useHostInputs } from "../host-inputs.js";
18
18
  import { HostAct } from "./HostAct.js";
19
19
  import { RenameHeading } from "./RenameHeading.js";
20
+ import { failedFiguresLine } from "../lib/figure-order.js";
20
21
  const MAX_TREEMAP_PROJECT_COUNT = 10;
21
22
  // Matches the project chart's 25px selector track, 9px gap, and 106px chart body.
22
23
  const SUMMARY_CHART_CONTENT_HEIGHT = 140;
@@ -34,6 +35,11 @@ function formatHourLabel(hour) {
34
35
  return "12 PM";
35
36
  return `${hour - 12} PM`;
36
37
  }
38
+ /** The veil's words while an import runs. Every figure waits on one global
39
+ * gate — the daemon publishes aggregates only once the whole import has
40
+ * finished (http.rs `is_published`) — so it names that gate, never work on
41
+ * this project. */
42
+ export const CHARTS_AFTER_IMPORT = "Charts appear when the whole import finishes";
37
43
  export function ProjectSummaryPanel({ project, visibleSessionCount, usage, activityGridStartTimestamp, currentTimestamp, ingestActive, censusRunning, isWorktreeVisible, onToggleWorktree, hostActs = null, }) {
38
44
  // Aggregate figures become available after canonical publication and
39
45
  // their own requests finish, independently of transcript readiness.
@@ -68,8 +74,9 @@ export function ProjectSummaryPanel({ project, visibleSessionCount, usage, activ
68
74
  return (_jsxs("div", { className: "ah-meta", style: { "--tint": project.tint }, children: [_jsxs("div", { className: "ah-meta__head", children: [rename === null ? (_jsx(ColumnHeading, { name: project.row.name, tint: project.tint, count: visibleSessionCount, countTitle: `${visibleSessionCount} sessions in this list` })) : (_jsx(RenameHeading, { name: project.row.name, tint: project.tint, count: visibleSessionCount, countTitle: `${visibleSessionCount} sessions in this list`, rename: rename }, project.row.id)), _jsxs("span", { className: "ah-meta__acts", children: [isWorktreeVisible !== null && (_jsx("button", { type: "button", className: "ah-iconbtn", "aria-pressed": isWorktreeVisible, title: isWorktreeVisible ? "Hide the worktree" : "Show the worktree", "aria-label": "Toggle the project worktree", onClick: onToggleWorktree, children: _jsx(TreeGlyph, {}) })), _jsx("button", { type: "button", className: "ah-iconbtn", "aria-pressed": isExpanded, title: isExpanded ? "Hide the figures" : "Show the figures", "aria-label": "Toggle the figures", onClick: () => setIsExpanded((current) => !current), children: _jsx(StatsGlyph, {}) }), repositoryUrl !== null && (_jsx("button", { type: "button", className: "ah-iconbtn", title: `Open ${repositoryUrl}`, "aria-label": "Open the git repository", onClick: () => window.open(repositoryUrl.includes("://")
69
75
  ? repositoryUrl
70
76
  : `https://${repositoryUrl}`), children: _jsx(GitHubGlyph, {}) })), hostActs?.map((act) => _jsx(HostAct, { act: act, place: "head" }, act.key))] })] }), isExpanded && (_jsxs("div", { className: "ah-meta__body ah-veilhost", children: [isVeiled && (_jsx(Veil, { label: ingestActive
71
- ? censusRunning ? "Discovering conversations…" : "Preparing activity summaries…"
72
- : "Loading activity summaries…", progress: null })), _jsx(SummaryMetrics, { sessionCount: project.rootSessionCount, messageCount: project.lifetimeMessages, tokenCount: project.tokensLast53Weeks, spend: project.spendLast53Weeks, pending: isVeiled, period: "53 weeks" }), _jsxs("div", { className: "ah-chartcard", children: [_jsx(SegmentedControl, { value: activeChart, options: PROJECT_CHART_OPTIONS, accessibleLabel: "Project chart", className: "ah-tabseg", onValueChange: setActiveChart }), _jsx("div", { className: "ah-tabbody", children: activeChart === "models" ? (_jsxs("div", { className: "ah-chart-launcher ah-chart-launcher--models", children: [_jsx(Streamgraph, { data: modelUsageData, title: "Tokens per day \u00B7 30 days", note: "no zero \u00B7 thickness is the total", ariaLabel: "Tokens per day by model over 30 days, shown as a wiggle-minimised streamgraph", emptyMessage: usage ? "No model-attributed usage in this window" : "Loading model usage…", formatValue: tokenText }), _jsx("button", { type: "button", className: "ah-chart-launcher__button", "aria-label": `Expand models chart for ${project.row.name}`, "aria-haspopup": "dialog", disabled: isVeiled || usage === null, onClick: () => setExpandedChart("models"), children: _jsxs("span", { className: "ah-chart-launcher__hint", children: [_jsx(FullscreenGlyph, {}), " Expand"] }) })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "ah-chart-launcher", children: [_jsx(CalendarHeatmap, { data: heatmapData, color: project.tint, ariaLabel: `Daily token activity for ${project.row.name} over 53 weeks`, summary: `${isVeiled && activityStats.activeDayCount === 0
77
+ ? censusRunning ? "Discovering conversations…" : CHARTS_AFTER_IMPORT
78
+ : project.statsFailed === true ? "Figures for this project failed · retrying"
79
+ : "Loading activity summaries…", progress: null })), _jsx(SummaryMetrics, { sessionCount: project.rootSessionCount, messageCount: project.lifetimeMessages, tokenCount: project.tokensLast53Weeks, spend: project.spendLast53Weeks, pending: isVeiled, period: "53 weeks" }), _jsxs("div", { className: "ah-chartcard", children: [_jsx(SegmentedControl, { value: activeChart, options: PROJECT_CHART_OPTIONS, accessibleLabel: "Project chart", className: "ah-tabseg", onValueChange: setActiveChart }), _jsx("div", { className: "ah-tabbody", children: activeChart === "models" ? (_jsxs("div", { className: "ah-chart-launcher ah-chart-launcher--models", children: [_jsx(Streamgraph, { data: modelUsageData, title: "Tokens per day \u00B7 30 days", note: "no zero \u00B7 thickness is the total", ariaLabel: "Tokens per day by model over 30 days, shown as a wiggle-minimised streamgraph", emptyMessage: usage ? "No model-attributed usage in this window" : "Loading model usage…", formatValue: tokenText }), _jsx("button", { type: "button", className: "ah-chart-launcher__button", "aria-label": `Expand models chart for ${project.row.name}`, "aria-haspopup": "dialog", disabled: isVeiled || usage === null, onClick: () => setExpandedChart("models"), children: _jsxs("span", { className: "ah-chart-launcher__hint", children: [_jsx(FullscreenGlyph, {}), " Expand"] }) })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "ah-chart-launcher", children: [_jsx(CalendarHeatmap, { data: heatmapData, color: project.tint, ariaLabel: `Daily token activity for ${project.row.name} over 53 weeks`, summary: `${isVeiled && activityStats.activeDayCount === 0
73
80
  ? "—"
74
81
  : activityStats.activeDayCount} active days · 53 weeks` }), _jsx("button", { type: "button", className: "ah-chart-launcher__button", "aria-label": `Expand activity chart for ${project.row.name}`, "aria-haspopup": "dialog", disabled: isVeiled, onClick: () => setExpandedChart("activity"), children: _jsxs("span", { className: "ah-chart-launcher__hint", children: [_jsx(FullscreenGlyph, {}), " Expand"] }) })] }), _jsxs("p", { className: "ah-meta__facts", children: [_jsx("b", { children: isVeiled && activityStats.longestStreakLength === 0
75
82
  ? "—"
@@ -79,7 +86,11 @@ export function ProjectSummaryPanel({ project, visibleSessionCount, usage, activ
79
86
  }
80
87
  export function PortfolioSummaryPanel({ projects, selectedProjectId, ingestActive, censusRunning, onProjectSelect, }) {
81
88
  const [isExpanded, setIsExpanded] = useState(true);
82
- const summariesPending = ingestActive || projects.some((project) => !project.statsReady);
89
+ // A project whose figures failed no longer holds the veil up: the rest
90
+ // show, and a line says how many are missing while they are retried.
91
+ const failedCount = ingestActive ? 0 : projects.filter((project) => project.statsFailed === true).length;
92
+ const summariesPending = ingestActive ||
93
+ projects.some((project) => !project.statsReady && project.statsFailed !== true);
83
94
  const summary = useMemo(() => {
84
95
  // Match the project list's lifetime spend ranking, tokens breaking ties.
85
96
  const treemapProjects = [...projects]
@@ -110,8 +121,8 @@ export function PortfolioSummaryPanel({ projects, selectedProjectId, ingestActiv
110
121
  };
111
122
  }, [projects]);
112
123
  return (_jsxs("div", { className: "ah-meta", children: [_jsxs("div", { className: "ah-meta__head", children: [_jsx(ColumnHeading, { name: "Projects", tint: "var(--vf-text-tertiary)", title: null, count: projects.length, countTitle: `${projects.length} projects in this list` }), _jsx("span", { className: "ah-meta__acts", children: _jsx("button", { type: "button", className: "ah-iconbtn", "aria-pressed": isExpanded, title: isExpanded ? "Hide the figures" : "Show the figures", "aria-label": "Toggle the figures", onClick: () => setIsExpanded((current) => !current), children: _jsx(StatsGlyph, {}) }) })] }), isExpanded && (_jsxs("div", { className: "ah-meta__body ah-veilhost", children: [summariesPending && (_jsx(Veil, { label: ingestActive
113
- ? censusRunning ? "Discovering conversations…" : "Preparing activity summaries…"
114
- : "Loading activity summaries…", progress: null })), _jsx(SummaryMetrics, { sessionCount: summary.sessionCount, messageCount: summary.messageCount, tokenCount: summary.tokenCount, spend: summary.spend, pending: summariesPending, period: "all time" }), _jsxs("div", { className: "ah-chartcard", children: [_jsx(Treemap, { data: summary.treemapData, ariaLabel: "Top projects by lifetime estimated spend, where area represents share among displayed projects", emptyMessage: "No priced project usage", showFooter: false, height: SUMMARY_CHART_CONTENT_HEIGHT, minimumVisibleShare: 0, selectedItemId: selectedProjectId, onItemSelect: (item) => onProjectSelect(item.id), formatValue: usdText, getItemAccessibleLabel: (item, context) => `${item.label} · ${usdText(item.value)}${item.partial ? "+" : ""} estimated cost${item.partial ? " (a lower bound)" : ""} · ${(context.share * 100).toFixed(1)}% of displayed lifetime spend` }), summary.unpricedOnlyProjects > 0 && (_jsx("p", { className: "ah-treemap__empty", children: summary.unpricedOnlyProjects === 1
124
+ ? censusRunning ? "Discovering conversations…" : CHARTS_AFTER_IMPORT
125
+ : "Loading activity summaries…", progress: null })), _jsx(SummaryMetrics, { sessionCount: summary.sessionCount, messageCount: summary.messageCount, tokenCount: summary.tokenCount, spend: summary.spend, pending: summariesPending, period: "all time" }), !summariesPending && failedCount > 0 && (_jsx("p", { className: "ah-meta__facts", role: "status", "data-figures-failed": failedCount, children: failedFiguresLine(failedCount) })), _jsxs("div", { className: "ah-chartcard", children: [_jsx(Treemap, { data: summary.treemapData, ariaLabel: "Top projects by lifetime estimated spend, where area represents share among displayed projects", emptyMessage: "No priced project usage", showFooter: false, height: SUMMARY_CHART_CONTENT_HEIGHT, minimumVisibleShare: 0, selectedItemId: selectedProjectId, onItemSelect: (item) => onProjectSelect(item.id), formatValue: usdText, getItemAccessibleLabel: (item, context) => `${item.label} · ${usdText(item.value)}${item.partial ? "+" : ""} estimated cost${item.partial ? " (a lower bound)" : ""} · ${(context.share * 100).toFixed(1)}% of displayed lifetime spend` }), summary.unpricedOnlyProjects > 0 && (_jsx("p", { className: "ah-treemap__empty", children: summary.unpricedOnlyProjects === 1
115
126
  ? "1 project has usage with no list price and is not shown"
116
127
  : `${summary.unpricedOnlyProjects} projects have usage with no list price and are not shown` }))] })] }))] }));
117
128
  }
@@ -4,6 +4,7 @@ import type { TimelineFeed } from "../lib/hooks.js";
4
4
  import type { ProjectViewModel } from "../lib/model.js";
5
5
  import type { ThreadFocus } from "./transcript/thread-index.js";
6
6
  import type { RoomHeadActs } from "../host-inputs.js";
7
+ import type { ImportCourse } from "../lib/import-state.js";
7
8
  export type { ThreadFocus } from "./transcript/thread-index.js";
8
9
  /** The stepper's face: the query, where the reader is, how many there are. */
9
10
  export interface MatchStepperState {
@@ -15,6 +16,10 @@ export interface TranscriptColumnProps {
15
16
  readonly session: SessionRow | null;
16
17
  /** The cold backfill is running — threaded to every watermark. */
17
18
  readonly duringBackfill: boolean;
19
+ /** When the running import opens a session it has not reached. */
20
+ readonly importCourse?: ImportCourse | undefined;
21
+ /** The session's agent, as a `runtime-close` promise names it. */
22
+ readonly importAgent?: string | undefined;
18
23
  /** Full metadata topology. Only roots are navigable, but descendants are
19
24
  * needed here to build the embedded thread tree. */
20
25
  readonly sessions: readonly SessionRow[];
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { publishedArtifactUrl } from "./artifacts/preview.js";
2
3
  // Column ④ — the transcript: a document, not a chat log.
3
4
  //
4
5
  // The column is the frame; the document inside it is `components/transcript`.
@@ -47,6 +48,7 @@ import { scrollRowTo } from "./transcript/scroll-to-row.js";
47
48
  import { HostAct } from "./HostAct.js";
48
49
  import { activityCuts } from "./transcript/activity-plan.js";
49
50
  import { ReadingSessionProvider, useRoom } from "../room-context.js";
51
+ import { NOT_IMPORTED_LABEL, importStanding } from "../lib/import-state.js";
50
52
  /** The receipt lands beneath a pinned day pill, never over it (§08).
51
53
  * Measured rather than guessed: the scroller starts 46px down (the head band),
52
54
  * a pinned pill occupies 58–80, and the first pill still in the flow starts at
@@ -57,8 +59,8 @@ export function TranscriptColumn(props) {
57
59
  // Reset them in the selection commit, before the previous session can paint.
58
60
  return (_jsx(ReadingSessionProvider, { value: props.session?.id ?? null, children: _jsx(SessionTranscript, { ...props }, props.session?.id ?? "no-session") }));
59
61
  }
60
- function SessionTranscript({ session, duringBackfill, sessions, project, feed, focus, onFocusConsumed, onReceipt, emptyPrompt, stepper, onStepMatch, onDismissStepper, getRuntimeKind, homeDirectory, onOpenThread, onBackToParent, reader = false, headActs = null, }) {
61
- const { sessions: leases, host } = useRoom();
62
+ function SessionTranscript({ session, duringBackfill, importCourse, importAgent, sessions, project, feed, focus, onFocusConsumed, onReceipt, emptyPrompt, stepper, onStepMatch, onDismissStepper, getRuntimeKind, homeDirectory, onOpenThread, onBackToParent, reader = false, headActs = null, }) {
63
+ const { sessions: leases, host, assets } = useRoom();
62
64
  const listBrowsers = useMemo(() => host?.browsers?.bind(host), [host]);
63
65
  const openInBrowser = useMemo(() => (host === null ? null : (name, bytes, browserId) => host.openInBrowser(name, bytes, browserId)), [host]);
64
66
  const attachments = useAttachmentReader();
@@ -169,7 +171,14 @@ function SessionTranscript({ session, duringBackfill, sessions, project, feed, f
169
171
  const openMetaArtifact = (artifact) => {
170
172
  if (session === null)
171
173
  return;
172
- openMetaFile(() => handleForTimelineMetaArtifact(leases, session.id, artifact), "Could not open that recorded artifact");
174
+ if (artifact.source.type === "html_publication" && artifact.source.availability !== "captured") {
175
+ const url = publishedArtifactUrl(artifact.source.url);
176
+ if (url) {
177
+ window.open(url, "_blank", "noopener,noreferrer");
178
+ return;
179
+ }
180
+ }
181
+ openMetaFile(() => handleForTimelineMetaArtifact(leases, assets, session.id, artifact), "Could not open that recorded artifact");
173
182
  };
174
183
  const openMetaTimeline = (timelineId, label, kind) => {
175
184
  if (timelineId === null) {
@@ -296,9 +305,15 @@ function SessionTranscript({ session, duringBackfill, sessions, project, feed, f
296
305
  useEffect(() => {
297
306
  markStuckPills(scrollRef.current);
298
307
  }, [model.plan]);
308
+ // A session the import has not reached has no messages to count and no
309
+ // activity to range over yet: the head says so instead.
310
+ const notImported = session !== null &&
311
+ importStanding(session, duringBackfill, (index.childrenByParent.get(session.id)?.length ?? 0) > 0) === "not-imported";
299
312
  const range = (() => {
300
313
  if (!session)
301
314
  return "";
315
+ if (notImported)
316
+ return NOT_IMPORTED_LABEL;
302
317
  if (!session.activity)
303
318
  return "Activity time unknown";
304
319
  return `${clockShort(session.activity.first_at)} → ${clockShort(session.activity.last_at)}`;
@@ -323,13 +338,13 @@ function SessionTranscript({ session, duringBackfill, sessions, project, feed, f
323
338
  prompt.classList.add("is-landed");
324
339
  window.setTimeout(() => prompt.classList.remove("is-landed"), 1400);
325
340
  };
326
- return (_jsx(ThreadNavigationContext.Provider, { value: threadNavigation, children: _jsx(MessageViewerContext.Provider, { value: reader ? null : openMessage, children: _jsxs("div", { className: "ah-col ah-col--measure", style: { position: "relative" }, "data-fold": fold.folded ? "on" : "off", children: [!reader && _jsxs("header", { children: [onBackToParent && _jsx("button", { type: "button", className: "tr-parent-link", title: "Back to parent transcript", "aria-label": "Back to parent transcript", onClick: onBackToParent, children: "\u2190" }), session === null ? (_jsx("div", { className: "ah-colhead", children: _jsx("span", { className: "ah-eyebrow", children: "Transcript" }) })) : (_jsx(ColumnHeading, { name: getSessionTitle(session), tint: project?.tint ?? null, count: loading ? null : feed.rows.length, countTitle: `${feed.rows.length} messages loaded` })), _jsxs("span", { className: "ah-headacts", children: [stepper !== null && session !== null ? (_jsx(MatchStepper, { query: stepper.query, at: stepper.at, total: stepper.total, onStep: onStepMatch, onDismiss: onDismissStepper })) : (_jsx("span", { className: "ah-caption tnum", children: range })), session !== null && headActs !== null && headActs.reason !== undefined && headActs.reason !== null && (_jsx("span", { className: "ah-caption ah-headreason", children: headActs.reason })), session !== null && headActs?.acts?.map((act) => _jsx(HostAct, { act: act, place: "pill" }, act.key)), session !== null && (
341
+ return (_jsx(ThreadNavigationContext.Provider, { value: threadNavigation, children: _jsx(MessageViewerContext.Provider, { value: reader ? null : openMessage, children: _jsxs("div", { className: "ah-col ah-col--measure", style: { position: "relative" }, "data-fold": fold.folded ? "on" : "off", children: [!reader && _jsxs("header", { children: [onBackToParent && _jsx("button", { type: "button", className: "tr-parent-link", title: "Back to parent transcript", "aria-label": "Back to parent transcript", onClick: onBackToParent, children: "\u2190" }), session === null ? (_jsx("div", { className: "ah-colhead", children: _jsx("span", { className: "ah-eyebrow", children: "Transcript" }) })) : (_jsx(ColumnHeading, { name: getSessionTitle(session), tint: project?.tint ?? null, count: loading || notImported ? null : feed.rows.length, countTitle: `${feed.rows.length} messages loaded` })), _jsxs("span", { className: "ah-headacts", children: [stepper !== null && session !== null ? (_jsx(MatchStepper, { query: stepper.query, at: stepper.at, total: stepper.total, onStep: onStepMatch, onDismiss: onDismissStepper })) : (_jsx("span", { className: "ah-caption tnum", children: range })), session !== null && headActs !== null && headActs.reason !== undefined && headActs.reason !== null && (_jsx("span", { className: "ah-caption ah-headreason", children: headActs.reason })), session !== null && headActs?.acts?.map((act) => _jsx(HostAct, { act: act, place: "pill" }, act.key)), session !== null && (
327
342
  // §05 — the activity act, beside the range. Folded is the default;
328
343
  // the reader who wants the build log gets it in one press, and the
329
344
  // preference is per room, not per run.
330
345
  _jsx("button", { type: "button", className: "ah-iconbtn", "aria-pressed": fold.folded, title: fold.folded
331
346
  ? "Activity: conversation — show activity"
332
- : "Activity: showing activity — return to conversation", onClick: fold.toggle, children: _jsx(ActivityGlyph, {}) }))] })] }), _jsxs("div", { className: "tr-stage", "data-ready": !loading || undefined, children: [_jsxs("div", { className: "tr-surface", inert: loading, "aria-hidden": loading || undefined, children: [!reader && session !== null && feed.timelineMeta !== null && (_jsx(TimelineMeta, { meta: feed.timelineMeta, onOpenTask: openMetaTask, onOpenWorkflow: openMetaWorkflow, onOpenPlan: openMetaPlan, onOpenArtifact: openMetaArtifact })), _jsxs("div", { className: "ah-scroll tr-scroll", "data-flush": "", ref: scrollRef, tabIndex: 0, role: "region", "aria-label": "Session messages", "aria-busy": loading, onScroll: () => markStuckPills(scrollRef.current), children: [_jsx(TopFade, {}), session === null ? (_jsx(EmptyState, { title: "No session open", description: emptyPrompt })) : (_jsx("div", { className: "tr-col", children: _jsx("div", { className: "tr", children: _jsx(TranscriptDocument, { session: session, model: model, feed: feed, duringBackfill: duringBackfill, index: index, focus: focus, highlightedTimelineId: highlightedTimelineId, onFocusConsumed: onFocusConsumed, onReceipt: onReceipt, onOpenAttachment: openAttachment, onOpenPath: openReadPath, getRuntimeKind: getRuntimeKind, homeDirectory: homeDirectory, onTimelineLayout: onTimelineLayout, onPillPress: reader ? null : (element, dayKey) => {
347
+ : "Activity: showing activity — return to conversation", onClick: fold.toggle, children: _jsx(ActivityGlyph, {}) }))] })] }), _jsxs("div", { className: "tr-stage", "data-ready": !loading || undefined, "data-session-key": session?.id, children: [_jsxs("div", { className: "tr-surface", inert: loading, "aria-hidden": loading || undefined, children: [!reader && session !== null && feed.timelineMeta !== null && (_jsx(TimelineMeta, { meta: feed.timelineMeta, onOpenTask: openMetaTask, onOpenWorkflow: openMetaWorkflow, onOpenPlan: openMetaPlan, onOpenArtifact: openMetaArtifact })), _jsxs("div", { className: "ah-scroll tr-scroll", "data-flush": "", ref: scrollRef, tabIndex: 0, role: "region", "aria-label": "Session messages", "aria-busy": loading, onScroll: () => markStuckPills(scrollRef.current), children: [_jsx(TopFade, {}), session === null ? (_jsx(EmptyState, { title: "No session open", description: emptyPrompt })) : (_jsx("div", { className: "tr-col", children: _jsx("div", { className: "tr", children: _jsx(TranscriptDocument, { session: session, model: model, feed: feed, duringBackfill: duringBackfill, importCourse: importCourse, importAgent: importAgent, index: index, focus: focus, highlightedTimelineId: highlightedTimelineId, onFocusConsumed: onFocusConsumed, onReceipt: onReceipt, onOpenAttachment: openAttachment, onOpenPath: openReadPath, getRuntimeKind: getRuntimeKind, homeDirectory: homeDirectory, onTimelineLayout: onTimelineLayout, onPillPress: reader ? null : (element, dayKey) => {
333
348
  const frame = element.closest(".ah-col");
334
349
  if (frame === null)
335
350
  return;
@@ -0,0 +1,14 @@
1
+ export declare function ArtifactGlyph(): import("react").JSX.Element;
2
+ export declare function ArtifactLibrary({ open, onClose, returnFocus, onOpenSession, agents, projects, canonicalReady }: {
3
+ readonly open: boolean;
4
+ readonly onClose: () => void;
5
+ readonly returnFocus: () => void;
6
+ readonly onOpenSession: (sessionId: string, timelineId: string) => void;
7
+ readonly agents: readonly string[];
8
+ readonly projects: readonly {
9
+ id: string;
10
+ name: string;
11
+ }[];
12
+ /** The archive is published: an open library loads its list again. */
13
+ readonly canonicalReady?: boolean;
14
+ }): import("react").JSX.Element | null;
@@ -0,0 +1,156 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import * as Dialog from "@radix-ui/react-dialog";
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
+ import { ApiRequestError } from "@vibefield/rosetta-protocol";
5
+ import { useRoom, useRoomOverlay, useRoomPortal } from "../../room-context.js";
6
+ import { AgentMark, agentLabel } from "../../lib/agents.js";
7
+ import { ARTIFACT_SANDBOX, artifactDocument, publishedArtifactUrl } from "./preview.js";
8
+ import { ArtifactContentCache } from "./content.js";
9
+ import { loadAllArtifacts } from "./load-all.js";
10
+ import { artifactThumbnails } from "./thumbnails.js";
11
+ const AVAILABILITY = {
12
+ captured: "Captured HTML",
13
+ not_captured: "HTML was not captured",
14
+ missing: "Source file was missing at capture",
15
+ too_large: "Source exceeds the 16 MiB limit",
16
+ unsupported: "Source could not be captured as HTML",
17
+ changed_during_read: "Source changed during capture",
18
+ };
19
+ const when = (at) => at === null ? "Date unavailable" : new Date(at).toLocaleString();
20
+ const errorText = (error) => error instanceof Error ? error.message : "Could not load artifacts";
21
+ export function ArtifactGlyph() {
22
+ return _jsxs("svg", { viewBox: "0 0 18 18", fill: "none", stroke: "currentColor", strokeWidth: "1.35", "aria-hidden": "true", children: [_jsx("rect", { x: "3.5", y: "2.5", width: "12", height: "11", rx: "2" }), _jsx("path", { d: "M12 15.5H4a2 2 0 0 1-2-2V6M7 6.5 5.5 8 7 9.5m5-3L13.5 8 12 9.5" })] });
23
+ }
24
+ /** `published` (canonical readiness) asks again when it turns true, so a
25
+ * list loaded during the import does not keep saying it is in progress. */
26
+ function useArtifacts(port, request, published) {
27
+ const [page, setPage] = useState(null);
28
+ const [error, setError] = useState(null);
29
+ const [loading, setLoading] = useState(false);
30
+ const [refresh, setRefresh] = useState(0);
31
+ const key = JSON.stringify(request);
32
+ useEffect(() => {
33
+ const controller = new AbortController();
34
+ setLoading(true);
35
+ setError(null);
36
+ setPage(null);
37
+ const timer = setTimeout(() => {
38
+ void loadAllArtifacts(port, request, controller.signal, setPage).catch((error) => {
39
+ if (controller.signal.aborted)
40
+ return;
41
+ setError(error instanceof ApiRequestError && error.code === "cursor_expired"
42
+ ? "The library is still changing. Refresh to load the complete list." : errorText(error));
43
+ }).finally(() => { if (!controller.signal.aborted)
44
+ setLoading(false); });
45
+ }, request.q ? 180 : 0);
46
+ return () => { clearTimeout(timer); controller.abort(); };
47
+ }, [port, key, refresh, published]);
48
+ return { page, error, loading, refresh: () => setRefresh((n) => n + 1) };
49
+ }
50
+ function ArtifactPreview({ entry, port, cache, onSession, onBack }) {
51
+ const { host } = useRoom();
52
+ const [view, setView] = useState("preview");
53
+ const [bytes, setBytes] = useState(null);
54
+ const [error, setError] = useState(null);
55
+ const [attempt, setAttempt] = useState(0);
56
+ const [opening, setOpening] = useState(false);
57
+ const publication = entry.publication;
58
+ const publishedUrl = publishedArtifactUrl(publication.url);
59
+ useEffect(() => {
60
+ const controller = new AbortController();
61
+ setBytes(null);
62
+ setError(null);
63
+ if (entry.availability === "captured") {
64
+ void cache.read(port, entry, controller.signal).then((result) => {
65
+ if (controller.signal.aborted)
66
+ return;
67
+ setBytes(result);
68
+ }).catch((error) => { if (!controller.signal.aborted)
69
+ setError(errorText(error)); });
70
+ }
71
+ return () => controller.abort();
72
+ }, [port, cache, entry, attempt]);
73
+ const text = useMemo(() => bytes === null ? null : new TextDecoder().decode(bytes), [bytes]);
74
+ const document = useMemo(() => text === null ? undefined : artifactDocument(text), [text]);
75
+ const openBrowser = async () => {
76
+ if (!host || !bytes)
77
+ return;
78
+ setOpening(true);
79
+ setError(null);
80
+ try {
81
+ if (!await host.openInBrowser(publication.filename, bytes))
82
+ setError("Could not open this artifact in your browser");
83
+ }
84
+ catch (error) {
85
+ setError(errorText(error));
86
+ }
87
+ finally {
88
+ setOpening(false);
89
+ }
90
+ };
91
+ return _jsxs("section", { className: "ah-artifacts__detail", "aria-label": publication.title, children: [_jsxs("div", { className: "ah-artifacts__detailhead", children: [_jsx("button", { type: "button", onClick: onBack, children: "\u2190 Back to grid" }), _jsxs("div", { children: [_jsx("h3", { children: publication.title }), _jsx("span", { className: "ah-artifacts__filename", children: publication.filename })] }), _jsx("button", { type: "button", onClick: onSession, children: "Open session \u2197" })] }), _jsxs("div", { className: "ah-artifacts__provenance", children: [_jsxs("span", { children: [_jsx(AgentMark, { kind: entry.agent }), " ", agentLabel(entry.agent), " \u00B7 ", entry.project_name ?? "No project"] }), _jsx("span", { title: entry.session_title ?? publication.session_id, children: entry.session_title ?? "Agent session" }), _jsxs("span", { children: ["Presented ", when(publication.published_at), publication.version === null ? "" : ` · Version ${publication.version}`] }), entry.captured_at !== null && _jsxs("span", { children: ["File captured ", when(entry.captured_at)] }), entry.recovered_from && _jsxs("span", { title: entry.recovered_from, children: ["Recovered copy \u00B7 ", entry.recovered_from] })] }), _jsxs("div", { className: "ah-artifacts__toolbar", children: [_jsxs("div", { role: "group", "aria-label": "Artifact view", hidden: entry.availability !== "captured", children: [_jsx("button", { type: "button", "aria-pressed": view === "preview", onClick: () => setView("preview"), children: "Preview" }), _jsx("button", { type: "button", "aria-pressed": view === "source", onClick: () => setView("source"), children: "HTML source" })] }), host && bytes && _jsx("button", { type: "button", disabled: opening, onClick: () => { void openBrowser(); }, children: "Open in browser \u2197" }), publishedUrl && _jsx("a", { href: publishedUrl, target: "_blank", rel: "noopener noreferrer", children: "Open published artifact \u2197" })] }), error !== null && _jsxs("div", { className: "ah-artifacts__message", role: "alert", children: [error, " ", _jsx("button", { type: "button", onClick: () => setAttempt((n) => n + 1), children: "Retry" })] }), entry.availability !== "captured" ? _jsxs("div", { className: "ah-artifacts__empty", children: [_jsx(ArtifactGlyph, {}), _jsx("h3", { children: publishedUrl ? "Available through its published link" : AVAILABILITY[entry.availability] }), _jsx("p", { children: publishedUrl ? "A local preview is unavailable. Open the published artifact in your browser." : "No local copy or published link is available. Open its session to review the original context." }), publishedUrl && _jsx("a", { className: "ah-artifacts__published", href: publishedUrl, target: "_blank", rel: "noopener noreferrer", children: "Open published artifact \u2197" })] })
92
+ : bytes === null ? _jsx("div", { className: "ah-artifacts__empty", role: "status", children: error === null ? "Loading captured HTML…" : "Preview unavailable" })
93
+ : view === "source" ? _jsxs("pre", { className: "ah-artifacts__source", children: [text.slice(0, 1_000_000), text.length > 1_000_000 ? "\n\n[Source display limited to 1 million characters]" : ""] })
94
+ : _jsx("iframe", { className: "ah-artifacts__preview", title: `Preview: ${publication.title}`, sandbox: ARTIFACT_SANDBOX, referrerPolicy: "no-referrer", srcDoc: document }), _jsx("p", { className: "ah-artifacts__note", children: entry.recovered_from ? "Recovered copy. It may differ from the published version." : entry.availability === "captured" ? "Captured file snapshot. External data and local file dependencies may be unavailable." : publishedUrl ? "Published pages may change or require you to sign in." : "The artifact’s presentation remains recorded in its session." })] });
95
+ }
96
+ function ArtifactThumbnail({ entry, port, active }) {
97
+ const { host } = useRoom();
98
+ const container = useRef(null);
99
+ const [visible, setVisible] = useState(false);
100
+ const [image, setImage] = useState(null);
101
+ const [failed, setFailed] = useState(false);
102
+ useEffect(() => {
103
+ const element = container.current;
104
+ if (!element)
105
+ return;
106
+ const observer = new IntersectionObserver(([entry]) => setVisible(entry?.isIntersecting ?? false));
107
+ observer.observe(element);
108
+ return () => observer.disconnect();
109
+ }, []);
110
+ useEffect(() => {
111
+ if (!active || !visible || entry.availability !== "captured") {
112
+ setImage(null);
113
+ return;
114
+ }
115
+ if (!host?.artifactThumbnail) {
116
+ setFailed(true);
117
+ return;
118
+ }
119
+ const controller = new AbortController();
120
+ setFailed(false);
121
+ void artifactThumbnails(port).read(port, entry, host.artifactThumbnail, controller.signal).then((image) => {
122
+ if (!controller.signal.aborted) {
123
+ setImage(image);
124
+ setFailed(image === null);
125
+ }
126
+ }).catch(() => { if (!controller.signal.aborted)
127
+ setFailed(true); });
128
+ return () => controller.abort();
129
+ }, [active, visible, entry, port, host]);
130
+ const online = publishedArtifactUrl(entry.publication.url) !== null;
131
+ return _jsx("span", { ref: container, className: "ah-artifacts__thumbnail", "aria-hidden": "true", children: active && visible && image && !failed ? _jsx("img", { alt: "", src: image, decoding: "async", onError: () => setFailed(true) })
132
+ : _jsxs("span", { className: "ah-artifacts__placeholder", children: [_jsx(ArtifactGlyph, {}), _jsx("span", { children: entry.availability === "captured" ? failed ? "Preview unavailable" : "Loading preview…" : online ? "Published online" : "No local preview" })] }) });
133
+ }
134
+ export function ArtifactLibrary({ open, onClose, returnFocus, onOpenSession, agents, projects, canonicalReady = false }) {
135
+ const { catalog } = useRoom();
136
+ const container = useRoomPortal();
137
+ useRoomOverlay(open);
138
+ if (!catalog.artifacts)
139
+ return null;
140
+ return _jsx(Dialog.Root, { open: open, onOpenChange: (next) => { if (!next)
141
+ onClose(); }, children: _jsxs(Dialog.Portal, { container: container, children: [_jsx(Dialog.Overlay, { className: "ah-layer ah-sheet__backdrop" }), _jsxs(Dialog.Content, { className: "ah-layer ah-artifacts", "aria-describedby": "ah-artifacts-description", onCloseAutoFocus: (event) => { event.preventDefault(); returnFocus(); }, children: [_jsxs("div", { className: "ah-artifacts__head", children: [_jsx(ArtifactGlyph, {}), _jsxs("div", { children: [_jsx(Dialog.Title, { children: "Artifacts" }), _jsx(Dialog.Description, { id: "ah-artifacts-description", children: "HTML reviews and designs from your agent sessions" })] }), _jsx(Dialog.Close, { className: "ah-artifacts__close", "aria-label": "Close artifacts", children: "\u00D7" })] }), open && _jsx(LibraryContents, { port: catalog.artifacts, agents: agents, projects: projects, published: canonicalReady, onOpenSession: (entry) => { onClose(); onOpenSession(entry.publication.session_id, entry.publication.timeline_id); } })] })] }) });
142
+ }
143
+ function LibraryContents({ port, agents, projects, published, onOpenSession }) {
144
+ const [q, setQ] = useState("");
145
+ const [agent, setAgent] = useState("");
146
+ const [project, setProject] = useState("");
147
+ const [history, setHistory] = useState(null);
148
+ const [selected, setSelected] = useState(null);
149
+ const cache = useMemo(() => new ArtifactContentCache(), [port]);
150
+ const selectedButton = useRef(null);
151
+ const request = { q: history ? null : q || null, agent: history ? null : agent || null, project: history ? null : project || null, artifact_id: history?.publication.artifact_id ?? null, limit: 100, cursor: null };
152
+ const feed = useArtifacts(port, request, published);
153
+ const filterKey = JSON.stringify(request);
154
+ useEffect(() => { setSelected(null); }, [filterKey]);
155
+ return _jsxs(_Fragment, { children: [_jsxs("div", { className: "ah-artifacts__filters", children: [history ? _jsxs(_Fragment, { children: [_jsx("button", { type: "button", onClick: () => setHistory(null), children: "\u2190 All artifacts" }), _jsxs("strong", { children: [history.publication.title, " \u00B7 Presentations"] })] }) : _jsxs(_Fragment, { children: [_jsx("input", { type: "search", "aria-label": "Search artifacts", placeholder: "Search artifacts\u2026", value: q, onChange: (event) => setQ(event.target.value) }), _jsxs("select", { "aria-label": "Filter by agent", value: agent, onChange: (event) => setAgent(event.target.value), children: [_jsx("option", { value: "", children: "All agents" }), agents.map((kind) => _jsx("option", { value: kind, children: agentLabel(kind) }, kind))] }), _jsxs("select", { "aria-label": "Filter by project", value: project, onChange: (event) => setProject(event.target.value), children: [_jsx("option", { value: "", children: "All projects" }), projects.map((item) => _jsx("option", { value: item.id, children: item.name }, item.id))] })] }), _jsx("button", { type: "button", onClick: () => { setSelected(null); feed.refresh(); }, disabled: feed.loading, children: "Refresh" })] }), feed.page && !feed.page.canonical_ready && _jsx("p", { className: "ah-artifacts__message", role: "status", children: "Ingestion is still in progress. More artifacts may appear." }), feed.error && _jsx("p", { className: "ah-artifacts__message", role: "alert", children: feed.error }), _jsxs("div", { className: "ah-artifacts__body", children: [_jsxs("div", { className: "ah-artifacts__list", hidden: selected !== null, "aria-label": history ? "Artifact presentations" : "Artifact list", "aria-busy": feed.loading, children: [feed.page?.entries.map((entry) => _jsxs("div", { className: "ah-artifacts__item", "data-selected": selected?.publication.id === entry.publication.id || undefined, children: [_jsxs("button", { className: "ah-artifacts__select", type: "button", onClick: (event) => { selectedButton.current = event.currentTarget; setSelected(entry); }, "aria-label": `Preview ${entry.publication.title}`, children: [_jsx(ArtifactThumbnail, { entry: entry, port: port, active: selected === null }), _jsxs("span", { className: "ah-artifacts__itemtitle", children: [_jsx(ArtifactGlyph, {}), _jsx("strong", { children: entry.publication.title })] }), _jsx("span", { className: "ah-artifacts__filename", children: entry.publication.filename }), _jsxs("span", { className: "ah-artifacts__itemmeta", children: [_jsx(AgentMark, { kind: entry.agent }), entry.project_name ?? agentLabel(entry.agent)] }), _jsx("span", { className: "ah-artifacts__itemmeta", children: history ? when(entry.publication.published_at) : entry.recovered_from ? "Recovered copy" : entry.availability !== "captured" && publishedArtifactUrl(entry.publication.url) ? "Published online" : AVAILABILITY[entry.availability] })] }), _jsxs("div", { className: "ah-artifacts__cardactions", children: [_jsx("button", { type: "button", onClick: () => onOpenSession(entry), children: "Open session \u2197" }), publishedArtifactUrl(entry.publication.url) && _jsx("a", { href: publishedArtifactUrl(entry.publication.url), target: "_blank", rel: "noopener noreferrer", children: "Published link \u2197" }), !history && entry.presentations > 1 && _jsxs("button", { className: "ah-artifacts__history", type: "button", onClick: () => setHistory(entry), children: [entry.presentations, " presentations \u2192"] })] })] }, entry.publication.id)), feed.loading && _jsxs("p", { className: "ah-artifacts__message", role: "status", children: ["Loading all artifacts\u2026", feed.page?.entries.length ? ` ${feed.page.entries.length} found` : ""] }), !feed.loading && !feed.error && feed.page?.entries.length === 0 && _jsxs("div", { className: "ah-artifacts__empty", children: [_jsx("h3", { children: q || agent || project ? "No matching artifacts" : "No artifacts yet" }), _jsx("p", { children: q || agent || project ? "Try another search or filter." : "HTML explicitly presented by an agent will appear here as sessions are ingested." })] })] }), selected && _jsx(ArtifactPreview, { entry: selected, port: port, cache: cache, onSession: () => onOpenSession(selected), onBack: () => { setSelected(null); requestAnimationFrame(() => selectedButton.current?.focus()); } }, selected.publication.id)] })] });
156
+ }
@@ -0,0 +1,8 @@
1
+ import type { ArtifactEntry } from "@vibefield/rosetta-protocol";
2
+ import type { CatalogPort } from "../../ports.js";
3
+ /** One open library's bounded cache for explicitly opened full previews. */
4
+ export declare class ArtifactContentCache {
5
+ private readonly entries;
6
+ private size;
7
+ read(port: NonNullable<CatalogPort["artifacts"]>, entry: ArtifactEntry, signal: AbortSignal): Promise<Uint8Array>;
8
+ }
@@ -0,0 +1,27 @@
1
+ import { ARTIFACT_MAX_BYTES } from "./preview.js";
2
+ /** One open library's bounded cache for explicitly opened full previews. */
3
+ export class ArtifactContentCache {
4
+ entries = new Map();
5
+ size = 0;
6
+ async read(port, entry, signal) {
7
+ const key = `${entry.publication.id}:${entry.asset?.digest ?? ""}`;
8
+ const cached = this.entries.get(key);
9
+ if (cached)
10
+ return cached;
11
+ const bytes = await port.read(entry.publication.session_id, entry.publication.id, signal);
12
+ if (signal.aborted)
13
+ throw new DOMException("Aborted", "AbortError");
14
+ if (bytes.byteLength > ARTIFACT_MAX_BYTES)
15
+ throw new Error("The captured HTML exceeds the preview limit");
16
+ if (!this.entries.has(key)) {
17
+ this.entries.set(key, bytes);
18
+ this.size += bytes.byteLength;
19
+ while (this.entries.size > 20 || this.size > 32 * 1024 * 1024) {
20
+ const first = this.entries.keys().next().value;
21
+ this.size -= this.entries.get(first).byteLength;
22
+ this.entries.delete(first);
23
+ }
24
+ }
25
+ return bytes;
26
+ }
27
+ }
@@ -0,0 +1,5 @@
1
+ import { type ArtifactListRequest, type ArtifactPage } from "@vibefield/rosetta-protocol";
2
+ import type { CatalogPort } from "../../ports.js";
3
+ /** Drain the bounded API pages. A source update may invalidate a scan; start
4
+ * over without mixing epochs, and keep the current cards visible until then. */
5
+ export declare function loadAllArtifacts(port: NonNullable<CatalogPort["artifacts"]>, request: ArtifactListRequest, signal: AbortSignal, update: (page: ArtifactPage) => void): Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { ApiRequestError } from "@vibefield/rosetta-protocol";
2
+ /** Drain the bounded API pages. A source update may invalidate a scan; start
3
+ * over without mixing epochs, and keep the current cards visible until then. */
4
+ export async function loadAllArtifacts(port, request, signal, update) {
5
+ for (let attempt = 0;; attempt++) {
6
+ const entries = new Map();
7
+ const cursors = new Set();
8
+ let cursor = null;
9
+ try {
10
+ do {
11
+ signal.throwIfAborted();
12
+ const page = await port.list({ ...request, limit: 100, cursor }, signal);
13
+ signal.throwIfAborted();
14
+ for (const entry of page.entries)
15
+ entries.set(entry.publication.id, entry);
16
+ update({ ...page, entries: [...entries.values()] });
17
+ cursor = page.next_cursor;
18
+ if (cursor !== null && cursors.has(cursor))
19
+ throw new Error("The artifact list returned a repeated page. Refresh to try again.");
20
+ if (cursor !== null)
21
+ cursors.add(cursor);
22
+ } while (cursor !== null);
23
+ return;
24
+ }
25
+ catch (error) {
26
+ signal.throwIfAborted();
27
+ if (!(error instanceof ApiRequestError && error.code === "cursor_expired") || attempt >= 2)
28
+ throw error;
29
+ }
30
+ }
31
+ }
@@ -0,0 +1,4 @@
1
+ export declare const ARTIFACT_SANDBOX = "allow-scripts";
2
+ export declare const ARTIFACT_MAX_BYTES: number;
3
+ export declare function publishedArtifactUrl(value: string | null): string | null;
4
+ export declare function artifactDocument(html: string): string;
@@ -0,0 +1,37 @@
1
+ // Captured pages run only in an opaque-origin iframe. This CSP is prepended
2
+ // before any captured markup; subsequent policies can only restrict it.
3
+ export const ARTIFACT_SANDBOX = "allow-scripts";
4
+ export const ARTIFACT_MAX_BYTES = 16 * 1024 * 1024;
5
+ export function publishedArtifactUrl(value) {
6
+ if (!value || /[\u0000-\u0020]/.test(value))
7
+ return null;
8
+ try {
9
+ const url = new URL(value);
10
+ return url.protocol === "https:" && url.hostname && !url.username && !url.password ? url.href : null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ export function artifactDocument(html) {
17
+ const policy = [
18
+ "default-src 'none'",
19
+ "script-src 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com",
20
+ "style-src 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net",
21
+ "font-src data: https://fonts.gstatic.com",
22
+ "img-src data: blob:",
23
+ "media-src data: blob:",
24
+ "connect-src 'none'",
25
+ "frame-src 'none'",
26
+ "object-src 'none'",
27
+ "worker-src 'none'",
28
+ "base-uri https://artifact.invalid",
29
+ "form-action 'none'",
30
+ ].join("; ");
31
+ // Full documents and the fragments used by presentation tools both parse in
32
+ // this shell. Base defaults are intentionally modest: authored styles win.
33
+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${policy}"><meta name="referrer" content="no-referrer"><base href="https://artifact.invalid/"><style>
34
+ :root { color-scheme: light; --color-background-primary: #fff; --color-background-secondary: #f5f5f3; --color-background-tertiary: #eeede9; --color-text-primary: #252521; --color-text-secondary: #62625c; --color-text-tertiary: #85857e; --color-border-primary: #d5d5ce; --color-border-secondary: #e5e5df; --color-border-tertiary: #efefea; --color-background-info: #eaf1ff; --color-text-info: #2e5b99; --color-background-success: #edf6e8; --color-text-success: #3c6530; --color-background-warning: #fff3d6; --color-text-warning: #855c12; --color-background-danger: #fdecea; --color-text-danger: #9a3830; --border-radius-md: 8px; --border-radius-lg: 12px; --font-sans: system-ui,sans-serif; --font-mono: ui-monospace,monospace; }
35
+ html { background: #fff; color: #252521; font-family: var(--font-sans); } body { margin: 24px; } * { box-sizing: border-box; } button,input,select,textarea { font: inherit; } a { color: #315e9c; }
36
+ </style></head><body>${html}</body></html>`;
37
+ }