loopable / web /src /assistant /AssistantPanel.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
7ce703c verified
Raw History Blame Contribute Delete
13.8 kB
import { useEffect, useRef, useState } from "react";
import type { ComponentType, ReactNode, Ref } from "react";
import type { AssistantLogTurn, AssistantMessage, AssistantTurn } from "./AssistantPage";
import type { SuggestionChips } from "./SuggestionChips";
import type { TypingIndicator } from "./TypingIndicator";
import type { NavEntry } from "../shell/nav";
import type { QueryCitation, QueryMessage, Result, SavedQuery } from "../query/queryApi";
import { dockClient, refusalSentence } from "./dockClient";
import type { DockClient, DockContext } from "./dockClient";
import "./assistantPanel.css";
/** The page's own components. Each optional member has a fallback, because node probes inject only Turn and Message. */
export type AssistantRenderers = {
Turn: typeof AssistantTurn;
Message: typeof AssistantMessage;
Typing?: typeof TypingIndicator;
Chips?: typeof SuggestionChips;
LinkHost?: ComponentType<{ sources: NavEntry[]; children?: ReactNode }>;
};
export interface AssistantPanelProps extends Omit<DockContext, "surface"> {
surface?: DockContext["surface"];
databaseLabel?: string;
open: boolean;
onClose: () => void;
model?: string;
client?: DockClient;
renderers?: AssistantRenderers;
}
export interface AssistantPanelState {
loading: boolean;
turns: AssistantLogTurn[];
messages: QueryMessage[];
citations: QueryCitation[];
view: SavedQuery | null;
draft: string;
busy: boolean;
problem: string;
retry?: { id: string; question: string };
}
export const initialPanelState = (): AssistantPanelState => ({
loading: true, turns: [], messages: [], citations: [], view: null, draft: "", busy: false, problem: "",
});
let sharedRenderers: Promise<AssistantRenderers> | undefined;
function loadRenderers(): Promise<AssistantRenderers> {
// Keep browser dependencies behind this seam so node probes can inject renderers.
return sharedRenderers ||= import("./AssistantPage").then((page) => ({
Turn: page.AssistantTurn, Message: page.AssistantMessage, Typing: page.TypingIndicator,
Chips: page.SuggestionChips, LinkHost: page.DockOpenInPlace,
})).catch((error: unknown) => { sharedRenderers = undefined; throw error; });
}
function unlogged(messages: QueryMessage[], turns: AssistantLogTurn[]): QueryMessage[] {
const ids = new Set(turns.flatMap((turn) => [turn.id, turn.payload?.id]));
return messages.filter((message) => !ids.has(message.id));
}
/** C2: failed turns use the shared mapper even without a response or a recognized code. */
export function dockFailureLine(result: Extract<Result<unknown>, { ok: false }>): string {
return refusalSentence(result.code);
}
/** The dock's databases as nav entries, for the suggestion chips and the link pop-up. */
export function dockSources(database?: string, databases?: string[], label?: string): NavEntry[] {
const keys = [...new Set([database || "", ...(databases || [])].map((key) => key.trim()).filter(Boolean))];
return keys.map((key) => ({ key, label: key === database?.trim() && label?.trim() ? label.trim() : "",
kind: "native" as const, depth: 0 }));
}
/** One chip per labelled database. A dock with no label offers one chip for all of its data. */
export function chipSources(sources: NavEntry[]): NavEntry[] {
const labelled = sources.filter((entry) => entry.label);
return labelled.length ? labelled : sources.slice(0, 1).map((entry) => ({ ...entry, label: "this data" }));
}
const preview = (id: string) => { window.location.hash = `#/query?view=${encodeURIComponent(id)}`; };
export default function AssistantPanel({ open, onClose, surface = "data", database, databases, databaseLabel, model,
client = dockClient, renderers: injectedRenderers }: AssistantPanelProps) {
const unbound = surface === "sheet" && !database?.trim()
&& !databases?.some((key) => key.trim());
const [state, setState] = useState(initialPanelState);
const [renderers, setRenderers] = useState(injectedRenderers);
const [present, setPresent] = useState(open);
const [entered, setEntered] = useState(false);
const [reduced, setReduced] = useState(() => typeof window !== "undefined"
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches);
const panelRef = useRef<HTMLElement | null>(null);
const logRef = useRef<HTMLDivElement | null>(null);
const inFlight = useRef(false);
const mounted = useRef(true);
const sequence = useRef(0);
const current = useRef(state);
current.current = state;
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
}, []);
useEffect(() => {
const preference = window.matchMedia("(prefers-reduced-motion: reduce)");
const changed = () => setReduced(preference.matches);
changed(); preference.addEventListener("change", changed);
return () => preference.removeEventListener("change", changed);
}, []);
useEffect(() => {
if (panelRef.current) panelRef.current.inert = !open;
if (open) {
setPresent(true);
if (reduced) { setEntered(true); return; }
const frame = requestAnimationFrame(() => setEntered(true));
return () => cancelAnimationFrame(frame);
}
setEntered(false);
if (reduced || !panelRef.current) { setPresent(false); return; }
const token = getComputedStyle(panelRef.current).getPropertyValue("--lp-motion-feedback-duration").trim();
const duration = parseFloat(token) * (token.endsWith("ms") ? 1 : 1000);
if (!(duration > 0)) { setPresent(false); return; }
const timer = setTimeout(() => setPresent(false), duration);
return () => clearTimeout(timer);
}, [open, reduced]);
useEffect(() => {
if (!open) return;
let active = true;
setState((value) => ({ ...value, loading: true, problem: "" }));
void (async () => {
try {
const [history, shared] = await Promise.all([
client.fetchDockHistory(), injectedRenderers ? Promise.resolve(injectedRenderers) : loadRenderers(),
]);
if (!active) return;
setRenderers(shared);
setState((value) => history.ok
? { ...value, loading: false, turns: history.value.turns,
messages: unlogged(value.messages, history.value.turns) }
: { ...value, loading: false, problem: history.message });
} catch {
if (active) setState((value) => ({ ...value, loading: false,
problem: "The conversation could not be loaded. Open it again to retry." }));
}
})();
return () => { active = false; };
}, [open, client, injectedRenderers]);
useEffect(() => {
if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
}, [state.turns, state.messages, state.busy]);
const send = async (chip?: { database: string; prompt: string }) => {
const draft = chip ? chip.prompt : current.current.draft;
const question = draft.trim();
const target = chip ? chip.database : database;
if (unbound || !question || inFlight.current || current.current.loading || !renderers) return;
inFlight.current = true;
const retry = current.current.retry;
const id = retry?.question === question ? retry.id : `dock-user-${Date.now()}-${sequence.current++}`;
const user: QueryMessage = { id, threadId: "", role: "user", content: question, createdAt: new Date().toISOString() };
setState((value) => ({ ...value, draft: "", busy: true, problem: "", retry: undefined,
messages: value.messages.some((message) => message.id === id) ? value.messages : [...value.messages, user] }));
try {
const result = await client.sendDockTurn({ question, surface, database: target, databases, model });
if (!mounted.current) return;
if (!result.ok) {
if (result.status === 403) {
const refusal: QueryMessage = { ...user, id: `${id}-refusal`, role: "assistant",
content: dockFailureLine(result), reason: "dock_permission_refused" };
setState((value) => ({ ...value, messages: [...value.messages, refusal] }));
} else {
setState((value) => ({ ...value, draft, problem: dockFailureLine(result), retry: { id, question } }));
}
return;
}
const response = result.value;
setState((value) => ({ ...value, messages: unlogged([
...value.messages.filter((message) => message.id !== id), response.userMessage, response.message,
], value.turns), citations: [...value.citations, ...response.citations], view: response.view }));
} catch {
if (mounted.current) setState((value) => ({ ...value, draft, retry: { id, question },
problem: refusalSentence() }));
} finally {
inFlight.current = false;
if (mounted.current) setState((value) => ({ ...value, busy: false }));
}
};
if (!open && (!present || reduced)) return null;
return <AssistantPanelView state={state} renderers={renderers} panelRef={panelRef} logRef={logRef}
unbound={unbound} sources={dockSources(database, databases, databaseLabel)}
visible={open && (entered || reduced)} onClose={onClose} onPreview={preview}
onDraft={(draft) => setState((value) => ({ ...value, draft }))} onSend={() => { void send(); }}
onAsk={(key, prompt) => { void send({ database: key, prompt }); }} />;
}
export function AssistantPanelView({ state, renderers, onClose, onDraft, onSend, onAsk, onPreview = preview,
panelRef, logRef, visible = true, unbound = false, sources = [] }: {
state: AssistantPanelState;
renderers?: AssistantRenderers;
onClose: () => void;
onDraft: (draft: string) => void;
onSend: () => void;
onAsk?: (database: string, prompt: string) => void;
onPreview?: (id: string) => void;
panelRef?: Ref<HTMLElement>;
logRef?: Ref<HTMLDivElement>;
visible?: boolean;
unbound?: boolean;
sources?: NavEntry[];
}) {
const disabled = state.loading || state.busy || !renderers;
const empty = !unbound && !state.loading && !state.problem && !state.turns.length && !state.messages.length;
const Turn = renderers?.Turn;
const Message = renderers?.Message;
const Typing = renderers?.Typing;
const Chips = renderers?.Chips;
const LinkHost = renderers?.LinkHost;
const answers = <>
{Turn ? state.turns.map((turn) => <Turn key={turn.id} turn={turn} citations={state.citations} onPreview={onPreview} />) : null}
{Message ? state.messages.map((message) => <Message key={message.id} message={message}
citations={state.citations} view={state.view && state.view.id === message.viewId ? state.view : undefined} onPreview={onPreview} />) : null}
</>;
return <aside ref={panelRef} className="assistant-panel" aria-label="Assistant"
data-state={visible ? "open" : "closed"} aria-hidden={!visible || undefined}>
<header className="assistant-panel-head">
<h2>Assistant</h2>
<button type="button" className="assistant-panel-close" onClick={onClose} aria-label="Close the assistant">
<svg viewBox="0 0 16 16" aria-hidden="true" fill="none">
<path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
</button>
</header>
<div className="assistant-panel-log" ref={logRef} role="log" aria-label="Conversation" aria-live="polite">
{unbound ? <p className="assistant-panel-status">Nothing is bound to this sheet yet.</p> : null}
{state.loading ? <p className="assistant-panel-status" role="status">Loading conversation</p> : null}
{empty ? <div className="as-opening">
<h3 className="assistant-panel-opening">How can I help?</h3>
{Chips && onAsk ? <Chips granted={chipSources(sources)} loaded turnCount={0} busy={disabled} onAsk={onAsk} /> : null}
</div> : null}
{LinkHost ? <LinkHost sources={sources}>{answers}</LinkHost> : answers}
{/* The page's typing dots. The inline copy serves a probe that injects no Typing renderer. */}
{state.busy ? Typing ? <Typing /> : <div className="as-message as-message--assistant as-typing" role="status"
aria-label="Loopy is thinking">
<span className="as-typing-dot" aria-hidden="true" />
<span className="as-typing-dot" aria-hidden="true" />
<span className="as-typing-dot" aria-hidden="true" />
</div> : null}
</div>
{unbound ? <footer className="as-composer assistant-panel-composer">
<div className="assistant-panel-composer-foot">
<a className="assistant-panel-full" href="#/assistant">Open the full conversation</a>
</div>
{state.problem ? <p className="assistant-panel-problem" role="alert">{state.problem}</p> : null}
</footer> : <form className="as-composer assistant-panel-composer" onSubmit={(event) => { event.preventDefault(); onSend(); }}>
{/* The page's composer markup, so assistant.css styles both. */}
<div className="as-field">
<textarea className="as-prompt" rows={1} value={state.draft} placeholder="Ask about this data"
aria-label="Ask about this data"
disabled={disabled} onChange={(event) => onDraft(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
event.preventDefault(); onSend();
}
}} />
<div className="as-field-foot">
<a className="assistant-panel-full" href="#/assistant">Open the full conversation</a>
<button type="submit" className="as-send" aria-label="Send" disabled={disabled || !state.draft.trim()}>
<svg viewBox="0 0 16 16" aria-hidden="true" width="15" height="15">
<path d="M8 13V3.6M4 7.4 8 3.4l4 4" />
</svg>
</button>
</div>
</div>
<p className="assistant-panel-problem" role={state.problem ? "alert" : undefined}>{state.problem}</p>
</form>}
</aside>;
}