397 lines
13 KiB
React
397 lines
13 KiB
React
"use client";
|
|
|
|
import React, { useEffect } from "react";
|
|
import { useState, useRef, useMemo } from "react";
|
|
import DiagnosticsView from "@/components/diagnostics-view";
|
|
import ReasoningWorkspace, { LoadingOverlay } from "@/components/reasoning-workspace";
|
|
import { mockFetch } from "@/lib/mocks/confidence-engine/mock-client";
|
|
|
|
/* Compile-time env resolution — NEXT_PUBLIC_ vars are injected by Next.js at build */
|
|
const MOCK_ENABLED = process.env.NEXT_PUBLIC_CONFIDENCE_ENGINE_MOCKS === "true";
|
|
|
|
/* ── inject runtime globals for the mock client to read ──── */
|
|
function useMockGlobals() {
|
|
useEffect(() => {
|
|
if (MOCK_ENABLED) {
|
|
var w = window;
|
|
w.__MOCK_ENABLED = true;
|
|
w.__MOCK_DELAY = process.env.NEXT_PUBLIC_CONFIDENCE_MOCK_DELAY || "normal";
|
|
w.__MOCK_SCENARIO = process.env.NEXT_PUBLIC_CONFIDENCE_ENGINE_MOCK_SCENARIO || "";
|
|
}
|
|
}, []);
|
|
}
|
|
|
|
const MAX_LENGTH = 10000;
|
|
|
|
export async function submitScenarioForStartCase(fetchImpl, scenario) {
|
|
return fetchImpl("/api/cases/start", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ scenario }),
|
|
});
|
|
}
|
|
|
|
export async function submitAnswerForUpdateCase(
|
|
fetchImpl,
|
|
{ situationGraph, previousQuestion, answer },
|
|
) {
|
|
if (!answer?.trim()) {
|
|
return {
|
|
ok: false,
|
|
skipped: true,
|
|
data: {
|
|
success: false,
|
|
stage: "request_validation",
|
|
error: "Please enter an answer before updating.",
|
|
},
|
|
};
|
|
}
|
|
|
|
const response = await fetchImpl("/api/cases/update", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ situationGraph, previousQuestion, answer }),
|
|
});
|
|
|
|
return {
|
|
ok: response.ok,
|
|
skipped: false,
|
|
data: await response.json(),
|
|
};
|
|
}
|
|
|
|
function normaliseStartResult(data) {
|
|
return {
|
|
...data,
|
|
selectedQuestion:
|
|
typeof data?.selectedQuestion === "string"
|
|
? data.selectedQuestion
|
|
: data?.selectedQuestion?.question ?? null,
|
|
newlySurfacedNodeIds: data?.newlySurfacedNodeIds ?? [],
|
|
};
|
|
}
|
|
|
|
function normaliseUpdateSelectedQuestion(selectedQuestion) {
|
|
if (!selectedQuestion) return null;
|
|
if (typeof selectedQuestion === "string") return selectedQuestion;
|
|
return selectedQuestion.question ?? null;
|
|
}
|
|
|
|
export function ScenarioResultPanels({ status, result }) {
|
|
if (!result) return null;
|
|
|
|
const hasGraph = Boolean(result.situationGraph);
|
|
const hasQuestion = Boolean(result.selectedQuestion?.question);
|
|
const hasDiagnostics = Boolean(result.diagnostics);
|
|
|
|
return (
|
|
<>
|
|
{status === "error" && (
|
|
<div className="space-y-3">
|
|
{result.error && (
|
|
<div className="rounded-lg border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-700 whitespace-pre-wrap">
|
|
Error: {result.error}
|
|
</div>
|
|
)}
|
|
{!hasGraph && !hasQuestion && (
|
|
<div className="rounded-lg border border-yellow-300 bg-yellow-50 px-4 py-2 text-sm text-yellow-800">
|
|
Validation failed — no structured graph output was produced.
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{hasDiagnostics && <DiagnosticsView result={result} />}
|
|
</>
|
|
);
|
|
}
|
|
|
|
// ── Message pools ───────────────────────────────────────────
|
|
const INITIAL_MESSAGES = [
|
|
{ min: 0, text: "Reading your situation" },
|
|
{ min: 10, text: "Building a structured understanding" },
|
|
{ min: 25, text: "Identifying what is known and still unclear" },
|
|
{ min: 45, text: "Selecting the next useful question" },
|
|
];
|
|
|
|
const UPDATE_MESSAGES = [
|
|
{ min: 0, text: "Considering your answer" },
|
|
{ min: 10, text: "Updating the situation" },
|
|
{ min: 25, text: "Checking what changed" },
|
|
{ min: 45, text: "Choosing the next question" },
|
|
];
|
|
|
|
function useLoadingStatus(messages, isLoading) {
|
|
const [elapsed, setElapsed] = useState(0);
|
|
const startRef = useRef(null);
|
|
|
|
useEffect(() => {
|
|
if (isLoading) {
|
|
startRef.current = Date.now();
|
|
const iv = setInterval(() => {
|
|
setElapsed(Math.floor((Date.now() - startRef.current) / 1000));
|
|
}, 1000);
|
|
return () => clearInterval(iv);
|
|
} else {
|
|
setElapsed(0);
|
|
startRef.current = null;
|
|
}
|
|
}, [isLoading]);
|
|
|
|
const currentMessage = useMemo(() => {
|
|
if (!messages || messages.length === 0) return "";
|
|
let msg = messages[0].text;
|
|
for (const m of messages) {
|
|
if (elapsed >= m.min) msg = m.text;
|
|
}
|
|
return msg;
|
|
}, [messages, elapsed]);
|
|
|
|
return { elapsed, currentMessage };
|
|
}
|
|
|
|
export function UpdateErrorPanel({ updateError }) {
|
|
if (!updateError) return null;
|
|
|
|
const errors = [
|
|
...(updateError.errors || []),
|
|
...(updateError.validationErrors || []),
|
|
...(updateError.graphValidationErrors || []),
|
|
...(updateError.proposalErrors || []),
|
|
...(updateError.providerErrors || []),
|
|
];
|
|
|
|
return (
|
|
<div className="space-y-3">
|
|
<div className="rounded-lg border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-700 whitespace-pre-wrap">
|
|
Update error: {updateError.error}
|
|
</div>
|
|
{errors.length > 0 && (
|
|
<details className="rounded-lg border border-red-200 bg-red-50 px-4 py-3">
|
|
<summary className="cursor-pointer text-sm font-medium text-red-700 underline">
|
|
Update details ({errors.length})
|
|
</summary>
|
|
<ul className="mt-2 space-y-1 text-sm text-red-700">
|
|
{errors.map((item, index) => (
|
|
<li key={index}>
|
|
{typeof item === "string" ? item : item?.message || JSON.stringify(item)}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</details>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export { INITIAL_MESSAGES, UPDATE_MESSAGES, useLoadingStatus };
|
|
|
|
export default function ScenarioForm() {
|
|
const [scenario, setScenario] = useState("");
|
|
const [status, setStatus] = useState("idle"); // idle | loading | error | success
|
|
const [result, setResult] = useState(null);
|
|
const [answer, setAnswer] = useState("");
|
|
const [updateStatus, setUpdateStatus] = useState("idle"); // idle | loading | error | success
|
|
const [updateError, setUpdateError] = useState(null);
|
|
const [updateResult, setUpdateResult] = useState(null);
|
|
const [lastSubmittedAnswer, setLastSubmittedAnswer] = useState("");
|
|
const [currentUnderstanding, setCurrentUnderstanding] = useState(null);
|
|
const textareaRef = useRef(null);
|
|
|
|
/* Inject mock globals so the interceptor can read them at runtime */
|
|
useMockGlobals();
|
|
|
|
const { elapsed: startElapsed, currentMessage: startMsg } = useLoadingStatus(
|
|
INITIAL_MESSAGES,
|
|
status === "loading"
|
|
);
|
|
|
|
const { elapsed: updateElapsed, currentMessage: updateMsg } = useLoadingStatus(
|
|
UPDATE_MESSAGES,
|
|
updateStatus === "loading"
|
|
);
|
|
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault();
|
|
setStatus("loading");
|
|
setResult(null);
|
|
setAnswer("");
|
|
setUpdateStatus("idle");
|
|
setUpdateResult(null);
|
|
setLastSubmittedAnswer("");
|
|
setUpdateError(null);
|
|
setCurrentUnderstanding(null);
|
|
|
|
try {
|
|
const res = await submitScenarioForStartCase(MOCK_ENABLED ? mockFetch : fetch, scenario);
|
|
|
|
const data = await res.json();
|
|
|
|
if (res.ok && data.success) {
|
|
setStatus("success");
|
|
setCurrentUnderstanding(data.summary ?? null);
|
|
setResult(normaliseStartResult(data));
|
|
} else {
|
|
setStatus("error");
|
|
setCurrentUnderstanding(data.summary ?? null);
|
|
setResult(normaliseStartResult(data));
|
|
}
|
|
} catch (err) {
|
|
setStatus("error");
|
|
setResult({ error: err.message || "Network request failed" });
|
|
}
|
|
};
|
|
|
|
const handleUpdate = async (e) => {
|
|
e.preventDefault();
|
|
|
|
// Guard empty answer before showing loading state
|
|
if (!answer?.trim()) {
|
|
setUpdateStatus("error");
|
|
setUpdateError({ error: "Please enter an answer before updating." });
|
|
return;
|
|
}
|
|
|
|
setUpdateStatus("loading");
|
|
setUpdateError(null);
|
|
setLastSubmittedAnswer(answer.trim());
|
|
|
|
const submission = await submitAnswerForUpdateCase(MOCK_ENABLED ? mockFetch : fetch, {
|
|
situationGraph: result?.situationGraph,
|
|
previousQuestion: result?.selectedQuestion,
|
|
answer,
|
|
});
|
|
|
|
if (submission.skipped) {
|
|
setUpdateStatus("error");
|
|
setUpdateError(submission.data);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const outcome = submission.data;
|
|
|
|
if (submission.ok && outcome.success) {
|
|
setUpdateStatus("success");
|
|
setCurrentUnderstanding(
|
|
outcome.summary ? outcome.summary : currentUnderstanding,
|
|
);
|
|
setUpdateResult({
|
|
...outcome,
|
|
previousSituationGraph: result?.situationGraph ?? null,
|
|
});
|
|
setResult((current) => ({
|
|
...current,
|
|
situationGraph: outcome.updatedSituationGraph,
|
|
selectedQuestion: normaliseUpdateSelectedQuestion(
|
|
outcome.selectedQuestion,
|
|
),
|
|
newlySurfacedNodeIds: (outcome.proposal?.addedNodes || [])
|
|
.filter((node) => node.kind === "unknown")
|
|
.map((node) => node.id),
|
|
diagnostics: outcome.diagnostics,
|
|
}));
|
|
setAnswer("");
|
|
} else {
|
|
setUpdateStatus("error");
|
|
setUpdateError(outcome);
|
|
}
|
|
} catch (err) {
|
|
setUpdateStatus("error");
|
|
setUpdateError({ error: err.message || "Network request failed" });
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
{status === "idle" && (
|
|
<form onSubmit={handleSubmit} className="space-y-4">
|
|
<textarea
|
|
ref={textareaRef}
|
|
value={scenario}
|
|
onChange={(e) => setScenario(e.target.value)}
|
|
placeholder="Describe the scenario you want analysed..."
|
|
rows={10}
|
|
className="w-full rounded-lg border border-gray-300 px-4 py-3 text-sm focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-400"
|
|
/>
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-xs text-gray-400">
|
|
{scenario.length}/{MAX_LENGTH}
|
|
</span>
|
|
<button
|
|
type="submit"
|
|
disabled={!scenario.trim()}
|
|
className="rounded-lg bg-gray-900 px-6 py-2.5 text-sm font-medium text-white transition hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-40"
|
|
>
|
|
Analyse
|
|
</button>
|
|
</div>
|
|
</form>
|
|
)}
|
|
|
|
{/* ── Initial analysis loading card ─────────────── */}
|
|
{status === "loading" && (
|
|
<LoadingOverlay
|
|
isLoading={true}
|
|
elapsed={startElapsed}
|
|
currentMessage={startMsg}
|
|
variant="initial"
|
|
/>
|
|
)}
|
|
|
|
{/* ── Main result workspace ─────────────────────── */}
|
|
{(status === "success" || status === "error" || updateStatus === "success") && (
|
|
<ReasoningWorkspace
|
|
scenario={scenario}
|
|
status={status}
|
|
updateStatus={updateStatus}
|
|
currentUnderstanding={currentUnderstanding}
|
|
result={{
|
|
...(result || {}),
|
|
situationGraph: updateResult?.updatedSituationGraph ?? result?.situationGraph,
|
|
selectedQuestion: updateResult?.selectedQuestion ?? result?.selectedQuestion,
|
|
newlySurfacedNodeIds: result?.newlySurfacedNodeIds || [],
|
|
diagnostics: result?.diagnostics || null,
|
|
updateError,
|
|
}}
|
|
answer={answer}
|
|
setAnswer={setAnswer}
|
|
onAnswerSubmit={handleUpdate}
|
|
lastSubmittedAnswer={lastSubmittedAnswer}
|
|
/>
|
|
)}
|
|
|
|
{/* Reset button after successful analysis */}
|
|
{status === "success" && (
|
|
<div className="text-center">
|
|
<button
|
|
onClick={() => {
|
|
setScenario("");
|
|
setStatus("idle");
|
|
setResult(null);
|
|
setAnswer("");
|
|
setUpdateStatus("idle");
|
|
setUpdateResult(null);
|
|
setLastSubmittedAnswer("");
|
|
setCurrentUnderstanding(null);
|
|
setUpdateError(null);
|
|
}}
|
|
className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-600 transition hover:bg-gray-50"
|
|
>
|
|
Start new investigation
|
|
</button>
|
|
</div>
|
|
)}
|
|
|
|
{/* Empty state */}
|
|
{status === "idle" && (
|
|
<div className="rounded-lg border border-dashed border-gray-300 bg-gray-50 px-6 py-8 text-center">
|
|
<p className="text-sm text-gray-400">
|
|
Enter a scenario above and click Analyse to begin.
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|