feat: improved chat ux (#103)

This commit is contained in:
Carlos Florêncio
2026-01-26 23:46:09 +00:00
committed by GitHub
parent 4941795532
commit ec77511f26
14 changed files with 1245 additions and 352 deletions
+576
View File
@@ -0,0 +1,576 @@
'use client';
import type { Message } from '@/lib/types/http';
import { MessageRenderer } from '@/components/task/chat/message-renderer';
const dummyMessages: Message[] = [
// Task description
{
id: 'task-description',
session_id: 'demo',
task_id: 'demo-task',
content: '[TASK DESCRIPTION - AMBER BANNER] Implement a new feature to handle user authentication with OAuth 2.0',
author_type: 'user',
type: 'message',
created_at: '2024-01-20T10:00:00Z',
},
// User message - short
{
id: 'user-1',
session_id: 'demo',
task_id: 'demo-task',
content: '[USER MESSAGE - SHORT] Can you help me with this?',
author_type: 'user',
type: 'message',
created_at: '2024-01-20T10:01:00Z',
},
// User message - long
{
id: 'user-2',
session_id: 'demo',
task_id: 'demo-task',
content: '[USER MESSAGE - LONG] I need to implement a complex feature that involves multiple components. The requirements are:\n1. User authentication\n2. Role-based access control\n3. Session management\n4. Token refresh mechanism\n\nCan you help me design this system?',
author_type: 'user',
type: 'message',
created_at: '2024-01-20T10:02:00Z',
},
// Agent message - plain text
{
id: 'agent-1',
session_id: 'demo',
task_id: 'demo-task',
content: '[AGENT MESSAGE - PLAIN TEXT] This is a simple paragraph with no markdown formatting. Just plain text content.',
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:03:00Z',
},
// Agent message - with markdown
{
id: 'agent-2',
session_id: 'demo',
task_id: 'demo-task',
content: `**[MARKDOWN DEMO]** Here's a message showing all markdown elements:
## Heading 2 (h2 element)
This is a **paragraph (p element)** with some **bold text (strong element)** to test styling.
### Heading 3 (h3 element)
**Ordered List (ol element):**
1. First item (li element in ol)
2. Second item with **bold text**
3. Third item with inline code: \`const example = true\`
4. Fourth item (li element)
**Unordered List (ul element):**
- Bullet point one (li element in ul)
- Bullet point two
- Bullet point with \`inline code\` (code element)
- Another bullet point
**Inline code examples (code element, inline):**
- Variable: \`const token = jwt.sign(payload)\`
- Function call: \`getUserData(userId)\`
- Path: \`/src/auth/config.ts\`
**Code block example (code element, block):**
\`\`\`typescript
// This is a code block (pre > code)
interface AuthConfig {
clientId: string;
clientSecret: string;
redirectUri: string;
}
function authenticate(config: AuthConfig) {
return jwt.sign(config);
}
\`\`\`
**Another code block (JavaScript):**
\`\`\`javascript
// Testing syntax highlighting
const data = { name: "test", value: 123 };
console.log(data);
\`\`\``,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:04:00Z',
},
// Thinking message
{
id: 'thinking-1',
session_id: 'demo',
task_id: 'demo-task',
type: 'thinking',
content: '',
author_type: 'agent',
created_at: '2024-01-20T10:05:00Z',
metadata: {
thinking: '[THINKING MESSAGE] This shows the agent\'s internal reasoning process. I need to check the current authentication implementation before suggesting changes. Let me search for existing auth files and understand the current architecture.',
},
},
// Tool call - Read (complete)
{
id: 'tool-1',
session_id: 'demo',
task_id: 'demo-task',
type: 'tool_call',
content: 'Read file',
author_type: 'agent',
created_at: '2024-01-20T10:06:00Z',
metadata: {
tool_call_id: 'tool-1',
tool_name: 'Read',
title: '[TOOL - READ - COMPLETE ✓] Read src/auth/config.ts',
status: 'complete',
args: {
file_path: '/Users/demo/project/src/auth/config.ts',
line_count: 50,
},
result: 'File content loaded successfully (50 lines)',
},
},
// Tool call - Bash (running)
{
id: 'tool-2',
session_id: 'demo',
task_id: 'demo-task',
type: 'tool_call',
content: 'Run command',
author_type: 'agent',
created_at: '2024-01-20T10:07:00Z',
metadata: {
tool_call_id: 'tool-2',
tool_name: 'Bash',
title: '[TOOL - BASH - RUNNING ⏳] npm test',
status: 'running',
args: {
command: 'npm test -- --coverage',
description: 'Run tests with coverage',
timeout: 30000,
},
},
},
// Tool call - Edit (error)
{
id: 'tool-3',
session_id: 'demo',
task_id: 'demo-task',
type: 'tool_call',
content: 'Edit file',
author_type: 'agent',
created_at: '2024-01-20T10:08:00Z',
metadata: {
tool_call_id: 'tool-3',
tool_name: 'Edit',
title: '[TOOL - EDIT - ERROR ✗] Edit src/components/Login.tsx',
status: 'error',
args: {
file_path: '/Users/demo/project/src/components/Login.tsx',
old_string: 'const handleLogin = () => {',
new_string: 'const handleLogin = async () => {',
},
result: 'Error: old_string not found in file. Make sure the old_string exactly matches the content in the file.',
},
},
// Tool call - Edit with complex metadata (complete)
{
id: 'tool-3b',
session_id: 'demo',
task_id: 'demo-task',
type: 'tool_call',
content: 'Auggie Read `drizzle.config.ts`',
author_type: 'agent',
created_at: '2024-01-20T10:08:30Z',
metadata: {
tool_call_id: 'toolu_vrtx_01W75yrLi1WLgLCz8P3D8jjh',
tool_name: 'edit',
title: 'Edit drizzle.config.ts',
status: 'complete',
args: {
kind: 'edit',
locations: [
{
path: '/Users/cfl/.kandev/worktrees/1_c28de20d/drizzle.config.ts',
},
],
path: '/Users/cfl/.kandev/worktrees/1_c28de20d/drizzle.config.ts',
raw_input: {
command: 'str_replace',
instruction_reminder: 'ALWAYS BREAK DOWN EDITS INTO SMALLER CHUNKS OF AT MOST 150 LINES EACH.',
new_str_1: 'export default defineConfig({\n schema: "./src/main/lib/db/schema/index.ts",\n dialect: "sqlite",\n})',
old_str_1: 'export default defineConfig({\n schema: "./src/main/lib/db/schema/index.ts",\n out: "./drizzle",\n dialect: "sqlite",\n})',
old_str_end_line_number_1: 7,
old_str_start_line_number_1: 3,
path: 'drizzle.config.ts',
},
},
},
},
// Tool call - Search (pending, with permission)
{
id: 'tool-4',
session_id: 'demo',
task_id: 'demo-task',
type: 'tool_call',
content: 'Search files',
author_type: 'agent',
created_at: '2024-01-20T10:09:00Z',
metadata: {
tool_call_id: 'tool-4',
tool_name: 'Grep',
title: '[TOOL - GREP - PENDING 🔒] Search for "authentication" in codebase',
status: 'pending',
args: {
pattern: 'authentication',
path: '/Users/demo/project/src',
output_mode: 'files_with_matches',
},
},
},
// Permission request (for tool-4)
{
id: 'permission-1',
session_id: 'demo',
task_id: 'demo-task',
type: 'permission_request',
content: '[PERMISSION REQUEST] Approve/Reject action',
author_type: 'user',
created_at: '2024-01-20T10:09:01Z',
metadata: {
pending_id: 'perm-1',
tool_call_id: 'tool-4',
action_type: 'file_search',
action_details: {
path: '/Users/demo/project/src',
command: 'grep -r "authentication"',
},
options: [
{ option_id: 'allow-1', name: 'Allow Once', kind: 'allow_once' },
{ option_id: 'allow-2', name: 'Allow Always', kind: 'allow_always' },
{ option_id: 'reject-1', name: 'Reject', kind: 'reject_once' },
],
status: 'pending',
},
},
// Status message - simple (separator style)
{
id: 'status-0',
session_id: 'demo',
task_id: 'demo-task',
type: 'status',
content: 'Agent initialized',
author_type: 'agent',
created_at: '2024-01-20T10:09:30Z',
},
// Status message - success
{
id: 'status-1',
session_id: 'demo',
task_id: 'demo-task',
type: 'status',
content: '[STATUS MESSAGE - SUCCESS ✓] Tests passed successfully! All 42 tests completed.',
author_type: 'agent',
created_at: '2024-01-20T10:10:00Z',
metadata: {
level: 'success',
},
},
// Status message - error
{
id: 'status-2',
session_id: 'demo',
task_id: 'demo-task',
type: 'error',
content: '[STATUS MESSAGE - ERROR ✗] Build failed: TypeScript compilation error in auth.ts:45',
author_type: 'agent',
created_at: '2024-01-20T10:11:00Z',
metadata: {
level: 'error',
},
},
// Todo message
{
id: 'todo-1',
session_id: 'demo',
task_id: 'demo-task',
type: 'todo',
content: '[TODO MESSAGE] Task list',
author_type: 'agent',
created_at: '2024-01-20T10:12:00Z',
metadata: {
todos: [
{ id: '1', text: '[TODO ITEM - COMPLETED] Set up OAuth provider', completed: true },
{ id: '2', text: '[TODO ITEM - PENDING] Implement token validation middleware', completed: false },
{ id: '3', text: '[TODO ITEM - PENDING] Add refresh token endpoint', completed: false },
{ id: '4', text: '[TODO ITEM - PENDING] Write integration tests', completed: false },
],
},
},
// Script execution message - running
{
id: 'script-1',
session_id: 'demo',
task_id: 'demo-task',
type: 'script_execution',
content: '[SCRIPT EXECUTION MESSAGE - RUNNING] Setting up environment...\nInstalling dependencies...',
author_type: 'agent',
created_at: '2024-01-20T10:13:00Z',
metadata: {
script_type: 'setup',
command: './scripts/setup-env.sh',
status: 'running',
},
},
// Script execution message - completed
{
id: 'script-2',
session_id: 'demo',
task_id: 'demo-task',
type: 'script_execution',
content: '[SCRIPT EXECUTION MESSAGE - COMPLETED] Build successful!\nAll tests passed.\nDeployment ready.',
author_type: 'agent',
created_at: '2024-01-20T10:14:00Z',
metadata: {
script_type: 'cleanup',
command: 'npm run build',
status: 'exited',
exit_code: 0,
started_at: '2024-01-20T10:13:00Z',
completed_at: '2024-01-20T10:14:00Z',
},
},
// Agent message - mixed content
{
id: 'agent-3',
session_id: 'demo',
task_id: 'demo-task',
content: `**[MIXED CONTENT DEMO]** Testing nested and mixed elements:
#### Heading 4 (h4 element)
Regular paragraph with inline elements: \`code\`, **bold**, and more text.
**Nested list structure:**
1. **First level item** (ol > li with strong)
- Nested bullet (this should indent)
- Another nested item
2. Second level item with \`inline code\`
3. Third item
**Technical details:**
- File path: \`/src/components/Auth.tsx\`
- Function: \`authenticateUser(credentials)\`
- Status: **Active** (strong element)
\`\`\`bash
# Code block with bash syntax
npm install
npm run dev
\`\`\`
Final paragraph (p element) to wrap up.`,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:14:00Z',
},
// Agent message with rich blocks - thinking
{
id: 'agent-rich-1',
session_id: 'demo',
task_id: 'demo-task',
content: `**[RICH BLOCK - THINKING]** Here's my analysis of the authentication system.`,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:15:00Z',
metadata: {
thinking: 'I need to carefully consider the security implications here. The current implementation uses JWT tokens, but we should add refresh token rotation to prevent token theft. We also need to implement proper CSRF protection for the authentication endpoints.',
},
},
// Agent message with rich blocks - todos
{
id: 'agent-rich-2',
session_id: 'demo',
task_id: 'demo-task',
content: `**[RICH BLOCK - TODOS]** Here are the next steps we need to take.`,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:16:00Z',
metadata: {
todos: [
{ text: 'Update the authentication middleware', done: true },
{ text: 'Add unit tests for token validation', done: false },
{ text: 'Implement rate limiting on login endpoint', done: false },
'Update documentation for new OAuth flow',
],
},
},
// Agent message with rich blocks - diff payload (structured)
{
id: 'agent-rich-3',
session_id: 'demo',
task_id: 'demo-task',
content: `**[RICH BLOCK - DIFF PAYLOAD]** I've made the following changes to the authentication config:`,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:17:00Z',
metadata: {
diff: {
oldFile: { fileName: 'src/auth/config.ts', fileLang: 'typescript' },
newFile: { fileName: 'src/auth/config.ts', fileLang: 'typescript' },
hunks: [
`diff --git a/src/auth/config.ts b/src/auth/config.ts
index 1234567..abcdefg 100644
--- a/src/auth/config.ts
+++ b/src/auth/config.ts
@@ -1,7 +1,10 @@
export const authConfig = {
clientId: process.env.OAUTH_CLIENT_ID,
- clientSecret: process.env.OAUTH_CLIENT_SECRET,
+ clientSecret: process.env.OAUTH_CLIENT_SECRET || '',
redirectUri: process.env.OAUTH_REDIRECT_URI,
+ tokenExpiry: '1h',
+ refreshTokenExpiry: '7d',
+ enableCsrf: true,
};
export function validateToken(token: string) {`,
],
},
},
},
// Agent message with rich blocks - diff string (plain text)
{
id: 'agent-rich-4',
session_id: 'demo',
task_id: 'demo-task',
content: `**[RICH BLOCK - DIFF STRING]** Here's the diff for the middleware changes:`,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:18:00Z',
metadata: {
diff: `--- a/src/middleware/auth.ts
+++ b/src/middleware/auth.ts
@@ -12,6 +12,11 @@ export async function authMiddleware(req: Request, res: Response, next: NextFun
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
- return res.status(401).json({ error: 'No token provided' });
+ return res.status(401).json({
+ error: 'No token provided',
+ code: 'AUTH_TOKEN_MISSING',
+ timestamp: new Date().toISOString()
+ });
}
try {`,
},
},
// Agent message with multiple rich blocks
{
id: 'agent-rich-5',
session_id: 'demo',
task_id: 'demo-task',
content: `**[RICH BLOCK - ALL TYPES]** Here's my complete analysis with all the changes:`,
author_type: 'agent',
type: 'message',
created_at: '2024-01-20T10:19:00Z',
metadata: {
thinking: 'After reviewing the code, I found several areas that need improvement. The error handling is inconsistent and we need better type safety.',
todos: [
{ text: 'Add TypeScript strict mode', done: true },
{ text: 'Implement error boundaries', done: false },
{ text: 'Add logging middleware', done: false },
],
diff: {
oldFile: { fileName: 'src/types/auth.ts', fileLang: 'typescript' },
newFile: { fileName: 'src/types/auth.ts', fileLang: 'typescript' },
hunks: [
`diff --git a/src/types/auth.ts b/src/types/auth.ts
index 9876543..fedcba9 100644
--- a/src/types/auth.ts
+++ b/src/types/auth.ts
@@ -1,4 +1,12 @@
-export type AuthToken = string;
+export interface AuthToken {
+ value: string;
+ expiresAt: Date;
+ type: 'access' | 'refresh';
+}
-export type User = {
+export interface User {
id: string;
email: string;
+ role: 'admin' | 'user';
+ createdAt: Date;
+}`,
],
},
},
},
];
export default function MessagesDemoPage() {
const permissionsByToolCallId = new Map<string, Message>();
const permMsg = dummyMessages.find(m => m.id === 'permission-1');
if (permMsg) {
permissionsByToolCallId.set('tool-4', permMsg);
}
return (
<div className="min-h-screen bg-background p-8">
<div className="max-w-4xl mx-auto">
<div className="mb-8">
<h1 className="text-2xl font-bold mb-2">Message Types Demo</h1>
<p className="text-muted-foreground">
All message types rendered for styling and testing
</p>
</div>
<div className="space-y-2 border rounded-lg p-5 bg-card">
{dummyMessages.map((message) => (
<MessageRenderer
key={message.id}
comment={message}
isTaskDescription={message.id === 'task-description'}
taskId="demo-task"
permissionsByToolCallId={permissionsByToolCallId}
/>
))}
</div>
</div>
</div>
);
}
@@ -1,12 +1,14 @@
'use client';
import { useMemo } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm';
import { IconRobot } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import { RichBlocks } from '@/components/task/chat/messages/rich-blocks';
import { InlineCode } from '@/components/task/chat/messages/inline-code';
import { CodeBlock } from '@/components/task/chat/messages/code-block';
type ChatMessageProps = {
comment: Message;
@@ -15,39 +17,47 @@ type ChatMessageProps = {
showRichBlocks?: boolean;
};
function formatMessageTime(dateString: string): string {
if (!dateString) return '';
try {
const date = new Date(dateString);
if (isNaN(date.getTime())) return '';
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} catch {
return '';
}
}
export function ChatMessage({ comment, label, className, showRichBlocks }: ChatMessageProps) {
const isUser = comment.author_type === 'user';
const formattedTime = useMemo(() => formatMessageTime(comment.created_at), [comment.created_at]);
const isTaskDescription = label === 'Task';
return (
<div className={cn('w-full rounded-lg border px-4 py-3 text-sm', className)}>
<div className="flex items-center justify-between mb-2">
<p className="text-[11px] uppercase tracking-wide opacity-70">
{label}
{comment.requests_input ? (
<span className="ml-2 rounded-full bg-amber-500/20 px-2 py-0.5 text-[10px] text-amber-300">
Needs input
</span>
) : null}
</p>
{formattedTime && (
<span className="text-[10px] text-muted-foreground/60">{formattedTime}</span>
)}
</div>
{isUser ? (
// Keep the old card-based layout for task descriptions (amber banner)
if (isTaskDescription) {
return (
<div className={cn('w-full rounded-lg px-4 py-3 text-xs', className)}>
<div className="flex items-center">
<p className="text-[11px] uppercase tracking-wide opacity-70">
{comment.requests_input ? (
<span className="ml-2 rounded-full bg-amber-500/20 px-2 py-0.5 text-[10px] text-amber-300">
Needs input
</span>
) : null}
</p>
</div>
<p className="whitespace-pre-wrap">{comment.content || '(empty)'}</p>
) : (
</div>
);
}
// User message: right-aligned bubble
if (isUser) {
return (
<div className="flex justify-end w-full">
<div className="max-w-[85%] sm:max-w-[75%] md:max-w-2xl">
<div className="rounded-2xl border-primary/30 bg-primary/10 px-4 py-2.5 text-xs">
<p className="whitespace-pre-wrap">{comment.content || '(empty)'}</p>
</div>
</div>
</div>
);
}
// Agent message: icon on left, no card background
return (
<div className="flex items-start gap-2 sm:gap-3 w-full">
{/* Content */}
<div className="flex-1 min-w-0 text-xs">
<div className="prose prose-sm dark:prose-invert max-w-none prose-p:my-4 prose-p:leading-relaxed prose-ul:my-4 prose-ul:list-disc prose-ul:pl-6 prose-ol:my-4 prose-ol:list-decimal prose-ol:pl-6 prose-li:my-1.5 prose-pre:my-5 prose-strong:text-foreground prose-strong:font-bold prose-headings:text-foreground prose-headings:font-bold">
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkBreaks]}
@@ -56,89 +66,56 @@ export function ChatMessage({ comment, label, className, showRichBlocks }: ChatM
// Check if it's inline code (no className means inline, className with language-* means code block)
const isInline = !className || !className.startsWith('language-');
// Inline code (backticks)
// Inline code (backticks) - with copy on click
if (isInline) {
return (
<code
style={{
padding: '2px 6px',
backgroundColor: 'rgba(59, 130, 246, 0.2)',
color: 'rgb(96, 165, 250)',
borderRadius: '4px',
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
fontSize: '0.9em',
}}
{...props}
>
{children}
</code>
);
return <InlineCode>{children}</InlineCode>;
}
// Code blocks (triple backticks)
return (
<code
className={className}
style={{
display: 'block',
padding: '12px',
backgroundColor: 'rgba(0, 0, 0, 0.3)',
borderRadius: '6px',
overflowX: 'auto',
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
fontSize: '0.85em',
}}
{...props}
>
{children}
</code>
);
// Code blocks (triple backticks) - with syntax highlighting and copy button
return <CodeBlock className={className}>{children}</CodeBlock>;
},
ol: ({ children, ...props }) => (
<ol
style={{
listStyleType: 'decimal',
paddingLeft: '1.5rem',
marginTop: '1rem',
marginBottom: '1rem',
}}
{...props}
>
<ol className="list-decimal pl-6" {...props}>
{children}
</ol>
),
ul: ({ children, ...props }) => (
<ul
style={{
listStyleType: 'disc',
paddingLeft: '1.5rem',
marginTop: '1rem',
marginBottom: '1rem',
}}
{...props}
>
<ul className="list-disc pl-6" {...props}>
{children}
</ul>
),
li: ({ children, ...props }) => (
<li
style={{
marginTop: '0.375rem',
marginBottom: '0.375rem',
}}
{...props}
>
<li className="my-1" {...props}>
{children}
</li>
),
p: ({ children, ...props }) => (
<p
style={{
marginTop: '1rem',
marginBottom: '1rem',
lineHeight: '1.625',
}}
{...props}
>
<p className="leading-relaxed" {...props}>
{children}
</p>
),
h1: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
{children}
</p>
),
h2: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
{children}
</p>
),
h3: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
{children}
</p>
),
h4: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
{children}
</p>
),
h5: ({ children, ...props }) => (
<p className="my-1 font-bold" {...props}>
{children}
</p>
),
@@ -148,7 +125,7 @@ export function ChatMessage({ comment, label, className, showRichBlocks }: ChatM
</ReactMarkdown>
{showRichBlocks ? <RichBlocks comment={comment} /> : null}
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,148 @@
'use client';
import { useState } from 'react';
import { useTheme } from 'next-themes';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import { go } from '@codemirror/lang-go';
import { rust } from '@codemirror/lang-rust';
import { java } from '@codemirror/lang-java';
import { cpp } from '@codemirror/lang-cpp';
import { css } from '@codemirror/lang-css';
import { html } from '@codemirror/lang-html';
import { json } from '@codemirror/lang-json';
import { markdown } from '@codemirror/lang-markdown';
import { yaml } from '@codemirror/lang-yaml';
import { vscodeDark, vscodeLight } from '@uiw/codemirror-theme-vscode';
import { EditorView } from '@codemirror/view';
import { IconCheck, IconCopy } from '@tabler/icons-react';
import type { Extension } from '@codemirror/state';
import { cn } from '@/lib/utils';
type CodeBlockProps = {
children: React.ReactNode;
className?: string;
};
const getLanguageExtension = (language?: string): Extension | undefined => {
if (!language) return undefined;
const lang = language.replace('language-', '').toLowerCase();
switch (lang) {
case 'javascript':
case 'js':
return javascript();
case 'jsx':
return javascript({ jsx: true });
case 'typescript':
case 'ts':
return javascript({ typescript: true });
case 'tsx':
return javascript({ jsx: true, typescript: true });
case 'python':
case 'py':
return python();
case 'go':
case 'golang':
return go();
case 'rust':
case 'rs':
return rust();
case 'java':
return java();
case 'cpp':
case 'c++':
case 'c':
return cpp();
case 'css':
case 'scss':
case 'less':
return css();
case 'html':
case 'htm':
return html();
case 'json':
return json();
case 'markdown':
case 'md':
return markdown();
case 'yaml':
case 'yml':
return yaml();
case 'bash':
case 'sh':
case 'shell':
// Bash doesn't have a specific extension, fallback to basic
return undefined;
default:
return undefined;
}
};
export function CodeBlock({ children, className }: CodeBlockProps) {
const [copied, setCopied] = useState(false);
const { theme, systemTheme } = useTheme();
const effectiveTheme = theme === 'system' ? systemTheme : theme;
const code = String(children).replace(/\n$/, '');
const language = className?.replace('language-', '') || '';
const languageExtension = getLanguageExtension(className);
// Custom padding theme
const paddingTheme = EditorView.theme({
'&': {
padding: '2px 2px',
},
});
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(code);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
};
return (
<div className="relative group my-4 w-fit max-w-full min-w-[50%]">
{/* Copy button */}
<button
onClick={handleCopy}
className={cn(
'absolute top-2 right-2 z-10',
'p-1.5 rounded-md',
'bg-white/10 hover:bg-white/20',
'transition-all duration-200',
'opacity-0 group-hover:opacity-100',
'cursor-pointer',
)}
title="Copy code"
>
{copied ? (
<IconCheck className="h-3 w-3 text-green-400" />
) : (
<IconCopy className="h-3 w-3 text-gray-400" />
)}
</button>
{/* Code editor */}
<CodeMirror
value={code}
theme={effectiveTheme === 'dark' ? vscodeDark : vscodeLight}
extensions={languageExtension ? [languageExtension, EditorView.lineWrapping, paddingTheme] : [EditorView.lineWrapping, paddingTheme]}
editable={false}
basicSetup={{
lineNumbers: false,
highlightActiveLineGutter: false,
highlightActiveLine: false,
foldGutter: false,
}}
className="text-xs rounded-md overflow-hidden"
/>
</div>
);
}
@@ -0,0 +1,57 @@
'use client';
import { useState } from 'react';
import { cn } from '@/lib/utils';
type InlineCodeProps = {
children: React.ReactNode;
};
export function InlineCode({ children }: InlineCodeProps) {
const [showTooltip, setShowTooltip] = useState(false);
const [tooltipText, setTooltipText] = useState('Copy to clipboard');
const handleClick = async () => {
const text = String(children);
try {
await navigator.clipboard.writeText(text);
setTooltipText('Copied!');
setShowTooltip(true);
setTimeout(() => {
setShowTooltip(false);
setTimeout(() => setTooltipText('Copy to clipboard'), 200);
}, 1500);
} catch (err) {
console.error('Failed to copy:', err);
}
};
return (
<span className="relative inline-block group">
<code
onClick={handleClick}
className={cn(
'px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded font-mono text-[0.9em]',
'cursor-pointer hover:bg-blue-500/30 transition-colors'
)}
>
{children}
</code>
{/* Tooltip */}
<span
className={cn(
'absolute bottom-full left-1/2 -translate-x-1/2 mb-1',
'px-2 py-1 text-xs text-white bg-gray-900 rounded whitespace-nowrap',
'pointer-events-none transition-opacity duration-200',
'opacity-0 group-hover:opacity-100',
showTooltip && 'opacity-100'
)}
>
{tooltipText}
<span className="absolute top-full left-1/2 -translate-x-1/2 -mt-px border-4 border-transparent border-t-gray-900" />
</span>
</span>
);
}
@@ -15,26 +15,26 @@ export function PermissionActionRow({
isResponding = false,
}: PermissionActionRowProps) {
return (
<div className="flex items-center gap-2 px-3 py-2 border-t border-amber-500/30 bg-amber-500/10">
<div className="flex items-center gap-2 px-3 py-2 rounded-sm bg-amber-500/10">
<span className="text-xs text-amber-600 dark:text-amber-400 flex-1">
Approve this action?
</span>
<Button
size="sm"
size="xs"
variant="outline"
onClick={onReject}
disabled={isResponding}
className="h-7 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
className="h-6 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
>
<IconX className="h-4 w-4 mr-1 text-red-500" />
Deny
</Button>
<Button
size="sm"
size="xs"
variant="outline"
onClick={onApprove}
disabled={isResponding}
className="h-7 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
className="h-6 px-3 text-foreground border-border bg-background hover:bg-muted hover:border-foreground/40 transition-colors cursor-pointer"
>
{isResponding ? (
<IconLoader2 className="h-4 w-4 mr-1 animate-spin" />
@@ -107,34 +107,43 @@ export function PermissionRequestMessage({ comment }: PermissionRequestMessagePr
};
return (
<div
className={cn(
'w-full rounded-md border overflow-hidden',
isPending ? 'border-amber-500/50 bg-amber-500/5' : 'border-border/50 bg-muted/20'
)}
>
{/* Header */}
<div className="flex items-center gap-2 px-3 py-2 text-sm">
<IconAlertTriangle
className={cn(
'h-4 w-4 flex-shrink-0',
isPending ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
)}
/>
<span className="flex-1 font-medium text-foreground truncate">
{comment.content || 'Permission Required'}
</span>
{getStatusBadge()}
</div>
<div className="w-full">
{/* Icon + Content Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<IconAlertTriangle
className={cn(
'h-4 w-4',
isPending ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
)}
/>
</div>
{/* Approval buttons - only show when pending */}
{isPending && (
<PermissionActionRow
onApprove={handleApprove}
onReject={handleReject}
isResponding={isResponding}
/>
)}
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<span className={cn(
'font-mono text-xs',
isPending ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
)}>
{comment.content || 'Permission Required'}
</span>
{getStatusBadge()}
</div>
{/* Approval buttons - only show when pending */}
{isPending && (
<div className="mt-2">
<PermissionActionRow
onApprove={handleApprove}
onReject={handleReject}
isResponding={isResponding}
/>
</div>
)}
</div>
</div>
</div>
);
}
@@ -53,7 +53,7 @@ export function RichBlocks({ comment }: { comment: Message }) {
</div>
)}
{todoItems.length > 0 && (
<div className="mt-3 rounded-md border border-border/50 bg-background/60 px-3 py-2 text-xs">
<div className="mt-3 rounded-md border border-border/49 bg-background/60 px-3 py-2 text-xs">
<div className="flex items-center gap-2 text-muted-foreground mb-1 uppercase tracking-wide">
<IconListCheck className="h-3.5 w-3.5" />
<span>Todos</span>
@@ -1,6 +1,7 @@
'use client';
import { IconCheck, IconX, IconLoader2, IconTerminal } from '@tabler/icons-react';
import { useState } from 'react';
import { IconCheck, IconX, IconLoader2, IconTerminal, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import { Badge } from '@kandev/ui/badge';
@@ -17,21 +18,49 @@ interface ScriptExecutionMetadata {
}
export function ScriptExecutionMessage({ comment }: { comment: Message }) {
const [isExpanded, setIsExpanded] = useState(false);
const metadata = comment.metadata as ScriptExecutionMetadata | undefined;
// Show fallback if metadata is missing or incomplete
if (!metadata || !metadata.script_type) {
const hasContent = !!comment.content;
return (
<div className="w-full rounded-lg border border-yellow-500/40 bg-yellow-500/5 px-4 py-3 text-sm">
<div className="flex items-center gap-2 text-yellow-600 dark:text-yellow-400">
<IconTerminal className="h-4 w-4" />
<span>Script Execution (metadata unavailable)</span>
<div className="w-full">
<div className="flex items-start gap-3 w-full">
<div className="flex-shrink-0 mt-0.5">
<IconTerminal className="h-4 w-4 text-yellow-600 dark:text-yellow-400" />
</div>
<div className="flex-1 min-w-0">
<button
type="button"
onClick={() => hasContent && setIsExpanded(!isExpanded)}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasContent && 'cursor-pointer hover:opacity-70 transition-opacity'
)}
disabled={!hasContent}
>
<span className="text-xs font-mono text-yellow-600 dark:text-yellow-400">
Script Execution (metadata unavailable)
</span>
{hasContent && (
isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)
)}
</button>
{isExpanded && comment.content && (
<div className="mt-2 pl-4 border-l-2 border-border/30">
<pre className="font-mono text-xs bg-muted/30 rounded px-3 py-2 overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
{comment.content}
</pre>
</div>
)}
</div>
</div>
{comment.content && (
<pre className="mt-2 font-mono text-xs bg-black/5 dark:bg-white/5 rounded px-3 py-2 border border-border/40 overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
{comment.content}
</pre>
)}
</div>
);
}
@@ -45,90 +74,106 @@ export function ScriptExecutionMessage({ comment }: { comment: Message }) {
const StatusIcon = isRunning
? IconLoader2
: isSuccess
? IconCheck
: IconX;
? IconCheck
: IconX;
const statusText = isRunning
? 'Running...'
: isSuccess
? 'Completed'
: 'Failed';
? 'Completed'
: 'Failed';
const statusColor = isRunning
? 'text-blue-500'
: isSuccess
? 'text-green-500'
: 'text-red-500';
? 'text-green-500'
: 'text-red-500';
const borderColor = isRunning
? 'border-blue-500/40'
: isSuccess
? 'border-green-500/40'
: 'border-red-500/40';
const bgColor = isRunning
? 'bg-blue-500/5'
: isSuccess
? 'bg-green-500/5'
: 'bg-red-500/5';
const hasDetails = comment.content || error || exit_code !== undefined;
return (
<div
className={cn(
'w-full rounded-lg border px-4 py-3 text-sm',
borderColor,
bgColor
)}
>
{/* Header */}
<div className="flex items-center justify-between gap-2 mb-2">
<div className="flex items-center gap-2">
<div className="w-full">
{/* Icon + Summary Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<IconTerminal className="h-4 w-4 text-muted-foreground" />
<Badge variant={isSetup ? 'default' : 'secondary'} className="text-xs">
{isSetup ? 'Setup Script' : 'Cleanup Script'}
</Badge>
<div className={cn('flex items-center gap-1.5 text-xs', statusColor)}>
<StatusIcon className={cn('h-3.5 w-3.5', isRunning && 'animate-spin')} />
<span>{statusText}</span>
</div>
{/* Content */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => hasDetails && setIsExpanded(!isExpanded)}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasDetails && 'cursor-pointer hover:opacity-70 transition-opacity'
)}
disabled={!hasDetails}
>
<Badge variant={isSetup ? 'default' : 'secondary'} className="text-xs">
{isSetup ? 'Setup' : 'Cleanup'}
</Badge>
<span className="font-mono text-xs text-muted-foreground">
{command}
</span>
{/* Status indicator - only show if not success */}
{!isSuccess && (
<StatusIcon className={cn('h-3.5 w-3.5', statusColor, isRunning && 'animate-spin')} />
)}
{hasDetails && (
isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)
)}
</button>
</div>
</div>
</div>
{/* Command */}
<div className="mb-2 font-mono text-xs bg-muted/50 rounded px-2 py-1.5 border border-border/40">
<span className="text-muted-foreground">$</span> {command}
</div>
{/* Expanded Details */}
{isExpanded && hasDetails && (
<div className="mt-2 pl-4 border-l-2 border-border/30 space-y-2">
{/* Output */}
{comment.content && comment.content.trim() !== '' && (
<div>
<div className="text-[10px] uppercase tracking-wide text-muted-foreground/60 mb-1">
Output
</div>
<pre className="font-mono text-xs bg-muted/30 rounded px-3 py-2 overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
{comment.content}
</pre>
</div>
)}
{/* Output */}
{comment.content && comment.content.trim() !== '' && (
<div className="mb-2">
<div className="text-[11px] uppercase tracking-wide text-muted-foreground mb-1">
Output
</div>
<pre className="font-mono text-xs bg-black/5 dark:bg-white/5 rounded px-3 py-2 border border-border/40 overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
{comment.content}
</pre>
</div>
)}
{/* Error message */}
{error && (
<div>
<div className="text-[10px] uppercase tracking-wide text-red-600/70 dark:text-red-400/70 mb-1">
Error
</div>
<div className="text-xs text-red-600 dark:text-red-400 bg-red-500/10 rounded px-2 py-1.5">
{error}
</div>
</div>
)}
{/* Error message */}
{error && (
<div className="mb-2 text-xs text-red-600 dark:text-red-400 bg-red-500/10 rounded px-2 py-1.5 border border-red-500/20">
{error}
</div>
)}
{/* Footer with exit code */}
{!isRunning && exit_code !== undefined && (
<div className="flex items-center justify-between text-[11px] text-muted-foreground pt-2 border-t border-border/40">
<span>Exit code: {exit_code}</span>
{metadata.started_at && metadata.completed_at && (
<span>
Duration: {calculateDuration(metadata.started_at, metadata.completed_at)}
</span>
{/* Footer with exit code */}
{!isRunning && exit_code !== undefined && (
<div className="flex items-center justify-between text-[10px] text-muted-foreground pt-2 border-t border-border/30">
<span>Exit code: {exit_code}</span>
{metadata.started_at && metadata.completed_at && (
<span>
Duration: {calculateDuration(metadata.started_at, metadata.completed_at)}
</span>
)}
</div>
)}
</div>
)}
</div>
)}
</div>
</div>
);
}
@@ -33,30 +33,31 @@ export function StatusMessage({ comment }: { comment: Message }) {
if (isSimpleStatus) {
return (
<div className="flex items-center justify-center py-1">
<div className="flex items-center gap-1.5 px-3 py-1 rounded-full bg-primary/10 border border-primary/20 text-xs text-primary">
<IconPointFilled className="h-2 w-2" />
<span>{message}</span>
</div>
<div className="flex items-center gap-3 w-full py-2">
<div className="flex-1 h-px bg-border" />
<span className="text-xs text-muted-foreground/60 whitespace-nowrap">{message}</span>
<div className="flex-1 h-px bg-border" />
</div>
);
}
// Cancelled turn gets a special compact warning style
// Cancelled turn gets a special separator style
if (metadata?.cancelled) {
return (
<div className="flex items-center justify-center py-1">
<div className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-amber-500/10 border border-amber-500/30 text-xs text-amber-600 dark:text-amber-400">
<div className="flex items-center gap-3 w-full py-2">
<div className="flex-1 h-px bg-amber-500/30" />
<div className="flex items-center gap-1.5 text-xs text-amber-600 dark:text-amber-400">
<IconHandStop className="h-3 w-3" />
<span>{message}</span>
</div>
<div className="flex-1 h-px bg-amber-500/30" />
</div>
);
}
const Icon = isError ? IconAlertTriangle : isWarning ? IconAlertTriangle : IconInfoCircle;
const iconClass = isError ? 'text-red-500' : isWarning ? 'text-amber-500' : 'text-muted-foreground';
const label = isError ? 'Error' : isWarning ? 'Warning' : 'Status';
const textClass = isError ? 'text-red-600 dark:text-red-400' : isWarning ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground';
// Format error details for display
const formatErrorDetails = () => {
@@ -86,68 +87,71 @@ export function StatusMessage({ comment }: { comment: Message }) {
const errorDetails = hasErrorDetails ? formatErrorDetails() : [];
return (
<div
className={cn(
'w-full rounded-lg border px-4 py-3 text-sm',
isError
? 'border-red-500/40 bg-red-500/10 text-foreground'
: isWarning
? 'border-amber-500/40 bg-amber-500/10 text-foreground'
: 'border-border/60 bg-muted/30 text-foreground'
)}
>
<div className="flex items-center gap-2 mb-2 text-[11px] uppercase tracking-wide opacity-70">
<Icon className={cn('h-3.5 w-3.5', iconClass)} />
<span>{label}</span>
</div>
<div className="whitespace-pre-wrap">{message || 'An error occurred'}</div>
<div className="w-full">
{/* Icon + Content Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<Icon className={cn('h-4 w-4', iconClass)} />
</div>
{/* Expandable error details */}
{hasErrorDetails && errorDetails.length > 0 && (
<div className="mt-3 border-t border-red-500/20 pt-2">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="flex items-center gap-1 text-xs text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 transition-colors"
>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5" />
) : (
<IconChevronRight className="h-3.5 w-3.5" />
)}
<span>{isExpanded ? 'Hide details' : 'Show details'}</span>
</button>
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className={cn('text-xs font-mono', textClass)}>
{message || 'An error occurred'}
</div>
{isExpanded && (
<div className="mt-2 space-y-2">
{errorDetails.map((detail, index) => (
<div key={index}>
<div className="text-[10px] uppercase tracking-wide text-red-600/70 dark:text-red-400/70 mb-0.5">
{detail.label}
</div>
<pre className="text-xs bg-red-500/5 rounded p-2 overflow-x-auto whitespace-pre-wrap break-all font-mono">
{detail.value}
</pre>
{/* Expandable error details */}
{hasErrorDetails && errorDetails.length > 0 && (
<div className="mt-2">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="inline-flex items-center gap-1.5 text-left cursor-pointer hover:opacity-70 transition-opacity"
>
<span className="font-mono text-xs text-muted-foreground">
{isExpanded ? 'Hide details' : 'Show details'}
</span>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)}
</button>
{isExpanded && (
<div className="mt-2 pl-4 border-l-2 border-border/30 space-y-2">
{errorDetails.map((detail, index) => (
<div key={index}>
<div className="text-[10px] uppercase tracking-wide text-muted-foreground/60 mb-0.5">
{detail.label}
</div>
<pre className="text-xs bg-muted/30 rounded p-2 overflow-x-auto whitespace-pre-wrap break-all font-mono">
{detail.value}
</pre>
</div>
))}
</div>
))}
)}
</div>
)}
{/* Progress bar */}
{progress !== null && (
<div className="mt-2">
<div className="flex items-center justify-between text-[10px] text-muted-foreground mb-1">
<span>{statusLine ?? 'Progress'}</span>
<span>{Math.round(progress)}%</span>
</div>
<div className="h-1.5 rounded-full bg-muted/70">
<div
className="h-full rounded-full bg-primary/80 transition-[width]"
style={{ width: `${progress}%` }}
/>
</div>
</div>
)}
</div>
)}
{progress !== null && (
<div className="mt-2">
<div className="flex items-center justify-between text-[11px] text-muted-foreground mb-1">
<span>{statusLine ?? 'Progress'}</span>
<span>{Math.round(progress)}%</span>
</div>
<div className="h-1.5 rounded-full bg-muted/70">
<div
className="h-full rounded-full bg-primary/80 transition-[width]"
style={{ width: `${progress}%` }}
/>
</div>
</div>
)}
</div>
</div>
);
}
@@ -1,20 +1,54 @@
'use client';
import { IconBrain } from '@tabler/icons-react';
import { useState } from 'react';
import { IconBrain, IconChevronDown, IconChevronRight } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import type { Message } from '@/lib/types/http';
import type { RichMetadata } from '@/components/task/chat/types';
export function ThinkingMessage({ comment }: { comment: Message }) {
const [isExpanded, setIsExpanded] = useState(false);
const metadata = comment.metadata as RichMetadata | undefined;
const text = metadata?.thinking ?? comment.content;
if (!text) return null;
return (
<div className="w-full rounded-lg border border-border/60 bg-background/60 px-4 py-3 text-sm">
<div className="flex items-center gap-2 text-muted-foreground mb-2 uppercase tracking-wide text-[11px]">
<IconBrain className="h-3.5 w-3.5" />
<span>Thinking</span>
<div className="w-full">
{/* Icon + Summary Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
<IconBrain className="h-4 w-4 text-muted-foreground" />
</div>
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => setIsExpanded(!isExpanded)}
className="inline-flex items-center gap-1.5 text-left cursor-pointer hover:opacity-70 transition-opacity"
>
<span className="font-mono text-xs text-muted-foreground">
Thinking
</span>
{isExpanded ? (
<IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
) : (
<IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)}
</button>
</div>
{/* Expanded Content */}
{isExpanded && (
<div className="mt-2 pl-4 border-l-2 border-border/30">
<div className="whitespace-pre-wrap leading-normal text-xs text-foreground/80">{text}</div>
</div>
)}
</div>
</div>
<div className="whitespace-pre-wrap text-foreground/80">{text}</div>
</div>
);
}
@@ -20,7 +20,7 @@ export function TodoMessage({ comment }: { comment: Message }) {
const progress = Math.round((completed / todoItems.length) * 100);
return (
<div className="w-full rounded-lg border border-border/60 bg-background/60 px-4 py-3 text-sm">
<div className="w-full rounded-lg border border-border/60 bg-background/60 px-4 py-3 text-xs">
<div className="flex items-center gap-2 text-muted-foreground mb-2 uppercase tracking-wide text-[11px]">
<IconListCheck className="h-3.5 w-3.5" />
<span>Todos</span>
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import {
IconCheck,
IconChevronDown,
@@ -87,8 +87,6 @@ type ToolCallMessageProps = {
};
export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageProps) {
const [isExpanded, setIsExpanded] = useState(false);
const [isResponding, setIsResponding] = useState(false);
const metadata = comment.metadata as ToolCallMetadata | undefined;
const permissionMetadata = permissionMessage?.metadata as PermissionRequestMetadata | undefined;
@@ -103,6 +101,31 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP
const permissionStatus = permissionMetadata?.status;
const isPermissionPending = hasPermission && permissionStatus !== 'approved' && permissionStatus !== 'rejected';
// Initialize isExpanded based on status - auto-expand if running
const [isExpanded, setIsExpanded] = useState(() => {
return status === 'running';
});
const [isManuallyToggled, setIsManuallyToggled] = useState(false);
const [isResponding, setIsResponding] = useState(false);
// Auto-collapse when complete (unless manually overridden)
useEffect(() => {
// Permission requests always stay expanded
if (isPermissionPending) {
setIsExpanded(true);
return;
}
// Only auto-collapse if user hasn't manually toggled
if (!isManuallyToggled) {
if (status === 'running') {
setIsExpanded(true);
} else if (status === 'complete' || status === 'error') {
setIsExpanded(false);
}
}
}, [status, isManuallyToggled, isPermissionPending]);
const handleRespond = useCallback(
async (optionId: string, cancelled: boolean = false) => {
if (!permissionMetadata || !permissionMessage) return;
@@ -150,10 +173,6 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP
}
}, [permissionMetadata, handleRespond]);
const toolIcon = getToolIcon(toolName, cn(
'h-4 w-4 flex-shrink-0',
isPermissionPending ? 'text-amber-600 dark:text-amber-400' : 'text-amber-600 dark:text-amber-400'
));
const hasDetails = args && Object.keys(args).length > 0;
let filePath: string | undefined;
@@ -168,75 +187,99 @@ export function ToolCallMessage({ comment, permissionMessage }: ToolCallMessageP
}
}
const isSuccess = status === 'complete' && !permissionStatus;
return (
<div className={cn(
'w-full rounded-md border overflow-hidden',
isPermissionPending ? 'border-amber-500/50 bg-amber-500/5' : 'border-border/50 bg-muted/20'
)}>
<button
type="button"
onClick={() => hasDetails && setIsExpanded(!isExpanded)}
className={cn(
'w-full flex items-center gap-2 px-3 py-2 text-sm text-left',
hasDetails && 'cursor-pointer hover:bg-muted/40 transition-colors'
)}
disabled={!hasDetails}
>
{toolIcon}
<span className="flex-1 font-mono text-xs text-muted-foreground truncate">
{title}
</span>
{filePath && (
<span className="text-xs text-muted-foreground/60 truncate max-w-[200px]">
{filePath}
</span>
)}
{getStatusIcon(status, permissionStatus)}
{hasDetails && (
isExpanded
? <IconChevronDown className="h-4 w-4 text-muted-foreground/50" />
: <IconChevronRight className="h-4 w-4 text-muted-foreground/50" />
)}
</button>
<div className="w-full">
{/* Icon + Summary Row */}
<div className="flex items-start gap-3 w-full">
{/* Icon */}
<div className="flex-shrink-0 mt-0.5">
{getToolIcon(toolName, cn(
'h-4 w-4',
isPermissionPending ? 'text-amber-600 dark:text-amber-400' : 'text-muted-foreground'
))}
</div>
{isExpanded && hasDetails && (
<div className="border-t border-border/30 bg-background/50 p-3 space-y-2">
{args && Object.entries(args).map(([key, value]) => {
const strValue = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
const isLongValue = strValue.length > 100 || strValue.includes('\n');
{/* Content */}
<div className="flex-1 min-w-0 pt-0.5">
<div className="flex items-center gap-2 text-xs">
<button
type="button"
onClick={() => {
if (hasDetails) {
setIsExpanded(!isExpanded);
setIsManuallyToggled(true);
}
}}
className={cn(
'inline-flex items-center gap-1.5 text-left',
hasDetails && 'cursor-pointer hover:opacity-70 transition-opacity',
isPermissionPending && 'text-amber-600 dark:text-amber-400'
)}
disabled={!hasDetails}
>
<span className="font-mono text-xs">
{title}
</span>
{/* Status indicator - only show if not success */}
{!isSuccess && getStatusIcon(status, permissionStatus)}
{hasDetails && (
isExpanded
? <IconChevronDown className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
: <IconChevronRight className="h-3.5 w-3.5 text-muted-foreground/50 flex-shrink-0" />
)}
</button>
{filePath && (
<span className="text-xs text-muted-foreground/60 truncate">
{filePath}
</span>
)}
</div>
return (
<div key={key} className="text-xs">
<span className="font-medium text-muted-foreground">{key}:</span>
{isLongValue ? (
<pre className="mt-1 p-2 bg-muted/50 rounded text-[11px] overflow-x-auto max-h-[200px] overflow-y-auto whitespace-pre-wrap break-all">
{strValue}
{/* Expanded Details */}
{isExpanded && hasDetails && (
<div className="mt-2 pl-4 border-l-2 border-border/30 space-y-2">
{args && Object.entries(args).map(([key, value]) => {
const strValue = typeof value === 'string' ? value : JSON.stringify(value, null, 2);
const isLongValue = strValue.length > 100 || strValue.includes('\n');
return (
<div key={key} className="text-xs">
<span className="font-medium text-muted-foreground">{key}:</span>
{isLongValue ? (
<pre className="mt-1 p-2 bg-muted/30 rounded text-[11px] overflow-x-auto max-h-[200px] overflow-y-auto whitespace-pre-wrap break-all">
{strValue}
</pre>
) : (
<span className="ml-2 font-mono text-foreground/80">{strValue}</span>
)}
</div>
);
})}
{result && (
<div className="text-xs pt-2 mt-2 border-t border-border/30">
<span className="font-medium text-muted-foreground">Result:</span>
<pre className="mt-1 p-2 bg-muted/30 rounded text-[11px] overflow-x-auto max-h-[150px] overflow-y-auto whitespace-pre-wrap">
{result}
</pre>
) : (
<span className="ml-2 font-mono text-foreground/80">{strValue}</span>
)}
</div>
);
})}
{result && (
<div className="text-xs border-t border-border/30 pt-2 mt-2">
<span className="font-medium text-muted-foreground">Result:</span>
<pre className="mt-1 p-2 bg-muted/50 rounded text-[11px] overflow-x-auto max-h-[150px] overflow-y-auto whitespace-pre-wrap">
{result}
</pre>
</div>
)}
</div>
)}
{/* Inline permission approval UI */}
{isPermissionPending && (
<div className="mt-2">
<PermissionActionRow
onApprove={handleApprove}
onReject={handleReject}
isResponding={isResponding}
/>
</div>
)}
</div>
)}
{/* Inline permission approval UI */}
{isPermissionPending && (
<PermissionActionRow
onApprove={handleApprove}
onReject={handleReject}
isResponding={isResponding}
/>
)}
</div>
</div>
);
}
@@ -100,7 +100,7 @@ export function VirtualizedMessageList({
return (
<SessionPanelContent
ref={messagesContainerRef}
className="relative"
className="relative p-4"
>
{isLoadingMore && hasMore && (
<div className="absolute top-2 left-1/2 -translate-x-1/2 text-xs text-muted-foreground">
@@ -133,7 +133,7 @@ export function VirtualizedMessageList({
className="absolute left-0 top-0 w-full"
style={{ transform: `translateY(${virtualRow.start}px)` }}
>
<div className="pb-3">
<div className="pb-2">
<MessageRenderer
comment={message}
isTaskDescription={message.id === 'task-description'}
@@ -342,7 +342,7 @@ const TaskFilesPanel = memo(function TaskFilesPanel({ onSelectDiff, onOpenFile }
{/* Empty state */}
{changedFiles.length === 0 && commits.length === 0 && (
<div className="flex items-center justify-center h-full text-muted-foreground text-sm">
<div className="flex items-center justify-center h-full text-muted-foreground text-xs">
No changes detected
</div>
)}
@@ -354,7 +354,7 @@ const TaskFilesPanel = memo(function TaskFilesPanel({ onSelectDiff, onOpenFile }
{activeSessionId ? (
<FileBrowser sessionId={activeSessionId} onOpenFile={onOpenFile} />
) : (
<div className="flex items-center justify-center h-full text-muted-foreground text-sm">
<div className="flex items-center justify-center h-full text-muted-foreground text-xs">
No task selected
</div>
)}