import { useCallback, useEffect, useRef, useState } from "react"; import { api } from "./api.js"; import ConstructPicker from "./ConstructPicker.jsx"; import ResultsView from "./ResultsView.jsx"; export default function Workspace({ project, auth, onAuthRefresh, onProjectChanged, onProjectDeleted }) { const [corpora, setCorpora] = useState([]); const [constructs, setConstructs] = useState([]); const [models, setModels] = useState([]); const [jobs, setJobs] = useState([]); const [corpusId, setCorpusId] = useState(""); const [textColumn, setTextColumn] = useState(""); const [constructIds, setConstructIds] = useState([]); // Anchor-vector (bipolar) run (spec 0006): an optional opposite pole scored // against a single target construct, plus the similarity metric. const [anchorMode, setAnchorMode] = useState(false); const [oppositeId, setOppositeId] = useState(""); const [metric, setMetric] = useState("cosine"); const [modelName, setModelName] = useState(""); const [languages, setLanguages] = useState(["en"]); const [language, setLanguage] = useState("en"); const [uploading, setUploading] = useState(false); const [running, setRunning] = useState(false); const [error, setError] = useState(""); // Custom-construct form: null = closed, else the item source it opens on // ("type" | "upload" | "ai"). Lifted here so the Step 2 card can expose the // three acquisition paths as explicit buttons (PI feedback 2026-08-07). const [constructFormTab, setConstructFormTab] = useState(null); const [viewJobId, setViewJobId] = useState(null); const [confirmDelete, setConfirmDelete] = useState(false); const [deleteText, setDeleteText] = useState(""); const fileRef = useRef(null); async function toggleArchive() { try { await api.patchProject(project.id, { archived: !project.archived }); onProjectChanged?.(); } catch (err) { setError(err.message); } } async function handleDelete() { try { await api.deleteProject(project.id); setConfirmDelete(false); onProjectDeleted?.(); } catch (err) { setError(err.message); } } const refreshJobs = useCallback( () => api.listJobs(project.id).then(setJobs).catch(() => {}), [project.id] ); useEffect(() => { api.listCorpora(project.id).then(setCorpora).catch((e) => setError(e.message)); api.listConstructs().then(setConstructs).catch((e) => setError(e.message)); api .models() .then((m) => { setModels(m); const def = m.find((x) => x.default) || m[0]; if (def) setModelName(def.id); }) .catch((e) => setError(e.message)); api.languages().then(setLanguages).catch(() => {}); refreshJobs(); }, [project.id, refreshJobs]); // Poll while any job is active. const anyActive = jobs.some((j) => j.status === "queued" || j.status === "running"); useEffect(() => { if (!anyActive) return undefined; const t = setInterval(refreshJobs, 1200); return () => clearInterval(t); }, [anyActive, refreshJobs]); const corpus = corpora.find((c) => c.id === corpusId) || null; const selectedConstructs = constructIds .map((id) => constructs.find((c) => c.id === id)) .filter(Boolean); // Server-enforced too; mirrored here so the picker can explain the cap. const MAX_CONSTRUCTS = 10; function toggleConstruct(id) { setConstructIds((ids) => { if (ids.includes(id)) return ids.filter((x) => x !== id); if (ids.length >= MAX_CONSTRUCTS) { setError(`At most ${MAX_CONSTRUCTS} constructs per run.`); return ids; } return [...ids, id]; }); } async function handleUpload(e) { const file = e.target.files?.[0]; if (!file) return; setUploading(true); setError(""); try { const uploaded = await api.uploadCorpus(project.id, file); const list = await api.listCorpora(project.id); setCorpora(list); setCorpusId(uploaded.id); setTextColumn(uploaded.suggested_text_column || uploaded.columns[0]); } catch (err) { setError(err.message); } finally { setUploading(false); if (fileRef.current) fileRef.current.value = ""; } } async function handleRun() { setRunning(true); setError(""); try { await api.createJob({ project_id: project.id, corpus_id: corpusId, construct_ids: constructIds, text_column: textColumn, model_name: modelName, language, ...(anchorMode && oppositeId ? { opposite_construct_id: oppositeId, similarity_metric: metric } : {}), }); await refreshJobs(); onAuthRefresh?.(); // anonymous run counter changed } catch (err) { setError(err.message); } finally { setRunning(false); } } if (viewJobId) { return ( { setViewJobId(null); refreshJobs(); }} /> ); } const fileMissing = corpus && corpus.file_available === false; const oppositeConstruct = constructs.find((c) => c.id === oppositeId) || null; // Anchored runs need exactly one target and a distinct opposite pole. const anchorReady = !anchorMode || (constructIds.length === 1 && oppositeId && oppositeId !== constructIds[0]); const canRun = corpusId && textColumn && constructIds.length > 0 && modelName && !running && !fileMissing && anchorReady; return ( <> {error && (
setError("")}> {error}
)} {/* Project header + actions */}
{project.name} {project.archived && archived}
{confirmDelete && (
setConfirmDelete(false)}>
e.stopPropagation()}>

Delete "{project.name}"?

This permanently deletes {corpora.length} dataset{corpora.length === 1 ? "" : "s"},{" "} {jobs.length} run{jobs.length === 1 ? "" : "s"}, and all uploaded and result files. This cannot be undone. If you might need it later, use Archive instead.

)} {/* Step 1 - corpus */}

1Corpus

Upload a CSV or XLSX file, then choose the column containing the text to analyze. {/* Both ceilings are shown up front, for signed-in users too: the row limit is global and usually binds first, so surfacing only the byte limit sent people off to split a file that was never too large in bytes. */} {auth && !auth.signed_in && auth.limits?.max_rows && ( <> {" "} Anonymous limit: {Math.round(auth.limits.max_bytes / 1048576)} MB /{" "} {auth.limits.max_rows.toLocaleString()} rows per file; uploads are deleted after analysis. Sign in (top right) for larger uploads and to keep your data. )} {auth && auth.signed_in && auth.limits?.max_rows && ( <> {" "} Limit: {Math.round(auth.limits.max_bytes / 1048576)} MB /{" "} {auth.limits.max_rows.toLocaleString()} rows per file. )}

{uploading && Uploading…}
{corpus?.parse_info?.note && (

⚠ {corpus.parse_info.note}

)} {corpus && corpus.file_available === false && (

⚠ This dataset's file is no longer on the server (the instance restarted). Your past results for it are safe, but to run a new analysis, upload the file again above.

)}
{/* Step 2 - construct */}

2Construct

Three ways to add a construct: pick validated scales from the library, add your own items (typed or uploaded), or draft items with AI when no validated scale exists. Selecting several runs them together in one pass (up to 10) and shows how they correlate in your texts.

{selectedConstructs.map((c) => (
{c.name} {" "} {c.items.length} item{c.items.length === 1 ? "" : "s"} {c.ai_generated ? " · AI-generated · not validated" : c.verification_status !== "verified" ? " · unverified" : ""}
    {c.items.map((item, i) => (
  • {item} {c.reverse_scored?.[i] ? " (reverse-scored)" : ""}
  • ))}
{c.reference && (

Reference: {c.reference}

)} {c.ai_generated ? ( /* Cautionary wording approved by the PI (2026-08-05) */

⚠ This construct's items were AI-generated and have not been psychometrically validated. Interpret scores with appropriate caution.

) : ( c.verification_status !== "verified" && (

⚠ Item wording not yet verified verbatim against the original publication (status: {c.verification_status.replace("_", " ")}).

) )}
))} {/* Anchor vectors (bipolar constructs, spec 0006): score along the axis between a target and a contrasting construct. */}
Scores texts along the axis between two poles - higher = toward the target, negative = toward the opposite.
{anchorMode && (
{constructIds.length !== 1 ? (

An anchored run uses exactly one target construct above. Select a single target to choose its opposite pole.

) : ( <> c.id !== constructIds[0])} selectedIds={oppositeId ? [oppositeId] : []} onToggle={(id) => setOppositeId((cur) => (cur === id ? "" : id))} /> {oppositeConstruct && (
{oppositeConstruct.name} {" "} {oppositeConstruct.items.length} item {oppositeConstruct.items.length === 1 ? "" : "s"} · opposite pole
    {oppositeConstruct.items.map((item, i) => (
  • {item}
  • ))}
)}
Similarity metric
)}
)} {constructFormTab && ( { const list = await api.listConstructs(); setConstructs(list); toggleConstruct(created.id); setConstructFormTab(null); }} onError={setError} /> )}
{/* Step 3 - language, model + run */}

3Language, model & run

Embeddings run locally via sentence-transformers; model and language are recorded in the run metadata. If the corpus doesn't match the selected language or the model doesn't support it, you'll get a warning - never a silent result.

{/* Disabled-until-valid with the reason inline (same pattern as the construct form's Save) - a dead button with no visible cause is the top tester confusion. */} {!canRun && !running && !fileMissing && (

To run, still needed:{" "} {[ !corpusId && "a dataset (Step 1)", corpusId && !textColumn && "a text column (Step 1)", constructIds.length === 0 && "at least one construct (Step 2)", anchorMode && constructIds.length > 1 && "a single target construct for the anchor (Step 2)", anchorMode && constructIds.length === 1 && !oppositeId && "a contrasting construct (Step 2)", ] .filter(Boolean) .join(", ")} .

)} {auth && !auth.signed_in && auth.usage?.max_runs_per_day != null && (

{Math.min(auth.usage.runs_used_today, auth.usage.max_runs_per_day)} of{" "} {auth.usage.max_runs_per_day} free runs used today {auth.usage.runs_used_today >= auth.usage.max_runs_per_day ? " - sign in (top right) to keep running." : "."}

)} {auth?.signed_in && auth.usage?.max_saved_runs != null && (

{auth.usage.saved_runs} of {auth.usage.max_saved_runs} saved runs used.

)} {models.find((m) => m.id === modelName)?.warnings?.map((w, i) => (

⚠ {w}

))}
{/* Jobs */} {jobs.length > 0 && (

Runs

{jobs.map((j) => ( ))}
Started Corpus Construct Model Lang Status
{(j.started_at || j.created_at).replace("T", " ").slice(0, 16)} {j.corpus_filename} {(j.construct_names?.length ? j.construct_names : [j.construct_name]).join(" + ")} {j.model_name} {j.language} {j.status === "running" ? (
) : ( {j.status} )} {j.status === "failed" && (
{j.error.split("\n").pop()}
)}
{j.status === "completed" && ( )}
)} ); } const REVERSE_SUFFIX = /\s*\((r|rev|reversed)\)\s*$/i; function NewConstructForm({ auth, constructs, source, onSourceChange, onCreated, onError }) { const [name, setName] = useState(""); const [reference, setReference] = useState(""); const [description, setDescription] = useState(""); const [itemsText, setItemsText] = useState(""); const [saving, setSaving] = useState(false); const [parsing, setParsing] = useState(false); const [parseNotes, setParseNotes] = useState([]); // AI drafting (ITEM_GENERATION.md): genInfo is the provenance stamp echoed // back on save; it survives manual edits (the seed was AI) but is cleared // when items come from a file upload instead. const [nItems, setNItems] = useState(10); const [generating, setGenerating] = useState(false); const [genInfo, setGenInfo] = useState(null); const [genNotes, setGenNotes] = useState(""); const [genUsage, setGenUsage] = useState(null); const itemFileRef = useRef(null); const itemsRef = useRef(null); const setSource = onSourceChange; // Quota shown from the first tab-open (auth/me carries it), replaced by the // fresher count from each generate response. const quotaInfo = genUsage || (auth?.usage?.max_generations_per_day != null ? { used: auth.usage.generations_used_today, max: auth.usage.max_generations_per_day, } : null); // Live drafting-model facts (from /api/auth/me) for the info tooltip. The // model varies by deployment (Claude vs the interim open model), so this is // read from the API, never hardcoded in the UI. const gen = auth?.generation; const genModelLabel = gen?.available ? gen.model_label || gen.model : null; const genAria = genModelLabel ? `AI item drafting uses ${genModelLabel}${ gen.provider_label ? ` (${gen.provider_label})` : "" }, prompt version ${gen.prompt_version}. Positively-keyed items only, ${ gen.n_items_min } to ${gen.n_items_max} per draft, ${ gen.max_generations_per_day } drafts per day. Not a validated scale; the model, version, and date are recorded in each run's metadata.` : "AI item drafting uses a hosted language model. Not a validated scale; the model, version, and date are recorded in each run's metadata."; // Simple library name-match (v1 guardrail, PI-approved): if a validated // scale with a similar name exists, say so before anyone generates. const nameQuery = name.trim().toLowerCase(); const libraryMatch = nameQuery.length >= 3 ? (constructs || []).find( (c) => c.is_seed && (c.name.toLowerCase().includes(nameQuery) || nameQuery.includes(c.name.toLowerCase())) ) : null; async function handleGenerate() { if (!name.trim() || !description.trim()) { onError( "AI drafting needs the construct's name and a few sentences explaining " + "what it means (the Description field)." ); return; } setGenerating(true); setGenNotes(""); try { const resp = await api.generateConstructItems({ name: name.trim(), description: description.trim(), n_items: nItems, }); setItemsText(resp.items.join("\n")); setGenInfo({ ...resp.generation, n: resp.items.length }); setGenNotes(resp.notes || ""); setGenUsage({ used: resp.generations_used_today, max: resp.max_generations_per_day, }); // The drafted items land in the textarea below the controls - scroll // there so it's obvious they arrived (PI feedback: "how can they see // all 10 items generated under the hood?"). setTimeout(() => { itemsRef.current?.scrollIntoView({ behavior: "smooth", block: "center" }); itemsRef.current?.focus({ preventScroll: true }); }, 50); } catch (err) { onError(err.message); } finally { setGenerating(false); } } // Convention shared with the file parser and the lab's own spreadsheets: // a trailing (R) marks a reverse-scored item. function parseLines() { return itemsText .split("\n") .map((s) => s.trim()) .filter(Boolean) .map((line) => ({ text: line.replace(REVERSE_SUFFIX, "").trim(), reverse: REVERSE_SUFFIX.test(line), })); } async function handleItemFile(e) { const file = e.target.files?.[0]; if (!file) return; setParsing(true); setParseNotes([]); try { const parsed = await api.parseConstructFile(file); setItemsText( parsed.items .map((i) => (i.reverse_scored ? `${i.text} (R)` : i.text)) .join("\n") ); setGenInfo(null); // items now come from the file, not an AI draft setGenNotes(""); if (!name.trim() && parsed.suggested_name) setName(parsed.suggested_name); setParseNotes(parsed.warnings || []); } catch (err) { onError(err.message); } finally { setParsing(false); if (itemFileRef.current) itemFileRef.current.value = ""; } } async function save(e) { e.preventDefault(); const parsed = parseLines(); if (!name.trim() || parsed.length === 0) { onError("A custom construct needs a name and at least one item (one per line)."); return; } setSaving(true); try { const created = await api.createConstruct({ name: name.trim(), reference, description: description.trim(), items: parsed.map((i) => i.text), reverse_scored: parsed.map((i) => i.reverse), // provenance stamp when AI-drafted (schema fields only); `items` is // the ORIGINAL draft - the audit record of what the AI produced // before the researcher's edits generation: genInfo ? { model: genInfo.model, prompt_version: genInfo.prompt_version, generated_at: genInfo.generated_at, items: genInfo.items, } : undefined, }); onCreated(created); } catch (err) { onError(err.message); } finally { setSaving(false); } } const nReverse = parseLines().filter((i) => i.reverse).length; const hasItems = parseLines().length > 0; // On the AI path the items box appears once there is something to review - // an empty box + disabled Save before drafting is just noise. const showItemsBox = source !== "ai" || Boolean(itemsText.trim() || genInfo); const SOURCE_CARDS = [ ["type", "Type or paste", "Enter a scale's items yourself, one per line"], ["upload", "Upload a file", "CSV/XLSX with an item column - review, then save"], ...(auth?.generation_available ? [["ai", "Draft with AI", "From a name + description, when no validated scale exists"]] : []), ]; return (
New construct
{/* The three paths as one visible choice (PI: "make the options explicit") - each card shows only its own fields below. */}
{SOURCE_CARDS.map(([key, title, desc]) => ( ))}
{source === "ai" && !auth?.signed_in ? (

Sign in (top right) to draft items with AI - accounts are free.

) : ( <>
{source !== "ai" && (
)}
{source === "ai" && ( <> {/* Live model details on demand (task: hover the i for version info). The label + tooltip read from auth.generation, so they always match the model this instance actually uses. */}
Drafted by{" "} {genModelLabel || "a hosted AI language model"} {/* Focusable span, not a