mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-04-25 00:36:31 +02:00
feat: old chat to new-chat with persistance
This commit is contained in:
parent
0c3574d049
commit
b5e20e7515
17 changed files with 490 additions and 385 deletions
|
|
@ -51,6 +51,7 @@ router = APIRouter()
|
|||
@router.get("/threads", response_model=ThreadListResponse)
|
||||
async def list_threads(
|
||||
search_space_id: int,
|
||||
limit: int | None = None,
|
||||
session: AsyncSession = Depends(get_async_session),
|
||||
user: User = Depends(current_active_user),
|
||||
):
|
||||
|
|
@ -58,6 +59,10 @@ async def list_threads(
|
|||
List all threads for the current user in a search space.
|
||||
Returns threads and archived_threads for ThreadListPrimitive.
|
||||
|
||||
Args:
|
||||
search_space_id: The search space to list threads for
|
||||
limit: Optional limit on number of threads to return (applies to active threads only)
|
||||
|
||||
Requires CHATS_READ permission.
|
||||
"""
|
||||
try:
|
||||
|
|
@ -91,14 +96,18 @@ async def list_threads(
|
|||
id=thread.id,
|
||||
title=thread.title,
|
||||
archived=thread.archived,
|
||||
createdAt=thread.created_at,
|
||||
updatedAt=thread.updated_at,
|
||||
created_at=thread.created_at,
|
||||
updated_at=thread.updated_at,
|
||||
)
|
||||
if thread.archived:
|
||||
archived_threads.append(item)
|
||||
else:
|
||||
threads.append(item)
|
||||
|
||||
# Apply limit to active threads if specified
|
||||
if limit is not None and limit > 0:
|
||||
threads = threads[:limit]
|
||||
|
||||
return ThreadListResponse(threads=threads, archived_threads=archived_threads)
|
||||
|
||||
except HTTPException:
|
||||
|
|
@ -114,6 +123,69 @@ async def list_threads(
|
|||
) from None
|
||||
|
||||
|
||||
@router.get("/threads/search", response_model=list[ThreadListItem])
|
||||
async def search_threads(
|
||||
search_space_id: int,
|
||||
title: str,
|
||||
session: AsyncSession = Depends(get_async_session),
|
||||
user: User = Depends(current_active_user),
|
||||
):
|
||||
"""
|
||||
Search threads by title in a search space.
|
||||
|
||||
Args:
|
||||
search_space_id: The search space to search in
|
||||
title: The search query (case-insensitive partial match)
|
||||
|
||||
Requires CHATS_READ permission.
|
||||
"""
|
||||
try:
|
||||
await check_permission(
|
||||
session,
|
||||
user,
|
||||
search_space_id,
|
||||
Permission.CHATS_READ.value,
|
||||
"You don't have permission to read chats in this search space",
|
||||
)
|
||||
|
||||
# Search threads by title (case-insensitive)
|
||||
query = (
|
||||
select(NewChatThread)
|
||||
.filter(
|
||||
NewChatThread.search_space_id == search_space_id,
|
||||
NewChatThread.user_id == user.id,
|
||||
NewChatThread.title.ilike(f"%{title}%"),
|
||||
)
|
||||
.order_by(NewChatThread.updated_at.desc())
|
||||
)
|
||||
|
||||
result = await session.execute(query)
|
||||
threads = result.scalars().all()
|
||||
|
||||
return [
|
||||
ThreadListItem(
|
||||
id=thread.id,
|
||||
title=thread.title,
|
||||
archived=thread.archived,
|
||||
created_at=thread.created_at,
|
||||
updated_at=thread.updated_at,
|
||||
)
|
||||
for thread in threads
|
||||
]
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except OperationalError:
|
||||
raise HTTPException(
|
||||
status_code=503, detail="Database operation failed. Please try again later."
|
||||
) from None
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"An unexpected error occurred while searching threads: {e!s}",
|
||||
) from None
|
||||
|
||||
|
||||
@router.post("/threads", response_model=NewChatThreadRead)
|
||||
async def create_thread(
|
||||
thread: NewChatThreadCreate,
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ export default function DashboardLayout({
|
|||
const customNavMain = [
|
||||
{
|
||||
title: "Chat",
|
||||
url: `/dashboard/${search_space_id}/researcher`,
|
||||
url: `/dashboard/${search_space_id}/new-chat`,
|
||||
icon: "SquareTerminal",
|
||||
items: [],
|
||||
},
|
||||
|
|
|
|||
|
|
@ -2,26 +2,26 @@
|
|||
|
||||
import {
|
||||
AssistantRuntimeProvider,
|
||||
useExternalStoreRuntime,
|
||||
type ThreadMessageLike,
|
||||
useExternalStoreRuntime,
|
||||
} from "@assistant-ui/react";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Thread } from "@/components/assistant-ui/thread";
|
||||
import { GeneratePodcastToolUI } from "@/components/tool-ui/generate-podcast";
|
||||
import {
|
||||
createThread,
|
||||
getThreadMessages,
|
||||
appendMessage,
|
||||
type MessageRecord,
|
||||
} from "@/lib/chat/thread-persistence";
|
||||
import { getBearerToken } from "@/lib/auth-utils";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
isPodcastGenerating,
|
||||
looksLikePodcastRequest,
|
||||
setActivePodcastTaskId,
|
||||
} from "@/lib/chat/podcast-state";
|
||||
import {
|
||||
appendMessage,
|
||||
createThread,
|
||||
getThreadMessages,
|
||||
type MessageRecord,
|
||||
} from "@/lib/chat/thread-persistence";
|
||||
|
||||
/**
|
||||
* Convert backend message to assistant-ui ThreadMessageLike format
|
||||
|
|
@ -223,8 +223,7 @@ export default function NewChatPage() {
|
|||
]);
|
||||
|
||||
try {
|
||||
const backendUrl =
|
||||
process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL || "http://localhost:8000";
|
||||
const backendUrl = process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL || "http://localhost:8000";
|
||||
|
||||
// Build message history for context
|
||||
const messageHistory = messages
|
||||
|
|
@ -232,11 +231,7 @@ export default function NewChatPage() {
|
|||
.map((m) => {
|
||||
let text = "";
|
||||
for (const part of m.content) {
|
||||
if (
|
||||
typeof part === "object" &&
|
||||
part.type === "text" &&
|
||||
"text" in part
|
||||
) {
|
||||
if (typeof part === "object" && part.type === "text" && "text" in part) {
|
||||
text += part.text;
|
||||
}
|
||||
}
|
||||
|
|
@ -296,9 +291,7 @@ export default function NewChatPage() {
|
|||
accumulatedText += parsed.delta;
|
||||
setMessages((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === assistantMsgId
|
||||
? { ...m, content: buildContent() }
|
||||
: m
|
||||
m.id === assistantMsgId ? { ...m, content: buildContent() } : m
|
||||
)
|
||||
);
|
||||
break;
|
||||
|
|
@ -311,9 +304,7 @@ export default function NewChatPage() {
|
|||
});
|
||||
setMessages((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === assistantMsgId
|
||||
? { ...m, content: buildContent() }
|
||||
: m
|
||||
m.id === assistantMsgId ? { ...m, content: buildContent() } : m
|
||||
)
|
||||
);
|
||||
break;
|
||||
|
|
@ -329,9 +320,7 @@ export default function NewChatPage() {
|
|||
});
|
||||
setMessages((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === assistantMsgId
|
||||
? { ...m, content: buildContent() }
|
||||
: m
|
||||
m.id === assistantMsgId ? { ...m, content: buildContent() } : m
|
||||
)
|
||||
);
|
||||
break;
|
||||
|
|
@ -351,9 +340,7 @@ export default function NewChatPage() {
|
|||
}
|
||||
setMessages((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === assistantMsgId
|
||||
? { ...m, content: buildContent() }
|
||||
: m
|
||||
m.id === assistantMsgId ? { ...m, content: buildContent() } : m
|
||||
)
|
||||
);
|
||||
break;
|
||||
|
|
@ -379,9 +366,7 @@ export default function NewChatPage() {
|
|||
appendMessage(threadId, {
|
||||
role: "assistant",
|
||||
content: finalContent,
|
||||
}).catch((err) =>
|
||||
console.error("Failed to persist assistant message:", err)
|
||||
);
|
||||
}).catch((err) => console.error("Failed to persist assistant message:", err));
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name === "AbortError") {
|
||||
|
|
|
|||
|
|
@ -39,4 +39,3 @@ export const InlineCitation: FC<InlineCitationProps> = ({ chunkId, citationNumbe
|
|||
</SourceDetailPanel>
|
||||
);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -9,11 +9,10 @@ import {
|
|||
useIsMarkdownCodeBlock,
|
||||
} from "@assistant-ui/react-markdown";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import { type FC, type ReactNode, memo, useState } from "react";
|
||||
import { type FC, memo, type ReactNode, useState } from "react";
|
||||
import remarkGfm from "remark-gfm";
|
||||
|
||||
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
|
||||
import { InlineCitation } from "@/components/assistant-ui/inline-citation";
|
||||
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Citation pattern: [citation:CHUNK_ID]
|
||||
|
|
@ -212,18 +211,12 @@ const defaultComponents = memoizeMarkdownComponents({
|
|||
</h5>
|
||||
),
|
||||
h6: ({ className, children, ...props }) => (
|
||||
<h6
|
||||
className={cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0", className)}
|
||||
{...props}
|
||||
>
|
||||
<h6 className={cn("aui-md-h6 my-4 font-semibold first:mt-0 last:mb-0", className)} {...props}>
|
||||
{processChildrenWithCitations(children)}
|
||||
</h6>
|
||||
),
|
||||
p: ({ className, children, ...props }) => (
|
||||
<p
|
||||
className={cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0", className)}
|
||||
{...props}
|
||||
>
|
||||
<p className={cn("aui-md-p mt-5 mb-5 leading-7 first:mt-0 last:mb-0", className)} {...props}>
|
||||
{processChildrenWithCitations(children)}
|
||||
</p>
|
||||
),
|
||||
|
|
@ -236,10 +229,7 @@ const defaultComponents = memoizeMarkdownComponents({
|
|||
</a>
|
||||
),
|
||||
blockquote: ({ className, children, ...props }) => (
|
||||
<blockquote
|
||||
className={cn("aui-md-blockquote border-l-2 pl-6 italic", className)}
|
||||
{...props}
|
||||
>
|
||||
<blockquote className={cn("aui-md-blockquote border-l-2 pl-6 italic", className)} {...props}>
|
||||
{processChildrenWithCitations(children)}
|
||||
</blockquote>
|
||||
),
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
MessageSquareIcon,
|
||||
MoreVerticalIcon,
|
||||
PlusIcon,
|
||||
RotateCcwIcon,
|
||||
TrashIcon,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { ArchiveIcon, MessageSquareIcon, PlusIcon, TrashIcon, MoreVerticalIcon, RotateCcwIcon } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
|
|
@ -13,10 +19,11 @@ import {
|
|||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
type ThreadListItem,
|
||||
createThreadListManager,
|
||||
type ThreadListItem,
|
||||
type ThreadListState,
|
||||
} from "@/lib/chat/thread-persistence";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ThreadListProps {
|
||||
searchSpaceId: number;
|
||||
|
|
@ -123,7 +130,13 @@ export function ThreadList({ searchSpaceId, currentThreadId, className }: Thread
|
|||
{/* Header with New Chat button */}
|
||||
<div className="flex items-center justify-between border-b p-3">
|
||||
<h2 className="font-semibold text-sm">Conversations</h2>
|
||||
<Button variant="ghost" size="icon" className="size-8" onClick={handleNewThread} title="New Chat">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-8"
|
||||
onClick={handleNewThread}
|
||||
title="New Chat"
|
||||
>
|
||||
<PlusIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import Image from "next/image";
|
||||
import { Streamdown } from "streamdown";
|
||||
import type { Components } from "react-markdown";
|
||||
import { Streamdown } from "streamdown";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface MarkdownViewerProps {
|
||||
|
|
@ -68,12 +68,8 @@ export function MarkdownViewer({ content, className }: MarkdownViewerProps) {
|
|||
<table className="min-w-full divide-y divide-border" {...props} />
|
||||
</div>
|
||||
),
|
||||
th: ({ ...props }) => (
|
||||
<th className="px-3 py-2 text-left font-medium bg-muted" {...props} />
|
||||
),
|
||||
td: ({ ...props }) => (
|
||||
<td className="px-3 py-2 border-t border-border" {...props} />
|
||||
),
|
||||
th: ({ ...props }) => <th className="px-3 py-2 text-left font-medium bg-muted" {...props} />,
|
||||
td: ({ ...props }) => <td className="px-3 py-2 border-t border-border" {...props} />,
|
||||
code: ({ className, children, ...props }) => {
|
||||
const match = /language-(\w+)/.exec(className || "");
|
||||
const isInline = !match;
|
||||
|
|
@ -96,11 +92,13 @@ export function MarkdownViewer({ content, className }: MarkdownViewerProps) {
|
|||
};
|
||||
|
||||
return (
|
||||
<div className={cn("prose prose-sm dark:prose-invert max-w-none overflow-hidden [&_pre]:overflow-x-auto [&_code]:wrap-break-word [&_table]:block [&_table]:overflow-x-auto", className)}>
|
||||
<Streamdown
|
||||
components={components}
|
||||
shikiTheme={["github-light", "github-dark"]}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"prose prose-sm dark:prose-invert max-w-none overflow-hidden [&_pre]:overflow-x-auto [&_code]:wrap-break-word [&_table]:block [&_table]:overflow-x-auto",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Streamdown components={components} shikiTheme={["github-light", "github-dark"]}>
|
||||
{content}
|
||||
</Streamdown>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,26 +1,26 @@
|
|||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
|
||||
import {
|
||||
BookOpen,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
ExternalLink,
|
||||
Loader2,
|
||||
X,
|
||||
FileText,
|
||||
Hash,
|
||||
BookOpen,
|
||||
Loader2,
|
||||
Sparkles,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
|
||||
import type React from "react";
|
||||
import { type ReactNode, forwardRef, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { forwardRef, type ReactNode, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { MarkdownViewer } from "@/components/markdown-viewer";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { documentsApiService } from "@/lib/apis/documents-api.service";
|
||||
import { cacheKeys } from "@/lib/query-client/cache-keys";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
|
@ -70,9 +70,7 @@ const ChunkCard = forwardRef<HTMLDivElement, ChunkCardProps>(
|
|||
)}
|
||||
>
|
||||
{/* Cited indicator glow effect */}
|
||||
{isCited && (
|
||||
<div className="absolute inset-0 rounded-2xl bg-primary/5 blur-xl -z-10" />
|
||||
)}
|
||||
{isCited && <div className="absolute inset-0 rounded-2xl bg-primary/5 blur-xl -z-10" />}
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-5 py-4 border-b border-border/50">
|
||||
|
|
@ -87,9 +85,7 @@ const ChunkCard = forwardRef<HTMLDivElement, ChunkCardProps>(
|
|||
>
|
||||
{index + 1}
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
of {totalChunks} chunks
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">of {totalChunks} chunks</span>
|
||||
</div>
|
||||
{isCited && (
|
||||
<Badge variant="default" className="gap-1.5 px-3 py-1">
|
||||
|
|
@ -152,86 +148,97 @@ export function SourceDetailPanel({
|
|||
const citedChunkIndex = documentData?.chunks?.findIndex((chunk) => chunk.id === chunkId) ?? -1;
|
||||
|
||||
// Simple scroll function that scrolls to a chunk by index
|
||||
const scrollToChunkByIndex = useCallback((chunkIndex: number, smooth = true) => {
|
||||
const scrollContainer = scrollAreaRef.current;
|
||||
if (!scrollContainer) return;
|
||||
const scrollToChunkByIndex = useCallback(
|
||||
(chunkIndex: number, smooth = true) => {
|
||||
const scrollContainer = scrollAreaRef.current;
|
||||
if (!scrollContainer) return;
|
||||
|
||||
const viewport = scrollContainer.querySelector(
|
||||
'[data-radix-scroll-area-viewport]'
|
||||
) as HTMLElement | null;
|
||||
if (!viewport) return;
|
||||
const viewport = scrollContainer.querySelector(
|
||||
"[data-radix-scroll-area-viewport]"
|
||||
) as HTMLElement | null;
|
||||
if (!viewport) return;
|
||||
|
||||
const chunkElement = scrollContainer.querySelector(
|
||||
`[data-chunk-index="${chunkIndex}"]`
|
||||
) as HTMLElement | null;
|
||||
if (!chunkElement) return;
|
||||
const chunkElement = scrollContainer.querySelector(
|
||||
`[data-chunk-index="${chunkIndex}"]`
|
||||
) as HTMLElement | null;
|
||||
if (!chunkElement) return;
|
||||
|
||||
// Get positions using getBoundingClientRect for accuracy
|
||||
const viewportRect = viewport.getBoundingClientRect();
|
||||
const chunkRect = chunkElement.getBoundingClientRect();
|
||||
// Get positions using getBoundingClientRect for accuracy
|
||||
const viewportRect = viewport.getBoundingClientRect();
|
||||
const chunkRect = chunkElement.getBoundingClientRect();
|
||||
|
||||
// Calculate where to scroll to center the chunk
|
||||
const currentScrollTop = viewport.scrollTop;
|
||||
const chunkTopRelativeToViewport = chunkRect.top - viewportRect.top + currentScrollTop;
|
||||
const scrollTarget = chunkTopRelativeToViewport - (viewportRect.height / 2) + (chunkRect.height / 2);
|
||||
// Calculate where to scroll to center the chunk
|
||||
const currentScrollTop = viewport.scrollTop;
|
||||
const chunkTopRelativeToViewport = chunkRect.top - viewportRect.top + currentScrollTop;
|
||||
const scrollTarget =
|
||||
chunkTopRelativeToViewport - viewportRect.height / 2 + chunkRect.height / 2;
|
||||
|
||||
viewport.scrollTo({
|
||||
top: Math.max(0, scrollTarget),
|
||||
behavior: smooth && !shouldReduceMotion ? "smooth" : "auto",
|
||||
});
|
||||
|
||||
setActiveChunkIndex(chunkIndex);
|
||||
}, [shouldReduceMotion]);
|
||||
|
||||
// Callback ref for the cited chunk - scrolls when the element mounts
|
||||
const citedChunkRefCallback = useCallback((node: HTMLDivElement | null) => {
|
||||
if (node && !hasScrolledRef.current && open) {
|
||||
hasScrolledRef.current = true; // Mark immediately to prevent duplicate scrolls
|
||||
|
||||
// Store the node reference for the delayed scroll
|
||||
const scrollToCitedChunk = () => {
|
||||
const scrollContainer = scrollAreaRef.current;
|
||||
if (!scrollContainer || !node.isConnected) return false;
|
||||
|
||||
const viewport = scrollContainer.querySelector(
|
||||
'[data-radix-scroll-area-viewport]'
|
||||
) as HTMLElement | null;
|
||||
if (!viewport) return false;
|
||||
|
||||
// Get positions
|
||||
const viewportRect = viewport.getBoundingClientRect();
|
||||
const chunkRect = node.getBoundingClientRect();
|
||||
|
||||
// Calculate scroll position to center the chunk
|
||||
const currentScrollTop = viewport.scrollTop;
|
||||
const chunkTopRelativeToViewport = chunkRect.top - viewportRect.top + currentScrollTop;
|
||||
const scrollTarget = chunkTopRelativeToViewport - (viewportRect.height / 2) + (chunkRect.height / 2);
|
||||
|
||||
viewport.scrollTo({
|
||||
top: Math.max(0, scrollTarget),
|
||||
behavior: "auto", // Instant scroll for initial positioning
|
||||
});
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
// Scroll multiple times with delays to handle progressive content rendering
|
||||
// Each subsequent scroll will correct for any layout shifts
|
||||
const scrollAttempts = [50, 150, 300, 600, 1000];
|
||||
|
||||
scrollAttempts.forEach((delay) => {
|
||||
setTimeout(() => {
|
||||
scrollToCitedChunk();
|
||||
}, delay);
|
||||
viewport.scrollTo({
|
||||
top: Math.max(0, scrollTarget),
|
||||
behavior: smooth && !shouldReduceMotion ? "smooth" : "auto",
|
||||
});
|
||||
|
||||
// After final attempt, mark state as scrolled
|
||||
setTimeout(() => {
|
||||
setHasScrolledToCited(true);
|
||||
setActiveChunkIndex(citedChunkIndex);
|
||||
}, scrollAttempts[scrollAttempts.length - 1] + 50);
|
||||
}
|
||||
}, [open, citedChunkIndex]);
|
||||
setActiveChunkIndex(chunkIndex);
|
||||
},
|
||||
[shouldReduceMotion]
|
||||
);
|
||||
|
||||
// Callback ref for the cited chunk - scrolls when the element mounts
|
||||
const citedChunkRefCallback = useCallback(
|
||||
(node: HTMLDivElement | null) => {
|
||||
if (node && !hasScrolledRef.current && open) {
|
||||
hasScrolledRef.current = true; // Mark immediately to prevent duplicate scrolls
|
||||
|
||||
// Store the node reference for the delayed scroll
|
||||
const scrollToCitedChunk = () => {
|
||||
const scrollContainer = scrollAreaRef.current;
|
||||
if (!scrollContainer || !node.isConnected) return false;
|
||||
|
||||
const viewport = scrollContainer.querySelector(
|
||||
"[data-radix-scroll-area-viewport]"
|
||||
) as HTMLElement | null;
|
||||
if (!viewport) return false;
|
||||
|
||||
// Get positions
|
||||
const viewportRect = viewport.getBoundingClientRect();
|
||||
const chunkRect = node.getBoundingClientRect();
|
||||
|
||||
// Calculate scroll position to center the chunk
|
||||
const currentScrollTop = viewport.scrollTop;
|
||||
const chunkTopRelativeToViewport = chunkRect.top - viewportRect.top + currentScrollTop;
|
||||
const scrollTarget =
|
||||
chunkTopRelativeToViewport - viewportRect.height / 2 + chunkRect.height / 2;
|
||||
|
||||
viewport.scrollTo({
|
||||
top: Math.max(0, scrollTarget),
|
||||
behavior: "auto", // Instant scroll for initial positioning
|
||||
});
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
// Scroll multiple times with delays to handle progressive content rendering
|
||||
// Each subsequent scroll will correct for any layout shifts
|
||||
const scrollAttempts = [50, 150, 300, 600, 1000];
|
||||
|
||||
scrollAttempts.forEach((delay) => {
|
||||
setTimeout(() => {
|
||||
scrollToCitedChunk();
|
||||
}, delay);
|
||||
});
|
||||
|
||||
// After final attempt, mark state as scrolled
|
||||
setTimeout(
|
||||
() => {
|
||||
setHasScrolledToCited(true);
|
||||
setActiveChunkIndex(citedChunkIndex);
|
||||
},
|
||||
scrollAttempts[scrollAttempts.length - 1] + 50
|
||||
);
|
||||
}
|
||||
},
|
||||
[open, citedChunkIndex]
|
||||
);
|
||||
|
||||
// Reset scroll state when panel closes
|
||||
useEffect(() => {
|
||||
|
|
@ -271,9 +278,12 @@ export function SourceDetailPanel({
|
|||
window.open(clickUrl, "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
const scrollToChunk = useCallback((index: number) => {
|
||||
scrollToChunkByIndex(index, true);
|
||||
}, [scrollToChunkByIndex]);
|
||||
const scrollToChunk = useCallback(
|
||||
(index: number) => {
|
||||
scrollToChunkByIndex(index, true);
|
||||
},
|
||||
[scrollToChunkByIndex]
|
||||
);
|
||||
|
||||
const panelContent = (
|
||||
<AnimatePresence mode="wait">
|
||||
|
|
@ -320,7 +330,8 @@ export function SourceDetailPanel({
|
|||
: sourceType && formatDocumentType(sourceType)}
|
||||
{documentData?.chunks && (
|
||||
<span className="ml-2">
|
||||
• {documentData.chunks.length} chunk{documentData.chunks.length !== 1 ? "s" : ""}
|
||||
• {documentData.chunks.length} chunk
|
||||
{documentData.chunks.length !== 1 ? "s" : ""}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
|
|
@ -378,9 +389,12 @@ export function SourceDetailPanel({
|
|||
<X className="h-10 w-10 text-destructive" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-semibold text-destructive text-lg">Failed to load document</p>
|
||||
<p className="font-semibold text-destructive text-lg">
|
||||
Failed to load document
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-2 max-w-md">
|
||||
{documentByChunkFetchingError.message || "An unexpected error occurred. Please try again."}
|
||||
{documentByChunkFetchingError.message ||
|
||||
"An unexpected error occurred. Please try again."}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} className="mt-2">
|
||||
|
|
@ -490,18 +504,14 @@ export function SourceDetailPanel({
|
|||
Document Information
|
||||
</h3>
|
||||
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
|
||||
{Object.entries(documentData.document_metadata).map(
|
||||
([key, value]) => (
|
||||
<div key={key} className="space-y-1">
|
||||
<dt className="font-medium text-muted-foreground capitalize text-xs">
|
||||
{key.replace(/_/g, " ")}
|
||||
</dt>
|
||||
<dd className="text-foreground wrap-break-word">
|
||||
{String(value)}
|
||||
</dd>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
{Object.entries(documentData.document_metadata).map(([key, value]) => (
|
||||
<div key={key} className="space-y-1">
|
||||
<dt className="font-medium text-muted-foreground capitalize text-xs">
|
||||
{key.replace(/_/g, " ")}
|
||||
</dt>
|
||||
<dd className="text-foreground wrap-break-word">{String(value)}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</motion.div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,11 @@
|
|||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useAtom, useAtomValue, useSetAtom } from "jotai";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useAtomValue, useSetAtom } from "jotai";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { deleteChatMutationAtom } from "@/atoms/chats/chat-mutation.atoms";
|
||||
import { chatsAtom } from "@/atoms/chats/chat-query.atoms";
|
||||
import { globalChatsQueryParamsAtom } from "@/atoms/chats/ui.atoms";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { hasUnsavedEditorChangesAtom, pendingEditorNavigationAtom } from "@/atoms/editor/ui.atoms";
|
||||
import { currentUserAtom } from "@/atoms/user/user-query.atoms";
|
||||
import { AppSidebar } from "@/components/sidebar/app-sidebar";
|
||||
|
|
@ -23,6 +20,7 @@ import {
|
|||
} from "@/components/ui/dialog";
|
||||
import { notesApiService } from "@/lib/apis/notes-api.service";
|
||||
import { searchSpacesApiService } from "@/lib/apis/search-spaces-api.service";
|
||||
import { deleteThread, fetchThreads } from "@/lib/chat/thread-persistence";
|
||||
import { cacheKeys } from "@/lib/query-client/cache-keys";
|
||||
|
||||
interface AppSidebarProviderProps {
|
||||
|
|
@ -52,18 +50,24 @@ export function AppSidebarProvider({
|
|||
const t = useTranslations("dashboard");
|
||||
const tCommon = useTranslations("common");
|
||||
const router = useRouter();
|
||||
const setChatsQueryParams = useSetAtom(globalChatsQueryParamsAtom);
|
||||
const { data: chats, error: chatError, isLoading: isLoadingChats } = useAtomValue(chatsAtom);
|
||||
const [{ isPending: isDeletingChat, mutateAsync: deleteChat, error: deleteError }] =
|
||||
useAtom(deleteChatMutationAtom);
|
||||
const queryClient = useQueryClient();
|
||||
const [isDeletingThread, setIsDeletingThread] = useState(false);
|
||||
|
||||
// Editor state for handling unsaved changes
|
||||
const hasUnsavedEditorChanges = useAtomValue(hasUnsavedEditorChangesAtom);
|
||||
const setPendingNavigation = useSetAtom(pendingEditorNavigationAtom);
|
||||
|
||||
useEffect(() => {
|
||||
setChatsQueryParams((prev) => ({ ...prev, search_space_id: searchSpaceId, skip: 0, limit: 4 }));
|
||||
}, [searchSpaceId, setChatsQueryParams]);
|
||||
// Fetch new chat threads
|
||||
const {
|
||||
data: threadsData,
|
||||
error: threadError,
|
||||
isLoading: isLoadingThreads,
|
||||
refetch: refetchThreads,
|
||||
} = useQuery({
|
||||
queryKey: ["threads", searchSpaceId],
|
||||
queryFn: () => fetchThreads(Number(searchSpaceId), 4),
|
||||
enabled: !!searchSpaceId,
|
||||
});
|
||||
|
||||
const {
|
||||
data: searchSpace,
|
||||
|
|
@ -95,7 +99,7 @@ export function AppSidebarProvider({
|
|||
});
|
||||
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [chatToDelete, setChatToDelete] = useState<{ id: number; name: string } | null>(null);
|
||||
const [threadToDelete, setThreadToDelete] = useState<{ id: number; name: string } | null>(null);
|
||||
const [showDeleteNoteDialog, setShowDeleteNoteDialog] = useState(false);
|
||||
const [noteToDelete, setNoteToDelete] = useState<{
|
||||
id: number;
|
||||
|
|
@ -103,62 +107,56 @@ export function AppSidebarProvider({
|
|||
search_space_id: number;
|
||||
} | null>(null);
|
||||
const [isDeletingNote, setIsDeletingNote] = useState(false);
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
|
||||
// Set isClient to true when component mounts on the client
|
||||
useEffect(() => {
|
||||
setIsClient(true);
|
||||
}, []);
|
||||
|
||||
// Retry function
|
||||
const retryFetch = useCallback(() => {
|
||||
fetchSearchSpace();
|
||||
}, [fetchSearchSpace]);
|
||||
|
||||
// Transform API response to the format expected by AppSidebar
|
||||
// Transform threads to the format expected by AppSidebar
|
||||
const recentChats = useMemo(() => {
|
||||
if (!chats) return [];
|
||||
if (!threadsData?.threads) return [];
|
||||
|
||||
// Sort chats by created_at (most recent first)
|
||||
const sortedChats = [...chats].sort((a, b) => {
|
||||
const dateA = new Date(a.created_at).getTime();
|
||||
const dateB = new Date(b.created_at).getTime();
|
||||
return dateB - dateA; // Descending order (most recent first)
|
||||
});
|
||||
|
||||
return sortedChats.map((chat) => ({
|
||||
name: chat.title || `Chat ${chat.id}`,
|
||||
url: `/dashboard/${chat.search_space_id}/researcher/${chat.id}`,
|
||||
// Threads are already sorted by updated_at desc from the API
|
||||
return threadsData.threads.map((thread) => ({
|
||||
name: thread.title || `Chat ${thread.id}`,
|
||||
url: `/dashboard/${searchSpaceId}/new-chat/${thread.id}`,
|
||||
icon: "MessageCircleMore",
|
||||
id: chat.id,
|
||||
search_space_id: chat.search_space_id,
|
||||
id: thread.id,
|
||||
search_space_id: Number(searchSpaceId),
|
||||
actions: [
|
||||
{
|
||||
name: "Delete",
|
||||
icon: "Trash2",
|
||||
onClick: () => {
|
||||
setChatToDelete({ id: chat.id, name: chat.title || `Chat ${chat.id}` });
|
||||
setThreadToDelete({
|
||||
id: thread.id,
|
||||
name: thread.title || `Chat ${thread.id}`,
|
||||
});
|
||||
setShowDeleteDialog(true);
|
||||
},
|
||||
},
|
||||
],
|
||||
}));
|
||||
}, [chats]);
|
||||
}, [threadsData, searchSpaceId]);
|
||||
|
||||
// Handle delete chat with better error handling
|
||||
const handleDeleteChat = useCallback(async () => {
|
||||
if (!chatToDelete) return;
|
||||
// Handle delete thread
|
||||
const handleDeleteThread = useCallback(async () => {
|
||||
if (!threadToDelete) return;
|
||||
|
||||
setIsDeletingThread(true);
|
||||
try {
|
||||
await deleteChat({ id: chatToDelete.id });
|
||||
await deleteThread(threadToDelete.id);
|
||||
// Invalidate threads query to refresh the list
|
||||
queryClient.invalidateQueries({ queryKey: ["threads", searchSpaceId] });
|
||||
} catch (error) {
|
||||
console.error("Error deleting chat:", error);
|
||||
// You could show a toast notification here
|
||||
console.error("Error deleting thread:", error);
|
||||
} finally {
|
||||
setIsDeletingThread(false);
|
||||
setShowDeleteDialog(false);
|
||||
setChatToDelete(null);
|
||||
setThreadToDelete(null);
|
||||
}
|
||||
}, [chatToDelete, deleteChat]);
|
||||
}, [threadToDelete, queryClient, searchSpaceId]);
|
||||
|
||||
// Handle delete note with confirmation
|
||||
const handleDeleteNote = useCallback(async () => {
|
||||
|
|
@ -182,7 +180,7 @@ export function AppSidebarProvider({
|
|||
|
||||
// Memoized fallback chats
|
||||
const fallbackChats = useMemo(() => {
|
||||
if (chatError) {
|
||||
if (threadError) {
|
||||
return [
|
||||
{
|
||||
name: t("error_loading_chats"),
|
||||
|
|
@ -194,7 +192,7 @@ export function AppSidebarProvider({
|
|||
{
|
||||
name: tCommon("retry"),
|
||||
icon: "RefreshCw",
|
||||
onClick: retryFetch,
|
||||
onClick: () => refetchThreads(),
|
||||
},
|
||||
],
|
||||
},
|
||||
|
|
@ -202,7 +200,7 @@ export function AppSidebarProvider({
|
|||
}
|
||||
|
||||
return [];
|
||||
}, [chatError, isLoadingChats, recentChats.length, searchSpaceId, retryFetch, t, tCommon]);
|
||||
}, [threadError, searchSpaceId, refetchThreads, t, tCommon]);
|
||||
|
||||
// Use fallback chats if there's an error or no chats
|
||||
const displayChats = recentChats.length > 0 ? recentChats : fallbackChats;
|
||||
|
|
@ -262,7 +260,7 @@ export function AppSidebarProvider({
|
|||
// Memoized updated navSecondary
|
||||
const updatedNavSecondary = useMemo(() => {
|
||||
const updated = [...navSecondary];
|
||||
if (updated.length > 0 && isClient) {
|
||||
if (updated.length > 0) {
|
||||
updated[0] = {
|
||||
...updated[0],
|
||||
title:
|
||||
|
|
@ -275,15 +273,7 @@ export function AppSidebarProvider({
|
|||
};
|
||||
}
|
||||
return updated;
|
||||
}, [
|
||||
navSecondary,
|
||||
isClient,
|
||||
searchSpace?.name,
|
||||
isLoadingSearchSpace,
|
||||
searchSpaceError,
|
||||
t,
|
||||
tCommon,
|
||||
]);
|
||||
}, [navSecondary, searchSpace?.name, isLoadingSearchSpace, searchSpaceError, t, tCommon]);
|
||||
|
||||
// Prepare page usage data
|
||||
const pageUsage = user
|
||||
|
|
@ -293,21 +283,6 @@ export function AppSidebarProvider({
|
|||
}
|
||||
: undefined;
|
||||
|
||||
// Show loading state if not client-side
|
||||
if (!isClient) {
|
||||
return (
|
||||
<AppSidebar
|
||||
searchSpaceId={searchSpaceId}
|
||||
navSecondary={navSecondary}
|
||||
navMain={navMain}
|
||||
RecentChats={[]}
|
||||
RecentNotes={[]}
|
||||
onAddNote={handleAddNote}
|
||||
pageUsage={pageUsage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppSidebar
|
||||
|
|
@ -329,25 +304,25 @@ export function AppSidebarProvider({
|
|||
<span>{t("delete_chat")}</span>
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("delete_chat_confirm")} <span className="font-medium">{chatToDelete?.name}</span>?{" "}
|
||||
{t("action_cannot_undone")}
|
||||
{t("delete_chat_confirm")} <span className="font-medium">{threadToDelete?.name}</span>
|
||||
? {t("action_cannot_undone")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter className="flex gap-2 sm:justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowDeleteDialog(false)}
|
||||
disabled={isDeletingChat}
|
||||
disabled={isDeletingThread}
|
||||
>
|
||||
{tCommon("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDeleteChat}
|
||||
disabled={isDeletingChat}
|
||||
onClick={handleDeleteThread}
|
||||
disabled={isDeletingThread}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDeletingChat ? (
|
||||
{isDeletingThread ? (
|
||||
<>
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
|
||||
{t("deleting")}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,16 @@
|
|||
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { format } from "date-fns";
|
||||
import { Loader2, MessageCircleMore, MoreHorizontal, Search, Trash2, X } from "lucide-react";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
Loader2,
|
||||
MessageCircleMore,
|
||||
MoreHorizontal,
|
||||
RotateCcwIcon,
|
||||
Search,
|
||||
Trash2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useCallback, useState } from "react";
|
||||
|
|
@ -12,6 +21,7 @@ import {
|
|||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
|
@ -25,7 +35,13 @@ import {
|
|||
} from "@/components/ui/sheet";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { chatsApiService } from "@/lib/apis/chats-api.service";
|
||||
import {
|
||||
deleteThread,
|
||||
fetchThreads,
|
||||
searchThreads,
|
||||
type ThreadListItem,
|
||||
updateThread,
|
||||
} from "@/lib/chat/thread-persistence";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface AllChatsSidebarProps {
|
||||
|
|
@ -38,70 +54,85 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
const t = useTranslations("sidebar");
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [deletingChatId, setDeletingChatId] = useState<number | null>(null);
|
||||
const [deletingThreadId, setDeletingThreadId] = useState<number | null>(null);
|
||||
const [archivingThreadId, setArchivingThreadId] = useState<number | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const debouncedSearchQuery = useDebouncedValue(searchQuery, 300);
|
||||
|
||||
const isSearchMode = !!debouncedSearchQuery.trim();
|
||||
|
||||
// Fetch all chats (when not searching)
|
||||
// Fetch all threads (when not searching)
|
||||
const {
|
||||
data: chatsData,
|
||||
error: chatsError,
|
||||
isLoading: isLoadingChats,
|
||||
data: threadsData,
|
||||
error: threadsError,
|
||||
isLoading: isLoadingThreads,
|
||||
} = useQuery({
|
||||
queryKey: ["all-chats", searchSpaceId],
|
||||
queryFn: () =>
|
||||
chatsApiService.getChats({
|
||||
queryParams: {
|
||||
search_space_id: Number(searchSpaceId),
|
||||
},
|
||||
}),
|
||||
queryKey: ["all-threads", searchSpaceId],
|
||||
queryFn: () => fetchThreads(Number(searchSpaceId)),
|
||||
enabled: !!searchSpaceId && open && !isSearchMode,
|
||||
});
|
||||
|
||||
// Search chats (when searching)
|
||||
// Search threads (when searching)
|
||||
const {
|
||||
data: searchData,
|
||||
error: searchError,
|
||||
isLoading: isLoadingSearch,
|
||||
} = useQuery({
|
||||
queryKey: ["search-chats", searchSpaceId, debouncedSearchQuery],
|
||||
queryFn: () =>
|
||||
chatsApiService.searchChats({
|
||||
queryParams: {
|
||||
title: debouncedSearchQuery.trim(),
|
||||
search_space_id: Number(searchSpaceId),
|
||||
},
|
||||
}),
|
||||
queryKey: ["search-threads", searchSpaceId, debouncedSearchQuery],
|
||||
queryFn: () => searchThreads(Number(searchSpaceId), debouncedSearchQuery.trim()),
|
||||
enabled: !!searchSpaceId && open && isSearchMode,
|
||||
});
|
||||
|
||||
// Handle chat navigation
|
||||
const handleChatClick = useCallback(
|
||||
(chatId: number, chatSearchSpaceId: number) => {
|
||||
router.push(`/dashboard/${chatSearchSpaceId}/researcher/${chatId}`);
|
||||
// Handle thread navigation
|
||||
const handleThreadClick = useCallback(
|
||||
(threadId: number) => {
|
||||
router.push(`/dashboard/${searchSpaceId}/new-chat/${threadId}`);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[router, onOpenChange]
|
||||
[router, onOpenChange, searchSpaceId]
|
||||
);
|
||||
|
||||
// Handle chat deletion
|
||||
const handleDeleteChat = useCallback(
|
||||
async (chatId: number) => {
|
||||
setDeletingChatId(chatId);
|
||||
// Handle thread deletion
|
||||
const handleDeleteThread = useCallback(
|
||||
async (threadId: number) => {
|
||||
setDeletingThreadId(threadId);
|
||||
try {
|
||||
await chatsApiService.deleteChat({ id: chatId });
|
||||
await deleteThread(threadId);
|
||||
toast.success(t("chat_deleted") || "Chat deleted successfully");
|
||||
// Invalidate queries to refresh the list
|
||||
queryClient.invalidateQueries({ queryKey: ["all-chats", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["search-chats", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["chats"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["all-threads", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["search-threads", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["threads", searchSpaceId] });
|
||||
} catch (error) {
|
||||
console.error("Error deleting chat:", error);
|
||||
console.error("Error deleting thread:", error);
|
||||
toast.error(t("error_deleting_chat") || "Failed to delete chat");
|
||||
} finally {
|
||||
setDeletingChatId(null);
|
||||
setDeletingThreadId(null);
|
||||
}
|
||||
},
|
||||
[queryClient, searchSpaceId, t]
|
||||
);
|
||||
|
||||
// Handle thread archive/unarchive
|
||||
const handleToggleArchive = useCallback(
|
||||
async (threadId: number, currentlyArchived: boolean) => {
|
||||
setArchivingThreadId(threadId);
|
||||
try {
|
||||
await updateThread(threadId, { archived: !currentlyArchived });
|
||||
toast.success(
|
||||
currentlyArchived
|
||||
? t("chat_unarchived") || "Chat restored"
|
||||
: t("chat_archived") || "Chat archived"
|
||||
);
|
||||
queryClient.invalidateQueries({ queryKey: ["all-threads", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["search-threads", searchSpaceId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["threads", searchSpaceId] });
|
||||
} catch (error) {
|
||||
console.error("Error archiving thread:", error);
|
||||
toast.error(t("error_archiving_chat") || "Failed to archive chat");
|
||||
} finally {
|
||||
setArchivingThreadId(null);
|
||||
}
|
||||
},
|
||||
[queryClient, searchSpaceId, t]
|
||||
|
|
@ -112,10 +143,20 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
setSearchQuery("");
|
||||
}, []);
|
||||
|
||||
// Determine which data source to use and loading/error states
|
||||
const chats = isSearchMode ? (searchData ?? []) : (chatsData ?? []);
|
||||
const isLoading = isSearchMode ? isLoadingSearch : isLoadingChats;
|
||||
const error = isSearchMode ? searchError : chatsError;
|
||||
// Determine which data source to use
|
||||
let threads: ThreadListItem[] = [];
|
||||
if (isSearchMode) {
|
||||
threads = searchData ?? [];
|
||||
} else if (threadsData) {
|
||||
threads = showArchived ? threadsData.archived_threads : threadsData.threads;
|
||||
}
|
||||
|
||||
const isLoading = isSearchMode ? isLoadingSearch : isLoadingThreads;
|
||||
const error = isSearchMode ? searchError : threadsError;
|
||||
|
||||
// Get counts for tabs
|
||||
const activeCount = threadsData?.threads.length ?? 0;
|
||||
const archivedCount = threadsData?.archived_threads.length ?? 0;
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
|
|
@ -150,6 +191,36 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
{/* Tab toggle for active/archived (only show when not searching) */}
|
||||
{!isSearchMode && (
|
||||
<div className="flex border-b mx-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowArchived(false)}
|
||||
className={cn(
|
||||
"flex-1 px-3 py-2 text-center text-xs font-medium transition-colors",
|
||||
!showArchived
|
||||
? "border-b-2 border-primary text-primary"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Active ({activeCount})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowArchived(true)}
|
||||
className={cn(
|
||||
"flex-1 px-3 py-2 text-center text-xs font-medium transition-colors",
|
||||
showArchived
|
||||
? "border-b-2 border-primary text-primary"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Archived ({archivedCount})
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-2">
|
||||
{isLoading ? (
|
||||
|
|
@ -160,19 +231,21 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
<div className="text-center py-8 text-sm text-destructive">
|
||||
{t("error_loading_chats") || "Error loading chats"}
|
||||
</div>
|
||||
) : chats.length > 0 ? (
|
||||
) : threads.length > 0 ? (
|
||||
<div className="space-y-1">
|
||||
{chats.map((chat) => {
|
||||
const isDeleting = deletingChatId === chat.id;
|
||||
{threads.map((thread) => {
|
||||
const isDeleting = deletingThreadId === thread.id;
|
||||
const isArchiving = archivingThreadId === thread.id;
|
||||
const isBusy = isDeleting || isArchiving;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={chat.id}
|
||||
key={thread.id}
|
||||
className={cn(
|
||||
"group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm",
|
||||
"hover:bg-accent hover:text-accent-foreground",
|
||||
"transition-colors cursor-pointer",
|
||||
isDeleting && "opacity-50 pointer-events-none"
|
||||
isBusy && "opacity-50 pointer-events-none"
|
||||
)}
|
||||
>
|
||||
{/* Main clickable area for navigation */}
|
||||
|
|
@ -180,23 +253,23 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleChatClick(chat.id, chat.search_space_id)}
|
||||
disabled={isDeleting}
|
||||
onClick={() => handleThreadClick(thread.id)}
|
||||
disabled={isBusy}
|
||||
className="flex items-center gap-2 flex-1 min-w-0 text-left"
|
||||
>
|
||||
<MessageCircleMore className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<span className="truncate">{chat.title}</span>
|
||||
<span className="truncate">{thread.title || "New Chat"}</span>
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">
|
||||
<p>
|
||||
{t("created") || "Created"}:{" "}
|
||||
{format(new Date(chat.created_at), "MMM d, yyyy 'at' h:mm a")}
|
||||
{t("updated") || "Updated"}:{" "}
|
||||
{format(new Date(thread.updatedAt), "MMM d, yyyy 'at' h:mm a")}
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{/* Actions dropdown - separate from main click area */}
|
||||
{/* Actions dropdown */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
|
|
@ -207,7 +280,7 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
"opacity-0 group-hover:opacity-100 focus:opacity-100",
|
||||
"transition-opacity"
|
||||
)}
|
||||
disabled={isDeleting}
|
||||
disabled={isBusy}
|
||||
>
|
||||
{isDeleting ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
|
|
@ -219,7 +292,24 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40">
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDeleteChat(chat.id)}
|
||||
onClick={() => handleToggleArchive(thread.id, thread.archived)}
|
||||
disabled={isArchiving}
|
||||
>
|
||||
{thread.archived ? (
|
||||
<>
|
||||
<RotateCcwIcon className="mr-2 h-4 w-4" />
|
||||
<span>{t("unarchive") || "Restore"}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<ArchiveIcon className="mr-2 h-4 w-4" />
|
||||
<span>{t("archive") || "Archive"}</span>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDeleteThread(thread.id)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
|
|
@ -244,10 +334,16 @@ export function AllChatsSidebar({ open, onOpenChange, searchSpaceId }: AllChatsS
|
|||
) : (
|
||||
<div className="text-center py-8">
|
||||
<MessageCircleMore className="h-12 w-12 mx-auto text-muted-foreground/50 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">{t("no_chats") || "No chats yet"}</p>
|
||||
<p className="text-xs text-muted-foreground/70 mt-1">
|
||||
{t("start_new_chat_hint") || "Start a new chat from the researcher"}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{showArchived
|
||||
? t("no_archived_chats") || "No archived chats"
|
||||
: t("no_chats") || "No chats yet"}
|
||||
</p>
|
||||
{!showArchived && (
|
||||
<p className="text-xs text-muted-foreground/70 mt-1">
|
||||
{t("start_new_chat_hint") || "Start a new chat from the chat page"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -25,15 +25,7 @@ function formatTime(seconds: number): string {
|
|||
return `${mins}:${secs.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function Audio({
|
||||
id,
|
||||
src,
|
||||
title,
|
||||
description,
|
||||
artwork,
|
||||
durationMs,
|
||||
className,
|
||||
}: AudioProps) {
|
||||
export function Audio({ id, src, title, description, artwork, durationMs, className }: AudioProps) {
|
||||
const audioRef = useRef<HTMLAudioElement>(null);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
|
|
@ -158,7 +150,7 @@ export function Audio({
|
|||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-4 rounded-xl border border-destructive/20 bg-destructive/5 p-4",
|
||||
className,
|
||||
className
|
||||
)}
|
||||
>
|
||||
<div className="flex size-16 items-center justify-center rounded-lg bg-destructive/10">
|
||||
|
|
@ -177,7 +169,7 @@ export function Audio({
|
|||
id={id}
|
||||
className={cn(
|
||||
"group relative overflow-hidden rounded-xl border bg-gradient-to-br from-background to-muted/30 p-4 shadow-sm transition-all hover:shadow-md",
|
||||
className,
|
||||
className
|
||||
)}
|
||||
>
|
||||
{/* Hidden audio element */}
|
||||
|
|
@ -190,13 +182,7 @@ export function Audio({
|
|||
<div className="relative shrink-0">
|
||||
<div className="relative size-20 overflow-hidden rounded-lg bg-gradient-to-br from-primary/20 to-primary/5 shadow-inner">
|
||||
{artwork ? (
|
||||
<Image
|
||||
src={artwork}
|
||||
alt={title}
|
||||
fill
|
||||
className="object-cover"
|
||||
unoptimized
|
||||
/>
|
||||
<Image src={artwork} alt={title} fill className="object-cover" unoptimized />
|
||||
) : (
|
||||
<div className="flex size-full items-center justify-center">
|
||||
<Volume2Icon className="size-8 text-primary/50" />
|
||||
|
|
@ -224,9 +210,7 @@ export function Audio({
|
|||
<div className="min-w-0">
|
||||
<h3 className="truncate font-semibold text-foreground">{title}</h3>
|
||||
{description && (
|
||||
<p className="mt-0.5 line-clamp-1 text-muted-foreground text-sm">
|
||||
{description}
|
||||
</p>
|
||||
<p className="mt-0.5 line-clamp-1 text-muted-foreground text-sm">{description}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
|
@ -271,17 +255,8 @@ export function Audio({
|
|||
|
||||
{/* Volume control */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleMute}
|
||||
className="size-8"
|
||||
>
|
||||
{isMuted ? (
|
||||
<VolumeXIcon className="size-4" />
|
||||
) : (
|
||||
<Volume2Icon className="size-4" />
|
||||
)}
|
||||
<Button variant="ghost" size="icon" onClick={toggleMute} className="size-8">
|
||||
{isMuted ? <VolumeXIcon className="size-4" /> : <Volume2Icon className="size-4" />}
|
||||
</Button>
|
||||
<Slider
|
||||
value={[isMuted ? 0 : volume]}
|
||||
|
|
@ -294,12 +269,7 @@ export function Audio({
|
|||
</div>
|
||||
|
||||
{/* Download button */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDownload}
|
||||
className="gap-2"
|
||||
>
|
||||
<Button variant="outline" size="sm" onClick={handleDownload} className="gap-2">
|
||||
<DownloadIcon className="size-4" />
|
||||
Download
|
||||
</Button>
|
||||
|
|
@ -307,4 +277,3 @@ export function Audio({
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,13 +4,10 @@ import { makeAssistantToolUI } from "@assistant-ui/react";
|
|||
import { AlertCircleIcon, Loader2Icon, MicIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Audio } from "@/components/tool-ui/audio";
|
||||
import type { PodcastTranscriptEntry } from "@/contracts/types/podcast.types";
|
||||
import { baseApiService } from "@/lib/apis/base-api.service";
|
||||
import { podcastsApiService } from "@/lib/apis/podcasts-api.service";
|
||||
import {
|
||||
clearActivePodcastTaskId,
|
||||
setActivePodcastTaskId,
|
||||
} from "@/lib/chat/podcast-state";
|
||||
import type { PodcastTranscriptEntry } from "@/contracts/types/podcast.types";
|
||||
import { clearActivePodcastTaskId, setActivePodcastTaskId } from "@/lib/chat/podcast-state";
|
||||
|
||||
/**
|
||||
* Type definitions for the generate_podcast tool
|
||||
|
|
@ -223,9 +220,7 @@ function PodcastPlayer({
|
|||
<div className="mt-3 space-y-3 max-h-96 overflow-y-auto">
|
||||
{transcript.map((entry, idx) => (
|
||||
<div key={`${idx}-${entry.speaker_id}`} className="text-sm">
|
||||
<span className="font-medium text-primary">
|
||||
Speaker {entry.speaker_id + 1}:
|
||||
</span>{" "}
|
||||
<span className="font-medium text-primary">Speaker {entry.speaker_id + 1}:</span>{" "}
|
||||
<span className="text-muted-foreground">{entry.dialog}</span>
|
||||
</div>
|
||||
))}
|
||||
|
|
@ -239,13 +234,7 @@ function PodcastPlayer({
|
|||
/**
|
||||
* Polling component that checks task status and shows player when complete
|
||||
*/
|
||||
function PodcastTaskPoller({
|
||||
taskId,
|
||||
title,
|
||||
}: {
|
||||
taskId: string;
|
||||
title: string;
|
||||
}) {
|
||||
function PodcastTaskPoller({ taskId, title }: { taskId: string; title: string }) {
|
||||
const [taskStatus, setTaskStatus] = useState<TaskStatusResponse>({ status: "processing" });
|
||||
const pollingRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
|
|
|
|||
|
|
@ -8,4 +8,3 @@
|
|||
|
||||
export { Audio } from "./audio";
|
||||
export { GeneratePodcastToolUI } from "./generate-podcast";
|
||||
|
||||
|
|
|
|||
|
|
@ -71,4 +71,3 @@ export function looksLikePodcastRequest(message: string): boolean {
|
|||
|
||||
return podcastPatterns.some((pattern) => pattern.test(message));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -51,11 +51,26 @@ export interface ThreadHistoryLoadResponse {
|
|||
* Fetch list of threads for a search space
|
||||
*/
|
||||
export async function fetchThreads(
|
||||
searchSpaceId: number
|
||||
searchSpaceId: number,
|
||||
limit?: number
|
||||
): Promise<ThreadListResponse> {
|
||||
return baseApiService.get<ThreadListResponse>(
|
||||
`/api/v1/threads?search_space_id=${searchSpaceId}`
|
||||
);
|
||||
const params = new URLSearchParams({ search_space_id: String(searchSpaceId) });
|
||||
if (limit) params.append("limit", String(limit));
|
||||
return baseApiService.get<ThreadListResponse>(`/api/v1/threads?${params}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search threads by title
|
||||
*/
|
||||
export async function searchThreads(
|
||||
searchSpaceId: number,
|
||||
title: string
|
||||
): Promise<ThreadListItem[]> {
|
||||
const params = new URLSearchParams({
|
||||
search_space_id: String(searchSpaceId),
|
||||
title,
|
||||
});
|
||||
return baseApiService.get<ThreadListItem[]>(`/api/v1/threads/search?${params}`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -77,12 +92,8 @@ export async function createThread(
|
|||
/**
|
||||
* Get thread messages
|
||||
*/
|
||||
export async function getThreadMessages(
|
||||
threadId: number
|
||||
): Promise<ThreadHistoryLoadResponse> {
|
||||
return baseApiService.get<ThreadHistoryLoadResponse>(
|
||||
`/api/v1/threads/${threadId}`
|
||||
);
|
||||
export async function getThreadMessages(threadId: number): Promise<ThreadHistoryLoadResponse> {
|
||||
return baseApiService.get<ThreadHistoryLoadResponse>(`/api/v1/threads/${threadId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -92,11 +103,9 @@ export async function appendMessage(
|
|||
threadId: number,
|
||||
message: { role: "user" | "assistant" | "system"; content: unknown }
|
||||
): Promise<MessageRecord> {
|
||||
return baseApiService.post<MessageRecord>(
|
||||
`/api/v1/threads/${threadId}/messages`,
|
||||
undefined,
|
||||
{ body: message }
|
||||
);
|
||||
return baseApiService.post<MessageRecord>(`/api/v1/threads/${threadId}/messages`, undefined, {
|
||||
body: message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -106,11 +115,9 @@ export async function updateThread(
|
|||
threadId: number,
|
||||
updates: { title?: string; archived?: boolean }
|
||||
): Promise<ThreadRecord> {
|
||||
return baseApiService.put<ThreadRecord>(
|
||||
`/api/v1/threads/${threadId}`,
|
||||
undefined,
|
||||
{ body: updates }
|
||||
);
|
||||
return baseApiService.put<ThreadRecord>(`/api/v1/threads/${threadId}`, undefined, {
|
||||
body: updates,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -159,8 +166,7 @@ export function createThreadListManager(config: ThreadListAdapterConfig) {
|
|||
threads: [],
|
||||
archivedThreads: [],
|
||||
isLoading: false,
|
||||
error:
|
||||
error instanceof Error ? error.message : "Failed to load threads",
|
||||
error: error instanceof Error ? error.message : "Failed to load threads",
|
||||
};
|
||||
}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -669,7 +669,13 @@
|
|||
"more_options": "More options",
|
||||
"clear_search": "Clear search",
|
||||
"view_all_notes": "View all notes",
|
||||
"add_note": "Add note"
|
||||
"add_note": "Add note",
|
||||
"archive": "Archive",
|
||||
"unarchive": "Restore",
|
||||
"chat_archived": "Chat archived",
|
||||
"chat_unarchived": "Chat restored",
|
||||
"no_archived_chats": "No archived chats",
|
||||
"error_archiving_chat": "Failed to archive chat"
|
||||
},
|
||||
"errors": {
|
||||
"something_went_wrong": "Something went wrong",
|
||||
|
|
|
|||
|
|
@ -33,4 +33,3 @@
|
|||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue