## Summary - Closes [#97](#97) — message action row: copy (raw markdown + code-block copy), thumbs up/down with optimistic updates + down-reason popover, and export menu (PDF / DOCX / CSV / XLSX / TXT) for a single message plus conversation-level export in the chat toolbar. - Closes [#98](#98) — versioned WS `citations` frame parsing, Sources list under assistant bubbles, clickable `[n]` markers, and history hydrate from `Prompt.citations`. - Backend companion for ratings: [chat_backend#67](ai_ml_operations/chat_backend#67). Thumbs UI posts to `prompt_feedback` once that lands; votes rehydrate from `conversation_details.feedback`. - Export libs (`pdfmake`, `docx`, `papaparse`, `xlsx`) are dynamically imported so they stay out of the main path until used. ## Test plan - [ ] Stream a grounded answer → Sources appear after stream; inline `[n]` highlights the matching source; reload keeps Sources. - [ ] Non-grounded turn → no Sources header. - [ ] Copy message + code block; confirm checkmark ~2s; failure path shows toast. - [ ] Thumbs up/down optimistic UI; clear by re-click; down opens reason popover without blocking the vote (needs chat_backend#67). - [ ] Export one message and whole conversation in all five formats; check searchable PDF text and DOCX structure. - [ ] Action row: hover reveal on desktop, always visible on last/touch; hidden while streaming. - [ ] `npm test -- --testPathPattern='wsFrames|clipboard|exportChat|promptFeedback|ConversationDetailCard'`Reviewed-on: #101
This commit was merged in pull request #101.
This commit is contained in:
@@ -27,6 +27,10 @@ Page views: always via `Tracker` / `tracker.js` on prod + beta.
|
||||
| Account Delete Started | `ACCOUNT_DELETE_STARTED` | DeleteAccountSection | — |
|
||||
| Account Delete Success | `ACCOUNT_DELETE_SUCCESS` | DeleteAccountSection | — |
|
||||
| Account Delete Failed | `ACCOUNT_DELETE_FAILED` | DeleteAccountSection | — |
|
||||
| Message Copied | `MESSAGE_COPIED` | MessageActions | `{ role }` |
|
||||
| Message Rated | `MESSAGE_RATED` | MessageActions | `{ rating: 'up' \| 'down' \| 'cleared' }` |
|
||||
| Message Rating Reason | `MESSAGE_RATING_REASON` | MessageActions | `{ reason, hasComment }` |
|
||||
| Message Exported | `MESSAGE_EXPORTED` | MessageActions, AsyncDashboard2 | `{ format, scope }` |
|
||||
|
||||
## Identify
|
||||
|
||||
|
||||
Generated
+555
-30
File diff suppressed because it is too large
Load Diff
@@ -21,16 +21,21 @@
|
||||
"@testing-library/user-event": "^14.5.2",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"@types/pdfmake": "^0.3.3",
|
||||
"axios": "^1.13.2",
|
||||
"babel-loader": "^9.2.1",
|
||||
"bootstrap": "^5.3.3",
|
||||
"brace-expansion": "file:vendor/brace-expansion-compat",
|
||||
"chroma-js": "^3.1.2",
|
||||
"docx": "^9.7.1",
|
||||
"formik": "^2.4.6",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"lodash": "^4.17.21",
|
||||
"markdown-to-jsx": "^7.7.2",
|
||||
"mini.css": "^3.0.1",
|
||||
"papaparse": "^5.5.4",
|
||||
"pdfmake": "^0.3.11",
|
||||
"react-bootstrap": "^2.10.6",
|
||||
"react-code-blocks": "^0.1.6",
|
||||
"react-github-btn": "^1.4.0",
|
||||
@@ -43,6 +48,7 @@
|
||||
"web-vitals": "^4.2.4",
|
||||
"webpack": "^5.97.1",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"xlsx": "^0.18.5",
|
||||
"yup": "^1.5.0"
|
||||
},
|
||||
"scripts": {
|
||||
@@ -80,6 +86,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor/assets": "^3.0.5",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@types/bootstrap": "~5.2.10",
|
||||
"@types/lodash": "~4.17.13",
|
||||
"@types/react": "^18.3.16",
|
||||
|
||||
@@ -24,6 +24,7 @@ import { AnalyticsConsentProvider } from './llm-fe/contexts/AnalyticsConsentCont
|
||||
import AnalyticsConsentBanner from './llm-fe/components/AnalyticsConsentBanner/AnalyticsConsentBanner';
|
||||
import AnalyticsSession from './llm-fe/components/AnalyticsSession/AnalyticsSession';
|
||||
import AppErrorBoundary from './llm-fe/components/AppErrorBoundary/AppErrorBoundary';
|
||||
import ToastHost from './llm-fe/components/ToastHost/ToastHost';
|
||||
|
||||
const ProtectedRoutes = () => {
|
||||
const { authenticated, loading } = useContext(AuthContext);
|
||||
@@ -48,6 +49,7 @@ class App extends Component {
|
||||
<AnalyticsConsentProvider>
|
||||
<Tracker />
|
||||
<AnalyticsSession />
|
||||
<ToastHost />
|
||||
<AnalyticsConsentBanner />
|
||||
<div className='site'>
|
||||
<main>
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { ThemeProvider } from 'styled-components';
|
||||
import ConversationDetailCard, {
|
||||
injectCitationMarkers,
|
||||
} from './ConversationDetailCard';
|
||||
|
||||
const theme = {
|
||||
main: '#336699',
|
||||
focus: '#224466',
|
||||
darkMode: true,
|
||||
colors: {
|
||||
text: '#ffffff',
|
||||
cardBackground: 'rgba(0,0,0,0.3)',
|
||||
cardBorder: 'rgba(255,255,255,0.1)',
|
||||
},
|
||||
};
|
||||
|
||||
const renderCard = (props: React.ComponentProps<typeof ConversationDetailCard>) =>
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ThemeProvider theme={theme as never}>
|
||||
<ConversationDetailCard {...props} />
|
||||
</ThemeProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
describe('ConversationDetailCard citations (#98)', () => {
|
||||
it('injects citation markers outside code fences', () => {
|
||||
const md = 'See [1] and [2, 3]\n\n```\n[9]\n```';
|
||||
const out = injectCitationMarkers(md);
|
||||
expect(out).toContain('<citation indices="1"></citation>');
|
||||
expect(out).toContain('<citation indices="2,3"></citation>');
|
||||
expect(out).toContain('```\n[9]\n```');
|
||||
});
|
||||
|
||||
it('renders Sources list from citations prop', () => {
|
||||
renderCard({
|
||||
message: 'Answer with [1]',
|
||||
user_created: false,
|
||||
citations: [
|
||||
{
|
||||
index: 1,
|
||||
title: 'Example Source',
|
||||
url: 'https://example.com/a',
|
||||
published_at: '2026-07-03',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(screen.getByLabelText('Sources')).toBeInTheDocument();
|
||||
const link = screen.getByRole('link', { name: 'Example Source' });
|
||||
expect(link).toHaveAttribute('href', 'https://example.com/a');
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
|
||||
it('renders nothing for Sources when citations empty', () => {
|
||||
renderCard({
|
||||
message: 'No sources here',
|
||||
user_created: false,
|
||||
citations: [],
|
||||
});
|
||||
expect(screen.queryByLabelText('Sources')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('highlights source when inline citation clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderCard({
|
||||
message: 'See [1]',
|
||||
user_created: false,
|
||||
citations: [
|
||||
{ index: 1, title: 'Src', url: 'https://example.com', published_at: null },
|
||||
],
|
||||
});
|
||||
await user.click(screen.getByRole('button', { name: 'Source 1' }));
|
||||
expect(document.getElementById('citation-source-1')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,13 @@
|
||||
import React from "react";
|
||||
import Markdown from "markdown-to-jsx";
|
||||
import { Link } from "react-router-dom";
|
||||
import styled, { keyframes } from "styled-components";
|
||||
import { isRagFeatureNotAllowed, parseChatErrorPayload } from "../../utils/chatErrors";
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
import Markdown from 'markdown-to-jsx';
|
||||
import { Link } from 'react-router-dom';
|
||||
import styled, { keyframes } from 'styled-components';
|
||||
import { isRagFeatureNotAllowed, parseChatErrorPayload } from '../../utils/chatErrors';
|
||||
import type { Citation } from '../../utils/wsFrames';
|
||||
import type { PromptRating } from '../../utils/promptFeedback';
|
||||
import CustomPreBlock from '../CustomPreBlock/CustomPreBlock';
|
||||
import SourcesList from '../SourcesList/SourcesList';
|
||||
import MessageActions from '../MessageActions/MessageActions';
|
||||
|
||||
const fadeIn = keyframes`
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
@@ -12,10 +17,16 @@ const fadeIn = keyframes`
|
||||
const MessageContainer = styled.div<{ $isUser: boolean }>`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: ${(props) => (props.$isUser ? "flex-end" : "flex-start")};
|
||||
align-items: ${(props) => (props.$isUser ? 'flex-end' : 'flex-start')};
|
||||
margin-bottom: 1.5rem;
|
||||
width: 100%;
|
||||
animation: ${fadeIn} 0.3s ease-out;
|
||||
|
||||
&:hover [data-message-actions],
|
||||
&:focus-within [data-message-actions] {
|
||||
opacity: 1 !important;
|
||||
pointer-events: auto !important;
|
||||
}
|
||||
`;
|
||||
|
||||
const Bubble = styled.div<{ $isUser: boolean }>`
|
||||
@@ -28,33 +39,33 @@ const Bubble = styled.div<{ $isUser: boolean }>`
|
||||
props.$isUser
|
||||
? `linear-gradient(135deg, ${props.theme.main} 0%, ${props.theme.focus} 100%)`
|
||||
: props.theme.darkMode
|
||||
? "rgba(255, 255, 255, 0.1)"
|
||||
: "rgba(0, 0, 0, 0.06)"};
|
||||
? 'rgba(255, 255, 255, 0.1)'
|
||||
: 'rgba(0, 0, 0, 0.06)'};
|
||||
color: ${(props) =>
|
||||
props.$isUser || props.theme.darkMode ? "#fff" : props.theme.colors.text};
|
||||
props.$isUser || props.theme.darkMode ? '#fff' : props.theme.colors.text};
|
||||
backdrop-filter: blur(10px);
|
||||
border: 1px solid ${(props) =>
|
||||
props.$isUser
|
||||
? props.theme.darkMode
|
||||
? "rgba(255, 255, 255, 0.1)"
|
||||
: "rgba(0, 0, 0, 0.1)"
|
||||
? 'rgba(255, 255, 255, 0.1)'
|
||||
: 'rgba(0, 0, 0, 0.1)'
|
||||
: props.theme.darkMode
|
||||
? "rgba(255, 255, 255, 0.1)"
|
||||
: "rgba(0, 0, 0, 0.08)"};
|
||||
? 'rgba(255, 255, 255, 0.1)'
|
||||
: 'rgba(0, 0, 0, 0.08)'};
|
||||
box-shadow: ${(props) =>
|
||||
props.$isUser || props.theme.darkMode
|
||||
? "0 4px 15px rgba(0, 0, 0, 0.2)"
|
||||
: "0 2px 10px rgba(0, 0, 0, 0.08)"};
|
||||
? '0 4px 15px rgba(0, 0, 0, 0.2)'
|
||||
: '0 2px 10px rgba(0, 0, 0, 0.08)'};
|
||||
font-size: 1rem;
|
||||
line-height: 1.6;
|
||||
border-bottom-right-radius: ${(props) => (props.$isUser ? "0.2rem" : "1.2rem")};
|
||||
border-bottom-left-radius: ${(props) => (props.$isUser ? "1.2rem" : "0.2rem")};
|
||||
border-bottom-right-radius: ${(props) => (props.$isUser ? '0.2rem' : '1.2rem')};
|
||||
border-bottom-left-radius: ${(props) => (props.$isUser ? '1.2rem' : '0.2rem')};
|
||||
|
||||
& pre {
|
||||
background: ${(props) =>
|
||||
props.$isUser || props.theme.darkMode
|
||||
? "rgba(0, 0, 0, 0.3)"
|
||||
: "rgba(0, 0, 0, 0.06)"};
|
||||
? 'rgba(0, 0, 0, 0.3)'
|
||||
: 'rgba(0, 0, 0, 0.06)'};
|
||||
padding: 1rem;
|
||||
border-radius: 0.5rem;
|
||||
overflow-x: auto;
|
||||
@@ -68,7 +79,7 @@ const Bubble = styled.div<{ $isUser: boolean }>`
|
||||
|
||||
& a {
|
||||
color: ${(props) =>
|
||||
props.$isUser || props.theme.darkMode ? "#a0c4ff" : props.theme.main};
|
||||
props.$isUser || props.theme.darkMode ? '#a0c4ff' : props.theme.main};
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@@ -129,9 +140,54 @@ const UpgradeLink = styled(Link)`
|
||||
}
|
||||
`;
|
||||
|
||||
const CitationButton = styled.button`
|
||||
display: inline;
|
||||
margin: 0 0.1rem;
|
||||
padding: 0 0.25rem;
|
||||
border: none;
|
||||
border-radius: 0.25rem;
|
||||
background: ${({ theme }) =>
|
||||
theme.darkMode ? 'rgba(160, 196, 255, 0.2)' : 'rgba(51, 102, 153, 0.12)'};
|
||||
color: ${({ theme }) => (theme.darkMode ? '#a0c4ff' : theme.main)};
|
||||
font: inherit;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
vertical-align: baseline;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
outline: 2px solid ${({ theme }) => theme.main};
|
||||
outline-offset: 1px;
|
||||
}
|
||||
`;
|
||||
|
||||
/** Linkify [n] / [1, 2] outside fenced code blocks. */
|
||||
export function injectCitationMarkers(markdown: string): string {
|
||||
const parts = markdown.split(/(```[\s\S]*?```)/g);
|
||||
return parts
|
||||
.map((part) => {
|
||||
if (part.startsWith('```')) return part;
|
||||
return part.replace(
|
||||
/\[(\d+(?:\s*,\s*\d+)*)\]/g,
|
||||
(_match, nums: string) =>
|
||||
`<citation indices="${nums.replace(/\s+/g, '')}"></citation>`,
|
||||
);
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
type ConversationDetailCardProps = {
|
||||
message: string;
|
||||
user_created: boolean;
|
||||
promptId?: number;
|
||||
citations?: Citation[];
|
||||
isStreaming?: boolean;
|
||||
isLast?: boolean;
|
||||
conversationTitle?: string;
|
||||
createdTimestamp?: Date | string | null;
|
||||
initialRating?: PromptRating | null;
|
||||
onRatingChange?: (rating: PromptRating | null) => void;
|
||||
};
|
||||
|
||||
const MyPlot = ({ format, image }: { format: string; image: string }) => {
|
||||
@@ -139,7 +195,7 @@ const MyPlot = ({ format, image }: { format: string; image: string }) => {
|
||||
return (
|
||||
<img
|
||||
src={imageSrc}
|
||||
style={{ maxWidth: "100%", height: "auto", borderRadius: "8px", marginTop: "10px" }}
|
||||
style={{ maxWidth: '100%', height: 'auto', borderRadius: '8px', marginTop: '10px' }}
|
||||
alt="plot"
|
||||
/>
|
||||
);
|
||||
@@ -147,7 +203,7 @@ const MyPlot = ({ format, image }: { format: string; image: string }) => {
|
||||
|
||||
const MyError = ({ content }: { content: string }) => {
|
||||
return (
|
||||
<span style={{ color: "#ff6b6b", fontWeight: "bold", display: "block", marginTop: "0.5rem" }}>
|
||||
<span style={{ color: '#ff6b6b', fontWeight: 'bold', display: 'block', marginTop: '0.5rem' }}>
|
||||
Error: {content}
|
||||
</span>
|
||||
);
|
||||
@@ -156,7 +212,59 @@ const MyError = ({ content }: { content: string }) => {
|
||||
const ConversationDetailCard = ({
|
||||
message,
|
||||
user_created,
|
||||
promptId,
|
||||
citations = [],
|
||||
isStreaming = false,
|
||||
isLast = false,
|
||||
conversationTitle = 'conversation',
|
||||
createdTimestamp = null,
|
||||
initialRating = null,
|
||||
onRatingChange,
|
||||
}: ConversationDetailCardProps): JSX.Element => {
|
||||
const [highlightIndex, setHighlightIndex] = useState<number | null>(null);
|
||||
|
||||
const CitationMark = useCallback(
|
||||
({ indices }: { indices?: string }) => {
|
||||
const list = (indices || '')
|
||||
.split(',')
|
||||
.map((n) => Number(n.trim()))
|
||||
.filter((n) => !Number.isNaN(n));
|
||||
if (!list.length) return null;
|
||||
return (
|
||||
<>
|
||||
{list.map((index, i) => {
|
||||
const citation = citations.find((c) => c.index === index);
|
||||
return (
|
||||
<CitationButton
|
||||
key={`${index}-${i}`}
|
||||
type="button"
|
||||
aria-label={`Source ${index}`}
|
||||
title={citation?.title || `Source ${index}`}
|
||||
onClick={() => {
|
||||
setHighlightIndex(index);
|
||||
if (citation?.url) {
|
||||
// Prefer scroll/highlight; URL still available from Sources list
|
||||
}
|
||||
const el = document.getElementById(`citation-source-${index}`);
|
||||
el?.scrollIntoView?.({ behavior: 'smooth', block: 'nearest' });
|
||||
}}
|
||||
>
|
||||
[{index}]
|
||||
</CitationButton>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
},
|
||||
[citations],
|
||||
);
|
||||
|
||||
const displayMarkdown = useMemo(() => {
|
||||
if (!message) return message;
|
||||
if (!citations.length || user_created) return message;
|
||||
return injectCitationMarkers(message);
|
||||
}, [message, citations, user_created]);
|
||||
|
||||
if (message.length === 0) {
|
||||
return (
|
||||
<MessageContainer $isUser={false}>
|
||||
@@ -188,36 +296,45 @@ const ConversationDetailCard = ({
|
||||
);
|
||||
}
|
||||
|
||||
let contentToAdd = message;
|
||||
let contentToAdd = displayMarkdown;
|
||||
let rawForCopy = message;
|
||||
try {
|
||||
const parsedMessage = JSON.parse(message);
|
||||
if (
|
||||
parsedMessage &&
|
||||
typeof parsedMessage === "object" &&
|
||||
typeof parsedMessage === 'object' &&
|
||||
parsedMessage.type
|
||||
) {
|
||||
switch (parsedMessage.type) {
|
||||
case "text":
|
||||
contentToAdd = parsedMessage.content;
|
||||
case 'text':
|
||||
rawForCopy = parsedMessage.content;
|
||||
contentToAdd =
|
||||
citations.length && !user_created
|
||||
? injectCitationMarkers(parsedMessage.content)
|
||||
: parsedMessage.content;
|
||||
break;
|
||||
case "plot":
|
||||
case 'plot':
|
||||
contentToAdd = `<plot format="${parsedMessage.format}" image="${parsedMessage.image}"></plot>`;
|
||||
rawForCopy = message;
|
||||
break;
|
||||
case "error":
|
||||
case 'error':
|
||||
contentToAdd = `<error content="${parsedMessage.content}"></error>`;
|
||||
rawForCopy = message;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch { }
|
||||
} catch {
|
||||
/* plain markdown */
|
||||
}
|
||||
|
||||
return (
|
||||
<MessageContainer $isUser={user_created}>
|
||||
<Bubble $isUser={user_created}>
|
||||
<Markdown
|
||||
className="display-linebreak"
|
||||
style={{ whiteSpace: "pre-line" }}
|
||||
style={{ whiteSpace: 'pre-line' }}
|
||||
options={{
|
||||
overrides: {
|
||||
plot: {
|
||||
@@ -226,12 +343,35 @@ const ConversationDetailCard = ({
|
||||
error: {
|
||||
component: MyError,
|
||||
},
|
||||
pre: {
|
||||
component: CustomPreBlock,
|
||||
},
|
||||
citation: {
|
||||
component: CitationMark,
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
{contentToAdd}
|
||||
</Markdown>
|
||||
</Bubble>
|
||||
|
||||
{!user_created && citations.length > 0 && (
|
||||
<SourcesList citations={citations} highlightIndex={highlightIndex} />
|
||||
)}
|
||||
|
||||
<MessageActions
|
||||
promptId={promptId}
|
||||
rawMarkdown={rawForCopy}
|
||||
userCreated={user_created}
|
||||
isStreaming={isStreaming}
|
||||
isLast={isLast}
|
||||
conversationTitle={conversationTitle}
|
||||
createdTimestamp={createdTimestamp}
|
||||
citations={citations}
|
||||
initialRating={initialRating}
|
||||
onRatingChange={onRatingChange}
|
||||
/>
|
||||
</MessageContainer>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,25 +1,72 @@
|
||||
import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter";
|
||||
import tsx from "react-syntax-highlighter/dist/cjs/languages/prism/tsx";
|
||||
import { oneDark } from "react-syntax-highlighter/dist/cjs/styles/prism";
|
||||
import React, { useState } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';
|
||||
import tsx from 'react-syntax-highlighter/dist/cjs/languages/prism/tsx';
|
||||
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
|
||||
import ContentCopy from '@mui/icons-material/ContentCopy';
|
||||
import Check from '@mui/icons-material/Check';
|
||||
import { IconButton, Tooltip } from '@mui/material';
|
||||
import { copyTextToClipboard } from '../../utils/clipboard';
|
||||
import { showToast } from '../../utils/toastBus';
|
||||
|
||||
SyntaxHighlighter.registerLanguage("tsx", tsx);
|
||||
SyntaxHighlighter.registerLanguage('tsx', tsx);
|
||||
|
||||
type CustomCodeBlock = {
|
||||
children: string,
|
||||
className: string
|
||||
const Wrapper = styled.div`
|
||||
position: relative;
|
||||
max-width: 100%;
|
||||
`;
|
||||
|
||||
}
|
||||
const CopyBtn = styled(IconButton)`
|
||||
&& {
|
||||
position: absolute;
|
||||
top: 0.35rem;
|
||||
right: 0.35rem;
|
||||
z-index: 1;
|
||||
color: #fff;
|
||||
background: rgba(0, 0, 0, 0.35);
|
||||
padding: 0.25rem;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
type CustomCodeBlockProps = {
|
||||
children: string;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
const CustomCodeBlock = ({children, className}: CustomCodeBlock): JSX.Element => {
|
||||
const language = className?.replace("lang-","");
|
||||
return (
|
||||
<SyntaxHighlighter language={language} style={oneDark}>
|
||||
{children}
|
||||
</SyntaxHighlighter>
|
||||
)
|
||||
}
|
||||
const CustomCodeBlock = ({
|
||||
children,
|
||||
className,
|
||||
}: CustomCodeBlockProps): JSX.Element => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const language = className?.replace('lang-', '').replace('language-', '') || undefined;
|
||||
const code = typeof children === 'string' ? children : String(children ?? '');
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await copyTextToClipboard(code.replace(/\n$/, ''));
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
showToast('Could not copy code', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Wrapper>
|
||||
<Tooltip title={copied ? 'Copied' : 'Copy code'}>
|
||||
<CopyBtn aria-label="Copy code block" size="small" onClick={() => void handleCopy()}>
|
||||
{copied ? <Check fontSize="inherit" /> : <ContentCopy fontSize="inherit" />}
|
||||
</CopyBtn>
|
||||
</Tooltip>
|
||||
<SyntaxHighlighter language={language} style={oneDark}>
|
||||
{code}
|
||||
</SyntaxHighlighter>
|
||||
</Wrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export default CustomCodeBlock;
|
||||
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import CustomCodeBlock from "../CustomCodeBlock/CustomCodeBlock"
|
||||
import CustomCodeBlock from '../CustomCodeBlock/CustomCodeBlock';
|
||||
|
||||
type CustomPreBlockProps = {
|
||||
children: JSX.Element | JSX.Element[]
|
||||
}
|
||||
children: JSX.Element | JSX.Element[];
|
||||
};
|
||||
|
||||
const CustomPreBlock = ({children, ...rest}: CustomPreBlockProps): JSX.Element => {
|
||||
if ("type" in children && children["type"] === "code") {
|
||||
return CustomCodeBlock({children: children["props"]["children"], className: children["props"]["className"] });
|
||||
}
|
||||
|
||||
return <pre {...rest}>{children}</pre>
|
||||
}
|
||||
export default CustomPreBlock;
|
||||
const CustomPreBlock = ({ children, ...rest }: CustomPreBlockProps): JSX.Element => {
|
||||
const child = Array.isArray(children) ? children[0] : children;
|
||||
if (child && typeof child === 'object' && 'type' in child && child.type === 'code') {
|
||||
return (
|
||||
<CustomCodeBlock
|
||||
className={(child.props as { className?: string }).className}
|
||||
>
|
||||
{(child.props as { children?: string }).children as string}
|
||||
</CustomCodeBlock>
|
||||
);
|
||||
}
|
||||
|
||||
return <pre {...rest}>{children}</pre>;
|
||||
};
|
||||
|
||||
export default CustomPreBlock;
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import {
|
||||
IconButton,
|
||||
Tooltip,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Popover,
|
||||
Chip,
|
||||
TextField,
|
||||
Button,
|
||||
Stack,
|
||||
} from '@mui/material';
|
||||
import ContentCopy from '@mui/icons-material/ContentCopy';
|
||||
import Check from '@mui/icons-material/Check';
|
||||
import ThumbUp from '@mui/icons-material/ThumbUp';
|
||||
import ThumbUpOutlined from '@mui/icons-material/ThumbUpOutlined';
|
||||
import ThumbDown from '@mui/icons-material/ThumbDown';
|
||||
import ThumbDownOutlined from '@mui/icons-material/ThumbDownOutlined';
|
||||
import FileDownload from '@mui/icons-material/FileDownload';
|
||||
import { copyTextToClipboard } from '../../utils/clipboard';
|
||||
import { showToast } from '../../utils/toastBus';
|
||||
import {
|
||||
clearPromptFeedback,
|
||||
upsertPromptFeedback,
|
||||
type PromptRating,
|
||||
} from '../../utils/promptFeedback';
|
||||
import {
|
||||
exportChat,
|
||||
type ExportFormat,
|
||||
type ExportTurn,
|
||||
} from '../../utils/export/exportChat';
|
||||
import { AnalyticsEvents, trackEvent } from '../../utils/analytics';
|
||||
import type { Citation } from '../../utils/wsFrames';
|
||||
|
||||
const DOWN_REASONS: { code: string; label: string }[] = [
|
||||
{ code: 'incorrect', label: 'Incorrect' },
|
||||
{ code: 'out_of_date', label: 'Out of date' },
|
||||
{ code: 'didnt_follow_instructions', label: "Didn't follow instructions" },
|
||||
{ code: 'unsafe', label: 'Unsafe' },
|
||||
{ code: 'other', label: 'Other' },
|
||||
];
|
||||
|
||||
const ActionsRow = styled.div<{ $alwaysVisible: boolean }>`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.15rem;
|
||||
margin-top: 0.35rem;
|
||||
min-height: 2rem;
|
||||
max-width: 100%;
|
||||
flex-wrap: wrap;
|
||||
opacity: ${({ $alwaysVisible }) => ($alwaysVisible ? 1 : 0)};
|
||||
pointer-events: ${({ $alwaysVisible }) => ($alwaysVisible ? 'auto' : 'none')};
|
||||
transition: opacity 0.15s ease;
|
||||
|
||||
@media (hover: hover) and (pointer: fine) {
|
||||
/* Desktop: revealed via parent :hover / :focus-within when not forced visible */
|
||||
}
|
||||
|
||||
@media (hover: none), (pointer: coarse) {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
`;
|
||||
|
||||
const ActionIconButton = styled(IconButton)`
|
||||
&& {
|
||||
color: ${({ theme }) => theme.colors.text};
|
||||
opacity: 0.7;
|
||||
padding: 0.35rem;
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
opacity: 1;
|
||||
background: ${({ theme }) =>
|
||||
theme.darkMode ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)'};
|
||||
}
|
||||
|
||||
&.Mui-disabled {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
type MessageActionsProps = {
|
||||
promptId?: number;
|
||||
rawMarkdown: string;
|
||||
userCreated: boolean;
|
||||
isStreaming?: boolean;
|
||||
isLast?: boolean;
|
||||
conversationTitle: string;
|
||||
createdTimestamp?: Date | string | null;
|
||||
citations?: Citation[];
|
||||
initialRating?: PromptRating | null;
|
||||
onRatingChange?: (rating: PromptRating | null) => void;
|
||||
};
|
||||
|
||||
const MessageActions = ({
|
||||
promptId,
|
||||
rawMarkdown,
|
||||
userCreated,
|
||||
isStreaming = false,
|
||||
isLast = false,
|
||||
conversationTitle,
|
||||
createdTimestamp,
|
||||
citations = [],
|
||||
initialRating = null,
|
||||
onRatingChange,
|
||||
}: MessageActionsProps): JSX.Element | null => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [rating, setRating] = useState<PromptRating | null>(initialRating);
|
||||
const [exportAnchor, setExportAnchor] = useState<null | HTMLElement>(null);
|
||||
const [reasonAnchor, setReasonAnchor] = useState<null | HTMLElement>(null);
|
||||
const [reasonCode, setReasonCode] = useState<string | null>(null);
|
||||
const [reasonComment, setReasonComment] = useState('');
|
||||
const [focused, setFocused] = useState(false);
|
||||
const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const rowRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setRating(initialRating);
|
||||
}, [initialRating, promptId]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (copyTimer.current) clearTimeout(copyTimer.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (isStreaming) return null;
|
||||
|
||||
const alwaysVisible = isLast || focused || Boolean(exportAnchor) || Boolean(reasonAnchor);
|
||||
|
||||
const handleCopy = async () => {
|
||||
try {
|
||||
await copyTextToClipboard(rawMarkdown);
|
||||
setCopied(true);
|
||||
trackEvent(AnalyticsEvents.MESSAGE_COPIED, {
|
||||
role: userCreated ? 'user' : 'assistant',
|
||||
});
|
||||
if (copyTimer.current) clearTimeout(copyTimer.current);
|
||||
copyTimer.current = setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
showToast('Could not copy message', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const applyRating = async (next: PromptRating | null) => {
|
||||
if (!promptId) {
|
||||
showToast('Rating unavailable until message is saved', 'info');
|
||||
return;
|
||||
}
|
||||
const prev = rating;
|
||||
setRating(next);
|
||||
onRatingChange?.(next);
|
||||
try {
|
||||
if (next == null) {
|
||||
await clearPromptFeedback(promptId);
|
||||
} else {
|
||||
await upsertPromptFeedback(promptId, { rating: next });
|
||||
}
|
||||
trackEvent(AnalyticsEvents.MESSAGE_RATED, {
|
||||
rating: next ?? 'cleared',
|
||||
});
|
||||
} catch {
|
||||
setRating(prev);
|
||||
onRatingChange?.(prev);
|
||||
showToast('Could not save rating', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleThumb = async (
|
||||
next: PromptRating,
|
||||
event: React.MouseEvent<HTMLElement>,
|
||||
) => {
|
||||
if (rating === next) {
|
||||
await applyRating(null);
|
||||
return;
|
||||
}
|
||||
await applyRating(next);
|
||||
if (next === 'down') {
|
||||
setReasonAnchor(event.currentTarget);
|
||||
setReasonCode(null);
|
||||
setReasonComment('');
|
||||
}
|
||||
};
|
||||
|
||||
const submitReason = async () => {
|
||||
if (!promptId || rating !== 'down') {
|
||||
setReasonAnchor(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await upsertPromptFeedback(promptId, {
|
||||
rating: 'down',
|
||||
reason: reasonCode ?? undefined,
|
||||
comment: reasonComment.trim() || undefined,
|
||||
});
|
||||
trackEvent(AnalyticsEvents.MESSAGE_RATING_REASON, {
|
||||
reason: reasonCode ?? 'none',
|
||||
hasComment: Boolean(reasonComment.trim()),
|
||||
});
|
||||
} catch {
|
||||
showToast('Could not save feedback reason', 'error');
|
||||
} finally {
|
||||
setReasonAnchor(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = async (format: ExportFormat) => {
|
||||
setExportAnchor(null);
|
||||
const turn: ExportTurn = {
|
||||
role: userCreated ? 'user' : 'assistant',
|
||||
message: rawMarkdown,
|
||||
timestamp: createdTimestamp ?? null,
|
||||
citations: userCreated ? [] : citations,
|
||||
};
|
||||
try {
|
||||
await exportChat({
|
||||
format,
|
||||
scope: 'message',
|
||||
title: conversationTitle,
|
||||
turns: [turn],
|
||||
});
|
||||
trackEvent(AnalyticsEvents.MESSAGE_EXPORTED, {
|
||||
format,
|
||||
scope: 'message',
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showToast('Export failed', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ActionsRow
|
||||
ref={rowRef}
|
||||
$alwaysVisible={alwaysVisible}
|
||||
data-message-actions
|
||||
onFocusCapture={() => setFocused(true)}
|
||||
onBlurCapture={(e) => {
|
||||
if (!rowRef.current?.contains(e.relatedTarget as Node)) {
|
||||
setFocused(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Tooltip title={copied ? 'Copied' : 'Copy markdown'}>
|
||||
<ActionIconButton
|
||||
aria-label="Copy message as markdown"
|
||||
size="small"
|
||||
onClick={() => void handleCopy()}
|
||||
>
|
||||
{copied ? <Check fontSize="small" /> : <ContentCopy fontSize="small" />}
|
||||
</ActionIconButton>
|
||||
</Tooltip>
|
||||
|
||||
{!userCreated && (
|
||||
<>
|
||||
<Tooltip title="Thumbs up">
|
||||
<span>
|
||||
<ActionIconButton
|
||||
aria-label="Thumbs up"
|
||||
size="small"
|
||||
disabled={!promptId}
|
||||
onClick={(e) => void handleThumb('up', e)}
|
||||
>
|
||||
{rating === 'up' ? (
|
||||
<ThumbUp fontSize="small" />
|
||||
) : (
|
||||
<ThumbUpOutlined fontSize="small" />
|
||||
)}
|
||||
</ActionIconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
<Tooltip title="Thumbs down">
|
||||
<span>
|
||||
<ActionIconButton
|
||||
aria-label="Thumbs down"
|
||||
size="small"
|
||||
disabled={!promptId}
|
||||
onClick={(e) => void handleThumb('down', e)}
|
||||
>
|
||||
{rating === 'down' ? (
|
||||
<ThumbDown fontSize="small" />
|
||||
) : (
|
||||
<ThumbDownOutlined fontSize="small" />
|
||||
)}
|
||||
</ActionIconButton>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Tooltip title="Export">
|
||||
<ActionIconButton
|
||||
aria-label="Export message"
|
||||
size="small"
|
||||
onClick={(e) => setExportAnchor(e.currentTarget)}
|
||||
>
|
||||
<FileDownload fontSize="small" />
|
||||
</ActionIconButton>
|
||||
</Tooltip>
|
||||
|
||||
<Menu
|
||||
anchorEl={exportAnchor}
|
||||
open={Boolean(exportAnchor)}
|
||||
onClose={() => setExportAnchor(null)}
|
||||
>
|
||||
{(
|
||||
[
|
||||
['pdf', 'PDF'],
|
||||
['docx', 'Word (.docx)'],
|
||||
['csv', 'CSV'],
|
||||
['xlsx', 'Excel (.xlsx)'],
|
||||
['txt', 'Plain text'],
|
||||
] as [ExportFormat, string][]
|
||||
).map(([format, label]) => (
|
||||
<MenuItem key={format} onClick={() => void handleExport(format)}>
|
||||
{label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
|
||||
<Popover
|
||||
open={Boolean(reasonAnchor)}
|
||||
anchorEl={reasonAnchor}
|
||||
onClose={() => setReasonAnchor(null)}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'left' }}
|
||||
>
|
||||
<Stack spacing={1.25} sx={{ p: 1.5, width: 280, maxWidth: '90vw' }}>
|
||||
<div style={{ fontSize: '0.85rem', fontWeight: 600 }}>
|
||||
What went wrong? (optional)
|
||||
</div>
|
||||
<Stack direction="row" flexWrap="wrap" gap={0.75}>
|
||||
{DOWN_REASONS.map((reason) => (
|
||||
<Chip
|
||||
key={reason.code}
|
||||
label={reason.label}
|
||||
size="small"
|
||||
color={reasonCode === reason.code ? 'primary' : 'default'}
|
||||
onClick={() => setReasonCode(reason.code)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
<TextField
|
||||
size="small"
|
||||
multiline
|
||||
minRows={2}
|
||||
placeholder="Additional details (optional)"
|
||||
value={reasonComment}
|
||||
onChange={(e) => setReasonComment(e.target.value)}
|
||||
/>
|
||||
<Button variant="contained" size="small" onClick={() => void submitReason()}>
|
||||
Done
|
||||
</Button>
|
||||
</Stack>
|
||||
</Popover>
|
||||
</ActionsRow>
|
||||
);
|
||||
};
|
||||
|
||||
export default MessageActions;
|
||||
@@ -0,0 +1,138 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import type { Citation } from '../../utils/wsFrames';
|
||||
|
||||
const SourcesRoot = styled.aside`
|
||||
margin-top: 0.65rem;
|
||||
max-width: 80%;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
padding: 0.65rem 0.85rem;
|
||||
border-radius: 0.75rem;
|
||||
border: 1px solid ${({ theme }) => theme.colors.cardBorder};
|
||||
background: ${({ theme }) =>
|
||||
theme.darkMode ? 'rgba(255, 255, 255, 0.04)' : 'rgba(0, 0, 0, 0.03)'};
|
||||
color: ${({ theme }) => theme.colors.text};
|
||||
|
||||
@media (max-width: 768px) {
|
||||
max-width: 92%;
|
||||
}
|
||||
`;
|
||||
|
||||
const SourcesTitle = styled.h4`
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
opacity: 0.75;
|
||||
`;
|
||||
|
||||
const SourceList = styled.ol`
|
||||
margin: 0;
|
||||
padding-left: 1.25rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
`;
|
||||
|
||||
const SourceItem = styled.li<{ $highlight: boolean }>`
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
border-radius: 0.35rem;
|
||||
padding: 0.15rem 0.25rem;
|
||||
outline: ${({ $highlight, theme }) =>
|
||||
$highlight ? `2px solid ${theme.main}` : 'none'};
|
||||
background: ${({ $highlight, theme }) =>
|
||||
$highlight
|
||||
? theme.darkMode
|
||||
? 'rgba(255,255,255,0.08)'
|
||||
: 'rgba(0,0,0,0.06)'
|
||||
: 'transparent'};
|
||||
transition: background 0.2s ease, outline 0.2s ease;
|
||||
`;
|
||||
|
||||
const SourceLink = styled.a`
|
||||
color: ${({ theme }) => (theme.darkMode ? '#a0c4ff' : theme.main)};
|
||||
text-decoration: underline;
|
||||
word-break: break-word;
|
||||
`;
|
||||
|
||||
const SourceMeta = styled.span`
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
opacity: 0.65;
|
||||
margin-top: 0.1rem;
|
||||
`;
|
||||
|
||||
function domainFromUrl(url: string): string {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, '');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
type SourcesListProps = {
|
||||
citations: Citation[];
|
||||
highlightIndex?: number | null;
|
||||
};
|
||||
|
||||
const SourcesList = ({
|
||||
citations,
|
||||
highlightIndex = null,
|
||||
}: SourcesListProps): JSX.Element | null => {
|
||||
const itemRefs = useRef<Record<number, HTMLLIElement | null>>({});
|
||||
const [active, setActive] = useState<number | null>(highlightIndex);
|
||||
|
||||
useEffect(() => {
|
||||
setActive(highlightIndex ?? null);
|
||||
if (highlightIndex == null) return;
|
||||
const el = itemRefs.current[highlightIndex];
|
||||
el?.scrollIntoView?.({ behavior: 'smooth', block: 'nearest' });
|
||||
}, [highlightIndex]);
|
||||
|
||||
if (!citations.length) return null;
|
||||
|
||||
const sorted = [...citations].sort((a, b) => a.index - b.index);
|
||||
|
||||
return (
|
||||
<SourcesRoot aria-label="Sources">
|
||||
<SourcesTitle>Sources</SourcesTitle>
|
||||
<SourceList>
|
||||
{sorted.map((citation) => {
|
||||
const domain = domainFromUrl(citation.url);
|
||||
return (
|
||||
<SourceItem
|
||||
key={citation.index}
|
||||
id={`citation-source-${citation.index}`}
|
||||
$highlight={active === citation.index}
|
||||
ref={(node) => {
|
||||
itemRefs.current[citation.index] = node;
|
||||
}}
|
||||
>
|
||||
{citation.url ? (
|
||||
<SourceLink
|
||||
href={citation.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{citation.title || `Source ${citation.index}`}
|
||||
</SourceLink>
|
||||
) : (
|
||||
<span>{citation.title || `Source ${citation.index}`}</span>
|
||||
)}
|
||||
{(citation.published_at || domain) && (
|
||||
<SourceMeta>
|
||||
{[citation.published_at, domain].filter(Boolean).join(' · ')}
|
||||
</SourceMeta>
|
||||
)}
|
||||
</SourceItem>
|
||||
);
|
||||
})}
|
||||
</SourceList>
|
||||
</SourcesRoot>
|
||||
);
|
||||
};
|
||||
|
||||
export default SourcesList;
|
||||
@@ -0,0 +1,40 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Snackbar, Alert } from '@mui/material';
|
||||
import { subscribeToast } from '../../utils/toastBus';
|
||||
|
||||
/**
|
||||
* Global snackbar host for copy/export/feedback errors (#97).
|
||||
*/
|
||||
const ToastHost = (): JSX.Element => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [severity, setSeverity] = useState<'error' | 'success' | 'info'>('info');
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeToast((nextMessage, nextSeverity) => {
|
||||
setMessage(nextMessage);
|
||||
setSeverity(nextSeverity);
|
||||
setOpen(true);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={4000}
|
||||
onClose={() => setOpen(false)}
|
||||
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
|
||||
>
|
||||
<Alert
|
||||
onClose={() => setOpen(false)}
|
||||
severity={severity}
|
||||
variant="filled"
|
||||
sx={{ width: '100%' }}
|
||||
>
|
||||
{message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
);
|
||||
};
|
||||
|
||||
export default ToastHost;
|
||||
@@ -6,6 +6,7 @@ import { ConversationPrompt, ConversationPromptType } from "../data";
|
||||
import { axiosInstance } from "../../axiosApi";
|
||||
import { AxiosResponse } from "axios";
|
||||
import { AnalyticsEvents, trackEvent } from "../utils/analytics";
|
||||
import { parseCitationsData, parseVersionedFrame } from "../utils/wsFrames";
|
||||
|
||||
type MessageProviderProps ={
|
||||
children? : ReactNode;
|
||||
@@ -53,6 +54,7 @@ const MessageProvider = ( {children}: MessageProviderProps) => {
|
||||
const selectedConversationRef = useRef<undefined | number>(undefined)
|
||||
const isGeneratingRef = useRef(false)
|
||||
const prevReconnectGenerationRef = useRef(0)
|
||||
const refetchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
const clearStreamInterrupted = () => setStreamInterrupted(false)
|
||||
|
||||
@@ -76,8 +78,11 @@ const MessageProvider = ( {children}: MessageProviderProps) => {
|
||||
message: item.message,
|
||||
user_created: item.user_created,
|
||||
created_timestamp: item.created_timestamp,
|
||||
created: item.created,
|
||||
tokens_in: item.tokens_in ?? null,
|
||||
tokens_out: item.tokens_out ?? null,
|
||||
citations: item.citations ?? [],
|
||||
feedback: item.feedback ?? null,
|
||||
}),
|
||||
)
|
||||
if (tempConversations.length === 1) {
|
||||
@@ -93,10 +98,27 @@ const MessageProvider = ( {children}: MessageProviderProps) => {
|
||||
}
|
||||
}
|
||||
|
||||
const schedulePostStreamRefetch = () => {
|
||||
if (refetchTimerRef.current) clearTimeout(refetchTimerRef.current)
|
||||
const conversationId = selectedConversationRef.current
|
||||
if (!conversationId) return
|
||||
// Backend saves the assistant prompt after END (+ citations frame); brief delay
|
||||
// hydrates prompt ids, persisted citations, and feedback.
|
||||
refetchTimerRef.current = setTimeout(() => {
|
||||
void GetConversationDetails(conversationId)
|
||||
}, 800)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
GetConversationDetails(selectedConversation)
|
||||
}, [selectedConversation])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (refetchTimerRef.current) clearTimeout(refetchTimerRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Streaming recovery: on reconnect after a drop mid-stream, refetch conversation
|
||||
// and mark the in-flight assistant turn interrupted (no resume protocol on backend).
|
||||
useEffect(() => {
|
||||
@@ -147,21 +169,46 @@ const MessageProvider = ( {children}: MessageProviderProps) => {
|
||||
|
||||
/* subscribe to channel and register callback */
|
||||
subscribe(channelName, (message: string) => {
|
||||
/* when a message is received just add it to the UI */
|
||||
|
||||
/* Versioned frames (citations #98, status #96) — ignore unknown types safely */
|
||||
const frame = parseVersionedFrame(message)
|
||||
if (frame) {
|
||||
if (frame.type === 'citations') {
|
||||
const citations = parseCitationsData(frame.data)
|
||||
const details = [...conversationRef.current]
|
||||
for (let i = details.length - 1; i >= 0; i -= 1) {
|
||||
if (!details[i].user_created && details[i].message) {
|
||||
details[i] = new ConversationPrompt({
|
||||
...details[i],
|
||||
citations,
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
conversationRef.current = details
|
||||
setConversationDetails(details)
|
||||
schedulePostStreamRefetch()
|
||||
}
|
||||
// status / unknown types: no-op (compatible with #96)
|
||||
return
|
||||
}
|
||||
|
||||
if (message === 'END_OF_THE_STREAM_ENDER_GAME_42'){
|
||||
messageResponsePart.current = 0
|
||||
|
||||
conversationRef.current.pop()
|
||||
|
||||
//handleAssistantPrompt({prompt: messageRef.current})
|
||||
setConversationDetails([...conversationRef.current, new ConversationPrompt({message: `${messageRef.current}`, user_created:false})])
|
||||
console.log([...conversationRef.current, new ConversationPrompt({message: `${messageRef.current}`, user_created:false})])
|
||||
const finalized = new ConversationPrompt({
|
||||
message: `${messageRef.current}`,
|
||||
user_created: false,
|
||||
})
|
||||
conversationRef.current = [...conversationRef.current, finalized]
|
||||
setConversationDetails([...conversationRef.current])
|
||||
messageRef.current = ''
|
||||
setStateMessage('')
|
||||
isGeneratingRef.current = false
|
||||
setIsGeneratingMessage(false)
|
||||
setStreamInterrupted(false)
|
||||
schedulePostStreamRefetch()
|
||||
}
|
||||
else if (message === 'START_OF_THE_STREAM_ENDER_GAME_42'){
|
||||
conversationRef.current = conversationDetails
|
||||
@@ -176,23 +223,26 @@ const MessageProvider = ( {children}: MessageProviderProps) => {
|
||||
setStreamInterrupted(false)
|
||||
messageResponsePart.current = 1
|
||||
}else{
|
||||
isGeneratingRef.current = true
|
||||
setIsGeneratingMessage(true)
|
||||
if (messageResponsePart.current === 1){
|
||||
isGeneratingRef.current = true
|
||||
setIsGeneratingMessage(true)
|
||||
// this has to do with the conversation id
|
||||
if(!selectedConversation){
|
||||
const conversationId = Number(message);
|
||||
setSelectedConversation(conversationId)
|
||||
selectedConversationRef.current = conversationId
|
||||
trackEvent(AnalyticsEvents.CONVERSATION_CREATED, {
|
||||
conversationId,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (messageResponsePart.current === 2){
|
||||
isGeneratingRef.current = true
|
||||
setIsGeneratingMessage(true)
|
||||
messageRef.current += message
|
||||
setStateMessage(messageRef.current)
|
||||
|
||||
}
|
||||
// ignore stray frames outside an active stream phase
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
import type { Citation } from './utils/wsFrames';
|
||||
import type { PromptRating } from './utils/promptFeedback';
|
||||
|
||||
export type PromptFeedbackState = {
|
||||
rating: PromptRating;
|
||||
reason?: string | null;
|
||||
comment?: string | null;
|
||||
};
|
||||
|
||||
/* Classes for the project */
|
||||
export interface ConversationPromptType {
|
||||
id: number,
|
||||
message: string,
|
||||
user_created: boolean,
|
||||
created_timestamp: Date,
|
||||
created_timestamp?: Date,
|
||||
created?: Date | string,
|
||||
tokens_in?: number | null,
|
||||
tokens_out?: number | null,
|
||||
citations?: Citation[],
|
||||
feedback?: PromptFeedbackState | null,
|
||||
}
|
||||
|
||||
export class ConversationPrompt{
|
||||
@@ -15,6 +27,8 @@ export class ConversationPrompt{
|
||||
created_timestamp: Date = new Date();
|
||||
tokens_in: number | null = null;
|
||||
tokens_out: number | null = null;
|
||||
citations: Citation[] = [];
|
||||
feedback: PromptFeedbackState | null = null;
|
||||
|
||||
constructor(initializer?: any){
|
||||
if(!initializer) return;
|
||||
@@ -22,8 +36,11 @@ export class ConversationPrompt{
|
||||
if (initializer.message) this.message = initializer.message;
|
||||
if (initializer.user_created) this.user_created = initializer.user_created;
|
||||
if (initializer.created_timestamp) this.created_timestamp = initializer.created_timestamp;
|
||||
else if (initializer.created) this.created_timestamp = new Date(initializer.created);
|
||||
if (initializer.tokens_in !== undefined) this.tokens_in = initializer.tokens_in;
|
||||
if (initializer.tokens_out !== undefined) this.tokens_out = initializer.tokens_out;
|
||||
if (Array.isArray(initializer.citations)) this.citations = initializer.citations;
|
||||
if (initializer.feedback !== undefined) this.feedback = initializer.feedback;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ import React, { useContext, useEffect, useRef, useState } from "react";
|
||||
import styled, { ThemeContext } from "styled-components";
|
||||
import { Formik, Form, Field } from "formik";
|
||||
import * as Yup from "yup";
|
||||
import { AttachFile, Delete, Send, Close } from "@mui/icons-material"; // Keeping icons for now, can replace later if needed
|
||||
import { Tooltip } from "@mui/material";
|
||||
import { AttachFile, Delete, Send, Close, FileDownload } from "@mui/icons-material";
|
||||
import { Tooltip, Menu, MenuItem, IconButton as MuiIconButton } from "@mui/material";
|
||||
import Markdown from "markdown-to-jsx";
|
||||
|
||||
import {
|
||||
@@ -17,6 +17,9 @@ import ParticleBackground from "../../components/ParticleBackground/ParticleBack
|
||||
|
||||
import Header2 from "../../components/Header2/Header2";
|
||||
import { AnalyticsEvents, trackEvent } from "../../utils/analytics";
|
||||
import { exportChat, type ExportFormat } from "../../utils/export/exportChat";
|
||||
import { showToast } from "../../utils/toastBus";
|
||||
import type { PromptRating } from "../../utils/promptFeedback";
|
||||
|
||||
// Styled Components
|
||||
const PageContainer = styled.div`
|
||||
@@ -152,6 +155,18 @@ const ChatArea = styled.div`
|
||||
}
|
||||
`;
|
||||
|
||||
const ChatToolbar = styled.div`
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
padding: 0.25rem 2rem 0;
|
||||
flex-shrink: 0;
|
||||
|
||||
@media (max-width: 768px) {
|
||||
padding: 0.25rem 0.85rem 0;
|
||||
}
|
||||
`;
|
||||
|
||||
const InputArea = styled.div`
|
||||
flex-shrink: 0;
|
||||
box-sizing: border-box;
|
||||
@@ -361,6 +376,57 @@ const AsyncDashboardInner = (): JSX.Element => {
|
||||
const theme = useContext(ThemeContext);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
|
||||
const [exportAnchor, setExportAnchor] = useState<null | HTMLElement>(null);
|
||||
|
||||
const selectedTitle =
|
||||
conversations.find((c) => c.id === selectedConversation)?.title ||
|
||||
'conversation';
|
||||
|
||||
const handleConversationExport = async (format: ExportFormat) => {
|
||||
setExportAnchor(null);
|
||||
const turns = conversationDetails
|
||||
.filter((d) => d.message.length > 0)
|
||||
.map((d) => ({
|
||||
role: (d.user_created ? 'user' : 'assistant') as 'user' | 'assistant',
|
||||
message: d.message,
|
||||
timestamp: d.created_timestamp,
|
||||
citations: d.citations,
|
||||
}));
|
||||
if (!turns.length) {
|
||||
showToast('Nothing to export yet', 'info');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await exportChat({
|
||||
format,
|
||||
scope: 'conversation',
|
||||
title: selectedTitle,
|
||||
turns,
|
||||
});
|
||||
trackEvent(AnalyticsEvents.MESSAGE_EXPORTED, {
|
||||
format,
|
||||
scope: 'conversation',
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
showToast('Export failed', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const updatePromptRating = (promptId: number | undefined, rating: PromptRating | null) => {
|
||||
if (!promptId) return;
|
||||
const next = conversationDetails.map((detail) => {
|
||||
if (detail.id !== promptId) return detail;
|
||||
return new ConversationPrompt({
|
||||
...detail,
|
||||
feedback: rating
|
||||
? { rating, reason: detail.feedback?.reason, comment: detail.feedback?.comment }
|
||||
: null,
|
||||
});
|
||||
});
|
||||
conversationRef.current = next;
|
||||
setConversationDetails(next);
|
||||
};
|
||||
|
||||
const connectionBanner = (() => {
|
||||
if (connectionStatus === ConnectionStatus.CONNECTED || isConnected) {
|
||||
@@ -483,23 +549,66 @@ const AsyncDashboardInner = (): JSX.Element => {
|
||||
</Sidebar>
|
||||
|
||||
<MainContent>
|
||||
{conversationDetails.length > 0 && (
|
||||
<ChatToolbar>
|
||||
<Tooltip title="Export conversation">
|
||||
<MuiIconButton
|
||||
aria-label="Export conversation"
|
||||
size="small"
|
||||
onClick={(e) => setExportAnchor(e.currentTarget)}
|
||||
sx={{ color: theme?.colors?.text }}
|
||||
>
|
||||
<FileDownload fontSize="small" />
|
||||
</MuiIconButton>
|
||||
</Tooltip>
|
||||
<Menu
|
||||
anchorEl={exportAnchor}
|
||||
open={Boolean(exportAnchor)}
|
||||
onClose={() => setExportAnchor(null)}
|
||||
>
|
||||
{(
|
||||
[
|
||||
['pdf', 'PDF'],
|
||||
['docx', 'Word (.docx)'],
|
||||
['csv', 'CSV'],
|
||||
['xlsx', 'Excel (.xlsx)'],
|
||||
['txt', 'Plain text'],
|
||||
] as [ExportFormat, string][]
|
||||
).map(([format, label]) => (
|
||||
<MenuItem key={format} onClick={() => void handleConversationExport(format)}>
|
||||
{label}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Menu>
|
||||
</ChatToolbar>
|
||||
)}
|
||||
<ChatArea>
|
||||
{conversationDetails.length > 0 ? (
|
||||
conversationDetails.map((convo_detail, index) =>
|
||||
convo_detail.message.length > 0 ? (
|
||||
conversationDetails.map((convo_detail, index) => {
|
||||
const isLast = index === conversationDetails.length - 1;
|
||||
const isLiveStream =
|
||||
!convo_detail.user_created && convo_detail.message.length === 0;
|
||||
const displayMessage = isLiveStream
|
||||
? stateMessage
|
||||
: convo_detail.message;
|
||||
return (
|
||||
<ConversationDetailCard
|
||||
message={convo_detail.message}
|
||||
user_created={convo_detail.user_created}
|
||||
key={convo_detail.id || index}
|
||||
/>
|
||||
) : (
|
||||
<ConversationDetailCard
|
||||
message={stateMessage}
|
||||
message={displayMessage}
|
||||
user_created={convo_detail.user_created}
|
||||
key={convo_detail.id || index}
|
||||
promptId={convo_detail.id}
|
||||
citations={convo_detail.citations}
|
||||
isStreaming={isLiveStream}
|
||||
isLast={isLast}
|
||||
conversationTitle={selectedTitle}
|
||||
createdTimestamp={convo_detail.created_timestamp}
|
||||
initialRating={convo_detail.feedback?.rating ?? null}
|
||||
onRatingChange={(rating) =>
|
||||
updatePromptRating(convo_detail.id, rating)
|
||||
}
|
||||
/>
|
||||
)
|
||||
)
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
|
||||
@@ -25,6 +25,7 @@ const queue: QueuedCall[] = [];
|
||||
* | Plan Change Started | Change-plan intent (#75) |
|
||||
* | Subscription Cancel Started | Cancel intent (#75) |
|
||||
* | Account Delete Started / Success / Failed | Self-delete (#34 companion) |
|
||||
* | Message Copied / Rated / Rating Reason / Exported | Message actions (#97) |
|
||||
*/
|
||||
export const AnalyticsEvents = {
|
||||
LOGIN_SUCCESS: 'Login Success',
|
||||
@@ -46,6 +47,10 @@ export const AnalyticsEvents = {
|
||||
ACCOUNT_DELETE_STARTED: 'Account Delete Started',
|
||||
ACCOUNT_DELETE_SUCCESS: 'Account Delete Success',
|
||||
ACCOUNT_DELETE_FAILED: 'Account Delete Failed',
|
||||
MESSAGE_COPIED: 'Message Copied',
|
||||
MESSAGE_RATED: 'Message Rated',
|
||||
MESSAGE_RATING_REASON: 'Message Rating Reason',
|
||||
MESSAGE_EXPORTED: 'Message Exported',
|
||||
} as const;
|
||||
|
||||
export type AnalyticsEventName = (typeof AnalyticsEvents)[keyof typeof AnalyticsEvents];
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { copyTextToClipboard } from './clipboard';
|
||||
|
||||
describe('clipboard', () => {
|
||||
const originalClipboard = navigator.clipboard;
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: originalClipboard,
|
||||
});
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('uses navigator.clipboard.writeText when available', async () => {
|
||||
const writeText = jest.fn().mockResolvedValue(undefined);
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: { writeText },
|
||||
});
|
||||
await copyTextToClipboard('hello');
|
||||
expect(writeText).toHaveBeenCalledWith('hello');
|
||||
});
|
||||
|
||||
it('falls back to execCommand when clipboard API fails', async () => {
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: {
|
||||
writeText: jest.fn().mockRejectedValue(new Error('denied')),
|
||||
},
|
||||
});
|
||||
Object.defineProperty(document, 'execCommand', {
|
||||
configurable: true,
|
||||
value: jest.fn().mockReturnValue(true),
|
||||
});
|
||||
await copyTextToClipboard('fallback text');
|
||||
expect(document.execCommand).toHaveBeenCalledWith('copy');
|
||||
});
|
||||
|
||||
it('falls back when clipboard API is missing', async () => {
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: undefined,
|
||||
});
|
||||
Object.defineProperty(document, 'execCommand', {
|
||||
configurable: true,
|
||||
value: jest.fn().mockReturnValue(true),
|
||||
});
|
||||
await copyTextToClipboard('legacy');
|
||||
expect(document.execCommand).toHaveBeenCalledWith('copy');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Clipboard helper with execCommand fallback for Capacitor / insecure contexts (#97).
|
||||
*/
|
||||
export async function copyTextToClipboard(text: string): Promise<void> {
|
||||
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return;
|
||||
} catch {
|
||||
// fall through to legacy path
|
||||
}
|
||||
}
|
||||
fallbackCopyText(text);
|
||||
}
|
||||
|
||||
function fallbackCopyText(text: string): void {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = text;
|
||||
textarea.setAttribute('readonly', '');
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.top = '0';
|
||||
textarea.style.left = '0';
|
||||
textarea.style.opacity = '0';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.focus();
|
||||
textarea.select();
|
||||
textarea.setSelectionRange(0, textarea.value.length);
|
||||
const ok = document.execCommand('copy');
|
||||
document.body.removeChild(textarea);
|
||||
if (!ok) {
|
||||
throw new Error('Copy command failed');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Client-side file download. Uses blob URL + anchor click.
|
||||
* Capacitor Android WebView: plain downloads often work for blob URLs;
|
||||
* if not, consider @capacitor/filesystem + Share (#97).
|
||||
*/
|
||||
export function downloadBlob(blob: Blob, filename: string): void {
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = filename;
|
||||
anchor.rel = 'noopener';
|
||||
anchor.style.display = 'none';
|
||||
document.body.appendChild(anchor);
|
||||
anchor.click();
|
||||
document.body.removeChild(anchor);
|
||||
} finally {
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
}
|
||||
|
||||
export function downloadText(text: string, filename: string, mime = 'text/plain;charset=utf-8'): void {
|
||||
downloadBlob(new Blob([text], { type: mime }), filename);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
buildExportFilename,
|
||||
extractMarkdownTables,
|
||||
parseMarkdownBlocks,
|
||||
sanitizeFilenamePart,
|
||||
stripMarkdown,
|
||||
} from './markdownUtils';
|
||||
import { selectTabularStrategy } from './exportChat';
|
||||
|
||||
describe('export markdown utils', () => {
|
||||
it('sanitises filenames with title + ISO date', () => {
|
||||
expect(sanitizeFilenamePart('Hesychia Taylor Swift Question!')).toBe(
|
||||
'hesychia-taylor-swift-question',
|
||||
);
|
||||
expect(
|
||||
buildExportFilename('Hesychia Taylor Swift Question', 'pdf', new Date('2026-08-02T12:00:00Z')),
|
||||
).toBe('hesychia-taylor-swift-question-2026-08-02.pdf');
|
||||
});
|
||||
|
||||
it('strips markdown for plain text', () => {
|
||||
expect(stripMarkdown('# Hello\n\n**world**')).toContain('Hello');
|
||||
expect(stripMarkdown('# Hello\n\n**world**')).not.toContain('**');
|
||||
});
|
||||
|
||||
it('parses headings, lists, tables, and code', () => {
|
||||
const blocks = parseMarkdownBlocks(
|
||||
[
|
||||
'# Title',
|
||||
'',
|
||||
'- a',
|
||||
'- b',
|
||||
'',
|
||||
'```js',
|
||||
'console.log(1)',
|
||||
'```',
|
||||
'',
|
||||
'| A | B |',
|
||||
'| --- | --- |',
|
||||
'| 1 | 2 |',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(blocks.find((b) => b.type === 'heading')).toMatchObject({
|
||||
level: 1,
|
||||
text: 'Title',
|
||||
});
|
||||
expect(blocks.find((b) => b.type === 'list')).toMatchObject({
|
||||
ordered: false,
|
||||
items: ['a', 'b'],
|
||||
});
|
||||
expect(blocks.find((b) => b.type === 'code')).toMatchObject({
|
||||
language: 'js',
|
||||
text: 'console.log(1)',
|
||||
});
|
||||
expect(blocks.find((b) => b.type === 'table')).toMatchObject({
|
||||
headers: ['A', 'B'],
|
||||
rows: [['1', '2']],
|
||||
});
|
||||
});
|
||||
|
||||
it('selects tabular strategy per CSV/XLSX rules', () => {
|
||||
const withTable = '| A | B |\n| --- | --- |\n| 1 | 2 |';
|
||||
expect(selectTabularStrategy('message', withTable)).toBe('tables');
|
||||
expect(selectTabularStrategy('message', 'no table here')).toBe('turns');
|
||||
expect(selectTabularStrategy('conversation', withTable)).toBe('turns');
|
||||
expect(extractMarkdownTables(withTable)).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,477 @@
|
||||
import { downloadBlob, downloadText } from '../downloadFile';
|
||||
import { Citation } from '../wsFrames';
|
||||
import {
|
||||
buildExportFilename,
|
||||
extractMarkdownTables,
|
||||
parseMarkdownBlocks,
|
||||
stripMarkdown,
|
||||
type MdBlock,
|
||||
} from './markdownUtils';
|
||||
|
||||
export type ExportFormat = 'pdf' | 'docx' | 'csv' | 'xlsx' | 'txt';
|
||||
|
||||
export type ExportTurn = {
|
||||
role: 'user' | 'assistant';
|
||||
message: string;
|
||||
timestamp?: string | Date | null;
|
||||
citations?: Citation[];
|
||||
};
|
||||
|
||||
export type ExportScope = 'message' | 'conversation';
|
||||
|
||||
export type ExportOptions = {
|
||||
format: ExportFormat;
|
||||
scope: ExportScope;
|
||||
title: string;
|
||||
turns: ExportTurn[];
|
||||
};
|
||||
|
||||
function yieldToUi(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function formatTs(value?: string | Date | null): string {
|
||||
if (!value) return '';
|
||||
try {
|
||||
return new Date(value).toISOString();
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function roleLabel(role: ExportTurn['role']): string {
|
||||
return role === 'user' ? 'User' : 'Assistant';
|
||||
}
|
||||
|
||||
function citationFootnotes(citations?: Citation[]): string {
|
||||
if (!citations?.length) return '';
|
||||
return citations
|
||||
.map((c) => `[${c.index}] ${c.title}${c.url ? ` — ${c.url}` : ''}`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
export async function exportChat(options: ExportOptions): Promise<void> {
|
||||
const { format, scope, title, turns } = options;
|
||||
const filename = buildExportFilename(title, format === 'docx' ? 'docx' : format);
|
||||
const exportedAt = new Date().toISOString();
|
||||
|
||||
// Yield so large conversations don't freeze the main thread (#97).
|
||||
await yieldToUi();
|
||||
|
||||
switch (format) {
|
||||
case 'txt':
|
||||
downloadText(buildTxt(title, turns, scope), filename);
|
||||
break;
|
||||
case 'csv':
|
||||
await exportCsv(title, turns, scope, filename);
|
||||
break;
|
||||
case 'xlsx':
|
||||
await exportXlsx(title, turns, scope, filename);
|
||||
break;
|
||||
case 'pdf':
|
||||
await exportPdf(title, turns, exportedAt, filename);
|
||||
break;
|
||||
case 'docx':
|
||||
await exportDocx(title, turns, exportedAt, filename);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unsupported export format: ${format}`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildTxt(title: string, turns: ExportTurn[], scope: ExportScope): string {
|
||||
if (scope === 'message' && turns.length === 1) {
|
||||
const turn = turns[0];
|
||||
const body = stripMarkdown(turn.message);
|
||||
const notes = citationFootnotes(turn.citations);
|
||||
return notes ? `${body}\n\nSources:\n${notes}` : body;
|
||||
}
|
||||
const parts = [`# ${title}`, ''];
|
||||
for (const turn of turns) {
|
||||
const ts = formatTs(turn.timestamp);
|
||||
parts.push(`[${roleLabel(turn.role)}${ts ? ` · ${ts}` : ''}]`);
|
||||
parts.push(stripMarkdown(turn.message));
|
||||
const notes = citationFootnotes(turn.citations);
|
||||
if (notes) {
|
||||
parts.push('Sources:');
|
||||
parts.push(notes);
|
||||
}
|
||||
parts.push('');
|
||||
}
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
function turnsAsRows(turns: ExportTurn[]): string[][] {
|
||||
const header = ['timestamp', 'role', 'message', 'citations'];
|
||||
const rows = turns.map((turn) => [
|
||||
formatTs(turn.timestamp),
|
||||
roleLabel(turn.role),
|
||||
stripMarkdown(turn.message),
|
||||
citationFootnotes(turn.citations).replace(/\n/g, ' | '),
|
||||
]);
|
||||
return [header, ...rows];
|
||||
}
|
||||
|
||||
async function exportCsv(
|
||||
_title: string,
|
||||
turns: ExportTurn[],
|
||||
scope: ExportScope,
|
||||
filename: string,
|
||||
): Promise<void> {
|
||||
const Papa = (await import('papaparse')).default;
|
||||
let matrix: string[][];
|
||||
|
||||
if (scope === 'message' && turns.length === 1) {
|
||||
const tables = extractMarkdownTables(turns[0].message);
|
||||
if (tables.length > 0) {
|
||||
const table = tables[0];
|
||||
matrix = [table.headers, ...table.rows];
|
||||
} else {
|
||||
matrix = turnsAsRows(turns);
|
||||
}
|
||||
} else {
|
||||
matrix = turnsAsRows(turns);
|
||||
}
|
||||
|
||||
const csv = Papa.unparse(matrix);
|
||||
downloadText(csv, filename, 'text/csv;charset=utf-8');
|
||||
}
|
||||
|
||||
async function exportXlsx(
|
||||
_title: string,
|
||||
turns: ExportTurn[],
|
||||
scope: ExportScope,
|
||||
filename: string,
|
||||
): Promise<void> {
|
||||
const XLSX = await import('xlsx');
|
||||
const workbook = XLSX.utils.book_new();
|
||||
|
||||
if (scope === 'message' && turns.length === 1) {
|
||||
const tables = extractMarkdownTables(turns[0].message);
|
||||
if (tables.length > 0) {
|
||||
tables.forEach((table, idx) => {
|
||||
const sheet = XLSX.utils.aoa_to_sheet([table.headers, ...table.rows]);
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, `Table ${idx + 1}`);
|
||||
});
|
||||
} else {
|
||||
const sheet = XLSX.utils.aoa_to_sheet(turnsAsRows(turns));
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, 'Messages');
|
||||
}
|
||||
} else {
|
||||
const sheet = XLSX.utils.aoa_to_sheet(turnsAsRows(turns));
|
||||
XLSX.utils.book_append_sheet(workbook, sheet, 'Messages');
|
||||
}
|
||||
|
||||
const arrayBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
||||
downloadBlob(
|
||||
new Blob([arrayBuffer], {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
}),
|
||||
filename,
|
||||
);
|
||||
}
|
||||
|
||||
function blocksToPdfContent(blocks: MdBlock[]): unknown[] {
|
||||
const content: unknown[] = [];
|
||||
for (const block of blocks) {
|
||||
switch (block.type) {
|
||||
case 'heading':
|
||||
content.push({
|
||||
text: block.text,
|
||||
style: `h${Math.min(block.level, 3)}`,
|
||||
margin: [0, 8, 0, 4],
|
||||
});
|
||||
break;
|
||||
case 'paragraph':
|
||||
content.push({ text: block.text, margin: [0, 2, 0, 6] });
|
||||
break;
|
||||
case 'code':
|
||||
content.push({
|
||||
text: block.text,
|
||||
fontSize: 9,
|
||||
preserveLeadingSpaces: true,
|
||||
margin: [0, 4, 0, 8],
|
||||
background: '#f5f5f5',
|
||||
});
|
||||
break;
|
||||
case 'list':
|
||||
content.push(
|
||||
block.ordered
|
||||
? { ol: block.items, margin: [0, 2, 0, 6] }
|
||||
: { ul: block.items, margin: [0, 2, 0, 6] },
|
||||
);
|
||||
break;
|
||||
case 'table':
|
||||
content.push({
|
||||
table: {
|
||||
headerRows: 1,
|
||||
widths: block.headers.map(() => '*'),
|
||||
body: [
|
||||
block.headers.map((h) => ({ text: h, bold: true })),
|
||||
...block.rows.map((row) =>
|
||||
block.headers.map((_, col) => row[col] ?? ''),
|
||||
),
|
||||
],
|
||||
},
|
||||
margin: [0, 4, 0, 8],
|
||||
});
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
async function exportPdf(
|
||||
title: string,
|
||||
turns: ExportTurn[],
|
||||
exportedAt: string,
|
||||
filename: string,
|
||||
): Promise<void> {
|
||||
const pdfMakeModule = await import('pdfmake/build/pdfmake');
|
||||
const pdfFonts = await import('pdfmake/build/vfs_fonts');
|
||||
const pdfMake = pdfMakeModule.default || pdfMakeModule;
|
||||
// vfs_fonts may export vfs on default or as pdfMake.vfs
|
||||
const vfs =
|
||||
(pdfFonts as { pdfMake?: { vfs?: unknown }; default?: { pdfMake?: { vfs?: unknown } } })
|
||||
.pdfMake?.vfs ||
|
||||
(pdfFonts as { default?: { pdfMake?: { vfs?: unknown } } }).default?.pdfMake?.vfs ||
|
||||
(pdfFonts as { default?: unknown }).default;
|
||||
if (vfs) {
|
||||
(pdfMake as { vfs?: unknown }).vfs = vfs;
|
||||
}
|
||||
|
||||
const content: unknown[] = [
|
||||
{ text: title, style: 'title' },
|
||||
{ text: `Exported ${exportedAt}`, style: 'meta', margin: [0, 0, 0, 16] },
|
||||
];
|
||||
|
||||
for (let i = 0; i < turns.length; i += 1) {
|
||||
if (i > 0 && i % 20 === 0) await yieldToUi();
|
||||
const turn = turns[i];
|
||||
if (turns.length > 1) {
|
||||
content.push({
|
||||
text: `${roleLabel(turn.role)}${turn.timestamp ? ` · ${formatTs(turn.timestamp)}` : ''}`,
|
||||
style: 'role',
|
||||
margin: [0, 12, 0, 4],
|
||||
});
|
||||
}
|
||||
content.push(...blocksToPdfContent(parseMarkdownBlocks(turn.message)));
|
||||
if (turn.citations?.length) {
|
||||
content.push({ text: 'Sources', style: 'h3', margin: [0, 8, 0, 4] });
|
||||
content.push({
|
||||
ol: turn.citations
|
||||
.slice()
|
||||
.sort((a, b) => a.index - b.index)
|
||||
.map((c) => `${c.title}${c.url ? ` (${c.url})` : ''}`),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const docDefinition = {
|
||||
content,
|
||||
styles: {
|
||||
title: { fontSize: 18, bold: true },
|
||||
meta: { fontSize: 9, color: '#666666' },
|
||||
role: { fontSize: 11, bold: true, color: '#333333' },
|
||||
h1: { fontSize: 16, bold: true },
|
||||
h2: { fontSize: 14, bold: true },
|
||||
h3: { fontSize: 12, bold: true },
|
||||
},
|
||||
defaultStyle: { fontSize: 11 },
|
||||
header: {
|
||||
text: `${title} · ${exportedAt}`,
|
||||
fontSize: 8,
|
||||
color: '#888888',
|
||||
margin: [40, 20, 40, 0] as [number, number, number, number],
|
||||
},
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
try {
|
||||
// pdfmake typings vary across 0.2/0.3 builds; keep runtime call flexible.
|
||||
const pdf = (pdfMake as { createPdf: (def: unknown) => { getBlob: (cb: (blob: Blob) => void) => void } }).createPdf(
|
||||
docDefinition,
|
||||
);
|
||||
pdf.getBlob((blob: Blob) => {
|
||||
downloadBlob(blob, filename);
|
||||
resolve();
|
||||
});
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function exportDocx(
|
||||
title: string,
|
||||
turns: ExportTurn[],
|
||||
exportedAt: string,
|
||||
filename: string,
|
||||
): Promise<void> {
|
||||
const {
|
||||
Document,
|
||||
Packer,
|
||||
Paragraph,
|
||||
TextRun,
|
||||
HeadingLevel,
|
||||
Table,
|
||||
TableRow,
|
||||
TableCell,
|
||||
WidthType,
|
||||
Header,
|
||||
} = await import('docx');
|
||||
|
||||
const children: InstanceType<typeof Paragraph | typeof Table>[] = [
|
||||
new Paragraph({
|
||||
text: title,
|
||||
heading: HeadingLevel.TITLE,
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({ text: `Exported ${exportedAt}`, italics: true, size: 18, color: '666666' }),
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
for (let i = 0; i < turns.length; i += 1) {
|
||||
if (i > 0 && i % 20 === 0) await yieldToUi();
|
||||
const turn = turns[i];
|
||||
if (turns.length > 1) {
|
||||
children.push(
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: `${roleLabel(turn.role)}${turn.timestamp ? ` · ${formatTs(turn.timestamp)}` : ''}`,
|
||||
bold: true,
|
||||
}),
|
||||
],
|
||||
spacing: { before: 240 },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
for (const block of parseMarkdownBlocks(turn.message)) {
|
||||
switch (block.type) {
|
||||
case 'heading': {
|
||||
const level =
|
||||
block.level === 1
|
||||
? HeadingLevel.HEADING_1
|
||||
: block.level === 2
|
||||
? HeadingLevel.HEADING_2
|
||||
: HeadingLevel.HEADING_3;
|
||||
children.push(new Paragraph({ text: block.text, heading: level }));
|
||||
break;
|
||||
}
|
||||
case 'paragraph':
|
||||
children.push(new Paragraph({ text: block.text }));
|
||||
break;
|
||||
case 'code':
|
||||
children.push(
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: block.text, font: 'Courier New', size: 18 })],
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case 'list':
|
||||
block.items.forEach((item, idx) => {
|
||||
children.push(
|
||||
new Paragraph({
|
||||
text: block.ordered ? `${idx + 1}. ${item}` : `• ${item}`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
break;
|
||||
case 'table':
|
||||
children.push(
|
||||
new Table({
|
||||
width: { size: 100, type: WidthType.PERCENTAGE },
|
||||
rows: [
|
||||
new TableRow({
|
||||
children: block.headers.map(
|
||||
(h) =>
|
||||
new TableCell({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: h, bold: true })],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
),
|
||||
}),
|
||||
...block.rows.map(
|
||||
(row) =>
|
||||
new TableRow({
|
||||
children: block.headers.map(
|
||||
(_, col) =>
|
||||
new TableCell({
|
||||
children: [new Paragraph({ text: row[col] ?? '' })],
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
],
|
||||
}),
|
||||
);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (turn.citations?.length) {
|
||||
children.push(
|
||||
new Paragraph({
|
||||
text: 'Sources',
|
||||
heading: HeadingLevel.HEADING_3,
|
||||
}),
|
||||
);
|
||||
turn.citations
|
||||
.slice()
|
||||
.sort((a, b) => a.index - b.index)
|
||||
.forEach((c) => {
|
||||
children.push(
|
||||
new Paragraph({
|
||||
text: `[${c.index}] ${c.title}${c.url ? ` — ${c.url}` : ''}`,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
headers: {
|
||||
default: new Header({
|
||||
children: [
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: `${title} · ${exportedAt}`,
|
||||
size: 16,
|
||||
color: '888888',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
children,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const blob = await Packer.toBlob(doc);
|
||||
downloadBlob(blob, filename);
|
||||
}
|
||||
|
||||
/** Decide CSV/XLSX matrix strategy — exported for unit tests. */
|
||||
export function selectTabularStrategy(
|
||||
scope: ExportScope,
|
||||
messageMarkdown: string,
|
||||
): 'tables' | 'turns' {
|
||||
if (scope === 'conversation') return 'turns';
|
||||
return extractMarkdownTables(messageMarkdown).length > 0 ? 'tables' : 'turns';
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
export function sanitizeFilenamePart(value: string): string {
|
||||
return value
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 80) || 'conversation';
|
||||
}
|
||||
|
||||
export function buildExportFilename(
|
||||
conversationTitle: string,
|
||||
extension: string,
|
||||
date = new Date(),
|
||||
): string {
|
||||
const day = date.toISOString().slice(0, 10);
|
||||
const base = sanitizeFilenamePart(conversationTitle || 'conversation');
|
||||
const ext = extension.replace(/^\./, '');
|
||||
return `${base}-${day}.${ext}`;
|
||||
}
|
||||
|
||||
/** Strip markdown to plain text for TXT / tabular message cells. */
|
||||
export function stripMarkdown(markdown: string): string {
|
||||
return markdown
|
||||
.replace(/```[\s\S]*?```/g, (block) =>
|
||||
block.replace(/```\w*\n?/, '').replace(/```$/, ''),
|
||||
)
|
||||
.replace(/!\[[^\]]*]\([^)]+\)/g, '')
|
||||
.replace(/\[([^\]]+)]\([^)]+\)/g, '$1')
|
||||
.replace(/^#{1,6}\s+/gm, '')
|
||||
.replace(/^\s*[-*+]\s+/gm, '')
|
||||
.replace(/^\s*\d+\.\s+/gm, '')
|
||||
.replace(/[*_~`]+/g, '')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
export type MdBlock =
|
||||
| { type: 'heading'; level: number; text: string }
|
||||
| { type: 'paragraph'; text: string }
|
||||
| { type: 'code'; language: string; text: string }
|
||||
| { type: 'list'; ordered: boolean; items: string[] }
|
||||
| { type: 'table'; headers: string[]; rows: string[][] };
|
||||
|
||||
/** Lightweight markdown → block AST for PDF/DOCX exporters. */
|
||||
export function parseMarkdownBlocks(markdown: string): MdBlock[] {
|
||||
const lines = markdown.replace(/\r\n/g, '\n').split('\n');
|
||||
const blocks: MdBlock[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < lines.length) {
|
||||
const line = lines[i];
|
||||
|
||||
if (/^```/.test(line)) {
|
||||
const language = line.replace(/^```/, '').trim();
|
||||
const body: string[] = [];
|
||||
i += 1;
|
||||
while (i < lines.length && !/^```/.test(lines[i])) {
|
||||
body.push(lines[i]);
|
||||
i += 1;
|
||||
}
|
||||
blocks.push({ type: 'code', language, text: body.join('\n') });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
|
||||
if (heading) {
|
||||
blocks.push({
|
||||
type: 'heading',
|
||||
level: heading[1].length,
|
||||
text: heading[2].trim(),
|
||||
});
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^\|.+\|$/.test(line.trim()) && i + 1 < lines.length && /^\|?\s*[-:| ]+\|?$/.test(lines[i + 1].trim())) {
|
||||
const headers = splitTableRow(line);
|
||||
i += 2;
|
||||
const rows: string[][] = [];
|
||||
while (i < lines.length && /^\|.+\|$/.test(lines[i].trim())) {
|
||||
rows.push(splitTableRow(lines[i]));
|
||||
i += 1;
|
||||
}
|
||||
blocks.push({ type: 'table', headers, rows });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^\s*[-*+]\s+/.test(line) || /^\s*\d+\.\s+/.test(line)) {
|
||||
const ordered = /^\s*\d+\.\s+/.test(line);
|
||||
const items: string[] = [];
|
||||
while (
|
||||
i < lines.length &&
|
||||
(ordered ? /^\s*\d+\.\s+/.test(lines[i]) : /^\s*[-*+]\s+/.test(lines[i]))
|
||||
) {
|
||||
items.push(lines[i].replace(/^\s*([-*+]|\d+\.)\s+/, '').trim());
|
||||
i += 1;
|
||||
}
|
||||
blocks.push({ type: 'list', ordered, items });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!line.trim()) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const para: string[] = [];
|
||||
while (i < lines.length && lines[i].trim() && !/^```/.test(lines[i]) && !/^(#{1,6})\s+/.test(lines[i])) {
|
||||
if (/^\|.+\|$/.test(lines[i].trim())) break;
|
||||
if (/^\s*[-*+]\s+/.test(lines[i]) || /^\s*\d+\.\s+/.test(lines[i])) break;
|
||||
para.push(lines[i]);
|
||||
i += 1;
|
||||
}
|
||||
blocks.push({ type: 'paragraph', text: para.join(' ').trim() });
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function splitTableRow(line: string): string[] {
|
||||
return line
|
||||
.trim()
|
||||
.replace(/^\|/, '')
|
||||
.replace(/\|$/, '')
|
||||
.split('|')
|
||||
.map((cell) => cell.trim());
|
||||
}
|
||||
|
||||
/** Extract markdown tables from a single message (for CSV/XLSX tabular rules). */
|
||||
export function extractMarkdownTables(markdown: string): { headers: string[]; rows: string[][] }[] {
|
||||
return parseMarkdownBlocks(markdown)
|
||||
.filter((b): b is Extract<MdBlock, { type: 'table' }> => b.type === 'table')
|
||||
.map(({ headers, rows }) => ({ headers, rows }));
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { upsertPromptFeedback, clearPromptFeedback } from './promptFeedback';
|
||||
import { axiosInstance } from '../../axiosApi';
|
||||
|
||||
jest.mock('../../axiosApi', () => ({
|
||||
axiosInstance: {
|
||||
post: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('promptFeedback optimistic helpers', () => {
|
||||
const post = axiosInstance.post as jest.Mock;
|
||||
const del = axiosInstance.delete as jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
post.mockReset();
|
||||
del.mockReset();
|
||||
});
|
||||
|
||||
it('posts upsert payload', async () => {
|
||||
post.mockResolvedValue({ data: { rating: 'up' } });
|
||||
await upsertPromptFeedback(42, { rating: 'up' });
|
||||
expect(post).toHaveBeenCalledWith('prompt_feedback', {
|
||||
prompt_id: 42,
|
||||
rating: 'up',
|
||||
reason: undefined,
|
||||
comment: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes vote by prompt_id', async () => {
|
||||
del.mockResolvedValue({});
|
||||
await clearPromptFeedback(42);
|
||||
expect(del).toHaveBeenCalledWith('prompt_feedback', {
|
||||
params: { prompt_id: 42 },
|
||||
});
|
||||
});
|
||||
|
||||
it('surfaces request failures for rollback callers', async () => {
|
||||
post.mockRejectedValue(new Error('network'));
|
||||
await expect(upsertPromptFeedback(1, { rating: 'down' })).rejects.toThrow(
|
||||
'network',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { axiosInstance } from '../../axiosApi';
|
||||
|
||||
export type PromptRating = 'up' | 'down';
|
||||
|
||||
export type PromptFeedbackPayload = {
|
||||
rating: PromptRating;
|
||||
reason?: string | null;
|
||||
comment?: string | null;
|
||||
};
|
||||
|
||||
export type PromptFeedbackResponse = PromptFeedbackPayload & {
|
||||
id?: number;
|
||||
prompt_id?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Upsert thumbs rating for an assistant prompt (chat_backend#67).
|
||||
*/
|
||||
export async function upsertPromptFeedback(
|
||||
promptId: number,
|
||||
payload: PromptFeedbackPayload,
|
||||
): Promise<PromptFeedbackResponse> {
|
||||
const { data } = await axiosInstance.post<PromptFeedbackResponse>('prompt_feedback', {
|
||||
prompt_id: promptId,
|
||||
rating: payload.rating,
|
||||
reason: payload.reason ?? undefined,
|
||||
comment: payload.comment ?? undefined,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear a vote for an assistant prompt.
|
||||
*/
|
||||
export async function clearPromptFeedback(promptId: number): Promise<void> {
|
||||
await axiosInstance.delete('prompt_feedback', {
|
||||
params: { prompt_id: promptId },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
type ToastListener = (message: string, severity: 'error' | 'success' | 'info') => void;
|
||||
|
||||
const listeners = new Set<ToastListener>();
|
||||
|
||||
export function subscribeToast(listener: ToastListener): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function showToast(
|
||||
message: string,
|
||||
severity: 'error' | 'success' | 'info' = 'info',
|
||||
): void {
|
||||
listeners.forEach((listener) => listener(message, severity));
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
parseCitationsData,
|
||||
parseVersionedFrame,
|
||||
} from './wsFrames';
|
||||
|
||||
describe('wsFrames', () => {
|
||||
it('parses a citations frame', () => {
|
||||
const raw = JSON.stringify({
|
||||
v: 1,
|
||||
type: 'citations',
|
||||
data: [
|
||||
{
|
||||
index: 1,
|
||||
title: 'Example',
|
||||
url: 'https://example.com',
|
||||
published_at: '2026-07-03',
|
||||
},
|
||||
],
|
||||
});
|
||||
const frame = parseVersionedFrame(raw);
|
||||
expect(frame).toEqual({
|
||||
v: 1,
|
||||
type: 'citations',
|
||||
data: [
|
||||
{
|
||||
index: 1,
|
||||
title: 'Example',
|
||||
url: 'https://example.com',
|
||||
published_at: '2026-07-03',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(parseCitationsData(frame!.data)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('ignores unknown types without throwing', () => {
|
||||
const frame = parseVersionedFrame(
|
||||
JSON.stringify({ v: 1, type: 'status', data: { stage: 'search' } }),
|
||||
);
|
||||
expect(frame?.type).toBe('status');
|
||||
});
|
||||
|
||||
it('returns null for sentinels and plain text', () => {
|
||||
expect(parseVersionedFrame('END_OF_THE_STREAM_ENDER_GAME_42')).toBeNull();
|
||||
expect(parseVersionedFrame('hello world')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns empty citations for bad data', () => {
|
||||
expect(parseCitationsData(null)).toEqual([]);
|
||||
expect(parseCitationsData('nope')).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Versioned WebSocket frame envelopes shared by citations (#98) and status (#96).
|
||||
* Shape: { v: 1, type: string, data: unknown }
|
||||
*/
|
||||
|
||||
export type VersionedFrame = {
|
||||
v: number;
|
||||
type: string;
|
||||
data: unknown;
|
||||
};
|
||||
|
||||
export type Citation = {
|
||||
index: number;
|
||||
title: string;
|
||||
url: string;
|
||||
published_at?: string | null;
|
||||
};
|
||||
|
||||
export function parseVersionedFrame(raw: string): VersionedFrame | null {
|
||||
const trimmed = raw?.trim?.() ?? '';
|
||||
if (!trimmed.startsWith('{')) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (
|
||||
parsed &&
|
||||
typeof parsed === 'object' &&
|
||||
typeof parsed.v === 'number' &&
|
||||
typeof parsed.type === 'string'
|
||||
) {
|
||||
return {
|
||||
v: parsed.v,
|
||||
type: parsed.type,
|
||||
data: parsed.data,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// not JSON — fall through to sentinel / stream text handling
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseCitationsData(data: unknown): Citation[] {
|
||||
if (!Array.isArray(data)) return [];
|
||||
return data
|
||||
.filter(
|
||||
(item): item is Record<string, unknown> =>
|
||||
!!item && typeof item === 'object' && typeof (item as { index?: unknown }).index === 'number',
|
||||
)
|
||||
.map((item) => ({
|
||||
index: item.index as number,
|
||||
title: typeof item.title === 'string' ? item.title : `Source ${item.index}`,
|
||||
url: typeof item.url === 'string' ? item.url : '',
|
||||
published_at:
|
||||
typeof item.published_at === 'string' ? item.published_at : null,
|
||||
}));
|
||||
}
|
||||
Reference in New Issue
Block a user