378 lines
12 KiB
TypeScript
378 lines
12 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import {
|
|
reviseResearchArtifactSchema,
|
|
reviseResearchHypothesisSchema,
|
|
} from '@stock-bot/stock-config/research';
|
|
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
|
import type {
|
|
ResearchArtifact,
|
|
ResearchArtifactRevision,
|
|
ResearchContentOrigin,
|
|
ResearchHypothesis,
|
|
ResearchHypothesisRevision,
|
|
} from '@stock-bot/types';
|
|
import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning';
|
|
import { downloadJsonText } from '@/utils/downloadJsonText';
|
|
import { evidenceReferences } from '../services/evidenceReferences';
|
|
import { researchApi, ResearchApiError } from '../services/researchApi';
|
|
|
|
type Entry =
|
|
| { kind: 'hypothesis'; entity: ResearchHypothesis; revisions: ResearchHypothesisRevision[] }
|
|
| { kind: 'artifact'; entity: ResearchArtifact; revisions: ResearchArtifactRevision[] };
|
|
export interface ResearchEntryWorkflowOptions {
|
|
projectId: string;
|
|
id: string;
|
|
kind: 'hypothesis' | 'artifact';
|
|
revisionId: string | null;
|
|
archived: boolean;
|
|
writeBlocked: string;
|
|
onRefresh: () => void;
|
|
onDirty: (dirty: boolean) => void;
|
|
}
|
|
/** Owns one mounted entry's reads, draft and acknowledged writes. The parent keys
|
|
* this hook's component by entry/revision so late completions cannot claim another draft. */
|
|
export function useResearchEntry({
|
|
projectId,
|
|
id,
|
|
kind,
|
|
revisionId,
|
|
archived,
|
|
writeBlocked,
|
|
onRefresh,
|
|
onDirty,
|
|
}: ResearchEntryWorkflowOptions) {
|
|
const mounted = useRef(false);
|
|
const pending = useRef(false);
|
|
const [entry, setEntry] = useState<Entry | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [loadError, setLoadError] = useState('');
|
|
const [reload, setReload] = useState(0);
|
|
const [editing, setEditing] = useState(false);
|
|
const [title, setTitle] = useState('');
|
|
const [body, setBody] = useState('');
|
|
const [criteria, setCriteria] = useState('');
|
|
const [origin, setOrigin] = useState<ResearchContentOrigin>('human');
|
|
const [saving, setSaving] = useState(false);
|
|
const [error, setError] = useState('');
|
|
const [blocked, setBlocked] = useState(false);
|
|
const [archiveUncertain, setArchiveUncertain] = useState(false);
|
|
const [downloadError, setDownloadError] = useState('');
|
|
useUnsavedWarning(editing);
|
|
useEffect(() => {
|
|
onDirty(editing);
|
|
}, [editing, onDirty]);
|
|
useEffect(() => {
|
|
mounted.current = true;
|
|
return () => {
|
|
mounted.current = false;
|
|
onDirty(false);
|
|
};
|
|
}, [onDirty]);
|
|
useEffect(() => {
|
|
let current = true;
|
|
const controller = new AbortController();
|
|
setLoading(true);
|
|
setLoadError('');
|
|
setDownloadError('');
|
|
setEntry(null);
|
|
const load = async (): Promise<Entry> => {
|
|
if (kind === 'hypothesis') {
|
|
const [{ hypothesis }, { revisions }] = await Promise.all([
|
|
researchApi.getHypothesis(id, controller.signal),
|
|
researchApi.hypothesisRevisions(id, controller.signal),
|
|
]);
|
|
if (
|
|
hypothesis.id !== id ||
|
|
hypothesis.projectId !== projectId ||
|
|
hypothesis.latestRevision.hypothesisId !== id ||
|
|
revisions.some(item => item.hypothesisId !== id)
|
|
) {
|
|
throw new Error(
|
|
'Hypothesis does not belong to this project or its history is inconsistent.'
|
|
);
|
|
}
|
|
return { kind, entity: hypothesis, revisions };
|
|
}
|
|
const [{ artifact }, { revisions }] = await Promise.all([
|
|
researchApi.getArtifact(id, controller.signal),
|
|
researchApi.artifactRevisions(id, controller.signal),
|
|
]);
|
|
if (
|
|
artifact.id !== id ||
|
|
artifact.projectId !== projectId ||
|
|
artifact.latestRevision.artifactId !== id ||
|
|
revisions.some(item => item.artifactId !== id)
|
|
) {
|
|
throw new Error('Artifact does not belong to this project or its history is inconsistent.');
|
|
}
|
|
return { kind, entity: artifact, revisions };
|
|
};
|
|
void load()
|
|
.then(result => {
|
|
if (revisionId && !result.revisions.some(item => item.id === revisionId)) {
|
|
throw new Error('The requested revision does not belong to this research entry.');
|
|
}
|
|
if (current) {
|
|
setEntry(result);
|
|
}
|
|
})
|
|
.catch(cause => {
|
|
if (current) {
|
|
setLoadError(cause instanceof Error ? cause.message : 'Could not load research entry');
|
|
}
|
|
})
|
|
.finally(() => {
|
|
if (current) {
|
|
setLoading(false);
|
|
}
|
|
});
|
|
return () => {
|
|
current = false;
|
|
controller.abort();
|
|
};
|
|
}, [id, kind, projectId, revisionId, reload]);
|
|
const revision = revisionId
|
|
? entry?.revisions.find(item => item.id === revisionId)
|
|
: entry?.entity.latestRevision;
|
|
const download = () => {
|
|
if (loading || saving || !entry || !revision) {
|
|
return;
|
|
}
|
|
setDownloadError('');
|
|
try {
|
|
const record = {
|
|
kind: 'research-revision-export/v1',
|
|
projectId,
|
|
entry:
|
|
entry.kind === 'hypothesis'
|
|
? { id: entry.entity.id, kind: 'hypothesis' }
|
|
: {
|
|
id: entry.entity.id,
|
|
kind: entry.entity.kind,
|
|
hypothesisRevisionId: entry.entity.hypothesisRevisionId,
|
|
},
|
|
revision,
|
|
};
|
|
downloadJsonText(JSON.stringify(record), `research-${entry.entity.id}-${revision.id}.json`);
|
|
} catch (cause) {
|
|
setDownloadError(
|
|
cause instanceof Error ? cause.message : 'Could not download saved revision'
|
|
);
|
|
}
|
|
};
|
|
const readonly =
|
|
archived || Boolean(writeBlocked) || entry?.entity.archived || Boolean(revisionId);
|
|
const beginEdit = () => {
|
|
if (!revision || readonly || archiveUncertain) {
|
|
return;
|
|
}
|
|
setTitle(revision.title);
|
|
setBody('proposition' in revision ? revision.proposition : revision.body);
|
|
setCriteria('validationCriteria' in revision ? revision.validationCriteria : '');
|
|
setOrigin(revision.contentOrigin);
|
|
setError('');
|
|
setBlocked(false);
|
|
setEditing(true);
|
|
};
|
|
const save = async (event: React.FormEvent) => {
|
|
event.preventDefault();
|
|
if (
|
|
!entry ||
|
|
!revision ||
|
|
pending.current ||
|
|
readonly ||
|
|
blocked ||
|
|
archiveUncertain ||
|
|
!title.trim() ||
|
|
(kind === 'hypothesis' && !body.trim())
|
|
) {
|
|
return;
|
|
}
|
|
pending.current = true;
|
|
setSaving(true);
|
|
setError('');
|
|
try {
|
|
let saved: ResearchHypothesis | ResearchArtifact;
|
|
let matches: boolean;
|
|
if (entry.kind === 'hypothesis') {
|
|
const input = reviseResearchHypothesisSchema.parse({
|
|
expectedRevision: entry.entity.latestRevision.ordinal,
|
|
title,
|
|
proposition: body,
|
|
validationCriteria: criteria,
|
|
contentOrigin: origin,
|
|
});
|
|
({ hypothesis: saved } = await researchApi.reviseHypothesis(id, input));
|
|
matches =
|
|
saved.latestRevision.hypothesisId === id &&
|
|
saved.latestRevision.title === input.title &&
|
|
saved.latestRevision.proposition === input.proposition &&
|
|
saved.latestRevision.validationCriteria === input.validationCriteria;
|
|
} else {
|
|
const input = reviseResearchArtifactSchema.parse({
|
|
expectedRevision: entry.entity.latestRevision.ordinal,
|
|
title,
|
|
body,
|
|
contentOrigin: origin,
|
|
evidence: evidenceReferences(entry.entity.latestRevision.evidence),
|
|
...(entry.entity.latestRevision.source !== undefined
|
|
? { source: entry.entity.latestRevision.source }
|
|
: {}),
|
|
});
|
|
({ artifact: saved } = await researchApi.reviseArtifact(id, input));
|
|
matches =
|
|
saved.kind === entry.entity.kind &&
|
|
saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId &&
|
|
saved.latestRevision.artifactId === id &&
|
|
saved.latestRevision.title === input.title &&
|
|
saved.latestRevision.body === input.body &&
|
|
saved.latestRevision.evidenceState === (input.evidence.length ? 'referenced' : 'none') &&
|
|
Array.isArray(saved.latestRevision.evidence) &&
|
|
canonicalStrategyJson(evidenceReferences(saved.latestRevision.evidence)) ===
|
|
canonicalStrategyJson(input.evidence) &&
|
|
canonicalStrategyJson(saved.latestRevision.source ?? null) ===
|
|
canonicalStrategyJson(entry.entity.latestRevision.source ?? null);
|
|
}
|
|
if (
|
|
!matches ||
|
|
saved.id !== id ||
|
|
saved.projectId !== projectId ||
|
|
saved.ownerPrincipal !== entry.entity.ownerPrincipal ||
|
|
saved.latestRevision.id === entry.entity.latestRevision.id ||
|
|
saved.latestRevision.ordinal !== entry.entity.latestRevision.ordinal + 1 ||
|
|
saved.latestRevision.contentOrigin !== origin ||
|
|
saved.latestRevision.validationState !== 'unvalidated'
|
|
) {
|
|
throw new ResearchApiError('The saved revision response could not be verified.', null);
|
|
}
|
|
if (mounted.current) {
|
|
setEditing(false);
|
|
setReload(value => value + 1);
|
|
onRefresh();
|
|
}
|
|
} catch (cause) {
|
|
if (mounted.current) {
|
|
setError(cause instanceof Error ? cause.message : 'Could not save revision');
|
|
setBlocked(!(cause instanceof ResearchApiError) || cause.status === 409 || cause.ambiguous);
|
|
}
|
|
} finally {
|
|
pending.current = false;
|
|
if (mounted.current) {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
};
|
|
const archive = async () => {
|
|
if (
|
|
!entry ||
|
|
archived ||
|
|
Boolean(writeBlocked) ||
|
|
pending.current ||
|
|
archiveUncertain ||
|
|
!confirmDiscard(editing) ||
|
|
!window.confirm(`${entry.entity.archived ? 'Restore' : 'Archive'} this research entry?`)
|
|
) {
|
|
return;
|
|
}
|
|
pending.current = true;
|
|
setSaving(true);
|
|
setError('');
|
|
try {
|
|
const targetArchived = !entry.entity.archived;
|
|
let saved: ResearchHypothesis | ResearchArtifact;
|
|
let matches: boolean;
|
|
if (entry.kind === 'hypothesis') {
|
|
({ hypothesis: saved } = await researchApi.archiveHypothesis(id, targetArchived));
|
|
matches = saved.latestRevision.hypothesisId === id;
|
|
} else {
|
|
({ artifact: saved } = await researchApi.archiveArtifact(id, targetArchived));
|
|
matches =
|
|
saved.latestRevision.artifactId === id &&
|
|
saved.kind === entry.entity.kind &&
|
|
saved.hypothesisRevisionId === entry.entity.hypothesisRevisionId;
|
|
}
|
|
// Archive has no narrative revision precondition. A concurrent edit may be newer.
|
|
if (
|
|
!matches ||
|
|
saved.id !== id ||
|
|
saved.projectId !== projectId ||
|
|
saved.ownerPrincipal !== entry.entity.ownerPrincipal ||
|
|
saved.archived !== targetArchived ||
|
|
saved.latestRevision.validationState !== 'unvalidated'
|
|
) {
|
|
throw new ResearchApiError('The archive response could not be verified.', null);
|
|
}
|
|
if (mounted.current) {
|
|
setEditing(false);
|
|
setReload(value => value + 1);
|
|
onRefresh();
|
|
}
|
|
} catch (cause) {
|
|
if (mounted.current) {
|
|
setError(cause instanceof Error ? cause.message : 'Could not update archive state');
|
|
setArchiveUncertain(!(cause instanceof ResearchApiError) || cause.ambiguous);
|
|
}
|
|
} finally {
|
|
pending.current = false;
|
|
if (mounted.current) {
|
|
setSaving(false);
|
|
}
|
|
}
|
|
};
|
|
const discardArchiveDraft = () => {
|
|
if (confirmDiscard(editing)) {
|
|
setLoading(true);
|
|
setEditing(false);
|
|
setArchiveUncertain(false);
|
|
setBlocked(false);
|
|
setError('');
|
|
setReload(value => value + 1);
|
|
onRefresh();
|
|
}
|
|
};
|
|
const discardRevisionAndReload = () => {
|
|
if (confirmDiscard(true)) {
|
|
setEditing(false);
|
|
setBlocked(false);
|
|
setError('');
|
|
setReload(value => value + 1);
|
|
onRefresh();
|
|
}
|
|
};
|
|
const discardRevisionDraft = () => {
|
|
if (confirmDiscard(true)) {
|
|
setEditing(false);
|
|
setError('');
|
|
}
|
|
};
|
|
const retry = () => setReload(value => value + 1);
|
|
return {
|
|
entry,
|
|
revision,
|
|
loading,
|
|
loadError,
|
|
downloadError,
|
|
download,
|
|
saving,
|
|
readonly,
|
|
archiveUncertain,
|
|
editing,
|
|
title,
|
|
setTitle,
|
|
body,
|
|
setBody,
|
|
criteria,
|
|
setCriteria,
|
|
origin,
|
|
setOrigin,
|
|
save,
|
|
error,
|
|
blocked,
|
|
beginEdit,
|
|
archive,
|
|
retry,
|
|
discardArchiveDraft,
|
|
discardRevisionAndReload,
|
|
discardRevisionDraft,
|
|
};
|
|
}
|