Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Support exporting conversations

Blue Mouse0bff6cb6b07f
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 2ea92653c..188e12f6f 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -1,6 +1,4 @@
-import _filter from 'lodash/filter'
-import _isEmpty from 'lodash/isEmpty'
-import _map from 'lodash/map'
+import { Menu, MenuButton, MenuItem, MenuItems } from '@headlessui/react'
import {
ArrowUpIcon,
CaretDownIcon,
@@ -34,7 +32,12 @@ import {
TagIcon,
PushPinIcon,
MagnifyingGlassIcon,
+ DownloadSimpleIcon,
+ ExportIcon,
} from '@phosphor-icons/react'
+import _filter from 'lodash/filter'
+import _isEmpty from 'lodash/isEmpty'
+import _map from 'lodash/map'
import { marked } from 'marked'
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -56,6 +59,13 @@ import Tooltip from '~/ui/Tooltip'
import { cn } from '~/utils/generic'
import AIChart from './AIChart'
+import { parseSegments } from './contentSegments'
+import {
+ chatToMarkdown,
+ downloadMarkdown,
+ ExportMessage,
+ getChatExportFilename,
+} from './exportHelpers'
import { formatToolCallSummary, ToolCallSummary } from './toolFormatters'
interface MessagePart {
@@ -119,98 +129,6 @@ marked.setOptions({
gfm: true,
})
-type ContentSegment =
- | { kind: 'text'; text: string }
- | { kind: 'chart'; chart: any; pending?: boolean }
-
-const CHART_START_PATTERN = '{"type":"chart"'
-
-const parseSegments = (content: string): ContentSegment[] => {
- const segments: ContentSegment[] = []
- let cursor = 0
-
- while (cursor < content.length) {
- const startIndex = content.indexOf(CHART_START_PATTERN, cursor)
- if (startIndex === -1) {
- const tail = content.slice(cursor)
- if (tail) segments.push({ kind: 'text', text: tail })
- break
- }
-
- if (startIndex > cursor) {
- segments.push({ kind: 'text', text: content.slice(cursor, startIndex) })
- }
-
- let braceCount = 0
- let endIndex = -1
- let inString = false
- let escape = false
-
- for (let i = startIndex; i < content.length; i++) {
- const ch = content[i]
- if (escape) {
- escape = false
- continue
- }
- if (ch === '\\') {
- escape = true
- continue
- }
- if (ch === '"') {
- inString = !inString
- continue
- }
- if (inString) continue
- if (ch === '{') braceCount++
- else if (ch === '}') {
- braceCount--
- if (braceCount === 0) {
- endIndex = i
- break
- }
- }
- }
-
- if (endIndex === -1) {
- // Chart JSON still streaming – keep raw text out of view to avoid showing JSON
- segments.push({ kind: 'chart', chart: null, pending: true })
- cursor = content.length
- break
- }
-
- const jsonString = content.substring(startIndex, endIndex + 1)
- try {
- const chartData = JSON.parse(jsonString)
- if (chartData?.type === 'chart') {
- segments.push({ kind: 'chart', chart: chartData })
- } else {
- segments.push({ kind: 'text', text: jsonString })
- }
- } catch {
- segments.push({ kind: 'chart', chart: null, pending: true })
- }
- cursor = endIndex + 1
- }
-
- // Trim leading/trailing whitespace-only text segments
- while (
- segments.length &&
- segments[0].kind === 'text' &&
- !segments[0].text.trim()
- ) {
- segments.shift()
- }
- while (
- segments.length &&
- segments[segments.length - 1].kind === 'text' &&
- !(segments[segments.length - 1] as { text: string }).text.trim()
- ) {
- segments.pop()
- }
-
- return segments
-}
-
const renderMarkdown = (content: string): string => {
const html = marked.parse(content) as string
return sanitizeHtml(html, {
@@ -2709,6 +2627,58 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
toast.success(t('project.askAi.linkCopied'))
}
+ const exportableMessages = useMemo<ExportMessage[]>(() => {
+ const list: ExportMessage[] = messages.map((m) => ({
+ id: m.id,
+ role: m.role,
+ content: m.content,
+ parts: m.parts,
+ toolCalls: m.toolCalls,
+ }))
+ if (streamingMessage) {
+ list.push({
+ id: streamingMessage.id,
+ role: streamingMessage.role,
+ content: streamingMessage.content,
+ parts: streamingMessage.parts,
+ toolCalls: streamingMessage.toolCalls,
+ })
+ }
+ return list
+ }, [messages, streamingMessage])
+
+ const isExportDisabled = useMemo(() => {
+ return exportableMessages.every(
+ (m) =>
+ !(m.content && m.content.trim()) &&
+ !(m.parts && m.parts.length > 0) &&
+ !(m.toolCalls && m.toolCalls.length > 0),
+ )
+ }, [exportableMessages])
+
+ const handleCopyConversation = useCallback(() => {
+ if (isExportDisabled) return
+ const md = chatToMarkdown(exportableMessages, chatTitle, projectId, t)
+ navigator.clipboard
+ .writeText(md)
+ .then(() => toast.success(t('project.askAi.conversationCopied')))
+ .catch(() => toast.error(t('project.askAi.error')))
+ }, [chatTitle, exportableMessages, isExportDisabled, projectId, t])
+
+ const handleDownloadMarkdown = useCallback(() => {
+ if (isExportDisabled) return
+ const md = chatToMarkdown(exportableMessages, chatTitle, projectId, t)
+ const filename = getChatExportFilename(chatTitle, currentChatId)
+ downloadMarkdown(md, filename)
+ }, [
+ chatTitle,
+ currentChatId,
+ exportableMessages,
+ isExportDisabled,
+ projectId,
+ t,
+ ])
+
useEffect(() => {
if (inputRef.current) {
inputRef.current.style.height = 'auto'
@@ -2777,14 +2747,54 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
: t('project.askAi.newChat'))}
</h2>
</div>
- <button
- type='button'
- onClick={handleCopyLink}
- className='flex shrink-0 items-center gap-2 rounded-md border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-900 dark:text-gray-200 dark:hover:bg-slate-800'
- >
- <LinkIcon className='h-4 w-4' />
- <span>{t('project.askAi.copyLink')}</span>
- </button>
+ <div className='flex shrink-0 items-center gap-2'>
+ <button
+ type='button'
+ onClick={handleCopyLink}
+ className='flex shrink-0 items-center gap-2 rounded-md border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-900 dark:text-gray-200 dark:hover:bg-slate-800'
+ >
+ <LinkIcon className='h-4 w-4' />
+ <span>{t('project.askAi.copyLink')}</span>
+ </button>
+ <Menu as='div' className='relative'>
+ <MenuButton
+ disabled={isExportDisabled}
+ className='flex shrink-0 items-center gap-2 rounded-md border border-gray-200 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-700 dark:bg-slate-900 dark:text-gray-200 dark:hover:bg-slate-800'
+ aria-label={t('project.askAi.export')}
+ >
+ <ExportIcon className='h-4 w-4' />
+ <span>{t('project.askAi.export')}</span>
+ <CaretDownIcon className='h-3.5 w-3.5' />
+ </MenuButton>
+ <MenuItems
+ anchor={{ to: 'bottom end', offset: 8 }}
+ modal={false}
+ transition
+ className='z-50 w-56 min-w-max origin-top-right rounded-md bg-white p-1 ring-1 ring-gray-200 transition duration-100 ease-out focus:outline-hidden data-closed:scale-95 data-closed:opacity-0 dark:bg-slate-900 dark:ring-slate-800'
+ >
+ <MenuItem>
+ <button
+ type='button'
+ onClick={handleCopyConversation}
+ className='flex w-full items-center gap-2 rounded-md p-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-100 dark:text-gray-50 dark:hover:bg-slate-800'
+ >
+ <CopyIcon className='h-4 w-4' />
+ {t('project.askAi.copyConversation')}
+ </button>
+ </MenuItem>
+ <MenuItem>
+ <button
+ type='button'
+ onClick={handleDownloadMarkdown}
+ className='flex w-full items-center gap-2 rounded-md p-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-100 dark:text-gray-50 dark:hover:bg-slate-800'
+ >
+ <DownloadSimpleIcon className='h-4 w-4' />
+ {t('project.askAi.downloadMarkdown')}
+ </button>
+ </MenuItem>
+ </MenuItems>
+ </Menu>
+ </div>
</div>
<hr className='mt-3 border-gray-200 dark:border-slate-800' />
</>
diff --git a/web/app/pages/Project/tabs/AskAI/contentSegments.ts b/web/app/pages/Project/tabs/AskAI/contentSegments.ts
new file mode 100644
index 000000000..c5c32badf
--- /dev/null
+++ b/web/app/pages/Project/tabs/AskAI/contentSegments.ts
@@ -0,0 +1,91 @@
+type ContentSegment =
+ | { kind: 'text'; text: string }
+ | { kind: 'chart'; chart: any; pending?: boolean }
+
+const CHART_START_PATTERN = '{"type":"chart"'
+
+export const parseSegments = (content: string): ContentSegment[] => {
+ const segments: ContentSegment[] = []
+ let cursor = 0
+
+ while (cursor < content.length) {
+ const startIndex = content.indexOf(CHART_START_PATTERN, cursor)
+ if (startIndex === -1) {
+ const tail = content.slice(cursor)
+ if (tail) segments.push({ kind: 'text', text: tail })
+ break
+ }
+
+ if (startIndex > cursor) {
+ segments.push({ kind: 'text', text: content.slice(cursor, startIndex) })
+ }
+
+ let braceCount = 0
+ let endIndex = -1
+ let inString = false
+ let escape = false
+
+ for (let i = startIndex; i < content.length; i++) {
+ const ch = content[i]
+ if (escape) {
+ escape = false
+ continue
+ }
+ if (ch === '\\') {
+ escape = true
+ continue
+ }
+ if (ch === '"') {
+ inString = !inString
+ continue
+ }
+ if (inString) continue
+ if (ch === '{') braceCount++
+ else if (ch === '}') {
+ braceCount--
+ if (braceCount === 0) {
+ endIndex = i
+ break
+ }
+ }
+ }
+
+ if (endIndex === -1) {
+ // Chart JSON still streaming – keep raw text out of view to avoid showing JSON
+ segments.push({ kind: 'chart', chart: null, pending: true })
+ cursor = content.length
+ break
+ }
+
+ const jsonString = content.substring(startIndex, endIndex + 1)
+ try {
+ const chartData = JSON.parse(jsonString)
+ if (chartData?.type === 'chart') {
+ segments.push({ kind: 'chart', chart: chartData })
+ } else {
+ segments.push({ kind: 'text', text: jsonString })
+ }
+ } catch {
+ segments.push({ kind: 'chart', chart: null, pending: true })
+ }
+ cursor = endIndex + 1
+ }
+
+ // Trim leading/trailing whitespace-only text segments
+ while (
+ segments.length &&
+ segments[0].kind === 'text' &&
+ !segments[0].text.trim()
+ ) {
+ segments.shift()
+ }
+ while (
+ segments.length &&
+ segments[segments.length - 1].kind === 'text' &&
+ !(segments[segments.length - 1] as { text: string }).text.trim()
+ ) {
+ segments.pop()
+ }
+
+ return segments
+}
diff --git a/web/app/pages/Project/tabs/AskAI/exportHelpers.ts b/web/app/pages/Project/tabs/AskAI/exportHelpers.ts
new file mode 100644
index 000000000..b42b090a8
--- /dev/null
+++ b/web/app/pages/Project/tabs/AskAI/exportHelpers.ts
@@ -0,0 +1,174 @@
+import type { TFunction } from 'i18next'
+
+import { parseSegments } from './contentSegments'
+
+export interface ExportMessagePart {
+ type: 'text' | 'toolCall'
+ text?: string
+ toolName?: string
+ args?: unknown
+}
+
+export interface ExportMessageToolCall {
+ toolName: string
+ args?: unknown
+ timestamp?: string
+}
+
+export interface ExportMessage {
+ id?: string
+ role: 'user' | 'assistant'
+ content: string
+ parts?: ExportMessagePart[]
+ toolCalls?: ExportMessageToolCall[]
+}
+
+const TOOL_LABEL_KEYS: Record<string, string> = {
+ getProjectInfo: 'project.askAi.tools.getProjectInfo',
+ getData: 'project.askAi.tools.getData',
+ getGoalStats: 'project.askAi.tools.getGoalStats',
+ getFunnelData: 'project.askAi.tools.getFunnelData',
+ getFeatureFlagStats: 'project.askAi.tools.getFeatureFlagStats',
+ getExperimentResults: 'project.askAi.tools.getExperimentResults',
+ getSessionsList: 'project.askAi.tools.getSessionsList',
+ getProfilesOverview: 'project.askAi.tools.getProfilesOverview',
+}
+
+const getToolLabel = (toolName: string, t?: TFunction): string => {
+ const key = TOOL_LABEL_KEYS[toolName]
+ if (!key || !t) return toolName
+ return t(key, { defaultValue: toolName })
+}
+
+const getChartLabel = (chart: any): string => {
+ if (chart && typeof chart === 'object') {
+ if (typeof chart.title === 'string' && chart.title.trim()) {
+ return chart.title.trim()
+ }
+ if (typeof chart.chartType === 'string' && chart.chartType.trim()) {
+ return chart.chartType.trim()
+ }
+ }
+ return 'chart'
+}
+
+const renderTextWithCharts = (text: string): string => {
+ const segments = parseSegments(text)
+ if (segments.length === 0) return text.trim()
+
+ const out: string[] = []
+ for (const segment of segments) {
+ if (segment.kind === 'text') {
+ const trimmed = segment.text.trim()
+ if (trimmed) out.push(trimmed)
+ } else if (segment.kind === 'chart') {
+ if (segment.chart) {
+ const label = getChartLabel(segment.chart)
+ const json = JSON.stringify(segment.chart, null, 2)
+ out.push(`_[Chart: ${label}]_\n\n\`\`\`json\n${json}\n\`\`\``)
+ } else {
+ out.push('_[Chart: pending]_')
+ }
+ }
+ }
+ return out.join('\n\n')
+}
+
+const renderAssistantMessage = (
+ message: ExportMessage,
+ t?: TFunction,
+): string => {
+ const blocks: string[] = []
+
+ if (message.parts && message.parts.length > 0) {
+ for (const part of message.parts) {
+ if (part.type === 'text' && part.text) {
+ const rendered = renderTextWithCharts(part.text)
+ if (rendered) blocks.push(rendered)
+ } else if (part.type === 'toolCall' && part.toolName) {
+ blocks.push(`_[Used: ${getToolLabel(part.toolName, t)}]_`)
+ }
+ }
+ } else {
+ if (message.content) {
+ const rendered = renderTextWithCharts(message.content)
+ if (rendered) blocks.push(rendered)
+ }
+ if (message.toolCalls && message.toolCalls.length > 0) {
+ const list = message.toolCalls
+ .map((tc) => `- ${getToolLabel(tc.toolName, t)}`)
+ .join('\n')
+ blocks.push(`**Tools used:**\n${list}`)
+ }
+ }
+
+ return blocks.join('\n\n')
+}
+
+const renderUserMessage = (message: ExportMessage): string => {
+ return (message.content || '').trim()
+}
+
+export const chatToMarkdown = (
+ messages: ExportMessage[],
+ chatTitle: string | null,
+ projectId: string,
+ t?: TFunction,
+): string => {
+ const title = chatTitle?.trim() || 'Untitled chat'
+ const exportedAt = new Date().toISOString()
+
+ const lines: string[] = []
+ lines.push(`# ${title}`)
+ lines.push(`Project: ${projectId} · Exported: ${exportedAt}`)
+
+ for (const message of messages) {
+ const body =
+ message.role === 'assistant'
+ ? renderAssistantMessage(message, t)
+ : renderUserMessage(message)
+
+ if (!body) continue
+
+ lines.push('')
+ lines.push('---')
+ lines.push('')
+ lines.push(message.role === 'user' ? '## You' : '## Assistant')
+ lines.push('')
+ lines.push(body)
+ }
+
+ return `${lines.join('\n')}\n`
+}
+
+const slugifyForFilename = (input: string): string =>
+ input
+ .toLowerCase()
+ .trim()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 80)
+
+export const getChatExportFilename = (
+ chatTitle: string | null,
+ chatId: string | null,
+): string => {
+ if (chatTitle) {
+ const slug = slugifyForFilename(chatTitle)
+ if (slug) return `${slug}.md`
+ }
+ if (chatId) return `swetrix-chat-${chatId}.md`
+ return 'swetrix-chat.md'
+}
+
+export const downloadMarkdown = (markdown: string, filename: string) => {
+ const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ setTimeout(() => URL.revokeObjectURL(url), 0)
+}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 9323e95ba..964d40c34 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2143,6 +2143,10 @@
"savingChanges": "Saving…",
"copyLink": "Copy link to chat",
"linkCopied": "Link copied to clipboard",
+ "export": "Export",
+ "copyConversation": "Copy conversation",
+ "downloadMarkdown": "Download as Markdown",
+ "conversationCopied": "Conversation copied to clipboard",
"copyMessage": "Copy message",
"messageCopied": "Copied to clipboard",
"regenerate": "Regenerate response",