Add frontend session management with localStorage persistence, deduplicate shared code
This commit is contained in:
parent
abfee49d13
commit
467bcff94d
14 changed files with 2598 additions and 1827 deletions
|
|
@ -21,6 +21,11 @@
|
|||
- **AG-UI state sync**: `ask` tool now emits `StateSnapshotEvent` instead of `StateDeltaEvent`, ensuring background summarization results are reliably delivered to clients
|
||||
- **TUI simplified**: Chat TUI reads directly from `ToolContext` namespace states instead of maintaining a separate `ChatSessionState` and manually syncing via AG-UI state events
|
||||
- **AG-UI web app**: Uses `ToolContextCache` to maintain per-thread state across requests
|
||||
- **Frontend session management**: Persistent chat sessions with localStorage, wired to backend `ToolContextCache` via CopilotKit `threadId`
|
||||
- Session manager dropdown: create, switch, delete, and export sessions to markdown
|
||||
- Messages, chat state, and citations restored on session switch
|
||||
- Session title derived from first user message
|
||||
- Inline citation blocks injected after assistant responses via `qa_history` correlation
|
||||
|
||||
### Removed
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,5 @@
|
|||
import type { Metadata } from "next";
|
||||
import "@copilotkit/react-core/v2/styles.css";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
|
|
|
|||
|
|
@ -1,60 +1,51 @@
|
|||
"use client";
|
||||
|
||||
import {
|
||||
CopilotKit,
|
||||
useCoAgent,
|
||||
useCoAgentStateRender,
|
||||
useCopilotAction,
|
||||
} from "@copilotkit/react-core";
|
||||
import { CopilotChat } from "@copilotkit/react-ui";
|
||||
import { useState } from "react";
|
||||
import "@copilotkit/react-ui/styles.css";
|
||||
CopilotChatMessageView,
|
||||
CopilotChatView,
|
||||
CopilotKitProvider,
|
||||
defineToolCallRenderer,
|
||||
UseAgentUpdate,
|
||||
useAgent,
|
||||
useCopilotKit,
|
||||
} from "@copilotkit/react-core/v2";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { BrainIcon, FilterIcon } from "../lib/icons";
|
||||
import type { ChatSessionState } from "../lib/sessionStorage";
|
||||
import {
|
||||
createSession,
|
||||
getActiveSessionId,
|
||||
getSession,
|
||||
normalizeChatState,
|
||||
updateSessionMessages,
|
||||
} from "../lib/sessionStorage";
|
||||
import CitationBlock from "./CitationBlock";
|
||||
import ContextPanel from "./ContextPanel";
|
||||
import DbInfo from "./DbInfo";
|
||||
import DocumentFilter from "./DocumentFilter";
|
||||
import SessionManager from "./SessionManager";
|
||||
|
||||
// Must match AGUI_STATE_KEY from haiku.rag.agents.chat
|
||||
const AGUI_STATE_KEY = "haiku.rag.chat";
|
||||
|
||||
interface Citation {
|
||||
index: number;
|
||||
document_id: string;
|
||||
chunk_id: string;
|
||||
document_uri: string;
|
||||
document_title: string | null;
|
||||
page_numbers: number[];
|
||||
headings: string[] | null;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface QAResponse {
|
||||
question: string;
|
||||
answer: string;
|
||||
confidence: number;
|
||||
citations: Citation[];
|
||||
}
|
||||
|
||||
interface SessionContext {
|
||||
summary: string;
|
||||
last_updated: string | null;
|
||||
}
|
||||
|
||||
interface ChatSessionState {
|
||||
session_id: string;
|
||||
initial_context: string | null;
|
||||
citations: Citation[];
|
||||
qa_history: QAResponse[];
|
||||
session_context: SessionContext | null;
|
||||
document_filter: string[];
|
||||
citation_registry: Record<string, number>;
|
||||
}
|
||||
|
||||
// AG-UI state is namespaced under AGUI_STATE_KEY
|
||||
interface AgentState {
|
||||
[AGUI_STATE_KEY]?: ChatSessionState;
|
||||
}
|
||||
|
||||
// biome-ignore lint/suspicious/noExplicitAny: CopilotKit message objects vary at runtime
|
||||
function serializeMessages(messages: any[]): any[] {
|
||||
return JSON.parse(JSON.stringify(messages));
|
||||
}
|
||||
|
||||
function SpinnerIcon() {
|
||||
return (
|
||||
<svg
|
||||
|
|
@ -143,31 +134,6 @@ function FileIcon() {
|
|||
);
|
||||
}
|
||||
|
||||
function BrainIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z" />
|
||||
<path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z" />
|
||||
<path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4" />
|
||||
<path d="M17.599 6.5a3 3 0 0 0 .399-1.375" />
|
||||
<path d="M6.003 5.125A3 3 0 0 0 6.401 6.5" />
|
||||
<path d="M3.477 10.896a4 4 0 0 1 .585-.396" />
|
||||
<path d="M19.938 10.5a4 4 0 0 1 .585.396" />
|
||||
<path d="M6 18a4 4 0 0 1-1.967-.516" />
|
||||
<path d="M19.967 17.484A4 4 0 0 1 18 18" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolCallIndicator({
|
||||
toolName,
|
||||
status,
|
||||
|
|
@ -246,114 +212,6 @@ function ToolCallIndicator({
|
|||
|
||||
return (
|
||||
<div className={`tool-call-card ${isComplete ? "complete" : "loading"}`}>
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
@keyframes fadeIn {
|
||||
from { opacity: 0; transform: translateY(-4px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.6; }
|
||||
}
|
||||
.tool-call-card {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
margin: 8px 0;
|
||||
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
|
||||
border-radius: 10px;
|
||||
font-size: 13px;
|
||||
color: #475569;
|
||||
border: 1px solid #e2e8f0;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
.tool-call-card.loading {
|
||||
border-color: #bfdbfe;
|
||||
background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
|
||||
}
|
||||
.tool-call-card.complete {
|
||||
border-color: #bbf7d0;
|
||||
background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
|
||||
}
|
||||
.tool-status-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tool-call-card.loading .tool-status-icon {
|
||||
background: #dbeafe;
|
||||
color: #2563eb;
|
||||
}
|
||||
.tool-call-card.complete .tool-status-icon {
|
||||
background: #bbf7d0;
|
||||
color: #16a34a;
|
||||
}
|
||||
.tool-spinner {
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
.tool-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.tool-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.tool-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 8px;
|
||||
background: rgba(59, 130, 246, 0.1);
|
||||
color: #2563eb;
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.025em;
|
||||
}
|
||||
.tool-call-card.complete .tool-badge {
|
||||
background: rgba(22, 163, 74, 0.1);
|
||||
color: #16a34a;
|
||||
}
|
||||
.tool-status-text {
|
||||
font-size: 11px;
|
||||
color: #94a3b8;
|
||||
}
|
||||
.tool-call-card.loading .tool-status-text {
|
||||
animation: pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
.tool-description {
|
||||
color: #334155;
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
}
|
||||
.tool-query {
|
||||
color: #0f172a;
|
||||
font-weight: 500;
|
||||
}
|
||||
.tool-context {
|
||||
color: #64748b;
|
||||
}
|
||||
.tool-context em {
|
||||
color: #475569;
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
}
|
||||
`}</style>
|
||||
<div className="tool-status-icon">
|
||||
{isComplete ? <CheckIcon /> : <SpinnerIcon />}
|
||||
</div>
|
||||
|
|
@ -373,60 +231,164 @@ function ToolCallIndicator({
|
|||
);
|
||||
}
|
||||
|
||||
function FilterIcon() {
|
||||
// Context for sharing chat state with the message view
|
||||
const ChatStateContext = createContext<ChatSessionState | null>(null);
|
||||
|
||||
// Wildcard tool call renderer for all server-side tools
|
||||
const toolCallRenderers = [
|
||||
defineToolCallRenderer({
|
||||
name: "*",
|
||||
render: ({ name, args, result }) => (
|
||||
<ToolCallIndicator
|
||||
toolName={name}
|
||||
status={result !== undefined ? "complete" : "loading"}
|
||||
args={(args ?? {}) as Record<string, unknown>}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
];
|
||||
|
||||
// Custom message view that injects CitationBlocks after assistant responses.
|
||||
// Uses CopilotChatMessageView's children render prop to post-process the
|
||||
// rendered message elements and inject citations at the right positions.
|
||||
function MessageViewWithCitations({
|
||||
messages,
|
||||
isRunning,
|
||||
}: {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: AG-UI Message type is a broad union
|
||||
messages: any[];
|
||||
isRunning: boolean;
|
||||
}) {
|
||||
const chatState = useContext(ChatStateContext);
|
||||
|
||||
const cursor = isRunning ? (
|
||||
<div key="cursor" className="streaming-cursor">
|
||||
<span className="dot" />
|
||||
<span className="dot" />
|
||||
<span className="dot" />
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3" />
|
||||
</svg>
|
||||
<CopilotChatMessageView messages={messages} isRunning={isRunning}>
|
||||
{({ messageElements }) => {
|
||||
if (!chatState?.qa_history?.length) {
|
||||
return (
|
||||
<>
|
||||
{messageElements}
|
||||
{cursor}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// CopilotChatMessageView renders one element per user/assistant/activity
|
||||
// message (tool messages produce nothing). We correlate elements with
|
||||
// messages to inject CitationBlocks after the right assistant responses.
|
||||
//
|
||||
// Tool call objects on messages only carry `id` (no `name`), so we
|
||||
// can't identify which tool was called from the message alone. Instead
|
||||
// we rely on the fact that qa_history only grows when the `ask` tool
|
||||
// runs: after each assistant text response that followed tool calls,
|
||||
// we inject any new qa_history citations.
|
||||
const result: React.ReactNode[] = [];
|
||||
let qaIdx = 0;
|
||||
let seenToolCalls = false;
|
||||
let elemIdx = 0;
|
||||
|
||||
for (const msg of messages) {
|
||||
if (msg.role === "user") {
|
||||
seenToolCalls = false;
|
||||
}
|
||||
|
||||
if (
|
||||
msg.role === "assistant" &&
|
||||
Array.isArray(msg.toolCalls) &&
|
||||
msg.toolCalls.length > 0
|
||||
) {
|
||||
seenToolCalls = true;
|
||||
}
|
||||
|
||||
const isRendered =
|
||||
msg.role === "user" ||
|
||||
msg.role === "assistant" ||
|
||||
msg.role === "activity";
|
||||
if (!isRendered) continue;
|
||||
|
||||
if (elemIdx < messageElements.length) {
|
||||
result.push(messageElements[elemIdx]);
|
||||
elemIdx++;
|
||||
}
|
||||
|
||||
// After an assistant text response that followed tool calls,
|
||||
// inject the next qa_history entry's citations (one per turn)
|
||||
if (msg.role === "assistant" && msg.content && seenToolCalls) {
|
||||
if (qaIdx < chatState.qa_history.length) {
|
||||
const qa = chatState.qa_history[qaIdx];
|
||||
if (qa.citations?.length) {
|
||||
result.push(
|
||||
<CitationBlock
|
||||
key={`citations-${qaIdx}`}
|
||||
citations={qa.citations}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
qaIdx++;
|
||||
}
|
||||
seenToolCalls = false;
|
||||
}
|
||||
}
|
||||
|
||||
while (elemIdx < messageElements.length) {
|
||||
result.push(messageElements[elemIdx]);
|
||||
elemIdx++;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{result}
|
||||
{cursor}
|
||||
</>
|
||||
);
|
||||
}}
|
||||
</CopilotChatMessageView>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatContentInner() {
|
||||
function ChatContentInner({
|
||||
sessionId,
|
||||
onSessionChange,
|
||||
}: {
|
||||
sessionId: string;
|
||||
onSessionChange: (id: string) => void;
|
||||
}) {
|
||||
const [contextOpen, setContextOpen] = useState(false);
|
||||
const [filterOpen, setFilterOpen] = useState(false);
|
||||
|
||||
const { state: agentState, setState: setAgentState } = useCoAgent<AgentState>(
|
||||
{
|
||||
name: "chat_agent",
|
||||
initialState: {
|
||||
[AGUI_STATE_KEY]: {
|
||||
session_id: "",
|
||||
initial_context: null,
|
||||
citations: [],
|
||||
qa_history: [],
|
||||
session_context: null,
|
||||
document_filter: [],
|
||||
citation_registry: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
const { agent } = useAgent({
|
||||
agentId: "chat_agent",
|
||||
updates: [
|
||||
UseAgentUpdate.OnMessagesChanged,
|
||||
UseAgentUpdate.OnStateChanged,
|
||||
UseAgentUpdate.OnRunStatusChanged,
|
||||
],
|
||||
});
|
||||
const { copilotkit: ck } = useCopilotKit();
|
||||
|
||||
// Set threadId (CopilotChat normally does this in its connect effect)
|
||||
useEffect(() => {
|
||||
agent.threadId = sessionId;
|
||||
}, [agent, sessionId]);
|
||||
|
||||
const chatState = normalizeChatState(
|
||||
(agent.state as AgentState)?.[AGUI_STATE_KEY],
|
||||
);
|
||||
|
||||
const normalizeChatState = (
|
||||
state: ChatSessionState | undefined,
|
||||
): ChatSessionState => ({
|
||||
session_id: state?.session_id ?? "",
|
||||
initial_context: state?.initial_context ?? null,
|
||||
citations: state?.citations ?? [],
|
||||
qa_history: state?.qa_history ?? [],
|
||||
session_context: state?.session_context ?? null,
|
||||
document_filter: state?.document_filter ?? [],
|
||||
citation_registry: state?.citation_registry ?? {},
|
||||
});
|
||||
|
||||
const mergeChatState = (partial: Partial<ChatSessionState>) => {
|
||||
const current = normalizeChatState(agentState?.[AGUI_STATE_KEY]);
|
||||
setAgentState({
|
||||
...agentState,
|
||||
const current = normalizeChatState(
|
||||
(agent.state as AgentState)?.[AGUI_STATE_KEY],
|
||||
);
|
||||
agent.setState({
|
||||
...agent.state,
|
||||
[AGUI_STATE_KEY]: {
|
||||
...current,
|
||||
...partial,
|
||||
|
|
@ -434,14 +396,105 @@ function ChatContentInner() {
|
|||
});
|
||||
};
|
||||
|
||||
// Extract session context, document filter, and initial context from agent state
|
||||
const sessionContext = agentState?.[AGUI_STATE_KEY]?.session_context ?? null;
|
||||
const documentFilter = agentState?.[AGUI_STATE_KEY]?.document_filter ?? [];
|
||||
const initialContext = agentState?.[AGUI_STATE_KEY]?.initial_context ?? "";
|
||||
// Restore session from localStorage when agent reference changes.
|
||||
// useAgent returns a provisional agent initially, then the real agent
|
||||
// after runtime connects — re-run restore each time so messages stick.
|
||||
useEffect(() => {
|
||||
if (agent.messages.length > 0) return;
|
||||
const session = getSession(sessionId);
|
||||
if (!session) return;
|
||||
if (session.chatState) {
|
||||
agent.setState({
|
||||
[AGUI_STATE_KEY]: normalizeChatState(session.chatState),
|
||||
});
|
||||
}
|
||||
if (session.messages.length > 0) {
|
||||
// biome-ignore lint/suspicious/noExplicitAny: AG-UI Message type is a broad union
|
||||
agent.setMessages(session.messages as any[]);
|
||||
}
|
||||
}, [agent, sessionId]);
|
||||
|
||||
// Persist messages and state to localStorage.
|
||||
// Read chatState from agent.state at effect time (not render time) so that
|
||||
// restore and persist effects in the same commit see consistent state.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: JSON.stringify tracks content changes
|
||||
useEffect(() => {
|
||||
if (sessionId && agent.messages.length > 0) {
|
||||
const currentChatState = normalizeChatState(
|
||||
(agent.state as AgentState)?.[AGUI_STATE_KEY],
|
||||
);
|
||||
updateSessionMessages(
|
||||
sessionId,
|
||||
serializeMessages(agent.messages),
|
||||
currentChatState,
|
||||
);
|
||||
}
|
||||
}, [JSON.stringify(agent.messages), chatState, sessionId]);
|
||||
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: stable identity via agent ref
|
||||
const messages = useMemo(
|
||||
() => [...agent.messages],
|
||||
[JSON.stringify(agent.messages)],
|
||||
);
|
||||
|
||||
const onSubmitMessage = useCallback(
|
||||
async (text: string) => {
|
||||
agent.addMessage({
|
||||
id: crypto.randomUUID(),
|
||||
role: "user",
|
||||
content: text,
|
||||
});
|
||||
try {
|
||||
await ck.runAgent({ agent });
|
||||
} catch (error) {
|
||||
console.error("runAgent failed", error);
|
||||
}
|
||||
},
|
||||
[agent, ck],
|
||||
);
|
||||
|
||||
const onStop = useCallback(() => {
|
||||
try {
|
||||
ck.stopAgent({ agent });
|
||||
} catch {
|
||||
agent.abortRun();
|
||||
}
|
||||
}, [agent, ck]);
|
||||
|
||||
// Strip the scroll view's internal paddingBottom (inline style set by
|
||||
// CopilotChatView to reserve space for its absolutely-positioned input
|
||||
// container, which we've overridden to flow in a flex layout).
|
||||
// Uses a ref callback so it runs when the element actually mounts.
|
||||
const paddingObserver = useRef<MutationObserver | null>(null);
|
||||
const scrollAreaCallbackRef = useCallback((node: HTMLDivElement | null) => {
|
||||
if (paddingObserver.current) {
|
||||
paddingObserver.current.disconnect();
|
||||
paddingObserver.current = null;
|
||||
}
|
||||
if (!node) return;
|
||||
const strip = () => {
|
||||
for (const div of node.querySelectorAll<HTMLElement>("div")) {
|
||||
if (div.style.paddingBottom && div.style.paddingBottom !== "1rem") {
|
||||
div.style.paddingBottom = "1rem";
|
||||
}
|
||||
}
|
||||
};
|
||||
strip();
|
||||
const observer = new MutationObserver(strip);
|
||||
observer.observe(node, {
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["style"],
|
||||
});
|
||||
paddingObserver.current = observer;
|
||||
}, []);
|
||||
|
||||
const sessionContext = chatState.session_context;
|
||||
const documentFilter = chatState.document_filter;
|
||||
const initialContext = chatState.initial_context ?? "";
|
||||
|
||||
// Context is locked after first message (qa_history has entries)
|
||||
const isContextLocked =
|
||||
(agentState?.[AGUI_STATE_KEY]?.qa_history?.length ?? 0) > 0;
|
||||
const isContextLocked = (chatState.qa_history?.length ?? 0) > 0;
|
||||
|
||||
const handleFilterApply = (selected: string[]) => {
|
||||
mergeChatState({ document_filter: selected });
|
||||
|
|
@ -452,132 +505,15 @@ function ChatContentInner() {
|
|||
mergeChatState({ initial_context: value || null });
|
||||
};
|
||||
|
||||
useCoAgentStateRender<AgentState>({
|
||||
name: "chat_agent",
|
||||
render: ({ state }) => {
|
||||
const chatState = state[AGUI_STATE_KEY];
|
||||
if (chatState?.citations.length) {
|
||||
return <CitationBlock citations={chatState.citations} />;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
|
||||
useCopilotAction({
|
||||
name: "search",
|
||||
available: "disabled",
|
||||
parameters: [
|
||||
{ name: "query", type: "string" },
|
||||
{ name: "document_name", type: "string" },
|
||||
],
|
||||
render: ({ status, args }) => (
|
||||
<ToolCallIndicator
|
||||
toolName="search"
|
||||
status={status}
|
||||
args={args as Record<string, unknown>}
|
||||
/>
|
||||
),
|
||||
});
|
||||
|
||||
useCopilotAction({
|
||||
name: "ask",
|
||||
available: "disabled",
|
||||
parameters: [
|
||||
{ name: "question", type: "string" },
|
||||
{ name: "document_name", type: "string" },
|
||||
],
|
||||
render: ({ status, args }) => (
|
||||
<ToolCallIndicator
|
||||
toolName="ask"
|
||||
status={status}
|
||||
args={args as Record<string, unknown>}
|
||||
/>
|
||||
),
|
||||
});
|
||||
|
||||
useCopilotAction({
|
||||
name: "get_document",
|
||||
available: "disabled",
|
||||
parameters: [{ name: "query", type: "string" }],
|
||||
render: ({ status, args }) => (
|
||||
<ToolCallIndicator
|
||||
toolName="get_document"
|
||||
status={status}
|
||||
args={args as Record<string, unknown>}
|
||||
/>
|
||||
),
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
.chat-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
padding: 1rem;
|
||||
}
|
||||
.chat-container {
|
||||
width: calc(100% - 2rem);
|
||||
max-width: 1400px;
|
||||
height: 90vh;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
||||
background: white;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.chat-header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.header-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.375rem 0.625rem;
|
||||
background: white;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
color: #64748b;
|
||||
font-size: 0.8125rem;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.header-btn:hover {
|
||||
background: #f1f5f9;
|
||||
border-color: #cbd5e1;
|
||||
color: #475569;
|
||||
}
|
||||
.header-btn.has-content {
|
||||
background: #eff6ff;
|
||||
border-color: #bfdbfe;
|
||||
color: #2563eb;
|
||||
}
|
||||
.header-btn.has-content:hover {
|
||||
background: #dbeafe;
|
||||
border-color: #93c5fd;
|
||||
}
|
||||
.chat-content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.chat-content > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
`}</style>
|
||||
<ChatStateContext.Provider value={chatState}>
|
||||
<div className="chat-wrapper">
|
||||
<div className="chat-container">
|
||||
<div className="chat-header">
|
||||
<SessionManager
|
||||
activeSessionId={sessionId}
|
||||
onSessionChange={onSessionChange}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className={`header-btn ${documentFilter.length > 0 ? "has-content" : ""}`}
|
||||
|
|
@ -612,13 +548,25 @@ function ChatContentInner() {
|
|||
</button>
|
||||
</div>
|
||||
<div className="chat-content">
|
||||
<CopilotChat
|
||||
labels={{
|
||||
title: "haiku.rag Chat",
|
||||
initial:
|
||||
"Hello! I can help you search and answer questions from your knowledge base. Ask me anything!",
|
||||
<CopilotChatView
|
||||
messageView={MessageViewWithCitations}
|
||||
messages={messages}
|
||||
isRunning={agent.isRunning}
|
||||
inputProps={{
|
||||
onSubmitMessage,
|
||||
onStop,
|
||||
}}
|
||||
/>
|
||||
>
|
||||
{({ scrollView, feather, inputContainer }) => (
|
||||
<div className="chat-layout">
|
||||
<div ref={scrollAreaCallbackRef} className="chat-scroll-area">
|
||||
{scrollView}
|
||||
{feather}
|
||||
</div>
|
||||
<div className="chat-input-area">{inputContainer}</div>
|
||||
</div>
|
||||
)}
|
||||
</CopilotChatView>
|
||||
</div>
|
||||
<DbInfo />
|
||||
</div>
|
||||
|
|
@ -637,18 +585,34 @@ function ChatContentInner() {
|
|||
selected={documentFilter}
|
||||
onApply={handleFilterApply}
|
||||
/>
|
||||
</>
|
||||
</ChatStateContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatContent() {
|
||||
return <ChatContentInner />;
|
||||
}
|
||||
|
||||
export default function Chat() {
|
||||
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let id = getActiveSessionId();
|
||||
if (!id) {
|
||||
id = createSession().id;
|
||||
}
|
||||
setActiveSessionId(id);
|
||||
}, []);
|
||||
|
||||
if (!activeSessionId) return null;
|
||||
|
||||
return (
|
||||
<CopilotKit runtimeUrl="/api/copilotkit" agent="chat_agent">
|
||||
<ChatContent />
|
||||
</CopilotKit>
|
||||
<CopilotKitProvider
|
||||
key={activeSessionId}
|
||||
runtimeUrl="/api/copilotkit"
|
||||
useSingleEndpoint
|
||||
renderToolCalls={toolCallRenderers}
|
||||
>
|
||||
<ChatContentInner
|
||||
sessionId={activeSessionId}
|
||||
onSessionChange={setActiveSessionId}
|
||||
/>
|
||||
</CopilotKitProvider>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
interface Citation {
|
||||
index: number;
|
||||
document_id: string;
|
||||
chunk_id: string;
|
||||
document_uri: string;
|
||||
document_title: string | null;
|
||||
page_numbers: number[];
|
||||
headings: string[] | null;
|
||||
content: string;
|
||||
}
|
||||
import type { Citation } from "../lib/sessionStorage";
|
||||
|
||||
interface CitationBlockProps {
|
||||
citations: Citation[];
|
||||
|
|
@ -133,172 +123,6 @@ export default function CitationBlock({ citations }: CitationBlockProps) {
|
|||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
.citation-block {
|
||||
margin-top: 0.75rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.citation-block-header {
|
||||
background: #f8fafc;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-weight: 500;
|
||||
color: #475569;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
}
|
||||
.citation-item {
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
}
|
||||
.citation-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.citation-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.citation-header:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
.citation-index {
|
||||
font-weight: 600;
|
||||
color: #3b82f6;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.citation-title {
|
||||
flex: 1;
|
||||
color: #334155;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.citation-page {
|
||||
color: #94a3b8;
|
||||
font-size: 0.75rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.citation-chevron {
|
||||
color: #94a3b8;
|
||||
font-size: 0.625rem;
|
||||
flex-shrink: 0;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.citation-chevron.expanded {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
.citation-content {
|
||||
padding: 0.75rem;
|
||||
background: #fafafa;
|
||||
border-top: 1px solid #f1f5f9;
|
||||
}
|
||||
.citation-headings {
|
||||
font-size: 0.75rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 0.5rem;
|
||||
font-style: italic;
|
||||
}
|
||||
.citation-text {
|
||||
color: #475569;
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.citation-view-btn {
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.25rem 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.citation-view-btn:hover {
|
||||
background: #2563eb;
|
||||
}
|
||||
.visual-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.75);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
.visual-modal {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
}
|
||||
.visual-modal-close {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
background: #ef4444;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.visual-modal-close:hover {
|
||||
background: #dc2626;
|
||||
}
|
||||
.visual-modal-title {
|
||||
margin: 0 0 1rem 0;
|
||||
font-size: 1.125rem;
|
||||
color: #1e293b;
|
||||
}
|
||||
.visual-modal-loading {
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
color: #64748b;
|
||||
}
|
||||
.visual-modal-error {
|
||||
padding: 1rem;
|
||||
background: #fef2f2;
|
||||
color: #dc2626;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.visual-modal-images {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
.visual-modal-page-label {
|
||||
font-size: 0.75rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.visual-modal-image {
|
||||
max-width: 100%;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 4px;
|
||||
}
|
||||
`}</style>
|
||||
<div className="citation-block">
|
||||
<div className="citation-block-header">
|
||||
Sources ({citations.length})
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useId, useState } from "react";
|
||||
|
||||
interface SessionContext {
|
||||
summary: string;
|
||||
last_updated: string | null;
|
||||
}
|
||||
import { formatRelativeTime } from "../lib/format";
|
||||
import { BrainIcon } from "../lib/icons";
|
||||
import type { SessionContext } from "../lib/sessionStorage";
|
||||
|
||||
interface ContextPanelProps {
|
||||
isOpen: boolean;
|
||||
|
|
@ -16,51 +14,6 @@ interface ContextPanelProps {
|
|||
isLocked?: boolean;
|
||||
}
|
||||
|
||||
function formatRelativeTime(isoString: string): string {
|
||||
const date = new Date(isoString);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffSec = Math.floor(diffMs / 1000);
|
||||
const diffMin = Math.floor(diffSec / 60);
|
||||
const diffHour = Math.floor(diffMin / 60);
|
||||
|
||||
if (diffSec < 60) {
|
||||
return "just now";
|
||||
}
|
||||
if (diffMin < 60) {
|
||||
return `${diffMin} minute${diffMin === 1 ? "" : "s"} ago`;
|
||||
}
|
||||
if (diffHour < 24) {
|
||||
return `${diffHour} hour${diffHour === 1 ? "" : "s"} ago`;
|
||||
}
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
|
||||
function BrainIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z" />
|
||||
<path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z" />
|
||||
<path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4" />
|
||||
<path d="M17.599 6.5a3 3 0 0 0 .399-1.375" />
|
||||
<path d="M6.003 5.125A3 3 0 0 0 6.401 6.5" />
|
||||
<path d="M3.477 10.896a4 4 0 0 1 .585-.396" />
|
||||
<path d="M19.938 10.5a4 4 0 0 1 .585.396" />
|
||||
<path d="M6 18a4 4 0 0 1-1.967-.516" />
|
||||
<path d="M19.967 17.484A4 4 0 0 1 18 18" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ContextPanel({
|
||||
isOpen,
|
||||
onClose,
|
||||
|
|
@ -101,223 +54,78 @@ export default function ContextPanel({
|
|||
const isEditMode = !isLocked && !hasSessionContext;
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
.context-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
.context-modal {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
width: 90%;
|
||||
max-width: 600px;
|
||||
max-height: 80vh;
|
||||
overflow: auto;
|
||||
position: relative;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
.context-modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.context-modal-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
|
||||
color: #3b82f6;
|
||||
}
|
||||
.context-modal-title {
|
||||
margin: 0;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: #1e293b;
|
||||
}
|
||||
.context-modal-description {
|
||||
margin: 0 0 1rem 0;
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.context-content {
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.6;
|
||||
color: #334155;
|
||||
white-space: pre-wrap;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.context-textarea {
|
||||
width: 100%;
|
||||
min-height: 200px;
|
||||
padding: 1rem;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.6;
|
||||
color: #334155;
|
||||
background: white;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
resize: vertical;
|
||||
font-family: inherit;
|
||||
}
|
||||
.context-textarea:focus {
|
||||
outline: none;
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
.context-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem 1rem;
|
||||
text-align: center;
|
||||
color: #94a3b8;
|
||||
}
|
||||
.context-empty-icon {
|
||||
margin-bottom: 0.75rem;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.context-empty-text {
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.context-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
}
|
||||
.context-timestamp {
|
||||
font-size: 0.75rem;
|
||||
color: #94a3b8;
|
||||
}
|
||||
.context-btn {
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.context-btn-close {
|
||||
background: white;
|
||||
color: #475569;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
.context-btn-close:hover {
|
||||
background: #f8fafc;
|
||||
border-color: #cbd5e1;
|
||||
}
|
||||
.context-btn-save {
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
border: 1px solid #3b82f6;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
.context-btn-save:hover {
|
||||
background: #2563eb;
|
||||
border-color: #2563eb;
|
||||
}
|
||||
.context-footer-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
`}</style>
|
||||
<div
|
||||
className="context-modal-overlay"
|
||||
onClick={onClose}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
>
|
||||
{/* biome-ignore lint/a11y/noStaticElementInteractions: modal content wrapper */}
|
||||
<div
|
||||
className="context-modal-overlay"
|
||||
onClick={onClose}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
className="context-modal"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* biome-ignore lint/a11y/noStaticElementInteractions: modal content wrapper */}
|
||||
<div
|
||||
className="context-modal"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="context-modal-header">
|
||||
<div className="context-modal-icon">
|
||||
<BrainIcon />
|
||||
</div>
|
||||
<h2 id={titleId} className="context-modal-title">
|
||||
{isEditMode ? "Initial Context" : "Session Context"}
|
||||
</h2>
|
||||
<div className="context-modal-header">
|
||||
<div className="context-modal-icon">
|
||||
<BrainIcon size={24} strokeWidth={1.5} />
|
||||
</div>
|
||||
<p className="context-modal-description">
|
||||
{isEditMode
|
||||
? "Set background context to guide the conversation. This will be locked after you send your first message."
|
||||
: "This is what the assistant has learned from your conversation so far. It uses this context to provide more relevant answers."}
|
||||
</p>
|
||||
{isEditMode ? (
|
||||
<textarea
|
||||
className="context-textarea"
|
||||
placeholder="Enter any background context or instructions for the assistant..."
|
||||
value={localValue}
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
/>
|
||||
) : hasSessionContext ? (
|
||||
<div className="context-content">{sessionContext.summary}</div>
|
||||
) : (
|
||||
<div className="context-empty">
|
||||
<div className="context-empty-icon">
|
||||
<BrainIcon />
|
||||
</div>
|
||||
<div className="context-empty-text">
|
||||
No context yet. Ask some questions to build context.
|
||||
</div>
|
||||
<h2 id={titleId} className="context-modal-title">
|
||||
{isEditMode ? "Initial Context" : "Session Context"}
|
||||
</h2>
|
||||
</div>
|
||||
<p className="context-modal-description">
|
||||
{isEditMode
|
||||
? "Set background context to guide the conversation. This will be locked after you send your first message."
|
||||
: "This is what the assistant has learned from your conversation so far. It uses this context to provide more relevant answers."}
|
||||
</p>
|
||||
{isEditMode ? (
|
||||
<textarea
|
||||
className="context-textarea"
|
||||
placeholder="Enter any background context or instructions for the assistant..."
|
||||
value={localValue}
|
||||
onChange={(e) => setLocalValue(e.target.value)}
|
||||
/>
|
||||
) : hasSessionContext ? (
|
||||
<div className="context-content">{sessionContext.summary}</div>
|
||||
) : (
|
||||
<div className="context-empty">
|
||||
<div className="context-empty-icon">
|
||||
<BrainIcon size={24} strokeWidth={1.5} />
|
||||
</div>
|
||||
)}
|
||||
<div className="context-footer">
|
||||
<span className="context-timestamp">
|
||||
{sessionContext?.last_updated
|
||||
? `Last updated: ${formatRelativeTime(sessionContext.last_updated)}`
|
||||
: ""}
|
||||
</span>
|
||||
<div className="context-footer-buttons">
|
||||
<div className="context-empty-text">
|
||||
No context yet. Ask some questions to build context.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="context-footer">
|
||||
<span className="context-timestamp">
|
||||
{sessionContext?.last_updated
|
||||
? `Last updated: ${formatRelativeTime(sessionContext.last_updated)}`
|
||||
: ""}
|
||||
</span>
|
||||
<div className="context-footer-buttons">
|
||||
<button
|
||||
type="button"
|
||||
className="context-btn context-btn-close"
|
||||
onClick={onClose}
|
||||
>
|
||||
{isEditMode ? "Cancel" : "Close"}
|
||||
</button>
|
||||
{isEditMode && (
|
||||
<button
|
||||
type="button"
|
||||
className="context-btn context-btn-close"
|
||||
onClick={onClose}
|
||||
className="context-btn context-btn-save"
|
||||
onClick={handleSave}
|
||||
>
|
||||
{isEditMode ? "Cancel" : "Close"}
|
||||
Save
|
||||
</button>
|
||||
{isEditMode && (
|
||||
<button
|
||||
type="button"
|
||||
className="context-btn context-btn-save"
|
||||
onClick={handleSave}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,79 +57,28 @@ export default function DbInfo() {
|
|||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
.db-info {
|
||||
display: flex;
|
||||
gap: 1.5rem;
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.75rem;
|
||||
color: #64748b;
|
||||
background: #f8fafc;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
justify-content: center;
|
||||
}
|
||||
.db-info-error {
|
||||
color: #dc2626;
|
||||
background: #fef2f2;
|
||||
}
|
||||
.db-info-loading {
|
||||
color: #64748b;
|
||||
}
|
||||
.db-info-empty {
|
||||
color: #f59e0b;
|
||||
background: #fffbeb;
|
||||
}
|
||||
.db-stat {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
.db-stat-value {
|
||||
font-weight: 600;
|
||||
color: #334155;
|
||||
}
|
||||
.db-stat-label {
|
||||
color: #94a3b8;
|
||||
}
|
||||
.db-index-badge {
|
||||
padding: 0.125rem 0.375rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.625rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.db-index-badge.indexed {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
.db-index-badge.not-indexed {
|
||||
background: #fef3c7;
|
||||
color: #92400e;
|
||||
}
|
||||
`}</style>
|
||||
<div className="db-info">
|
||||
<div className="db-stat">
|
||||
<span className="db-stat-value">{info.documents}</span>
|
||||
<span className="db-stat-label">documents</span>
|
||||
</div>
|
||||
<div className="db-stat">
|
||||
<span className="db-stat-value">{info.chunks}</span>
|
||||
<span className="db-stat-label">chunks</span>
|
||||
</div>
|
||||
<div className="db-stat">
|
||||
<span className="db-stat-value">
|
||||
{formatBytes(info.documents_bytes + info.chunks_bytes)}
|
||||
</span>
|
||||
<span className="db-stat-label">total</span>
|
||||
</div>
|
||||
<div className="db-stat">
|
||||
<span
|
||||
className={`db-index-badge ${info.has_vector_index ? "indexed" : "not-indexed"}`}
|
||||
>
|
||||
{info.has_vector_index ? "indexed" : "no index"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="db-info">
|
||||
<div className="db-stat">
|
||||
<span className="db-stat-value">{info.documents}</span>
|
||||
<span className="db-stat-label">documents</span>
|
||||
</div>
|
||||
</>
|
||||
<div className="db-stat">
|
||||
<span className="db-stat-value">{info.chunks}</span>
|
||||
<span className="db-stat-label">chunks</span>
|
||||
</div>
|
||||
<div className="db-stat">
|
||||
<span className="db-stat-value">
|
||||
{formatBytes(info.documents_bytes + info.chunks_bytes)}
|
||||
</span>
|
||||
<span className="db-stat-label">total</span>
|
||||
</div>
|
||||
<div className="db-stat">
|
||||
<span
|
||||
className={`db-index-badge ${info.has_vector_index ? "indexed" : "not-indexed"}`}
|
||||
>
|
||||
{info.has_vector_index ? "indexed" : "no index"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useId, useState } from "react";
|
||||
import { FilterIcon } from "../lib/icons";
|
||||
|
||||
interface Document {
|
||||
id: string;
|
||||
|
|
@ -15,23 +16,6 @@ interface DocumentFilterProps {
|
|||
onApply: (selected: string[]) => void;
|
||||
}
|
||||
|
||||
function FilterIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DocumentFilter({
|
||||
isOpen,
|
||||
onClose,
|
||||
|
|
@ -113,269 +97,98 @@ export default function DocumentFilter({
|
|||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`
|
||||
.filter-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
.filter-modal {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
padding: 1.5rem;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
|
||||
}
|
||||
.filter-modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.filter-modal-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 10px;
|
||||
background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
|
||||
color: #d97706;
|
||||
}
|
||||
.filter-modal-title {
|
||||
margin: 0;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: #1e293b;
|
||||
}
|
||||
.filter-modal-description {
|
||||
margin: 0 0 1rem 0;
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.filter-search {
|
||||
width: 100%;
|
||||
padding: 0.625rem 0.875rem;
|
||||
font-size: 0.875rem;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 0.75rem;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
.filter-search:focus {
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
.filter-list {
|
||||
flex: 1;
|
||||
min-height: 200px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.filter-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.625rem 0.875rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
}
|
||||
.filter-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.filter-item:hover {
|
||||
background: #f1f5f9;
|
||||
}
|
||||
.filter-item input[type="checkbox"] {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
cursor: pointer;
|
||||
accent-color: #3b82f6;
|
||||
}
|
||||
.filter-item-label {
|
||||
flex: 1;
|
||||
font-size: 0.875rem;
|
||||
color: #334155;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.filter-loading, .filter-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100px;
|
||||
color: #94a3b8;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
.filter-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-top: 1rem;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
}
|
||||
.filter-count {
|
||||
font-size: 0.75rem;
|
||||
color: #64748b;
|
||||
}
|
||||
.filter-count strong {
|
||||
color: #3b82f6;
|
||||
}
|
||||
.filter-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.filter-btn {
|
||||
padding: 0.5rem 1rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.filter-btn-secondary {
|
||||
background: white;
|
||||
color: #475569;
|
||||
border: 1px solid #e2e8f0;
|
||||
}
|
||||
.filter-btn-secondary:hover {
|
||||
background: #f8fafc;
|
||||
border-color: #cbd5e1;
|
||||
}
|
||||
.filter-btn-primary {
|
||||
background: #3b82f6;
|
||||
color: white;
|
||||
border: 1px solid #3b82f6;
|
||||
}
|
||||
.filter-btn-primary:hover {
|
||||
background: #2563eb;
|
||||
border-color: #2563eb;
|
||||
}
|
||||
.filter-btn-clear {
|
||||
background: transparent;
|
||||
color: #ef4444;
|
||||
border: none;
|
||||
padding: 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.filter-btn-clear:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
`}</style>
|
||||
<div
|
||||
className="filter-modal-overlay"
|
||||
onClick={onClose}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
>
|
||||
{/* biome-ignore lint/a11y/noStaticElementInteractions: modal content wrapper */}
|
||||
<div
|
||||
className="filter-modal-overlay"
|
||||
onClick={onClose}
|
||||
onKeyDown={handleKeyDown}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={titleId}
|
||||
className="filter-modal"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* biome-ignore lint/a11y/noStaticElementInteractions: modal content wrapper */}
|
||||
<div
|
||||
className="filter-modal"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="filter-modal-header">
|
||||
<div className="filter-modal-icon">
|
||||
<FilterIcon />
|
||||
</div>
|
||||
<h2 id={titleId} className="filter-modal-title">
|
||||
Filter Documents
|
||||
</h2>
|
||||
<div className="filter-modal-header">
|
||||
<div className="filter-modal-icon">
|
||||
<FilterIcon size={24} strokeWidth={1.5} />
|
||||
</div>
|
||||
<p className="filter-modal-description">
|
||||
Select documents to restrict searches. When active, only selected
|
||||
documents will be searched.
|
||||
</p>
|
||||
<input
|
||||
type="text"
|
||||
className="filter-search"
|
||||
placeholder="Search documents..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
<div className="filter-list">
|
||||
{loading ? (
|
||||
<div className="filter-loading">Loading documents...</div>
|
||||
) : filteredDocuments.length === 0 ? (
|
||||
<div className="filter-empty">
|
||||
{searchTerm ? "No matching documents" : "No documents found"}
|
||||
</div>
|
||||
<h2 id={titleId} className="filter-modal-title">
|
||||
Filter Documents
|
||||
</h2>
|
||||
</div>
|
||||
<p className="filter-modal-description">
|
||||
Select documents to restrict searches. When active, only selected
|
||||
documents will be searched.
|
||||
</p>
|
||||
<input
|
||||
type="text"
|
||||
className="filter-search"
|
||||
placeholder="Search documents..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
<div className="filter-list">
|
||||
{loading ? (
|
||||
<div className="filter-loading">Loading documents...</div>
|
||||
) : filteredDocuments.length === 0 ? (
|
||||
<div className="filter-empty">
|
||||
{searchTerm ? "No matching documents" : "No documents found"}
|
||||
</div>
|
||||
) : (
|
||||
filteredDocuments.map((doc) => {
|
||||
const displayName = getDisplayName(doc);
|
||||
return (
|
||||
<label key={doc.id} className="filter-item">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={localSelected.has(displayName)}
|
||||
onChange={() => toggleDocument(displayName)}
|
||||
/>
|
||||
<span className="filter-item-label">{displayName}</span>
|
||||
</label>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
<div className="filter-footer">
|
||||
<div className="filter-count">
|
||||
{localSelected.size > 0 ? (
|
||||
<>
|
||||
<strong>{localSelected.size}</strong> document
|
||||
{localSelected.size === 1 ? "" : "s"} selected
|
||||
<button
|
||||
type="button"
|
||||
className="filter-btn filter-btn-clear"
|
||||
onClick={handleClearAll}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
filteredDocuments.map((doc) => {
|
||||
const displayName = getDisplayName(doc);
|
||||
return (
|
||||
<label key={doc.id} className="filter-item">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={localSelected.has(displayName)}
|
||||
onChange={() => toggleDocument(displayName)}
|
||||
/>
|
||||
<span className="filter-item-label">{displayName}</span>
|
||||
</label>
|
||||
);
|
||||
})
|
||||
"No filter (all documents)"
|
||||
)}
|
||||
</div>
|
||||
<div className="filter-footer">
|
||||
<div className="filter-count">
|
||||
{localSelected.size > 0 ? (
|
||||
<>
|
||||
<strong>{localSelected.size}</strong> document
|
||||
{localSelected.size === 1 ? "" : "s"} selected
|
||||
<button
|
||||
type="button"
|
||||
className="filter-btn filter-btn-clear"
|
||||
onClick={handleClearAll}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
"No filter (all documents)"
|
||||
)}
|
||||
</div>
|
||||
<div className="filter-buttons">
|
||||
<button
|
||||
type="button"
|
||||
className="filter-btn filter-btn-secondary"
|
||||
onClick={onClose}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="filter-btn filter-btn-primary"
|
||||
onClick={handleApply}
|
||||
>
|
||||
Apply
|
||||
</button>
|
||||
</div>
|
||||
<div className="filter-buttons">
|
||||
<button
|
||||
type="button"
|
||||
className="filter-btn filter-btn-secondary"
|
||||
onClick={onClose}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="filter-btn filter-btn-primary"
|
||||
onClick={handleApply}
|
||||
>
|
||||
Apply
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
268
app/frontend/components/SessionManager.tsx
Normal file
268
app/frontend/components/SessionManager.tsx
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { formatRelativeTime } from "../lib/format";
|
||||
import {
|
||||
createSession,
|
||||
deleteSession,
|
||||
exportSessionToMarkdown,
|
||||
getAllSessions,
|
||||
type StoredSession,
|
||||
setActiveSessionId,
|
||||
} from "../lib/sessionStorage";
|
||||
|
||||
interface SessionManagerProps {
|
||||
activeSessionId: string | null;
|
||||
onSessionChange: (sessionId: string) => void;
|
||||
}
|
||||
|
||||
function HistoryIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
|
||||
<path d="M3 3v5h5" />
|
||||
<path d="M12 7v5l4 2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function PlusIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2.5"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 5v14" />
|
||||
<path d="M5 12h14" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="7 10 12 15 17 10" />
|
||||
<line x1="12" y1="15" x2="12" y2="3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function TrashIcon() {
|
||||
return (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M3 6h18" />
|
||||
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
|
||||
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SessionManager({
|
||||
activeSessionId,
|
||||
onSessionChange,
|
||||
}: SessionManagerProps) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [sessions, setSessions] = useState<StoredSession[]>([]);
|
||||
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) setSessions(getAllSessions());
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (
|
||||
dropdownRef.current &&
|
||||
!dropdownRef.current.contains(e.target as Node)
|
||||
) {
|
||||
setIsOpen(false);
|
||||
setConfirmDelete(null);
|
||||
}
|
||||
}
|
||||
if (isOpen) document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [isOpen]);
|
||||
|
||||
const handleNewSession = () => {
|
||||
const session = createSession();
|
||||
setSessions(getAllSessions());
|
||||
setIsOpen(false);
|
||||
onSessionChange(session.id);
|
||||
};
|
||||
|
||||
const handleSelectSession = (id: string) => {
|
||||
setActiveSessionId(id);
|
||||
setIsOpen(false);
|
||||
onSessionChange(id);
|
||||
};
|
||||
|
||||
const handleDelete = (id: string) => {
|
||||
deleteSession(id);
|
||||
const remaining = getAllSessions();
|
||||
setSessions(remaining);
|
||||
setConfirmDelete(null);
|
||||
if (id === activeSessionId) {
|
||||
if (remaining.length > 0) {
|
||||
setActiveSessionId(remaining[0].id);
|
||||
onSessionChange(remaining[0].id);
|
||||
} else {
|
||||
const session = createSession();
|
||||
setSessions(getAllSessions());
|
||||
onSessionChange(session.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = (session: StoredSession) => {
|
||||
exportSessionToMarkdown(session);
|
||||
};
|
||||
|
||||
const activeTitle =
|
||||
sessions.find((s) => s.id === activeSessionId)?.title ?? "Sessions";
|
||||
|
||||
return (
|
||||
<div ref={dropdownRef} style={{ position: "relative" }}>
|
||||
<button
|
||||
type="button"
|
||||
className="header-btn"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
title="Session history"
|
||||
>
|
||||
<HistoryIcon />
|
||||
<span
|
||||
style={{
|
||||
maxWidth: 120,
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{activeTitle}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="session-dropdown">
|
||||
<div className="session-dropdown-header">
|
||||
<span>Sessions</span>
|
||||
<button
|
||||
type="button"
|
||||
className="new-session-btn"
|
||||
onClick={handleNewSession}
|
||||
>
|
||||
<PlusIcon />
|
||||
New
|
||||
</button>
|
||||
</div>
|
||||
<div className="session-list">
|
||||
{sessions.length === 0 && (
|
||||
<div
|
||||
style={{
|
||||
padding: "16px",
|
||||
textAlign: "center",
|
||||
color: "#94a3b8",
|
||||
fontSize: "13px",
|
||||
}}
|
||||
>
|
||||
No sessions yet
|
||||
</div>
|
||||
)}
|
||||
{sessions.map((session) => (
|
||||
<div
|
||||
key={session.id}
|
||||
className={`session-item ${session.id === activeSessionId ? "active" : ""}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="session-item-content"
|
||||
onClick={() => handleSelectSession(session.id)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") handleSelectSession(session.id);
|
||||
}}
|
||||
>
|
||||
<div className="session-item-title">{session.title}</div>
|
||||
<div className="session-item-meta">
|
||||
<span>{session.messages.length} messages</span>
|
||||
<span>{formatRelativeTime(session.updatedAt, true)}</span>
|
||||
</div>
|
||||
</button>
|
||||
{confirmDelete === session.id ? (
|
||||
<div className="confirm-delete">
|
||||
<button
|
||||
type="button"
|
||||
className="confirm-yes"
|
||||
onClick={() => handleDelete(session.id)}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="confirm-no"
|
||||
onClick={() => setConfirmDelete(null)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="session-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="session-action-btn"
|
||||
onClick={() => handleExport(session)}
|
||||
title="Export to markdown"
|
||||
>
|
||||
<DownloadIcon />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="session-action-btn danger"
|
||||
onClick={() => setConfirmDelete(session.id)}
|
||||
title="Delete session"
|
||||
>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
app/frontend/lib/format.ts
Normal file
18
app/frontend/lib/format.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
export function formatRelativeTime(dateStr: string, compact = false): string {
|
||||
const now = Date.now();
|
||||
const then = new Date(dateStr).getTime();
|
||||
const seconds = Math.floor((now - then) / 1000);
|
||||
if (seconds < 60) return "just now";
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60)
|
||||
return compact
|
||||
? `${minutes}m ago`
|
||||
: `${minutes} minute${minutes === 1 ? "" : "s"} ago`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24)
|
||||
return compact
|
||||
? `${hours}h ago`
|
||||
: `${hours} hour${hours === 1 ? "" : "s"} ago`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return compact ? `${days}d ago` : new Date(dateStr).toLocaleDateString();
|
||||
}
|
||||
46
app/frontend/lib/icons.tsx
Normal file
46
app/frontend/lib/icons.tsx
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
interface IconProps {
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
}
|
||||
|
||||
export function BrainIcon({ size = 18, strokeWidth = 2 }: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z" />
|
||||
<path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z" />
|
||||
<path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4" />
|
||||
<path d="M17.599 6.5a3 3 0 0 0 .399-1.375" />
|
||||
<path d="M6.003 5.125A3 3 0 0 0 6.401 6.5" />
|
||||
<path d="M3.477 10.896a4 4 0 0 1 .585-.396" />
|
||||
<path d="M19.938 10.5a4 4 0 0 1 .585.396" />
|
||||
<path d="M6 18a4 4 0 0 1-1.967-.516" />
|
||||
<path d="M19.967 17.484A4 4 0 0 1 18 18" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function FilterIcon({ size = 18, strokeWidth = 2 }: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
172
app/frontend/lib/sessionStorage.ts
Normal file
172
app/frontend/lib/sessionStorage.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
export interface Citation {
|
||||
index: number;
|
||||
document_id: string;
|
||||
chunk_id: string;
|
||||
document_uri: string;
|
||||
document_title: string | null;
|
||||
page_numbers: number[];
|
||||
headings: string[] | null;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface QAResponse {
|
||||
question: string;
|
||||
answer: string;
|
||||
confidence: number;
|
||||
citations: Citation[];
|
||||
}
|
||||
|
||||
export interface SessionContext {
|
||||
summary: string;
|
||||
last_updated: string | null;
|
||||
}
|
||||
|
||||
export interface ChatSessionState {
|
||||
initial_context: string | null;
|
||||
citations: Citation[];
|
||||
qa_history: QAResponse[];
|
||||
session_context: SessionContext | null;
|
||||
document_filter: string[];
|
||||
citation_registry: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface StoredMessage {
|
||||
id: string;
|
||||
role?: string;
|
||||
content?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface StoredSession {
|
||||
id: string;
|
||||
title: string;
|
||||
messages: StoredMessage[];
|
||||
chatState: ChatSessionState;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
const SESSIONS_KEY = "haiku.rag.sessions";
|
||||
const ACTIVE_SESSION_KEY = "haiku.rag.activeSession";
|
||||
|
||||
export function normalizeChatState(state?: ChatSessionState): ChatSessionState {
|
||||
return {
|
||||
initial_context: state?.initial_context ?? null,
|
||||
citations: state?.citations ?? [],
|
||||
qa_history: state?.qa_history ?? [],
|
||||
session_context: state?.session_context ?? null,
|
||||
document_filter: state?.document_filter ?? [],
|
||||
citation_registry: state?.citation_registry ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
export function getAllSessions(): StoredSession[] {
|
||||
const raw = localStorage.getItem(SESSIONS_KEY);
|
||||
if (!raw) return [];
|
||||
try {
|
||||
return JSON.parse(raw) as StoredSession[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getSession(id: string): StoredSession | null {
|
||||
return getAllSessions().find((s) => s.id === id) ?? null;
|
||||
}
|
||||
|
||||
export function getActiveSessionId(): string | null {
|
||||
return localStorage.getItem(ACTIVE_SESSION_KEY);
|
||||
}
|
||||
|
||||
export function setActiveSessionId(id: string): void {
|
||||
localStorage.setItem(ACTIVE_SESSION_KEY, id);
|
||||
}
|
||||
|
||||
export function createSession(): StoredSession {
|
||||
const now = new Date().toISOString();
|
||||
const session: StoredSession = {
|
||||
id: crypto.randomUUID(),
|
||||
title: "New Session",
|
||||
messages: [],
|
||||
chatState: normalizeChatState(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const sessions = getAllSessions();
|
||||
sessions.unshift(session);
|
||||
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
||||
setActiveSessionId(session.id);
|
||||
return session;
|
||||
}
|
||||
|
||||
export function saveSession(session: StoredSession): void {
|
||||
const sessions = getAllSessions();
|
||||
const idx = sessions.findIndex((s) => s.id === session.id);
|
||||
if (idx >= 0) {
|
||||
sessions[idx] = session;
|
||||
} else {
|
||||
sessions.unshift(session);
|
||||
}
|
||||
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
||||
}
|
||||
|
||||
export function updateSessionMessages(
|
||||
id: string,
|
||||
messages: StoredMessage[],
|
||||
chatState: ChatSessionState,
|
||||
): void {
|
||||
const sessions = getAllSessions();
|
||||
const idx = sessions.findIndex((s) => s.id === id);
|
||||
if (idx < 0) return;
|
||||
|
||||
const session = sessions[idx];
|
||||
session.messages = messages;
|
||||
session.chatState = chatState;
|
||||
session.updatedAt = new Date().toISOString();
|
||||
|
||||
// Derive title from first user message
|
||||
if (session.title === "New Session") {
|
||||
const firstUserMsg = messages.find(
|
||||
(m) =>
|
||||
m.content &&
|
||||
typeof m.role === "string" &&
|
||||
m.role.toLowerCase() === "user",
|
||||
);
|
||||
if (firstUserMsg?.content) {
|
||||
session.title =
|
||||
firstUserMsg.content.length > 60
|
||||
? `${firstUserMsg.content.slice(0, 57)}...`
|
||||
: firstUserMsg.content;
|
||||
}
|
||||
}
|
||||
|
||||
sessions[idx] = session;
|
||||
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
||||
}
|
||||
|
||||
export function deleteSession(id: string): void {
|
||||
const sessions = getAllSessions().filter((s) => s.id !== id);
|
||||
localStorage.setItem(SESSIONS_KEY, JSON.stringify(sessions));
|
||||
if (getActiveSessionId() === id) {
|
||||
localStorage.removeItem(ACTIVE_SESSION_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
export function exportSessionToMarkdown(session: StoredSession): void {
|
||||
const lines: string[] = [`# ${session.title}`, ""];
|
||||
for (const msg of session.messages) {
|
||||
const role = typeof msg.role === "string" ? msg.role.toLowerCase() : "";
|
||||
if (role === "user" && msg.content) {
|
||||
lines.push(`**User:** ${msg.content}`, "");
|
||||
} else if (role === "assistant" && msg.content) {
|
||||
lines.push(`**Assistant:** ${msg.content}`, "");
|
||||
}
|
||||
}
|
||||
const blob = new Blob([lines.join("\n")], { type: "text/markdown" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${session.title.replace(/[^a-zA-Z0-9]/g, "_")}.md`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
|
@ -7,14 +7,13 @@
|
|||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"check": "biome check app components",
|
||||
"format": "biome check --write app components"
|
||||
"check": "biome check app components lib",
|
||||
"format": "biome check --write app components lib"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ag-ui/client": "^0.0.42",
|
||||
"@copilotkit/react-core": "^1.50.0",
|
||||
"@copilotkit/react-ui": "^1.50.0",
|
||||
"@copilotkit/runtime": "^1.50.0",
|
||||
"@copilotkit/react-core": "^1.51.3",
|
||||
"@copilotkit/runtime": "^1.51.3",
|
||||
"next": "^16.1.1",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0"
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue