File size: 13,829 Bytes
8145bee
1ad1eea
8145bee
1ad1eea
 
 
 
7ce703c
8145bee
 
 
1ad1eea
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
 
8145bee
 
 
 
 
 
7ce703c
1ad1eea
7ce703c
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
1ad1eea
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
8145bee
1ad1eea
8145bee
 
 
 
 
 
 
 
1ad1eea
8145bee
 
 
 
1ad1eea
8145bee
 
1ad1eea
8145bee
 
 
 
 
 
 
 
 
7ce703c
8145bee
 
 
 
 
 
 
 
1ad1eea
8145bee
1ad1eea
 
8145bee
 
1ad1eea
 
8145bee
 
 
 
 
1ad1eea
8145bee
 
 
 
 
1ad1eea
8145bee
 
 
 
 
1ad1eea
 
 
 
 
 
 
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
8145bee
1ad1eea
8145bee
1ad1eea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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>;
}