Skip to content

🙌 OpenHands: AI-Driven Development

feat(conversation): export transcript as Markdown or self-contained HTML (#1662)

Matt Van Horn4690301e0cd0
diff --git a/__tests__/components/features/conversation/conversation-name.test.tsx b/__tests__/components/features/conversation/conversation-name.test.tsx
index 70ec2da3c6..2daffd8721 100644
--- a/__tests__/components/features/conversation/conversation-name.test.tsx
+++ b/__tests__/components/features/conversation/conversation-name.test.tsx
@@ -89,6 +89,8 @@ vi.mock("react-i18next", async () => {
CONVERSATION$TITLE_UPDATED: "Conversation title updated",
BUTTON$RENAME: "Rename",
BUTTON$EXPORT_CONVERSATION: "Export Conversation",
+ BUTTON$EXPORT_TRANSCRIPT: "Export…",
+ BUTTON$DOWNLOAD_CONVERSATION_DATA: "Download conversation data",
BUTTON$DOWNLOAD_VIA_VSCODE: "Download via VS Code",
BUTTON$SHOW_AGENT_TOOLS_AND_METADATA: "Show Agent Tools",
CONVERSATION$SHOW_SKILLS: "Show Skills",
@@ -548,6 +550,7 @@ describe("ConversationNameContextMenu", () => {
onDisplayCost: vi.fn(),
onShowAgentTools: vi.fn(),
onShowSkills: vi.fn(),
+ onExportTranscript: vi.fn(),
onDownloadConversation: vi.fn(),
};
@@ -571,8 +574,11 @@ describe("ConversationNameContextMenu", () => {
expect(screen.getByTestId("show-skills-button")).toHaveTextContent(
"Show Skills",
);
+ expect(screen.getByTestId("export-transcript-button")).toHaveTextContent(
+ "Export…",
+ );
expect(screen.getByTestId("download-trajectory-button")).toHaveTextContent(
- "Export Conversation",
+ "Download conversation data",
);
});
diff --git a/src/api/event-service/event-service.api.test.ts b/src/api/event-service/event-service.api.test.ts
new file mode 100644
index 0000000000..6c74ba2721
--- /dev/null
+++ b/src/api/event-service/event-service.api.test.ts
@@ -0,0 +1,56 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { callCloudProxyMock } = vi.hoisted(() => ({
+ callCloudProxyMock: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ConversationClient: class {},
+}));
+vi.mock("@openhands/typescript-client/events/remote-events-list", () => ({
+ RemoteEventsList: class {},
+}));
+vi.mock("../backend-registry/active-store", () => ({
+ getActiveBackend: () => ({ backend: { kind: "cloud" } }),
+}));
+vi.mock("../cloud/proxy", () => ({ callCloudProxy: callCloudProxyMock }));
+vi.mock("../agent-server-client-options", () => ({
+ getAgentServerClientOptions: vi.fn(),
+ getAgentServerHttpClientOptions: vi.fn(),
+}));
+
+import EventService from "./event-service.api";
+
+describe("EventService.searchEvents strict pagination", () => {
+ beforeEach(() => {
+ callCloudProxyMock.mockReset();
+ });
+
+ it("rethrows unsupported cloud pagination for completeness-sensitive callers", async () => {
+ const paginationError = new Error("pagination unsupported");
+ callCloudProxyMock.mockRejectedValue(paginationError);
+
+ await expect(
+ EventService.searchEvents("conversation-1", null, null, {
+ limit: 100,
+ sortOrder: "TIMESTAMP_DESC",
+ strictPagination: true,
+ }),
+ ).rejects.toBe(paginationError);
+ });
+
+ it("retains the empty-page fallback for ordinary chat pagination", async () => {
+ callCloudProxyMock.mockRejectedValue(new Error("pagination unsupported"));
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+
+ await expect(
+ EventService.searchEvents("conversation-1", null, null, {
+ limit: 50,
+ timestampLt: "2026-07-10T12:34:56.000Z",
+ }),
+ ).resolves.toEqual({ items: [], next_page_id: null });
+
+ expect(warn).toHaveBeenCalledOnce();
+ warn.mockRestore();
+ });
+});
diff --git a/src/api/event-service/event-service.api.ts b/src/api/event-service/event-service.api.ts
index 633d985f16..8745d59041 100644
--- a/src/api/event-service/event-service.api.ts
+++ b/src/api/event-service/event-service.api.ts
@@ -148,6 +148,7 @@ class EventService {
};
} catch (err) {
if (!hasFilterParams) throw err;
+ if (options.strictPagination) throw err;
// Server doesn't support timestamp filters yet — stop pagination
// by returning an empty page so the UI doesn't retry indefinitely.
diff --git a/src/api/event-service/event-service.types.ts b/src/api/event-service/event-service.types.ts
index 4b87963f50..32b2054444 100644
--- a/src/api/event-service/event-service.types.ts
+++ b/src/api/event-service/event-service.types.ts
@@ -20,6 +20,12 @@ export interface EventSearchOptions {
timestampGte?: string;
/** Filter: event timestamp < this value (ISO 8601). */
timestampLt?: string;
+ /**
+ * Surface unsupported cloud pagination instead of degrading to an empty
+ * page. Callers that require a complete result (such as transcript export)
+ * must set this so a partial history is never mistaken for exhaustion.
+ */
+ strictPagination?: boolean;
}
export interface EventSearchPage<TEvent> {
diff --git a/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx b/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx
index ff6babf641..7ed9beae3a 100644
--- a/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx
+++ b/src/components/features/conversation-panel/conversation-card/conversation-card-context-menu.tsx
@@ -185,7 +185,7 @@ export function ConversationCardContextMenu({
>
<ConversationNameContextMenuIconText
icon={<DownloadIcon width={16} height={16} />}
- text={t(I18nKey.BUTTON$EXPORT_CONVERSATION)}
+ text={t(I18nKey.BUTTON$DOWNLOAD_CONVERSATION_DATA)}
/>
</ContextMenuListItem>
),
diff --git a/src/components/features/conversation/conversation-name-context-menu.tsx b/src/components/features/conversation/conversation-name-context-menu.tsx
index 8609ad39ca..509ad599f4 100644
--- a/src/components/features/conversation/conversation-name-context-menu.tsx
+++ b/src/components/features/conversation/conversation-name-context-menu.tsx
@@ -36,6 +36,7 @@ interface ConversationNameContextMenuProps {
onShowHooks?: (event: React.MouseEvent<HTMLButtonElement>) => void;
onTogglePublic?: (nextIsPublic: boolean) => void;
onCopyShareLink?: (event: React.MouseEvent<HTMLButtonElement>) => void;
+ onExportTranscript?: (event: React.MouseEvent<HTMLButtonElement>) => void;
onDownloadConversation?: (event: React.MouseEvent<HTMLButtonElement>) => void;
shareUrl?: string;
position?: "top" | "bottom";
@@ -98,6 +99,7 @@ export function ConversationNameContextMenu({
onShowHooks,
onTogglePublic,
onCopyShareLink,
+ onExportTranscript,
onDownloadConversation,
shareUrl,
position = "bottom",
@@ -231,6 +233,18 @@ export function ConversationNameContextMenu({
</ArchivedDisabledTooltip>
)}
+ {onExportTranscript && (
+ <ContextMenuListItem
+ testId="export-transcript-button"
+ onClick={onExportTranscript}
+ >
+ <ConversationNameContextMenuIconText
+ icon={<DownloadIcon width={16} height={16} />}
+ text={t(I18nKey.BUTTON$EXPORT_TRANSCRIPT)}
+ />
+ </ContextMenuListItem>
+ )}
+
{onDownloadConversation && (
<ContextMenuListItem
testId="download-trajectory-button"
@@ -238,7 +252,7 @@ export function ConversationNameContextMenu({
>
<ConversationNameContextMenuIconText
icon={<DownloadIcon width={16} height={16} />}
- text={t(I18nKey.BUTTON$EXPORT_CONVERSATION)}
+ text={t(I18nKey.BUTTON$DOWNLOAD_CONVERSATION_DATA)}
/>
</ContextMenuListItem>
)}
diff --git a/src/components/features/conversation/conversation-name.tsx b/src/components/features/conversation/conversation-name.tsx
index ba5453b331..b22c28d0b0 100644
--- a/src/components/features/conversation/conversation-name.tsx
+++ b/src/components/features/conversation/conversation-name.tsx
@@ -14,6 +14,7 @@ import { HooksModal } from "../conversation-panel/hooks-modal";
import { ConfirmDeleteModal } from "../conversation-panel/confirm-delete-modal";
import { ConfirmStopModal } from "../conversation-panel/confirm-stop-modal";
import { MetricsModal } from "./metrics-modal/metrics-modal";
+import { TranscriptExportModal } from "./transcript-export-modal";
export function ConversationName() {
const { t } = useTranslation("openhands");
@@ -23,6 +24,8 @@ export function ConversationName() {
const [titleMode, setTitleMode] = React.useState<"view" | "edit">("view");
const [contextMenuOpen, setContextMenuOpen] = React.useState(false);
+ const [transcriptExportModalVisible, setTranscriptExportModalVisible] =
+ React.useState(false);
const inputRef = React.useRef<HTMLInputElement>(null);
const ellipsisAnchorRef = React.useRef<HTMLDivElement>(null);
@@ -121,6 +124,15 @@ export function ConversationName() {
setContextMenuOpen(false);
};
+ const handleExportTranscript = (
+ event: React.MouseEvent<HTMLButtonElement>,
+ ) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setTranscriptExportModalVisible(true);
+ setContextMenuOpen(false);
+ };
+
React.useEffect(() => {
if (titleMode === "edit") {
inputRef.current?.focus();
@@ -182,6 +194,7 @@ export function ConversationName() {
onTogglePublic={handleTogglePublic}
onCopyShareLink={handleCopyShareLink}
shareUrl={shareUrl}
+ onExportTranscript={handleExportTranscript}
onDownloadConversation={
shouldShowDownloadConversation
? handleDownloadConversation
@@ -201,6 +214,17 @@ export function ConversationName() {
onOpenChange={setMetricsModalVisible}
/>
+ {transcriptExportModalVisible && conversationId && (
+ <TranscriptExportModal
+ conversationId={conversationId}
+ conversationUrl={conversation.conversation_url}
+ sessionApiKey={conversation.session_api_key}
+ conversationTitle={conversation.title}
+ model={conversation.llm_model}
+ onClose={() => setTranscriptExportModalVisible(false)}
+ />
+ )}
+
{/* System Message Modal */}
<SystemMessageModal
isOpen={systemModalVisible}
diff --git a/src/components/features/conversation/transcript-export-modal.tsx b/src/components/features/conversation/transcript-export-modal.tsx
new file mode 100644
index 0000000000..4555660156
--- /dev/null
+++ b/src/components/features/conversation/transcript-export-modal.tsx
@@ -0,0 +1,226 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { ModalBody } from "#/components/shared/modals/modal-body";
+import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";
+import {
+ BaseModalDescription,
+ BaseModalTitle,
+} from "#/components/shared/modals/confirmation-modals/base-modal";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { downloadBlob } from "#/utils/utils";
+import {
+ eventsToHtml,
+ eventsToMarkdown,
+ type TranscriptExportFormat,
+} from "#/utils/transcript-export";
+import { useTracking } from "#/hooks/use-tracking";
+import { useEventStore } from "#/stores/use-event-store";
+import EventService from "#/api/event-service/event-service.api";
+import { loadCompleteTranscriptEvents } from "#/utils/transcript-export/load-complete-events";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+
+const TRANSCRIPT_FORMAT_RADIO_NAME = "transcript-export-format";
+
+interface TranscriptExportModalProps {
+ conversationId: string;
+ conversationUrl?: string | null;
+ sessionApiKey?: string | null;
+ conversationTitle?: string | null;
+ model?: string | null;
+ onClose: () => void;
+}
+
+export function TranscriptExportModal({
+ conversationId,
+ conversationUrl,
+ sessionApiKey,
+ conversationTitle,
+ model,
+ onClose,
+}: TranscriptExportModalProps) {
+ const { t } = useTranslation("openhands");
+ const { trackConversationExported } = useTracking();
+ const [format, setFormat] =
+ React.useState<TranscriptExportFormat>("markdown");
+ const [includeToolDetails, setIncludeToolDetails] = React.useState(true);
+ const [includeTimestamps, setIncludeTimestamps] = React.useState(true);
+ const [isExporting, setIsExporting] = React.useState(false);
+ const isExportingRef = React.useRef(false);
+ const isCancelledRef = React.useRef(false);
+ const isMountedRef = React.useRef(true);
+
+ React.useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ isCancelledRef.current = true;
+ };
+ }, []);
+
+ const handleClose = () => {
+ if (isExportingRef.current) isCancelledRef.current = true;
+ onClose();
+ };
+
+ const handleExport = async () => {
+ if (isExportingRef.current) return;
+
+ isCancelledRef.current = false;
+ isExportingRef.current = true;
+ setIsExporting(true);
+ try {
+ // The count lets us reject silently truncated pagination. Archived cloud
+ // runtimes may no longer expose this endpoint, while their persisted
+ // App API history remains exportable, so treat the check as best-effort.
+ const expectedEventCount = await EventService.getEventCount(
+ conversationId,
+ conversationUrl ?? "",
+ sessionApiKey,
+ ).catch(() => undefined);
+ if (isCancelledRef.current) return;
+
+ const eventStore = useEventStore.getState();
+ const loadedEvents =
+ eventStore.loadedConversationId === conversationId
+ ? eventStore.events
+ : [];
+ const events = await loadCompleteTranscriptEvents(
+ loadedEvents,
+ (searchOptions) =>
+ EventService.searchEvents(
+ conversationId,
+ conversationUrl,
+ sessionApiKey,
+ searchOptions,
+ ),
+ expectedEventCount,
+ );
+ if (isCancelledRef.current) return;
+
+ const options = {
+ includeToolDetails,
+ includeTimestamps,
+ title: conversationTitle,
+ model,
+ };
+ const isMarkdown = format === "markdown";
+ const content = isMarkdown
+ ? eventsToMarkdown(events, options)
+ : eventsToHtml(events, options);
+ const extension = isMarkdown ? "md" : "html";
+ const mimeType = isMarkdown
+ ? "text/markdown;charset=utf-8"
+ : "text/html;charset=utf-8";
+
+ downloadBlob(
+ new Blob([content], { type: mimeType }),
+ `conversation-${conversationId}.${extension}`,
+ );
+ trackConversationExported(format);
+ onClose();
+ } catch {
+ if (!isCancelledRef.current) {
+ displayErrorToast(t(I18nKey.ERROR$GENERIC));
+ }
+ } finally {
+ isExportingRef.current = false;
+ if (isMountedRef.current) setIsExporting(false);
+ }
+ };
+
+ return (
+ <ModalBackdrop
+ onClose={handleClose}
+ aria-label={t(I18nKey.TRANSCRIPT_EXPORT$TITLE)}
+ >
+ <ModalBody
+ testID="transcript-export-modal"
+ className="relative items-start border border-[var(--oh-border)]"
+ >
+ <ModalCloseButton
+ onClose={handleClose}
+ testId="close-transcript-export-modal"
+ className="absolute right-4 top-4"
+ />
+ <div className="flex flex-col gap-2 pr-8">
+ <BaseModalTitle title={t(I18nKey.TRANSCRIPT_EXPORT$TITLE)} />
+ <BaseModalDescription
+ description={t(I18nKey.TRANSCRIPT_EXPORT$DESCRIPTION)}
+ />
+ </div>
+
+ <fieldset className="flex w-full flex-col gap-2">
+ <legend className="mb-2 text-sm font-medium text-white">
+ {t(I18nKey.TRANSCRIPT_EXPORT$FORMAT)}
+ </legend>
+ <label className="flex cursor-pointer items-center gap-3 rounded-md border border-[var(--oh-border)] px-3 py-2 text-sm text-white">
+ <input
+ type="radio"
+ name={TRANSCRIPT_FORMAT_RADIO_NAME}
+ value="markdown"
+ disabled={isExporting}
+ checked={format === "markdown"}
+ onChange={() => setFormat("markdown")}
+ />
+ {t(I18nKey.TRANSCRIPT_EXPORT$MARKDOWN)}
+ </label>
+ <label className="flex cursor-pointer items-center gap-3 rounded-md border border-[var(--oh-border)] px-3 py-2 text-sm text-white">
+ <input
+ type="radio"
+ name={TRANSCRIPT_FORMAT_RADIO_NAME}
+ value="html"
+ disabled={isExporting}
+ checked={format === "html"}
+ onChange={() => setFormat("html")}
+ />
+ {t(I18nKey.TRANSCRIPT_EXPORT$HTML)}
+ </label>
+ </fieldset>
+
+ <div className="flex w-full flex-col gap-3 text-sm text-white">
+ <label className="flex cursor-pointer items-center gap-3">
+ <input
+ type="checkbox"
+ disabled={isExporting}
+ checked={includeToolDetails}
+ onChange={(event) => setIncludeToolDetails(event.target.checked)}
+ />
+ {t(I18nKey.TRANSCRIPT_EXPORT$INCLUDE_TOOL_DETAILS)}
+ </label>
+ <label className="flex cursor-pointer items-center gap-3">
+ <input
+ type="checkbox"
+ disabled={isExporting}
+ checked={includeTimestamps}
+ onChange={(event) => setIncludeTimestamps(event.target.checked)}
+ />
+ {t(I18nKey.TRANSCRIPT_EXPORT$INCLUDE_TIMESTAMPS)}
+ </label>
+ </div>
+
+ <div className="flex w-full justify-end gap-2">
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={handleClose}
+ testId="cancel-transcript-export"
+ >
+ {t(I18nKey.BUTTON$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ type="button"
+ variant="primary"
+ onClick={handleExport}
+ testId="confirm-transcript-export"
+ isDisabled={isExporting}
+ aria-busy={isExporting}
+ >
+ {t(I18nKey.BUTTON$EXPORT_CONVERSATION)}
+ </BrandButton>
+ </div>
+ </ModalBody>
+ </ModalBackdrop>
+ );
+}
diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.ts
index 72e5209276..3453de58b0 100644
--- a/src/hooks/use-tracking.ts
+++ b/src/hooks/use-tracking.ts
@@ -178,6 +178,10 @@ export const useTracking = () => {
track("download_trajectory_button_clicked");
};
+ const trackConversationExported = (format: "markdown" | "html") => {
+ track("conversation_exported", { format });
+ };
+
const trackAutomationCreated = ({
backendKind,
}: {
@@ -319,6 +323,7 @@ export const useTracking = () => {
trackSettingsSaved,
trackMcpConfigUpdated,
trackDownloadTrajectoryButtonClicked,
+ trackConversationExported,
trackAutomationCreated,
trackAutomationExecuted,
trackAutomationDeleted,
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index fcba55ac62..2ad705897a 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -17866,6 +17866,261 @@
"uk": "Експорт розмови",
"ca": "Exporta la conversa"
},
+ "BUTTON$EXPORT_TRANSCRIPT": {
+ "en": "Export…",
+ "ja": "エクスポート…",
+ "zh-CN": "导出…",
+ "zh-TW": "匯出…",
+ "ko-KR": "내보내기…",
+ "no": "Eksporter…",
+ "it": "Esporta…",
+ "pt": "Exportar…",
+ "es": "Exportar…",
+ "ar": "تصدير…",
+ "fr": "Exporter…",
+ "tr": "Dışa aktar…",
+ "de": "Exportieren…",
+ "uk": "Експортувати…",
+ "ca": "Exporta…"
+ },
+ "BUTTON$DOWNLOAD_CONVERSATION_DATA": {
+ "en": "Download conversation data",
+ "ja": "会話データをダウンロード",
+ "zh-CN": "下载对话数据",
+ "zh-TW": "下載對話資料",
+ "ko-KR": "대화 데이터 다운로드",
+ "no": "Last ned samtaledata",
+ "it": "Scarica i dati della conversazione",
+ "pt": "Baixar dados da conversa",
+ "es": "Descargar datos de la conversación",
+ "ar": "تنزيل بيانات المحادثة",
+ "fr": "Télécharger les données de la conversation",
+ "tr": "Konuşma verilerini indir",
+ "de": "Konversationsdaten herunterladen",
+ "uk": "Завантажити дані розмови",
+ "ca": "Baixa les dades de la conversa"
+ },
+ "TRANSCRIPT_EXPORT$TITLE": {
+ "en": "Export conversation",
+ "ja": "会話をエクスポート",
+ "zh-CN": "导出对话",
+ "zh-TW": "匯出對話",
+ "ko-KR": "대화 내보내기",
+ "no": "Eksporter samtale",
+ "it": "Esporta conversazione",
+ "pt": "Exportar conversa",
+ "es": "Exportar conversación",
+ "ar": "تصدير المحادثة",
+ "fr": "Exporter la conversation",
+ "tr": "Konuşmayı dışa aktar",
+ "de": "Konversation exportieren",
+ "uk": "Експортувати розмову",
+ "ca": "Exporta la conversa"
+ },
+ "TRANSCRIPT_EXPORT$DESCRIPTION": {
+ "en": "Download a shareable transcript without sending conversation data anywhere.",
+ "ja": "会話データを外部に送信せず、共有可能な記録をダウンロードします。",
+ "zh-CN": "在不向外部发送对话数据的情况下下载可共享的记录。",
+ "zh-TW": "在不向外部傳送對話資料的情況下下載可分享的記錄。",
+ "ko-KR": "대화 데이터를 외부로 보내지 않고 공유 가능한 기록을 다운로드합니다.",
+ "no": "Last ned en delbar utskrift uten å sende samtaledata noe sted.",
+ "it": "Scarica una trascrizione condivisibile senza inviare altrove i dati della conversazione.",
+ "pt": "Baixe uma transcrição compartilhável sem enviar os dados da conversa para nenhum lugar.",
+ "es": "Descarga una transcripción para compartir sin enviar los datos de la conversación a ningún sitio.",
+ "ar": "نزّل نصًا قابلاً للمشاركة من دون إرسال بيانات المحادثة إلى أي مكان.",
+ "fr": "Téléchargez une transcription partageable sans envoyer les données de conversation ailleurs.",
+ "tr": "Konuşma verilerini herhangi bir yere göndermeden paylaşılabilir bir döküm indirin.",
+ "de": "Laden Sie ein teilbares Transkript herunter, ohne Konversationsdaten zu versenden.",
+ "uk": "Завантажте стенограму для поширення, не надсилаючи дані розмови назовні.",
+ "ca": "Baixa una transcripció compartible sense enviar les dades de la conversa enlloc."
+ },
+ "TRANSCRIPT_EXPORT$FORMAT": {
+ "en": "Format",
+ "ja": "形式",
+ "zh-CN": "格式",
+ "zh-TW": "格式",
+ "ko-KR": "형식",
+ "no": "Format",
+ "it": "Formato",
+ "pt": "Formato",
+ "es": "Formato",
+ "ar": "التنسيق",
+ "fr": "Format",
+ "tr": "Biçim",
+ "de": "Format",
+ "uk": "Формат",
+ "ca": "Format"
+ },
+ "TRANSCRIPT_EXPORT$MARKDOWN": {
+ "en": "Markdown document (.md)",
+ "ja": "Markdown ドキュメント(.md)",
+ "zh-CN": "Markdown 文档(.md)",
+ "zh-TW": "Markdown 文件(.md)",
+ "ko-KR": "Markdown 문서(.md)",
+ "no": "Markdown-dokument (.md)",
+ "it": "Documento Markdown (.md)",
+ "pt": "Documento Markdown (.md)",
+ "es": "Documento Markdown (.md)",
+ "ar": "مستند Markdown ‏(.md)",
+ "fr": "Document Markdown (.md)",
+ "tr": "Markdown belgesi (.md)",
+ "de": "Markdown-Dokument (.md)",
+ "uk": "Документ Markdown (.md)",
+ "ca": "Document Markdown (.md)"
+ },
+ "TRANSCRIPT_EXPORT$HTML": {
+ "en": "Standalone web page (.html)",
+ "ja": "スタンドアロン Web ページ(.html)",
+ "zh-CN": "独立网页(.html)",
+ "zh-TW": "獨立網頁(.html)",
+ "ko-KR": "독립형 웹 페이지(.html)",
+ "no": "Frittstående nettside (.html)",
+ "it": "Pagina web autonoma (.html)",
+ "pt": "Página web independente (.html)",
+ "es": "Página web independiente (.html)",
+ "ar": "صفحة ويب مستقلة (.html)",
+ "fr": "Page web autonome (.html)",
+ "tr": "Bağımsız web sayfası (.html)",
+ "de": "Eigenständige Webseite (.html)",
+ "uk": "Автономна вебсторінка (.html)",
+ "ca": "Pàgina web autònoma (.html)"
+ },
+ "TRANSCRIPT_EXPORT$INCLUDE_TOOL_DETAILS": {
+ "en": "Include tool call details",
+ "ja": "ツール呼び出しの詳細を含める",
+ "zh-CN": "包含工具调用详情",
+ "zh-TW": "包含工具呼叫詳細資料",
+ "ko-KR": "도구 호출 세부 정보 포함",
+ "no": "Ta med detaljer om verktøykall",
+ "it": "Includi i dettagli delle chiamate agli strumenti",
+ "pt": "Incluir detalhes das chamadas de ferramentas",
+ "es": "Incluir detalles de las llamadas a herramientas",
+ "ar": "تضمين تفاصيل استدعاءات الأدوات",
+ "fr": "Inclure les détails des appels d’outils",
+ "tr": "Araç çağrısı ayrıntılarını dahil et",
+ "de": "Details zu Werkzeugaufrufen einschließen",
+ "uk": "Додати подробиці викликів інструментів",
+ "ca": "Inclou els detalls de les crides d’eines"
+ },
+ "TRANSCRIPT_EXPORT$INCLUDE_TIMESTAMPS": {
+ "en": "Include timestamps",
+ "ja": "タイムスタンプを含める",
+ "zh-CN": "包含时间戳",
+ "zh-TW": "包含時間戳記",
+ "ko-KR": "타임스탬프 포함",
+ "no": "Ta med tidsstempler",
+ "it": "Includi timestamp",
+ "pt": "Incluir carimbos de data e hora",
+ "es": "Incluir marcas de tiempo",
+ "ar": "تضمين الطوابع الزمنية",
+ "fr": "Inclure les horodatages",
+ "tr": "Zaman damgalarını dahil et",
+ "de": "Zeitstempel einschließen",
+ "uk": "Додати часові позначки",
+ "ca": "Inclou les marques de temps"
+ },
+ "TRANSCRIPT_EXPORT$DEFAULT_TITLE": {
+ "en": "Conversation transcript",
+ "ja": "会話の記録",
+ "zh-CN": "对话记录",
+ "zh-TW": "對話記錄",
+ "ko-KR": "대화 기록",
+ "no": "Samtaleutskrift",
+ "it": "Trascrizione della conversazione",
+ "pt": "Transcrição da conversa",
+ "es": "Transcripción de la conversación",
+ "ar": "نص المحادثة",
+ "fr": "Transcription de la conversation",
+ "tr": "Konuşma dökümü",
+ "de": "Konversationstranskript",
+ "uk": "Стенограма розмови",
+ "ca": "Transcripció de la conversa"
+ },
+ "TRANSCRIPT_EXPORT$MODEL": {
+ "en": "Model",
+ "ja": "モデル",
+ "zh-CN": "模型",
+ "zh-TW": "模型",
+ "ko-KR": "모델",
+ "no": "Modell",
+ "it": "Modello",
+ "pt": "Modelo",
+ "es": "Modelo",
+ "ar": "النموذج",
+ "fr": "Modèle",
+ "tr": "Model",
+ "de": "Modell",
+ "uk": "Модель",
+ "ca": "Model"
+ },
+ "TRANSCRIPT_EXPORT$REASON": {
+ "en": "Reason",
+ "ja": "理由",
+ "zh-CN": "原因",
+ "zh-TW": "原因",
+ "ko-KR": "이유",
+ "no": "Årsak",
+ "it": "Motivo",
+ "pt": "Motivo",
+ "es": "Motivo",
+ "ar": "السبب",
+ "fr": "Raison",
+ "tr": "Neden",
+ "de": "Grund",
+ "uk": "Причина",
+ "ca": "Motiu"
+ },
+ "TRANSCRIPT_EXPORT$USER": {
+ "en": "User",
+ "ja": "ユーザー",
+ "zh-CN": "用户",
+ "zh-TW": "使用者",
+ "ko-KR": "사용자",
+ "no": "Bruker",
+ "it": "Utente",
+ "pt": "Usuário",
+ "es": "Usuario",
+ "ar": "المستخدم",
+ "fr": "Utilisateur",
+ "tr": "Kullanıcı",
+ "de": "Benutzer",
+ "uk": "Користувач",
+ "ca": "Usuari"
+ },
+ "TRANSCRIPT_EXPORT$TOOL": {
+ "en": "Tool",
+ "ja": "ツール",
+ "zh-CN": "工具",
+ "zh-TW": "工具",
+ "ko-KR": "도구",
+ "no": "Verktøy",
+ "it": "Strumento",
+ "pt": "Ferramenta",
+ "es": "Herramienta",
+ "ar": "الأداة",
+ "fr": "Outil",
+ "tr": "Araç",
+ "de": "Werkzeug",
+ "uk": "Інструмент",
+ "ca": "Eina"
+ },
+ "TRANSCRIPT_EXPORT$HOOK": {
+ "en": "Hook: {{command}}",
+ "ja": "フック: {{command}}",
+ "zh-CN": "钩子: {{command}}",
+ "zh-TW": "掛鉤: {{command}}",
+ "ko-KR": "후크: {{command}}",
+ "no": "Hook: {{command}}",
+ "it": "Hook: {{command}}",
+ "pt": "Hook: {{command}}",
+ "es": "Hook: {{command}}",
+ "ar": "الخطاف: {{command}}",
+ "fr": "Hook : {{command}}",
+ "tr": "Kanca: {{command}}",
+ "de": "Hook: {{command}}",
+ "uk": "Гук: {{command}}",
+ "ca": "Hook: {{command}}"
+ },
"WAITLIST$IF_NOT_JOINED": {
"en": "If you haven't already joined the waitlist, please do so to get access.",
"ja": "まだウェイトリストに参加していない場合は、アクセスを得るために参加してください。",
diff --git a/src/utils/transcript-export/__snapshots__/index.test.ts.snap b/src/utils/transcript-export/__snapshots__/index.test.ts.snap
new file mode 100644
index 0000000000..9d8a3a5277
--- /dev/null
+++ b/src/utils/transcript-export/__snapshots__/index.test.ts.snap
@@ -0,0 +1,61 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`conversation transcript export > renders a self-contained HTML document 1`] = `
+"<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:">
+ <title>Debug session</title>
+ <style>
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
+ body { margin: 0; background: #111827; color: #e5e7eb; line-height: 1.55; }
+ main { box-sizing: border-box; width: min(860px, 100%); margin: 0 auto; padding: 48px 24px 80px; }
+ h1 { margin: 0; font-size: 2rem; }
+ h2 { margin: 0; font-size: 1rem; }
+ .model { margin: 8px 0 32px; color: #9ca3af; }
+ .message, details, .tool-summary, .note { margin: 16px 0; border: 1px solid #374151; border-radius: 10px; padding: 16px; background: #1f2937; }
+ .user { border-left: 4px solid #60a5fa; }
+ .assistant { border-left: 4px solid #34d399; }
+ .error { border-left: 4px solid #f87171; }
+ .note { border-left: 4px solid #a78bfa; }
+ header, summary, .tool-summary { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
+ summary { cursor: pointer; }
+ time { flex: none; color: #9ca3af; font-size: .75rem; font-weight: 400; }
+ .content { margin-top: 10px; white-space: pre-wrap; overflow-wrap: anywhere; }
+ pre { margin: 14px 0 0; padding: 14px; overflow-x: auto; border-radius: 7px; background: #111827; color: #d1d5db; white-space: pre-wrap; overflow-wrap: anywhere; }
+ @media (prefers-color-scheme: light) {
+ body { background: #f9fafb; color: #111827; }
+ .message, details, .tool-summary, .note { border-color: #d1d5db; background: #fff; }
+ pre { background: #f3f4f6; color: #1f2937; }
+ .model, time { color: #6b7280; }
+ }
+ </style>
+</head>
+<body>
+ <main>
+ <h1>Debug session</h1>
+ <p class="model"><strong>Model:</strong> anthropic/claude-sonnet</p>
+ <section class="message user">
+ <header><h2>User</h2><time datetime="2026-07-10T12:34:56.000Z">2026-07-10T12:34:56.000Z</time></header>
+ <div class="content">Please diagnose **the failure**.</div>
+</section>
+<details>
+ <summary><strong>Tool:</strong> Run the unit tests<time datetime="2026-07-10T12:34:58.000Z">2026-07-10T12:34:58.000Z</time></summary>
+ <pre>Command: \`npm test\`
+
+Output:
+\`\`\`sh
+3 tests passed
+\`\`\`</pre>
+</details>
+<section class="message assistant">
+ <header><h2>Assistant</h2><time datetime="2026-07-10T12:35:00.000Z">2026-07-10T12:35:00.000Z</time></header>
+ <div class="content">The service is healthy now.</div>
+</section>
+ </main>
+</body>
+</html>
+"
+`;
diff --git a/src/utils/transcript-export/index.test.ts b/src/utils/transcript-export/index.test.ts
new file mode 100644
index 0000000000..957b775299
--- /dev/null
+++ b/src/utils/transcript-export/index.test.ts
@@ -0,0 +1,363 @@
+import { describe, expect, it, vi } from "vitest";
+import type {
+ ActionEvent,
+ AgentErrorEvent,
+ MessageEvent,
+ ObservationEvent,
+} from "#/types/agent-server/core";
+import type {
+ ExecuteBashAction,
+ MCPToolAction,
+ TaskAction,
+} from "#/types/agent-server/core/base/action";
+import type {
+ ExecuteBashObservation,
+ TaskObservation,
+} from "#/types/agent-server/core/base/observation";
+import type { StreamingDeltaEvent } from "#/types/agent-server/core/events/streaming-delta-event";
+import { SecurityRisk } from "#/types/agent-server/core/base/common";
+import { eventsToHtml, eventsToMarkdown } from ".";
+
+vi.mock("#/i18n", () => ({
+ default: {
+ exists: () => false,
+ language: "en",
+ resolvedLanguage: "en",
+ t: (key: string, values?: Record<string, string>) => {
+ const translations: Record<string, string> = {
+ ACTION_MESSAGE$ACP_TOOL: "Use tool",
+ CHAT_INTERFACE$ASSISTANT: "Assistant",
+ COMMON$ERROR: "Error",
+ TASK$QUERY: "Query",
+ TASK$RESULT: "Result",
+ TASK$SUBAGENT: "Subagent",
+ TASK$TASK_ID: "Task ID",
+ TRANSCRIPT_EXPORT$DEFAULT_TITLE: "Conversation transcript",
+ TRANSCRIPT_EXPORT$MODEL: "Model",
+ TRANSCRIPT_EXPORT$TOOL: "Tool",
+ TRANSCRIPT_EXPORT$USER: "User",
+ };
+ return translations[key] ?? values?.name ?? key;
+ },
+ },
+}));
+
+const timestamp = "2026-07-10T12:34:56.000Z";
+
+const userMessage: MessageEvent = {
+ id: "user-1",
+ timestamp,
+ source: "user",
+ llm_message: {
+ role: "user",
+ content: [{ type: "text", text: "Please diagnose **the failure**." }],
+ },
+ activated_microagents: [],
+ extended_content: [],
+};
+
+const assistantMessage: MessageEvent = {
+ id: "assistant-1",
+ timestamp: "2026-07-10T12:35:00.000Z",
+ source: "agent",
+ llm_message: {
+ role: "assistant",
+ content: [{ type: "text", text: "The service is healthy now." }],
+ },
+ activated_microagents: [],
+ extended_content: [],
+};
+
+const terminalAction: ActionEvent<ExecuteBashAction> = {
+ id: "action-1",
+ timestamp: "2026-07-10T12:34:57.000Z",
+ source: "agent",
+ thought: [],
+ thinking_blocks: [],
+ action: {
+ kind: "ExecuteBashAction",
+ command: "npm test",
+ is_input: false,
+ timeout: null,
+ reset: false,
+ },
+ tool_name: "terminal",
+ tool_call_id: "tool-1",
+ tool_call: {
+ id: "tool-1",
+ type: "function",
+ function: { name: "terminal", arguments: "{}" },
+ },
+ llm_response_id: "response-1",
+ security_risk: SecurityRisk.LOW,
+ summary: "Run the unit tests",
+};
+
+const terminalObservation = (
+ output: string,
+): ObservationEvent<ExecuteBashObservation> => ({
+ id: "observation-1",
+ timestamp: "2026-07-10T12:34:58.000Z",
+ source: "environment",
+ tool_name: "terminal",
+ tool_call_id: "tool-1",
+ action_id: "action-1",
+ observation: {
+ kind: "ExecuteBashObservation",
+ command: "npm test",
+ content: [{ type: "text", text: output }],
+ exit_code: 0,
+ error: false,
+ timeout: false,
+ metadata: {
+ exit_code: 0,
+ pid: 123,
+ username: "openhands",
+ hostname: "sandbox",
+ working_dir: "/workspace/project",
+ py_interpreter_path: null,
+ prefix: "",
+ suffix: "",
+ },
+ },
+});
+
+const defaultOptions = {
+ includeToolDetails: true,
+ includeTimestamps: true,
+ title: "Debug session",
+ model: "anthropic/claude-sonnet",
+};
+
+describe("conversation transcript export", () => {
+ it("exports messages and collapsed tool details as GitHub-ready Markdown", () => {
+ const markdown = eventsToMarkdown(
+ [
+ userMessage,
+ terminalAction,
+ terminalObservation("3 tests passed"),
+ assistantMessage,
+ ],
+ defaultOptions,
+ );
+
+ expect(markdown).toContain("# Debug session");
+ expect(markdown).toContain("**Model:** anthropic/claude-sonnet");
+ expect(markdown).toContain("## User");
+ expect(markdown).toContain("Please diagnose **the failure**.");
+ expect(markdown).toContain("<details>");
+ expect(markdown).toContain("Run the unit tests");
+ expect(markdown).toContain("3 tests passed");
+ expect(markdown).toContain("## Assistant");
+ });
+
+ it("honors tool-detail and timestamp options in both formats", () => {
+ const events = [userMessage, terminalAction, terminalObservation("passed")];
+ const options = {
+ ...defaultOptions,
+ includeToolDetails: false,
+ includeTimestamps: false,
+ };
+ const markdown = eventsToMarkdown(events, options);
+ const html = eventsToHtml(events, options);
+
+ expect(markdown).toContain("<strong>Tool:</strong> Run the unit tests");
+ expect(markdown).not.toContain("<details>");
+ expect(markdown).not.toContain("passed");
+ expect(markdown).not.toContain(timestamp);
+ expect(html).not.toContain("<details>");
+ expect(html).not.toContain("passed");
+ expect(html).not.toContain("<time");
+ });
+
+ it("exports agent errors and uses the UI's tool-output truncation", () => {
+ const errorEvent: AgentErrorEvent = {
+ id: "error-1",
+ timestamp,
+ source: "agent",
+ tool_name: "terminal",
+ tool_call_id: "tool-error",
+ error: "Command failed with exit code 1",
+ };
+ const markdown = eventsToMarkdown(
+ [terminalAction, terminalObservation("x".repeat(1200)), errorEvent],
+ defaultOptions,
+ );
+
+ expect(markdown).toContain("## Error");
+ expect(markdown).toContain("> Command failed with exit code 1");
+ expect(markdown).toContain(`${"x".repeat(1000)}...`);
+ expect(markdown).not.toContain("x".repeat(1001));
+ });
+
+ it("exports assistant narration once when an observation replaces its action", () => {
+ const narratedAction: ActionEvent<ExecuteBashAction> = {
+ ...terminalAction,
+ thought: [{ type: "text", text: "I checked the failing service." }],
+ reasoning_content: "The logs point to a stale process.",
+ };
+ const markdown = eventsToMarkdown(
+ [narratedAction, terminalObservation("passed")],
+ defaultOptions,
+ );
+
+ expect(markdown.match(/I checked the failing service\./g)).toHaveLength(1);
+ expect(markdown.match(/The logs point to a stale process\./g)).toHaveLength(
+ 1,
+ );
+ });
+
+ it("exports streaming reasoning with the same inline-think split as chat", () => {
+ const streamingEvent: StreamingDeltaEvent = {
+ id: "streaming-1",
+ timestamp,
+ source: "agent",
+ kind: "StreamingDeltaEvent",
+ reasoning_content: "Separate reasoning",
+ content: "<think>Inline reasoning</think>Visible answer",
+ };
+
+ const markdown = eventsToMarkdown([streamingEvent], defaultOptions);
+
+ expect(markdown).toContain("Separate reasoning");
+ expect(markdown).toContain("Inline reasoning");
+ expect(markdown).toContain("Visible answer");
+ expect(markdown).not.toContain("&lt;think&gt;");
+ });
+
+ it("splits inline reasoning from finalized assistant messages", () => {
+ const messageEvent: MessageEvent = {
+ ...assistantMessage,
+ llm_message: {
+ role: "assistant",
+ content: [
+ {
+ type: "text",
+ text: "<think>Reloaded reasoning</think>Reloaded answer",
+ },
+ ],
+ },
+ };
+
+ const markdown = eventsToMarkdown([messageEvent], defaultOptions);
+
+ expect(markdown).toContain("Reloaded reasoning");
+ expect(markdown).toContain("Reloaded answer");
+ expect(markdown).not.toContain("&lt;think&gt;");
+ });
+
+ it("exports task inputs and results through their display projection", () => {
+ const taskAction: ActionEvent<TaskAction> = {
+ ...terminalAction,
+ id: "task-action",
+ tool_name: "task",
+ tool_call_id: "task-call",
+ tool_call: {
+ id: "task-call",
+ type: "function",
+ function: { name: "task", arguments: "{}" },
+ },
+ action: {
+ kind: "TaskAction",
+ prompt: "Inspect the authentication flow",
+ subagent_type: "security",
+ description: "Inspect authentication",
+ },
+ summary: "Delegate authentication review",
+ };
+ const taskObservation: ObservationEvent<TaskObservation> = {
+ id: "task-observation",
+ timestamp: "2026-07-10T12:34:59.000Z",
+ source: "environment",
+ tool_name: "task",
+ tool_call_id: "task-call",
+ action_id: "task-action",
+ observation: {
+ kind: "TaskObservation",
+ content: [{ type: "text", text: "No credential leak found." }],
+ task_id: "task-123",
+ subagent: "security",
+ status: "completed",
+ is_error: false,
+ },
+ };
+
+ const markdown = eventsToMarkdown(
+ [taskAction, taskObservation],
+ defaultOptions,
+ );
+
+ expect(markdown).toContain("Inspect the authentication flow");
+ expect(markdown).toContain("No credential leak found.");
+ expect(markdown).toContain("task-123");
+ });
+
+ it("only exports the redacted display projection, never hidden raw tool arguments", () => {
+ const redactedAction: ActionEvent<MCPToolAction> = {
+ ...terminalAction,
+ id: "secret-action",
+ tool_call_id: "secret-tool",
+ action: {
+ kind: "MCPToolAction",
+ data: { api_key: "**********" },
+ },
+ tool_call: {
+ id: "secret-tool",
+ type: "function",
+ function: {
+ name: "mcp_call",
+ arguments: '{"api_key":"raw-secret-must-not-export"}',
+ },
+ },
+ tool_name: "mcp_call",
+ summary: "Call the configured service",
+ };
+
+ const markdown = eventsToMarkdown([redactedAction], defaultOptions);
+ const html = eventsToHtml([redactedAction], defaultOptions);
+
+ expect(markdown).toContain("**********");
+ expect(html).toContain("**********");
+ expect(markdown).not.toContain("raw-secret-must-not-export");
+ expect(html).not.toContain("raw-secret-must-not-export");
+ });
+
+ it("neutralizes active content in Markdown and HTML", () => {
+ const unsafeMessage: MessageEvent = {
+ ...userMessage,
+ llm_message: {
+ role: "user",
+ content: [
+ {
+ type: "text",
+ text: "<script>alert(1)</script> [click](javascript:alert(1))\n[ref]: javascript:alert(2)",
+ },
+ ],
+ },
+ };
+ const markdown = eventsToMarkdown([unsafeMessage], defaultOptions);
+ const html = eventsToHtml([unsafeMessage], defaultOptions);
+
+ expect(markdown).not.toContain("<script>");
+ expect(markdown).toContain("&lt;script&gt;");
+ expect(markdown).toContain("\\[click\\](javascript:alert(1))");
+ expect(markdown).toContain("\\[ref\\]: javascript:alert(2)");
+ expect(html).not.toContain("<script>");
+ expect(html).toContain("&lt;script&gt;");
+ });
+
+ it("renders a self-contained HTML document", () => {
+ const html = eventsToHtml(
+ [
+ userMessage,
+ terminalAction,
+ terminalObservation("3 tests passed"),
+ assistantMessage,
+ ],
+ defaultOptions,
+ );
+
+ expect(html).not.toMatch(/<(?:link|script)[^>]+(?:href|src)=/i);
+ expect(html).toMatchSnapshot();
+ });
+});
diff --git a/src/utils/transcript-export/index.ts b/src/utils/transcript-export/index.ts
new file mode 100644
index 0000000000..1364cc4db8
--- /dev/null
+++ b/src/utils/transcript-export/index.ts
@@ -0,0 +1,678 @@
+import type {
+ ActionEvent,
+ OpenHandsEvent,
+ ObservationEvent,
+} from "#/types/agent-server/core";
+import type { TaskAction } from "#/types/agent-server/core/base/action";
+import type { TaskObservation } from "#/types/agent-server/core/base/observation";
+import {
+ isACPToolCallEvent,
+ isActionEvent,
+ isAgentErrorEvent,
+ isConversationStateUpdateEvent,
+ isGoalConversationStateUpdateEvent,
+ isHookExecutionEvent,
+ isMessageEvent,
+ isObservationEvent,
+ isStreamingDeltaEvent,
+ isSwitchLLMObservationEvent,
+} from "#/types/agent-server/type-guards";
+import { handleEventForUI } from "#/utils/handle-event-for-ui";
+import { shouldRenderEvent } from "#/components/conversation-events/chat/event-content-helpers/should-render-event";
+import { parseMessageFromEvent } from "#/components/conversation-events/chat/event-content-helpers/parse-message-from-event";
+import { getActionContent } from "#/components/conversation-events/chat/event-content-helpers/get-action-content";
+import { getObservationContent } from "#/components/conversation-events/chat/event-content-helpers/get-observation-content";
+import {
+ getACPToolCallContent,
+ stripRedundantTitlePrefix,
+} from "#/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content";
+import { groupEvents } from "#/components/conversation-events/chat/group-events";
+import {
+ getActionThoughtText,
+ getReasoningContent,
+ splitInlineThink,
+} from "#/components/conversation-events/chat/event-thought-helpers";
+import i18n from "#/i18n";
+import { I18nKey } from "#/i18n/declaration";
+
+export type TranscriptExportFormat = "markdown" | "html";
+
+export interface TranscriptExportOptions {
+ includeToolDetails: boolean;
+ includeTimestamps: boolean;
+ title?: string | null;
+ model?: string | null;
+}
+
+type TranscriptEntry =
+ | {
+ kind: "message";
+ author: "user" | "assistant";
+ content: string;
+ timestamp: string;
+ }
+ | {
+ kind: "tool";
+ summary: string;
+ details: string;
+ timestamp: string;
+ }
+ | {
+ kind: "error";
+ content: string;
+ timestamp: string;
+ }
+ | {
+ kind: "note";
+ summary: string;
+ content: string;
+ timestamp: string;
+ };
+
+const SAFE_ACTION_DETAIL_KINDS = new Set([
+ "BrowserClickAction",
+ "BrowserCloseTabAction",
+ "BrowserGetContentAction",
+ "BrowserGetStateAction",
+ "BrowserGoBackAction",
+ "BrowserListTabsAction",
+ "BrowserNavigateAction",
+ "BrowserScrollAction",
+ "BrowserSwitchTabAction",
+ "BrowserTypeAction",
+ "ExecuteBashAction",
+ "FileEditorAction",
+ "GlobAction",
+ "GrepAction",
+ "InvokeSkillAction",
+ "MCPToolAction",
+ "StrReplaceEditorAction",
+ "TaskAction",
+ "TaskTrackerAction",
+ "TerminalAction",
+ "ThinkAction",
+]);
+
+const SAFE_OBSERVATION_DETAIL_KINDS = new Set([
+ "BrowserObservation",
+ "CanvasUIObservation",
+ "ExecuteBashObservation",
+ "FileEditorObservation",
+ "GlobObservation",
+ "GrepObservation",
+ "InvokeSkillObservation",
+ "MCPToolObservation",
+ "StrReplaceEditorObservation",
+ "SwitchLLMObservation",
+ "TaskTrackerObservation",
+ "TaskObservation",
+ "TerminalObservation",
+]);
+
+const cleanInlineText = (value: string): string =>
+ value
+ .replace(/[\r\n]+/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+
+const truncate = (value: string, maxLength = 100): string =>
+ value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
+
+const formatTimestamp = (timestamp: string): string => {
+ const date = new Date(timestamp);
+ return Number.isNaN(date.getTime()) ? timestamp : date.toISOString();
+};
+
+const escapeHtml = (value: string): string =>
+ value
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replaceAll('"', "&quot;")
+ .replaceAll("'", "&#039;");
+
+/**
+ * GitHub Markdown permits raw HTML, so dynamic conversation text needs the
+ * same inert representation as the chat's sanitized Markdown renderer.
+ */
+const sanitizeMarkdownText = (value: string): string =>
+ value
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;")
+ .replace(
+ /(!?)\[([^\]]*)\]\(\s*((?:javascript|data|vbscript):[^)]*)\)/gi,
+ "$1\\[$2\\]($3)",
+ )
+ .replace(
+ /^(\s{0,3})\[([^\]]+)\]:(\s*<?(?:javascript|data|vbscript):)/gim,
+ "$1\\[$2\\]:$3",
+ );
+
+const safeTitle = (title?: string | null): string =>
+ cleanInlineText(title || i18n.t(I18nKey.TRANSCRIPT_EXPORT$DEFAULT_TITLE)) ||
+ i18n.t(I18nKey.TRANSCRIPT_EXPORT$DEFAULT_TITLE);
+
+const translatePlain = (
+ key: I18nKey,
+ values?: Record<string, unknown>,
+): string =>
+ cleanInlineText(i18n.t(key, values).replace(/<\/?(?:cmd|path)>/g, ""));
+
+const isServerFallbackSummary = (summary: string): boolean =>
+ /^[a-z][a-z0-9_]*\s*:\s*[[{]/i.test(summary);
+
+const humanizeEventKind = (kind: string): string =>
+ kind
+ .replace(/(?:Action|Observation)$/, "")
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .trim();
+
+const getActionSummary = (event: ActionEvent): string => {
+ const summary = cleanInlineText(event.summary || "");
+ if (summary && !isServerFallbackSummary(summary)) return summary;
+ return (
+ cleanInlineText(event.tool_name) || humanizeEventKind(event.action.kind)
+ );
+};
+
+const getObservationSummary = (
+ event: ObservationEvent,
+ correspondingAction?: ActionEvent,
+): string => {
+ if (correspondingAction) return getActionSummary(correspondingAction);
+ return (
+ cleanInlineText(event.tool_name) ||
+ humanizeEventKind(event.observation.kind)
+ );
+};
+
+const getTextContent = (
+ content: Array<{ type: string; text?: string }>,
+): string =>
+ content
+ .filter(
+ (item): item is { type: "text"; text: string } =>
+ item.type === "text" && typeof item.text === "string",
+ )
+ .map((item) => item.text)
+ .join("\n");
+
+const getTaskActionDetails = (action: TaskAction): string =>
+ [
+ `${i18n.t(I18nKey.TASK$SUBAGENT)}: ${action.subagent_type}`,
+ `${i18n.t(I18nKey.TASK$QUERY)}:\n${action.prompt}`,
+ ].join("\n\n");
+
+const getTaskObservationDetails = (
+ observation: TaskObservation,
+ correspondingAction?: ActionEvent,
+): string => {
+ const taskAction =
+ correspondingAction?.action.kind === "TaskAction"
+ ? correspondingAction.action
+ : undefined;
+ return [
+ `${i18n.t(I18nKey.TASK$SUBAGENT)}: ${observation.subagent}`,
+ `${i18n.t(I18nKey.TASK$TASK_ID)}: ${observation.task_id}`,
+ taskAction ? `${i18n.t(I18nKey.TASK$QUERY)}:\n${taskAction.prompt}` : "",
+ `${i18n.t(I18nKey.TASK$RESULT)}:\n${getTextContent(observation.content)}`,
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+};
+
+const getSafeActionDetails = (event: ActionEvent): string => {
+ if (event.action.kind === "TaskAction") {
+ return getTaskActionDetails(event.action);
+ }
+ return SAFE_ACTION_DETAIL_KINDS.has(event.action.kind)
+ ? getActionContent(event)
+ : "";
+};
+
+const getSafeObservationDetails = (
+ event: ObservationEvent,
+ correspondingAction?: ActionEvent,
+): string => {
+ if (event.observation.kind === "TaskObservation") {
+ return getTaskObservationDetails(event.observation, correspondingAction);
+ }
+ return SAFE_OBSERVATION_DETAIL_KINDS.has(event.observation.kind)
+ ? getObservationContent(event)
+ : "";
+};
+
+const getHookDetails = (event: OpenHandsEvent): string => {
+ if (!isHookExecutionEvent(event)) return "";
+ return [event.reason, event.error, event.stdout, event.stderr]
+ .filter((value): value is string => Boolean(value?.trim()))
+ .join("\n\n");
+};
+
+const getActionNarration = (event: ActionEvent): string =>
+ [getReasoningContent(event), getActionThoughtText(event)]
+ .map((content) => content.trim())
+ .filter(Boolean)
+ .join("\n\n");
+
+const canRenderActionNarration = (event: ActionEvent): boolean =>
+ !["FinishAction", "SwitchLLMAction", "ThinkAction"].includes(
+ event.action.kind,
+ );
+
+const buildTranscriptEntries = (
+ events: OpenHandsEvent[],
+ includeToolDetails: boolean,
+): TranscriptEntry[] => {
+ const uiEvents = events.reduce<OpenHandsEvent[]>((current, event) => {
+ try {
+ return handleEventForUI(event, current);
+ } catch {
+ return current;
+ }
+ }, []);
+ const actionsById = new Map(
+ events.filter(isActionEvent).map((event) => [event.id, event]),
+ );
+ const entries: TranscriptEntry[] = [];
+ const emittedNarrationActionIds = new Set<string>();
+ const renderableEvents = uiEvents.filter(
+ (event) =>
+ (isSwitchLLMObservationEvent(event) && !event.observation.is_error) ||
+ shouldRenderEvent(event),
+ );
+ const renderedItems = groupEvents(
+ renderableEvents,
+ Number.MAX_SAFE_INTEGER,
+ events,
+ );
+
+ const addActionNarration = (action: ActionEvent) => {
+ if (
+ emittedNarrationActionIds.has(action.id) ||
+ !canRenderActionNarration(action)
+ ) {
+ return;
+ }
+ emittedNarrationActionIds.add(action.id);
+ const content = getActionNarration(action);
+ if (content) {
+ entries.push({
+ kind: "message",
+ author: "assistant",
+ content,
+ timestamp: action.timestamp,
+ });
+ }
+ };
+
+ for (const item of renderedItems) {
+ if (item.kind === "group") continue;
+ if (item.kind === "thought") {
+ addActionNarration(item.action);
+ continue;
+ }
+
+ const { event } = item;
+ try {
+ const narrationAction = isActionEvent(event)
+ ? event
+ : isObservationEvent(event)
+ ? actionsById.get(event.action_id)
+ : undefined;
+ if (narrationAction) addActionNarration(narrationAction);
+
+ if (isSwitchLLMObservationEvent(event) && !event.observation.is_error) {
+ entries.push({
+ kind: "note",
+ summary: translatePlain(I18nKey.MODEL$SWITCHED_TO_PROFILE, {
+ name: event.observation.profile_name,
+ }),
+ content: [
+ event.observation.active_model
+ ? `${i18n.t(I18nKey.TRANSCRIPT_EXPORT$MODEL)}: ${event.observation.active_model}`
+ : "",
+ event.observation.reason
+ ? `${i18n.t(I18nKey.TRANSCRIPT_EXPORT$REASON)}: ${event.observation.reason}`
+ : "",
+ ]
+ .filter(Boolean)
+ .join("\n"),
+ timestamp: event.timestamp,
+ });
+ continue;
+ }
+
+ if (isMessageEvent(event)) {
+ const parsed = parseMessageFromEvent(event).trim();
+ if (event.source === "agent") {
+ const { reasoning, message } = splitInlineThink(parsed);
+ [reasoning, message].filter(Boolean).forEach((content) => {
+ entries.push({
+ kind: "message",
+ author: "assistant",
+ content,
+ timestamp: event.timestamp,
+ });
+ });
+ } else if (parsed) {
+ entries.push({
+ kind: "message",
+ author: "user",
+ content: parsed,
+ timestamp: event.timestamp,
+ });
+ }
+ continue;
+ }
+
+ if (isStreamingDeltaEvent(event)) {
+ const { reasoning: inlineThink, message } = splitInlineThink(
+ event.content ?? "",
+ { streaming: true },
+ );
+ const reasoningContent = [
+ event.reasoning_content?.trim() || "",
+ inlineThink,
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+ if (reasoningContent) {
+ entries.push({
+ kind: "message",
+ author: "assistant",
+ content: reasoningContent,
+ timestamp: event.timestamp,
+ });
+ }
+ if (message.trim()) {
+ entries.push({
+ kind: "message",
+ author: "assistant",
+ content: message.trim(),
+ timestamp: event.timestamp,
+ });
+ }
+ continue;
+ }
+
+ if (isAgentErrorEvent(event)) {
+ entries.push({
+ kind: "error",
+ content: event.error,
+ timestamp: event.timestamp,
+ });
+ continue;
+ }
+
+ if (isActionEvent(event)) {
+ if (event.action.kind === "FinishAction") {
+ const content = event.action.message.trim();
+ if (content) {
+ entries.push({
+ kind: "message",
+ author: "assistant",
+ content,
+ timestamp: event.timestamp,
+ });
+ }
+ } else {
+ entries.push({
+ kind: "tool",
+ summary: getActionSummary(event),
+ details: includeToolDetails ? getSafeActionDetails(event) : "",
+ timestamp: event.timestamp,
+ });
+ }
+ continue;
+ }
+
+ if (isObservationEvent(event)) {
+ const correspondingAction = actionsById.get(event.action_id);
+ entries.push({
+ kind: "tool",
+ summary: getObservationSummary(event, correspondingAction),
+ details: includeToolDetails
+ ? getSafeObservationDetails(event, correspondingAction)
+ : "",
+ timestamp: event.timestamp,
+ });
+ continue;
+ }
+
+ if (isACPToolCallEvent(event)) {
+ entries.push({
+ kind: "tool",
+ summary:
+ stripRedundantTitlePrefix(event) ||
+ i18n.t(I18nKey.ACTION_MESSAGE$ACP_TOOL),
+ details: includeToolDetails ? getACPToolCallContent(event) : "",
+ timestamp: event.timestamp,
+ });
+ continue;
+ }
+
+ if (isHookExecutionEvent(event)) {
+ entries.push({
+ kind: "tool",
+ summary: i18n.t(I18nKey.TRANSCRIPT_EXPORT$HOOK, {
+ command: truncate(cleanInlineText(event.hook_command), 100),
+ }),
+ details: includeToolDetails ? getHookDetails(event) : "",
+ timestamp: event.timestamp,
+ });
+ continue;
+ }
+
+ if (
+ isConversationStateUpdateEvent(event) &&
+ isGoalConversationStateUpdateEvent(event)
+ ) {
+ entries.push({
+ kind: "note",
+ summary: `${i18n.t(I18nKey.GOAL$PREFIX)} ${i18n.t(
+ {
+ running: I18nKey.GOAL$STATUS_RUNNING,
+ complete: I18nKey.GOAL$STATUS_COMPLETE,
+ capped: I18nKey.GOAL$STATUS_CAPPED,
+ interrupted: I18nKey.GOAL$STATUS_INTERRUPTED,
+ }[event.value.status],
+ )}`,
+ content: [event.value.objective, event.value.verdict?.missing || ""]
+ .filter(Boolean)
+ .join("\n\n"),
+ timestamp: event.timestamp,
+ });
+ }
+ } catch {
+ // Runtime event payloads may be older than the local TypeScript schema.
+ // Skip malformed entries instead of aborting an otherwise valid export.
+ }
+ }
+
+ return entries;
+};
+
+const markdownTimestamp = (
+ entry: TranscriptEntry,
+ options: TranscriptExportOptions,
+): string =>
+ options.includeTimestamps
+ ? `<sub>${escapeHtml(formatTimestamp(entry.timestamp))}</sub>\n\n`
+ : "";
+
+const markdownFence = (content: string): string => {
+ const longestRun = Math.max(
+ 0,
+ ...Array.from(content.matchAll(/`+/g), (match) => match[0].length),
+ );
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
+ return `${fence}text\n${content}\n${fence}`;
+};
+
+export const eventsToMarkdown = (
+ events: OpenHandsEvent[],
+ options: TranscriptExportOptions,
+): string => {
+ const lines = [`# ${sanitizeMarkdownText(safeTitle(options.title))}`, ""];
+
+ if (options.model) {
+ lines.push(
+ `**${i18n.t(I18nKey.TRANSCRIPT_EXPORT$MODEL)}:** ${sanitizeMarkdownText(cleanInlineText(options.model))}`,
+ "",
+ );
+ }
+
+ for (const entry of buildTranscriptEntries(
+ events,
+ options.includeToolDetails,
+ )) {
+ const timestamp = markdownTimestamp(entry, options);
+ if (entry.kind === "message") {
+ const author =
+ entry.author === "user"
+ ? i18n.t(I18nKey.TRANSCRIPT_EXPORT$USER)
+ : i18n.t(I18nKey.CHAT_INTERFACE$ASSISTANT);
+ lines.push(
+ `## ${author}`,
+ "",
+ timestamp + sanitizeMarkdownText(entry.content),
+ "",
+ );
+ } else if (entry.kind === "error") {
+ const quoted = entry.content
+ .split("\n")
+ .map((line) => `> ${sanitizeMarkdownText(line)}`)
+ .join("\n");
+ lines.push(
+ `## ${i18n.t(I18nKey.COMMON$ERROR)}`,
+ "",
+ timestamp + quoted,
+ "",
+ );
+ } else if (entry.kind === "note") {
+ lines.push(
+ `> **${escapeHtml(entry.summary)}**`,
+ "",
+ timestamp + sanitizeMarkdownText(entry.content),
+ "",
+ );
+ } else if (options.includeToolDetails && entry.details) {
+ lines.push(
+ "<details>",
+ `<summary><strong>${escapeHtml(i18n.t(I18nKey.TRANSCRIPT_EXPORT$TOOL))}:</strong> ${escapeHtml(entry.summary)}</summary>`,
+ "",
+ timestamp + markdownFence(entry.details),
+ "",
+ "</details>",
+ "",
+ );
+ } else {
+ const timestampMarkup = timestamp ? `<br>${timestamp.trimEnd()}` : "";
+ lines.push(
+ `<p><strong>${escapeHtml(i18n.t(I18nKey.TRANSCRIPT_EXPORT$TOOL))}:</strong> ${escapeHtml(entry.summary)}${timestampMarkup}</p>`,
+ "",
+ );
+ }
+ }
+
+ return `${lines.join("\n").trim()}\n`;
+};
+
+const htmlTimestamp = (
+ entry: TranscriptEntry,
+ options: TranscriptExportOptions,
+): string => {
+ if (!options.includeTimestamps) return "";
+ const timestamp = formatTimestamp(entry.timestamp);
+ return `<time datetime="${escapeHtml(timestamp)}">${escapeHtml(timestamp)}</time>`;
+};
+
+export const eventsToHtml = (
+ events: OpenHandsEvent[],
+ options: TranscriptExportOptions,
+): string => {
+ const title = safeTitle(options.title);
+ const body = buildTranscriptEntries(events, options.includeToolDetails)
+ .map((entry) => {
+ const timestamp = htmlTimestamp(entry, options);
+ if (entry.kind === "message") {
+ const author =
+ entry.author === "user"
+ ? i18n.t(I18nKey.TRANSCRIPT_EXPORT$USER)
+ : i18n.t(I18nKey.CHAT_INTERFACE$ASSISTANT);
+ return `<section class="message ${entry.author.toLowerCase()}">
+ <header><h2>${escapeHtml(author)}</h2>${timestamp}</header>
+ <div class="content">${escapeHtml(entry.content)}</div>
+</section>`;
+ }
+ if (entry.kind === "error") {
+ return `<section class="message error">
+ <header><h2>${escapeHtml(i18n.t(I18nKey.COMMON$ERROR))}</h2>${timestamp}</header>
+ <div class="content">${escapeHtml(entry.content)}</div>
+</section>`;
+ }
+ if (entry.kind === "note") {
+ return `<aside class="note">
+ <header><strong>${escapeHtml(entry.summary)}</strong>${timestamp}</header>
+ ${entry.content ? `<div class="content">${escapeHtml(entry.content)}</div>` : ""}
+</aside>`;
+ }
+ const details =
+ options.includeToolDetails && entry.details
+ ? `<details>
+ <summary><strong>${escapeHtml(i18n.t(I18nKey.TRANSCRIPT_EXPORT$TOOL))}:</strong> ${escapeHtml(entry.summary)}${timestamp}</summary>
+ <pre>${escapeHtml(entry.details)}</pre>
+</details>`
+ : `<div class="tool-summary"><strong>${escapeHtml(i18n.t(I18nKey.TRANSCRIPT_EXPORT$TOOL))}:</strong> ${escapeHtml(entry.summary)}${timestamp}</div>`;
+ return details;
+ })
+ .join("\n");
+
+ const model = options.model
+ ? `<p class="model"><strong>${escapeHtml(i18n.t(I18nKey.TRANSCRIPT_EXPORT$MODEL))}:</strong> ${escapeHtml(cleanInlineText(options.model))}</p>`
+ : "";
+
+ return `<!doctype html>
+<html lang="${escapeHtml(i18n.resolvedLanguage || i18n.language || "en")}">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:">
+ <title>${escapeHtml(title)}</title>
+ <style>
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
+ body { margin: 0; background: #111827; color: #e5e7eb; line-height: 1.55; }
+ main { box-sizing: border-box; width: min(860px, 100%); margin: 0 auto; padding: 48px 24px 80px; }
+ h1 { margin: 0; font-size: 2rem; }
+ h2 { margin: 0; font-size: 1rem; }
+ .model { margin: 8px 0 32px; color: #9ca3af; }
+ .message, details, .tool-summary, .note { margin: 16px 0; border: 1px solid #374151; border-radius: 10px; padding: 16px; background: #1f2937; }
+ .user { border-left: 4px solid #60a5fa; }
+ .assistant { border-left: 4px solid #34d399; }
+ .error { border-left: 4px solid #f87171; }
+ .note { border-left: 4px solid #a78bfa; }
+ header, summary, .tool-summary { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; }
+ summary { cursor: pointer; }
+ time { flex: none; color: #9ca3af; font-size: .75rem; font-weight: 400; }
+ .content { margin-top: 10px; white-space: pre-wrap; overflow-wrap: anywhere; }
+ pre { margin: 14px 0 0; padding: 14px; overflow-x: auto; border-radius: 7px; background: #111827; color: #d1d5db; white-space: pre-wrap; overflow-wrap: anywhere; }
+ @media (prefers-color-scheme: light) {
+ body { background: #f9fafb; color: #111827; }
+ .message, details, .tool-summary, .note { border-color: #d1d5db; background: #fff; }
+ pre { background: #f3f4f6; color: #1f2937; }
+ .model, time { color: #6b7280; }
+ }
+ </style>
+</head>
+<body>
+ <main>
+ <h1>${escapeHtml(title)}</h1>
+ ${model}
+ ${body}
+ </main>
+</body>
+</html>
+`;
+};
diff --git a/src/utils/transcript-export/load-complete-events.test.ts b/src/utils/transcript-export/load-complete-events.test.ts
new file mode 100644
index 0000000000..5fa6e21eac
--- /dev/null
+++ b/src/utils/transcript-export/load-complete-events.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it, vi } from "vitest";
+import type { MessageEvent } from "#/types/agent-server/core";
+import {
+ loadCompleteTranscriptEvents,
+ TRANSCRIPT_HISTORY_PAGE_SIZE,
+} from "./load-complete-events";
+
+const timestamp = "2026-07-10T12:34:56.000Z";
+
+const makeMessage = (index: number): MessageEvent => ({
+ id: `event-${index.toString().padStart(3, "0")}`,
+ timestamp: new Date(Date.UTC(2026, 6, 10, 0, 0, index)).toISOString(),
+ source: "user",
+ llm_message: {
+ role: "user",
+ content: [{ type: "text", text: `Message ${index}` }],
+ },
+ activated_microagents: [],
+ extended_content: [],
+});
+
+describe("loadCompleteTranscriptEvents", () => {
+ it("paginates beyond the 50 events initially loaded by the chat", async () => {
+ const allEvents = Array.from({ length: 225 }, (_, index) =>
+ makeMessage(index),
+ );
+ const loadedEvents = allEvents.slice(-50);
+ const descendingEvents = allEvents.slice().reverse();
+ const searchEvents = vi.fn(
+ async ({ limit, pageId }: { limit: number; pageId?: string }) => {
+ const offset = Number(pageId ?? 0);
+ const items = descendingEvents.slice(offset, offset + limit);
+ const nextOffset = offset + items.length;
+ return {
+ items,
+ next_page_id:
+ nextOffset < descendingEvents.length ? String(nextOffset) : null,
+ };
+ },
+ );
+
+ const result = await loadCompleteTranscriptEvents(
+ loadedEvents,
+ searchEvents,
+ );
+
+ expect(result).toEqual(allEvents);
+ expect(searchEvents).toHaveBeenCalledTimes(3);
+ expect(searchEvents).toHaveBeenNthCalledWith(1, {
+ limit: TRANSCRIPT_HISTORY_PAGE_SIZE,
+ sortOrder: "TIMESTAMP_DESC",
+ strictPagination: true,
+ });
+ });
+
+ it("rejects a repeated full page when completeness cannot be proven", async () => {
+ const page = Array.from(
+ { length: TRANSCRIPT_HISTORY_PAGE_SIZE },
+ (_, index) => makeMessage(index),
+ ).reverse();
+ const searchEvents = vi.fn().mockResolvedValue({ items: page });
+
+ await expect(
+ loadCompleteTranscriptEvents(page, searchEvents),
+ ).rejects.toThrow("cannot prove that all events were loaded");
+ expect(searchEvents).toHaveBeenCalledTimes(1);
+ });
+
+ it("uses cursors without dropping events at a shared timestamp boundary", async () => {
+ const allEvents = Array.from({ length: 125 }, (_, index) => ({
+ ...makeMessage(index),
+ timestamp,
+ }));
+ const descendingEvents = allEvents.slice().reverse();
+ const searchEvents = vi.fn(
+ async ({ limit, pageId }: { limit: number; pageId?: string }) => {
+ const offset = Number(pageId ?? 0);
+ const items = descendingEvents.slice(offset, offset + limit);
+ return {
+ items,
+ next_page_id:
+ offset + items.length < descendingEvents.length
+ ? String(offset + items.length)
+ : null,
+ };
+ },
+ );
+
+ const result = await loadCompleteTranscriptEvents([], searchEvents);
+
+ expect(result).toEqual(allEvents);
+ expect(searchEvents).toHaveBeenNthCalledWith(2, {
+ limit: TRANSCRIPT_HISTORY_PAGE_SIZE,
+ pageId: "100",
+ sortOrder: "TIMESTAMP_DESC",
+ strictPagination: true,
+ });
+ });
+
+ it("does not let live-only store events mask unfetched persisted history", async () => {
+ const persistedEvents = Array.from({ length: 150 }, (_, index) =>
+ makeMessage(index),
+ );
+ const liveEvents = Array.from({ length: 50 }, (_, index) =>
+ makeMessage(index + 150),
+ );
+ const searchEvents = vi.fn(
+ async ({
+ limit,
+ timestampLt,
+ }: {
+ limit: number;
+ timestampLt?: string;
+ }) => ({
+ items: persistedEvents
+ .filter((event) =>
+ timestampLt ? event.timestamp < timestampLt : true,
+ )
+ .slice()
+ .reverse()
+ .slice(0, limit),
+ next_page_id: null,
+ }),
+ );
+
+ const result = await loadCompleteTranscriptEvents(
+ liveEvents,
+ searchEvents,
+ persistedEvents.length,
+ );
+
+ expect(result).toEqual([...persistedEvents, ...liveEvents]);
+ expect(searchEvents).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects malformed history pages", async () => {
+ await expect(
+ loadCompleteTranscriptEvents([], async () => ({ items: null as never })),
+ ).rejects.toThrow("expected page.items to be an array");
+ });
+
+ it("rejects a partial export when the server reports more events", async () => {
+ await expect(
+ loadCompleteTranscriptEvents(
+ [],
+ async () => ({ items: [makeMessage(1)], next_page_id: null }),
+ 2,
+ ),
+ ).rejects.toThrow("Transcript history is incomplete");
+ });
+});
diff --git a/src/utils/transcript-export/load-complete-events.ts b/src/utils/transcript-export/load-complete-events.ts
new file mode 100644
index 0000000000..7d776194d6
--- /dev/null
+++ b/src/utils/transcript-export/load-complete-events.ts
@@ -0,0 +1,137 @@
+import type { OpenHandsEvent } from "#/types/agent-server/core";
+
+export const TRANSCRIPT_HISTORY_PAGE_SIZE = 100;
+
+interface TranscriptEventSearchOptions {
+ limit: number;
+ sortOrder: "TIMESTAMP_DESC";
+ pageId?: string;
+ timestampLt?: string;
+ strictPagination: true;
+}
+
+interface TranscriptEventPage {
+ items: OpenHandsEvent[];
+ next_page_id?: string | null;
+}
+
+type SearchTranscriptEvents = (
+ options: TranscriptEventSearchOptions,
+) => Promise<TranscriptEventPage>;
+
+const compareEventTimestamps = (
+ first: OpenHandsEvent,
+ second: OpenHandsEvent,
+): number => first.timestamp.localeCompare(second.timestamp);
+
+/**
+ * Loads the persisted history from the newest page back to the beginning,
+ * then merges any live store events that have not persisted yet. The timestamp
+ * anchor matches the chat's existing history pagination, while id-based
+ * de-duplication keeps the result stable if pages overlap.
+ */
+export const loadCompleteTranscriptEvents = async (
+ loadedEvents: OpenHandsEvent[],
+ searchEvents: SearchTranscriptEvents,
+ expectedEventCount?: number,
+): Promise<OpenHandsEvent[]> => {
+ const persistedDescending: OpenHandsEvent[] = [];
+ const fetchedEventIds = new Set<string>();
+ const seenPageIds = new Set<string>();
+ let oldestTimestamp: string | undefined;
+ let pageId: string | undefined;
+ let usedCursor = false;
+ let usingTimestampFallback = false;
+
+ while (true) {
+ const page = await searchEvents({
+ limit: TRANSCRIPT_HISTORY_PAGE_SIZE,
+ sortOrder: "TIMESTAMP_DESC",
+ strictPagination: true,
+ ...(pageId ? { pageId } : {}),
+ ...(oldestTimestamp ? { timestampLt: oldestTimestamp } : {}),
+ });
+
+ if (!Array.isArray(page.items)) {
+ throw new Error(
+ "Invalid transcript history response: expected page.items to be an array.",
+ );
+ }
+
+ persistedDescending.push(...page.items);
+ let pageOldestTimestamp: string | undefined;
+ let addedEvent = false;
+ page.items.forEach((event) => {
+ if (!fetchedEventIds.has(event.id)) {
+ fetchedEventIds.add(event.id);
+ addedEvent = true;
+ }
+ if (!pageOldestTimestamp || event.timestamp < pageOldestTimestamp) {
+ pageOldestTimestamp = event.timestamp;
+ }
+ });
+
+ if (page.next_page_id) {
+ if (seenPageIds.has(page.next_page_id)) {
+ throw new Error(
+ "Transcript history pagination repeated a page cursor.",
+ );
+ }
+ seenPageIds.add(page.next_page_id);
+ pageId = page.next_page_id;
+ oldestTimestamp = undefined;
+ usedCursor = true;
+ continue;
+ }
+
+ // Once a server supplies a cursor, a page without a next cursor is an
+ // explicit exhaustion signal, even when the final page is exactly full.
+ if (usedCursor && !usingTimestampFallback) break;
+ if (page.items.length < TRANSCRIPT_HISTORY_PAGE_SIZE) break;
+
+ // Some older servers omit cursors for filtered searches. A timestamp
+ // fallback is safe to attempt only when an independent event count can
+ // prove completeness; otherwise fail instead of exporting a partial tail.
+ if (expectedEventCount === undefined) {
+ throw new Error(
+ "Transcript history pagination cannot prove that all events were loaded.",
+ );
+ }
+ if (!pageOldestTimestamp) {
+ throw new Error("Transcript history pagination did not advance.");
+ }
+ if (
+ oldestTimestamp &&
+ (!addedEvent || pageOldestTimestamp >= oldestTimestamp)
+ ) {
+ throw new Error("Transcript history pagination did not advance.");
+ }
+
+ pageId = undefined;
+ oldestTimestamp = pageOldestTimestamp;
+ usingTimestampFallback = true;
+ }
+
+ const eventsById = new Map<string, OpenHandsEvent>();
+ persistedDescending
+ .slice()
+ .reverse()
+ .forEach((event) => {
+ if (!eventsById.has(event.id)) eventsById.set(event.id, event);
+ });
+ loadedEvents.forEach((event) => {
+ if (!eventsById.has(event.id)) eventsById.set(event.id, event);
+ });
+ // Array.prototype.sort is stable, so equal-timestamp events keep the causal
+ // order returned by the server/store rather than being reordered by id.
+ const completeEvents = [...eventsById.values()].sort(compareEventTimestamps);
+ if (
+ expectedEventCount !== undefined &&
+ fetchedEventIds.size < expectedEventCount
+ ) {
+ throw new Error(
+ `Transcript history is incomplete: expected ${expectedEventCount} persisted events, received ${fetchedEventIds.size}.`,
+ );
+ }
+ return completeEvents;
+};