import { useCallback, useEffect, useRef, useState } from 'react'; import { Link, useParams, useSearchParams } from 'react-router-dom'; import { updateResearchProjectSchema } from '@stock-bot/stock-config/research'; import type { ResearchArtifact, ResearchHypothesis, ResearchProject, StrategyRecord, } from '@stock-bot/types'; import { Card } from '@/components/ui/Card'; import { actionClass, fieldClass } from '../strategies/components/StrategyParameterForm'; import { confirmDiscard, useUnsavedWarning } from '../strategies/components/useUnsavedWarning'; import { strategyApi } from '../strategies/services/strategyApi'; import { CreateResearchEntry } from './components/CreateResearchEntry'; import { ResearchEntry } from './components/ResearchEntry'; import { researchApi, ResearchApiError } from './services/researchApi'; type Section = 'project' | 'strategies' | 'hypotheses' | 'artifacts' | 'catalog'; const initialErrors: Record = { project: '', strategies: '', hypotheses: '', artifacts: '', catalog: '', }; export function ResearchProjectPage() { const { projectId } = useParams(); return projectId ? ( ) : (

Missing research project.

); } function ProjectWorkspace({ projectId }: { projectId: string }) { const [params, setParams] = useSearchParams(); const mounted = useRef(false); const pending = useRef(false); const [project, setProject] = useState(null); const [strategies, setStrategies] = useState([]); const [catalog, setCatalog] = useState([]); const [hypotheses, setHypotheses] = useState([]); const [artifacts, setArtifacts] = useState([]); const [errors, setErrors] = useState(initialErrors); const [loading, setLoading] = useState(true); const [refresh, setRefresh] = useState(0); const [selectionEpoch, setSelectionEpoch] = useState(0); const [showArchived, setShowArchived] = useState(false); const [editing, setEditing] = useState<{ title: string; description: string; expectedRevision: number; } | null>(null); const [creator, setCreator] = useState<'hypothesis' | 'note' | null>(null); const [createDirty, setCreateDirty] = useState(false); const [entryDirty, setEntryDirty] = useState(false); const [strategyId, setStrategyId] = useState(''); const [saving, setSaving] = useState(false); const [mutationError, setMutationError] = useState(''); const [conflict, setConflict] = useState(false); const dirty = Boolean(editing) || createDirty || entryDirty; useUnsavedWarning(dirty); const reload = useCallback(() => setRefresh(value => value + 1), []); useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); useEffect(() => { let current = true; const controller = new AbortController(); setLoading(true); setErrors(initialErrors); const failed = (section: Section, cause: unknown) => { if (current) { setErrors(previous => ({ ...previous, [section]: cause instanceof Error ? cause.message : `Could not load ${section}`, })); } }; void Promise.allSettled([ researchApi .getProject(projectId, controller.signal) .then(({ project: value }) => { if (value.id !== projectId) { throw new Error('The response belongs to another project.'); } if (current) { setProject(value); } }) .catch(cause => failed('project', cause)), researchApi .listStrategies(projectId, controller.signal) .then(({ strategies: value }) => { if (current) { setStrategies(value); } }) .catch(cause => failed('strategies', cause)), researchApi .listHypotheses(projectId, true, controller.signal) .then(({ hypotheses: value }) => { if (value.some(item => item.projectId !== projectId)) { throw new Error('Hypotheses belong to another project.'); } if (current) { setHypotheses(value); } }) .catch(cause => failed('hypotheses', cause)), researchApi .listArtifacts(projectId, true, controller.signal) .then(({ artifacts: value }) => { if (value.some(item => item.projectId !== projectId)) { throw new Error('Research entries belong to another project.'); } if (current) { setArtifacts(value); } }) .catch(cause => failed('artifacts', cause)), strategyApi .list(controller.signal) .then(({ strategies: value }) => { if (current) { setCatalog(value); } }) .catch(cause => failed('catalog', cause)), ]).finally(() => { if (current) { setLoading(false); } }); return () => { current = false; controller.abort(); }; }, [projectId, refresh]); const select = (kind: 'hypothesis' | 'artifact', id: string, revisionId?: string | null) => { if (!confirmDiscard(dirty)) { return; } setEditing(null); setCreator(null); setCreateDirty(false); setEntryDirty(false); if (params.get(kind) === id && params.get('revision') === (revisionId ?? null)) { setSelectionEpoch(value => value + 1); } setParams({ [kind]: id, ...(revisionId ? { revision: revisionId } : {}) }); }; const mutateProject = async (archived?: boolean) => { if ( !project || loading || pending.current || errors.project || conflict || (archived === undefined && !editing) ) { return; } if ( archived !== undefined && (!confirmDiscard(dirty) || !window.confirm(`${archived ? 'Archive' : 'Restore'} this project?`)) ) { return; } pending.current = true; setSaving(true); setMutationError(''); try { const body = archived === undefined ? editing : { expectedRevision: project.revision, archived }; if (!body) { return; } const input = updateResearchProjectSchema.parse(body); const { project: updated } = await researchApi.updateProject(projectId, input); if ( updated.id !== projectId || updated.ownerPrincipal !== project.ownerPrincipal || updated.revision !== input.expectedRevision + 1 || updated.title !== (input.title ?? project.title) || updated.description !== (input.description ?? project.description) || updated.archived !== (input.archived ?? project.archived) ) { throw new ResearchApiError('The saved project update could not be verified.', null); } if (mounted.current) { setProject(updated); setEditing(null); setConflict(false); if (archived !== undefined) { setCreator(null); setCreateDirty(false); setEntryDirty(false); setSelectionEpoch(value => value + 1); } reload(); } } catch (cause) { if (mounted.current) { setMutationError(cause instanceof Error ? cause.message : 'Could not update project'); setConflict( !(cause instanceof ResearchApiError) || cause.status === 409 || cause.ambiguous ); } } finally { pending.current = false; if (mounted.current) { setSaving(false); } } }; const membership = async (id: string, remove: boolean) => { if ( !project || project.archived || loading || saving || pending.current || editing || errors.project || errors.strategies || conflict ) { return; } pending.current = true; setSaving(true); setMutationError(''); try { if (remove) { await researchApi.unlinkStrategy(projectId, id); } else { await researchApi.linkStrategy(projectId, id); } if (mounted.current) { setStrategyId(''); reload(); } } catch (cause) { if (mounted.current) { setMutationError( cause instanceof Error ? cause.message : 'Could not update linked strategies' ); reload(); } } finally { pending.current = false; if (mounted.current) { setSaving(false); } } }; const discardAndReloadProject = () => { if (saving || !confirmDiscard(dirty)) { return; } setLoading(true); setEditing(null); setCreator(null); setCreateDirty(false); setEntryDirty(false); setSelectionEpoch(value => value + 1); setConflict(false); setMutationError(''); reload(); }; const hypothesisId = params.get('hypothesis'); const artifactId = params.get('artifact'); const selection = hypothesisId && !artifactId ? { kind: 'hypothesis' as const, id: hypothesisId } : artifactId && !hypothesisId ? { kind: 'artifact' as const, id: artifactId } : null; const visibleHypotheses = hypotheses.filter( item => showArchived || project?.archived || !item.archived ); const visibleArtifacts = artifacts.filter( item => showArchived || project?.archived || !item.archived ); const canWrite = project && !project.archived && !errors.project && !loading && !saving && !conflict; const projectWriteBlocked = conflict ? 'Review the saved project before another update.' : saving ? 'Updating project.' : loading ? 'Refreshing project.' : errors.project ? 'Project status could not be verified.' : ''; const sectionError = (section: Section) => errors[section] && (

{section}: {errors[section]}

); return (
{ if ((event.target as HTMLElement).closest('a') && !confirmDiscard(dirty)) { event.preventDefault(); event.stopPropagation(); } }} >
Research projects Backtesting workbench
{loading &&

Loading research workspace...

} {sectionError('project')} {project && ( <>

{project.title}

{project.description || 'No description yet.'}

Project revision {project.revision} · Owner: {project.ownerPrincipal} · Updated{' '} {project.updatedAt}

{project.archived && (

Archived project. Records, history and evidence remain available; restore the project to make changes.

)} {!editing && canWrite && ( )}{' '} {editing && !project.archived && (
{ event.preventDefault(); void mutateProject(); }} >