batch4: chats-in-sessions, force-send, /compact, right-rail file browser
Session 1:N Chat data model with backfill. Workspace switches to client-side multi-tab pane management. Right-rail file browser with float-over viewer and click-drag line selection replaces FileBrowserPane. Adds /compact streaming summarizer (respects compact markers in context builder), force-send (cancels in-flight, persists partial as 'cancelled', awaits cancellation completion via deferred Promise + 5s timeout), message queue, stop generation, chat auto-rename, session archive/unarchive with Closed Sessions section on repo landing page. CHECK constraints on sessions.status, messages.role, messages.status with KEEP IN SYNC comments tying to MESSAGE_ROLES / MESSAGE_STATUSES const arrays. Deletes dead pane routes/hook and the api.panes.* client block. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,11 +1,29 @@
|
||||
import { BrowserRouter, Routes, Route } from 'react-router-dom';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { BrowserRouter, Routes, Route, useParams } from 'react-router-dom';
|
||||
import { api } from '@/api/client';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { RightRail } from '@/components/RightRail';
|
||||
import { Home } from '@/pages/Home';
|
||||
import { Project } from '@/pages/Project';
|
||||
import { Session } from '@/pages/Session';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { useUserEvents } from '@/hooks/useUserEvents';
|
||||
|
||||
function SessionRightRail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
if (!id) return null;
|
||||
return <RightRailForSession sessionId={id} />;
|
||||
}
|
||||
|
||||
function RightRailForSession({ sessionId }: { sessionId: string }) {
|
||||
const [projectId, setProjectId] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
api.sessions.get(sessionId).then((s) => setProjectId(s.project_id)).catch(() => {});
|
||||
}, [sessionId]);
|
||||
if (!projectId) return null;
|
||||
return <RightRail projectId={projectId} />;
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
useUserEvents();
|
||||
return (
|
||||
@@ -18,6 +36,9 @@ function AppShell() {
|
||||
<Route path="/session/:id" element={<Session />} />
|
||||
</Routes>
|
||||
</main>
|
||||
<Routes>
|
||||
<Route path="/session/:id" element={<SessionRightRail />} />
|
||||
</Routes>
|
||||
<Toaster position="bottom-right" />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,14 +2,12 @@ import type {
|
||||
Project,
|
||||
AvailableProject,
|
||||
Session,
|
||||
Chat,
|
||||
Message,
|
||||
ModelInfo,
|
||||
SidebarResponse,
|
||||
ListDirResult,
|
||||
ViewFileResult,
|
||||
Pane,
|
||||
PaneCreateRequest,
|
||||
PaneUpdateRequest,
|
||||
} from './types';
|
||||
|
||||
export class ApiError extends Error {
|
||||
@@ -61,8 +59,8 @@ export const api = {
|
||||
},
|
||||
|
||||
sessions: {
|
||||
listForProject: (projectId: string) =>
|
||||
request<Session[]>(`/api/projects/${projectId}/sessions`),
|
||||
listForProject: (projectId: string, status?: 'open' | 'archived') =>
|
||||
request<Session[]>(`/api/projects/${projectId}/sessions${status ? `?status=${status}` : ''}`),
|
||||
create: (
|
||||
projectId: string,
|
||||
body: { name?: string; model?: string; system_prompt?: string }
|
||||
@@ -82,22 +80,54 @@ export const api = {
|
||||
}),
|
||||
remove: (id: string) =>
|
||||
request<void>(`/api/sessions/${id}`, { method: 'DELETE' }),
|
||||
archive: (id: string) =>
|
||||
request<void>(`/api/sessions/${id}/archive`, { method: 'POST' }),
|
||||
unarchive: (id: string) =>
|
||||
request<Session>(`/api/sessions/${id}/unarchive`, { method: 'POST' }),
|
||||
},
|
||||
|
||||
chats: {
|
||||
listForSession: (sessionId: string) =>
|
||||
request<Chat[]>(`/api/sessions/${sessionId}/chats`),
|
||||
create: (sessionId: string, body?: { name?: string }) =>
|
||||
request<Chat>(`/api/sessions/${sessionId}/chats`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body ?? {}),
|
||||
}),
|
||||
update: (chatId: string, body: { name?: string; status?: 'open' | 'closed' }) =>
|
||||
request<Chat>(`/api/chats/${chatId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
remove: (chatId: string) =>
|
||||
request<void>(`/api/chats/${chatId}`, { method: 'DELETE' }),
|
||||
messages: (chatId: string) =>
|
||||
request<Message[]>(`/api/chats/${chatId}/messages`),
|
||||
compact: (chatId: string) =>
|
||||
request<{ compact_message_id: string }>(`/api/chats/${chatId}/compact`, { method: 'POST' }),
|
||||
stop: (chatId: string) =>
|
||||
request<{ stopped: boolean }>(`/api/chats/${chatId}/stop`, { method: 'POST' }),
|
||||
forceSend: (chatId: string, content: string) =>
|
||||
request<{ user_message_id: string; assistant_message_id: string }>(
|
||||
`/api/chats/${chatId}/force_send`,
|
||||
{ method: 'POST', body: JSON.stringify({ content }) }
|
||||
),
|
||||
},
|
||||
|
||||
messages: {
|
||||
list: (sessionId: string) =>
|
||||
request<Message[]>(`/api/sessions/${sessionId}/messages`),
|
||||
send: (sessionId: string, content: string) =>
|
||||
send: (chatId: string, content: string) =>
|
||||
request<{ user_message_id: string; assistant_message_id: string }>(
|
||||
`/api/sessions/${sessionId}/messages`,
|
||||
`/api/chats/${chatId}/messages`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ content }),
|
||||
}
|
||||
),
|
||||
regenerate: (sessionId: string, messageId: string) =>
|
||||
regenerate: (chatId: string, messageId: string) =>
|
||||
request<{ assistant_message_id: string }>(
|
||||
`/api/sessions/${sessionId}/messages/${messageId}/regenerate`,
|
||||
`/api/chats/${chatId}/messages/${messageId}/regenerate`,
|
||||
{ method: 'POST' }
|
||||
),
|
||||
},
|
||||
@@ -116,21 +146,4 @@ export const api = {
|
||||
sidebar: {
|
||||
get: () => request<SidebarResponse>('/api/sidebar'),
|
||||
},
|
||||
|
||||
panes: {
|
||||
getForSession: (sessionId: string) =>
|
||||
request<{ panes: Pane[] }>(`/api/sessions/${sessionId}/panes`),
|
||||
create: (sessionId: string, body: PaneCreateRequest) =>
|
||||
request<Pane>(`/api/sessions/${sessionId}/panes`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
update: (id: string, body: PaneUpdateRequest) =>
|
||||
request<Pane>(`/api/panes/${id}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
remove: (id: string) =>
|
||||
request<void>(`/api/panes/${id}`, { method: 'DELETE' }),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -11,18 +11,33 @@ export interface AvailableProject {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export type SessionStatus = 'open' | 'archived';
|
||||
|
||||
export interface Session {
|
||||
id: string;
|
||||
project_id: string;
|
||||
name: string;
|
||||
model: string;
|
||||
system_prompt: string;
|
||||
status: SessionStatus;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export type MessageRole = 'user' | 'assistant' | 'tool';
|
||||
export type MessageStatus = 'streaming' | 'complete' | 'failed';
|
||||
export type ChatStatus = 'open' | 'closed';
|
||||
|
||||
export interface Chat {
|
||||
id: string;
|
||||
session_id: string;
|
||||
name: string | null;
|
||||
status: ChatStatus;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export type MessageRole = 'user' | 'assistant' | 'tool' | 'system';
|
||||
export type MessageStatus = 'streaming' | 'complete' | 'failed' | 'cancelled';
|
||||
export type MessageKind = 'message' | 'compact';
|
||||
|
||||
export interface ToolCall {
|
||||
id: string;
|
||||
@@ -40,8 +55,10 @@ export interface ToolResult {
|
||||
export interface Message {
|
||||
id: string;
|
||||
session_id: string;
|
||||
chat_id: string;
|
||||
role: MessageRole;
|
||||
content: string;
|
||||
kind: MessageKind;
|
||||
tool_calls: ToolCall[] | null;
|
||||
tool_results: ToolResult | null;
|
||||
status: MessageStatus;
|
||||
@@ -127,14 +144,25 @@ export interface PaneUpdateRequest {
|
||||
position?: number;
|
||||
}
|
||||
|
||||
export type WorkspacePaneKind = 'chat' | 'terminal' | 'agent' | 'empty';
|
||||
|
||||
export interface WorkspacePane {
|
||||
id: string;
|
||||
kind: WorkspacePaneKind;
|
||||
chatId?: string;
|
||||
chatIds: string[];
|
||||
activeChatIdx: number;
|
||||
}
|
||||
|
||||
export type WsFrame =
|
||||
| { type: 'snapshot'; messages: Message[] }
|
||||
| { type: 'message_started'; message_id: string; role: MessageRole }
|
||||
| { type: 'delta'; message_id: string; content: string }
|
||||
| { type: 'tool_call'; message_id: string; tool_call: ToolCall }
|
||||
| { type: 'message_started'; message_id: string; chat_id?: string; role: MessageRole }
|
||||
| { type: 'delta'; message_id: string; chat_id?: string; content: string }
|
||||
| { type: 'tool_call'; message_id: string; chat_id?: string; tool_call: ToolCall }
|
||||
| {
|
||||
type: 'tool_result';
|
||||
tool_message_id: string;
|
||||
chat_id?: string;
|
||||
tool_call_id: string;
|
||||
output: unknown;
|
||||
truncated: boolean;
|
||||
@@ -143,12 +171,14 @@ export type WsFrame =
|
||||
| {
|
||||
type: 'message_complete';
|
||||
message_id: string;
|
||||
chat_id?: string;
|
||||
tokens_used?: number | null;
|
||||
ctx_used?: number | null;
|
||||
ctx_max?: number | null;
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
}
|
||||
| { type: 'messages_deleted'; message_ids: string[] }
|
||||
| { type: 'session_renamed'; session_id: string; name: string }
|
||||
| { type: 'error'; message_id?: string; error: string };
|
||||
| { type: 'messages_deleted'; message_ids: string[]; chat_id?: string }
|
||||
| { type: 'session_renamed'; session_id: string; name: string; chat_id?: string }
|
||||
| { type: 'chat_renamed'; chat_id: string; name: string }
|
||||
| { type: 'error'; message_id?: string; chat_id?: string; error: string };
|
||||
|
||||
41
apps/web/src/components/AttachmentChip.tsx
Normal file
41
apps/web/src/components/AttachmentChip.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
import { FileText, X } from 'lucide-react';
|
||||
import type { Attachment } from '@/lib/attachments';
|
||||
|
||||
interface Props {
|
||||
attachment: Attachment;
|
||||
onRemove: (id: string) => void;
|
||||
onPreview: (attachment: Attachment) => void;
|
||||
}
|
||||
|
||||
export function AttachmentChip({ attachment, onRemove, onPreview }: Props) {
|
||||
const lineCount = attachment.content.split('\n').length;
|
||||
|
||||
const label =
|
||||
attachment.kind === 'lines' && attachment.range
|
||||
? `${attachment.filename}:${attachment.range[0]}-${attachment.range[1]}`
|
||||
: attachment.filename;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 bg-muted/60 border border-border rounded px-2 py-0.5 text-xs font-mono">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onPreview(attachment)}
|
||||
className="flex items-center gap-1.5 hover:bg-muted/60 transition-colors min-w-0"
|
||||
>
|
||||
<FileText className="size-3 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate max-w-[200px]">{label}</span>
|
||||
<span className="text-muted-foreground whitespace-nowrap">
|
||||
+{lineCount} lines
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(attachment.id)}
|
||||
className="ml-0.5 rounded hover:bg-muted-foreground/20 p-0.5 shrink-0"
|
||||
aria-label="Remove attachment"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
37
apps/web/src/components/AttachmentPreviewModal.tsx
Normal file
37
apps/web/src/components/AttachmentPreviewModal.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { Attachment } from '@/lib/attachments';
|
||||
import { CodeBlock } from '@/components/CodeBlock';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
interface Props {
|
||||
attachment: Attachment | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function AttachmentPreviewModal({ attachment, onClose }: Props) {
|
||||
const title = attachment
|
||||
? attachment.kind === 'lines' && attachment.range
|
||||
? `${attachment.filename}:${attachment.range[0]}-${attachment.range[1]}`
|
||||
: attachment.filename
|
||||
: '';
|
||||
|
||||
return (
|
||||
<Dialog open={attachment !== null} onOpenChange={() => onClose()}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-mono text-sm">{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{attachment && (
|
||||
<CodeBlock
|
||||
code={attachment.content}
|
||||
lang={attachment.language ?? undefined}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +1,73 @@
|
||||
import { useState, type KeyboardEvent } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from 'react';
|
||||
import { Send } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { flattenToMessage, inferLanguage, type Attachment } from '@/lib/attachments';
|
||||
import { AttachmentChip } from '@/components/AttachmentChip';
|
||||
import { AttachmentPreviewModal } from '@/components/AttachmentPreviewModal';
|
||||
import { FileMentionPopover } from '@/components/FileMentionPopover';
|
||||
import { api } from '@/api/client';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
|
||||
interface Props {
|
||||
disabled?: boolean;
|
||||
projectId: string;
|
||||
onSend: (content: string) => void | Promise<void>;
|
||||
onForceSend?: (content: string) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function ChatInput({ disabled, onSend }: Props) {
|
||||
export function ChatInput({ disabled, projectId, onSend, onForceSend }: Props) {
|
||||
const [value, setValue] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [attachments, setAttachments] = useState<Attachment[]>([]);
|
||||
const [previewAttachment, setPreviewAttachment] = useState<Attachment | null>(null);
|
||||
const [mentionState, setMentionState] = useState<{
|
||||
open: boolean;
|
||||
query: string;
|
||||
atIdx: number;
|
||||
anchorRect: { top: number; left: number };
|
||||
} | null>(null);
|
||||
const [fileIndex, setFileIndex] = useState<string[] | null>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
|
||||
function addAttachment(a: Attachment) {
|
||||
setAttachments(prev => {
|
||||
if (prev.length >= 10) {
|
||||
toast.error('Max 10 attachments per message');
|
||||
return prev;
|
||||
}
|
||||
return [...prev, a];
|
||||
});
|
||||
}
|
||||
|
||||
const addAttachmentRef = useRef(addAttachment);
|
||||
addAttachmentRef.current = addAttachment;
|
||||
|
||||
useEffect(() => {
|
||||
return sessionEvents.subscribe((event) => {
|
||||
if (event.type !== 'attach_chat_file') return;
|
||||
addAttachmentRef.current({
|
||||
id: crypto.randomUUID(),
|
||||
...event.attachment,
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
function removeAttachment(id: string) {
|
||||
setAttachments(prev => prev.filter(a => a.id !== id));
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const text = value.trim();
|
||||
if (!text || disabled || busy) return;
|
||||
if (!text && attachments.length === 0) return;
|
||||
if (disabled || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await onSend(text);
|
||||
const body = flattenToMessage(attachments, text);
|
||||
await onSend(body);
|
||||
setValue('');
|
||||
setAttachments([]);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'failed to send');
|
||||
} finally {
|
||||
@@ -27,32 +75,196 @@ export function ChatInput({ disabled, onSend }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
function getCaretCoords(textarea: HTMLTextAreaElement): { top: number; left: number } {
|
||||
const mirror = document.createElement('div');
|
||||
const style = window.getComputedStyle(textarea);
|
||||
|
||||
const properties = [
|
||||
'fontFamily', 'fontSize', 'fontWeight', 'fontStyle',
|
||||
'letterSpacing', 'lineHeight', 'textTransform', 'wordSpacing',
|
||||
'textIndent', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
|
||||
'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth',
|
||||
'boxSizing', 'whiteSpace', 'overflowWrap',
|
||||
] as const;
|
||||
|
||||
mirror.style.position = 'absolute';
|
||||
mirror.style.visibility = 'hidden';
|
||||
mirror.style.overflow = 'hidden';
|
||||
mirror.style.width = style.width;
|
||||
for (const prop of properties) {
|
||||
mirror.style[prop] = style[prop];
|
||||
}
|
||||
mirror.style.whiteSpace = 'pre-wrap';
|
||||
mirror.style.overflowWrap = 'break-word';
|
||||
|
||||
const textBefore = textarea.value.slice(0, textarea.selectionStart);
|
||||
mirror.textContent = textBefore;
|
||||
|
||||
const span = document.createElement('span');
|
||||
span.textContent = ''; // zero-width space
|
||||
mirror.appendChild(span);
|
||||
|
||||
document.body.appendChild(mirror);
|
||||
|
||||
const taRect = textarea.getBoundingClientRect();
|
||||
const spanRect = span.getBoundingClientRect();
|
||||
const mirrorRect = mirror.getBoundingClientRect();
|
||||
|
||||
const top = taRect.top + (spanRect.top - mirrorRect.top) - textarea.scrollTop + span.offsetHeight;
|
||||
const left = taRect.left + (spanRect.left - mirrorRect.left);
|
||||
|
||||
document.body.removeChild(mirror);
|
||||
|
||||
return { top, left };
|
||||
}
|
||||
|
||||
function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) {
|
||||
const newValue = e.target.value;
|
||||
setValue(newValue);
|
||||
|
||||
const ta = e.target;
|
||||
const pos = ta.selectionStart;
|
||||
|
||||
// Check for @ trigger
|
||||
if (pos > 0 && newValue[pos - 1] === '@') {
|
||||
const charBefore = pos >= 2 ? newValue[pos - 2] : null;
|
||||
if (charBefore === null || charBefore === ' ' || charBefore === '\n') {
|
||||
const coords = getCaretCoords(ta);
|
||||
setMentionState({ open: true, query: '', atIdx: pos - 1, anchorRect: coords });
|
||||
if (!fileIndex) {
|
||||
api.projects.files(projectId).then(r => setFileIndex(r.files)).catch(() => {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Update query if popover is open — use stored atIdx
|
||||
if (mentionState?.open) {
|
||||
const { atIdx } = mentionState;
|
||||
if (atIdx < pos && newValue[atIdx] === '@') {
|
||||
const query = newValue.slice(atIdx + 1, pos);
|
||||
setMentionState(prev => prev ? { ...prev, query } : null);
|
||||
} else {
|
||||
setMentionState(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMentionSelect(path: string) {
|
||||
const atIdx = mentionState?.atIdx ?? -1;
|
||||
const ta = textareaRef.current;
|
||||
const caretPos = ta?.selectionStart ?? value.length;
|
||||
setMentionState(null);
|
||||
|
||||
try {
|
||||
const result = await api.projects.viewFile(projectId, path);
|
||||
if (atIdx >= 0) {
|
||||
const cleaned = value.slice(0, atIdx) + value.slice(caretPos);
|
||||
setValue(cleaned);
|
||||
if (ta) {
|
||||
requestAnimationFrame(() => {
|
||||
ta.selectionStart = ta.selectionEnd = atIdx;
|
||||
ta.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
addAttachment({
|
||||
id: crypto.randomUUID(),
|
||||
kind: 'file',
|
||||
filename: path,
|
||||
language: inferLanguage(path),
|
||||
content: result.content,
|
||||
source: '@',
|
||||
});
|
||||
} catch {
|
||||
toast.error('Failed to load file');
|
||||
}
|
||||
}
|
||||
|
||||
const closeMention = useCallback(() => setMentionState(null), []);
|
||||
|
||||
function onKeyDown(e: KeyboardEvent<HTMLTextAreaElement>) {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
|
||||
if (mentionState?.open) return;
|
||||
if (e.key === 'Enter' && e.shiftKey && (e.metaKey || e.ctrlKey) && onForceSend) {
|
||||
e.preventDefault();
|
||||
void forceSubmit();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
}
|
||||
|
||||
async function forceSubmit() {
|
||||
const text = value.trim();
|
||||
if (!text || !onForceSend) return;
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const body = flattenToMessage(attachments, text);
|
||||
await onForceSend(body);
|
||||
setValue('');
|
||||
setAttachments([]);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'force send failed');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-t px-4 py-3 flex items-end gap-2">
|
||||
<Textarea
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Ask about this project. Cmd/Ctrl+Enter to send."
|
||||
disabled={disabled || busy}
|
||||
rows={3}
|
||||
className="resize-none min-h-[68px] max-h-[240px]"
|
||||
<div className="border-t">
|
||||
{attachments.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5 px-4 pt-3">
|
||||
{attachments.map(a => (
|
||||
<AttachmentChip
|
||||
key={a.id}
|
||||
attachment={a}
|
||||
onRemove={removeAttachment}
|
||||
onPreview={setPreviewAttachment}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="px-4 py-3 flex items-end gap-2">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
onKeyDown={onKeyDown}
|
||||
placeholder="Ask about this project. Enter to send, Shift+Enter for newline."
|
||||
disabled={disabled || busy}
|
||||
rows={3}
|
||||
className="resize-none min-h-[68px] max-h-[240px]"
|
||||
/>
|
||||
<Button
|
||||
onClick={() => void submit()}
|
||||
disabled={disabled || busy || (!value.trim() && attachments.length === 0)}
|
||||
size="icon-lg"
|
||||
aria-label="Send"
|
||||
>
|
||||
<Send />
|
||||
</Button>
|
||||
</div>
|
||||
<AttachmentPreviewModal
|
||||
attachment={previewAttachment}
|
||||
onClose={() => setPreviewAttachment(null)}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => void submit()}
|
||||
disabled={disabled || busy || !value.trim()}
|
||||
size="icon-lg"
|
||||
aria-label="Send"
|
||||
>
|
||||
<Send />
|
||||
</Button>
|
||||
{mentionState?.open && (
|
||||
<FileMentionPopover
|
||||
query={mentionState.query}
|
||||
files={fileIndex ?? []}
|
||||
anchorRect={mentionState.anchorRect}
|
||||
onSelect={handleMentionSelect}
|
||||
onClose={closeMention}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
201
apps/web/src/components/ChatTabBar.tsx
Normal file
201
apps/web/src/components/ChatTabBar.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
import { useState } from 'react';
|
||||
import { History, MessageSquare, Plus, X } from 'lucide-react';
|
||||
import type { Chat, WorkspacePane } from '@/api/types';
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from '@/components/ui/context-menu';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
pane: WorkspacePane;
|
||||
tabs: Chat[];
|
||||
onSwitchTab: (tabIdx: number) => void;
|
||||
onRemoveTab: (chatId: string) => void;
|
||||
onNewChat: () => void;
|
||||
onShowHistory: () => void;
|
||||
onRename: (chatId: string, name: string) => Promise<void>;
|
||||
onClose: (chatId: string) => Promise<void>;
|
||||
onDelete: (chatId: string) => Promise<void>;
|
||||
onRemovePane?: () => void;
|
||||
}
|
||||
|
||||
export function ChatTabBar({
|
||||
pane,
|
||||
tabs,
|
||||
onSwitchTab,
|
||||
onRemoveTab,
|
||||
onNewChat,
|
||||
onShowHistory,
|
||||
onRename,
|
||||
onClose,
|
||||
onDelete,
|
||||
onRemovePane,
|
||||
}: Props) {
|
||||
const [renamingId, setRenamingId] = useState<string | null>(null);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const [deleteConfirm, setDeleteConfirm] = useState<string | null>(null);
|
||||
|
||||
function startRename(chatId: string, currentName: string | null) {
|
||||
setRenamingId(chatId);
|
||||
setRenameValue(currentName ?? '');
|
||||
}
|
||||
|
||||
async function finishRename() {
|
||||
if (renamingId && renameValue.trim()) {
|
||||
await onRename(renamingId, renameValue.trim());
|
||||
}
|
||||
setRenamingId(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center border-b border-border bg-muted/20 h-8 shrink-0 overflow-x-auto">
|
||||
{/* Chat tabs */}
|
||||
{tabs.map((chat, tabIdx) => {
|
||||
const isActive = tabIdx === pane.activeChatIdx;
|
||||
const label = chat.name ?? 'New chat';
|
||||
return (
|
||||
<ContextMenu key={chat.id}>
|
||||
<ContextMenuTrigger asChild>
|
||||
<div
|
||||
onClick={() => onSwitchTab(tabIdx)}
|
||||
className={cn(
|
||||
'group flex items-center gap-1.5 px-3 py-1.5 text-xs border-r border-border cursor-default select-none shrink-0',
|
||||
isActive
|
||||
? 'bg-background text-foreground'
|
||||
: 'bg-muted/30 text-muted-foreground hover:bg-muted/60'
|
||||
)}
|
||||
>
|
||||
<MessageSquare size={12} className="shrink-0" />
|
||||
{renamingId === chat.id ? (
|
||||
<input
|
||||
autoFocus
|
||||
value={renameValue}
|
||||
onChange={(e) => setRenameValue(e.target.value)}
|
||||
onBlur={() => void finishRename()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void finishRename();
|
||||
if (e.key === 'Escape') setRenamingId(null);
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-transparent border-b border-border text-xs outline-none w-28"
|
||||
/>
|
||||
) : (
|
||||
<span className="truncate max-w-[140px]" title={label}>
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRemoveTab(chat.id);
|
||||
}}
|
||||
className="p-0.5 hover:bg-muted rounded opacity-0 group-hover:opacity-60 hover:!opacity-100 shrink-0"
|
||||
aria-label="Remove from tab bar"
|
||||
>
|
||||
<X size={10} />
|
||||
</button>
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={() => startRename(chat.id, chat.name)}>
|
||||
Rename
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => void onClose(chat.id)}>
|
||||
Close
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem
|
||||
variant="destructive"
|
||||
onSelect={() => setDeleteConfirm(chat.id)}
|
||||
>
|
||||
Delete
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Empty state label */}
|
||||
{tabs.length === 0 && (
|
||||
<div className="flex items-center gap-1.5 px-3 py-1.5 text-xs text-muted-foreground">
|
||||
<History size={12} className="shrink-0" />
|
||||
<span>Session</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="flex items-center ml-auto gap-0.5 px-1 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onNewChat}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
aria-label="New chat"
|
||||
title="New chat"
|
||||
>
|
||||
<Plus size={12} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onShowHistory}
|
||||
className={cn(
|
||||
'p-1 rounded text-muted-foreground hover:bg-muted hover:text-foreground',
|
||||
pane.kind === 'empty' && 'text-foreground bg-muted/50'
|
||||
)}
|
||||
aria-label="Session history"
|
||||
title="Session history"
|
||||
>
|
||||
<History size={12} />
|
||||
</button>
|
||||
{onRemovePane && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemovePane}
|
||||
className="p-1 rounded text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
aria-label="Close pane"
|
||||
title="Close pane"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Dialog open={deleteConfirm !== null} onOpenChange={(open) => { if (!open) setDeleteConfirm(null); }}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Delete chat</DialogTitle>
|
||||
<DialogDescription>
|
||||
This will permanently delete this chat and all its messages. This cannot be undone.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex gap-2 justify-end pt-2">
|
||||
<Button variant="outline" onClick={() => setDeleteConfirm(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={() => {
|
||||
if (deleteConfirm) void onDelete(deleteConfirm);
|
||||
setDeleteConfirm(null);
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
145
apps/web/src/components/FileMentionPopover.tsx
Normal file
145
apps/web/src/components/FileMentionPopover.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
files: string[];
|
||||
anchorRect: { top: number; left: number };
|
||||
onSelect: (path: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function filterAndRank(files: string[], query: string): string[] {
|
||||
const q = query.toLowerCase();
|
||||
if (!q) {
|
||||
return files.slice(0, 20);
|
||||
}
|
||||
|
||||
const filenameMatches: string[] = [];
|
||||
const pathOnlyMatches: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
const lower = file.toLowerCase();
|
||||
if (!lower.includes(q)) continue;
|
||||
const basename = file.split('/').pop() ?? file;
|
||||
if (basename.toLowerCase().includes(q)) {
|
||||
filenameMatches.push(file);
|
||||
} else {
|
||||
pathOnlyMatches.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
filenameMatches.sort((a, b) => a.localeCompare(b));
|
||||
pathOnlyMatches.sort((a, b) => a.localeCompare(b));
|
||||
|
||||
return [...filenameMatches, ...pathOnlyMatches].slice(0, 20);
|
||||
}
|
||||
|
||||
export function FileMentionPopover({
|
||||
query,
|
||||
files,
|
||||
anchorRect,
|
||||
onSelect,
|
||||
onClose,
|
||||
}: Props) {
|
||||
const [highlightIndex, setHighlightIndex] = useState(0);
|
||||
const popoverRef = useRef<HTMLDivElement>(null);
|
||||
const filtered = useMemo(() => filterAndRank(files, query), [files, query]);
|
||||
|
||||
// Reset highlight when query changes
|
||||
useEffect(() => {
|
||||
setHighlightIndex(0);
|
||||
}, [query]);
|
||||
|
||||
// Keyboard navigation
|
||||
useEffect(() => {
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
setHighlightIndex(prev =>
|
||||
prev < filtered.length - 1 ? prev + 1 : 0
|
||||
);
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
setHighlightIndex(prev =>
|
||||
prev > 0 ? prev - 1 : filtered.length - 1
|
||||
);
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (filtered.length > 0) {
|
||||
onSelect(filtered[highlightIndex] ?? filtered[0]!);
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||
}, [filtered, highlightIndex, onSelect, onClose]);
|
||||
|
||||
// Click outside to close
|
||||
useEffect(() => {
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (
|
||||
popoverRef.current &&
|
||||
!popoverRef.current.contains(e.target as Node)
|
||||
) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('mousedown', handleMouseDown);
|
||||
return () => document.removeEventListener('mousedown', handleMouseDown);
|
||||
}, [onClose]);
|
||||
|
||||
// Scroll highlighted item into view
|
||||
useEffect(() => {
|
||||
const el = popoverRef.current?.querySelector('[data-highlighted="true"]');
|
||||
if (el) {
|
||||
el.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [highlightIndex]);
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return (
|
||||
<div
|
||||
ref={popoverRef}
|
||||
className="fixed z-50 bg-popover border border-border rounded-md shadow min-w-[260px] p-2"
|
||||
style={{ top: anchorRect.top, left: anchorRect.left }}
|
||||
>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1">
|
||||
No matching files
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={popoverRef}
|
||||
className="fixed z-50 bg-popover border border-border rounded-md shadow min-w-[260px] max-h-[240px] overflow-y-auto"
|
||||
style={{ top: anchorRect.top, left: anchorRect.left }}
|
||||
>
|
||||
{filtered.map((file, i) => (
|
||||
<button
|
||||
key={file}
|
||||
type="button"
|
||||
data-highlighted={i === highlightIndex}
|
||||
className={cn(
|
||||
'w-full text-left text-xs font-mono px-2 py-1.5 cursor-pointer',
|
||||
i === highlightIndex && 'bg-muted'
|
||||
)}
|
||||
onMouseEnter={() => setHighlightIndex(i)}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
onSelect(file);
|
||||
}}
|
||||
>
|
||||
{file}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
241
apps/web/src/components/FileViewerOverlay.tsx
Normal file
241
apps/web/src/components/FileViewerOverlay.tsx
Normal file
@@ -0,0 +1,241 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Check, Copy, X, Paperclip } from 'lucide-react';
|
||||
import { codeToHtml } from 'shiki';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
path: string;
|
||||
content: string;
|
||||
lang: string | null;
|
||||
projectId: string;
|
||||
onClose: () => void;
|
||||
onNavigate: (path: string) => void;
|
||||
}
|
||||
|
||||
const SHIKI_THEME = 'github-dark';
|
||||
|
||||
function splitShikiLines(html: string): string[] {
|
||||
const match = html.match(/<code[^>]*>([\s\S]*)<\/code>/);
|
||||
if (!match) return [];
|
||||
const inner = match[1]!;
|
||||
const lines = inner.split(/(?=<span class="line">)/);
|
||||
return lines.filter(l => l.trim().length > 0);
|
||||
}
|
||||
|
||||
function basename(path: string): string {
|
||||
const parts = path.split('/');
|
||||
return parts[parts.length - 1] ?? path;
|
||||
}
|
||||
|
||||
export function FileViewerOverlay({ path, content, lang, onClose }: Props) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [lineHtmls, setLineHtmls] = useState<string[] | null>(null);
|
||||
const [selectedLines, setSelectedLines] = useState<Set<number>>(new Set());
|
||||
const [showAttachPopover, setShowAttachPopover] = useState(false);
|
||||
const draggingRef = useRef(false);
|
||||
const dragStartRef = useRef<number | null>(null);
|
||||
const overlayRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedLines(new Set());
|
||||
setShowAttachPopover(false);
|
||||
if (!lang) { setLineHtmls(null); return; }
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const result = await codeToHtml(content, { lang, theme: SHIKI_THEME });
|
||||
if (!cancelled) {
|
||||
const lines = splitShikiLines(result);
|
||||
setLineHtmls(lines.length > 0 ? lines : null);
|
||||
}
|
||||
} catch { if (!cancelled) setLineHtmls(null); }
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [content, lang]);
|
||||
|
||||
const plainLines = content.split('\n');
|
||||
const totalLines = lineHtmls ? lineHtmls.length : plainLines.length;
|
||||
|
||||
async function copyAll() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(content);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1200);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
function handleLineMouseDown(lineNo: number, e: React.MouseEvent) {
|
||||
if (e.shiftKey && dragStartRef.current !== null) {
|
||||
const start = dragStartRef.current;
|
||||
const min = Math.min(start, lineNo);
|
||||
const max = Math.max(start, lineNo);
|
||||
const next = new Set<number>();
|
||||
for (let i = min; i <= max; i++) next.add(i);
|
||||
setSelectedLines(next);
|
||||
setShowAttachPopover(true);
|
||||
return;
|
||||
}
|
||||
draggingRef.current = true;
|
||||
dragStartRef.current = lineNo;
|
||||
setSelectedLines(new Set([lineNo]));
|
||||
setShowAttachPopover(false);
|
||||
}
|
||||
|
||||
function handleLineMouseEnter(lineNo: number) {
|
||||
if (!draggingRef.current || dragStartRef.current === null) return;
|
||||
const start = dragStartRef.current;
|
||||
const min = Math.min(start, lineNo);
|
||||
const max = Math.max(start, lineNo);
|
||||
const next = new Set<number>();
|
||||
for (let i = min; i <= max; i++) next.add(i);
|
||||
setSelectedLines(next);
|
||||
}
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
if (draggingRef.current) {
|
||||
draggingRef.current = false;
|
||||
if (selectedLines.size > 0) setShowAttachPopover(true);
|
||||
}
|
||||
}, [selectedLines.size]);
|
||||
|
||||
useEffect(() => {
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
return () => document.removeEventListener('mouseup', handleMouseUp);
|
||||
}, [handleMouseUp]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClick(e: MouseEvent) {
|
||||
if (overlayRef.current && !overlayRef.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClick);
|
||||
return () => document.removeEventListener('mousedown', handleClick);
|
||||
}, [onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleKey(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') onClose();
|
||||
}
|
||||
document.addEventListener('keydown', handleKey);
|
||||
return () => document.removeEventListener('keydown', handleKey);
|
||||
}, [onClose]);
|
||||
|
||||
function getSelectionRange(): { min: number; max: number } | null {
|
||||
if (selectedLines.size === 0) return null;
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
for (const n of selectedLines) {
|
||||
if (n < min) min = n;
|
||||
if (n > max) max = n;
|
||||
}
|
||||
return { min, max };
|
||||
}
|
||||
|
||||
function handleAttach() {
|
||||
const range = getSelectionRange();
|
||||
if (!range) return;
|
||||
const lines = content.split('\n').slice(range.min - 1, range.max);
|
||||
sessionEvents.emit({
|
||||
type: 'attach_chat_file',
|
||||
attachment: {
|
||||
kind: 'lines',
|
||||
filename: path,
|
||||
language: lang,
|
||||
content: lines.join('\n'),
|
||||
range: [range.min, range.max],
|
||||
source: 'line-select',
|
||||
},
|
||||
});
|
||||
setSelectedLines(new Set());
|
||||
setShowAttachPopover(false);
|
||||
}
|
||||
|
||||
const range = getSelectionRange();
|
||||
const attachLabel = range
|
||||
? range.min === range.max
|
||||
? `Attach line ${range.min} to chat`
|
||||
: `Attach lines ${range.min}–${range.max} to chat`
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-12 pb-12">
|
||||
<div className="absolute inset-0 bg-black/40" />
|
||||
<div
|
||||
ref={overlayRef}
|
||||
className="relative bg-background border rounded-lg shadow-xl flex flex-col w-[80vw] max-w-[1000px] max-h-[80vh] overflow-hidden"
|
||||
>
|
||||
<div className="flex items-center gap-2 px-4 py-2 border-b shrink-0">
|
||||
<span className="text-sm font-medium truncate flex-1" title={path}>
|
||||
{basename(path)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground truncate">{path}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copyAll()}
|
||||
className="flex items-center gap-1 text-xs px-2 py-1 rounded hover:bg-muted"
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="p-1 rounded hover:bg-muted"
|
||||
aria-label="Close"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Shiki-highlighted code lines are generated from source code files, not user content */}
|
||||
<div className="flex-1 overflow-auto text-sm font-mono select-none">
|
||||
{Array.from({ length: totalLines }, (_, i) => {
|
||||
const lineNo = i + 1;
|
||||
const isSelected = selectedLines.has(lineNo);
|
||||
return (
|
||||
<div
|
||||
key={lineNo}
|
||||
className={cn('flex', isSelected && 'bg-blue-500/10')}
|
||||
onMouseDown={(e) => handleLineMouseDown(lineNo, e)}
|
||||
onMouseEnter={() => handleLineMouseEnter(lineNo)}
|
||||
>
|
||||
<div
|
||||
className="shrink-0 w-[3.5ch] text-right pr-2 text-xs text-muted-foreground select-none cursor-pointer hover:text-foreground"
|
||||
style={{ fontVariantNumeric: 'tabular-nums' }}
|
||||
>
|
||||
{lineNo}
|
||||
</div>
|
||||
{lineHtmls ? (
|
||||
<div
|
||||
className="flex-1 min-w-0 text-xs leading-relaxed [&>.line]:!bg-transparent"
|
||||
dangerouslySetInnerHTML={{ __html: lineHtmls[i] ?? '' }}
|
||||
/>
|
||||
) : (
|
||||
<span className="flex-1 min-w-0 text-xs leading-relaxed whitespace-pre">
|
||||
{plainLines[i] ?? ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{showAttachPopover && range && (
|
||||
<div className="sticky bottom-0 border-t bg-background px-4 py-2 flex items-center gap-2">
|
||||
<Paperclip size={14} className="text-muted-foreground" />
|
||||
<span className="text-xs flex-1">{attachLabel}</span>
|
||||
<Button size="sm" onClick={handleAttach}>
|
||||
Attach
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => { setSelectedLines(new Set()); setShowAttachPopover(false); }}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,9 +2,9 @@ import { Children, cloneElement, isValidElement, useState } from 'react';
|
||||
import type { ReactElement, ReactNode } from 'react';
|
||||
import Markdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { Copy, RefreshCw, Check } from 'lucide-react';
|
||||
import { ChevronDown, ChevronRight, Copy, RefreshCw, Check, Share2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import type { Message } from '@/api/types';
|
||||
import type { Chat, Message } from '@/api/types';
|
||||
import { api } from '@/api/client';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
import { ToolCallCard } from './ToolCallCard';
|
||||
@@ -84,7 +84,7 @@ function linkifyChildren(children: ReactNode, keyPrefix = 'l'): ReactNode {
|
||||
|
||||
interface Props {
|
||||
message: Message;
|
||||
sessionId: string;
|
||||
sessionChats?: Chat[];
|
||||
}
|
||||
|
||||
function MarkdownBody({ content }: { content: string }) {
|
||||
@@ -193,10 +193,8 @@ function StatsLine({ message }: { message: Message }) {
|
||||
|
||||
function ActionRow({
|
||||
message,
|
||||
sessionId,
|
||||
}: {
|
||||
message: Message;
|
||||
sessionId: string;
|
||||
}) {
|
||||
const [justCopied, setJustCopied] = useState(false);
|
||||
const [regenerating, setRegenerating] = useState(false);
|
||||
@@ -215,7 +213,7 @@ function ActionRow({
|
||||
if (regenerating || message.status === 'streaming') return;
|
||||
setRegenerating(true);
|
||||
try {
|
||||
await api.messages.regenerate(sessionId, message.id);
|
||||
await api.messages.regenerate(message.chat_id, message.id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'regenerate failed');
|
||||
} finally {
|
||||
@@ -253,7 +251,101 @@ function ActionRow({
|
||||
);
|
||||
}
|
||||
|
||||
export function MessageBubble({ message, sessionId }: Props) {
|
||||
function CompactCard({ message, sessionChats }: { message: Message; sessionChats?: Chat[] }) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [shareOpen, setShareOpen] = useState(false);
|
||||
|
||||
const headerMatch = message.content.match(/^\[Context compacted — (\d+) messages summarized\]/);
|
||||
const headerText = headerMatch ? headerMatch[0] : 'Context compacted';
|
||||
const summaryText = headerMatch
|
||||
? message.content.slice(headerMatch[0].length).trim()
|
||||
: message.content;
|
||||
|
||||
async function handleCopy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(summaryText);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1200);
|
||||
} catch {
|
||||
toast.error('Copy failed');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleShareToChat(chatId: string) {
|
||||
try {
|
||||
await api.messages.send(chatId, summaryText);
|
||||
toast.success('Summary sent to chat');
|
||||
setShareOpen(false);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to share');
|
||||
}
|
||||
}
|
||||
|
||||
const otherChats = (sessionChats ?? []).filter(
|
||||
(c) => c.id !== message.chat_id && c.status === 'open'
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-muted/30 text-sm">
|
||||
<div className="flex items-center gap-2 px-3 py-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
className="flex items-center gap-1.5 flex-1 min-w-0 text-left text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
<span className="text-xs font-medium truncate">{headerText}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleCopy()}
|
||||
className="p-1 rounded hover:bg-muted text-muted-foreground"
|
||||
aria-label="Copy summary"
|
||||
>
|
||||
{copied ? <Check size={12} /> : <Copy size={12} />}
|
||||
</button>
|
||||
{otherChats.length > 0 && (
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShareOpen(!shareOpen)}
|
||||
className="p-1 rounded hover:bg-muted text-muted-foreground"
|
||||
aria-label="Send to chat"
|
||||
>
|
||||
<Share2 size={12} />
|
||||
</button>
|
||||
{shareOpen && (
|
||||
<div className="absolute right-0 top-full mt-1 z-50 bg-popover border rounded-md shadow-md min-w-[160px] py-1">
|
||||
{otherChats.map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
onClick={() => void handleShareToChat(c.id)}
|
||||
className="w-full text-left px-3 py-1.5 text-xs hover:bg-accent truncate"
|
||||
>
|
||||
{c.name ?? 'New chat'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{expanded && (
|
||||
<div className="px-3 pb-3 text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap border-t pt-2">
|
||||
{summaryText}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MessageBubble({ message, sessionChats }: Props) {
|
||||
if (message.kind === 'compact') {
|
||||
return <CompactCard message={message} sessionChats={sessionChats} />;
|
||||
}
|
||||
|
||||
if (message.role === 'tool') {
|
||||
return <ToolCallCard message={message} />;
|
||||
}
|
||||
@@ -264,7 +356,7 @@ export function MessageBubble({ message, sessionId }: Props) {
|
||||
<div className="max-w-[80%] rounded-lg bg-primary text-primary-foreground px-3 py-2 text-sm whitespace-pre-wrap">
|
||||
{message.content}
|
||||
</div>
|
||||
<ActionRow message={message} sessionId={sessionId} />
|
||||
<ActionRow message={message} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -292,7 +384,7 @@ export function MessageBubble({ message, sessionId }: Props) {
|
||||
)}
|
||||
{!isStreaming && <StatsLine message={message} />}
|
||||
{!isStreaming && (hasContent || hasToolCalls) && (
|
||||
<ActionRow message={message} sessionId={sessionId} />
|
||||
<ActionRow message={message} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { Message } from '@/api/types';
|
||||
import type { Chat, Message } from '@/api/types';
|
||||
import { MessageBubble } from './MessageBubble';
|
||||
|
||||
interface Props {
|
||||
messages: Message[];
|
||||
sessionId: string;
|
||||
sessionChats?: Chat[];
|
||||
}
|
||||
|
||||
export function MessageList({ messages, sessionId }: Props) {
|
||||
export function MessageList({ messages, sessionChats }: Props) {
|
||||
const endRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -25,7 +25,7 @@ export function MessageList({ messages, sessionId }: Props) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4 space-y-4">
|
||||
{messages.map((m) => (
|
||||
<MessageBubble key={m.id} message={m} sessionId={sessionId} />
|
||||
<MessageBubble key={m.id} message={m} sessionChats={sessionChats} />
|
||||
))}
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
|
||||
@@ -9,6 +9,13 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
} from '@/components/ui/context-menu';
|
||||
import { AddProjectModal } from './AddProjectModal';
|
||||
import { api } from '@/api/client';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
@@ -91,6 +98,8 @@ export function ProjectSidebar() {
|
||||
useSidebar();
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [expanded, setExpanded] = useState<Set<string>>(() => readExpanded());
|
||||
const [renamingSession, setRenamingSession] = useState<string | null>(null);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const lastToastedError = useRef<string | null>(null);
|
||||
@@ -133,6 +142,28 @@ export function ProjectSidebar() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleArchiveSession(sessionId: string, projectId: string) {
|
||||
try {
|
||||
await api.sessions.archive(sessionId);
|
||||
sessionEvents.emit({ type: 'session_archived', session_id: sessionId, project_id: projectId });
|
||||
if (activeSession === sessionId) navigate(`/project/${projectId}`);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'failed to archive session');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRenameSession(sessionId: string) {
|
||||
const trimmed = renameValue.trim();
|
||||
setRenamingSession(null);
|
||||
if (!trimmed) return;
|
||||
try {
|
||||
await api.sessions.update(sessionId, { name: trimmed });
|
||||
sessionEvents.emit({ type: 'session_renamed', session_id: sessionId, name: trimmed });
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'failed to rename session');
|
||||
}
|
||||
}
|
||||
|
||||
const rowCls = (active: boolean) =>
|
||||
active ? 'bg-sidebar-accent text-sidebar-accent-foreground' : 'hover:bg-sidebar-accent/60';
|
||||
|
||||
@@ -225,17 +256,49 @@ export function ProjectSidebar() {
|
||||
{isExpanded && (
|
||||
<div className="ml-5 mt-0.5 space-y-0.5">
|
||||
{visible.map((s) => (
|
||||
<NavLink
|
||||
key={s.id}
|
||||
to={`/session/${s.id}`}
|
||||
className={`flex items-center gap-2 rounded-md px-2 py-1 text-sm min-w-0 ${rowCls(activeSession === s.id)}`}
|
||||
>
|
||||
<MessageSquare className="size-3.5 shrink-0 opacity-70" />
|
||||
<span className="truncate flex-1" title={s.name}>{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0 tabular-nums">
|
||||
{relTime(s.updated_at)}
|
||||
</span>
|
||||
</NavLink>
|
||||
<ContextMenu key={s.id}>
|
||||
<ContextMenuTrigger asChild>
|
||||
{renamingSession === s.id ? (
|
||||
<div className={`flex items-center gap-2 rounded-md px-2 py-1 text-sm min-w-0 ${rowCls(activeSession === s.id)}`}>
|
||||
<MessageSquare className="size-3.5 shrink-0 opacity-70" />
|
||||
<input
|
||||
autoFocus
|
||||
value={renameValue}
|
||||
onChange={(e) => setRenameValue(e.target.value)}
|
||||
onBlur={() => void handleRenameSession(s.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') void handleRenameSession(s.id);
|
||||
if (e.key === 'Escape') setRenamingSession(null);
|
||||
}}
|
||||
className="bg-transparent border-b border-border text-sm outline-none flex-1 min-w-0"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<NavLink
|
||||
to={`/session/${s.id}`}
|
||||
className={`flex items-center gap-2 rounded-md px-2 py-1 text-sm min-w-0 ${rowCls(activeSession === s.id)}`}
|
||||
>
|
||||
<MessageSquare className="size-3.5 shrink-0 opacity-70" />
|
||||
<span className="truncate flex-1" title={s.name}>{s.name}</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0 tabular-nums">
|
||||
{relTime(s.updated_at)}
|
||||
</span>
|
||||
</NavLink>
|
||||
)}
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onSelect={() => {
|
||||
setRenamingSession(s.id);
|
||||
setRenameValue(s.name);
|
||||
}}>
|
||||
Rename
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => void handleArchiveSession(s.id, p.id)}>
|
||||
Archive
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
))}
|
||||
{p.total_sessions > MAX_VISIBLE_SESSIONS && (
|
||||
<NavLink
|
||||
|
||||
264
apps/web/src/components/RightRail.tsx
Normal file
264
apps/web/src/components/RightRail.tsx
Normal file
@@ -0,0 +1,264 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { ChevronRight, ChevronDown, FileText, Folder, PanelRightClose, PanelRightOpen } from 'lucide-react';
|
||||
import { api } from '@/api/client';
|
||||
import type { FileEntry } from '@/api/types';
|
||||
import { inferLanguage } from '@/lib/attachments';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
import { FileViewerOverlay } from '@/components/FileViewerOverlay';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
interface Props {
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'boocode.rightrail';
|
||||
|
||||
function basename(path: string): string {
|
||||
if (!path) return '';
|
||||
const parts = path.split('/');
|
||||
return parts[parts.length - 1] ?? path;
|
||||
}
|
||||
|
||||
function joinPath(parent: string, name: string): string {
|
||||
if (!parent || parent === '.' || parent === '') return name;
|
||||
return `${parent}/${name}`;
|
||||
}
|
||||
|
||||
export function RightRail({ projectId }: Props) {
|
||||
const [open, setOpen] = useState(() => {
|
||||
try { return localStorage.getItem(`${STORAGE_KEY}.open`) !== 'false'; } catch { return true; }
|
||||
});
|
||||
const [filter, setFilter] = useState('');
|
||||
const [expandedDirs, setExpandedDirs] = useState<Set<string>>(new Set());
|
||||
const [cache, setCache] = useState<Map<string, FileEntry[]>>(new Map());
|
||||
const [fullFileList, setFullFileList] = useState<string[] | null>(null);
|
||||
const [viewerFile, setViewerFile] = useState<{ path: string; content: string } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
try { localStorage.setItem(`${STORAGE_KEY}.open`, String(open)); } catch {}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
api.projects.files(projectId).then((r) => {
|
||||
if (!cancelled) setFullFileList(r.files);
|
||||
}).catch(() => {});
|
||||
return () => { cancelled = true; };
|
||||
}, [projectId]);
|
||||
|
||||
const loadDir = useCallback(async (dirPath: string) => {
|
||||
const apiPath = dirPath === '' ? '.' : dirPath;
|
||||
try {
|
||||
const result = await api.projects.listDir(projectId, apiPath);
|
||||
setCache((prev) => { const next = new Map(prev); next.set(dirPath, result.entries); return next; });
|
||||
} catch { /* ignore */ }
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (!cache.has('')) void loadDir('');
|
||||
}, [open, cache, loadDir]);
|
||||
|
||||
function toggleDir(dirPath: string) {
|
||||
setExpandedDirs((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(dirPath)) {
|
||||
next.delete(dirPath);
|
||||
} else {
|
||||
next.add(dirPath);
|
||||
if (!cache.has(dirPath)) void loadDir(dirPath);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
async function openFile(path: string) {
|
||||
try {
|
||||
const result = await api.projects.viewFile(projectId, path);
|
||||
setViewerFile({ path, content: result.content });
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// Filter results
|
||||
const trimmed = filter.trim().toLowerCase();
|
||||
const filterActive = trimmed.length > 0;
|
||||
|
||||
interface FilterResult { path: string; name: string; }
|
||||
|
||||
const filterResults = useMemo<FilterResult[]>(() => {
|
||||
if (!filterActive) return [];
|
||||
if (fullFileList) {
|
||||
const filenameMatches: string[] = [];
|
||||
const pathOnly: string[] = [];
|
||||
for (const p of fullFileList) {
|
||||
const lp = p.toLowerCase();
|
||||
if (!lp.includes(trimmed)) continue;
|
||||
if (basename(p).toLowerCase().includes(trimmed)) filenameMatches.push(p);
|
||||
else pathOnly.push(p);
|
||||
}
|
||||
filenameMatches.sort((a, b) => a.localeCompare(b));
|
||||
pathOnly.sort((a, b) => a.localeCompare(b));
|
||||
return [...filenameMatches, ...pathOnly].slice(0, 50).map((p) => ({ path: p, name: basename(p) }));
|
||||
}
|
||||
return [];
|
||||
}, [filterActive, trimmed, fullFileList]);
|
||||
|
||||
// Listen for open_file_in_browser events
|
||||
useEffect(() => {
|
||||
return sessionEvents.subscribe((event) => {
|
||||
if (event.type !== 'open_file_in_browser') return;
|
||||
if (!open) setOpen(true);
|
||||
void openFile(event.path);
|
||||
});
|
||||
}, [open, projectId]);
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className="shrink-0 border-l bg-sidebar p-2 hover:bg-muted"
|
||||
aria-label="Open file browser"
|
||||
>
|
||||
<PanelRightOpen size={16} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const rootEntries = cache.get('') ?? [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside className="w-64 shrink-0 border-l bg-sidebar flex flex-col h-full overflow-hidden">
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b shrink-0">
|
||||
<span className="text-xs font-medium flex-1">Files</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
className="p-1 rounded hover:bg-muted text-muted-foreground"
|
||||
aria-label="Close file browser"
|
||||
>
|
||||
<PanelRightClose size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="px-2 py-1.5 shrink-0">
|
||||
<Input
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
placeholder="Filter files..."
|
||||
className="h-7 text-xs"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-1 py-1">
|
||||
{filterActive ? (
|
||||
filterResults.length > 0 ? (
|
||||
<ul className="list-none space-y-0.5">
|
||||
{filterResults.map((r) => (
|
||||
<li key={r.path}>
|
||||
<button
|
||||
type="button"
|
||||
className="w-full flex items-center gap-1 px-2 py-1 text-xs rounded hover:bg-muted/60 text-left"
|
||||
onClick={() => void openFile(r.path)}
|
||||
>
|
||||
<FileText size={12} className="text-muted-foreground shrink-0" />
|
||||
<span className="font-bold truncate">{r.name}</span>
|
||||
<span className="text-muted-foreground ml-1 truncate">{r.path}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground px-2 py-4 text-center">No matches</div>
|
||||
)
|
||||
) : (
|
||||
<TreeLevel
|
||||
parentPath=""
|
||||
entries={rootEntries}
|
||||
cache={cache}
|
||||
expanded={expandedDirs}
|
||||
depth={0}
|
||||
onToggleDir={toggleDir}
|
||||
onSelectFile={(path) => void openFile(path)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{viewerFile && (
|
||||
<FileViewerOverlay
|
||||
path={viewerFile.path}
|
||||
content={viewerFile.content}
|
||||
lang={inferLanguage(viewerFile.path)}
|
||||
projectId={projectId}
|
||||
onClose={() => setViewerFile(null)}
|
||||
onNavigate={(path) => void openFile(path)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface TreeLevelProps {
|
||||
parentPath: string;
|
||||
entries: FileEntry[];
|
||||
cache: Map<string, FileEntry[]>;
|
||||
expanded: Set<string>;
|
||||
depth: number;
|
||||
onToggleDir: (dirPath: string) => void;
|
||||
onSelectFile: (path: string) => void;
|
||||
}
|
||||
|
||||
function TreeLevel({ parentPath, entries, cache, expanded, depth, onToggleDir, onSelectFile }: TreeLevelProps) {
|
||||
const sorted = useMemo(() => {
|
||||
const copy = [...entries];
|
||||
copy.sort((a, b) => {
|
||||
if (a.kind !== b.kind) return a.kind === 'dir' ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
return copy;
|
||||
}, [entries]);
|
||||
|
||||
return (
|
||||
<ul className="list-none">
|
||||
{sorted.map((entry) => {
|
||||
const fullPath = joinPath(parentPath, entry.name);
|
||||
const isExpanded = entry.kind === 'dir' && expanded.has(fullPath);
|
||||
return (
|
||||
<li key={fullPath}>
|
||||
<div
|
||||
className="flex items-center gap-1 px-1 py-0.5 text-xs cursor-default rounded hover:bg-muted/60"
|
||||
style={{ paddingLeft: 4 + depth * 12 }}
|
||||
onClick={() => {
|
||||
if (entry.kind === 'dir') onToggleDir(fullPath);
|
||||
else onSelectFile(fullPath);
|
||||
}}
|
||||
>
|
||||
{entry.kind === 'dir' ? (
|
||||
isExpanded ? <ChevronDown size={10} className="shrink-0" /> : <ChevronRight size={10} className="shrink-0" />
|
||||
) : (
|
||||
<span className="w-[10px] shrink-0" />
|
||||
)}
|
||||
{entry.kind === 'dir' ? (
|
||||
<Folder size={12} className="text-muted-foreground shrink-0" />
|
||||
) : (
|
||||
<FileText size={12} className="text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{entry.name}</span>
|
||||
</div>
|
||||
{entry.kind === 'dir' && isExpanded && cache.has(fullPath) && (
|
||||
<TreeLevel
|
||||
parentPath={fullPath}
|
||||
entries={cache.get(fullPath) ?? []}
|
||||
cache={cache}
|
||||
expanded={expanded}
|
||||
depth={depth + 1}
|
||||
onToggleDir={onToggleDir}
|
||||
onSelectFile={onSelectFile}
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
155
apps/web/src/components/SessionLandingPage.tsx
Normal file
155
apps/web/src/components/SessionLandingPage.tsx
Normal file
@@ -0,0 +1,155 @@
|
||||
import { useState } from 'react';
|
||||
import { MessageSquare, Send, ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import type { Chat } from '@/api/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
projectId: string;
|
||||
chats: Chat[];
|
||||
onOpenChat: (chatId: string) => void;
|
||||
onSend: (content: string) => void;
|
||||
onReopenChat: (chatId: string) => Promise<void>;
|
||||
}
|
||||
|
||||
function relTime(iso: string): string {
|
||||
const now = Date.now();
|
||||
const t = Date.parse(iso);
|
||||
if (Number.isNaN(t)) return '';
|
||||
const sec = Math.max(0, Math.floor((now - t) / 1000));
|
||||
if (sec < 60) return `${sec}s ago`;
|
||||
const min = Math.floor(sec / 60);
|
||||
if (min < 60) return `${min}m ago`;
|
||||
const hr = Math.floor(min / 60);
|
||||
if (hr < 24) return `${hr}h ago`;
|
||||
const day = Math.floor(hr / 24);
|
||||
return `${day}d ago`;
|
||||
}
|
||||
|
||||
export function SessionLandingPage({
|
||||
chats,
|
||||
onOpenChat,
|
||||
onSend,
|
||||
onReopenChat,
|
||||
}: Props) {
|
||||
const [composerValue, setComposerValue] = useState('');
|
||||
const [showClosed, setShowClosed] = useState(false);
|
||||
|
||||
const openChats = chats
|
||||
.filter((c) => c.status === 'open')
|
||||
.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
|
||||
const closedChats = chats
|
||||
.filter((c) => c.status === 'closed')
|
||||
.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
|
||||
|
||||
function handleSend() {
|
||||
const text = composerValue.trim();
|
||||
if (!text) return;
|
||||
onSend(text);
|
||||
setComposerValue('');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
|
||||
{/* Open chats */}
|
||||
{openChats.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-xs font-medium text-muted-foreground mb-2">Open chats</h3>
|
||||
<ul className="divide-y rounded-md border">
|
||||
{openChats.map((chat) => (
|
||||
<li key={chat.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onOpenChat(chat.id)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 hover:bg-muted/50 text-left"
|
||||
>
|
||||
<MessageSquare className="size-3.5 opacity-70 shrink-0" />
|
||||
<span className="truncate text-sm flex-1">
|
||||
{chat.name ?? 'New chat'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0 tabular-nums">
|
||||
{relTime(chat.updated_at)}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Closed chats */}
|
||||
{closedChats.length > 0 && (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowClosed(!showClosed)}
|
||||
className="flex items-center gap-1 text-xs font-medium text-muted-foreground mb-2 hover:text-foreground"
|
||||
>
|
||||
{showClosed ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
|
||||
Closed chats ({closedChats.length})
|
||||
</button>
|
||||
{showClosed && (
|
||||
<ul className="divide-y rounded-md border">
|
||||
{closedChats.map((chat) => (
|
||||
<li key={chat.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void onReopenChat(chat.id)}
|
||||
className="w-full flex items-center gap-2 px-3 py-2 hover:bg-muted/50 text-left"
|
||||
>
|
||||
<MessageSquare className="size-3.5 opacity-40 shrink-0" />
|
||||
<span className="truncate text-sm flex-1 text-muted-foreground">
|
||||
{chat.name ?? 'New chat'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0">
|
||||
Reopen
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{openChats.length === 0 && closedChats.length === 0 && (
|
||||
<div className="text-sm text-muted-foreground py-8 text-center">
|
||||
No chats yet. Type below to start a conversation.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Composer */}
|
||||
<div className="border-t px-4 py-3 flex items-end gap-2 shrink-0">
|
||||
<Textarea
|
||||
value={composerValue}
|
||||
onChange={(e) => setComposerValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSend();
|
||||
}
|
||||
}}
|
||||
placeholder="Start a new chat..."
|
||||
rows={2}
|
||||
className="resize-none min-h-[52px] max-h-[160px]"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
disabled={!composerValue.trim()}
|
||||
size="icon-lg"
|
||||
aria-label="Send"
|
||||
>
|
||||
<Send />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,18 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { DragEvent } from 'react';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { usePanes } from '@/hooks/usePanes';
|
||||
import { PanelRight, MessageSquare, Terminal, Bot } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/api/client';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
import type { FileBrowserPaneState, Pane, PaneKind } from '@/api/types';
|
||||
import { PaneTab } from '@/components/PaneTab';
|
||||
import { PaneShell } from '@/components/panes/PaneShell';
|
||||
import type { Chat, WorkspacePane } from '@/api/types';
|
||||
import { ChatPane } from '@/components/panes/ChatPane';
|
||||
import { FileBrowserPane } from '@/components/panes/FileBrowserPane';
|
||||
import { ChatTabBar } from '@/components/ChatTabBar';
|
||||
import { SessionLandingPage } from '@/components/SessionLandingPage';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
@@ -16,324 +21,341 @@ interface Props {
|
||||
}
|
||||
|
||||
const MAX_PANES = 5;
|
||||
const STORAGE_KEY = 'boocode.workspace.panes';
|
||||
|
||||
function PaneSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex items-center border-b border-border bg-muted/20 h-8" />
|
||||
<div className="flex-1 flex items-center justify-center text-xs text-muted-foreground">
|
||||
Loading panes...
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
function generateId(): string {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
|
||||
function PaneError({
|
||||
message,
|
||||
onRetry,
|
||||
}: {
|
||||
message: string;
|
||||
onRetry: () => void | Promise<void>;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col h-full items-center justify-center gap-2 text-sm">
|
||||
<span className="text-destructive">{message}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void onRetry()}
|
||||
className="text-xs underline text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
function emptyPane(): WorkspacePane {
|
||||
return { id: generateId(), kind: 'empty', chatIds: [], activeChatIdx: -1 };
|
||||
}
|
||||
|
||||
function chatPane(chatId: string): WorkspacePane {
|
||||
return { id: generateId(), kind: 'chat', chatId, chatIds: [chatId], activeChatIdx: 0 };
|
||||
}
|
||||
|
||||
function loadPanes(sessionId: string): WorkspacePane[] | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(`${STORAGE_KEY}.${sessionId}`);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as WorkspacePane[];
|
||||
if (!Array.isArray(parsed) || parsed.length === 0) return null;
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function savePanes(sessionId: string, panes: WorkspacePane[]): void {
|
||||
try {
|
||||
localStorage.setItem(`${STORAGE_KEY}.${sessionId}`, JSON.stringify(panes));
|
||||
} catch { /* quota or disabled */ }
|
||||
}
|
||||
|
||||
export function Workspace({ sessionId, projectId }: Props) {
|
||||
const { panes, loading, error, create, update, remove, refresh } =
|
||||
usePanes(sessionId);
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const draggingIdRef = useRef<string | null>(null);
|
||||
const [panes, setPanes] = useState<WorkspacePane[]>(() => {
|
||||
return loadPanes(sessionId) ?? [emptyPane()];
|
||||
});
|
||||
const [activePaneIdx, setActivePaneIdx] = useState(0);
|
||||
const [chats, setChats] = useState<Chat[]>([]);
|
||||
const chatsRef = useRef<Chat[]>([]);
|
||||
chatsRef.current = chats;
|
||||
|
||||
// Keep latest panes in a ref so the event-bus subscription doesn't need
|
||||
// to re-subscribe whenever the list changes (which would race with rapid
|
||||
// updates).
|
||||
const panesRef = useRef<Pane[] | null>(null);
|
||||
panesRef.current = panes;
|
||||
|
||||
// Default active: first pane (and reset if the active one disappears)
|
||||
useEffect(() => {
|
||||
if (!panes || panes.length === 0) {
|
||||
if (activeId !== null) setActiveId(null);
|
||||
return;
|
||||
}
|
||||
if (!panes.some((p) => p.id === activeId)) {
|
||||
setActiveId(panes[0]!.id);
|
||||
}
|
||||
}, [panes, activeId]);
|
||||
let cancelled = false;
|
||||
api.chats.listForSession(sessionId).then((list) => {
|
||||
if (cancelled) return;
|
||||
setChats(list);
|
||||
const openChat = list.find((c) => c.status === 'open');
|
||||
if (openChat) {
|
||||
setPanes((prev) => {
|
||||
if (prev.length === 1 && prev[0]!.kind === 'empty') {
|
||||
return [chatPane(openChat.id)];
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}
|
||||
}).catch(() => {});
|
||||
return () => { cancelled = true; };
|
||||
}, [sessionId]);
|
||||
|
||||
// Tracks an in-flight create() call so rapid open_file_in_browser events
|
||||
// don't race to each spawn a new file_browser pane. While a create is in
|
||||
// progress the subsequent events wait for it and update the same pane.
|
||||
const creatingRef = useRef<{ id: string; promise: Promise<string> } | null>(
|
||||
null
|
||||
);
|
||||
useEffect(() => {
|
||||
savePanes(sessionId, panes);
|
||||
}, [sessionId, panes]);
|
||||
|
||||
// Subscribe to open_file_in_browser events: focus an existing file_browser
|
||||
// pane (updating its open_file) or spawn one if room is available.
|
||||
useEffect(() => {
|
||||
return sessionEvents.subscribe((event) => {
|
||||
if (event.type !== 'open_file_in_browser') return;
|
||||
void (async () => {
|
||||
// If a create is already in flight, wait for it to finish then update
|
||||
// the newly-created pane rather than spawning a second one.
|
||||
if (creatingRef.current) {
|
||||
const { id: pendingId, promise } = creatingRef.current;
|
||||
const resolvedId = await promise;
|
||||
const targetId = resolvedId || pendingId;
|
||||
const current = panesRef.current;
|
||||
const fb = current?.find((p) => p.id === targetId);
|
||||
const nextState: FileBrowserPaneState = {
|
||||
...(fb?.kind === 'file_browser' ? fb.state : {}),
|
||||
open_file: event.path,
|
||||
};
|
||||
await update(targetId, { state: nextState });
|
||||
setActiveId(targetId);
|
||||
return;
|
||||
}
|
||||
|
||||
const current = panesRef.current;
|
||||
if (!current) return;
|
||||
const fb = current.find(
|
||||
(p): p is Pane & { kind: 'file_browser' } =>
|
||||
p.kind === 'file_browser'
|
||||
);
|
||||
if (fb) {
|
||||
const nextState: FileBrowserPaneState = {
|
||||
...fb.state,
|
||||
open_file: event.path,
|
||||
};
|
||||
await update(fb.id, { state: nextState });
|
||||
setActiveId(fb.id);
|
||||
} else if (current.length < MAX_PANES) {
|
||||
// Reserve the slot immediately so concurrent events see the flag.
|
||||
const createPromise = (async (): Promise<string> => {
|
||||
const newPane = await create({ kind: 'file_browser' });
|
||||
return newPane.id;
|
||||
})();
|
||||
// Use a stable object; id is filled in once resolved.
|
||||
const entry: { id: string; promise: Promise<string> } = {
|
||||
id: '',
|
||||
promise: createPromise,
|
||||
};
|
||||
creatingRef.current = entry;
|
||||
try {
|
||||
const newId = await createPromise;
|
||||
entry.id = newId;
|
||||
const nextState: FileBrowserPaneState = {
|
||||
open_file: event.path,
|
||||
filter: '',
|
||||
expanded_dirs: [],
|
||||
};
|
||||
await update(newId, { state: nextState });
|
||||
setActiveId(newId);
|
||||
} finally {
|
||||
if (creatingRef.current === entry) {
|
||||
creatingRef.current = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
if (event.type === 'chat_created' && event.session_id === sessionId) {
|
||||
setChats((prev) => [event.chat, ...prev]);
|
||||
}
|
||||
if (event.type === 'chat_updated') {
|
||||
setChats((prev) => prev.map((c) =>
|
||||
c.id === event.chat_id ? { ...c, name: event.name, updated_at: event.updated_at } : c
|
||||
));
|
||||
}
|
||||
if (event.type === 'chat_closed') {
|
||||
setChats((prev) => prev.map((c) =>
|
||||
c.id === event.chat_id ? { ...c, status: 'closed' as const } : c
|
||||
));
|
||||
removeChatFromPanes(event.chat_id);
|
||||
}
|
||||
});
|
||||
}, [create, update]);
|
||||
}, [sessionId]);
|
||||
|
||||
const handleClose = useCallback(
|
||||
async (id: string) => {
|
||||
try {
|
||||
await remove(id);
|
||||
} catch {
|
||||
/* error surfaced via hook state */
|
||||
function removeChatFromPanes(chatId: string) {
|
||||
setPanes((prev) => prev.map((p) => {
|
||||
const idx = p.chatIds.indexOf(chatId);
|
||||
if (idx < 0) return p;
|
||||
const nextIds = p.chatIds.filter((id) => id !== chatId);
|
||||
if (nextIds.length === 0) {
|
||||
return { ...p, kind: 'empty' as const, chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
||||
}
|
||||
},
|
||||
[remove]
|
||||
);
|
||||
const nextActiveIdx = Math.min(p.activeChatIdx, nextIds.length - 1);
|
||||
return {
|
||||
...p,
|
||||
chatIds: nextIds,
|
||||
activeChatIdx: nextActiveIdx,
|
||||
chatId: nextIds[nextActiveIdx],
|
||||
};
|
||||
}));
|
||||
}
|
||||
|
||||
const handleSplit = useCallback(
|
||||
async (afterIdx: number, kind: PaneKind) => {
|
||||
const current = panesRef.current;
|
||||
if (!current || current.length >= MAX_PANES) return;
|
||||
try {
|
||||
const created = await create({ kind, position: afterIdx + 1 });
|
||||
setActiveId(created.id);
|
||||
} catch {
|
||||
/* error surfaced via hook state */
|
||||
const openChatInPane = useCallback((paneIdx: number, chatId: string) => {
|
||||
setPanes((prev) => {
|
||||
const next = [...prev];
|
||||
const pane = next[paneIdx]!;
|
||||
const existing = pane.chatIds.indexOf(chatId);
|
||||
if (existing >= 0) {
|
||||
next[paneIdx] = { ...pane, kind: 'chat', chatId, activeChatIdx: existing };
|
||||
} else {
|
||||
const newIds = [...pane.chatIds, chatId];
|
||||
next[paneIdx] = {
|
||||
...pane,
|
||||
kind: 'chat',
|
||||
chatId,
|
||||
chatIds: newIds,
|
||||
activeChatIdx: newIds.length - 1,
|
||||
};
|
||||
}
|
||||
},
|
||||
[create]
|
||||
);
|
||||
|
||||
const handleCloseOthers = useCallback(
|
||||
async (id: string) => {
|
||||
const current = panesRef.current;
|
||||
if (!current) return;
|
||||
const targets = current.filter((p) => p.id !== id).map((p) => p.id);
|
||||
for (const targetId of targets) {
|
||||
try {
|
||||
await remove(targetId);
|
||||
} catch {
|
||||
// Stop on first failure to avoid cascading errors.
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
[remove]
|
||||
);
|
||||
|
||||
const handleCloseToRight = useCallback(
|
||||
async (idx: number) => {
|
||||
const current = panesRef.current;
|
||||
if (!current) return;
|
||||
const targets = current.slice(idx + 1).map((p) => p.id);
|
||||
for (const targetId of targets) {
|
||||
try {
|
||||
await remove(targetId);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
[remove]
|
||||
);
|
||||
|
||||
const handleCloseAll = useCallback(async () => {
|
||||
const current = panesRef.current;
|
||||
if (!current) return;
|
||||
const targets = current.map((p) => p.id);
|
||||
for (const targetId of targets) {
|
||||
try {
|
||||
await remove(targetId);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}, [remove]);
|
||||
|
||||
const handleAdd = useCallback(async () => {
|
||||
const current = panesRef.current;
|
||||
if (current && current.length >= MAX_PANES) return;
|
||||
try {
|
||||
const created = await create({ kind: 'chat' });
|
||||
setActiveId(created.id);
|
||||
} catch {
|
||||
/* error surfaced via hook state */
|
||||
}
|
||||
}, [create]);
|
||||
|
||||
const handleDragStart = useCallback(
|
||||
(id: string) => (e: DragEvent<HTMLDivElement>) => {
|
||||
draggingIdRef.current = id;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
e.dataTransfer.setData('text/plain', id);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleDragOver = useCallback((e: DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
return next;
|
||||
});
|
||||
setActivePaneIdx(paneIdx);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(targetIdx: number) => async (e: DragEvent<HTMLDivElement>) => {
|
||||
e.preventDefault();
|
||||
const draggedId =
|
||||
draggingIdRef.current || e.dataTransfer.getData('text/plain');
|
||||
draggingIdRef.current = null;
|
||||
if (!draggedId) return;
|
||||
const current = panesRef.current;
|
||||
if (!current) return;
|
||||
const draggedIdx = current.findIndex((p) => p.id === draggedId);
|
||||
if (draggedIdx < 0 || draggedIdx === targetIdx) return;
|
||||
try {
|
||||
await update(draggedId, { position: targetIdx });
|
||||
} catch {
|
||||
/* error surfaced via hook state */
|
||||
}
|
||||
},
|
||||
[update]
|
||||
);
|
||||
const switchTab = useCallback((paneIdx: number, tabIdx: number) => {
|
||||
setPanes((prev) => {
|
||||
const next = [...prev];
|
||||
const pane = next[paneIdx]!;
|
||||
const chatId = pane.chatIds[tabIdx];
|
||||
if (!chatId) return prev;
|
||||
next[paneIdx] = { ...pane, chatId, activeChatIdx: tabIdx };
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (loading && !panes) return <PaneSkeleton />;
|
||||
if (error && !panes) return <PaneError message={error} onRetry={refresh} />;
|
||||
if (!panes) return <PaneSkeleton />;
|
||||
const removeTab = useCallback((paneIdx: number, chatId: string) => {
|
||||
setPanes((prev) => {
|
||||
const next = [...prev];
|
||||
const pane = next[paneIdx]!;
|
||||
const nextIds = pane.chatIds.filter((id) => id !== chatId);
|
||||
if (nextIds.length === 0) {
|
||||
next[paneIdx] = { ...pane, kind: 'empty', chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
||||
} else {
|
||||
const nextActiveIdx = Math.min(pane.activeChatIdx, nextIds.length - 1);
|
||||
next[paneIdx] = {
|
||||
...pane,
|
||||
chatIds: nextIds,
|
||||
activeChatIdx: nextActiveIdx,
|
||||
chatId: nextIds[nextActiveIdx],
|
||||
};
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const createChat = useCallback(async (paneIdx: number) => {
|
||||
try {
|
||||
const chat = await api.chats.create(sessionId);
|
||||
setChats((prev) => [chat, ...prev]);
|
||||
sessionEvents.emit({ type: 'chat_created', chat, session_id: sessionId });
|
||||
openChatInPane(paneIdx, chat.id);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to create chat');
|
||||
}
|
||||
}, [sessionId, openChatInPane]);
|
||||
|
||||
const closeChat = useCallback(async (chatId: string) => {
|
||||
try {
|
||||
await api.chats.update(chatId, { status: 'closed' });
|
||||
setChats((prev) => prev.map((c) =>
|
||||
c.id === chatId ? { ...c, status: 'closed' as const } : c
|
||||
));
|
||||
removeChatFromPanes(chatId);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to close chat');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const deleteChat = useCallback(async (chatId: string) => {
|
||||
try {
|
||||
await api.chats.remove(chatId);
|
||||
setChats((prev) => prev.filter((c) => c.id !== chatId));
|
||||
removeChatFromPanes(chatId);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to delete chat');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const renameChat = useCallback(async (chatId: string, name: string) => {
|
||||
try {
|
||||
await api.chats.update(chatId, { name });
|
||||
setChats((prev) => prev.map((c) =>
|
||||
c.id === chatId ? { ...c, name } : c
|
||||
));
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to rename chat');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const showLandingPage = useCallback((paneIdx: number) => {
|
||||
setPanes((prev) => {
|
||||
const next = [...prev];
|
||||
const pane = next[paneIdx]!;
|
||||
next[paneIdx] = { ...pane, kind: 'empty', chatId: undefined };
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const addSplitPane = useCallback((kind: 'chat' | 'terminal' | 'agent') => {
|
||||
if (kind === 'terminal') {
|
||||
toast('Terminal panes coming in BooTerm');
|
||||
return;
|
||||
}
|
||||
if (kind === 'agent') {
|
||||
toast('Agent panes coming in BooCoder');
|
||||
return;
|
||||
}
|
||||
setPanes((prev) => {
|
||||
if (prev.length >= MAX_PANES) {
|
||||
toast.error(`Maximum ${MAX_PANES} panes`);
|
||||
return prev;
|
||||
}
|
||||
const next = [...prev, emptyPane()];
|
||||
setActivePaneIdx(next.length - 1);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const removePane = useCallback((idx: number) => {
|
||||
setPanes((prev) => {
|
||||
if (prev.length <= 1) return prev;
|
||||
const next = prev.filter((_, i) => i !== idx);
|
||||
setActivePaneIdx((ai) => Math.min(ai, next.length - 1));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleLandingSend = useCallback(async (paneIdx: number, content: string) => {
|
||||
try {
|
||||
const chat = await api.chats.create(sessionId);
|
||||
setChats((prev) => [chat, ...prev]);
|
||||
sessionEvents.emit({ type: 'chat_created', chat, session_id: sessionId });
|
||||
openChatInPane(paneIdx, chat.id);
|
||||
await api.messages.send(chat.id, content);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to send');
|
||||
}
|
||||
}, [sessionId, openChatInPane]);
|
||||
|
||||
function chatsForPane(pane: WorkspacePane): Chat[] {
|
||||
return pane.chatIds
|
||||
.map((id) => chats.find((c) => c.id === id))
|
||||
.filter((c): c is Chat => c !== undefined);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="flex items-center gap-2 border-b border-border bg-muted/20 px-3 py-1.5 shrink-0">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
disabled={panes.length >= MAX_PANES}
|
||||
className={cn(
|
||||
'flex items-center gap-1 text-xs px-2 py-1 rounded hover:bg-muted',
|
||||
panes.length >= MAX_PANES && 'opacity-40 cursor-not-allowed hover:bg-transparent'
|
||||
)}
|
||||
>
|
||||
<PanelRight size={14} />
|
||||
Split
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onSelect={() => addSplitPane('chat')}>
|
||||
<MessageSquare size={14} /> Chat
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => addSplitPane('terminal')}>
|
||||
<Terminal size={14} /> Terminal
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => addSplitPane('agent')}>
|
||||
<Bot size={14} /> Agent
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex items-center border-b border-border bg-muted/20"
|
||||
role="tablist"
|
||||
className="flex-1 grid min-h-0"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${panes.length}, minmax(0, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{panes.map((pane, idx) => (
|
||||
<PaneTab
|
||||
<div
|
||||
key={pane.id}
|
||||
pane={pane}
|
||||
isActive={pane.id === activeId}
|
||||
onClick={() => setActiveId(pane.id)}
|
||||
onClose={() => void handleClose(pane.id)}
|
||||
onSplit={(kind) => void handleSplit(idx, kind)}
|
||||
onCloseOthers={() => void handleCloseOthers(pane.id)}
|
||||
onCloseToRight={() => void handleCloseToRight(idx)}
|
||||
onCloseAll={() => void handleCloseAll()}
|
||||
onDragStart={handleDragStart(pane.id)}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop(idx)}
|
||||
/>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleAdd()}
|
||||
disabled={panes.length >= MAX_PANES}
|
||||
className={cn(
|
||||
'p-1.5 ml-1 rounded text-muted-foreground hover:bg-muted hover:text-foreground',
|
||||
panes.length >= MAX_PANES && 'opacity-40 cursor-not-allowed hover:bg-transparent'
|
||||
)}
|
||||
aria-label="Add pane"
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{panes.length === 0 ? (
|
||||
<div className="flex-1 flex items-center justify-center text-xs text-muted-foreground">
|
||||
No panes. Click + to add one.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="flex-1 grid min-h-0"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${panes.length}, minmax(0, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{panes.map((pane) => (
|
||||
<PaneShell
|
||||
key={pane.id}
|
||||
className={cn(
|
||||
'flex flex-col h-full min-h-0 border-r border-border last:border-r-0',
|
||||
idx === activePaneIdx && 'ring-1 ring-inset ring-ring/20'
|
||||
)}
|
||||
onClick={() => setActivePaneIdx(idx)}
|
||||
>
|
||||
<ChatTabBar
|
||||
pane={pane}
|
||||
onClose={() => void handleClose(pane.id)}
|
||||
>
|
||||
{pane.kind === 'chat' ? (
|
||||
<ChatPane sessionId={sessionId} />
|
||||
tabs={chatsForPane(pane)}
|
||||
onSwitchTab={(tabIdx) => switchTab(idx, tabIdx)}
|
||||
onRemoveTab={(chatId) => removeTab(idx, chatId)}
|
||||
onNewChat={() => void createChat(idx)}
|
||||
onShowHistory={() => showLandingPage(idx)}
|
||||
onRename={renameChat}
|
||||
onClose={closeChat}
|
||||
onDelete={deleteChat}
|
||||
onRemovePane={panes.length > 1 ? () => removePane(idx) : undefined}
|
||||
/>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-hidden">
|
||||
{pane.kind === 'chat' && pane.chatId ? (
|
||||
<ChatPane sessionId={sessionId} chatId={pane.chatId} projectId={projectId} sessionChats={chats} />
|
||||
) : (
|
||||
<FileBrowserPane
|
||||
pane={pane}
|
||||
<SessionLandingPage
|
||||
sessionId={sessionId}
|
||||
projectId={projectId}
|
||||
onStateChange={(state) =>
|
||||
void update(pane.id, { state })
|
||||
}
|
||||
chats={chats}
|
||||
onOpenChat={(chatId) => openChatInPane(idx, chatId)}
|
||||
onSend={(content) => void handleLandingSend(idx, content)}
|
||||
onReopenChat={async (chatId) => {
|
||||
await api.chats.update(chatId, { status: 'open' });
|
||||
setChats((prev) => prev.map((c) =>
|
||||
c.id === chatId ? { ...c, status: 'open' as const } : c
|
||||
));
|
||||
openChatInPane(idx, chatId);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</PaneShell>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ChevronDown, Square, X } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/api/client';
|
||||
import { useSessionStream } from '@/hooks/useSessionStream';
|
||||
import { MessageList } from '@/components/MessageList';
|
||||
import { ChatInput } from '@/components/ChatInput';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
chatId: string;
|
||||
projectId: string;
|
||||
sessionChats?: import('@/api/types').Chat[];
|
||||
}
|
||||
|
||||
export function ChatPane({ sessionId }: Props) {
|
||||
export function ChatPane({ sessionId, chatId, projectId, sessionChats }: Props) {
|
||||
const stream = useSessionStream(sessionId);
|
||||
const lastErrorRef = useRef<string | null>(null);
|
||||
const [queue, setQueue] = useState<string[]>([]);
|
||||
const processingRef = useRef(false);
|
||||
|
||||
// Surface stream errors via toast — matches Session.tsx behavior.
|
||||
useEffect(() => {
|
||||
if (stream.error && stream.error !== lastErrorRef.current) {
|
||||
lastErrorRef.current = stream.error;
|
||||
@@ -24,16 +35,130 @@ export function ChatPane({ sessionId }: Props) {
|
||||
}
|
||||
}, [stream.error]);
|
||||
|
||||
async function handleSend(content: string) {
|
||||
await api.messages.send(sessionId, content);
|
||||
const chatMessages = stream.messages.filter((m) => m.chat_id === chatId);
|
||||
const streaming = chatMessages.some((m) => m.status === 'streaming');
|
||||
|
||||
// Auto-send next queued message when streaming completes
|
||||
useEffect(() => {
|
||||
if (streaming || queue.length === 0 || processingRef.current) return;
|
||||
processingRef.current = true;
|
||||
const next = queue[0]!;
|
||||
setQueue((prev) => prev.slice(1));
|
||||
api.messages.send(chatId, next)
|
||||
.catch((err) => toast.error(err instanceof Error ? err.message : 'queue send failed'))
|
||||
.finally(() => { processingRef.current = false; });
|
||||
}, [streaming, queue, chatId]);
|
||||
|
||||
const handleSend = useCallback(async (content: string) => {
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed) return;
|
||||
if (trimmed === '/compact') {
|
||||
try {
|
||||
await api.chats.compact(chatId);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'compact failed');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (streaming) {
|
||||
setQueue((prev) => [...prev, trimmed]);
|
||||
return;
|
||||
}
|
||||
await api.messages.send(chatId, trimmed);
|
||||
}, [chatId, streaming]);
|
||||
|
||||
async function handleStop() {
|
||||
try {
|
||||
await api.chats.stop(chatId);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'stop failed');
|
||||
}
|
||||
}
|
||||
|
||||
const streaming = stream.messages.some((m) => m.status === 'streaming');
|
||||
const handleForceSend = useCallback(async (content: string) => {
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed) return;
|
||||
try {
|
||||
await api.chats.forceSend(chatId, trimmed);
|
||||
setQueue([]);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'force send failed');
|
||||
}
|
||||
}, [chatId]);
|
||||
|
||||
function removeQueued(idx: number) {
|
||||
setQueue((prev) => prev.filter((_, i) => i !== idx));
|
||||
}
|
||||
|
||||
async function forceSendQueued(idx: number) {
|
||||
const msg = queue[idx];
|
||||
if (!msg) return;
|
||||
setQueue((prev) => prev.filter((_, i) => i !== idx));
|
||||
try {
|
||||
await api.chats.forceSend(chatId, msg);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'force send failed');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<MessageList messages={stream.messages} sessionId={sessionId} />
|
||||
<ChatInput disabled={streaming} onSend={handleSend} />
|
||||
<MessageList messages={chatMessages} sessionChats={sessionChats} />
|
||||
|
||||
{/* Queued messages */}
|
||||
{queue.length > 0 && (
|
||||
<div className="px-4 py-1 border-t space-y-1">
|
||||
{queue.map((msg, i) => (
|
||||
<div key={i} className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/30 rounded px-2 py-1">
|
||||
<span className="font-medium shrink-0">Queued:</span>
|
||||
<span className="truncate flex-1">{msg}</span>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="p-0.5 hover:bg-muted rounded shrink-0"
|
||||
aria-label="Queued message options"
|
||||
>
|
||||
<ChevronDown size={12} />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onSelect={() => { /* default: queued, nothing to do */ }}>
|
||||
Send when done
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => void forceSendQueued(i)}>
|
||||
Force send now
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeQueued(i)}
|
||||
className="p-0.5 hover:bg-muted rounded shrink-0"
|
||||
aria-label="Cancel queued message"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stop button when streaming */}
|
||||
{streaming && (
|
||||
<div className="flex justify-center py-1 border-t">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void handleStop()}
|
||||
className="flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border hover:bg-muted text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<Square size={10} className="fill-current" />
|
||||
Stop generating
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ChatInput disabled={false} projectId={projectId} onSend={handleSend} onForceSend={streaming ? handleForceSend : undefined} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { KeyboardEvent } from 'react';
|
||||
import { ChevronRight, ChevronDown, FileText, Folder, X } from 'lucide-react';
|
||||
import { Check, ChevronRight, ChevronDown, Copy, FileText, Folder, X } from 'lucide-react';
|
||||
import { codeToHtml } from 'shiki';
|
||||
import { api, ApiError } from '@/api/client';
|
||||
import type {
|
||||
FileBrowserPaneState,
|
||||
@@ -8,7 +9,8 @@ import type {
|
||||
Pane,
|
||||
ViewFileResult,
|
||||
} from '@/api/types';
|
||||
import { CodeBlock } from '@/components/CodeBlock';
|
||||
import { inferLanguage } from '@/lib/attachments';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface Props {
|
||||
@@ -17,49 +19,113 @@ interface Props {
|
||||
onStateChange: (state: FileBrowserPaneState) => void;
|
||||
}
|
||||
|
||||
const LANG_BY_EXT: Record<string, string> = {
|
||||
ts: 'typescript',
|
||||
tsx: 'tsx',
|
||||
js: 'javascript',
|
||||
jsx: 'jsx',
|
||||
mjs: 'javascript',
|
||||
cjs: 'javascript',
|
||||
py: 'python',
|
||||
go: 'go',
|
||||
rs: 'rust',
|
||||
rb: 'ruby',
|
||||
java: 'java',
|
||||
c: 'c',
|
||||
h: 'c',
|
||||
cpp: 'cpp',
|
||||
hpp: 'cpp',
|
||||
cs: 'csharp',
|
||||
php: 'php',
|
||||
sh: 'bash',
|
||||
bash: 'bash',
|
||||
zsh: 'bash',
|
||||
yaml: 'yaml',
|
||||
yml: 'yaml',
|
||||
json: 'json',
|
||||
toml: 'toml',
|
||||
md: 'markdown',
|
||||
markdown: 'markdown',
|
||||
sql: 'sql',
|
||||
dockerfile: 'dockerfile',
|
||||
html: 'html',
|
||||
htm: 'html',
|
||||
css: 'css',
|
||||
scss: 'scss',
|
||||
};
|
||||
const SHIKI_THEME = 'github-dark';
|
||||
|
||||
function deriveLang(filePath: string): string | undefined {
|
||||
// basename
|
||||
const base = filePath.split('/').pop() ?? filePath;
|
||||
if (base.toLowerCase() === 'dockerfile') return 'dockerfile';
|
||||
const dot = base.lastIndexOf('.');
|
||||
if (dot < 0 || dot === base.length - 1) return undefined;
|
||||
const ext = base.slice(dot + 1).toLowerCase();
|
||||
return LANG_BY_EXT[ext];
|
||||
function splitShikiLines(html: string): string[] {
|
||||
const match = html.match(/<code[^>]*>([\s\S]*)<\/code>/);
|
||||
if (!match) return [];
|
||||
const inner = match[1]!;
|
||||
const lines = inner.split(/(?=<span class="line">)/);
|
||||
return lines.filter(l => l.trim().length > 0);
|
||||
}
|
||||
|
||||
interface FileViewerProps {
|
||||
code: string;
|
||||
lang: string | null;
|
||||
selectedLines: Set<number>;
|
||||
onLineClick: (lineNo: number, shiftKey: boolean) => void;
|
||||
}
|
||||
|
||||
function FileViewer({ code, lang, selectedLines, onLineClick }: FileViewerProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [lineHtmls, setLineHtmls] = useState<string[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (!lang) {
|
||||
setLineHtmls(null);
|
||||
return;
|
||||
}
|
||||
(async () => {
|
||||
try {
|
||||
const result = await codeToHtml(code, { lang, theme: SHIKI_THEME });
|
||||
if (cancelled) return;
|
||||
const lines = splitShikiLines(result);
|
||||
setLineHtmls(lines.length > 0 ? lines : null);
|
||||
} catch (err) {
|
||||
console.warn('shiki failed', err);
|
||||
if (!cancelled) setLineHtmls(null);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [code, lang]);
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1200);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
const plainLines = code.split('\n');
|
||||
const totalLines = lineHtmls ? lineHtmls.length : plainLines.length;
|
||||
|
||||
return (
|
||||
<div className="text-sm font-mono">
|
||||
<div className="flex items-center justify-between px-2 py-1 border-b text-xs text-muted-foreground">
|
||||
<span className="font-mono">{lang || 'code'}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void copy()}
|
||||
className="flex items-center gap-1 px-1.5 py-0.5 rounded hover:bg-muted text-foreground"
|
||||
aria-label="Copy code"
|
||||
>
|
||||
{copied ? <Check className="size-3" /> : <Copy className="size-3" />}
|
||||
<span>{copied ? 'Copied' : 'Copy'}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
{Array.from({ length: totalLines }, (_, i) => {
|
||||
const lineNo = i + 1;
|
||||
const isSelected = selectedLines.has(lineNo);
|
||||
return (
|
||||
<div
|
||||
key={lineNo}
|
||||
className={cn(
|
||||
'flex',
|
||||
isSelected && 'bg-blue-500/10'
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 w-[3ch] text-right pr-2 text-xs text-muted-foreground select-none cursor-pointer hover:text-foreground"
|
||||
style={{ fontVariantNumeric: 'tabular-nums' }}
|
||||
onClick={(e) => onLineClick(lineNo, e.shiftKey)}
|
||||
>
|
||||
{lineNo}
|
||||
</button>
|
||||
{lineHtmls ? (
|
||||
<div
|
||||
className="flex-1 min-w-0 text-xs leading-relaxed [&>.line]:!bg-transparent"
|
||||
// eslint-disable-next-line react/no-danger -- Shiki generates sanitized HTML spans, not user content
|
||||
dangerouslySetInnerHTML={{ __html: lineHtmls[i] ?? '' }}
|
||||
/>
|
||||
) : (
|
||||
<span className="flex-1 min-w-0 text-xs leading-relaxed whitespace-pre">
|
||||
{plainLines[i] ?? ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function basename(path: string): string {
|
||||
@@ -230,6 +296,26 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Full file list fetched once on mount for filter mode (covers unexpanded dirs)
|
||||
const [fullFileList, setFullFileList] = useState<string[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const result = await api.projects.files(projectId);
|
||||
if (!cancelled) setFullFileList(result.files);
|
||||
} catch {
|
||||
// Silently ignore; filter will fall back to cache-based list
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// Intentionally run once per mount (projectId is stable per pane)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [projectId]);
|
||||
|
||||
// Directory cache: dirPath -> entries
|
||||
const [cache, setCache] = useState<Map<string, FileEntry[]>>(new Map());
|
||||
const [loadingDirs, setLoadingDirs] = useState<Set<string>>(new Set());
|
||||
@@ -380,11 +466,43 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
|
||||
const trimmedFilter = filterDraft.trim();
|
||||
const filterActive = trimmedFilter.length > 0;
|
||||
const filterResults = useMemo<FlatEntry[]>(() => {
|
||||
|
||||
interface FilterResult {
|
||||
path: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const filterResults = useMemo<FilterResult[]>(() => {
|
||||
if (!filterActive) return [];
|
||||
const needle = trimmedFilter.toLowerCase();
|
||||
return flattenedAll.filter((e) => e.path.toLowerCase().includes(needle));
|
||||
}, [filterActive, trimmedFilter, flattenedAll]);
|
||||
|
||||
if (fullFileList !== null) {
|
||||
// Use complete file list from API; rank filename matches above path-only matches
|
||||
const filenameMatches: string[] = [];
|
||||
const pathOnlyMatches: string[] = [];
|
||||
for (const p of fullFileList) {
|
||||
const lp = p.toLowerCase();
|
||||
if (!lp.includes(needle)) continue;
|
||||
const bn = basename(p).toLowerCase();
|
||||
if (bn.includes(needle)) {
|
||||
filenameMatches.push(p);
|
||||
} else {
|
||||
pathOnlyMatches.push(p);
|
||||
}
|
||||
}
|
||||
filenameMatches.sort((a, b) => a.localeCompare(b));
|
||||
pathOnlyMatches.sort((a, b) => a.localeCompare(b));
|
||||
return [...filenameMatches, ...pathOnlyMatches]
|
||||
.slice(0, 50)
|
||||
.map((p) => ({ path: p, name: basename(p) }));
|
||||
}
|
||||
|
||||
// Fallback: use cache-based flat list (only loaded directories, files only)
|
||||
return flattenedAll
|
||||
.filter((e) => e.kind === 'file' && e.path.toLowerCase().includes(needle))
|
||||
.slice(0, 50)
|
||||
.map((e) => ({ path: e.path, name: e.name }));
|
||||
}, [filterActive, trimmedFilter, fullFileList, flattenedAll]);
|
||||
|
||||
// Keyboard navigation
|
||||
const [highlightedPath, setHighlightedPath] = useState<string | null>(null);
|
||||
@@ -401,7 +519,38 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
}, [highlightedPath, filterActive, filterResults, flattenedVisible]);
|
||||
|
||||
function onTreeKeyDown(e: KeyboardEvent<HTMLDivElement>) {
|
||||
const list = filterActive ? filterResults : flattenedVisible;
|
||||
if (filterActive) {
|
||||
if (filterResults.length === 0) return;
|
||||
const idx = highlightedPath
|
||||
? filterResults.findIndex((entry) => entry.path === highlightedPath)
|
||||
: -1;
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
const next = idx < 0 ? 0 : Math.min(filterResults.length - 1, idx + 1);
|
||||
const target = filterResults[next];
|
||||
if (target) setHighlightedPath(target.path);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
const next = idx <= 0 ? 0 : idx - 1;
|
||||
const target = filterResults[next];
|
||||
if (target) setHighlightedPath(target.path);
|
||||
return;
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
if (idx < 0) return;
|
||||
const target = filterResults[idx];
|
||||
if (!target) return;
|
||||
e.preventDefault();
|
||||
// Filter results are always files (API returns only files)
|
||||
selectFile(target.path);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Tree mode: use flattenedVisible which has kind info
|
||||
const list = flattenedVisible;
|
||||
if (list.length === 0) return;
|
||||
const idx = highlightedPath
|
||||
? list.findIndex((entry) => entry.path === highlightedPath)
|
||||
@@ -434,6 +583,31 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
}
|
||||
}
|
||||
|
||||
// Line selection state
|
||||
const [selectedLines, setSelectedLines] = useState<Set<number>>(new Set());
|
||||
const [selectionAnchor, setSelectionAnchor] = useState<number | null>(null);
|
||||
|
||||
function handleLineClick(lineNo: number, shiftKey: boolean) {
|
||||
if (shiftKey && selectionAnchor !== null) {
|
||||
const start = Math.min(selectionAnchor, lineNo);
|
||||
const end = Math.max(selectionAnchor, lineNo);
|
||||
const range = new Set<number>();
|
||||
for (let i = start; i <= end; i++) range.add(i);
|
||||
setSelectedLines(range);
|
||||
} else {
|
||||
setSelectedLines(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(lineNo)) {
|
||||
next.delete(lineNo);
|
||||
} else {
|
||||
next.add(lineNo);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setSelectionAnchor(lineNo);
|
||||
}
|
||||
}
|
||||
|
||||
// Viewer state
|
||||
const [viewer, setViewer] = useState<{
|
||||
path: string;
|
||||
@@ -490,6 +664,45 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
};
|
||||
}, [openFile, projectId]);
|
||||
|
||||
// Clear line selection when open file changes
|
||||
useEffect(() => {
|
||||
setSelectedLines(new Set());
|
||||
setSelectionAnchor(null);
|
||||
}, [openFile]);
|
||||
|
||||
// Compute selection range for the floating action bar (loop avoids call-stack limit on spread)
|
||||
let selectionMin = 0;
|
||||
let selectionMax = 0;
|
||||
if (selectedLines.size > 0) {
|
||||
for (const n of selectedLines) {
|
||||
if (selectionMin === 0 || n < selectionMin) selectionMin = n;
|
||||
if (n > selectionMax) selectionMax = n;
|
||||
}
|
||||
}
|
||||
|
||||
function handleAttachLines() {
|
||||
if (!openFile || !viewer?.result || selectedLines.size === 0) return;
|
||||
const min = selectionMin;
|
||||
const max = selectionMax;
|
||||
const selectedContent = viewer.result.content
|
||||
.split('\n')
|
||||
.slice(min - 1, max)
|
||||
.join('\n');
|
||||
sessionEvents.emit({
|
||||
type: 'attach_chat_file',
|
||||
attachment: {
|
||||
kind: 'lines',
|
||||
filename: openFile,
|
||||
language: inferLanguage(openFile) ?? null,
|
||||
content: selectedContent,
|
||||
range: [min, max],
|
||||
source: 'line-select',
|
||||
},
|
||||
});
|
||||
setSelectedLines(new Set());
|
||||
setSelectionAnchor(null);
|
||||
}
|
||||
|
||||
// Root errors / loading
|
||||
const rootEntries = cache.get('');
|
||||
const rootLoading = loadingDirs.has('') && !rootEntries;
|
||||
@@ -534,8 +747,7 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
</li>
|
||||
) : (
|
||||
filterResults.map((entry) => {
|
||||
const isActive =
|
||||
entry.kind === 'file' && openFile === entry.path;
|
||||
const isActive = openFile === entry.path;
|
||||
const isHighlight = highlightedPath === entry.path;
|
||||
return (
|
||||
<li key={entry.path}>
|
||||
@@ -547,19 +759,14 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
)}
|
||||
onClick={() => {
|
||||
setHighlightedPath(entry.path);
|
||||
if (entry.kind === 'dir') {
|
||||
toggleDir(entry.path);
|
||||
} else {
|
||||
selectFile(entry.path);
|
||||
}
|
||||
selectFile(entry.path);
|
||||
}}
|
||||
>
|
||||
{entry.kind === 'dir' ? (
|
||||
<Folder size={12} className="text-muted-foreground shrink-0" />
|
||||
) : (
|
||||
<FileText size={12} className="text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<span className="truncate">{entry.path}</span>
|
||||
<FileText size={12} className="text-muted-foreground shrink-0" />
|
||||
<span className="truncate">
|
||||
<span className="font-bold">{entry.name}</span>
|
||||
<span className="text-muted-foreground ml-1">{entry.path}</span>
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -606,7 +813,7 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto relative">
|
||||
{viewer?.state === 'loading' && (
|
||||
<div className="text-xs text-muted-foreground px-2 py-1.5">
|
||||
Loading...
|
||||
@@ -619,12 +826,33 @@ export function FileBrowserPane({ pane, projectId, onStateChange }: Props) {
|
||||
)}
|
||||
{viewer?.state === 'ready' && viewer.result && (
|
||||
<div className="p-2">
|
||||
{selectedLines.size > 0 && (
|
||||
<div className="sticky top-0 z-10 bg-muted border-b border-border flex items-center justify-between px-2 py-1 mb-2 rounded-t">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedLines.size === 1
|
||||
? `Attach line ${selectionMin} to chat`
|
||||
: `Attach lines ${selectionMin}–${selectionMax} to chat`}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs font-medium text-primary hover:underline"
|
||||
onClick={handleAttachLines}
|
||||
>
|
||||
Attach
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{viewer.result.truncated && (
|
||||
<div className="text-[11px] text-muted-foreground mb-1 px-2 py-1 rounded bg-muted/40 border border-border">
|
||||
Showing first {viewer.result.bytes_returned} bytes; file is {viewer.result.total_bytes} bytes total.
|
||||
</div>
|
||||
)}
|
||||
<CodeBlock code={viewer.result.content} lang={deriveLang(openFile)} />
|
||||
<FileViewer
|
||||
code={viewer.result.content}
|
||||
lang={inferLanguage(openFile)}
|
||||
selectedLines={selectedLines}
|
||||
onLineClick={handleLineClick}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
// across hooks (e.g. AI rename arriving via WS in the session view needs to
|
||||
// also refresh the sidebar's session list).
|
||||
|
||||
import type { Project, Session } from '@/api/types';
|
||||
import type { Chat, Project, Session } from '@/api/types';
|
||||
import type { Attachment } from '@/lib/attachments';
|
||||
|
||||
export interface SessionRenamedEvent {
|
||||
type: 'session_renamed';
|
||||
@@ -51,6 +52,37 @@ export interface OpenFileInBrowserEvent {
|
||||
path: string; // project-relative
|
||||
}
|
||||
|
||||
export interface AttachChatFileEvent {
|
||||
type: 'attach_chat_file';
|
||||
attachment: Omit<Attachment, 'id'>;
|
||||
}
|
||||
|
||||
export interface SessionArchivedEvent {
|
||||
type: 'session_archived';
|
||||
session_id: string;
|
||||
project_id: string;
|
||||
}
|
||||
|
||||
export interface ChatCreatedEvent {
|
||||
type: 'chat_created';
|
||||
chat: Chat;
|
||||
session_id: string;
|
||||
}
|
||||
|
||||
export interface ChatUpdatedEvent {
|
||||
type: 'chat_updated';
|
||||
chat_id: string;
|
||||
session_id: string;
|
||||
name: string | null;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ChatClosedEvent {
|
||||
type: 'chat_closed';
|
||||
chat_id: string;
|
||||
session_id: string;
|
||||
}
|
||||
|
||||
export type SessionEvent =
|
||||
| SessionRenamedEvent
|
||||
| ProjectCreatedEvent
|
||||
@@ -59,7 +91,12 @@ export type SessionEvent =
|
||||
| SessionDeletedEvent
|
||||
| SessionUpdatedEvent
|
||||
| SessionLoadedEvent
|
||||
| OpenFileInBrowserEvent;
|
||||
| OpenFileInBrowserEvent
|
||||
| AttachChatFileEvent
|
||||
| SessionArchivedEvent
|
||||
| ChatCreatedEvent
|
||||
| ChatUpdatedEvent
|
||||
| ChatClosedEvent;
|
||||
type Listener = (event: SessionEvent) => void;
|
||||
|
||||
const listeners = new Set<Listener>();
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from '@/api/client';
|
||||
import type { Pane, PaneCreateRequest, PaneState, PaneUpdateRequest } from '@/api/types';
|
||||
|
||||
export function usePanes(sessionId: string | undefined): {
|
||||
panes: Pane[] | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => Promise<void>;
|
||||
create: (body: PaneCreateRequest) => Promise<Pane>;
|
||||
update: (id: string, body: PaneUpdateRequest) => Promise<void>;
|
||||
remove: (id: string) => Promise<void>;
|
||||
} {
|
||||
const [panes, setPanes] = useState<Pane[] | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Pending debounced state PATCHes: pane id -> latest PaneState
|
||||
const pendingState = useRef<Map<string, PaneState>>(new Map());
|
||||
const debounceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!sessionId) {
|
||||
setPanes(null);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const { panes: list } = await api.panes.getForSession(sessionId);
|
||||
setPanes(list);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'pane operation failed');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [sessionId]);
|
||||
|
||||
const flushPendingState = useCallback(async () => {
|
||||
if (debounceTimer.current !== null) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
debounceTimer.current = null;
|
||||
}
|
||||
const updates = Array.from(pendingState.current.entries());
|
||||
pendingState.current.clear();
|
||||
if (updates.length === 0) return;
|
||||
try {
|
||||
await Promise.all(updates.map(([id, state]) => api.panes.update(id, { state })));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'pane state PATCH failed');
|
||||
// server truth may diverge from optimistic local state; resync
|
||||
void refresh();
|
||||
}
|
||||
}, [refresh]);
|
||||
|
||||
// Fetch on mount / sessionId change; preserve previous list while reloading
|
||||
// (loading=true but panes stays non-null after first fetch to avoid flash)
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
// Flush debounced PATCHes on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
flushPendingState();
|
||||
};
|
||||
}, [flushPendingState]);
|
||||
|
||||
const create = useCallback(
|
||||
async (body: PaneCreateRequest): Promise<Pane> => {
|
||||
if (!sessionId) throw new Error('no session');
|
||||
const created = await api.panes.create(sessionId, body);
|
||||
await refresh();
|
||||
return created;
|
||||
},
|
||||
[sessionId, refresh]
|
||||
);
|
||||
|
||||
const update = useCallback(
|
||||
async (id: string, body: PaneUpdateRequest): Promise<void> => {
|
||||
if (body.state !== undefined && body.position === undefined) {
|
||||
const nextState = body.state;
|
||||
// Optimistic local update
|
||||
setPanes((prev) => {
|
||||
if (!prev) return prev;
|
||||
let changed = false;
|
||||
const next = prev.map((pane) => {
|
||||
if (pane.id !== id) return pane;
|
||||
changed = true;
|
||||
// Narrow via discriminated union to satisfy TypeScript
|
||||
if (pane.kind === 'chat') {
|
||||
return { ...pane, state: nextState as typeof pane.state };
|
||||
}
|
||||
if (pane.kind === 'file_browser') {
|
||||
return { ...pane, state: nextState as typeof pane.state };
|
||||
}
|
||||
return pane;
|
||||
});
|
||||
return changed ? next : prev;
|
||||
});
|
||||
|
||||
// Coalesce: last state wins within debounce window
|
||||
pendingState.current.set(id, nextState);
|
||||
|
||||
if (debounceTimer.current !== null) {
|
||||
clearTimeout(debounceTimer.current);
|
||||
}
|
||||
debounceTimer.current = setTimeout(() => {
|
||||
debounceTimer.current = null;
|
||||
flushPendingState();
|
||||
}, 300);
|
||||
} else {
|
||||
// position involved — fire immediately
|
||||
try {
|
||||
await api.panes.update(id, body);
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'pane operation failed');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
},
|
||||
[refresh, flushPendingState]
|
||||
);
|
||||
|
||||
const remove = useCallback(
|
||||
async (id: string): Promise<void> => {
|
||||
// Optimistic remove — capture snapshot inside functional updater to avoid stale closure
|
||||
let snapshot: Pane[] | null = null;
|
||||
setPanes((prev) => {
|
||||
snapshot = prev;
|
||||
return prev ? prev.filter((p) => p.id !== id) : prev;
|
||||
});
|
||||
|
||||
try {
|
||||
await api.panes.remove(id);
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
// Rollback to the truly-most-recent value captured above
|
||||
setPanes(snapshot);
|
||||
setError(err instanceof Error ? err.message : 'pane operation failed');
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
[refresh]
|
||||
);
|
||||
|
||||
return { panes, loading, error, refresh, create, update, remove };
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { api } from '@/api/client';
|
||||
import type { Project } from '@/api/types';
|
||||
import { sessionEvents } from './sessionEvents';
|
||||
|
||||
export function useProjects() {
|
||||
const [projects, setProjects] = useState<Project[] | null>(null);
|
||||
@@ -33,7 +32,6 @@ export function useProjects() {
|
||||
const remove = useCallback(
|
||||
async (id: string) => {
|
||||
await api.projects.remove(id);
|
||||
sessionEvents.emit({ type: 'project_deleted', project_id: id });
|
||||
await refresh();
|
||||
},
|
||||
[refresh]
|
||||
|
||||
@@ -19,8 +19,10 @@ function applyFrame(state: State, frame: WsFrame): State {
|
||||
const newMsg: Message = {
|
||||
id: frame.message_id,
|
||||
session_id: '',
|
||||
chat_id: frame.chat_id ?? '',
|
||||
role: frame.role,
|
||||
content: '',
|
||||
kind: 'message',
|
||||
tool_calls: null,
|
||||
tool_results: null,
|
||||
status: 'streaming',
|
||||
@@ -71,8 +73,10 @@ function applyFrame(state: State, frame: WsFrame): State {
|
||||
const newMsg: Message = {
|
||||
id: frame.tool_message_id,
|
||||
session_id: '',
|
||||
chat_id: frame.chat_id ?? '',
|
||||
role: 'tool',
|
||||
content: '',
|
||||
kind: 'message',
|
||||
tool_calls: null,
|
||||
tool_results: {
|
||||
tool_call_id: frame.tool_call_id,
|
||||
@@ -115,7 +119,6 @@ function applyFrame(state: State, frame: WsFrame): State {
|
||||
};
|
||||
}
|
||||
case 'session_renamed': {
|
||||
// Side-effect, not state — dispatch via event bus to other hooks.
|
||||
sessionEvents.emit({
|
||||
type: 'session_renamed',
|
||||
session_id: frame.session_id,
|
||||
@@ -123,6 +126,16 @@ function applyFrame(state: State, frame: WsFrame): State {
|
||||
});
|
||||
return state;
|
||||
}
|
||||
case 'chat_renamed': {
|
||||
sessionEvents.emit({
|
||||
type: 'chat_updated',
|
||||
chat_id: frame.chat_id,
|
||||
session_id: '',
|
||||
name: frame.name,
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
return state;
|
||||
}
|
||||
case 'error': {
|
||||
const next = frame.message_id
|
||||
? state.messages.map((m) =>
|
||||
|
||||
@@ -140,26 +140,50 @@ function applyEvent(prev: SidebarResponse, event: import('./sessionEvents').Sess
|
||||
case 'open_file_in_browser':
|
||||
// Consumed by Workspace (T7); no sidebar state change needed.
|
||||
return prev;
|
||||
case 'attach_chat_file':
|
||||
return prev;
|
||||
case 'session_archived': {
|
||||
let changed = false;
|
||||
const projects = prev.projects.map((p) => {
|
||||
if (p.id !== event.project_id) return p;
|
||||
const recent = p.recent_sessions.filter((s) => s.id !== event.session_id);
|
||||
if (recent.length === p.recent_sessions.length) return p;
|
||||
changed = true;
|
||||
return {
|
||||
...p,
|
||||
recent_sessions: recent,
|
||||
total_sessions: Math.max(0, p.total_sessions - 1),
|
||||
};
|
||||
});
|
||||
return changed ? { ...prev, projects } : prev;
|
||||
}
|
||||
case 'chat_created':
|
||||
case 'chat_updated':
|
||||
case 'chat_closed':
|
||||
return prev;
|
||||
}
|
||||
}
|
||||
|
||||
// One bus subscription for the lifetime of the module. Events arriving
|
||||
// before the initial fetch resolves are dropped; the eventual fetch
|
||||
// result is the source of truth.
|
||||
sessionEvents.subscribe((event) => {
|
||||
// session_loaded updates activeSessionProjectId regardless of whether
|
||||
// sharedData is populated yet — notify so subscribers can re-read.
|
||||
if (event.type === 'session_loaded') {
|
||||
activeSession = { session_id: event.session_id, project_id: event.project_id };
|
||||
// Guard prevents duplicate listeners during Vite HMR reloads.
|
||||
const G = globalThis as Record<string, unknown>;
|
||||
if (!G.__boocode_sidebar_subscribed) {
|
||||
G.__boocode_sidebar_subscribed = true;
|
||||
sessionEvents.subscribe((event) => {
|
||||
if (event.type === 'session_loaded') {
|
||||
activeSession = { session_id: event.session_id, project_id: event.project_id };
|
||||
notify();
|
||||
return;
|
||||
}
|
||||
if (!sharedData) return;
|
||||
const next = applyEvent(sharedData, event);
|
||||
if (next === sharedData) return;
|
||||
sharedData = next;
|
||||
notify();
|
||||
return;
|
||||
}
|
||||
if (!sharedData) return;
|
||||
const next = applyEvent(sharedData, event);
|
||||
if (next === sharedData) return;
|
||||
sharedData = next;
|
||||
notify();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface Snapshot {
|
||||
data: SidebarResponse | null;
|
||||
|
||||
44
apps/web/src/lib/attachments.ts
Normal file
44
apps/web/src/lib/attachments.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
export type Attachment = {
|
||||
id: string;
|
||||
kind: 'file' | 'lines' | 'paste';
|
||||
filename: string;
|
||||
language: string | null;
|
||||
content: string;
|
||||
range?: [number, number];
|
||||
source: '@' | 'line-select' | 'drop' | 'paste';
|
||||
};
|
||||
|
||||
export const LANG_MAP: Record<string, string> = {
|
||||
ts: 'typescript', tsx: 'tsx', js: 'javascript', jsx: 'jsx',
|
||||
mjs: 'javascript', cjs: 'javascript',
|
||||
py: 'python', go: 'go', rs: 'rust', rb: 'ruby', java: 'java',
|
||||
c: 'c', h: 'c', cpp: 'cpp', cc: 'cpp', hpp: 'cpp', cs: 'csharp',
|
||||
php: 'php', sh: 'bash', bash: 'bash', zsh: 'bash',
|
||||
yml: 'yaml', yaml: 'yaml', json: 'json', toml: 'toml',
|
||||
md: 'markdown', markdown: 'markdown', sql: 'sql', dockerfile: 'dockerfile',
|
||||
html: 'html', htm: 'html', css: 'css', scss: 'scss',
|
||||
};
|
||||
|
||||
export function inferLanguage(filename: string): string | null {
|
||||
const base = filename.split('/').pop() ?? filename;
|
||||
if (base.toLowerCase() === 'dockerfile') return 'dockerfile';
|
||||
const m = base.match(/\.([^.]+)$/);
|
||||
return m ? (LANG_MAP[m[1]!.toLowerCase()] ?? null) : null;
|
||||
}
|
||||
|
||||
export function flattenToMessage(attachments: Attachment[], text: string): string {
|
||||
if (attachments.length === 0) return text;
|
||||
const blocks = attachments.map(a => {
|
||||
const fence = '```' + (a.language ?? '');
|
||||
let header: string;
|
||||
if (a.kind === 'lines') {
|
||||
header = `// from: ${a.filename}:${a.range?.[0] ?? '?'}-${a.range?.[1] ?? '?'}`;
|
||||
} else if (a.kind === 'paste') {
|
||||
header = `// from: pasted text (${a.content.split('\n').length} lines)`;
|
||||
} else {
|
||||
header = `// from: ${a.filename}`;
|
||||
}
|
||||
return `${fence}\n${header}\n${a.content}\n\`\`\``;
|
||||
});
|
||||
return [...blocks, text].filter(Boolean).join('\n\n');
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import { Plus, MessageSquare, Trash2 } from 'lucide-react';
|
||||
import { Plus, MessageSquare, Trash2, ChevronDown, ChevronRight, RotateCcw } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '@/api/client';
|
||||
import type { Project as ProjectType } from '@/api/types';
|
||||
import type { Project as ProjectType, Session } from '@/api/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { sessionEvents } from '@/hooks/sessionEvents';
|
||||
import { useSessions } from '@/hooks/useSessions';
|
||||
@@ -14,6 +14,8 @@ export function Project() {
|
||||
const { sessions, create, remove } = useSessions(id);
|
||||
const [project, setProject] = useState<ProjectType | null>(null);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [archivedSessions, setArchivedSessions] = useState<Session[] | null>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -23,6 +25,26 @@ export function Project() {
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
api.sessions.listForProject(id, 'archived')
|
||||
.then(setArchivedSessions)
|
||||
.catch(() => {});
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
return sessionEvents.subscribe((event) => {
|
||||
if (event.type === 'session_archived' && event.project_id === id) {
|
||||
setArchivedSessions((prev) => {
|
||||
if (!prev) return prev;
|
||||
const session = sessions?.find((s) => s.id === event.session_id);
|
||||
if (!session) return prev;
|
||||
return [{ ...session, status: 'archived' as const }, ...prev];
|
||||
});
|
||||
}
|
||||
});
|
||||
}, [id, sessions]);
|
||||
|
||||
async function handleNew() {
|
||||
if (!id || creating) return;
|
||||
setCreating(true);
|
||||
@@ -35,6 +57,17 @@ export function Project() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnarchive(sessionId: string) {
|
||||
try {
|
||||
await api.sessions.unarchive(sessionId);
|
||||
setArchivedSessions((prev) =>
|
||||
prev ? prev.filter((s) => s.id !== sessionId) : prev
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'failed to unarchive');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col">
|
||||
<header className="border-b px-6 py-3 flex items-center justify-between">
|
||||
@@ -52,7 +85,7 @@ export function Project() {
|
||||
</Button>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4">
|
||||
<div className="flex-1 overflow-y-auto px-6 py-4 space-y-6">
|
||||
{sessions === null && (
|
||||
<div className="text-sm text-muted-foreground">Loading…</div>
|
||||
)}
|
||||
@@ -97,6 +130,61 @@ export function Project() {
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{/* Archived sessions */}
|
||||
{archivedSessions && archivedSessions.length > 0 && (
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowArchived(!showArchived)}
|
||||
className="flex items-center gap-1 text-xs font-medium text-muted-foreground mb-2 hover:text-foreground"
|
||||
>
|
||||
{showArchived ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
|
||||
Closed sessions ({archivedSessions.length})
|
||||
</button>
|
||||
{showArchived && (
|
||||
<ul className="divide-y rounded-md border">
|
||||
{archivedSessions.map((s) => (
|
||||
<li key={s.id} className="flex items-center justify-between px-3 py-2 hover:bg-muted/50">
|
||||
<div className="flex-1 flex items-center gap-2 min-w-0">
|
||||
<MessageSquare className="size-3.5 opacity-40 shrink-0" />
|
||||
<span className="truncate text-sm text-muted-foreground">{s.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Reopen session"
|
||||
onClick={() => void handleUnarchive(s.id)}
|
||||
>
|
||||
<RotateCcw size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label="Delete session permanently"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await api.sessions.remove(s.id);
|
||||
setArchivedSessions((prev) =>
|
||||
prev ? prev.filter((a) => a.id !== s.id) : prev
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : 'failed to delete'
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Trash2 />
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user