mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-05-01 20:03:30 +02:00
Merge pull request #430 from CREDO23/feat/chat-pannel
[Feature] Add the chat panel
This commit is contained in:
commit
0835a192a2
38 changed files with 1219 additions and 72 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
|
podcast_title: str
|
||||||
user_id: str
|
user_id: str
|
||||||
search_space_id: int
|
search_space_id: int
|
||||||
|
user_prompt: str | None = None
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_runnable_config(
|
def from_runnable_config(
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ async def create_podcast_transcript(
|
||||||
configuration = Configuration.from_runnable_config(config)
|
configuration = Configuration.from_runnable_config(config)
|
||||||
user_id = configuration.user_id
|
user_id = configuration.user_id
|
||||||
search_space_id = configuration.search_space_id
|
search_space_id = configuration.search_space_id
|
||||||
|
user_prompt = configuration.user_prompt
|
||||||
|
|
||||||
# Get user's long context LLM
|
# Get user's long context LLM
|
||||||
llm = await get_user_long_context_llm(state.db_session, user_id, search_space_id)
|
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)
|
raise RuntimeError(error_message)
|
||||||
|
|
||||||
# Get the prompt
|
# Get the prompt
|
||||||
prompt = get_podcast_generation_prompt()
|
prompt = get_podcast_generation_prompt(user_prompt)
|
||||||
|
|
||||||
# Create the messages
|
# Create the messages
|
||||||
messages = [
|
messages = [
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,23 @@
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
|
||||||
def get_podcast_generation_prompt():
|
def get_podcast_generation_prompt(user_prompt: str | None = None):
|
||||||
return f"""
|
return f"""
|
||||||
Today's date: {datetime.datetime.now().strftime("%Y-%m-%d")}
|
Today's date: {datetime.datetime.now().strftime("%Y-%m-%d")}
|
||||||
<podcast_generation_system>
|
<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.
|
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>
|
<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.
|
- '<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>
|
</input>
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ from sqlalchemy import (
|
||||||
ARRAY,
|
ARRAY,
|
||||||
JSON,
|
JSON,
|
||||||
TIMESTAMP,
|
TIMESTAMP,
|
||||||
|
BigInteger,
|
||||||
Boolean,
|
Boolean,
|
||||||
Column,
|
Column,
|
||||||
Enum as SQLAlchemyEnum,
|
Enum as SQLAlchemyEnum,
|
||||||
|
|
@ -157,6 +158,7 @@ class Chat(BaseModel, TimestampMixin):
|
||||||
title = Column(String, nullable=False, index=True)
|
title = Column(String, nullable=False, index=True)
|
||||||
initial_connectors = Column(ARRAY(String), nullable=True)
|
initial_connectors = Column(ARRAY(String), nullable=True)
|
||||||
messages = Column(JSON, nullable=False)
|
messages = Column(JSON, nullable=False)
|
||||||
|
state_version = Column(BigInteger, nullable=False, default=1)
|
||||||
|
|
||||||
search_space_id = Column(
|
search_space_id = Column(
|
||||||
Integer, ForeignKey("searchspaces.id", ondelete="CASCADE"), nullable=False
|
Integer, ForeignKey("searchspaces.id", ondelete="CASCADE"), nullable=False
|
||||||
|
|
@ -203,6 +205,10 @@ class Podcast(BaseModel, TimestampMixin):
|
||||||
title = Column(String, nullable=False, index=True)
|
title = Column(String, nullable=False, index=True)
|
||||||
podcast_transcript = Column(JSON, nullable=False, default={})
|
podcast_transcript = Column(JSON, nullable=False, default={})
|
||||||
file_location = Column(String(500), 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(
|
search_space_id = Column(
|
||||||
Integer, ForeignKey("searchspaces.id", ondelete="CASCADE"), nullable=False
|
Integer, ForeignKey("searchspaces.id", ondelete="CASCADE"), nullable=False
|
||||||
|
|
|
||||||
|
|
@ -199,6 +199,7 @@ async def read_chats(
|
||||||
Chat.initial_connectors,
|
Chat.initial_connectors,
|
||||||
Chat.search_space_id,
|
Chat.search_space_id,
|
||||||
Chat.created_at,
|
Chat.created_at,
|
||||||
|
Chat.state_version,
|
||||||
)
|
)
|
||||||
.join(SearchSpace)
|
.join(SearchSpace)
|
||||||
.filter(SearchSpace.user_id == user.id)
|
.filter(SearchSpace.user_id == user.id)
|
||||||
|
|
@ -261,7 +262,10 @@ async def update_chat(
|
||||||
db_chat = await read_chat(chat_id, session, user)
|
db_chat = await read_chat(chat_id, session, user)
|
||||||
update_data = chat_update.model_dump(exclude_unset=True)
|
update_data = chat_update.model_dump(exclude_unset=True)
|
||||||
for key, value in update_data.items():
|
for key, value in update_data.items():
|
||||||
|
if key == "messages":
|
||||||
|
db_chat.state_version = len(update_data["messages"])
|
||||||
setattr(db_chat, key, value)
|
setattr(db_chat, key, value)
|
||||||
|
|
||||||
await session.commit()
|
await session.commit()
|
||||||
await session.refresh(db_chat)
|
await session.refresh(db_chat)
|
||||||
return db_chat
|
return db_chat
|
||||||
|
|
|
||||||
|
|
@ -155,7 +155,11 @@ async def delete_podcast(
|
||||||
|
|
||||||
|
|
||||||
async def generate_chat_podcast_with_new_session(
|
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."""
|
"""Create a new session and process chat podcast generation."""
|
||||||
from app.db import async_session_maker
|
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:
|
async with async_session_maker() as session:
|
||||||
try:
|
try:
|
||||||
await generate_chat_podcast(
|
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:
|
except Exception as e:
|
||||||
import logging
|
import logging
|
||||||
|
|
@ -211,7 +215,11 @@ async def generate_podcast(
|
||||||
# Add Celery tasks for each chat ID
|
# Add Celery tasks for each chat ID
|
||||||
for chat_id in valid_chat_ids:
|
for chat_id in valid_chat_ids:
|
||||||
generate_chat_podcast_task.delay(
|
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 {
|
return {
|
||||||
|
|
@ -287,3 +295,27 @@ async def stream_podcast(
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=500, detail=f"Error streaming podcast: {e!s}"
|
status_code=500, detail=f"Error streaming podcast: {e!s}"
|
||||||
) from e
|
) 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
|
initial_connectors: list[str] | None = None
|
||||||
messages: list[Any]
|
messages: list[Any]
|
||||||
search_space_id: int
|
search_space_id: int
|
||||||
|
state_version: int = 1
|
||||||
|
|
||||||
|
|
||||||
class ChatBaseWithoutMessages(BaseModel):
|
class ChatBaseWithoutMessages(BaseModel):
|
||||||
type: ChatType
|
type: ChatType
|
||||||
title: str
|
title: str
|
||||||
search_space_id: int
|
search_space_id: int
|
||||||
|
state_version: int = 1
|
||||||
|
|
||||||
|
|
||||||
class ClientAttachment(BaseModel):
|
class ClientAttachment(BaseModel):
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ class PodcastBase(BaseModel):
|
||||||
podcast_transcript: list[Any]
|
podcast_transcript: list[Any]
|
||||||
file_location: str = ""
|
file_location: str = ""
|
||||||
search_space_id: int
|
search_space_id: int
|
||||||
|
chat_state_version: int | None = None
|
||||||
|
|
||||||
|
|
||||||
class PodcastCreate(PodcastBase):
|
class PodcastCreate(PodcastBase):
|
||||||
|
|
@ -28,4 +29,5 @@ class PodcastGenerateRequest(BaseModel):
|
||||||
type: Literal["DOCUMENT", "CHAT"]
|
type: Literal["DOCUMENT", "CHAT"]
|
||||||
ids: list[int]
|
ids: list[int]
|
||||||
search_space_id: 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)
|
@celery_app.task(name="generate_chat_podcast", bind=True)
|
||||||
def generate_chat_podcast_task(
|
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.
|
Celery task to generate podcast from chat.
|
||||||
|
|
@ -46,15 +51,18 @@ def generate_chat_podcast_task(
|
||||||
Args:
|
Args:
|
||||||
chat_id: ID of the chat to generate podcast from
|
chat_id: ID of the chat to generate podcast from
|
||||||
search_space_id: ID of the search space
|
search_space_id: ID of the search space
|
||||||
|
user_id: ID of the user,
|
||||||
podcast_title: Title for the podcast
|
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()
|
loop = asyncio.new_event_loop()
|
||||||
asyncio.set_event_loop(loop)
|
asyncio.set_event_loop(loop)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
loop.run_until_complete(
|
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())
|
loop.run_until_complete(loop.shutdown_asyncgens())
|
||||||
finally:
|
finally:
|
||||||
|
|
@ -63,13 +71,17 @@ def generate_chat_podcast_task(
|
||||||
|
|
||||||
|
|
||||||
async def _generate_chat_podcast(
|
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."""
|
"""Generate chat podcast with new session."""
|
||||||
async with get_celery_session_maker()() as session:
|
async with get_celery_session_maker()() as session:
|
||||||
try:
|
try:
|
||||||
await generate_chat_podcast(
|
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:
|
except Exception as e:
|
||||||
logger.error(f"Error generating podcast from chat: {e!s}")
|
logger.error(f"Error generating podcast from chat: {e!s}")
|
||||||
|
|
|
||||||
|
|
@ -19,8 +19,9 @@ async def generate_chat_podcast(
|
||||||
session: AsyncSession,
|
session: AsyncSession,
|
||||||
chat_id: int,
|
chat_id: int,
|
||||||
search_space_id: int,
|
search_space_id: int,
|
||||||
podcast_title: str,
|
|
||||||
user_id: int,
|
user_id: int,
|
||||||
|
podcast_title: str | None = None,
|
||||||
|
user_prompt: str | None = None,
|
||||||
):
|
):
|
||||||
task_logger = TaskLoggingService(session, search_space_id)
|
task_logger = TaskLoggingService(session, search_space_id)
|
||||||
|
|
||||||
|
|
@ -34,6 +35,7 @@ async def generate_chat_podcast(
|
||||||
"search_space_id": search_space_id,
|
"search_space_id": search_space_id,
|
||||||
"podcast_title": podcast_title,
|
"podcast_title": podcast_title,
|
||||||
"user_id": str(user_id),
|
"user_id": str(user_id),
|
||||||
|
"user_prompt": user_prompt,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -96,9 +98,10 @@ async def generate_chat_podcast(
|
||||||
|
|
||||||
config = {
|
config = {
|
||||||
"configurable": {
|
"configurable": {
|
||||||
"podcast_title": "SurfSense",
|
"podcast_title": podcast_title or "SurfSense Podcast",
|
||||||
"user_id": str(user_id),
|
"user_id": str(user_id),
|
||||||
"search_space_id": search_space_id,
|
"search_space_id": search_space_id,
|
||||||
|
"user_prompt": user_prompt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
# Initialize state with database session and streaming service
|
# Initialize state with database session and streaming service
|
||||||
|
|
@ -139,33 +142,49 @@ async def generate_chat_podcast(
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
podcast = Podcast(
|
# check if podcast already exists for this chat (re-generation)
|
||||||
title=f"{podcast_title}",
|
existing_podcast = await session.execute(
|
||||||
podcast_transcript=serializable_transcript,
|
select(Podcast).filter(Podcast.chat_id == chat_id)
|
||||||
file_location=result["final_podcast_file_path"],
|
|
||||||
search_space_id=search_space_id,
|
|
||||||
)
|
)
|
||||||
|
existing_podcast = existing_podcast.scalars().first()
|
||||||
|
|
||||||
# Add to session and commit
|
if existing_podcast:
|
||||||
session.add(podcast)
|
existing_podcast.podcast_transcript = serializable_transcript
|
||||||
await session.commit()
|
existing_podcast.file_location = result["final_podcast_file_path"]
|
||||||
await session.refresh(podcast)
|
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
|
# Add to session and commit
|
||||||
await task_logger.log_task_success(
|
session.add(podcast)
|
||||||
log_entry,
|
await session.commit()
|
||||||
f"Successfully generated podcast for chat {chat_id}",
|
await session.refresh(podcast)
|
||||||
{
|
|
||||||
"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
|
# 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:
|
except ValueError as ve:
|
||||||
# ValueError is already logged above for chat not found
|
# ValueError is already logged above for chat not found
|
||||||
|
|
|
||||||
|
|
@ -56,12 +56,24 @@ import {
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface Chat {
|
export interface Chat {
|
||||||
created_at: string;
|
created_at: string;
|
||||||
id: number;
|
id: number;
|
||||||
type: string;
|
type: "DOCUMENT" | "CHAT";
|
||||||
title: string;
|
title: string;
|
||||||
search_space_id: number;
|
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 {
|
interface ChatsPageClientProps {
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,12 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Loader2 } from "lucide-react";
|
import { useAtom } from "jotai";
|
||||||
|
import { Loader2, PanelRight } from "lucide-react";
|
||||||
import { usePathname, useRouter } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import type React from "react";
|
import type React from "react";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
import { ChatPanelContainer } from "@/components/chat/ChatPanel/ChatPanelContainer";
|
||||||
import { DashboardBreadcrumb } from "@/components/dashboard-breadcrumb";
|
import { DashboardBreadcrumb } from "@/components/dashboard-breadcrumb";
|
||||||
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
|
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
|
||||||
import { AppSidebarProvider } from "@/components/sidebar/AppSidebarProvider";
|
import { AppSidebarProvider } from "@/components/sidebar/AppSidebarProvider";
|
||||||
|
|
@ -13,6 +15,8 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
|
||||||
import { Separator } from "@/components/ui/separator";
|
import { Separator } from "@/components/ui/separator";
|
||||||
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
|
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
|
||||||
import { useLLMPreferences } from "@/hooks/use-llm-configs";
|
import { useLLMPreferences } from "@/hooks/use-llm-configs";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { chatUIAtom } from "@/stores/chat/chat-ui.atom";
|
||||||
|
|
||||||
export function DashboardClientLayout({
|
export function DashboardClientLayout({
|
||||||
children,
|
children,
|
||||||
|
|
@ -30,6 +34,10 @@ export function DashboardClientLayout({
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const searchSpaceIdNum = Number(searchSpaceId);
|
const searchSpaceIdNum = Number(searchSpaceId);
|
||||||
|
|
||||||
|
const [chatUIState, setChatUIState] = useAtom(chatUIAtom);
|
||||||
|
|
||||||
|
const { isChatPannelOpen } = chatUIState;
|
||||||
|
|
||||||
const { loading, error, isOnboardingComplete } = useLLMPreferences(searchSpaceIdNum);
|
const { loading, error, isOnboardingComplete } = useLLMPreferences(searchSpaceIdNum);
|
||||||
const [hasCheckedOnboarding, setHasCheckedOnboarding] = useState(false);
|
const [hasCheckedOnboarding, setHasCheckedOnboarding] = useState(false);
|
||||||
|
|
||||||
|
|
@ -129,28 +137,49 @@ export function DashboardClientLayout({
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
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 */}
|
{/* Use AppSidebarProvider which fetches user, search space, and recent chats */}
|
||||||
<AppSidebarProvider
|
<AppSidebarProvider
|
||||||
searchSpaceId={searchSpaceId}
|
searchSpaceId={searchSpaceId}
|
||||||
navSecondary={translatedNavSecondary}
|
navSecondary={translatedNavSecondary}
|
||||||
navMain={translatedNavMain}
|
navMain={translatedNavMain}
|
||||||
/>
|
/>
|
||||||
<SidebarInset>
|
<SidebarInset className="h-full ">
|
||||||
<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">
|
<main className="flex h-full">
|
||||||
<div className="flex items-center justify-between w-full gap-2 px-4">
|
<div className="flex grow flex-col h-full border-r">
|
||||||
<div className="flex items-center gap-2">
|
<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">
|
||||||
<SidebarTrigger className="-ml-1" />
|
<div className="flex items-center justify-between w-full gap-2 px-4">
|
||||||
<Separator orientation="vertical" className="h-6" />
|
<div className="flex items-center gap-2">
|
||||||
<DashboardBreadcrumb />
|
<SidebarTrigger className="-ml-1" />
|
||||||
</div>
|
<Separator orientation="vertical" className="h-6" />
|
||||||
<div className="flex items-center gap-2">
|
<DashboardBreadcrumb />
|
||||||
<LanguageSwitcher />
|
</div>
|
||||||
<ThemeTogglerComponent />
|
<div className="flex items-center gap-2">
|
||||||
</div>
|
<LanguageSwitcher />
|
||||||
|
<ThemeTogglerComponent />
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setChatUIState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
isChatPannelOpen: !isChatPannelOpen,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className={cn(" shrink-0 rounded-full w-fit hover:bg-muted")}
|
||||||
|
>
|
||||||
|
<PanelRight className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<div className="grow flex-1 overflow-auto">{children}</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
<ChatPanelContainer />
|
||||||
{children}
|
</main>
|
||||||
</SidebarInset>
|
</SidebarInset>
|
||||||
</SidebarProvider>
|
</SidebarProvider>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -59,12 +59,6 @@ export default function DashboardLayout({
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
title: "Podcasts",
|
|
||||||
url: `/dashboard/${search_space_id}/podcasts`,
|
|
||||||
icon: "Podcast",
|
|
||||||
items: [],
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
title: "Logs",
|
title: "Logs",
|
||||||
url: `/dashboard/${search_space_id}/logs`,
|
url: `/dashboard/${search_space_id}/logs`,
|
||||||
|
|
|
||||||
|
|
@ -47,13 +47,14 @@ import {
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { Slider } from "@/components/ui/slider";
|
import { Slider } from "@/components/ui/slider";
|
||||||
|
|
||||||
interface PodcastItem {
|
export interface PodcastItem {
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
file_location: string;
|
file_location: string;
|
||||||
podcast_transcript: any[];
|
podcast_transcript: any[];
|
||||||
search_space_id: number;
|
search_space_id: number;
|
||||||
|
chat_state_version: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PodcastsPageClientProps {
|
interface PodcastsPageClientProps {
|
||||||
|
|
|
||||||
|
|
@ -42,9 +42,9 @@ export default function DashboardLayout({ children }: DashboardLayoutProps) {
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<div className="h-full flex flex-col ">
|
||||||
<AnnouncementBanner />
|
<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 { ThemeProvider } from "@/components/theme/theme-provider";
|
||||||
import { Toaster } from "@/components/ui/sonner";
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
import { LocaleProvider } from "@/contexts/LocaleContext";
|
import { LocaleProvider } from "@/contexts/LocaleContext";
|
||||||
|
import { ReactQueryClientProvider } from "@/lib/query-client/query-client.provider";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
const roboto = Roboto({
|
const roboto = Roboto({
|
||||||
|
|
@ -89,7 +90,7 @@ export default function RootLayout({
|
||||||
// Locale state is managed by LocaleContext and persisted in localStorage
|
// Locale state is managed by LocaleContext and persisted in localStorage
|
||||||
return (
|
return (
|
||||||
<html lang="en" suppressHydrationWarning>
|
<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>
|
<LocaleProvider>
|
||||||
<I18nProvider>
|
<I18nProvider>
|
||||||
<ThemeProvider
|
<ThemeProvider
|
||||||
|
|
@ -99,7 +100,9 @@ export default function RootLayout({
|
||||||
defaultTheme="light"
|
defaultTheme="light"
|
||||||
>
|
>
|
||||||
<RootProvider>
|
<RootProvider>
|
||||||
{children}
|
<ReactQueryClientProvider>
|
||||||
|
<div className=" h-[100dvh] w-[100vw] overflow-hidden">{children}</div>
|
||||||
|
</ReactQueryClientProvider>
|
||||||
<Toaster />
|
<Toaster />
|
||||||
</RootProvider>
|
</RootProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ export function AnnouncementBanner() {
|
||||||
if (!isVisible) return null;
|
if (!isVisible) return null;
|
||||||
|
|
||||||
return (
|
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="container mx-auto px-4">
|
||||||
<div className="flex items-center justify-center gap-3 py-2.5">
|
<div className="flex items-center justify-center gap-3 py-2.5">
|
||||||
<Info className="h-4 w-4 text-blue-50 flex-shrink-0" />
|
<Info className="h-4 w-4 text-blue-50 flex-shrink-0" />
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,14 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { type ChatHandler, ChatSection as LlamaIndexChatSection } from "@llamaindex/chat-ui";
|
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 { ChatInputUI } from "@/components/chat/ChatInputGroup";
|
||||||
import { ChatMessagesUI } from "@/components/chat/ChatMessages";
|
import { ChatMessagesUI } from "@/components/chat/ChatMessages";
|
||||||
import type { Document } from "@/hooks/use-documents";
|
import type { Document } from "@/hooks/use-documents";
|
||||||
|
import { activeChatIdAtom } from "@/stores/chat/active-chat.atom";
|
||||||
|
import { ChatPanelContainer } from "./ChatPanel/ChatPanelContainer";
|
||||||
|
|
||||||
interface ChatInterfaceProps {
|
interface ChatInterfaceProps {
|
||||||
handler: ChatHandler;
|
handler: ChatHandler;
|
||||||
|
|
@ -28,9 +33,18 @@ export default function ChatInterface({
|
||||||
topK = 10,
|
topK = 10,
|
||||||
onTopKChange,
|
onTopKChange,
|
||||||
}: ChatInterfaceProps) {
|
}: 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 (
|
return (
|
||||||
<LlamaIndexChatSection handler={handler} className="flex h-full">
|
<LlamaIndexChatSection handler={handler} className="flex h-full">
|
||||||
<div className="flex flex-1 flex-col">
|
<div className="flex grow-1 flex-col">
|
||||||
<ChatMessagesUI />
|
<ChatMessagesUI />
|
||||||
<div className="border-t p-4">
|
<div className="border-t p-4">
|
||||||
<ChatInputUI
|
<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-64" : "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;
|
||||||
|
}
|
||||||
147
surfsense_web/components/chat/ChatPanel/ChatPanelView.tsx
Normal file
147
surfsense_web/components/chat/ChatPanel/ChatPanelView.tsx
Normal file
|
|
@ -0,0 +1,147 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useAtom, useAtomValue } from "jotai";
|
||||||
|
import { AlertCircle, Pencil, Play, Podcast, RefreshCw } from "lucide-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 cursor-pointer p-4 border-b",
|
||||||
|
!isChatPannelOpen && "flex items-center justify-center"
|
||||||
|
)}
|
||||||
|
title={podcastIsStale ? "Regenerate Podcast" : "Generate Podcast"}
|
||||||
|
>
|
||||||
|
{isChatPannelOpen ? (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{/* Show stale podcast warning if applicable */}
|
||||||
|
{podcastIsStale && (
|
||||||
|
<div className="rounded-lg p-3 bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800">
|
||||||
|
<div className="flex gap-2 items-start">
|
||||||
|
<AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-500 mt-0.5 flex-shrink-0" />
|
||||||
|
<div className="text-sm text-amber-800 dark:text-amber-200">
|
||||||
|
<p className="font-medium">Podcast is outdated</p>
|
||||||
|
<p className="text-xs mt-1 opacity-90">
|
||||||
|
{getPodcastStalenessMessage(
|
||||||
|
chatDetails?.state_version || 0,
|
||||||
|
podcast?.chat_state_version
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
onClick={handleGeneratePost}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") {
|
||||||
|
e.preventDefault();
|
||||||
|
handleGeneratePost();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"w-full space-y-3 rounded-xl p-3 transition-colors",
|
||||||
|
podcastIsStale
|
||||||
|
? "bg-gradient-to-r from-amber-400/50 to-orange-300/50 dark:from-amber-500/30 dark:to-orange-600/30 hover:from-amber-400/60 hover:to-orange-300/60"
|
||||||
|
: "bg-gradient-to-r from-slate-400/50 to-slate-200/50 dark:from-slate-400/30 dark:to-slate-800/60 hover:from-slate-400/60 hover:to-slate-200/60"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="w-full flex items-center justify-between">
|
||||||
|
{podcastIsStale ? (
|
||||||
|
<RefreshCw strokeWidth={1} className="h-5 w-5" />
|
||||||
|
) : (
|
||||||
|
<Podcast strokeWidth={1} className="h-5 w-5" />
|
||||||
|
)}
|
||||||
|
<ConfigModal generatePodcast={generatePodcast} />
|
||||||
|
</div>
|
||||||
|
<p className="text-sm font-medium text-left">
|
||||||
|
{podcastIsStale ? "Regenerate Podcast" : "Generate Podcast"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
title={podcastIsStale ? "Regenerate Podcast" : "Generate Podcast"}
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setChatUIState((prev) => ({
|
||||||
|
...prev,
|
||||||
|
isChatPannelOpen: !isChatPannelOpen,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className={cn(
|
||||||
|
"p-2 rounded-full hover:bg-muted transition-colors",
|
||||||
|
podcastIsStale && "text-amber-600 dark:text-amber-500"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{podcastIsStale ? (
|
||||||
|
<RefreshCw strokeWidth={1} className="h-5 w-5" />
|
||||||
|
) : (
|
||||||
|
<Podcast strokeWidth={1} className="h-5 w-5" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{podcast ? (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"w-full border-b",
|
||||||
|
!isChatPannelOpen && "flex items-center justify-center p-4"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{isChatPannelOpen ? (
|
||||||
|
<PodcastPlayer compact podcast={podcast} />
|
||||||
|
) : podcast ? (
|
||||||
|
<button
|
||||||
|
title="Play Podcast"
|
||||||
|
type="button"
|
||||||
|
onClick={() => setChatUIState((prev) => ({ ...prev, isChatPannelOpen: true }))}
|
||||||
|
className="p-2 rounded-full hover:bg-muted transition-colors text-green-600 dark:text-green-500"
|
||||||
|
>
|
||||||
|
<Play strokeWidth={1} className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
72
surfsense_web/components/chat/ChatPanel/ConfigModal.tsx
Normal file
72
surfsense_web/components/chat/ChatPanel/ConfigModal.tsx
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
"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">
|
||||||
|
What subjects should the AI cover in this podcast ?
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<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,321 @@
|
||||||
|
"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-3 p-3">
|
||||||
|
<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: isPlaying ? [1, 1.05, 1] : 1 }}
|
||||||
|
transition={{
|
||||||
|
repeat: isPlaying ? Infinity : 0,
|
||||||
|
duration: 2,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Podcast className="h-4 w-4 text-primary" />
|
||||||
|
</motion.div>
|
||||||
|
<h4 className="font-medium text-xs line-clamp-1 flex-grow">{podcast.title}</h4>
|
||||||
|
{onClose && (
|
||||||
|
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={onClose}
|
||||||
|
className="h-6 w-6 flex-shrink-0"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</motion.div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Slider
|
||||||
|
value={[currentTime]}
|
||||||
|
min={0}
|
||||||
|
max={duration || 100}
|
||||||
|
step={0.1}
|
||||||
|
onValueChange={handleSeek}
|
||||||
|
className="flex-grow"
|
||||||
|
/>
|
||||||
|
<div className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0">
|
||||||
|
{formatTime(currentTime)} / {formatTime(duration)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between gap-1">
|
||||||
|
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={skipBackward}
|
||||||
|
className="h-7 w-7"
|
||||||
|
disabled={!duration}
|
||||||
|
>
|
||||||
|
<SkipBack className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
size="icon"
|
||||||
|
onClick={togglePlayPause}
|
||||||
|
className="h-8 w-8 rounded-full"
|
||||||
|
disabled={!duration}
|
||||||
|
>
|
||||||
|
{isPlaying ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4 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-7 w-7"
|
||||||
|
disabled={!duration}
|
||||||
|
>
|
||||||
|
<SkipForward className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
<motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.95 }}>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={toggleMute}
|
||||||
|
className={`h-7 w-7 ${isMuted ? "text-muted-foreground" : "text-primary"}`}
|
||||||
|
>
|
||||||
|
{isMuted ? <VolumeX className="h-3 w-3" /> : <Volume2 className="h-3 w-3" />}
|
||||||
|
</Button>
|
||||||
|
</motion.div>
|
||||||
|
</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.";
|
||||||
|
}
|
||||||
|
|
@ -294,7 +294,7 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||||
data-slot="sidebar-inset"
|
data-slot="sidebar-inset"
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-background relative flex w-full flex-1 flex-col",
|
"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
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import type { Message } from "@ai-sdk/react";
|
import type { Message } from "@ai-sdk/react";
|
||||||
import { useCallback, useEffect, useState } from "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 { ResearchMode } from "@/components/chat";
|
||||||
import type { Document } from "@/hooks/use-documents";
|
import type { Document } from "@/hooks/use-documents";
|
||||||
|
|
||||||
|
|
@ -52,7 +53,7 @@ interface UseChatAPIProps {
|
||||||
|
|
||||||
export function useChatAPI({ token, search_space_id }: UseChatAPIProps) {
|
export function useChatAPI({ token, search_space_id }: UseChatAPIProps) {
|
||||||
const fetchChatDetails = useCallback(
|
const fetchChatDetails = useCallback(
|
||||||
async (chatId: string) => {
|
async (chatId: string): Promise<ChatDetails | null> => {
|
||||||
if (!token) return null;
|
if (!token) return null;
|
||||||
|
|
||||||
try {
|
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:generate": "drizzle-kit generate",
|
||||||
"db:migrate": "drizzle-kit migrate",
|
"db:migrate": "drizzle-kit migrate",
|
||||||
"db:push": "drizzle-kit push",
|
"db:push": "drizzle-kit push",
|
||||||
"db:studio": "drizzle-kit studio"
|
"db:studio": "drizzle-kit studio",
|
||||||
|
"format:fix": "npx @biomejs/biome check --fix"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/react": "^1.2.12",
|
"@ai-sdk/react": "^1.2.12",
|
||||||
|
|
@ -45,6 +46,9 @@
|
||||||
"@radix-ui/react-toggle-group": "^1.1.10",
|
"@radix-ui/react-toggle-group": "^1.1.10",
|
||||||
"@radix-ui/react-tooltip": "^1.2.7",
|
"@radix-ui/react-tooltip": "^1.2.7",
|
||||||
"@tabler/icons-react": "^3.34.1",
|
"@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",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"@types/mdx": "^2.0.13",
|
"@types/mdx": "^2.0.13",
|
||||||
"@types/react-syntax-highlighter": "^15.5.13",
|
"@types/react-syntax-highlighter": "^15.5.13",
|
||||||
|
|
@ -60,6 +64,8 @@
|
||||||
"fumadocs-mdx": "^11.7.1",
|
"fumadocs-mdx": "^11.7.1",
|
||||||
"fumadocs-ui": "^15.6.6",
|
"fumadocs-ui": "^15.6.6",
|
||||||
"geist": "^1.4.2",
|
"geist": "^1.4.2",
|
||||||
|
"jotai": "^2.15.1",
|
||||||
|
"jotai-tanstack-query": "^0.11.0",
|
||||||
"lucide-react": "^0.477.0",
|
"lucide-react": "^0.477.0",
|
||||||
"motion": "^12.23.22",
|
"motion": "^12.23.22",
|
||||||
"next": "^15.4.4",
|
"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':
|
'@tabler/icons-react':
|
||||||
specifier: ^3.34.1
|
specifier: ^3.34.1
|
||||||
version: 3.34.1(react@19.1.0)
|
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':
|
'@tanstack/react-table':
|
||||||
specifier: ^8.21.3
|
specifier: ^8.21.3
|
||||||
version: 8.21.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
version: 8.21.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||||
|
|
@ -128,6 +137,12 @@ importers:
|
||||||
geist:
|
geist:
|
||||||
specifier: ^1.4.2
|
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))
|
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:
|
lucide-react:
|
||||||
specifier: ^0.477.0
|
specifier: ^0.477.0
|
||||||
version: 0.477.0(react@19.1.0)
|
version: 0.477.0(react@19.1.0)
|
||||||
|
|
@ -2340,6 +2355,23 @@ packages:
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
tailwindcss: '>=3.0.0 || insiders || >=4.0.0-alpha.20 || >=4.0.0-beta.1'
|
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':
|
'@tanstack/react-table@8.21.3':
|
||||||
resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}
|
resolution: {integrity: sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww==}
|
||||||
engines: {node: '>=12'}
|
engines: {node: '>=12'}
|
||||||
|
|
@ -3818,6 +3850,37 @@ packages:
|
||||||
resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==}
|
resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==}
|
||||||
hasBin: true
|
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:
|
js-tokens@4.0.0:
|
||||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||||
|
|
||||||
|
|
@ -5228,6 +5291,9 @@ packages:
|
||||||
tailwind-merge@3.3.1:
|
tailwind-merge@3.3.1:
|
||||||
resolution: {integrity: sha512-gBXpgUm/3rp1lMZZrM/w7D8GKqshif0zAymAhbCyIt8KMe+0v9DQ7cdYLR4FHH/cKpdTXb+A/tKKU3eolfsI+g==}
|
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:
|
tailwindcss-animate@1.0.7:
|
||||||
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
|
resolution: {integrity: sha512-bl6mpH3T7I3UFxuvDEXLxy/VuFxBk5bbzplh7tXI68mwMokNYd1t9qPBHlnyTwfa4JGC4zP516I1hYYtQ/vspA==}
|
||||||
peerDependencies:
|
peerDependencies:
|
||||||
|
|
@ -7953,6 +8019,21 @@ snapshots:
|
||||||
postcss-selector-parser: 6.0.10
|
postcss-selector-parser: 6.0.10
|
||||||
tailwindcss: 4.1.11
|
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)':
|
'@tanstack/react-table@8.21.3(react-dom@19.1.0(react@19.1.0))(react@19.1.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@tanstack/table-core': 8.21.3
|
'@tanstack/table-core': 8.21.3
|
||||||
|
|
@ -8607,7 +8688,7 @@ snapshots:
|
||||||
react: 19.1.0
|
react: 19.1.0
|
||||||
react-dom: 19.1.0(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)
|
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:
|
transitivePeerDependencies:
|
||||||
- '@types/react'
|
- '@types/react'
|
||||||
- '@types/react-dom'
|
- '@types/react-dom'
|
||||||
|
|
@ -9748,6 +9829,19 @@ snapshots:
|
||||||
|
|
||||||
jiti@2.4.2: {}
|
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-tokens@4.0.0: {}
|
||||||
|
|
||||||
js-yaml@4.1.0:
|
js-yaml@4.1.0:
|
||||||
|
|
@ -11807,6 +11901,8 @@ snapshots:
|
||||||
|
|
||||||
tailwind-merge@3.3.1: {}
|
tailwind-merge@3.3.1: {}
|
||||||
|
|
||||||
|
tailwind-merge@3.4.0: {}
|
||||||
|
|
||||||
tailwindcss-animate@1.0.7(tailwindcss@4.1.11):
|
tailwindcss-animate@1.0.7(tailwindcss@4.1.11):
|
||||||
dependencies:
|
dependencies:
|
||||||
tailwindcss: 4.1.11
|
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