extracted chat component to widgets

This commit is contained in:
2026-02-17 19:52:41 +00:00
parent 21213c281d
commit 74e98e95e1
37 changed files with 44 additions and 327 deletions
@@ -0,0 +1,94 @@
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import type { ChatMessage } from './types';
import { ToolActivity } from './ToolActivity';
import { QuestionActivity } from './QuestionActivity';
type MessageBubbleProps = {
message: ChatMessage;
onAnswer?: (text: string) => void;
};
export const MessageBubble = ({ message, onAnswer }: MessageBubbleProps) => {
const text = formatText(message.text);
switch (message.role) {
case 'user':
return (
<div className="flex justify-end">
<div className="max-w-[80%] rounded-2xl rounded-tr-sm bg-duck-yellow/10 border border-duck-yellow/20 px-4 py-2.5 text-sm text-duck-dark">
{message.images?.map((img, i) => (
<img key={i} src={img.dataUrl} alt={img.filename} className="max-w-full max-h-64 rounded-lg mb-2" />
))}
<div className="whitespace-pre-wrap">{text}</div>
</div>
</div>
);
case 'assistant':
if (!text) return null;
return (
<div className="flex justify-start">
<div className="max-w-[85%] rounded-2xl rounded-tl-sm bg-white/80 border border-duck-dark/10 px-4 py-2.5 text-sm text-duck-dark prose prose-sm max-w-none prose-pre:bg-gray-900 prose-pre:text-green-400 prose-code:text-duck-teal prose-code:before:content-none prose-code:after:content-none">
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
{text}
</ReactMarkdown>
</div>
</div>
);
case 'tool':
if (message.toolName === 'question' && onAnswer) {
return <QuestionActivity message={message} onAnswer={onAnswer} />;
}
return <ToolActivity message={message} />;
case 'result':
return (
<div className="flex justify-center py-1">
<span className="text-xs text-duck-dark/40">
Done · ${message.costUsd.toFixed(3)} · {(message.durationMs / 1000).toFixed(1)}s · {message.numTurns} turn
{message.numTurns !== 1 ? 's' : ''}
{message.isError ? ' (with errors)' : ''}
</span>
</div>
);
case 'error':
return (
<div className="flex justify-start">
<div className="max-w-[80%] rounded-2xl bg-red-50 border border-red-200 px-4 py-2.5 text-sm text-red-700">
{text}
</div>
</div>
);
}
};
function formatText(value: unknown): string {
if (typeof value === 'string') return value;
if (value == null) return '';
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
type StreamingBubbleProps = {
text: string;
};
export const StreamingBubble = ({ text }: StreamingBubbleProps) => {
if (!text) return null;
return (
<div className="flex justify-start">
<div className="max-w-[85%] rounded-2xl rounded-tl-sm bg-white/80 border border-duck-dark/10 px-4 py-2.5 text-sm text-duck-dark prose prose-sm max-w-none prose-pre:bg-gray-900 prose-pre:text-green-400 prose-code:text-duck-teal prose-code:before:content-none prose-code:after:content-none">
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeRaw]}>
{text}
</ReactMarkdown>
<span className="inline-block w-2 h-4 bg-duck-teal/60 animate-pulse ml-0.5 align-middle" />
</div>
</div>
);
};
@@ -0,0 +1,52 @@
import type { RefObject } from 'react';
import { ArrowDown } from 'lucide-react';
import type { ChatMessage } from './types';
import { MessageBubble, StreamingBubble } from './MessageBubble';
type MessageListProps = {
messages: ChatMessage[];
streamingText: string;
isGenerating: boolean;
showJumpToBottom: boolean;
onJumpToBottom: () => void;
onQuestionAnswer?: (text: string) => void;
scrollViewportRef: RefObject<HTMLDivElement | null>;
bottomRef: RefObject<HTMLDivElement | null>;
};
export const MessageList = ({
messages,
streamingText,
isGenerating,
showJumpToBottom,
onJumpToBottom,
onQuestionAnswer,
scrollViewportRef,
bottomRef,
}: MessageListProps) => (
<div className="flex-1 min-h-0 relative">
<div ref={scrollViewportRef} className="h-full overflow-y-auto">
<div className="p-4 space-y-3">
{messages.length === 0 && !isGenerating && (
<div className="flex items-center justify-center h-full min-h-[200px] text-duck-dark/30 text-sm">
Send a message to start
</div>
)}
{messages.map((msg, i) => (
<MessageBubble key={i} message={msg} onAnswer={onQuestionAnswer} />
))}
{isGenerating && <StreamingBubble text={streamingText} />}
<div ref={bottomRef} />
</div>
</div>
{showJumpToBottom && (
<button
onClick={onJumpToBottom}
className="absolute bottom-2 left-1/2 -translate-x-1/2 bg-duck-teal text-white rounded-full p-1.5 shadow-lg hover:bg-duck-teal/90 transition-colors cursor-pointer"
>
<ArrowDown className="h-4 w-4" />
</button>
)}
</div>
);
@@ -0,0 +1,164 @@
import { useState } from 'react';
import { MessageCircleQuestion, Check } from 'lucide-react';
import type { ChatMessage } from './types';
type ToolMessage = Extract<ChatMessage, { role: 'tool' }>;
type QuestionOption = {
label: string;
description: string;
};
type Question = {
question: string;
header: string;
multiple: boolean;
options: QuestionOption[];
};
type QuestionActivityProps = {
message: ToolMessage;
onAnswer: (text: string) => void;
};
export const QuestionActivity = ({ message, onAnswer }: QuestionActivityProps) => {
const [selectedOptions, setSelectedOptions] = useState<Set<string>>(new Set());
const [otherText, setOtherText] = useState('');
const [answered, setAnswered] = useState(false);
const [answeredText, setAnsweredText] = useState('');
const input = message.toolInput as { questions?: Question[] };
const questions = input.questions;
if (!questions || questions.length === 0) return null;
const pending = message.output === undefined;
const handleSelect = (question: Question, label: string) => {
if (answered || !pending) return;
if (question.multiple) {
setSelectedOptions((prev) => {
const next = new Set(prev);
if (next.has(label)) next.delete(label);
else next.add(label);
return next;
});
} else {
const text = label;
setAnswered(true);
setAnsweredText(text);
onAnswer(text);
}
};
const handleSubmitMultiple = () => {
if (selectedOptions.size === 0 || answered || !pending) return;
const text = Array.from(selectedOptions).join(', ');
setAnswered(true);
setAnsweredText(text);
onAnswer(text);
};
const handleSubmitOther = () => {
const text = otherText.trim();
if (!text || answered || !pending) return;
setAnswered(true);
setAnsweredText(text);
onAnswer(text);
};
const isDisabled = answered || !pending;
return (
<div className="my-1 space-y-3">
{questions.map((q, qi) => (
<div key={qi} className="rounded-xl border border-duck-teal/20 bg-white/90 overflow-hidden">
<div className="flex items-center gap-2 px-4 py-2.5 bg-duck-teal/5 border-b border-duck-teal/10">
<MessageCircleQuestion className="h-4 w-4 text-duck-teal shrink-0" />
<span className="text-xs font-medium text-duck-teal uppercase tracking-wider">{q.header}</span>
</div>
<div className="px-4 py-3 space-y-3">
<p className="text-sm text-duck-dark font-medium">{q.question}</p>
<div className="space-y-1.5">
{q.options.map((opt) => {
const isSelected = answered
? answeredText === opt.label || answeredText.split(', ').includes(opt.label)
: selectedOptions.has(opt.label);
return (
<button
key={opt.label}
onClick={() => handleSelect(q, opt.label)}
disabled={isDisabled}
className={`w-full text-left px-3 py-2 rounded-lg border text-sm transition-colors ${
isSelected
? 'border-duck-teal bg-duck-teal/10 text-duck-dark'
: isDisabled
? 'border-duck-dark/10 bg-duck-dark/5 text-duck-dark/40 cursor-not-allowed'
: 'border-duck-dark/15 hover:border-duck-teal/40 hover:bg-duck-teal/5 text-duck-dark cursor-pointer'
}`}
>
<div className="flex items-center gap-2">
{isSelected && <Check className="h-3.5 w-3.5 text-duck-teal shrink-0" />}
<div>
<span className="font-medium">{opt.label}</span>
{opt.description && <span className="text-duck-dark/50 ml-1.5">&mdash; {opt.description}</span>}
</div>
</div>
</button>
);
})}
</div>
{/* "Other" free-text option */}
{!isDisabled && (
<div className="flex gap-2">
<input
type="text"
value={otherText}
onChange={(ev) => setOtherText(ev.target.value)}
onKeyDown={(ev) => {
if (ev.key === 'Enter') {
ev.preventDefault();
handleSubmitOther();
}
}}
placeholder="Other..."
className="flex-1 px-3 py-1.5 rounded-lg border border-duck-dark/15 text-sm text-duck-dark placeholder:text-duck-dark/30 focus:outline-none focus:border-duck-teal/40"
/>
<button
onClick={handleSubmitOther}
disabled={!otherText.trim()}
className="px-3 py-1.5 rounded-lg bg-duck-teal text-white text-sm font-medium disabled:opacity-40 disabled:cursor-not-allowed hover:bg-duck-teal/90 transition-colors cursor-pointer"
>
Send
</button>
</div>
)}
{/* Submit button for multi-select */}
{q.multiple && !isDisabled && (
<button
onClick={handleSubmitMultiple}
disabled={selectedOptions.size === 0}
className="px-4 py-1.5 rounded-lg bg-duck-teal text-white text-sm font-medium disabled:opacity-40 disabled:cursor-not-allowed hover:bg-duck-teal/90 transition-colors cursor-pointer"
>
Submit ({selectedOptions.size} selected)
</button>
)}
{/* Answered indicator */}
{isDisabled && answeredText && (
<div className="flex items-center gap-1.5 text-xs text-duck-teal">
<Check className="h-3 w-3" />
<span>Answered: {answeredText}</span>
</div>
)}
</div>
</div>
))}
</div>
);
};
@@ -0,0 +1,138 @@
import { useState } from 'react';
import { FileText, Terminal, Pencil, Search, Globe, Wrench, ChevronRight } from 'lucide-react';
import type { ChatMessage } from './types';
type ToolMessage = Extract<ChatMessage, { role: 'tool' }>;
type ToolActivityProps = {
message: ToolMessage;
};
const toolIcons: Record<string, typeof FileText> = {
Read: FileText,
Edit: Pencil,
Write: Pencil,
Bash: Terminal,
Grep: Search,
Glob: Search,
WebFetch: Globe,
WebSearch: Globe,
};
function getToolSummary(toolName: string, toolInput: Record<string, unknown>): string {
switch (toolName) {
case 'Read':
case 'Edit':
case 'Write':
return (toolInput.file_path as string) ?? '';
case 'Bash':
return truncate((toolInput.command as string) ?? '', 80);
case 'Grep':
case 'Glob':
return (toolInput.pattern as string) ?? '';
case 'WebFetch':
return (toolInput.url as string) ?? '';
case 'WebSearch':
return (toolInput.query as string) ?? '';
default:
return (
Object.values(toolInput)
.find((v) => typeof v === 'string')
?.toString() ?? ''
);
}
}
function truncate(str: string, max: number): string {
return str.length > max ? str.slice(0, max) + '...' : str;
}
export const ToolActivity = ({ message }: ToolActivityProps) => {
const [open, setOpen] = useState(false);
const Icon = toolIcons[message.toolName] ?? Wrench;
const summary = getToolSummary(message.toolName, message.toolInput);
const pending = message.output === undefined;
const isError = message.isError === true;
return (
<div className="my-1">
<button
onClick={() => setOpen(!open)}
className="flex items-center gap-2 w-full text-left px-3 py-1.5 rounded-md hover:bg-duck-dark/5 transition-colors cursor-pointer text-sm"
>
<ChevronRight className={`h-3 w-3 shrink-0 transition-transform ${open ? 'rotate-90' : ''}`} />
<Icon className="h-4 w-4 shrink-0 text-duck-teal" />
<span className="font-medium text-duck-dark/80">{message.toolName}</span>
<span className="text-duck-dark/50 truncate flex-1 font-mono text-xs">{summary}</span>
<span className="shrink-0">
{pending && <span className="inline-block h-2 w-2 rounded-full bg-amber-400 animate-pulse" />}
{!pending && !isError && <span className="text-green-600 text-xs">done</span>}
{!pending && isError && <span className="text-red-600 text-xs">error</span>}
</span>
</button>
{open && (
<div className="ml-7 mt-1 space-y-2 text-xs">
<div className="rounded-md bg-duck-dark/5 p-2 overflow-x-auto">
<div className="text-duck-dark/50 text-[10px] uppercase tracking-wider mb-1">Input</div>
{message.toolName === 'Bash' ? (
<pre className="bg-gray-900 text-green-400 p-2 rounded font-mono whitespace-pre-wrap break-all">
{(message.toolInput.command as string) ?? JSON.stringify(message.toolInput, null, 2)}
</pre>
) : (
<pre className="font-mono whitespace-pre-wrap break-all text-duck-dark/70">
{Object.entries(message.toolInput)
.map(([k, v]) => `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`)
.join('\n')}
</pre>
)}
</div>
{message.output !== undefined && (
<div className="rounded-md bg-duck-dark/5 p-2 overflow-x-auto">
<div className="text-duck-dark/50 text-[10px] uppercase tracking-wider mb-1">Output</div>
<ToolOutput toolName={message.toolName} output={message.output} isError={isError} />
</div>
)}
</div>
)}
</div>
);
};
type ToolOutputProps = {
toolName: string;
output: string;
isError: boolean;
};
const ToolOutput = ({ toolName, output, isError }: ToolOutputProps) => {
const [expanded, setExpanded] = useState(false);
const maxLines = 20;
const lines = output.split('\n');
const needsTruncation = lines.length > maxLines;
const displayText = expanded ? output : lines.slice(0, maxLines).join('\n');
const isBash = toolName === 'Bash';
return (
<>
<pre
className={`font-mono whitespace-pre-wrap break-all p-2 rounded ${
isBash ? 'bg-gray-900 text-green-400' : isError ? 'bg-red-50 text-red-700' : 'text-duck-dark/70'
}`}
>
{displayText}
</pre>
{needsTruncation && (
<button
onClick={() => setExpanded(!expanded)}
className="text-duck-teal hover:underline text-[11px] mt-1 cursor-pointer"
>
{expanded ? 'Show less' : `Show more (${lines.length - maxLines} more lines)`}
</button>
)}
</>
);
};
+5
View File
@@ -0,0 +1,5 @@
export { MessageList } from './MessageList';
export { MessageBubble, StreamingBubble } from './MessageBubble';
export { ToolActivity } from './ToolActivity';
export { QuestionActivity } from './QuestionActivity';
export type { ChatMessage, SessionEntry, ServerMessage, TaskInfo } from './types';
+38
View File
@@ -0,0 +1,38 @@
export type SessionEntry = {
id: string;
title: string;
createdAt: number;
provider: 'claude' | 'opencode';
model?: string | null;
};
export type ChatMessage =
| { role: 'user'; text: string; images?: { filename: string; dataUrl: string }[] }
| { role: 'assistant'; text: string }
| {
role: 'tool';
toolName: string;
toolInput: Record<string, unknown>;
toolUseId: string;
output?: string;
isError?: boolean;
}
| { role: 'result'; costUsd: number; durationMs: number; numTurns: number; isError: boolean }
| { role: 'error'; text: string };
export type TaskInfo = {
taskName: string;
taskDirName: string;
entryName: string;
entryType: 'file' | 'directory';
};
export type ServerMessage =
| { type: 'session:init'; sessionId: string; model: string }
| { type: 'assistant:text'; text: string }
| { type: 'assistant:partial'; text: string }
| { type: 'tool:use'; toolName: string; toolInput: Record<string, unknown>; toolUseId: string }
| { type: 'tool:result'; toolUseId: string; output: string; isError: boolean }
| { type: 'result'; costUsd: number; durationMs: number; numTurns: number; isError: boolean }
| { type: 'error'; message: string }
| { type: 'stopped' };