import { useEffect, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { useCellValue } from "@mdxeditor/gurx"; import { $getSelection, $isElementNode, $nodesOfType, COMMAND_PRIORITY_HIGH, COPY_COMMAND, CUT_COMMAND, DRAGSTART_COMMAND, SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, } from "lexical"; import { ResearchQuestionNode, ULID, ulid } from "@chopin/dialect"; import { canCancelJob, researchJob, useJobs } from "../jobs"; import { widgets$ } from "../widget-options"; import type { JobStore } from "../jobs"; import type { LexicalEditor, LexicalNode } from "lexical"; type ResearchQuestion = { key: string; id: string; question: string }; /** Preserve an explicit move; every ordinary paste creates document-local identity. */ export function normalizeResearchQuestionIds( nodes: LexicalNode[], preserve: Set = new Set(), ): void { let used = new Set($nodesOfType(ResearchQuestionNode).map(node => node.getId())); let visit = (node: LexicalNode): void => { if (node instanceof ResearchQuestionNode) { let id = node.getId(); let moving = preserve.delete(id) && !used.has(id); if (!ULID.test(id) || used.has(id) || !moving) { id = ulid(); node.setId(id); } used.add(id); } if ($isElementNode(node)) { for (let child of node.getChildren()) visit(child); } }; for (let node of nodes) visit(node); } function selectedResearchIds(): Set { let ids = new Set(); let selection = $getSelection(); for (let selected of selection?.getNodes() ?? []) { let node: LexicalNode | null = selected; while (node) { if (node instanceof ResearchQuestionNode) ids.add(node.getId()); node = node.getParent(); } } return ids; } export function collectResearchQuestions(editor: LexicalEditor): ResearchQuestion[] { return editor.getEditorState().read(() => $nodesOfType(ResearchQuestionNode).map(node => ({ key: node.getKey(), id: node.getId(), question: node.getTextContent().replace(/\s+/g, " ").trim(), })) ); } function report(value: unknown): { title: string; summary: string; findings: Array<{ text: string; sourceUrls: string[] }>; sources: Array<{ title: string; url: string }>; question: string; caveats: string[]; documentRevision: number; documentSourceHash: string; } | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; let artifact = value as Record; let body = artifact.report; if ( !body || typeof body !== "object" || Array.isArray(body) || !Array.isArray(artifact.sources) ) { return undefined; } let valueBody = body as Record; if ( typeof valueBody.title !== "string" || typeof valueBody.summary !== "string" || !Array.isArray(valueBody.findings) || !Array.isArray(valueBody.caveats) || typeof artifact.question !== "string" || typeof artifact.documentRevision !== "number" || typeof artifact.documentSourceHash !== "string" ) return undefined; let findings = valueBody.findings.flatMap(item => { if (!item || typeof item !== "object" || Array.isArray(item)) return []; let finding = item as Record; return typeof finding.text === "string" && Array.isArray(finding.sourceUrls) ? [{ text: finding.text, sourceUrls: finding.sourceUrls.filter((url): url is string => typeof url === "string"), }] : []; }); let sources = artifact.sources.flatMap(item => { if (!item || typeof item !== "object" || Array.isArray(item)) return []; let source = item as Record; if (typeof source.title !== "string" || typeof source.url !== "string") return []; try { let url = new URL(source.url); return url.protocol === "https:" ? [{ title: source.title, url: url.toString() }] : []; } catch { return []; } }); return { title: valueBody.title, summary: valueBody.summary, findings, sources, question: artifact.question, caveats: valueBody.caveats.filter((value): value is string => typeof value === "string"), documentRevision: artifact.documentRevision, documentSourceHash: artifact.documentSourceHash, }; } function Chrome( { connected, editable, question, store }: { connected: boolean; editable: boolean; question: ResearchQuestion; store: JobStore; }, ) { let snapshot = useJobs(store); let job = researchJob(snapshot.jobs, question.id); let [expanded, setExpanded] = useState(false); let [error, setError] = useState(); let detail = job ? snapshot.details[job.id] : undefined; let result = detail?.artifact && report(detail.artifact.value); let stale = !!result && (result.question.replace(/\s+/g, " ").trim() !== question.question || detail?.currentTargetGeneration !== job?.targetGeneration); if (!snapshot.ready) return null; let assign = (requestKey = "initial") => { setError(undefined); void store.assignResearch(question.id, requestKey).catch(err => setError(err instanceof Error ? err.message : "Could not assign research.") ); }; let cancel = () => { if (!job) return; setError(undefined); void store.cancel(job).catch(err => setError(err instanceof Error ? err.message : "Could not cancel research.") ); }; let open = () => { setExpanded(value => !value); if (job && !detail) void store.detail(job.id).catch(() => {}); }; let terminal = job && (job.state === "failed" || job.state === "cancelled" || job.state === "superseded"); let canAssign = !job || !!terminal || job?.state === "completed" && stale; let unavailable = !connected || snapshot.refreshing || snapshot.pending[question.id] === "assign"; return (

Public search receives this question text. Private document context is analyzed separately without web access.

{canAssign && editable && ( )} {job && (
Research: {job.state}{job.reason ? ` (${job.reason})` : ""} {editable && canCancelJob(job) && ( )} {job.state === "completed" && ( )}
)} {expanded && result && (
{stale && (

This report answers an earlier question or document revision.

)}

{result.title}

Based on document revision {result.documentRevision}.

{result.summary}

    {result.findings.map((finding, index) =>
  • {finding.text}
  • )}
{result.sources.length > 0 && ( )} {result.caveats.length > 0 && (
Caveats
    {result.caveats.map(value =>
  • {value}
  • )}
)}
)} {expanded && detail && !result &&

Research report is unavailable.

} {error &&

{error}

}
); } export function ResearchQuestionPlugin() { let [editor] = useLexicalComposerContext(); let options = useCellValue(widgets$); let [questions, setQuestions] = useState([]); let moving = useRef(new Set()); useEffect(() => { let update = () => setQuestions(collectResearchQuestions(editor)); update(); return editor.registerUpdateListener(update); }, [editor]); useEffect(() => { let copy = editor.registerCommand( COPY_COMMAND, () => { moving.current.clear(); return false; }, COMMAND_PRIORITY_HIGH, ); let cut = editor.registerCommand( CUT_COMMAND, () => { moving.current = selectedResearchIds(); return false; }, COMMAND_PRIORITY_HIGH, ); let drag = editor.registerCommand( DRAGSTART_COMMAND, () => { moving.current = selectedResearchIds(); return false; }, COMMAND_PRIORITY_HIGH, ); let insert = editor.registerCommand( SELECTION_INSERT_CLIPBOARD_NODES_COMMAND, payload => { normalizeResearchQuestionIds(payload.nodes, moving.current); moving.current.clear(); return false; }, COMMAND_PRIORITY_HIGH, ); return () => { copy(); cut(); drag(); insert(); }; }, [editor]); let store = options.jobs; if (!store) return null; return ( <> {questions.map(question => { let host = editor.getElementByKey(question.key) ?.querySelector("[data-plan-research-question-derived]"); return host ? createPortal( , host, question.key, ) : null; })} ); }