Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Add Assistant transcript actions

rcourtman29c09c6d1634
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
index 357507f9f5..caa4e194bf 100644
--- a/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
+++ b/frontend-modern/src/components/AI/Chat/__tests__/AIChat.test.tsx
@@ -365,6 +365,14 @@ async function waitForProviderCheckSettled() {
});
}
+const readBlobText = (blob: Blob): Promise<string> =>
+ new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result || ''));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(blob);
+ });
+
// ── Setup / teardown ───────────────────────────────────────────────────────
beforeEach(() => {
@@ -424,6 +432,188 @@ describe('AIChat', () => {
expect(screen.getByText('Pulse Assistant')).toBeInTheDocument();
});
+ it('disables transcript actions until the current session has messages', () => {
+ renderChat();
+
+ expect(screen.getByRole('button', { name: 'Copy Assistant transcript' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Export Assistant transcript' })).toBeDisabled();
+ });
+
+ it('copies the current Assistant transcript from the header', async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ value: { writeText },
+ configurable: true,
+ });
+ mockChat.sessionId.mockReturnValue('session-123456789');
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'how many devices in this',
+ timestamp: new Date('2026-06-06T12:34:56Z'),
+ },
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content: 'There are 4,358 entries in /dev.',
+ timestamp: new Date('2026-06-06T12:35:01Z'),
+ model: 'openrouter:deepseek/deepseek-chat',
+ streamEvents: [
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: JSON.stringify({
+ action: 'exec',
+ command: 'ls /dev | wc -l',
+ target_host: 'current_resource',
+ }),
+ output: '4358\n',
+ success: true,
+ },
+ },
+ {
+ type: 'content',
+ content: 'There are 4,358 entries in /dev.',
+ },
+ ],
+ },
+ ]);
+
+ renderChat();
+ fireEvent.click(screen.getByRole('button', { name: 'Copy Assistant transcript' }));
+
+ await waitFor(() => {
+ expect(writeText).toHaveBeenCalled();
+ });
+ const transcript = writeText.mock.calls[0][0] as string;
+ expect(transcript).toContain('Session ID: session-123456789');
+ expect(transcript).toContain('how many devices in this');
+ expect(transcript).toContain('[tool:read]');
+ expect(transcript).toContain('ls /dev | wc -l');
+ expect(transcript).toContain('There are 4,358 entries in /dev.');
+ expect(transcript).not.toContain('pulse_read');
+ await waitFor(() => {
+ expect(mockNotificationStore.success).toHaveBeenCalledWith(
+ 'Assistant transcript copied',
+ 2000,
+ );
+ });
+ });
+
+ it('opens a manual transcript panel when clipboard writes are blocked', async () => {
+ const writeText = vi.fn().mockRejectedValue(new DOMException('Denied', 'NotAllowedError'));
+ Object.defineProperty(navigator, 'clipboard', {
+ value: { writeText },
+ configurable: true,
+ });
+ mockChat.sessionId.mockReturnValue('session-clipboard-denied');
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'copy fallback check',
+ timestamp: new Date('2026-06-06T12:34:56Z'),
+ },
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content: 'fallback transcript body',
+ timestamp: new Date('2026-06-06T12:35:01Z'),
+ },
+ ]);
+
+ renderChat();
+ fireEvent.click(screen.getByRole('button', { name: 'Copy Assistant transcript' }));
+
+ const transcriptField = await screen.findByLabelText('Assistant transcript');
+ const transcriptValue = (transcriptField as HTMLTextAreaElement).value;
+ expect(transcriptValue).toContain('copy fallback check');
+ expect(transcriptValue).toContain('fallback transcript body');
+ expect(document.activeElement).toBe(transcriptField);
+ expect(mockNotificationStore.warning).toHaveBeenCalledWith(
+ 'Clipboard blocked; transcript opened for manual copy',
+ 4000,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close Assistant transcript copy panel' }));
+
+ await waitFor(() => {
+ expect(screen.queryByLabelText('Assistant transcript')).not.toBeInTheDocument();
+ });
+ });
+
+ it('exports the current Assistant transcript from the header', async () => {
+ const originalCreateObjectURL = URL.createObjectURL;
+ const originalRevokeObjectURL = URL.revokeObjectURL;
+ const createObjectURL = vi.fn((blob: Blob) => {
+ void blob;
+ return 'blob:assistant-transcript';
+ });
+ const revokeObjectURL = vi.fn();
+ Object.defineProperty(URL, 'createObjectURL', {
+ value: createObjectURL,
+ configurable: true,
+ });
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ value: revokeObjectURL,
+ configurable: true,
+ });
+ const originalCreateElement = document.createElement.bind(document);
+ const createElementSpy = vi.spyOn(document, 'createElement').mockImplementation((tagName) => {
+ const element = originalCreateElement(tagName);
+ if (tagName.toLowerCase() === 'a') {
+ vi.spyOn(element as HTMLAnchorElement, 'click').mockImplementation(() => undefined);
+ }
+ return element;
+ });
+ mockChat.sessionId.mockReturnValue('session-abcdef123456');
+ mockChat.messages.mockReturnValue([
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'summarize the session',
+ timestamp: new Date('2026-06-06T12:34:56Z'),
+ },
+ ]);
+
+ try {
+ renderChat();
+ fireEvent.click(screen.getByRole('button', { name: 'Export Assistant transcript' }));
+
+ await waitFor(() => {
+ expect(createObjectURL).toHaveBeenCalled();
+ });
+ const createdBlob = createObjectURL.mock.calls[0]?.[0] as unknown as Blob;
+ expect(await readBlobText(createdBlob)).toContain('summarize the session');
+ const anchor = createElementSpy.mock.results
+ .map((result) => result.value)
+ .find((element): element is HTMLAnchorElement => element instanceof HTMLAnchorElement);
+ expect(anchor?.download).toBe('pulse-assistant-session-abcdef123456.md');
+ expect(anchor?.click).toHaveBeenCalled();
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:assistant-transcript');
+ expect(mockNotificationStore.success).toHaveBeenCalledWith(
+ 'Assistant transcript exported',
+ 2000,
+ );
+ } finally {
+ createElementSpy.mockRestore();
+ if (originalCreateObjectURL) {
+ Object.defineProperty(URL, 'createObjectURL', {
+ value: originalCreateObjectURL,
+ configurable: true,
+ });
+ }
+ if (originalRevokeObjectURL) {
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ value: originalRevokeObjectURL,
+ configurable: true,
+ });
+ }
+ }
+ });
+
it('renders the input textarea', () => {
renderChat();
expect(screen.getByPlaceholderText('Ask about your infrastructure...')).toBeInTheDocument();
diff --git a/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts b/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts
new file mode 100644
index 0000000000..4b720c8c6c
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/__tests__/transcriptExport.test.ts
@@ -0,0 +1,240 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { ChatMessage } from '../types';
+import {
+ buildAssistantTranscriptFilename,
+ downloadAssistantTranscriptFile,
+ formatAssistantTranscript,
+ hasAssistantTranscriptContent,
+} from '../transcriptExport';
+
+const timestamp = new Date('2026-06-06T12:34:56Z');
+
+const readBlobText = (blob: Blob): Promise<string> =>
+ new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result || ''));
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(blob);
+ });
+
+describe('Assistant transcript export', () => {
+ it('formats a clean session transcript with status and tool summaries', () => {
+ const messages: ChatMessage[] = [
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'how many devices in this',
+ timestamp,
+ },
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content: 'There are 4,358 entries in /dev.',
+ timestamp,
+ completedAt: new Date('2026-06-06T12:35:02Z'),
+ model: 'openrouter:deepseek/deepseek-chat',
+ streamEvents: [
+ {
+ type: 'workflow_status',
+ workflowStatus: {
+ message: 'Checking device nodes',
+ phase: 'tool',
+ },
+ },
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_read',
+ input: JSON.stringify({
+ action: 'exec',
+ command: 'ls /dev | wc -l',
+ target_host: 'current_resource',
+ }),
+ output: '4358\n',
+ success: true,
+ },
+ },
+ {
+ type: 'content',
+ content: 'There are 4,358 entries in /dev.',
+ },
+ ],
+ },
+ ];
+
+ const transcript = formatAssistantTranscript({
+ messages,
+ session: { id: 'session-123456789', title: 'Device count' },
+ generatedAt: timestamp,
+ getModelRouteLabel: () => 'DeepSeek via OpenRouter',
+ });
+
+ expect(transcript).toContain('# Pulse Assistant Transcript');
+ expect(transcript).toContain('Session: Device count');
+ expect(transcript).toContain('Session ID: session-123456789');
+ expect(transcript).toContain('## User');
+ expect(transcript).toContain('how many devices in this');
+ expect(transcript).toContain('## Pulse Assistant');
+ expect(transcript).toContain('Model: DeepSeek via OpenRouter');
+ expect(transcript).toContain('[status] Checking device nodes');
+ expect(transcript).toContain('[tool:read]');
+ expect(transcript).toContain('ls /dev | wc -l');
+ expect(transcript).toContain('completed');
+ expect(transcript).toContain('There are 4,358 entries in /dev.');
+ expect(transcript).not.toContain('4358\n\n##');
+ });
+
+ it('keeps hidden reasoning and raw tool-call leaks out of default transcripts', () => {
+ const messages: ChatMessage[] = [
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content:
+ "I'llcheckthedevicenodesinsidethecontainertoanswerthat.Letmecounttheentriesin/devandlisttheblockdevices.pulse_read(target_host=\"current_resource\",command=\"ls/dev|wc-l\")",
+ thinking: 'Private chain of thought',
+ timestamp,
+ streamEvents: [
+ {
+ type: 'thinking',
+ thinking: 'Private chain of thought',
+ },
+ ],
+ },
+ ];
+
+ const transcript = formatAssistantTranscript({
+ messages,
+ generatedAt: timestamp,
+ });
+
+ expect(transcript).toBe('');
+ expect(transcript).not.toContain('Private chain of thought');
+ expect(transcript).not.toContain('pulse_read');
+ expect(transcript).not.toContain('ls/dev');
+ });
+
+ it('can include thinking and tool output when explicitly requested', () => {
+ const messages: ChatMessage[] = [
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ streamEvents: [
+ {
+ type: 'thinking',
+ thinking: 'Checking the live state.',
+ },
+ {
+ type: 'tool',
+ tool: {
+ name: 'pulse_get_active_alerts',
+ input: JSON.stringify({ action: 'list' }),
+ output: 'No active alerts',
+ success: true,
+ },
+ },
+ ],
+ },
+ ];
+
+ const transcript = formatAssistantTranscript({
+ messages,
+ generatedAt: timestamp,
+ includeThinking: true,
+ includeToolOutput: true,
+ });
+
+ expect(transcript).toContain('[thinking]');
+ expect(transcript).toContain('Checking the live state.');
+ expect(transcript).toContain('No active alerts');
+ });
+
+ it('reports whether a transcript has content', () => {
+ expect(hasAssistantTranscriptContent([])).toBe(false);
+ expect(
+ hasAssistantTranscriptContent([
+ {
+ id: 'empty-assistant',
+ role: 'assistant',
+ content: '',
+ timestamp,
+ },
+ ]),
+ ).toBe(false);
+ expect(
+ hasAssistantTranscriptContent([
+ {
+ id: 'user-1',
+ role: 'user',
+ content: 'hello',
+ timestamp,
+ },
+ ]),
+ ).toBe(true);
+ });
+
+ it('builds stable markdown filenames', () => {
+ expect(buildAssistantTranscriptFilename('session-1234/abcd', timestamp)).toBe(
+ 'pulse-assistant-session-1234-abcd.md',
+ );
+ expect(buildAssistantTranscriptFilename('', timestamp)).toBe('pulse-assistant-2026-06-06.md');
+ });
+
+ it('downloads the transcript as a markdown blob', async () => {
+ const originalCreateObjectURL = URL.createObjectURL;
+ const originalRevokeObjectURL = URL.revokeObjectURL;
+ const createObjectURL = vi.fn((blob: Blob) => {
+ void blob;
+ return 'blob:transcript';
+ });
+ const revokeObjectURL = vi.fn();
+ Object.defineProperty(URL, 'createObjectURL', {
+ value: createObjectURL,
+ configurable: true,
+ });
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ value: revokeObjectURL,
+ configurable: true,
+ });
+ const originalCreateElement = document.createElement.bind(document);
+ let createdAnchor: HTMLAnchorElement | null = null;
+
+ const createElementSpy = vi.spyOn(document, 'createElement').mockImplementation((tagName) => {
+ const element = originalCreateElement(tagName);
+ if (tagName.toLowerCase() === 'a') {
+ createdAnchor = element as HTMLAnchorElement;
+ vi.spyOn(createdAnchor, 'click').mockImplementation(() => undefined);
+ }
+ return element;
+ });
+
+ try {
+ downloadAssistantTranscriptFile('transcript body', 'pulse-assistant-session.md');
+
+ expect(createObjectURL).toHaveBeenCalled();
+ const createdBlob = createObjectURL.mock.calls[0]?.[0] as unknown as Blob;
+ expect(await readBlobText(createdBlob)).toBe('transcript body');
+ expect(createdAnchor).not.toBeNull();
+ const anchor = createdAnchor as unknown as HTMLAnchorElement;
+ expect(anchor.href).toBe('blob:transcript');
+ expect(anchor.download).toBe('pulse-assistant-session.md');
+ expect(anchor.click).toHaveBeenCalled();
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:transcript');
+ } finally {
+ createElementSpy.mockRestore();
+ if (originalCreateObjectURL) {
+ Object.defineProperty(URL, 'createObjectURL', {
+ value: originalCreateObjectURL,
+ configurable: true,
+ });
+ }
+ if (originalRevokeObjectURL) {
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ value: originalRevokeObjectURL,
+ configurable: true,
+ });
+ }
+ }
+ });
+});
diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsx
index 8220184391..8f5e7bd342 100644
--- a/frontend-modern/src/components/AI/Chat/index.tsx
+++ b/frontend-modern/src/components/AI/Chat/index.tsx
@@ -12,6 +12,8 @@ import { unwrap } from 'solid-js/store';
import SendIcon from 'lucide-solid/icons/send';
import SquareIcon from 'lucide-solid/icons/square';
import ClockIcon from 'lucide-solid/icons/clock';
+import CopyIcon from 'lucide-solid/icons/copy';
+import DownloadIcon from 'lucide-solid/icons/download';
import PencilIcon from 'lucide-solid/icons/pencil';
import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';
import SettingsIcon from 'lucide-solid/icons/settings';
@@ -41,10 +43,12 @@ import {
AI_CHAT_CLOSE_LABEL,
AI_CHAT_CONTROL_MODE_LABEL,
AI_CHAT_CONTROL_MODE_MENU_LABEL,
+ AI_CHAT_COPY_TRANSCRIPT_LABEL,
AI_CHAT_DISCOVERY_HINT_BODY,
AI_CHAT_DISCOVERY_HINT_DISMISS_LABEL,
AI_CHAT_DISCOVERY_HINT_TITLE,
AI_CHAT_DRAWER_TITLE,
+ AI_CHAT_EXPORT_TRANSCRIPT_LABEL,
AI_CHAT_INPUT_PLACEHOLDER,
AI_CHAT_LAST_TURN_USAGE_LABEL,
AI_CHAT_NEW_SESSION_BUTTON_TITLE,
@@ -63,6 +67,10 @@ import {
AI_CHAT_SESSION_SEARCH_PLACEHOLDER,
AI_CHAT_SESSION_SEARCH_TITLE,
AI_CHAT_SWITCH_TO_APPROVAL_LABEL,
+ AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL,
+ AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL,
+ AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL,
+ AI_CHAT_TRANSCRIPT_FALLBACK_TITLE,
getAIChatProviderReadinessPresentation,
} from '@/utils/aiChatPresentation';
import {
@@ -85,6 +93,7 @@ import {
} from '@/utils/agentResources';
import { normalizeChatMentionKeyPart } from '@/utils/chatIdentifiers';
import { getGlobalWebSocketStore } from '@/stores/websocket-global';
+import { copyToClipboard } from '@/utils/clipboard';
import {
getPreferredResourceDisplayName,
getPreferredResourceHostname,
@@ -95,6 +104,12 @@ import { ChatMessages } from './ChatMessages';
import { ModelSelector } from './ModelSelector';
import { MentionAutocomplete, type MentionResource } from './MentionAutocomplete';
import { getAssistantActiveTurnStatus } from './activeTurnStatus';
+import {
+ buildAssistantTranscriptFilename,
+ downloadAssistantTranscriptFile,
+ formatAssistantTranscript,
+ hasAssistantTranscriptContent,
+} from './transcriptExport';
import type {
ChatMessage,
ModelRouteRecoveryOption,
@@ -152,6 +167,11 @@ interface AssistantUsageSummary {
title: string;
}
+interface TranscriptCopyFallback {
+ generatedAt: Date;
+ transcript: string;
+}
+
interface AIChatProps {
onClose: () => void;
}
@@ -559,6 +579,8 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [controlLevel, setControlLevel] = createSignal<AIControlLevel>('read_only');
const [showControlMenu, setShowControlMenu] = createSignal(false);
const [controlSaving, setControlSaving] = createSignal(false);
+ const [transcriptCopyFallback, setTranscriptCopyFallback] =
+ createSignal<TranscriptCopyFallback | null>(null);
const [discoveryEnabled, setDiscoveryEnabled] = createSignal<boolean | null>(null); // null = loading
const [discoveryHintDismissed, setDiscoveryHintDismissed] = createSignal(false);
const [autonomousBannerDismissed, setAutonomousBannerDismissed] = createSignal(false);
@@ -580,6 +602,7 @@ export const AIChat: Component<AIChatProps> = (props) => {
const [mentionResources, setMentionResources] = createSignal<MentionResource[]>([]);
const [accumulatedMentions, setAccumulatedMentions] = createSignal<MentionResource[]>([]);
let textareaRef: HTMLTextAreaElement | undefined;
+ let transcriptFallbackTextareaRef: HTMLTextAreaElement | undefined;
let interruptArmTimeout: ReturnType<typeof setTimeout> | undefined;
let composerSubmitDispatchLocked = false;
@@ -1240,6 +1263,76 @@ export const AIChat: Component<AIChatProps> = (props) => {
return match?.provider?.trim() || getProviderFromModelId(normalized);
};
+ const hasCurrentTranscript = createMemo(() => hasAssistantTranscriptContent(chat.messages()));
+
+ const buildCurrentTranscript = (generatedAt = new Date()) => {
+ const sessionId = chat.sessionId().trim();
+ const knownSession = sessionId ? findKnownSession(sessionId) : undefined;
+ return formatAssistantTranscript({
+ messages: chat.messages(),
+ session: {
+ id: sessionId || undefined,
+ title: knownSession?.title,
+ },
+ generatedAt,
+ getModelRouteLabel: formatChatMessageModelRoute,
+ });
+ };
+
+ const downloadTranscript = (transcript: string, generatedAt: Date) => {
+ downloadAssistantTranscriptFile(
+ transcript,
+ buildAssistantTranscriptFilename(chat.sessionId(), generatedAt),
+ );
+ };
+
+ const copyAssistantTranscript = async () => {
+ const generatedAt = new Date();
+ const transcript = buildCurrentTranscript(generatedAt);
+ if (!transcript.trim()) {
+ notificationStore.info('No Assistant transcript to copy', 2000);
+ return;
+ }
+
+ const copied = await copyToClipboard(transcript);
+ if (copied) {
+ setTranscriptCopyFallback(null);
+ notificationStore.success('Assistant transcript copied', 2000);
+ return;
+ }
+ setTranscriptCopyFallback({ generatedAt, transcript });
+ notificationStore.warning('Clipboard blocked; transcript opened for manual copy', 4000);
+ };
+
+ const exportAssistantTranscript = () => {
+ const generatedAt = new Date();
+ const transcript = buildCurrentTranscript(generatedAt);
+ if (!transcript.trim()) {
+ notificationStore.info('No Assistant transcript to export', 2000);
+ return;
+ }
+
+ try {
+ downloadTranscript(transcript, generatedAt);
+ notificationStore.success('Assistant transcript exported', 2000);
+ } catch (error) {
+ logger.error('[AIChat] Failed to export Assistant transcript:', error);
+ notificationStore.error('Failed to export Assistant transcript');
+ }
+ };
+
+ const downloadFallbackTranscript = () => {
+ const fallback = transcriptCopyFallback();
+ if (!fallback) return;
+ try {
+ downloadTranscript(fallback.transcript, fallback.generatedAt);
+ notificationStore.success('Assistant transcript exported', 2000);
+ } catch (error) {
+ logger.error('[AIChat] Failed to export Assistant transcript:', error);
+ notificationStore.error('Failed to export Assistant transcript');
+ }
+ };
+
const failedModelRouteHistory = createMemo(() => {
const modelIds = new Set<string>();
const providers = new Set<string>();
@@ -1585,6 +1678,14 @@ export const AIChat: Component<AIChatProps> = (props) => {
return null;
});
+ createEffect(() => {
+ if (!transcriptCopyFallback()) return;
+ queueMicrotask(() => {
+ transcriptFallbackTextareaRef?.focus();
+ transcriptFallbackTextareaRef?.select();
+ });
+ });
+
createEffect(() => {
input();
queueMicrotask(resizeTextarea);
@@ -2469,6 +2570,30 @@ export const AIChat: Component<AIChatProps> = (props) => {
<span class="font-medium">{AI_CHAT_NEW_SESSION_SHORT_LABEL}</span>
</button>
+ <button
+ type="button"
+ onClick={() => {
+ void copyAssistantTranscript();
+ }}
+ disabled={!hasCurrentTranscript()}
+ class="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border bg-surface text-muted transition-colors hover:border-border hover:bg-surface-hover hover:text-base-content disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-surface disabled:hover:text-muted"
+ title={AI_CHAT_COPY_TRANSCRIPT_LABEL}
+ aria-label={AI_CHAT_COPY_TRANSCRIPT_LABEL}
+ >
+ <CopyIcon class="h-4 w-4" aria-hidden="true" />
+ </button>
+
+ <button
+ type="button"
+ onClick={exportAssistantTranscript}
+ disabled={!hasCurrentTranscript()}
+ class="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-border bg-surface text-muted transition-colors hover:border-border hover:bg-surface-hover hover:text-base-content disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-surface disabled:hover:text-muted"
+ title={AI_CHAT_EXPORT_TRANSCRIPT_LABEL}
+ aria-label={AI_CHAT_EXPORT_TRANSCRIPT_LABEL}
+ >
+ <DownloadIcon class="h-4 w-4" aria-hidden="true" />
+ </button>
+
{/* Session picker */}
<div class="relative" data-dropdown>
<button
@@ -2682,6 +2807,46 @@ export const AIChat: Component<AIChatProps> = (props) => {
</button>
</div>
+ <Show when={transcriptCopyFallback()}>
+ {(fallback) => (
+ <section
+ class="border-b border-amber-200 bg-amber-50 px-4 py-3 text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
+ aria-label={AI_CHAT_TRANSCRIPT_FALLBACK_TITLE}
+ >
+ <div class="mb-2 flex items-center justify-between gap-2">
+ <div class="text-xs font-semibold">{AI_CHAT_TRANSCRIPT_FALLBACK_TITLE}</div>
+ <div class="flex items-center gap-1.5">
+ <button
+ type="button"
+ onClick={downloadFallbackTranscript}
+ class="flex h-7 w-7 items-center justify-center rounded-md border border-amber-200 bg-surface text-amber-700 transition-colors hover:bg-amber-100 hover:text-amber-900 dark:border-amber-800 dark:bg-amber-950/60 dark:text-amber-200 dark:hover:bg-amber-900"
+ title={AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL}
+ aria-label={AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL}
+ >
+ <DownloadIcon class="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setTranscriptCopyFallback(null)}
+ class="flex h-7 w-7 items-center justify-center rounded-md text-amber-700 transition-colors hover:bg-amber-100 hover:text-amber-900 dark:text-amber-200 dark:hover:bg-amber-900"
+ title={AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL}
+ aria-label={AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL}
+ >
+ <XIcon class="h-3.5 w-3.5" aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ <textarea
+ ref={transcriptFallbackTextareaRef}
+ class="h-36 w-full resize-y rounded-md border border-amber-200 bg-surface px-2 py-2 font-mono text-[11px] leading-relaxed text-base-content outline-none focus:border-amber-400 dark:border-amber-800 dark:bg-surface"
+ readonly
+ value={fallback().transcript}
+ aria-label={AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL}
+ />
+ </section>
+ )}
+ </Show>
+
<Show
when={
controlLevel() === 'autonomous' &&
diff --git a/frontend-modern/src/components/AI/Chat/transcriptExport.ts b/frontend-modern/src/components/AI/Chat/transcriptExport.ts
new file mode 100644
index 0000000000..94e52ef95e
--- /dev/null
+++ b/frontend-modern/src/components/AI/Chat/transcriptExport.ts
@@ -0,0 +1,380 @@
+import type {
+ ChatMessage,
+ PendingApproval,
+ PendingQuestion,
+ PendingTool,
+ StreamDisplayEvent,
+ ToolExecution,
+ WorkflowStatus,
+} from './types';
+import { stripAssistantOutputArtifacts } from './assistantOutputHygiene';
+import { formatAssistantWorkflowStatus } from './activeTurnStatus';
+import { groupStreamEventsForDisplay } from './streamEventGrouping';
+import {
+ getToolLabel,
+ isPlaceholderToolInputSummary,
+ parseToolInputSummary,
+ pendingToolActionLabel,
+ toolValueText,
+} from './toolPresentation';
+import { formatAIModelRouteLabel } from '@/utils/aiProviderPresentation';
+
+export interface AssistantTranscriptSession {
+ id?: string;
+ title?: string;
+}
+
+export interface AssistantTranscriptOptions {
+ generatedAt?: Date;
+ includeAssistantMetadata?: boolean;
+ includeThinking?: boolean;
+ includeToolOutput?: boolean;
+ messages: ChatMessage[];
+ session?: AssistantTranscriptSession;
+ getModelRouteLabel?: (modelId: string) => string;
+}
+
+const transcriptDateFormatter = new Intl.DateTimeFormat(undefined, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+});
+
+const normalizeText = (value: string | undefined): string =>
+ (value || '').replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
+
+const compactText = (parts: Array<string | undefined>): string =>
+ parts
+ .map((part) => part?.trim() || '')
+ .filter(Boolean)
+ .join(' - ');
+
+const appendBlock = (lines: string[], block: string) => {
+ const text = normalizeText(block);
+ if (!text) return false;
+ lines.push(text);
+ lines.push('');
+ return true;
+};
+
+const formatTimestamp = (date: Date): string => {
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return '';
+ return transcriptDateFormatter.format(date);
+};
+
+const formatGeneratedAt = (date: Date): string => {
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return '';
+ return date.toISOString();
+};
+
+const formatModelRoute = (
+ modelId: string | undefined,
+ getModelRouteLabel?: (modelId: string) => string,
+): string => {
+ const model = modelId?.trim();
+ if (!model) return '';
+ return getModelRouteLabel?.(model) || formatAIModelRouteLabel(model);
+};
+
+const visibleAssistantContent = (message: ChatMessage): string =>
+ stripAssistantOutputArtifacts(message.content || '').text.trim();
+
+const visibleContentEvent = (event: StreamDisplayEvent): string =>
+ stripAssistantOutputArtifacts(event.content || '').text.trim();
+
+const formatToolInputSummary = (name: string, input: unknown, rawInput?: string): string => {
+ const summary = parseToolInputSummary(toolValueText(input), name, rawInput).trim();
+ if (!summary || isPlaceholderToolInputSummary(summary)) return '';
+ return summary;
+};
+
+const formatToolOutput = (output: unknown): string => {
+ const text = toolValueText(output).replace(/\r\n/g, '\n').replace(/\r/g, '\n').trim();
+ if (!text) return '';
+ const lines = text.split('\n').slice(0, 6);
+ const preview = lines.map((line) => line.trimEnd().slice(0, 160)).join('\n').trim();
+ if (!preview) return '';
+ return text.split('\n').length > lines.length ? `${preview}\n...` : preview;
+};
+
+const formatCompletedTool = (tool: ToolExecution, includeOutput: boolean): string => {
+ const label = getToolLabel(tool.name);
+ const summary = formatToolInputSummary(tool.name, tool.input, tool.rawInput);
+ const status = tool.success ? 'completed' : 'failed';
+ const line = compactText([`[tool:${label}]${summary ? ` ${summary}` : ''}`, status]);
+ const output = includeOutput ? formatToolOutput(tool.output) : '';
+ return output ? `${line}\n${output}` : line;
+};
+
+const formatPendingTool = (tool: PendingTool): string => {
+ const label = getToolLabel(tool.name);
+ const parsedSummary = formatToolInputSummary(tool.name, tool.input, tool.rawInput);
+ const summary = parsedSummary || pendingToolActionLabel(tool.name);
+ const status = tool.status || 'pending';
+ return compactText([
+ `[tool:${label}] ${summary}`,
+ status,
+ tool.progress?.trim() ? `progress: ${tool.progress.trim()}` : undefined,
+ ]);
+};
+
+const formatWorkflowStatus = (status?: WorkflowStatus): string => {
+ const message = formatAssistantWorkflowStatus(status).trim();
+ return message ? `[status] ${message}` : '';
+};
+
+const formatModelSwitch = (
+ event: StreamDisplayEvent,
+ getModelRouteLabel?: (modelId: string) => string,
+): string => {
+ const model = formatModelRoute(event.model, getModelRouteLabel);
+ if (!model) return '';
+ const failed = formatModelRoute(event.failedModel, getModelRouteLabel);
+ return failed && failed !== model ? `[model] ${model} after ${failed}` : `[model] ${model}`;
+};
+
+const formatApproval = (approval: PendingApproval): string => {
+ const label = getToolLabel(approval.toolName || 'approval');
+ const subject = normalizeText(approval.description || approval.command) || 'action';
+ const status = approval.isExecuting ? 'executing' : 'approval required';
+ return compactText([
+ `[approval:${label}] ${subject}`,
+ status,
+ approval.risk ? `${approval.risk} risk` : undefined,
+ ]);
+};
+
+const formatQuestion = (question: PendingQuestion): string => {
+ const prompts = question.questions
+ .map((item) => normalizeText(item.question || item.header))
+ .filter(Boolean);
+ if (prompts.length === 0) return '';
+ return `[question] ${prompts.join(' / ')}`;
+};
+
+const hasRenderableEvent = (event: StreamDisplayEvent, includeThinking = false): boolean => {
+ switch (event.type) {
+ case 'thinking':
+ return includeThinking && Boolean(event.thinking?.trim());
+ case 'workflow_status':
+ return Boolean(formatWorkflowStatus(event.workflowStatus));
+ case 'tool':
+ return Boolean(event.tool);
+ case 'pending_tool':
+ return Boolean(event.pendingTool);
+ case 'content':
+ return Boolean(visibleContentEvent(event));
+ case 'model_switch':
+ return Boolean(event.model?.trim());
+ case 'approval':
+ return Boolean(event.approval);
+ case 'question':
+ return Boolean(event.question);
+ default:
+ return false;
+ }
+};
+
+const hasTranscriptMessageContent = (message: ChatMessage, includeThinking = false): boolean => {
+ if (message.role === 'user') return Boolean(normalizeText(message.content));
+ if (visibleAssistantContent(message)) return true;
+ if (message.error?.trim()) return true;
+ if (message.toolCalls?.length) return true;
+ if (message.pendingTools?.length) return true;
+ if (message.pendingApprovals?.length) return true;
+ if (message.pendingQuestions?.length) return true;
+ return (message.streamEvents || []).some((event) => hasRenderableEvent(event, includeThinking));
+};
+
+const appendMessageMetadata = (
+ lines: string[],
+ message: ChatMessage,
+ options: AssistantTranscriptOptions,
+) => {
+ if (options.includeAssistantMetadata === false) return;
+ const modelRoute =
+ message.role === 'assistant'
+ ? formatModelRoute(message.model, options.getModelRouteLabel)
+ : '';
+
+ const metadata = [
+ message.timestamp ? `Time: ${formatTimestamp(message.timestamp)}` : undefined,
+ modelRoute ? `Model: ${modelRoute}` : undefined,
+ message.delivery === 'queued' ? 'Delivery: queued' : undefined,
+ message.isStreaming ? 'State: streaming' : undefined,
+ ].filter((item): item is string => Boolean(item));
+
+ if (metadata.length > 0) {
+ lines.push(metadata.join('\n'));
+ lines.push('');
+ }
+};
+
+const appendAssistantStreamEvents = (
+ lines: string[],
+ message: ChatMessage,
+ options: AssistantTranscriptOptions,
+) => {
+ let contentAppended = false;
+ let toolAppended = false;
+ let pendingToolAppended = false;
+ let approvalAppended = false;
+ let questionAppended = false;
+
+ for (const event of groupStreamEventsForDisplay(message.streamEvents || [])) {
+ switch (event.type) {
+ case 'thinking':
+ if (options.includeThinking) {
+ appendBlock(lines, `[thinking]\n${event.thinking || ''}`);
+ }
+ break;
+ case 'workflow_status':
+ appendBlock(lines, formatWorkflowStatus(event.workflowStatus));
+ break;
+ case 'content':
+ if (appendBlock(lines, visibleContentEvent(event))) {
+ contentAppended = true;
+ }
+ break;
+ case 'tool':
+ if (event.tool) {
+ appendBlock(lines, formatCompletedTool(event.tool, options.includeToolOutput === true));
+ toolAppended = true;
+ }
+ break;
+ case 'pending_tool':
+ if (event.pendingTool) {
+ appendBlock(lines, formatPendingTool(event.pendingTool));
+ pendingToolAppended = true;
+ }
+ break;
+ case 'model_switch':
+ appendBlock(lines, formatModelSwitch(event, options.getModelRouteLabel));
+ break;
+ case 'approval':
+ if (event.approval) {
+ appendBlock(lines, formatApproval(event.approval));
+ approvalAppended = true;
+ }
+ break;
+ case 'question':
+ if (event.question) {
+ appendBlock(lines, formatQuestion(event.question));
+ questionAppended = true;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ if (!contentAppended) {
+ appendBlock(lines, visibleAssistantContent(message));
+ }
+
+ if (!toolAppended) {
+ for (const tool of message.toolCalls || []) {
+ appendBlock(lines, formatCompletedTool(tool, options.includeToolOutput === true));
+ }
+ }
+
+ if (!pendingToolAppended) {
+ for (const tool of message.pendingTools || []) {
+ appendBlock(lines, formatPendingTool(tool));
+ }
+ }
+
+ if (!approvalAppended) {
+ for (const approval of message.pendingApprovals || []) {
+ appendBlock(lines, formatApproval(approval));
+ }
+ }
+
+ if (!questionAppended) {
+ for (const question of message.pendingQuestions || []) {
+ appendBlock(lines, formatQuestion(question));
+ }
+ }
+
+ if (message.error?.trim()) {
+ appendBlock(lines, `[error] ${message.error.trim()}`);
+ }
+
+ if (message.interruption === 'stopped') {
+ appendBlock(lines, '[interrupted] Stopped by user');
+ } else if (message.interruption === 'replaced') {
+ appendBlock(lines, '[interrupted] Replaced by a later user message');
+ }
+};
+
+export const hasAssistantTranscriptContent = (messages: ChatMessage[]): boolean =>
+ messages.some((message) => hasTranscriptMessageContent(message));
+
+export const formatAssistantTranscript = (options: AssistantTranscriptOptions): string => {
+ const includeThinking = options.includeThinking === true;
+ if (!options.messages.some((message) => hasTranscriptMessageContent(message, includeThinking))) {
+ return '';
+ }
+
+ const lines: string[] = ['# Pulse Assistant Transcript', ''];
+ const sessionTitle = options.session?.title?.trim();
+ const sessionId = options.session?.id?.trim();
+ const generatedAt = formatGeneratedAt(options.generatedAt || new Date());
+
+ if (sessionTitle) lines.push(`Session: ${sessionTitle}`);
+ if (sessionId) lines.push(`Session ID: ${sessionId}`);
+ if (generatedAt) lines.push(`Generated: ${generatedAt}`);
+ lines.push('');
+
+ for (const message of options.messages) {
+ if (!hasTranscriptMessageContent(message, includeThinking)) continue;
+
+ const role = message.role === 'user' ? 'User' : 'Pulse Assistant';
+ lines.push(`## ${role}`);
+ lines.push('');
+ appendMessageMetadata(lines, message, options);
+
+ if (message.role === 'user') {
+ appendBlock(lines, message.content);
+ } else {
+ appendAssistantStreamEvents(lines, message, options);
+ }
+ }
+
+ return `${lines.join('\n').replace(/\n{3,}/g, '\n\n').trim()}\n`;
+};
+
+const filenameDatePart = (date: Date): string => {
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) return 'session';
+ return date.toISOString().slice(0, 10);
+};
+
+const sanitizeFilenamePart = (value: string): string =>
+ value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 48);
+
+export const buildAssistantTranscriptFilename = (
+ sessionId?: string,
+ generatedAt = new Date(),
+): string => {
+ const sessionPart = sanitizeFilenamePart(sessionId || '');
+ return sessionPart
+ ? `pulse-assistant-${sessionPart}.md`
+ : `pulse-assistant-${filenameDatePart(generatedAt)}.md`;
+};
+
+export const downloadAssistantTranscriptFile = (transcript: string, filename: string): void => {
+ const blob = new Blob([transcript], { type: 'text/markdown;charset=utf-8' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = filename;
+ anchor.rel = 'noopener';
+ document.body.appendChild(anchor);
+ anchor.click();
+ document.body.removeChild(anchor);
+ URL.revokeObjectURL(url);
+};
diff --git a/frontend-modern/src/utils/aiChatPresentation.ts b/frontend-modern/src/utils/aiChatPresentation.ts
index d368b0485e..05a3bebf71 100644
--- a/frontend-modern/src/utils/aiChatPresentation.ts
+++ b/frontend-modern/src/utils/aiChatPresentation.ts
@@ -9,6 +9,12 @@ export const AI_CHAT_NEW_SESSION_SHORT_LABEL = 'New';
export const AI_CHAT_NEW_SESSION_BUTTON_TITLE = 'Start new Assistant session';
export const AI_CHAT_NEW_SESSION_MENU_LABEL = 'New session';
export const AI_CHAT_NEW_SESSION_MENU_ARIA_LABEL = 'Start new Assistant session';
+export const AI_CHAT_COPY_TRANSCRIPT_LABEL = 'Copy Assistant transcript';
+export const AI_CHAT_EXPORT_TRANSCRIPT_LABEL = 'Export Assistant transcript';
+export const AI_CHAT_TRANSCRIPT_FALLBACK_CLOSE_LABEL = 'Close Assistant transcript copy panel';
+export const AI_CHAT_TRANSCRIPT_FALLBACK_DOWNLOAD_LABEL = 'Download Assistant transcript';
+export const AI_CHAT_TRANSCRIPT_FALLBACK_TEXTAREA_LABEL = 'Assistant transcript';
+export const AI_CHAT_TRANSCRIPT_FALLBACK_TITLE = 'Transcript ready';
export const AI_CHAT_AUTONOMOUS_WARNING_DISMISS_LABEL = 'Dismiss autonomous control warning';
export const AI_CHAT_DISCOVERY_HINT_DISMISS_LABEL = 'Dismiss discovery context warning';
export const AI_CHAT_CONTROL_MODE_LABEL = 'Assistant control mode';