mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-04-25 00:36:31 +02:00
Merge pull request #476 from MODSetter/dev
refactor(ux): moved podcasts to chat artifacts
This commit is contained in:
commit
a7ee0232b6
39 changed files with 1467 additions and 76 deletions
|
|
@ -0,0 +1,60 @@
|
|||
"""Add podcast staleness detection columns to chats and podcasts tables
|
||||
|
||||
This feature allows the system to detect when a podcast is outdated compared to
|
||||
the current state of the chat it was generated from, enabling users to regenerate
|
||||
podcasts when needed.
|
||||
|
||||
Revision ID: 34
|
||||
Revises: 33
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers
|
||||
revision: str = "34"
|
||||
down_revision: str | None = "33"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Add columns only if they don't already exist (safe for re-runs)."""
|
||||
|
||||
# Add 'state_version' column to chats table (default 1)
|
||||
op.execute("""
|
||||
ALTER TABLE chats
|
||||
ADD COLUMN IF NOT EXISTS state_version BIGINT DEFAULT 1 NOT NULL
|
||||
""")
|
||||
|
||||
# Add 'chat_state_version' column to podcasts table
|
||||
op.execute("""
|
||||
ALTER TABLE podcasts
|
||||
ADD COLUMN IF NOT EXISTS chat_state_version BIGINT
|
||||
""")
|
||||
|
||||
# Add 'chat_id' column to podcasts table
|
||||
op.execute("""
|
||||
ALTER TABLE podcasts
|
||||
ADD COLUMN IF NOT EXISTS chat_id INTEGER
|
||||
""")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Remove columns only if they exist."""
|
||||
|
||||
op.execute("""
|
||||
ALTER TABLE podcasts
|
||||
DROP COLUMN IF EXISTS chat_state_version
|
||||
""")
|
||||
|
||||
op.execute("""
|
||||
ALTER TABLE podcasts
|
||||
DROP COLUMN IF EXISTS chat_id
|
||||
""")
|
||||
|
||||
op.execute("""
|
||||
ALTER TABLE chats
|
||||
DROP COLUMN IF EXISTS state_version
|
||||
""")
|
||||
|
|
@ -18,6 +18,7 @@ class Configuration:
|
|||
podcast_title: str
|
||||
user_id: str
|
||||
search_space_id: int
|
||||
user_prompt: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_runnable_config(
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ async def create_podcast_transcript(
|
|||
configuration = Configuration.from_runnable_config(config)
|
||||
user_id = configuration.user_id
|
||||
search_space_id = configuration.search_space_id
|
||||
user_prompt = configuration.user_prompt
|
||||
|
||||
# Get user's long context LLM
|
||||
llm = await get_user_long_context_llm(state.db_session, user_id, search_space_id)
|
||||
|
|
@ -38,7 +39,7 @@ async def create_podcast_transcript(
|
|||
raise RuntimeError(error_message)
|
||||
|
||||
# Get the prompt
|
||||
prompt = get_podcast_generation_prompt()
|
||||
prompt = get_podcast_generation_prompt(user_prompt)
|
||||
|
||||
# Create the messages
|
||||
messages = [
|
||||
|
|
@ -98,10 +99,10 @@ async def create_merged_podcast_audio(
|
|||
) -> dict[str, Any]:
|
||||
"""Generate audio for each transcript and merge them into a single podcast file."""
|
||||
|
||||
configuration = Configuration.from_runnable_config(config)
|
||||
# configuration = Configuration.from_runnable_config(config)
|
||||
|
||||
starting_transcript = PodcastTranscriptEntry(
|
||||
speaker_id=1, dialog=f"Welcome to {configuration.podcast_title} Podcast."
|
||||
speaker_id=1, dialog="Welcome to Surfsense Podcast."
|
||||
)
|
||||
|
||||
transcript = state.podcast_transcript
|
||||
|
|
|
|||
|
|
@ -1,12 +1,23 @@
|
|||
import datetime
|
||||
|
||||
|
||||
def get_podcast_generation_prompt():
|
||||
def get_podcast_generation_prompt(user_prompt: str | None = None):
|
||||
return f"""
|
||||
Today's date: {datetime.datetime.now().strftime("%Y-%m-%d")}
|
||||
<podcast_generation_system>
|
||||
You are a master podcast scriptwriter, adept at transforming diverse input content into a lively, engaging, and natural-sounding conversation between two distinct podcast hosts. Your primary objective is to craft authentic, flowing dialogue that captures the spontaneity and chemistry of a real podcast discussion, completely avoiding any hint of robotic scripting or stiff formality. Think dynamic interplay, not just information delivery.
|
||||
|
||||
{
|
||||
f'''
|
||||
You **MUST** strictly adhere to the following user instruction while generating the podcast script:
|
||||
<user_instruction>
|
||||
{user_prompt}
|
||||
</user_instruction>
|
||||
'''
|
||||
if user_prompt
|
||||
else ""
|
||||
}
|
||||
|
||||
<input>
|
||||
- '<source_content>': A block of text containing the information to be discussed in the podcast. This could be research findings, an article summary, a detailed outline, user chat history related to the topic, or any other relevant raw information. The content might be unstructured but serves as the factual basis for the podcast dialogue.
|
||||
</input>
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ from sqlalchemy import (
|
|||
ARRAY,
|
||||
JSON,
|
||||
TIMESTAMP,
|
||||
BigInteger,
|
||||
Boolean,
|
||||
Column,
|
||||
Enum as SQLAlchemyEnum,
|
||||
|
|
@ -157,6 +158,7 @@ class Chat(BaseModel, TimestampMixin):
|
|||
title = Column(String, nullable=False, index=True)
|
||||
initial_connectors = Column(ARRAY(String), nullable=True)
|
||||
messages = Column(JSON, nullable=False)
|
||||
state_version = Column(BigInteger, nullable=False, default=1)
|
||||
|
||||
search_space_id = Column(
|
||||
Integer, ForeignKey("searchspaces.id", ondelete="CASCADE"), nullable=False
|
||||
|
|
@ -203,6 +205,10 @@ class Podcast(BaseModel, TimestampMixin):
|
|||
title = Column(String, nullable=False, index=True)
|
||||
podcast_transcript = Column(JSON, nullable=False, default={})
|
||||
file_location = Column(String(500), nullable=False, default="")
|
||||
chat_id = Column(
|
||||
Integer, ForeignKey("chats.id", ondelete="CASCADE"), nullable=True
|
||||
) # If generated from a chat, this will be the chat id, else null ( can be from a document or a chat )
|
||||
chat_state_version = Column(BigInteger, nullable=True)
|
||||
|
||||
search_space_id = Column(
|
||||
Integer, ForeignKey("searchspaces.id", ondelete="CASCADE"), nullable=False
|
||||
|
|
|
|||
|
|
@ -199,6 +199,7 @@ async def read_chats(
|
|||
Chat.initial_connectors,
|
||||
Chat.search_space_id,
|
||||
Chat.created_at,
|
||||
Chat.state_version,
|
||||
)
|
||||
.join(SearchSpace)
|
||||
.filter(SearchSpace.user_id == user.id)
|
||||
|
|
@ -261,7 +262,10 @@ async def update_chat(
|
|||
db_chat = await read_chat(chat_id, session, user)
|
||||
update_data = chat_update.model_dump(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
if key == "messages":
|
||||
db_chat.state_version = len(update_data["messages"])
|
||||
setattr(db_chat, key, value)
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(db_chat)
|
||||
return db_chat
|
||||
|
|
|
|||
|
|
@ -155,7 +155,11 @@ async def delete_podcast(
|
|||
|
||||
|
||||
async def generate_chat_podcast_with_new_session(
|
||||
chat_id: int, search_space_id: int, podcast_title: str, user_id: int
|
||||
chat_id: int,
|
||||
search_space_id: int,
|
||||
user_id: int,
|
||||
podcast_title: str | None = None,
|
||||
user_prompt: str | None = None,
|
||||
):
|
||||
"""Create a new session and process chat podcast generation."""
|
||||
from app.db import async_session_maker
|
||||
|
|
@ -163,7 +167,7 @@ async def generate_chat_podcast_with_new_session(
|
|||
async with async_session_maker() as session:
|
||||
try:
|
||||
await generate_chat_podcast(
|
||||
session, chat_id, search_space_id, podcast_title, user_id
|
||||
session, chat_id, search_space_id, user_id, podcast_title, user_prompt
|
||||
)
|
||||
except Exception as e:
|
||||
import logging
|
||||
|
|
@ -211,7 +215,11 @@ async def generate_podcast(
|
|||
# Add Celery tasks for each chat ID
|
||||
for chat_id in valid_chat_ids:
|
||||
generate_chat_podcast_task.delay(
|
||||
chat_id, request.search_space_id, request.podcast_title, user.id
|
||||
chat_id,
|
||||
request.search_space_id,
|
||||
user.id,
|
||||
request.podcast_title,
|
||||
request.user_prompt,
|
||||
)
|
||||
|
||||
return {
|
||||
|
|
@ -287,3 +295,27 @@ async def stream_podcast(
|
|||
raise HTTPException(
|
||||
status_code=500, detail=f"Error streaming podcast: {e!s}"
|
||||
) from e
|
||||
|
||||
|
||||
@router.get("/podcasts/by-chat/{chat_id}", response_model=PodcastRead | None)
|
||||
async def get_podcast_by_chat_id(
|
||||
chat_id: int,
|
||||
session: AsyncSession = Depends(get_async_session),
|
||||
user: User = Depends(current_active_user),
|
||||
):
|
||||
try:
|
||||
# Get the podcast and check if user has access
|
||||
result = await session.execute(
|
||||
select(Podcast)
|
||||
.join(SearchSpace)
|
||||
.filter(Podcast.chat_id == chat_id, SearchSpace.user_id == user.id)
|
||||
)
|
||||
podcast = result.scalars().first()
|
||||
|
||||
return podcast
|
||||
except HTTPException as he:
|
||||
raise he
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=500, detail=f"Error fetching podcast: {e!s}"
|
||||
) from e
|
||||
|
|
|
|||
|
|
@ -13,12 +13,14 @@ class ChatBase(BaseModel):
|
|||
initial_connectors: list[str] | None = None
|
||||
messages: list[Any]
|
||||
search_space_id: int
|
||||
state_version: int = 1
|
||||
|
||||
|
||||
class ChatBaseWithoutMessages(BaseModel):
|
||||
type: ChatType
|
||||
title: str
|
||||
search_space_id: int
|
||||
state_version: int = 1
|
||||
|
||||
|
||||
class ClientAttachment(BaseModel):
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ class PodcastBase(BaseModel):
|
|||
podcast_transcript: list[Any]
|
||||
file_location: str = ""
|
||||
search_space_id: int
|
||||
chat_state_version: int | None = None
|
||||
|
||||
|
||||
class PodcastCreate(PodcastBase):
|
||||
|
|
@ -28,4 +29,5 @@ class PodcastGenerateRequest(BaseModel):
|
|||
type: Literal["DOCUMENT", "CHAT"]
|
||||
ids: list[int]
|
||||
search_space_id: int
|
||||
podcast_title: str = "SurfSense Podcast"
|
||||
podcast_title: str | None = None
|
||||
user_prompt: str | None = None
|
||||
|
|
|
|||
|
|
@ -38,7 +38,12 @@ def get_celery_session_maker():
|
|||
|
||||
@celery_app.task(name="generate_chat_podcast", bind=True)
|
||||
def generate_chat_podcast_task(
|
||||
self, chat_id: int, search_space_id: int, podcast_title: str, user_id: int
|
||||
self,
|
||||
chat_id: int,
|
||||
search_space_id: int,
|
||||
user_id: int,
|
||||
podcast_title: str | None = None,
|
||||
user_prompt: str | None = None,
|
||||
):
|
||||
"""
|
||||
Celery task to generate podcast from chat.
|
||||
|
|
@ -46,15 +51,18 @@ def generate_chat_podcast_task(
|
|||
Args:
|
||||
chat_id: ID of the chat to generate podcast from
|
||||
search_space_id: ID of the search space
|
||||
user_id: ID of the user,
|
||||
podcast_title: Title for the podcast
|
||||
user_id: ID of the user
|
||||
user_prompt: Optional prompt from the user to guide the podcast generation
|
||||
"""
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
_generate_chat_podcast(chat_id, search_space_id, podcast_title, user_id)
|
||||
_generate_chat_podcast(
|
||||
chat_id, search_space_id, user_id, podcast_title, user_prompt
|
||||
)
|
||||
)
|
||||
loop.run_until_complete(loop.shutdown_asyncgens())
|
||||
finally:
|
||||
|
|
@ -63,13 +71,17 @@ def generate_chat_podcast_task(
|
|||
|
||||
|
||||
async def _generate_chat_podcast(
|
||||
chat_id: int, search_space_id: int, podcast_title: str, user_id: int
|
||||
chat_id: int,
|
||||
search_space_id: int,
|
||||
user_id: int,
|
||||
podcast_title: str | None = None,
|
||||
user_prompt: str | None = None,
|
||||
):
|
||||
"""Generate chat podcast with new session."""
|
||||
async with get_celery_session_maker()() as session:
|
||||
try:
|
||||
await generate_chat_podcast(
|
||||
session, chat_id, search_space_id, podcast_title, user_id
|
||||
session, chat_id, search_space_id, user_id, podcast_title, user_prompt
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating podcast from chat: {e!s}")
|
||||
|
|
|
|||
|
|
@ -19,8 +19,9 @@ async def generate_chat_podcast(
|
|||
session: AsyncSession,
|
||||
chat_id: int,
|
||||
search_space_id: int,
|
||||
podcast_title: str,
|
||||
user_id: int,
|
||||
podcast_title: str | None = None,
|
||||
user_prompt: str | None = None,
|
||||
):
|
||||
task_logger = TaskLoggingService(session, search_space_id)
|
||||
|
||||
|
|
@ -34,6 +35,7 @@ async def generate_chat_podcast(
|
|||
"search_space_id": search_space_id,
|
||||
"podcast_title": podcast_title,
|
||||
"user_id": str(user_id),
|
||||
"user_prompt": user_prompt,
|
||||
},
|
||||
)
|
||||
|
||||
|
|
@ -96,9 +98,10 @@ async def generate_chat_podcast(
|
|||
|
||||
config = {
|
||||
"configurable": {
|
||||
"podcast_title": "SurfSense",
|
||||
"podcast_title": podcast_title or "SurfSense Podcast",
|
||||
"user_id": str(user_id),
|
||||
"search_space_id": search_space_id,
|
||||
"user_prompt": user_prompt,
|
||||
}
|
||||
}
|
||||
# Initialize state with database session and streaming service
|
||||
|
|
@ -139,33 +142,49 @@ async def generate_chat_podcast(
|
|||
},
|
||||
)
|
||||
|
||||
podcast = Podcast(
|
||||
title=f"{podcast_title}",
|
||||
podcast_transcript=serializable_transcript,
|
||||
file_location=result["final_podcast_file_path"],
|
||||
search_space_id=search_space_id,
|
||||
# check if podcast already exists for this chat (re-generation)
|
||||
existing_podcast = await session.execute(
|
||||
select(Podcast).filter(Podcast.chat_id == chat_id)
|
||||
)
|
||||
existing_podcast = existing_podcast.scalars().first()
|
||||
|
||||
# Add to session and commit
|
||||
session.add(podcast)
|
||||
await session.commit()
|
||||
await session.refresh(podcast)
|
||||
if existing_podcast:
|
||||
existing_podcast.podcast_transcript = serializable_transcript
|
||||
existing_podcast.file_location = result["final_podcast_file_path"]
|
||||
existing_podcast.chat_state_version = chat.state_version
|
||||
await session.commit()
|
||||
await session.refresh(existing_podcast)
|
||||
return existing_podcast
|
||||
else:
|
||||
podcast = Podcast(
|
||||
title=f"{podcast_title}",
|
||||
podcast_transcript=serializable_transcript,
|
||||
file_location=result["final_podcast_file_path"],
|
||||
search_space_id=search_space_id,
|
||||
chat_state_version=chat.state_version,
|
||||
chat_id=chat.id,
|
||||
)
|
||||
|
||||
# Log success
|
||||
await task_logger.log_task_success(
|
||||
log_entry,
|
||||
f"Successfully generated podcast for chat {chat_id}",
|
||||
{
|
||||
"podcast_id": podcast.id,
|
||||
"podcast_title": podcast_title,
|
||||
"transcript_entries": len(serializable_transcript),
|
||||
"file_location": result.get("final_podcast_file_path"),
|
||||
"processed_messages": processed_messages,
|
||||
"content_length": len(chat_history_str),
|
||||
},
|
||||
)
|
||||
# Add to session and commit
|
||||
session.add(podcast)
|
||||
await session.commit()
|
||||
await session.refresh(podcast)
|
||||
|
||||
return podcast
|
||||
# Log success
|
||||
await task_logger.log_task_success(
|
||||
log_entry,
|
||||
f"Successfully generated podcast for chat {chat_id}",
|
||||
{
|
||||
"podcast_id": podcast.id,
|
||||
"podcast_title": podcast_title,
|
||||
"transcript_entries": len(serializable_transcript),
|
||||
"file_location": result.get("final_podcast_file_path"),
|
||||
"processed_messages": processed_messages,
|
||||
"content_length": len(chat_history_str),
|
||||
},
|
||||
)
|
||||
|
||||
return podcast
|
||||
|
||||
except ValueError as ve:
|
||||
# ValueError is already logged above for chat not found
|
||||
|
|
|
|||
|
|
@ -56,12 +56,24 @@ import {
|
|||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface Chat {
|
||||
export interface Chat {
|
||||
created_at: string;
|
||||
id: number;
|
||||
type: string;
|
||||
type: "DOCUMENT" | "CHAT";
|
||||
title: string;
|
||||
search_space_id: number;
|
||||
state_version: number;
|
||||
}
|
||||
|
||||
export interface ChatDetails {
|
||||
type: "DOCUMENT" | "CHAT";
|
||||
title: string;
|
||||
initial_connectors: string[];
|
||||
messages: any[];
|
||||
created_at: string;
|
||||
id: number;
|
||||
search_space_id: number;
|
||||
state_version: number;
|
||||
}
|
||||
|
||||
interface ChatsPageClientProps {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
"use client";
|
||||
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { Loader2, PanelRight } from "lucide-react";
|
||||
import { AnimatePresence, motion } from "motion/react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import type React from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { ChatPanelContainer } from "@/components/chat/ChatPanel/ChatPanelContainer";
|
||||
import { DashboardBreadcrumb } from "@/components/dashboard-breadcrumb";
|
||||
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
|
||||
import { AppSidebarProvider } from "@/components/sidebar/AppSidebarProvider";
|
||||
|
|
@ -13,6 +16,9 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
|||
import { Separator } from "@/components/ui/separator";
|
||||
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
|
||||
import { useLLMPreferences } from "@/hooks/use-llm-configs";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { activeChatIdAtom } from "@/stores/chat/active-chat.atom";
|
||||
import { chatUIAtom } from "@/stores/chat/chat-ui.atom";
|
||||
|
||||
export function DashboardClientLayout({
|
||||
children,
|
||||
|
|
@ -30,6 +36,27 @@ export function DashboardClientLayout({
|
|||
const pathname = usePathname();
|
||||
const searchSpaceIdNum = Number(searchSpaceId);
|
||||
|
||||
const [chatUIState, setChatUIState] = useAtom(chatUIAtom);
|
||||
const activeChatId = useAtomValue(activeChatIdAtom);
|
||||
const [showIndicator, setShowIndicator] = useState(false);
|
||||
|
||||
const { isChatPannelOpen } = chatUIState;
|
||||
|
||||
// Check if we're on the researcher page
|
||||
const isResearcherPage = pathname?.includes("/researcher");
|
||||
|
||||
// Show indicator when chat becomes active and panel is closed
|
||||
useEffect(() => {
|
||||
if (activeChatId && !isChatPannelOpen) {
|
||||
setShowIndicator(true);
|
||||
// Hide indicator after 5 seconds
|
||||
const timer = setTimeout(() => setShowIndicator(false), 5000);
|
||||
return () => clearTimeout(timer);
|
||||
} else {
|
||||
setShowIndicator(false);
|
||||
}
|
||||
}, [activeChatId, isChatPannelOpen]);
|
||||
|
||||
const { loading, error, isOnboardingComplete } = useLLMPreferences(searchSpaceIdNum);
|
||||
const [hasCheckedOnboarding, setHasCheckedOnboarding] = useState(false);
|
||||
|
||||
|
|
@ -129,28 +156,137 @@ export function DashboardClientLayout({
|
|||
}
|
||||
|
||||
return (
|
||||
<SidebarProvider open={open} onOpenChange={setOpen}>
|
||||
<SidebarProvider
|
||||
className="h-full bg-red-600 overflow-hidden"
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
>
|
||||
{/* Use AppSidebarProvider which fetches user, search space, and recent chats */}
|
||||
<AppSidebarProvider
|
||||
searchSpaceId={searchSpaceId}
|
||||
navSecondary={translatedNavSecondary}
|
||||
navMain={translatedNavMain}
|
||||
/>
|
||||
<SidebarInset>
|
||||
<header className="sticky top-0 z-50 flex h-16 shrink-0 items-center gap-2 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b">
|
||||
<div className="flex items-center justify-between w-full gap-2 px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="h-6" />
|
||||
<DashboardBreadcrumb />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<LanguageSwitcher />
|
||||
<ThemeTogglerComponent />
|
||||
</div>
|
||||
<SidebarInset className="h-full ">
|
||||
<main className="flex h-full">
|
||||
<div className="flex grow flex-col h-full border-r">
|
||||
<header className="sticky top-0 z-50 flex h-16 shrink-0 items-center gap-2 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-b">
|
||||
<div className="flex items-center justify-between w-full gap-2 px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<SidebarTrigger className="-ml-1" />
|
||||
<Separator orientation="vertical" className="h-6" />
|
||||
<DashboardBreadcrumb />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<LanguageSwitcher />
|
||||
<ThemeTogglerComponent />
|
||||
{/* Only show artifacts toggle on researcher page */}
|
||||
{isResearcherPage && (
|
||||
<motion.div
|
||||
className="relative"
|
||||
animate={
|
||||
showIndicator
|
||||
? {
|
||||
scale: [1, 1.05, 1],
|
||||
}
|
||||
: {}
|
||||
}
|
||||
transition={{
|
||||
duration: 2,
|
||||
repeat: showIndicator ? Number.POSITIVE_INFINITY : 0,
|
||||
ease: "easeInOut",
|
||||
}}
|
||||
>
|
||||
<motion.button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setChatUIState((prev) => ({
|
||||
...prev,
|
||||
isChatPannelOpen: !isChatPannelOpen,
|
||||
}));
|
||||
setShowIndicator(false);
|
||||
}}
|
||||
className={cn(
|
||||
"shrink-0 rounded-full p-2 transition-all duration-300 relative",
|
||||
showIndicator
|
||||
? "bg-primary/20 hover:bg-primary/30 shadow-lg shadow-primary/25"
|
||||
: "hover:bg-muted",
|
||||
activeChatId && !showIndicator && "hover:bg-primary/10"
|
||||
)}
|
||||
title="Toggle Artifacts Panel"
|
||||
whileHover={{ scale: 1.05 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
>
|
||||
<motion.div
|
||||
animate={
|
||||
showIndicator
|
||||
? {
|
||||
rotate: [0, -10, 10, -10, 0],
|
||||
}
|
||||
: {}
|
||||
}
|
||||
transition={{
|
||||
duration: 0.5,
|
||||
repeat: showIndicator ? Number.POSITIVE_INFINITY : 0,
|
||||
repeatDelay: 2,
|
||||
}}
|
||||
>
|
||||
<PanelRight
|
||||
className={cn(
|
||||
"h-4 w-4 transition-colors",
|
||||
showIndicator && "text-primary"
|
||||
)}
|
||||
/>
|
||||
</motion.div>
|
||||
</motion.button>
|
||||
|
||||
{/* Pulsing indicator badge */}
|
||||
<AnimatePresence>
|
||||
{showIndicator && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0 }}
|
||||
className="absolute -right-1 -top-1 pointer-events-none"
|
||||
>
|
||||
<motion.div
|
||||
animate={{
|
||||
scale: [1, 1.3, 1],
|
||||
}}
|
||||
transition={{
|
||||
duration: 1.5,
|
||||
repeat: Number.POSITIVE_INFINITY,
|
||||
ease: "easeInOut",
|
||||
}}
|
||||
className="relative"
|
||||
>
|
||||
<div className="h-2.5 w-2.5 rounded-full bg-primary shadow-lg" />
|
||||
<motion.div
|
||||
animate={{
|
||||
scale: [1, 2.5, 1],
|
||||
opacity: [0.6, 0, 0.6],
|
||||
}}
|
||||
transition={{
|
||||
duration: 1.5,
|
||||
repeat: Number.POSITIVE_INFINITY,
|
||||
ease: "easeInOut",
|
||||
}}
|
||||
className="absolute inset-0 h-2.5 w-2.5 rounded-full bg-primary"
|
||||
/>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<div className="grow flex-1 overflow-auto">{children}</div>
|
||||
</div>
|
||||
</header>
|
||||
{children}
|
||||
{/* Only render chat panel on researcher page */}
|
||||
{isResearcherPage && <ChatPanelContainer />}
|
||||
</main>
|
||||
</SidebarInset>
|
||||
</SidebarProvider>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -59,12 +59,6 @@ export default function DashboardLayout({
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Podcasts",
|
||||
url: `/dashboard/${search_space_id}/podcasts`,
|
||||
icon: "Podcast",
|
||||
items: [],
|
||||
},
|
||||
{
|
||||
title: "Logs",
|
||||
url: `/dashboard/${search_space_id}/logs`,
|
||||
|
|
|
|||
|
|
@ -47,13 +47,14 @@ import {
|
|||
} from "@/components/ui/select";
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
|
||||
interface PodcastItem {
|
||||
export interface PodcastItem {
|
||||
id: number;
|
||||
title: string;
|
||||
created_at: string;
|
||||
file_location: string;
|
||||
podcast_transcript: any[];
|
||||
search_space_id: number;
|
||||
chat_state_version: number | null;
|
||||
}
|
||||
|
||||
interface PodcastsPageClientProps {
|
||||
|
|
|
|||
|
|
@ -42,9 +42,9 @@ export default function DashboardLayout({ children }: DashboardLayoutProps) {
|
|||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="h-full flex flex-col ">
|
||||
<AnnouncementBanner />
|
||||
{children}
|
||||
</>
|
||||
<div className="flex-1 min-h-0">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { I18nProvider } from "@/components/providers/I18nProvider";
|
|||
import { ThemeProvider } from "@/components/theme/theme-provider";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
import { LocaleProvider } from "@/contexts/LocaleContext";
|
||||
import { ReactQueryClientProvider } from "@/lib/query-client/query-client.provider";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const roboto = Roboto({
|
||||
|
|
@ -89,7 +90,7 @@ export default function RootLayout({
|
|||
// Locale state is managed by LocaleContext and persisted in localStorage
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body className={cn(roboto.className, "bg-white dark:bg-black antialiased h-full w-full")}>
|
||||
<body className={cn(roboto.className, "bg-white dark:bg-black antialiased h-full w-full ")}>
|
||||
<LocaleProvider>
|
||||
<I18nProvider>
|
||||
<ThemeProvider
|
||||
|
|
@ -99,7 +100,9 @@ export default function RootLayout({
|
|||
defaultTheme="light"
|
||||
>
|
||||
<RootProvider>
|
||||
{children}
|
||||
<ReactQueryClientProvider>
|
||||
<div className=" h-[100dvh] w-[100vw] overflow-hidden">{children}</div>
|
||||
</ReactQueryClientProvider>
|
||||
<Toaster />
|
||||
</RootProvider>
|
||||
</ThemeProvider>
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ export function AnnouncementBanner() {
|
|||
if (!isVisible) return null;
|
||||
|
||||
return (
|
||||
<div className="relative bg-gradient-to-r from-blue-600 to-blue-500 dark:from-blue-700 dark:to-blue-600 border-b border-blue-700 dark:border-blue-800">
|
||||
<div className="relative h-[3rem] flex items-center justify-center border bg-gradient-to-r from-blue-600 to-blue-500 dark:from-blue-700 dark:to-blue-600 border-b border-blue-700 dark:border-blue-800">
|
||||
<div className="container mx-auto px-4">
|
||||
<div className="flex items-center justify-center gap-3 py-2.5">
|
||||
<Info className="h-4 w-4 text-blue-50 flex-shrink-0" />
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
"use client";
|
||||
|
||||
import { type ChatHandler, ChatSection as LlamaIndexChatSection } from "@llamaindex/chat-ui";
|
||||
import { useSetAtom } from "jotai";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
import { ChatInputUI } from "@/components/chat/ChatInputGroup";
|
||||
import { ChatMessagesUI } from "@/components/chat/ChatMessages";
|
||||
import type { Document } from "@/hooks/use-documents";
|
||||
import { activeChatIdAtom } from "@/stores/chat/active-chat.atom";
|
||||
import { ChatPanelContainer } from "./ChatPanel/ChatPanelContainer";
|
||||
|
||||
interface ChatInterfaceProps {
|
||||
handler: ChatHandler;
|
||||
|
|
@ -28,9 +33,18 @@ export default function ChatInterface({
|
|||
topK = 10,
|
||||
onTopKChange,
|
||||
}: ChatInterfaceProps) {
|
||||
const { chat_id, search_space_id } = useParams();
|
||||
const setActiveChatIdState = useSetAtom(activeChatIdAtom);
|
||||
|
||||
useEffect(() => {
|
||||
const id = typeof chat_id === "string" ? chat_id : chat_id ? chat_id[0] : "";
|
||||
if (!id) return;
|
||||
setActiveChatIdState(id);
|
||||
}, [chat_id, search_space_id]);
|
||||
|
||||
return (
|
||||
<LlamaIndexChatSection handler={handler} className="flex h-full">
|
||||
<div className="flex flex-1 flex-col">
|
||||
<div className="flex grow-1 flex-col">
|
||||
<ChatMessagesUI />
|
||||
<div className="border-t p-4">
|
||||
<ChatInputUI
|
||||
|
|
|
|||
|
|
@ -0,0 +1,68 @@
|
|||
"use client";
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { LoaderIcon, PanelRight, TriangleAlert } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { generatePodcast } from "@/lib/apis/podcast-apis";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { activeChatAtom, activeChatIdAtom } from "@/stores/chat/active-chat.atom";
|
||||
import { chatUIAtom } from "@/stores/chat/chat-ui.atom";
|
||||
import { ChatPanelView } from "./ChatPanelView";
|
||||
|
||||
export interface GeneratePodcastRequest {
|
||||
type: "CHAT" | "DOCUMENT";
|
||||
ids: number[];
|
||||
search_space_id: number;
|
||||
podcast_title?: string;
|
||||
user_prompt?: string;
|
||||
}
|
||||
|
||||
export function ChatPanelContainer() {
|
||||
const {
|
||||
data: activeChatState,
|
||||
isLoading: isChatLoading,
|
||||
error: chatError,
|
||||
} = useAtomValue(activeChatAtom);
|
||||
const activeChatIdState = useAtomValue(activeChatIdAtom);
|
||||
const authToken = localStorage.getItem("surfsense_bearer_token");
|
||||
const { isChatPannelOpen } = useAtomValue(chatUIAtom);
|
||||
|
||||
const handleGeneratePodcast = async (request: GeneratePodcastRequest) => {
|
||||
try {
|
||||
if (!authToken) {
|
||||
throw new Error("Authentication error. Please log in again.");
|
||||
}
|
||||
await generatePodcast(request, authToken);
|
||||
toast.success(`Podcast generation started!`);
|
||||
} catch (error) {
|
||||
toast.error("Error generating podcast. Please log in again.");
|
||||
console.error("Error generating podcast:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return activeChatIdState ? (
|
||||
<div
|
||||
className={cn(
|
||||
"shrink-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 flex flex-col h-full transition-all",
|
||||
isChatPannelOpen ? "w-96" : "w-0"
|
||||
)}
|
||||
>
|
||||
{isChatLoading || chatError ? (
|
||||
<div className="border-b p-2">
|
||||
{isChatLoading ? (
|
||||
<div title="Loading chat" className="flex items-center justify-center h-full">
|
||||
<LoaderIcon strokeWidth={1.5} className="h-5 w-5 animate-spin" />
|
||||
</div>
|
||||
) : chatError ? (
|
||||
<div title="Failed to load chat" className="flex items-center justify-center h-full">
|
||||
<TriangleAlert strokeWidth={1.5} className="h-5 w-5 text-red-600" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!isChatLoading && !chatError && activeChatState?.chatDetails && (
|
||||
<ChatPanelView generatePodcast={handleGeneratePodcast} />
|
||||
)}
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
208
surfsense_web/components/chat/ChatPanel/ChatPanelView.tsx
Normal file
208
surfsense_web/components/chat/ChatPanel/ChatPanelView.tsx
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
"use client";
|
||||
|
||||
import { useAtom, useAtomValue } from "jotai";
|
||||
import { AlertCircle, Pencil, Play, Podcast, RefreshCw, Sparkles } from "lucide-react";
|
||||
import { motion } from "motion/react";
|
||||
import { useCallback, useContext, useTransition } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { activeChatAtom } from "@/stores/chat/active-chat.atom";
|
||||
import { chatUIAtom } from "@/stores/chat/chat-ui.atom";
|
||||
import { getPodcastStalenessMessage, isPodcastStale } from "../PodcastUtils";
|
||||
import type { GeneratePodcastRequest } from "./ChatPanelContainer";
|
||||
import { ConfigModal } from "./ConfigModal";
|
||||
import { PodcastPlayer } from "./PodcastPlayer";
|
||||
|
||||
interface ChatPanelViewProps {
|
||||
generatePodcast: (request: GeneratePodcastRequest) => Promise<void>;
|
||||
}
|
||||
|
||||
export function ChatPanelView(props: ChatPanelViewProps) {
|
||||
const [chatUIState, setChatUIState] = useAtom(chatUIAtom);
|
||||
const { data: activeChatState } = useAtomValue(activeChatAtom);
|
||||
|
||||
const { isChatPannelOpen } = chatUIState;
|
||||
const podcast = activeChatState?.podcast;
|
||||
const chatDetails = activeChatState?.chatDetails;
|
||||
|
||||
const { generatePodcast } = props;
|
||||
|
||||
// Check if podcast is stale
|
||||
const podcastIsStale =
|
||||
podcast && chatDetails && isPodcastStale(chatDetails.state_version, podcast.chat_state_version);
|
||||
|
||||
const handleGeneratePost = useCallback(async () => {
|
||||
if (!chatDetails) return;
|
||||
await generatePodcast({
|
||||
type: "CHAT",
|
||||
ids: [chatDetails.id],
|
||||
search_space_id: chatDetails.search_space_id,
|
||||
podcast_title: chatDetails.title,
|
||||
});
|
||||
}, [chatDetails, generatePodcast]);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className={cn("w-full p-4", !isChatPannelOpen && "flex items-center justify-center")}>
|
||||
{isChatPannelOpen ? (
|
||||
<div className="space-y-3">
|
||||
{/* Show stale podcast warning if applicable */}
|
||||
{podcastIsStale && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="rounded-xl p-3 bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-950/30 dark:to-orange-950/20 border border-amber-200/50 dark:border-amber-800/50 shadow-sm"
|
||||
>
|
||||
<div className="flex gap-2 items-start">
|
||||
<motion.div
|
||||
animate={{ rotate: [0, 10, -10, 0] }}
|
||||
transition={{ duration: 0.5, repeat: Infinity, repeatDelay: 3 }}
|
||||
>
|
||||
<AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />
|
||||
</motion.div>
|
||||
<div className="text-sm text-amber-900 dark:text-amber-100">
|
||||
<p className="font-semibold">Podcast Outdated</p>
|
||||
<p className="text-xs mt-1 opacity-80">
|
||||
{getPodcastStalenessMessage(
|
||||
chatDetails?.state_version || 0,
|
||||
podcast?.chat_state_version
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<motion.div
|
||||
whileHover={{ scale: 1.02 }}
|
||||
whileTap={{ scale: 0.98 }}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={handleGeneratePost}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
handleGeneratePost();
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
"relative w-full rounded-2xl p-4 transition-all duration-300 cursor-pointer group overflow-hidden",
|
||||
"border-2",
|
||||
podcastIsStale
|
||||
? "bg-gradient-to-br from-amber-500/10 via-orange-500/10 to-amber-500/10 dark:from-amber-500/20 dark:via-orange-500/20 dark:to-amber-500/20 border-amber-400/50 hover:border-amber-400 hover:shadow-lg hover:shadow-amber-500/20"
|
||||
: "bg-gradient-to-br from-primary/10 via-primary/5 to-primary/10 border-primary/30 hover:border-primary/60 hover:shadow-lg hover:shadow-primary/20"
|
||||
)}
|
||||
>
|
||||
{/* Background gradient animation */}
|
||||
<motion.div
|
||||
className={cn(
|
||||
"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500",
|
||||
podcastIsStale
|
||||
? "bg-gradient-to-r from-transparent via-amber-400/10 to-transparent"
|
||||
: "bg-gradient-to-r from-transparent via-primary/10 to-transparent"
|
||||
)}
|
||||
animate={{
|
||||
x: ["-100%", "100%"],
|
||||
}}
|
||||
transition={{
|
||||
duration: 3,
|
||||
repeat: Infinity,
|
||||
ease: "linear",
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="relative z-10 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<motion.div
|
||||
className={cn(
|
||||
"p-2.5 rounded-xl",
|
||||
podcastIsStale
|
||||
? "bg-amber-500/20 dark:bg-amber-500/30"
|
||||
: "bg-primary/20 dark:bg-primary/30"
|
||||
)}
|
||||
animate={{
|
||||
rotate: podcastIsStale ? [0, 360] : 0,
|
||||
}}
|
||||
transition={{
|
||||
duration: 2,
|
||||
repeat: podcastIsStale ? Infinity : 0,
|
||||
ease: "linear",
|
||||
}}
|
||||
>
|
||||
{podcastIsStale ? (
|
||||
<RefreshCw className="h-5 w-5 text-amber-600 dark:text-amber-400" />
|
||||
) : (
|
||||
<Sparkles className="h-5 w-5 text-primary" />
|
||||
)}
|
||||
</motion.div>
|
||||
<div>
|
||||
<p className="text-sm font-semibold">
|
||||
{podcastIsStale ? "Regenerate Podcast" : "Generate Podcast"}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{podcastIsStale
|
||||
? "Update with latest changes"
|
||||
: "Create podcasts of your chat"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<ConfigModal generatePodcast={generatePodcast} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
) : (
|
||||
<motion.button
|
||||
title={podcastIsStale ? "Regenerate Podcast" : "Generate Podcast"}
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setChatUIState((prev) => ({
|
||||
...prev,
|
||||
isChatPannelOpen: !isChatPannelOpen,
|
||||
}))
|
||||
}
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
className={cn(
|
||||
"p-2.5 rounded-full transition-colors shadow-sm",
|
||||
podcastIsStale
|
||||
? "bg-amber-500/20 hover:bg-amber-500/30 text-amber-600 dark:text-amber-400"
|
||||
: "bg-primary/20 hover:bg-primary/30 text-primary"
|
||||
)}
|
||||
>
|
||||
{podcastIsStale ? <RefreshCw className="h-5 w-5" /> : <Sparkles className="h-5 w-5" />}
|
||||
</motion.button>
|
||||
)}
|
||||
</div>
|
||||
{podcast ? (
|
||||
<div
|
||||
className={cn(
|
||||
"w-full border-t",
|
||||
!isChatPannelOpen && "flex items-center justify-center p-4"
|
||||
)}
|
||||
>
|
||||
{isChatPannelOpen ? (
|
||||
<PodcastPlayer compact podcast={podcast} />
|
||||
) : podcast ? (
|
||||
<motion.button
|
||||
title="Play Podcast"
|
||||
type="button"
|
||||
onClick={() => setChatUIState((prev) => ({ ...prev, isChatPannelOpen: true }))}
|
||||
whileHover={{ scale: 1.1 }}
|
||||
whileTap={{ scale: 0.9 }}
|
||||
className="p-2.5 rounded-full bg-green-500/20 hover:bg-green-500/30 text-green-600 dark:text-green-400 transition-colors shadow-sm"
|
||||
>
|
||||
<Play className="h-5 w-5" />
|
||||
</motion.button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
84
surfsense_web/components/chat/ChatPanel/ConfigModal.tsx
Normal file
84
surfsense_web/components/chat/ChatPanel/ConfigModal.tsx
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { Pencil } from "lucide-react";
|
||||
import { useCallback, useContext, useState } from "react";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { activeChatAtom } from "@/stores/chat/active-chat.atom";
|
||||
import type { GeneratePodcastRequest } from "./ChatPanelContainer";
|
||||
|
||||
interface ConfigModalProps {
|
||||
generatePodcast: (request: GeneratePodcastRequest) => Promise<void>;
|
||||
}
|
||||
|
||||
export function ConfigModal(props: ConfigModalProps) {
|
||||
const { data: activeChatState } = useAtomValue(activeChatAtom);
|
||||
|
||||
const chatDetails = activeChatState?.chatDetails;
|
||||
const podcast = activeChatState?.podcast;
|
||||
|
||||
const { generatePodcast } = props;
|
||||
|
||||
const [userPromt, setUserPrompt] = useState("");
|
||||
|
||||
const handleGeneratePost = useCallback(async () => {
|
||||
if (!chatDetails) return;
|
||||
await generatePodcast({
|
||||
type: "CHAT",
|
||||
ids: [chatDetails.id],
|
||||
search_space_id: chatDetails.search_space_id,
|
||||
podcast_title: podcast?.title || chatDetails.title,
|
||||
user_prompt: userPromt,
|
||||
});
|
||||
}, [chatDetails, userPromt]);
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
title="Edit the prompt"
|
||||
className="rounded-full p-2 bg-slate-400/30 hover:bg-slate-400/40"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Pencil strokeWidth={1} className="h-4 w-4" />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent onClick={(e) => e.stopPropagation()} align="end" className="bg-sidebar w-96 ">
|
||||
<form className="flex flex-col gap-3 w-full">
|
||||
<label className="text-sm font-medium" htmlFor="prompt">
|
||||
Special user instructions
|
||||
</label>
|
||||
<p className="text-xs text-slate-500 dark:text-slate-400">
|
||||
Leave empty to use the default prompt
|
||||
</p>
|
||||
<div className="text-xs text-slate-500 dark:text-slate-400 space-y-1">
|
||||
<p>Examples:</p>
|
||||
<ul className="list-disc list-inside space-y-0.5">
|
||||
<li>Make hosts speak in London street language</li>
|
||||
<li>Use real-world analogies and metaphors</li>
|
||||
<li>Add dramatic pauses like a late-night radio show</li>
|
||||
<li>Include 90s pop culture references</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<textarea
|
||||
name="prompt"
|
||||
id="prompt"
|
||||
defaultValue={userPromt}
|
||||
className="w-full rounded-md border border-slate-400/40 p-2"
|
||||
onChange={(e) => {
|
||||
e.stopPropagation();
|
||||
setUserPrompt(e.target.value);
|
||||
}}
|
||||
></textarea>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleGeneratePost}
|
||||
className="w-full rounded-md bg-foreground text-white dark:text-black p-2"
|
||||
>
|
||||
Generate Podcast
|
||||
</button>
|
||||
</form>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,343 @@
|
|||
"use client";
|
||||
|
||||
import { Pause, Play, Podcast, SkipBack, SkipForward, Volume2, VolumeX, X } from "lucide-react";
|
||||
import { motion } from "motion/react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import type { PodcastItem } from "@/app/dashboard/[search_space_id]/podcasts/podcasts-client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
import { PodcastPlayerCompactSkeleton } from "./PodcastPlayerCompactSkeleton";
|
||||
|
||||
interface PodcastPlayerProps {
|
||||
podcast: PodcastItem | null;
|
||||
isLoading?: boolean;
|
||||
onClose?: () => void;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function PodcastPlayer({
|
||||
podcast,
|
||||
isLoading = false,
|
||||
onClose,
|
||||
compact = false,
|
||||
}: PodcastPlayerProps) {
|
||||
const [audioSrc, setAudioSrc] = useState<string | undefined>(undefined);
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
const [duration, setDuration] = useState(0);
|
||||
const [volume, setVolume] = useState(0.7);
|
||||
const [isMuted, setIsMuted] = useState(false);
|
||||
const [isFetching, setIsFetching] = useState(false);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const currentObjectUrlRef = useRef<string | null>(null);
|
||||
|
||||
// Cleanup object URL on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (currentObjectUrlRef.current) {
|
||||
URL.revokeObjectURL(currentObjectUrlRef.current);
|
||||
currentObjectUrlRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Load podcast audio when podcast changes
|
||||
useEffect(() => {
|
||||
if (!podcast) {
|
||||
setAudioSrc(undefined);
|
||||
setCurrentTime(0);
|
||||
setDuration(0);
|
||||
setIsPlaying(false);
|
||||
setIsFetching(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const loadPodcast = async () => {
|
||||
setIsFetching(true);
|
||||
try {
|
||||
const token = localStorage.getItem("surfsense_bearer_token");
|
||||
if (!token) {
|
||||
throw new Error("Authentication token not found.");
|
||||
}
|
||||
|
||||
// Revoke previous object URL if exists
|
||||
if (currentObjectUrlRef.current) {
|
||||
URL.revokeObjectURL(currentObjectUrlRef.current);
|
||||
currentObjectUrlRef.current = null;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 30000);
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/podcasts/${podcast.id}/stream`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
signal: controller.signal,
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch audio stream: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
currentObjectUrlRef.current = objectUrl;
|
||||
setAudioSrc(objectUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "AbortError") {
|
||||
throw new Error("Request timed out. Please try again.");
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching podcast:", error);
|
||||
toast.error(error instanceof Error ? error.message : "Failed to load podcast audio.");
|
||||
setAudioSrc(undefined);
|
||||
} finally {
|
||||
setIsFetching(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadPodcast();
|
||||
}, [podcast]);
|
||||
|
||||
const handleTimeUpdate = () => {
|
||||
if (audioRef.current) {
|
||||
setCurrentTime(audioRef.current.currentTime);
|
||||
}
|
||||
};
|
||||
|
||||
const handleMetadataLoaded = () => {
|
||||
if (audioRef.current) {
|
||||
setDuration(audioRef.current.duration);
|
||||
}
|
||||
};
|
||||
|
||||
const togglePlayPause = () => {
|
||||
if (audioRef.current) {
|
||||
if (isPlaying) {
|
||||
audioRef.current.pause();
|
||||
} else {
|
||||
audioRef.current.play();
|
||||
}
|
||||
setIsPlaying(!isPlaying);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSeek = (value: number[]) => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = value[0];
|
||||
setCurrentTime(value[0]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVolumeChange = (value: number[]) => {
|
||||
if (audioRef.current) {
|
||||
const newVolume = value[0];
|
||||
audioRef.current.volume = newVolume;
|
||||
setVolume(newVolume);
|
||||
|
||||
if (newVolume === 0) {
|
||||
audioRef.current.muted = true;
|
||||
setIsMuted(true);
|
||||
} else {
|
||||
audioRef.current.muted = false;
|
||||
setIsMuted(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const toggleMute = () => {
|
||||
if (audioRef.current) {
|
||||
const newMutedState = !isMuted;
|
||||
audioRef.current.muted = newMutedState;
|
||||
setIsMuted(newMutedState);
|
||||
|
||||
if (!newMutedState && volume === 0) {
|
||||
const restoredVolume = 0.5;
|
||||
audioRef.current.volume = restoredVolume;
|
||||
setVolume(restoredVolume);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const skipForward = () => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = Math.min(
|
||||
audioRef.current.duration,
|
||||
audioRef.current.currentTime + 10
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const skipBackward = () => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.currentTime = Math.max(0, audioRef.current.currentTime - 10);
|
||||
}
|
||||
};
|
||||
|
||||
const formatTime = (time: number) => {
|
||||
const minutes = Math.floor(time / 60);
|
||||
const seconds = Math.floor(time % 60);
|
||||
return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
|
||||
};
|
||||
|
||||
// Show skeleton while fetching
|
||||
if (isFetching && compact) {
|
||||
return <PodcastPlayerCompactSkeleton />;
|
||||
}
|
||||
|
||||
if (!podcast || !audioSrc) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col gap-4 p-4">
|
||||
{/* Audio Visualizer */}
|
||||
<motion.div
|
||||
className="relative h-1 bg-gradient-to-r from-primary/20 via-primary/40 to-primary/20 rounded-full overflow-hidden"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.5 }}
|
||||
>
|
||||
{isPlaying && (
|
||||
<motion.div
|
||||
className="absolute inset-0 bg-gradient-to-r from-transparent via-primary to-transparent"
|
||||
animate={{
|
||||
x: ["-100%", "100%"],
|
||||
}}
|
||||
transition={{
|
||||
duration: 2,
|
||||
repeat: Infinity,
|
||||
ease: "linear",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
{/* Progress Bar with Time */}
|
||||
<div className="space-y-2">
|
||||
<Slider
|
||||
value={[currentTime]}
|
||||
min={0}
|
||||
max={duration || 100}
|
||||
step={0.1}
|
||||
onValueChange={handleSeek}
|
||||
className="w-full cursor-pointer"
|
||||
/>
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span className="font-mono">{formatTime(currentTime)}</span>
|
||||
<span className="font-mono">{formatTime(duration)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="flex items-center justify-between">
|
||||
{/* Left: Volume */}
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||
<Button variant="ghost" size="icon" onClick={toggleMute} className="h-8 w-8">
|
||||
{isMuted ? (
|
||||
<VolumeX className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<Volume2 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* Center: Playback Controls */}
|
||||
<div className="flex items-center gap-1">
|
||||
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={skipBackward}
|
||||
className="h-9 w-9"
|
||||
disabled={!duration}
|
||||
>
|
||||
<SkipBack className="h-4 w-4" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
|
||||
<motion.div
|
||||
whileHover={{ scale: 1.05 }}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
animate={
|
||||
isPlaying
|
||||
? {
|
||||
boxShadow: [
|
||||
"0 0 0 0 rgba(var(--primary), 0)",
|
||||
"0 0 0 8px rgba(var(--primary), 0.1)",
|
||||
"0 0 0 0 rgba(var(--primary), 0)",
|
||||
],
|
||||
}
|
||||
: {}
|
||||
}
|
||||
transition={{ duration: 1.5, repeat: isPlaying ? Infinity : 0 }}
|
||||
>
|
||||
<Button
|
||||
variant="default"
|
||||
size="icon"
|
||||
onClick={togglePlayPause}
|
||||
className="h-10 w-10 rounded-full"
|
||||
disabled={!duration}
|
||||
>
|
||||
{isPlaying ? <Pause className="h-5 w-5" /> : <Play className="h-5 w-5 ml-0.5" />}
|
||||
</Button>
|
||||
</motion.div>
|
||||
|
||||
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={skipForward}
|
||||
className="h-9 w-9"
|
||||
disabled={!duration}
|
||||
>
|
||||
<SkipForward className="h-4 w-4" />
|
||||
</Button>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* Right: Placeholder for symmetry */}
|
||||
<div className="flex-1" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<audio
|
||||
ref={audioRef}
|
||||
src={audioSrc}
|
||||
preload="auto"
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
onLoadedMetadata={handleMetadataLoaded}
|
||||
onEnded={() => setIsPlaying(false)}
|
||||
onError={(e) => {
|
||||
console.error("Audio error:", e);
|
||||
if (audioRef.current?.error) {
|
||||
console.error("Audio error code:", audioRef.current.error.code);
|
||||
if (audioRef.current.error.code !== audioRef.current.error.MEDIA_ERR_ABORTED) {
|
||||
toast.error("Error playing audio. Please try again.");
|
||||
}
|
||||
}
|
||||
setIsPlaying(false);
|
||||
}}
|
||||
>
|
||||
<track kind="captions" />
|
||||
</audio>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
"use client";
|
||||
|
||||
import { Podcast } from "lucide-react";
|
||||
import { motion } from "motion/react";
|
||||
|
||||
export function PodcastPlayerCompactSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col gap-3 p-3">
|
||||
{/* Header with icon and title */}
|
||||
<div className="flex items-center gap-2">
|
||||
<motion.div
|
||||
className="w-8 h-8 bg-primary/20 rounded-md flex items-center justify-center flex-shrink-0"
|
||||
animate={{ scale: [1, 1.05, 1] }}
|
||||
transition={{
|
||||
repeat: Infinity,
|
||||
duration: 2,
|
||||
}}
|
||||
>
|
||||
<Podcast className="h-4 w-4 text-primary" />
|
||||
</motion.div>
|
||||
{/* Title skeleton */}
|
||||
<div className="h-4 bg-muted rounded w-32 flex-grow animate-pulse" />
|
||||
</div>
|
||||
|
||||
{/* Progress bar skeleton */}
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="h-1 bg-muted rounded flex-grow animate-pulse" />
|
||||
<div className="h-4 bg-muted rounded w-12 animate-pulse" />
|
||||
</div>
|
||||
|
||||
{/* Controls skeleton */}
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<div className="h-7 w-7 bg-muted rounded-full animate-pulse" />
|
||||
<div className="h-8 w-8 bg-primary/20 rounded-full animate-pulse" />
|
||||
<div className="h-7 w-7 bg-muted rounded-full animate-pulse" />
|
||||
<div className="h-7 w-7 bg-muted rounded-full animate-pulse" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { PodcastPlayer } from "./PodcastPlayer";
|
||||
export { PodcastPlayerCompactSkeleton } from "./PodcastPlayerCompactSkeleton";
|
||||
43
surfsense_web/components/chat/PodcastUtils.ts
Normal file
43
surfsense_web/components/chat/PodcastUtils.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/**
|
||||
* Determines if a podcast is stale compared to the current chat state.
|
||||
* A podcast is considered stale if:
|
||||
* - The chat's current state_version is greater than the podcast's chat_state_version
|
||||
*
|
||||
* @param chatVersion - The current state_version of the chat
|
||||
* @param podcastVersion - The chat_state_version stored when the podcast was generated (nullable)
|
||||
* @returns true if the podcast is stale, false otherwise
|
||||
*/
|
||||
export function isPodcastStale(
|
||||
chatVersion: number,
|
||||
podcastVersion: number | null | undefined
|
||||
): boolean {
|
||||
// If podcast has no version, it's stale (generated before this feature)
|
||||
if (!podcastVersion) {
|
||||
return true;
|
||||
}
|
||||
// If chat version is greater than podcast version, it's stale : We can change this condition to consider staleness after a huge number of updates
|
||||
return chatVersion > podcastVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a human-readable message about podcast staleness
|
||||
*
|
||||
* @param chatVersion - The current state_version of the chat
|
||||
* @param podcastVersion - The chat_state_version stored when the podcast was generated
|
||||
* @returns A descriptive message about the podcast's staleness status
|
||||
*/
|
||||
export function getPodcastStalenessMessage(
|
||||
chatVersion: number,
|
||||
podcastVersion: number | null | undefined
|
||||
): string {
|
||||
if (!podcastVersion) {
|
||||
return "This podcast was generated before chat updates were tracked. Consider regenerating it.";
|
||||
}
|
||||
|
||||
if (chatVersion > podcastVersion) {
|
||||
const versionDiff = chatVersion - podcastVersion;
|
||||
return `This podcast is outdated. The chat has been updated ${versionDiff} time${versionDiff > 1 ? "s" : ""} since this podcast was generated.`;
|
||||
}
|
||||
|
||||
return "This podcast is up to date with the current chat.";
|
||||
}
|
||||
|
|
@ -2,7 +2,8 @@
|
|||
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import React from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import type { ChatDetails } from "@/app/dashboard/[search_space_id]/chats/chats-client";
|
||||
import {
|
||||
Breadcrumb,
|
||||
BreadcrumbItem,
|
||||
|
|
@ -11,6 +12,8 @@ import {
|
|||
BreadcrumbPage,
|
||||
BreadcrumbSeparator,
|
||||
} from "@/components/ui/breadcrumb";
|
||||
import { useSearchSpace } from "@/hooks/use-search-space";
|
||||
import { fetchChatDetails } from "@/lib/apis/chat-apis";
|
||||
|
||||
interface BreadcrumbItemInterface {
|
||||
label: string;
|
||||
|
|
@ -20,6 +23,31 @@ interface BreadcrumbItemInterface {
|
|||
export function DashboardBreadcrumb() {
|
||||
const t = useTranslations("breadcrumb");
|
||||
const pathname = usePathname();
|
||||
const [chatDetails, setChatDetails] = useState<ChatDetails | null>(null);
|
||||
|
||||
// Extract search space ID and chat ID from pathname
|
||||
const segments = pathname.split("/").filter(Boolean);
|
||||
const searchSpaceId = segments[0] === "dashboard" && segments[1] ? segments[1] : null;
|
||||
const chatId =
|
||||
segments[0] === "dashboard" && segments[2] === "researcher" && segments[3] ? segments[3] : null;
|
||||
|
||||
// Fetch search space details if we have an ID
|
||||
const { searchSpace } = useSearchSpace({
|
||||
searchSpaceId: searchSpaceId || "",
|
||||
autoFetch: !!searchSpaceId,
|
||||
});
|
||||
|
||||
// Fetch chat details if we have a chat ID
|
||||
useEffect(() => {
|
||||
if (chatId) {
|
||||
const token = localStorage.getItem("surfsense_bearer_token");
|
||||
if (token) {
|
||||
fetchChatDetails(chatId, token).then(setChatDetails);
|
||||
}
|
||||
} else {
|
||||
setChatDetails(null);
|
||||
}
|
||||
}, [chatId]);
|
||||
|
||||
// Parse the pathname to create breadcrumb items
|
||||
const generateBreadcrumbs = (path: string): BreadcrumbItemInterface[] => {
|
||||
|
|
@ -31,8 +59,10 @@ export function DashboardBreadcrumb() {
|
|||
|
||||
// Handle search space
|
||||
if (segments[0] === "dashboard" && segments[1]) {
|
||||
// Use the actual search space name if available, otherwise fall back to the ID
|
||||
const searchSpaceLabel = searchSpace?.name || `${t("search_space")} ${segments[1]}`;
|
||||
breadcrumbs.push({
|
||||
label: `${t("search_space")} ${segments[1]}`,
|
||||
label: searchSpaceLabel,
|
||||
href: `/dashboard/${segments[1]}`,
|
||||
});
|
||||
|
||||
|
|
@ -92,6 +122,18 @@ export function DashboardBreadcrumb() {
|
|||
return breadcrumbs;
|
||||
}
|
||||
|
||||
// Handle researcher sub-sections (chat IDs)
|
||||
if (section === "researcher") {
|
||||
// Use the actual chat title if available, otherwise fall back to the ID
|
||||
const chatLabel = chatDetails?.title || subSection;
|
||||
breadcrumbs.push({
|
||||
label: t("researcher"),
|
||||
href: `/dashboard/${segments[1]}/researcher`,
|
||||
});
|
||||
breadcrumbs.push({ label: chatLabel });
|
||||
return breadcrumbs;
|
||||
}
|
||||
|
||||
// Handle connector sub-sections
|
||||
if (section === "connectors") {
|
||||
// Handle specific connector types
|
||||
|
|
|
|||
|
|
@ -294,7 +294,7 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
|||
data-slot="sidebar-inset"
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
"md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-l-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import type { Message } from "@ai-sdk/react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { ChatDetails } from "@/app/dashboard/[search_space_id]/chats/chats-client";
|
||||
import type { ResearchMode } from "@/components/chat";
|
||||
import type { Document } from "@/hooks/use-documents";
|
||||
|
||||
|
|
@ -52,7 +53,7 @@ interface UseChatAPIProps {
|
|||
|
||||
export function useChatAPI({ token, search_space_id }: UseChatAPIProps) {
|
||||
const fetchChatDetails = useCallback(
|
||||
async (chatId: string) => {
|
||||
async (chatId: string): Promise<ChatDetails | null> => {
|
||||
if (!token) return null;
|
||||
|
||||
try {
|
||||
|
|
|
|||
28
surfsense_web/lib/apis/chat-apis.ts
Normal file
28
surfsense_web/lib/apis/chat-apis.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import type { ChatDetails } from "@/app/dashboard/[search_space_id]/chats/chats-client";
|
||||
|
||||
export const fetchChatDetails = async (
|
||||
chatId: string,
|
||||
authToken: string
|
||||
): Promise<ChatDetails | null> => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/chats/${Number(chatId)}`,
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch chat details: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (err) {
|
||||
console.error("Error fetching chat details:", err);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
50
surfsense_web/lib/apis/podcast-apis.ts
Normal file
50
surfsense_web/lib/apis/podcast-apis.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import type { PodcastItem } from "@/app/dashboard/[search_space_id]/podcasts/podcasts-client";
|
||||
import type { GeneratePodcastRequest } from "@/components/chat/ChatPanel/ChatPanelContainer";
|
||||
|
||||
export const getPodcastByChatId = async (chatId: string, authToken: string) => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/podcasts/by-chat/${Number(chatId)}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
},
|
||||
method: "GET",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.detail || "Failed to fetch podcast");
|
||||
}
|
||||
|
||||
return (await response.json()) as PodcastItem | null;
|
||||
} catch (err: any) {
|
||||
console.error("Error fetching podcast:", err);
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const generatePodcast = async (request: GeneratePodcastRequest, authToken: string) => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL}/api/v1/podcasts/generate/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(request),
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.detail || "Failed to generate podcast");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error generating podcast:", error);
|
||||
}
|
||||
};
|
||||
3
surfsense_web/lib/query-client/cache-keys.ts
Normal file
3
surfsense_web/lib/query-client/cache-keys.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export const cacheKeys = {
|
||||
activeChat: (chatId: string) => ["activeChat", chatId],
|
||||
};
|
||||
3
surfsense_web/lib/query-client/client.ts
Normal file
3
surfsense_web/lib/query-client/client.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { QueryClient } from "@tanstack/react-query";
|
||||
|
||||
export const queryClient = new QueryClient();
|
||||
13
surfsense_web/lib/query-client/query-client.provider.tsx
Normal file
13
surfsense_web/lib/query-client/query-client.provider.tsx
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
"use client";
|
||||
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
|
||||
import { QueryClientAtomProvider } from "jotai-tanstack-query/react";
|
||||
import { queryClient } from "./client";
|
||||
|
||||
export function ReactQueryClientProvider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientAtomProvider client={queryClient}>
|
||||
{children}
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</QueryClientAtomProvider>
|
||||
);
|
||||
}
|
||||
|
|
@ -17,7 +17,8 @@
|
|||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:push": "drizzle-kit push",
|
||||
"db:studio": "drizzle-kit studio"
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"format:fix": "npx @biomejs/biome check --fix"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/react": "^1.2.12",
|
||||
|
|
@ -45,6 +46,9 @@
|
|||
"@radix-ui/react-toggle-group": "^1.1.10",
|
||||
"@radix-ui/react-tooltip": "^1.2.7",
|
||||
"@tabler/icons-react": "^3.34.1",
|
||||
"@tanstack/query-core": "^5.90.7",
|
||||
"@tanstack/react-query": "^5.90.7",
|
||||
"@tanstack/react-query-devtools": "^5.90.2",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@types/mdx": "^2.0.13",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
|
|
@ -60,6 +64,8 @@
|
|||
"fumadocs-mdx": "^11.7.1",
|
||||
"fumadocs-ui": "^15.6.6",
|
||||
"geist": "^1.4.2",
|
||||
"jotai": "^2.15.1",
|
||||
"jotai-tanstack-query": "^0.11.0",
|
||||
"lucide-react": "^0.477.0",
|
||||
"motion": "^12.23.22",
|
||||
"next": "^15.4.4",
|
||||
|
|
|
|||
98
surfsense_web/pnpm-lock.yaml
generated
98
surfsense_web/pnpm-lock.yaml
generated
|
|
@ -83,6 +83,15 @@ importers:
|
|||
'@tabler/icons-react':
|
||||
specifier: ^3.34.1
|
||||
version: 3.34.1(react@19.1.0)
|
||||
'@tanstack/query-core':
|
||||
specifier: ^5.90.7
|
||||
version: 5.90.7
|
||||
'@tanstack/react-query':
|
||||
specifier: ^5.90.7
|
||||
version: 5.90.7(react@19.1.0)
|
||||
'@tanstack/react-query-devtools':
|
||||
specifier: ^5.90.2
|
||||
version: 5.90.2(@tanstack/react-query@5.90.7(react@19.1.0))(react@19.1.0)
|
||||
'@tanstack/react-table':
|
||||
specifier: ^8.21.3
|
||||
version: 8.21.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
|
|
@ -128,6 +137,12 @@ importers:
|
|||
geist:
|
||||
specifier: ^1.4.2
|
||||
version: 1.4.2(next@15.4.4(@opentelemetry/api@1.9.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))
|
||||
jotai:
|
||||
specifier: ^2.15.1
|
||||
version: 2.15.1(@types/react@19.1.8)(react@19.1.0)
|
||||
jotai-tanstack-query:
|
||||
specifier: ^0.11.0
|
||||
version: 0.11.0(@tanstack/query-core@5.90.7)(@tanstack/react-query@5.90.7(react@19.1.0))(jotai@2.15.1(@types/react@19.1.8)(react@19.1.0))(react@19.1.0)
|
||||
lucide-react:
|
||||
specifier: ^0.477.0
|
||||
version: 0.477.0(react@19.1.0)
|
||||
|
|
@ -2340,6 +2355,23 @@ packages:
|
|||
peerDependencies:
|
||||
tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1'
|
||||
|
||||
'@tanstack/query-core@5.90.7':
|
||||
resolution: {integrity: sha512-6PN65csiuTNfBMXqQUxQhCNdtm1rV+9kC9YwWAIKcaxAauq3Wu7p18j3gQY3YIBJU70jT/wzCCZ2uqto/vQgiQ==}
|
||||
|
||||
'@tanstack/query-devtools@5.90.1':
|
||||
resolution: {integrity: sha512-GtINOPjPUH0OegJExZ70UahT9ykmAhmtNVcmtdnOZbxLwT7R5OmRztR5Ahe3/Cu7LArEmR6/588tAycuaWb1xQ==}
|
||||
|
||||
'@tanstack/react-query-devtools@5.90.2':
|
||||
resolution: {integrity: sha512-vAXJzZuBXtCQtrY3F/yUNJCV4obT/A/n81kb3+YqLbro5Z2+phdAbceO+deU3ywPw8B42oyJlp4FhO0SoivDFQ==}
|
||||
peerDependencies:
|
||||
'@tanstack/react-query': ^5.90.2
|
||||
react: ^18 || ^19
|
||||
|
||||
'@tanstack/react-query@5.90.7':
|
||||
resolution: {integrity: sha512-wAHc/cgKzW7LZNFloThyHnV/AX9gTg3w5yAv0gvQHPZoCnepwqCMtzbuPbb2UvfvO32XZ46e8bPOYbfZhzVnnQ==}
|
||||
peerDependencies:
|
||||
react: ^18 || ^19
|
||||
|
||||
'@tanstack/react-table@8.21.3':
|
||||
resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}
|
||||
engines: {node: '>=12'}
|
||||
|
|
@ -3818,6 +3850,37 @@ packages:
|
|||
resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==}
|
||||
hasBin: true
|
||||
|
||||
jotai-tanstack-query@0.11.0:
|
||||
resolution: {integrity: sha512-Ys0u0IuuS6/okUJOulFTdCVfVaeKbm1+lKVSN9zHhIxtrAXl9FM4yu7fNvxM6fSz/NCE9tZOKR0MQ3hvplaH8A==}
|
||||
peerDependencies:
|
||||
'@tanstack/query-core': '*'
|
||||
'@tanstack/react-query': '*'
|
||||
jotai: '>=2.0.0'
|
||||
react: ^18.0.0 || ^19.0.0
|
||||
peerDependenciesMeta:
|
||||
'@tanstack/react-query':
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
|
||||
jotai@2.15.1:
|
||||
resolution: {integrity: sha512-yHT1HAZ3ba2Q8wgaUQ+xfBzEtcS8ie687I8XVCBinfg4bNniyqLIN+utPXWKQE93LMF5fPbQSVRZqgpcN5yd6Q==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
peerDependencies:
|
||||
'@babel/core': '>=7.0.0'
|
||||
'@babel/template': '>=7.0.0'
|
||||
'@types/react': '>=17.0.0'
|
||||
react: '>=17.0.0'
|
||||
peerDependenciesMeta:
|
||||
'@babel/core':
|
||||
optional: true
|
||||
'@babel/template':
|
||||
optional: true
|
||||
'@types/react':
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
|
||||
js-tokens@4.0.0:
|
||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||
|
||||
|
|
@ -5228,6 +5291,9 @@ packages:
|
|||
tailwind-merge@3.3.1:
|
||||
resolution: {integrity: sha512-gBXpgUm/3rp1lMZZrM/w7D8GKqshif0zAymAhbCyIt8KMe+0v9DQ7cdYLR4FHH/cKpdTXb+A/tKKU3eolfsI+g==}
|
||||
|
||||
tailwind-merge@3.4.0:
|
||||
resolution: {integrity: sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==}
|
||||
|
||||
tailwindcss-animate@1.0.7:
|
||||
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
|
||||
peerDependencies:
|
||||
|
|
@ -7953,6 +8019,21 @@ snapshots:
|
|||
postcss-selector-parser: 6.0.10
|
||||
tailwindcss: 4.1.11
|
||||
|
||||
'@tanstack/query-core@5.90.7': {}
|
||||
|
||||
'@tanstack/query-devtools@5.90.1': {}
|
||||
|
||||
'@tanstack/react-query-devtools@5.90.2(@tanstack/react-query@5.90.7(react@19.1.0))(react@19.1.0)':
|
||||
dependencies:
|
||||
'@tanstack/query-devtools': 5.90.1
|
||||
'@tanstack/react-query': 5.90.7(react@19.1.0)
|
||||
react: 19.1.0
|
||||
|
||||
'@tanstack/react-query@5.90.7(react@19.1.0)':
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.90.7
|
||||
react: 19.1.0
|
||||
|
||||
'@tanstack/react-table@8.21.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)':
|
||||
dependencies:
|
||||
'@tanstack/table-core': 8.21.3
|
||||
|
|
@ -8607,7 +8688,7 @@ snapshots:
|
|||
react: 19.1.0
|
||||
react-dom: 19.1.0(react@19.1.0)
|
||||
react-easy-sort: 1.6.0(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
tailwind-merge: 3.3.1
|
||||
tailwind-merge: 3.4.0
|
||||
transitivePeerDependencies:
|
||||
- '@types/react'
|
||||
- '@types/react-dom'
|
||||
|
|
@ -9748,6 +9829,19 @@ snapshots:
|
|||
|
||||
jiti@2.4.2: {}
|
||||
|
||||
jotai-tanstack-query@0.11.0(@tanstack/query-core@5.90.7)(@tanstack/react-query@5.90.7(react@19.1.0))(jotai@2.15.1(@types/react@19.1.8)(react@19.1.0))(react@19.1.0):
|
||||
dependencies:
|
||||
'@tanstack/query-core': 5.90.7
|
||||
jotai: 2.15.1(@types/react@19.1.8)(react@19.1.0)
|
||||
optionalDependencies:
|
||||
'@tanstack/react-query': 5.90.7(react@19.1.0)
|
||||
react: 19.1.0
|
||||
|
||||
jotai@2.15.1(@types/react@19.1.8)(react@19.1.0):
|
||||
optionalDependencies:
|
||||
'@types/react': 19.1.8
|
||||
react: 19.1.0
|
||||
|
||||
js-tokens@4.0.0: {}
|
||||
|
||||
js-yaml@4.1.0:
|
||||
|
|
@ -11807,6 +11901,8 @@ snapshots:
|
|||
|
||||
tailwind-merge@3.3.1: {}
|
||||
|
||||
tailwind-merge@3.4.0: {}
|
||||
|
||||
tailwindcss-animate@1.0.7(tailwindcss@4.1.11):
|
||||
dependencies:
|
||||
tailwindcss: 4.1.11
|
||||
|
|
|
|||
39
surfsense_web/stores/chat/active-chat.atom.ts
Normal file
39
surfsense_web/stores/chat/active-chat.atom.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { atom } from "jotai";
|
||||
import { atomWithQuery } from "jotai-tanstack-query";
|
||||
import type { ChatDetails } from "@/app/dashboard/[search_space_id]/chats/chats-client";
|
||||
import type { PodcastItem } from "@/app/dashboard/[search_space_id]/podcasts/podcasts-client";
|
||||
import { fetchChatDetails } from "@/lib/apis/chat-apis";
|
||||
import { getPodcastByChatId } from "@/lib/apis/podcast-apis";
|
||||
|
||||
type ActiveChatState = {
|
||||
chatId: string | null;
|
||||
chatDetails: ChatDetails | null;
|
||||
podcast: PodcastItem | null;
|
||||
};
|
||||
|
||||
export const activeChatIdAtom = atom<string | null>(null);
|
||||
|
||||
export const activeChatAtom = atomWithQuery<ActiveChatState>((get) => {
|
||||
const activeChatId = get(activeChatIdAtom);
|
||||
const authToken = localStorage.getItem("surfsense_bearer_token");
|
||||
|
||||
return {
|
||||
queryKey: ["activeChat", activeChatId],
|
||||
enabled: !!activeChatId && !!authToken,
|
||||
queryFn: async () => {
|
||||
if (!authToken) {
|
||||
throw new Error("No authentication token found");
|
||||
}
|
||||
if (!activeChatId) {
|
||||
throw new Error("No active chat id found");
|
||||
}
|
||||
|
||||
const [podcast, chatDetails] = await Promise.all([
|
||||
getPodcastByChatId(activeChatId, authToken),
|
||||
fetchChatDetails(activeChatId, authToken),
|
||||
]);
|
||||
|
||||
return { chatId: activeChatId, chatDetails, podcast };
|
||||
},
|
||||
};
|
||||
});
|
||||
9
surfsense_web/stores/chat/chat-ui.atom.ts
Normal file
9
surfsense_web/stores/chat/chat-ui.atom.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { atom } from "jotai";
|
||||
|
||||
type ChatUIState = {
|
||||
isChatPannelOpen: boolean;
|
||||
};
|
||||
|
||||
export const chatUIAtom = atom<ChatUIState>({
|
||||
isChatPannelOpen: false,
|
||||
});
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
import { atom } from "jotai";
|
||||
|
||||
export const activeSearchSpaceIdAtom = atom<string | null>(null);
|
||||
Loading…
Add table
Add a link
Reference in a new issue