Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {exploreFindingCopy} from "./explore-finding-copy";
import {AlertCircle, ArrowLeft, ArrowRight, Circle, CircleHelp, FlaskConical, GitBranch, RefreshCw, Search} from "lucide-react";
import {Fragment, useEffect, useId, useLayoutEffect, useMemo, useRef, useState} from "react";
import {defaultParseSearch} from "@tanstack/react-router";
import {ResearchRecordSearch} from "./research-record-browser";
import {ResearchRecordSearch, useResearchRecordsLocation} from "./research-record-browser";
import {ResearchAnalysisButton, ResearchAnalysisPanel, ResearchAnalysisStatus, ResearchCitationPanel, ResearchProgressSummary, ResearchReportSummary, ResearchCaseReading, useResearchAnalysis} from "./goal-research-analysis";
import {buildExploreTimeline, latestExploreFindingInPhase, parseExploreFindingSections, type TimelineFinding} from "../../../../../../loopx/control_plane/presentation/explore_timeline.js";
import {GoalResearchTimeline} from "./goal-research-timeline";
Expand Down Expand Up @@ -122,7 +122,9 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist
const [selection, setSelection] = useState(() => selectedFromUrl(goalId));
// The same finding can be read directly or as part of its complete question.
const questionExpanded = selection.question ?? !selection.finding;
const [recordsOpen, setRecordsOpen] = useState(false);
const recordReading = useResearchRecordsLocation(historySource);
const recordsOpen = recordReading.value.open;
const setRecordsOpen = (open: boolean) => recordReading.update({open});
const records = useRef<HTMLDetailsElement>(null);
const [lens, setLens] = useState<Lens>(() => viewFromUrl(goalId).lens);
const [requestedPhase, setPhase] = useState<number | null>(() => viewFromUrl(goalId).phase);
Expand Down Expand Up @@ -725,7 +727,7 @@ export function GoalResearchHistory({goalId, originalGoalId = goalId, preferHist
{value?.unknownKindCount ? <p className="research-history-note">{zh ? "未识别类型保留于已读记录" : "Unrecognized types remain in loaded records"} · {value.unknownKindCount}</p> : null}
</ContextHelp> : null}
{value?.events.length ? <details ref={records} className="research-history-all-records" open={recordsOpen} onToggle={event => setRecordsOpen(event.currentTarget.open)}><summary>{zh ? "全部已读记录" : "All loaded records"} · {value.events.length}</summary>
{recordsOpen ? <ResearchRecordSearch key={JSON.stringify([goalId, readSourceUrl])} goalId={originalGoalId} events={history.canonical?.events ?? []}
{recordsOpen ? <ResearchRecordSearch key={JSON.stringify([goalId, readSourceUrl])} reading={recordReading} goalId={originalGoalId} events={history.canonical?.events ?? []}
nodes={history.canonical?.nodes ?? []}
displayEvents={currentDisplay && !originalDisplay ? value.events : undefined}
displaySections={currentDisplay && !originalDisplay ? displayProjection.sections : undefined}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,36 +1,78 @@
import {ResearchRecordComparison} from "./research-record-comparison";
import {CircleHelp, TriangleAlert} from "lucide-react";
import {ContextHelp} from "./context-help";
import {useMemo, useState, type ReactNode} from "react";
import {useEffect, useMemo, useRef, useState, type ReactNode} from "react";
import type {ExploreHistoryEvent, ExploreHistoryNode} from "../../../../../../loopx/control_plane/presentation/explore_history.ts";
import {researchRecordGroups, searchResearchRecords, type ResearchRecordDisplay} from "./research-record-search";
import {readResearchRecordsLocation, writeResearchRecordsLocation, researchRecordGroups, searchResearchRecords, type ResearchRecordDisplay, type ResearchRecordsLocation} from "./research-record-search";
import {exportResearchRecords} from "./research-record-export";
import {exportResearchReport} from "./research-record-report";
import {downloadReport} from "./report-download";

/** Record browsing updates the current history entry. Goal and source
* navigation create the entries that Back/Forward restores. */
export function useResearchRecordsLocation(scope: string) {
const read = () => readResearchRecordsLocation(new URLSearchParams(window.location.search), scope);
const [location, setLocation] = useState(() => ({scope, value: read(), navigation: 0}));
const value = location.scope === scope ? location.value : read();
const current = useRef(value);
current.current = value;
useEffect(() => {
const changed = () => {current.current = read(); setLocation(previous => ({scope, value: current.current, navigation: previous.navigation + 1}));};
changed(); window.addEventListener("popstate", changed);
return () => window.removeEventListener("popstate", changed);
}, [scope]);
const update = (patch: Partial<ResearchRecordsLocation>) => {
const next = {...current.current, ...patch};
if (JSON.stringify(next) === JSON.stringify(current.current)) return;
current.current = next;
const url = new URL(window.location.href);
url.search = writeResearchRecordsLocation(url.searchParams, scope, next).toString();
window.history.replaceState(window.history.state, "", url);
setLocation(previous => ({scope, value: next, navigation: previous.navigation}));
};
return {value, update, navigation: location.navigation};
}

/** Local read controls over the existing validated history snapshot. */
export function ResearchRecordSearch({goalId, events, nodes, displayEvents, displaySections, renderBody, renderSummary, complete, stale, busy, zh, stateLabel, timeLabel}: {
export function ResearchRecordSearch({goalId, events, nodes, displayEvents, displaySections, renderBody, renderSummary, complete, stale, busy, zh, stateLabel, timeLabel, reading}: {
goalId: string;
displayEvents?: readonly ExploreHistoryEvent[]; renderBody?: (event: ExploreHistoryEvent) => ReactNode;
displaySections?: ResearchRecordDisplay["sections"];
renderSummary?: (event: ExploreHistoryEvent) => ReactNode;
events: readonly ExploreHistoryEvent[]; nodes: readonly ExploreHistoryNode[]; complete: boolean; stale: boolean; busy: boolean; zh: boolean;
stateLabel: (status: string) => string; timeLabel: (at: string) => string;
reading: ReturnType<typeof useResearchRecordsLocation>;
}) {
const [query, setQuery] = useState("");
const [status, setStatus] = useState("");
const [limit, setLimit] = useState(50);
const {query, status, limit, expanded} = reading.value;
const root = useRef<HTMLDivElement>(null);
const focusNavigation = useRef(-1);
const [downloadFailed, setDownloadFailed] = useState(false);
const [format, setFormat] = useState("json");
const displayed = useMemo(() => new Map(displayEvents?.map(event => [event.event_id, event])), [displayEvents]);
const display = useMemo(() => ({events: displayed, sections: displaySections}), [displayed, displaySections]);
const matches = useMemo(() => searchResearchRecords(events, query, status, display), [events, query, status, display]);
const groups = useMemo(() => researchRecordGroups(matches, complete ? nodes : []), [matches, nodes, complete]);
const allGroups = useMemo(() => researchRecordGroups(events, complete ? nodes : []), [events, nodes, complete]);
useEffect(() => {
if (!complete || busy || focusNavigation.current === reading.navigation) return;
focusNavigation.current = reading.navigation;
const row = [...(root.current?.querySelectorAll<HTMLElement>("[data-research-record]") ?? [])]
.find(element => expanded.includes(element.dataset.researchRecord!));
const target = row?.querySelector<HTMLElement>("summary");
target?.focus({preventScroll: true}); target?.scrollIntoView({block: "nearest"});
}, [complete, busy, reading.navigation, groups, expanded]);
const missing = complete && expanded.some(id => !allGroups.some(group => group.id === id));
const statuses = [...new Set(events.map(event => event.status).filter(Boolean))].sort();
const groupCount = zh ? `${groups.length} 个条目` : `${groups.length} ${groups.length === 1 ? "entry" : "entries"}`;
const countLabel = zh ? `匹配 ${matches.length} / ${events.length} 条已读记录 · ${groupCount}` : `${matches.length} matches in ${events.length} loaded records · ${groupCount}`;
const readState = busy ? (zh ? "读取中" : "Reading") : stale ? (zh ? "刷新失败" : "Refresh failed") : "";
const reset = () => {setQuery(""); setStatus(""); setLimit(50);};
const updateFilters = (filters: Partial<Pick<ResearchRecordsLocation, "query" | "status">>) => {
reading.update({...filters, limit: 50, expanded: []});
};
const toggle = (id: string, open: boolean) => {
if (expanded.includes(id) === open) return;
reading.update({expanded: open ? [...expanded, id] : expanded.filter(value => value !== id)});
};
const originalContent = (event: ExploreHistoryEvent) => {
const shown = displayed.get(event.event_id) ?? event;
return <>
Expand All @@ -55,17 +97,17 @@ export function ResearchRecordSearch({goalId, events, nodes, displayEvents, disp
zh={zh} stateLabel={stateLabel} timeLabel={timeLabel}/>
</>;
};
return <div className="research-record-search">
return <div className="research-record-search" ref={root}>
<div className="research-record-filters">
<input type="search" aria-label={zh ? "搜索研究记录" : "Search research records"}
placeholder={zh ? "正文、来源引用或 ID" : "Text, source reference or ID"} value={query}
onChange={event => {setQuery(event.target.value); setLimit(50);}}/>
onChange={event => updateFilters({query: event.target.value})}/>
<select aria-label={zh ? "记录状态" : "Recorded status"} value={status}
onChange={event => {setStatus(event.target.value); setLimit(50);}}>
onChange={event => updateFilters({status: event.target.value})}>
<option value="">{zh ? "所有状态" : "All statuses"}</option>
{[...new Set([...statuses, ...(status ? [status] : [])])].map(item => <option key={item} value={item}>{stateLabel(item)}</option>)}
</select>
{query || status ? <button type="button" onClick={reset}>{zh ? "清除筛选" : "Clear filters"}</button> : null}
{query || status ? <button type="button" onClick={() => updateFilters({query: "", status: ""})}>{zh ? "清除筛选" : "Clear filters"}</button> : null}
<select aria-label={zh ? "下载格式" : "Download format"} value={format} onChange={event => setFormat(event.target.value)}>
<option value="json">JSON</option>
<option value="md">{zh ? "阅读报告(Markdown)" : "Reading report (Markdown)"}</option>
Expand Down Expand Up @@ -97,34 +139,36 @@ export function ResearchRecordSearch({goalId, events, nodes, displayEvents, disp
: (zh ? "已读部分没有匹配记录;其余历史尚未核验。" : "No matches in the loaded records; the remaining history is not verified.")}</p> : null}
</ContextHelp>
</div>
{missing ? <p role="status">{zh ? "原先展开的条目在当前分组中不可用,其他原始记录仍可查阅。" : "A previously opened entry is unavailable in the current grouping. Other original records remain readable."}</p> : null}
<ol className="research-history-records">{groups.slice(0, limit).map(group => {
const event = group.events[0]!;
const shown = displayed.get(event.event_id) ?? event;
return <li key={group.id}>
return <li key={group.id} data-research-record={group.id}>
{group.node && group.events.length > 1
? <GroupedResearchRecord title={(displayed.get(group.node.latest.event_id) ?? group.node.latest).title}
events={group.events} displayed={displayed} renderRecord={originalContent} zh={zh} stateLabel={stateLabel} timeLabel={timeLabel}/>
: <details className="research-record-entry">
events={group.events} displayed={displayed} renderRecord={originalContent} zh={zh} stateLabel={stateLabel} timeLabel={timeLabel}
open={expanded.includes(group.id)} onOpen={open => toggle(group.id, open)}/>
: <details className="research-record-entry" open={expanded.includes(group.id)} onToggle={event => toggle(group.id, event.currentTarget.open)}>
<summary><strong>{shown.title}</strong><span>{timeLabel(event.recorded_at)} · {stateLabel(event.status)}</span></summary>
{originalContent(event)}
</details>}
</li>;})}</ol>
{limit < groups.length ? <button type="button" onClick={() => setLimit(value => value + 50)}>{zh ? "显示更多条目" : "Show more entries"} · {limit} / {groups.length}</button> : null}
{limit < groups.length ? <button type="button" onClick={() => reading.update({limit: limit + 50})}>{zh ? "显示更多条目" : "Show more entries"} · {limit} / {groups.length}</button> : null}
</div>;
}

function GroupedResearchRecord({title, events, displayed, renderRecord, zh, stateLabel, timeLabel}: {
function GroupedResearchRecord({title, events, displayed, renderRecord, zh, stateLabel, timeLabel, open, onOpen}: {
title: string; events: readonly ExploreHistoryEvent[]; displayed: ReadonlyMap<string, ExploreHistoryEvent>;
renderRecord: (event: ExploreHistoryEvent) => ReactNode; zh: boolean;
stateLabel: (status: string) => string; timeLabel: (at: string) => string;
open: boolean; onOpen: (open: boolean) => void;
}) {
const [open, setOpen] = useState(false);
const findings = events.filter(event => event.event_kind === "finding");
const lifecycle = events.filter(event => event.event_kind === "node").at(-1)?.status;
const statuses = [...new Set(findings.map(event => event.status))].filter(Boolean).map(stateLabel);
if (lifecycle) statuses.push(stateLabel(lifecycle));
const summary = [timeLabel(events.at(-1)!.recorded_at), ...statuses, zh ? `${events.length} 条记录` : `${events.length} records`];
return <details className="research-record-entry" onToggle={event => setOpen(event.currentTarget.open)}
return <details className="research-record-entry" open={open} onToggle={event => onOpen(event.currentTarget.open)}
onKeyDown={event => {
if (event.key !== "Escape" || !event.currentTarget.open || !(event.target instanceof Element)
|| event.target.closest("details") !== event.currentTarget) return;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,54 @@
import assert from "node:assert/strict";
import {test} from "node:test";
import {searchResearchRecords} from "./research-record-search.ts";
import {searchResearchRecords, researchRecordGroups, readResearchRecordsLocation, writeResearchRecordsLocation,
defaultResearchRecordsLocation} from "./research-record-search.ts";
import {projectExploreHistory} from "../../../../../../loopx/control_plane/presentation/explore_history.ts";

const record = (overrides = {}) => ({title: "", summary: "", blocked_reason: "", event_id: "event",
result_id: "finding", node_id: "", parent_id: "", from_node: "", to_node: "", run_id: "",
agent_id: "", supersedes: "", evidence_refs: [], status: "tentative", ...overrides});

test("record bookmarks retain filters, later-page expansion and unrelated research focus only for their original scope", () => {
const state = {open: true, query: "negative 原文", status: "refuted", expanded: ["node:question-57", "event:unlinked"], limit: 100};
const scope = JSON.stringify(["goal-a", "original-goal", "/status.json?source_namespace=source-a"]);
const search = new URLSearchParams("research_event=old-version&research_node=question-57");
const saved = writeResearchRecordsLocation(search, scope, state);
assert.deepEqual(readResearchRecordsLocation(new URLSearchParams(saved.toString()), scope), state);
assert.equal(saved.get("research_event"), "old-version");
assert.equal(search.has("research_records"), false, "Writing a bookmark must not mutate another reader's URL");
for (const other of ["", scope.replace("goal-a", "goal-b"), scope.replace("source-a", "source-b")]) {
assert.deepEqual(readResearchRecordsLocation(saved, other), defaultResearchRecordsLocation);
}
});

test("old, ambiguous and malformed bookmarks recover to closed records without selecting a substitute", () => {
const valid = {scope: "scope", open: true, query: "", status: "", expanded: ["missing-event"], limit: 50};
for (const input of ["", "research_records=broken", "research_records=null", "research_records=[]",
...[{...valid, expanded: [42]}, {...valid, open: "true"}, {...valid, query: []}, {...valid, limit: 49}, {...valid, limit: 50.5}]
.map(value => new URLSearchParams({research_records: JSON.stringify(value)}).toString())]) {
assert.deepEqual(readResearchRecordsLocation(new URLSearchParams(input), "scope"), defaultResearchRecordsLocation);
}
const duplicate = writeResearchRecordsLocation(new URLSearchParams(), "scope", valid);
duplicate.append("research_records", duplicate.get("research_records"));
assert.deepEqual(readResearchRecordsLocation(duplicate, "scope"), defaultResearchRecordsLocation);
const missing = writeResearchRecordsLocation(new URLSearchParams(), "scope", valid);
assert.deepEqual(readResearchRecordsLocation(missing, "scope").expanded, ["missing-event"], "The reader reports an absent selection instead of choosing the latest event");
});

test("linked lifecycle and conflicting finding revisions retain every original record, never merge on title or time", () => {
const node = record({goal_id: "goal", event_kind: "node", event_id: "node-event", result_id: "q", status: "resolved"});
const old = record({goal_id: "goal", event_kind: "finding", event_id: "old", result_id: "f", node_id: "q", status: "confirmed"});
const current = {...old, event_id: "new", status: "refuted", supersedes: "old"};
const other = {...node, event_id: "other", result_id: "other-q"};
const records = [node, old, current, other];
const groups = researchRecordGroups(records, projectExploreHistory(records, "goal").nodes);
assert.deepEqual(groups.map(group => group.events.map(event => event.event_id)), [["node-event", "old", "new"], ["other"]]);
const conflictingRun = records.map(event => ({...event, run_id: event.event_id === "new" ? "run-b" : "run-a"}));
assert.equal(researchRecordGroups(conflictingRun, projectExploreHistory(conflictingRun, "goal").nodes).length, 4);
const unlinked = records.map(event => ({...event, node_id: ""}));
assert.equal(researchRecordGroups(unlinked, projectExploreHistory(unlinked, "goal").nodes).length, 4);
});

test("searches full records before the caller's display limit and preserves source order", () => {
const records = Array.from({length: 75}, (_, i) => record({event_id: `event-${i}`, summary: i === 74 ? "Negative result for candidate Z" : "Other evidence"}));
assert.deepEqual(searchResearchRecords(records, "NEGATIVE z").map(row => row.event_id), ["event-74"]);
Expand Down
Loading
Loading