Files
Sybil-2/web/src/pages/lite-route-page.tsx
T

268 lines
17 KiB
TypeScript

import type { ComponentType } from "preact";
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
import { Bot, LogOut, Menu, MessageSquare, Plus, RefreshCw, Search, SendHorizontal, Settings2, Star, X } from "lucide-preact";
import { AssistantMessageFooter } from "@/components/chat/assistant-message-footer";
import { MarkdownContent } from "@/components/markdown/markdown-content";
import { useSessionAuth } from "@/hooks/use-session-auth";
import { useLiteWorkspace } from "@/hooks/use-lite-workspace";
import { useWorkspaceSearch } from "@/hooks/use-workspace-search";
import { getMessageAttachments, type Message, type SearchDetail, type WorkspaceItem } from "@/lib/api";
import { getProviderLabel } from "@/lib/message-generation";
import { buildUiModeUrl } from "@/lib/ui-mode";
import "./lite.css";
const PAGE_SIZE = 30;
function LiteAgentPanel() {
const [Agent, setAgent] = useState<ComponentType | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let active = true;
setFailed(false);
void import("@/components/lite/lite-agent").then(module => {
if (active) setAgent(() => module.LiteAgent);
}, () => { if (active) setFailed(true); });
return () => { active = false; };
}, []);
if (failed) return <div className="lite-error" role="alert"><p>Agent could not load. Check your connection and reload this page.</p><button onClick={() => window.location.reload()}>Reload</button></div>;
return Agent ? <Agent /> : <p role="status">Opening Agent…</p>;
}
function itemTitle(item: WorkspaceItem) {
return item.title?.trim() || (item.type === "search" ? item.query : null) || (item.type === "chat" ? "New chat" : "New search");
}
function formatDate(value: string) {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? "" : date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
function webLink(value: string | undefined) {
return value && /^https?:\/\//i.test(value) ? value : undefined;
}
function LiteMessage({ message }: { message: Message }) {
const attachments = getMessageAttachments(message.metadata);
if (message.role === "system") return null;
if (message.role === "tool") return (
<details className="lite-tool">
<summary>{message.name || "Tool activity"}</summary>
<pre>{message.content}</pre>
</details>
);
return (
<article className={`lite-message${message.role === "user" ? " lite-message-user" : ""}`} aria-label={message.role === "user" ? "Your message" : "Assistant message"}>
<div className={`lite-message-content${message.role === "user" ? " message-bubble message-bubble--user" : ""}`}>
{attachments.length > 0 && <ul className="lite-attachments" aria-label="Attachments">
{attachments.map(file => <li key={file.id}>{file.filename}</li>)}
</ul>}
<MarkdownContent markdown={message.content} allowImages={false} openLinksInNewTab />
{message.role === "assistant" && <AssistantMessageFooter message={message} />}
</div>
</article>
);
}
function LiteTranscript({ messages }: { messages: Message[] }) {
const [count, setCount] = useState(PAGE_SIZE);
const visible = messages.filter(message => message.role !== "system");
return (
<section className="lite-transcript" aria-label="Conversation">
{visible.length > count && <button type="button" onClick={() => setCount(value => value + PAGE_SIZE)}>Show earlier messages ({visible.length - count})</button>}
{visible.slice(-count).map(message => <LiteMessage key={message.id} message={message} />)}
</section>
);
}
function LiteSearch({ search }: { search: SearchDetail }) {
return (
<section className="lite-search-results" aria-label="Web search results">
{search.error && <p className="lite-error" role="alert">{search.error}</p>}
{search.answerError && <p className="lite-error" role="alert">{search.answerError}</p>}
{search.answerText && <article className="lite-search-answer"><h2>Answer</h2><MarkdownContent markdown={search.answerText} allowImages={false} /></article>}
{!!search.answerCitations?.length && <details className="lite-tool"><summary>Answer sources</summary><ul>
{search.answerCitations.map((citation, index) => <li key={index}><a href={webLink(citation.url)}>{citation.title || citation.url || `Source ${index + 1}`}</a></li>)}
</ul></details>}
<ol className="lite-result-list">
{search.results.map(result => <li key={result.id}>
<h2><a href={webLink(result.url)}>{result.title || result.url}</a></h2>
<p className="lite-result-url">{result.url}</p>
{(result.highlights?.length || result.text) && <p>{(result.highlights?.join(" ") || result.text || "").slice(0, 600)}</p>}
</li>)}
</ol>
{!search.results.length && !search.answerText && !search.error && <p>No results saved for this search.</p>}
</section>
);
}
export default function LiteRoutePage() {
const auth = useSessionAuth({ backgroundSession: false });
const workspace = useLiteWorkspace(auth.isAuthenticated, auth.handleAuthFailure);
const [sidebarOpen, setSidebarOpen] = useState(false);
const [historyQuery, setHistoryQuery] = useState("");
const [historyCount, setHistoryCount] = useState(PAGE_SIZE);
const [draft, setDraft] = useState(() => new URLSearchParams(window.location.search).get("q") || "");
const [submitted, setSubmitted] = useState("");
const submitLock = useRef(false);
const transcriptRef = useRef<HTMLDivElement>(null);
const followTranscript = useRef(true);
const historySearch = useWorkspaceSearch(historyQuery, auth.isAuthenticated, workspace.items.length);
const historyItems = historyQuery.trim() ? historySearch.items : workspace.items;
const isAgent = workspace.selection?.kind === "agent";
const isSearch = workspace.selection?.kind === "search" || (!workspace.selection && workspace.draftKind === "search");
const title = isAgent ? "Sybil Agent" : isSearch ? workspace.search?.title || "New search" : workspace.chat?.title || "New chat";
const selectedKey = workspace.selection ? `${workspace.selection.kind}:${workspace.selection.id}` : workspace.draftKind;
const priorSelection = useRef(selectedKey);
const lastMessageId = workspace.chat?.messages[workspace.chat.messages.length - 1]?.id;
useEffect(() => {
document.title = `${title} · Sybil Lite`;
}, [title]);
useLayoutEffect(() => {
if (priorSelection.current !== selectedKey && (!submitLock.current || !workspace.isSending)) {
setDraft("");
setSubmitted("");
}
priorSelection.current = selectedKey;
}, [selectedKey, workspace.isSending]);
useEffect(() => { setHistoryCount(PAGE_SIZE); }, [historyQuery]);
useLayoutEffect(() => { followTranscript.current = true; }, [selectedKey]);
useLayoutEffect(() => {
const transcript = transcriptRef.current;
if (transcript && followTranscript.current) transcript.scrollTop = isSearch ? 0 : transcript.scrollHeight;
}, [selectedKey, lastMessageId, submitted, workspace.isBusy]);
useEffect(() => {
if (!sidebarOpen) return;
const close = (event: KeyboardEvent) => { if (event.key === "Escape") setSidebarOpen(false); };
window.addEventListener("keydown", close);
return () => window.removeEventListener("keydown", close);
}, [sidebarOpen]);
const send = async (event: Event) => {
event.preventDefault();
const text = draft.trim();
if (!text || workspace.isBusy || submitLock.current) return;
submitLock.current = true;
followTranscript.current = true;
setSubmitted(text);
try {
if (await workspace.send(text)) setDraft("");
} finally {
setSubmitted("");
submitLock.current = false;
}
};
const fullLink = <a href={buildUiModeUrl("full", window.location)}>Full interface</a>;
const brand = <a className="lite-brand sybil-wordmark" href="/lite?ui=lite" aria-label="Sybil home">SYBIL</a>;
if (auth.isCheckingSession) return <div className="lite-auth">{brand}<p role="status">Checking session…</p></div>;
if (!auth.isAuthenticated) return (
<main className="lite-auth">
{brand}
<h1>Sign in to Sybil</h1>
<p>Enter your admin token.</p>
<form onSubmit={event => { event.preventDefault(); if (auth.authTokenInput.trim()) void auth.handleSignIn(auth.authTokenInput.trim()); }}>
<label htmlFor="lite-token">Admin token</label>
<input id="lite-token" type="password" autoComplete="off" required value={auth.authTokenInput}
onInput={event => auth.setAuthTokenInput(event.currentTarget.value)} disabled={auth.isSigningIn} />
<button className="lite-primary" disabled={auth.isSigningIn || !auth.authTokenInput.trim()}>{auth.isSigningIn ? "Signing in…" : "Sign in"}</button>
</form>
{auth.authError && <p className="lite-error" role="alert">{auth.authError}</p>}
{fullLink}
</main>
);
return (
<div className="lite-shell">
<a className="lite-skip" href="#lite-main">Skip to conversation</a>
{sidebarOpen && <button type="button" className="lite-sidebar-backdrop" aria-label="Close sidebar" onClick={() => setSidebarOpen(false)} />}
<aside id="lite-sidebar" className={`lite-sidebar${sidebarOpen ? " is-open" : ""}`} aria-label="Workspace">
<header className="lite-sidebar-header">
{brand}
<button type="button" className="lite-icon-button lite-sidebar-close" aria-label="Close sidebar" onClick={() => setSidebarOpen(false)}><X aria-hidden="true" /></button>
</header>
<nav className="lite-workspace-actions" aria-label="Workspace actions">
<button className="lite-primary" type="button" onClick={() => { workspace.newChat(); setDraft(""); setSidebarOpen(false); }} disabled={workspace.isSending}><Plus aria-hidden="true" />New chat</button>
<button type="button" onClick={() => { workspace.newSearch(); setDraft(""); setSidebarOpen(false); }} disabled={workspace.isSending}><Search aria-hidden="true" />New search</button>
<button className="lite-agent-button" type="button" aria-current={isAgent ? "page" : undefined} onClick={() => { workspace.selectItem({ kind: "agent", id: "root" }); setSidebarOpen(false); }} disabled={workspace.isSending}><Bot aria-hidden="true" />Sybil Agent</button>
</nav>
<div className="lite-history-search">
<Search aria-hidden="true" />
<label className="lite-visually-hidden" htmlFor="lite-history-query">Search history</label>
<input id="lite-history-query" type="search" placeholder="Search chats and web searches" value={historyQuery} onInput={event => setHistoryQuery(event.currentTarget.value)} />
</div>
<section className="lite-history" aria-label="History">
<h2>History</h2>
{historySearch.error && historyQuery && <p className="lite-error" role="alert">{historySearch.error}</p>}
{historySearch.isLoading && <p role="status">Searching history…</p>}
<ul className="lite-history-list">
{historyItems.slice(0, historyCount).map(item => <li key={`${item.type}:${item.id}`}>
<button type="button" aria-current={workspace.selection?.kind === item.type && workspace.selection.id === item.id ? "page" : undefined}
disabled={workspace.isSending} onClick={() => { workspace.selectItem({ kind: item.type, id: item.id }); setSidebarOpen(false); }}>
{item.type === "chat" ? <MessageSquare aria-hidden="true" /> : <Search aria-hidden="true" />}
<span className="lite-history-item-content"><span className="lite-history-title">{itemTitle(item)}{item.starred && <Star aria-label="Starred" />}</span>
<time dateTime={item.updatedAt}>{formatDate(item.updatedAt)}</time>
{historyQuery && item.searchSnippet && <small>{item.searchSnippet}</small>}
</span>
</button>
</li>)}
</ul>
{historyItems.length > historyCount && <button type="button" onClick={() => setHistoryCount(value => value + PAGE_SIZE)}>More history</button>}
{!historyItems.length && !workspace.isLoading && !historySearch.isLoading && <p className="lite-muted">{historyQuery ? "No matches." : "No chats or searches."}</p>}
{historySearch.hasMore && <p className="lite-muted">Refine your search to see more matches.</p>}
</section>
<footer className="lite-sidebar-footer">
{fullLink}
<button type="button" className="lite-text-button" onClick={() => void auth.logout()}><LogOut aria-hidden="true" />Sign out</button>
</footer>
</aside>
<main id="lite-main" className="lite-main" tabIndex={-1}>
<header className="lite-workspace-header">
<button type="button" className="lite-icon-button lite-sidebar-trigger" aria-label="Open sidebar" aria-expanded={sidebarOpen} aria-controls="lite-sidebar" onClick={() => setSidebarOpen(true)}><Menu aria-hidden="true" /></button>
<div className="lite-workspace-title"><h1>{title}</h1>{!isSearch && !isAgent && <p>{getProviderLabel(workspace.provider)} · {workspace.model || "No model"}</p>}</div>
{!isAgent && <div className="lite-header-actions">
<button className="lite-icon-button" type="button" aria-label="Refresh" title="Refresh" onClick={() => void workspace.refresh()} disabled={workspace.isSending || workspace.isLoading}><RefreshCw aria-hidden="true" /></button>
{!isSearch && <details className="lite-settings"><summary aria-label="Settings"><Settings2 aria-hidden="true" /><span>Settings</span></summary>
<div className="lite-model-controls">
<label>Provider<select value={workspace.provider} onChange={event => workspace.setProvider(event.currentTarget.value as typeof workspace.provider)} disabled={workspace.isBusy}>
{workspace.providerOptions.map(provider => <option key={provider} value={provider}>{getProviderLabel(provider)}</option>)}
</select></label>
<label>Model<input list="lite-model-options" value={workspace.model} onInput={event => workspace.setModel(event.currentTarget.value)} disabled={workspace.isBusy} autoComplete="off" /></label>
<datalist id="lite-model-options">{workspace.modelOptions.map(model => <option key={model} value={model} />)}</datalist>
</div>
</details>}
</div>}
</header>
{isAgent ? <LiteAgentPanel /> : <>
<div className="lite-scroll" ref={transcriptRef} tabIndex={0} aria-label={isSearch ? "Search results" : "Conversation"}
onScroll={event => { const element = event.currentTarget; followTranscript.current = element.scrollHeight - element.scrollTop - element.clientHeight < 96; }}>
{workspace.isLoading && <p className="lite-status" role="status">Loading…</p>}
{workspace.chat && <LiteTranscript key={workspace.chat.id} messages={workspace.chat.messages} />}
{workspace.search && <LiteSearch search={workspace.search} />}
{submitted && <div className="lite-transcript"><article className="lite-message lite-message-user"><div className="lite-message-content message-bubble message-bubble--user"><p className="lite-plain-text">{submitted}</p></div></article></div>}
{workspace.isBusy && <p className="lite-status" role="status">{isSearch ? "Searching…" : "Generating…"}{!workspace.isSending && " Refresh to reconnect."}</p>}
</div>
<div className="lite-composer-shell">
{workspace.error && <p className="lite-error" role="alert">{workspace.error}</p>}
<form className="lite-composer" onSubmit={send}>
<label className="lite-visually-hidden" htmlFor="lite-draft">{isSearch ? "Search the web" : "Message"}</label>
<textarea id="lite-draft" rows={2} value={draft} onInput={event => setDraft(event.currentTarget.value)}
onKeyDown={event => { if (event.key === "Enter" && !event.shiftKey && !event.isComposing) void send(event); }}
disabled={workspace.isBusy || workspace.isLoading} placeholder={isSearch ? "Search the web" : "Enter prompt..."} />
<div className="lite-composer-footer">
<button className="lite-primary lite-send" type="submit" aria-label={isSearch ? "Search" : "Send message"} disabled={!draft.trim() || workspace.isBusy || workspace.isLoading || (!isSearch && !workspace.model.trim())}>{isSearch ? <Search aria-hidden="true" /> : <SendHorizontal aria-hidden="true" />}</button>
</div>
</form>
</div>
</>}
</main>
</div>
);
}