Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/reducer.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * The research view model, reduced from the generation stream (CONTRACT §9.6).47 *48 * Pure and replayable: `replay(events)` gives the same state as feeding the events one by one. Entities that have49 * an id (runs, experiments, notes, approvals, cells, figures) are upserted, so a duplicate does no harm — the server50 * is known to send the start of a run twice; a re-attached stream (`?from=N`) is handled by the event index.51 * Events of a type the reducer does not know leave the state untouched — the SAME object is returned, so React does52 * not re-render on text chunks.53 */54import type {55 Approval, Execution, ExecutionStatus, Experiment, Figure, LintIssue, LintStatus, PlanStep, ResearchState, Run, RunStatus, StreamEvent, TimelineItem, TimelineKind,56} from "./types";5758export const NOTEBOOK_TOOL = "execute_custom_python_analysis";5960export function initialResearchState(): ResearchState {61 return {62 lastIndex: -1, workspace: null, generationId: null, sessionId: null, objective: null, plan: [], planRevisions: 0,63 datasets: [], files: [], executions: [], installs: [], runs: [], experiments: [], notes: [], figures: [], approvals: [], gates: [],64 budgetHits: [], budgetApplied: null, generations: [], timeline: [], finished: false, counter: 0, lastCompletedToolId: null,65 };66}6768const str = (v: unknown): string | null => (typeof v === "string" && v.length > 0 ? v : null);69const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);70const obj = (v: unknown): Record<string, unknown> | null => (v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null);7172const RUN_TERMINAL: ReadonlySet<string> = new Set(["done", "failed", "timeout", "killed", "cancelled", "interrupted"]);73export const isRunTerminal = (status: string) => RUN_TERMINAL.has(status);7475function pushTimeline(state: ResearchState, kind: TimelineKind, ref: string, at: number | null): TimelineItem[] {76 const key = `${kind}:${ref}`;77 if (state.timeline.some((t) => t.key === key)) return state.timeline;78 return [...state.timeline, { key, kind, ref, at, generationId: state.generationId }];79}8081function replaceAt<T>(list: T[], index: number, next: T): T[] {82 const copy = list.slice();83 copy[index] = next;84 return copy;85}8687function executionStatus(ok: boolean, error: string | null): ExecutionStatus {88 if (ok) return "ok";89 if (error && /time limit|Execution stopped after/.test(error)) return "timeout";90 if (error && /stopped by the sandbox/.test(error)) return "killed";91 return "failed";92}9394/** Text a person can read out of the notebook's tool result (the stream sends the object the model received). */95export function outputOfToolResult(result: unknown): string | null {96 if (typeof result === "string") return result.trim() || null;97 const r = obj(result);98 if (!r) return null;99 const parts = [str(r.output), r.result != null && typeof r.result !== "object" ? String(r.result) : null].filter(Boolean) as string[];100 const text = parts.join("\n").replace(/\n*\[Notebook session — variables in memory:[^\]]*\]\s*$/, "").replace(/\n+---\nFIGURES PRODUCED BY THIS CALL[\s\S]*$/, "").trim();101 return text || null;102}103104function toRun(raw: Record<string, unknown>, prev: Run | undefined, generationId: string | null): Run {105 const status = (str(raw.status) ?? prev?.status ?? "running") as RunStatus;106 // A late duplicate of the start event must not bring a finished run back to life.107 const regress = prev && isRunTerminal(prev.status) && !isRunTerminal(status);108 return {109 id: String(raw.id),110 label: str(raw.label) ?? prev?.label ?? null,111 code: str(raw.code) ?? str(raw.codeRef) ?? prev?.code ?? null,112 codeHash: str(raw.codeHash) ?? prev?.codeHash ?? null,113 args: Array.isArray(raw.args) ? raw.args.map(String) : prev?.args ?? [],114 status: regress ? prev.status : status,115 progress: regress ? prev.progress : num(raw.progress) ?? prev?.progress ?? null,116 exitCode: regress ? prev.exitCode : num(raw.exitCode) ?? prev?.exitCode ?? null,117 error: regress ? prev.error : str(raw.error) ?? prev?.error ?? null,118 network: raw.network === "open" || prev?.network === "open" ? "open" : "default",119 startedAt: num(raw.startedAt) ?? prev?.startedAt ?? null,120 finishedAt: regress ? prev.finishedAt : num(raw.finishedAt) ?? prev?.finishedAt ?? null,121 generationId: str(raw.generationId) ?? prev?.generationId ?? generationId,122 };123}124125function toExperiment(raw: Record<string, unknown>, prev: Experiment | undefined, generationId: string | null): Experiment {126 return {127 id: String(raw.id),128 seq: num(raw.seq) ?? prev?.seq ?? null,129 title: str(raw.title) ?? prev?.title ?? "Expérience sans titre",130 hypothesis: str(raw.hypothesis) ?? prev?.hypothesis ?? null,131 method: str(raw.method) ?? prev?.method ?? null,132 status: (str(raw.status) ?? prev?.status ?? "ok") as Experiment["status"],133 metrics: obj(raw.metrics) ?? prev?.metrics ?? null,134 diagnostics: raw.diagnostics ?? prev?.diagnostics ?? null,135 artifacts: Array.isArray(raw.artifacts) ? raw.artifacts.map(String) : prev?.artifacts ?? [],136 codeRef: str(raw.codeRef) ?? prev?.codeRef ?? null,137 runId: str(raw.runId) ?? prev?.runId ?? null,138 codeHash: str(raw.codeHash) ?? prev?.codeHash ?? null,139 notes: str(raw.notes) ?? prev?.notes ?? null,140 error: str(raw.error) ?? prev?.error ?? null,141 envHash: str(raw.envHash) ?? prev?.envHash ?? null,142 generationId: str(raw.generationId) ?? prev?.generationId ?? generationId,143 startedAt: num(raw.startedAt) ?? prev?.startedAt ?? null,144 finishedAt: num(raw.finishedAt) ?? prev?.finishedAt ?? null,145 durationMs: num(raw.durationMs) ?? prev?.durationMs ?? null,146 };147}148149function toApproval(raw: Record<string, unknown>, prev: Approval | undefined): Approval {150 return {151 id: String(raw.id),152 action: str(raw.action) ?? prev?.action ?? "other",153 reason: str(raw.reason) ?? prev?.reason ?? null,154 detail: obj(raw.detail) ?? prev?.detail ?? null,155 status: (str(raw.status) ?? prev?.status ?? "pending") as Approval["status"],156 createdAt: num(raw.createdAt) ?? prev?.createdAt ?? null,157 resolvedAt: num(raw.resolvedAt) ?? prev?.resolvedAt ?? null,158 };159}160161const lintIssues = (v: unknown, fixed?: boolean): LintIssue[] => (Array.isArray(v) ? v : []).map((x) => obj(x)).filter((x): x is Record<string, unknown> => !!x)162 .map((x) => ({ code: String(x.code ?? ""), severity: String(x.severity ?? "info"), message: String(x.message ?? ""), fixed: fixed ?? x.fixed === true }));163164/** The verdict of a figure from a `figure_lint` event or a REST figure, whatever the age of the server that wrote it. */165export function lintOf(raw: Record<string, unknown>): { status: LintStatus; fixes: LintIssue[]; findings: LintIssue[] } {166 const legacy = lintIssues(raw.issues);167 const fixes = Array.isArray(raw.fixes) ? lintIssues(raw.fixes, true) : legacy.filter((i) => i.fixed);168 const findings = Array.isArray(raw.findings) ? lintIssues(raw.findings, false) : legacy.filter((i) => !i.fixed);169 const status = raw.status === "passed" || raw.status === "fixed" || raw.status === "issues" ? raw.status170 : raw.ok === false || findings.some((i) => i.severity !== "info") ? "issues" : fixes.length > 0 ? "fixed" : "passed";171 return { status, fixes, findings };172}173174/**175 * Applies one stream event. `index` is the SSE id of the event when the transport knows it: an event at or below176 * the highest index already applied is a replay and is ignored.177 */178export function reduceResearch(state: ResearchState, event: StreamEvent, index?: number): ResearchState {179 if (!event || typeof event.type !== "string") return state;180 if (index != null && index <= state.lastIndex) return state;181 const next = apply(state, event);182 if (next === state) return state;183 return index != null ? { ...next, lastIndex: index } : next;184}185186function apply(state: ResearchState, e: StreamEvent): ResearchState {187 // Server time of the event (absent on `job` and on streams recorded before events were stamped).188 const at = num(e.at);189 switch (e.type) {190 case "job":191 return { ...state, generationId: str(e.id) ?? state.generationId, sessionId: str(e.sessionId) ?? state.sessionId, objective: str(e.query) ?? state.objective };192193 case "budget_applied": {194 const applied = { maxCostUsd: num(e.maxCostUsd), maxMinutes: num(e.maxMinutes), source: str(e.source) ?? "default" };195 return JSON.stringify(applied) === JSON.stringify(state.budgetApplied) ? state : { ...state, budgetApplied: applied };196 }197198 case "research_workspace": {199 const id = str(e.workspaceId);200 if (!id || state.workspace?.id === id) return state;201 return { ...state, workspace: { id, kind: str(e.kind) ?? "session" }, timeline: pushTimeline(state, "workspace", id, at) };202 }203204 case "plan": {205 const steps = (Array.isArray(e.steps) ? e.steps : []).map((s) => obj(s)).filter((s): s is Record<string, unknown> => !!s && typeof s.title === "string")206 .map((s) => ({ title: String(s.title), status: s.status === "done" || s.status === "in_progress" ? s.status : "pending" }) as PlanStep);207 if (JSON.stringify(steps) === JSON.stringify(state.plan)) return state;208 // A new set of titles is a methodological decision (the agent re-planned); a status change is only progress.209 const retitled = state.plan.length > 0 && steps.map((s) => s.title).join("\n") !== state.plan.map((s) => s.title).join("\n");210 const revisions = state.plan.length === 0 ? 0 : state.planRevisions + (retitled ? 1 : 0);211 const timeline = state.plan.length === 0 ? pushTimeline(state, "plan", "0", at) : retitled ? pushTimeline(state, "plan", String(revisions), at) : state.timeline;212 return { ...state, plan: steps, planRevisions: revisions, timeline };213 }214215 case "dataset": {216 const path = str(e.path);217 if (!path) return state;218 const ref = { path, rows: num(e.rows), columns: num(e.columns), bytes: num(e.bytes) };219 const i = state.datasets.findIndex((d) => d.path === path);220 return { ...state, datasets: i < 0 ? [...state.datasets, ref] : replaceAt(state.datasets, i, ref), timeline: pushTimeline(state, "dataset", path, at) };221 }222223 case "research_file": {224 const path = str(e.path);225 if (!path) return state;226 const n = state.counter + 1;227 const action = (["write", "patch", "delete", "library"].includes(String(e.action)) ? e.action : "write") as "write";228 return { ...state, counter: n, files: [...state.files, { action, path, bytes: num(e.bytes), agent: str(e.agent) }], timeline: pushTimeline(state, "file", `${n}:${path}`, at) };229 }230231 case "tool_start":232 case "code_execution_start": {233 // A cell starts. `tool_start` (lead only) carries the code itself; `code_execution_start` exists for every234 // cell, sub-analysts included, with the hash of the code. Both name the same cell by `toolId`.235 if (e.type === "tool_start" && e.tool !== NOTEBOOK_TOOL) return state;236 const toolId = str(e.toolId);237 const input = e.type === "tool_start" ? obj(e.input) ?? {} : {};238 const fresh = {239 title: e.type === "tool_start" ? str(input.description) : str(e.description),240 code: str(input.code),241 codeHash: str(e.codeHash),242 lines: num(e.lines) ?? (typeof input.code === "string" ? input.code.split("\n").length : null),243 agent: str(e.agent),244 };245 const i = toolId ? state.executions.findIndex((x) => x.toolId === toolId) : -1;246 if (i >= 0) {247 const x = state.executions[i];248 const merged = { ...x, title: x.title ?? fresh.title, code: x.code ?? fresh.code, codeHash: x.codeHash ?? fresh.codeHash, lines: x.lines ?? fresh.lines, agent: fresh.agent ?? x.agent, startedAt: x.startedAt ?? at,249 codePath: x.codePath ?? (fresh.codeHash ? `logs/cells/${fresh.codeHash}.py` : null) };250 return JSON.stringify(merged) === JSON.stringify(x) ? state : { ...state, executions: replaceAt(state.executions, i, merged) };251 }252 const n = state.counter + 1;253 const key = `x${n}`;254 const exec: Execution = {255 key, id: null, seq: null, agent: fresh.agent ?? "lead", title: fresh.title, codeHash: fresh.codeHash, codePath: fresh.codeHash ? `logs/cells/${fresh.codeHash}.py` : null, code: fresh.code,256 lines: fresh.lines, status: "running", durationMs: null, error: null, output: null, envHash: null, generationId: state.generationId, startedAt: at, toolId, figureKeys: [],257 };258 return { ...state, counter: n, executions: [...state.executions, exec], timeline: pushTimeline(state, "execution", key, at) };259 }260261 case "code_execution": {262 const id = str(e.experimentId);263 const toolId = str(e.toolId);264 if (id && state.executions.some((x) => x.id === id)) return state;265 const agent = str(e.agent) ?? "lead";266 const title = str(e.description);267 const error = str(e.error);268 const durationMs = num(e.durationMs);269 const done = { id, agent, title, codeHash: str(e.codeHash), codePath: str(e.code), lines: num(e.lines), status: executionStatus(e.ok === true, error), durationMs, error };270 let i = toolId ? state.executions.findIndex((x) => x.toolId === toolId) : -1;271 if (i < 0 && !toolId) {272 // Stream recorded before `code_execution` carried its `toolId`: the cell announced by tool_start with the273 // same description, else the oldest one still running.274 const running = state.executions.map((x, k) => ({ x, k })).filter(({ x }) => x.status === "running" && x.toolId && agent === "lead");275 i = (running.find(({ x }) => x.title === title) ?? running[0])?.k ?? -1;276 }277 if (i >= 0) {278 const x = state.executions[i];279 return { ...state, executions: replaceAt(state.executions, i, { ...x, ...done, title: title ?? x.title, lines: done.lines ?? x.lines, startedAt: x.startedAt ?? (at != null && durationMs != null ? at - durationMs : null) }) };280 }281 const n = state.counter + 1;282 const key = `x${n}`;283 const exec: Execution = { key, seq: null, code: null, output: null, envHash: null, generationId: state.generationId, startedAt: at != null && durationMs != null ? at - durationMs : at, toolId, figureKeys: [], ...done };284 return { ...state, counter: n, executions: [...state.executions, exec], timeline: pushTimeline(state, "execution", key, at) };285 }286287 case "tool_complete": {288 // Only needed for streams whose `tool_result` has no `toolId` (recorded before it had one).289 const toolId = str(e.toolId);290 if (e.tool !== NOTEBOOK_TOOL || !toolId) return state.lastCompletedToolId === null ? state : { ...state, lastCompletedToolId: null };291 return { ...state, lastCompletedToolId: toolId };292 }293294 case "tool_result": {295 if (e.tool !== NOTEBOOK_TOOL) return state;296 const toolId = str(e.toolId) ?? state.lastCompletedToolId;297 const cleared = state.lastCompletedToolId === null ? state : { ...state, lastCompletedToolId: null };298 const i = toolId ? state.executions.findIndex((x) => x.toolId === toolId) : -1;299 if (i < 0 || state.executions[i].output != null) return cleared;300 return { ...cleared, executions: replaceAt(state.executions, i, { ...state.executions[i], output: outputOfToolResult(e.result) }) };301 }302303 case "tool_error": {304 if (e.tool !== NOTEBOOK_TOOL) return state;305 const toolId = str(e.toolId);306 const i = state.executions.findIndex((x) => toolId && x.toolId === toolId);307 if (i < 0) return state;308 const x = state.executions[i];309 const error = str(e.error) ?? x.error ?? "Erreur";310 // The tool error is the full text; the one of code_execution is cut short by the server.311 if (x.status !== "running" && (x.error?.length ?? 0) >= error.length) return state;312 return { ...state, executions: replaceAt(state.executions, i, { ...x, status: x.status === "running" || x.status === "ok" ? executionStatus(false, error) : x.status, error }) };313 }314315 case "package_install": {316 const spec = str(e.spec);317 if (!spec) return state;318 const n = state.counter + 1;319 const key = `i${n}`;320 return { ...state, counter: n, installs: [...state.installs, { key, spec, ok: e.ok === true }], timeline: pushTimeline(state, "install", key, at) };321 }322323 case "research_run": {324 const raw = obj(e.run);325 if (!raw || !raw.id) return state;326 const i = state.runs.findIndex((r) => r.id === raw.id);327 const run = toRun(raw, i < 0 ? undefined : state.runs[i], state.generationId);328 if (i >= 0 && JSON.stringify(run) === JSON.stringify(state.runs[i])) return state;329 return { ...state, runs: i < 0 ? [...state.runs, run] : replaceAt(state.runs, i, run), timeline: pushTimeline(state, "run", run.id, run.startedAt ?? at) };330 }331332 case "experiment": {333 const raw = obj(e.experiment);334 if (!raw || !raw.id) return state;335 // The stream may also carry automatic `execution` entries: those are already shown as cells and runs.336 if (raw.kind === "execution") return state;337 const i = state.experiments.findIndex((x) => x.id === raw.id);338 const exp = toExperiment(raw, i < 0 ? undefined : state.experiments[i], state.generationId);339 if (i >= 0 && JSON.stringify(exp) === JSON.stringify(state.experiments[i])) return state;340 return { ...state, experiments: i < 0 ? [...state.experiments, exp] : replaceAt(state.experiments, i, exp), timeline: pushTimeline(state, "experiment", exp.id, at ?? exp.startedAt) };341 }342343 case "research_note": {344 const raw = obj(e.note);345 if (!raw || !raw.id) return state;346 const note = { id: String(raw.id), kind: str(raw.kind) ?? "finding", title: str(raw.title) ?? "Note", body: str(raw.body) ?? "", createdAt: num(raw.createdAt) };347 const i = state.notes.findIndex((x) => x.id === note.id);348 return { ...state, notes: i < 0 ? [...state.notes, note] : replaceAt(state.notes, i, note), timeline: pushTimeline(state, "note", note.id, note.createdAt ?? at) };349 }350351 case "figure_lint": {352 const files = obj(e.files) as Figure["files"];353 const figureId = str(e.figureId);354 const toolId = str(e.toolId);355 // A figure is identified by its id; before figures had one, by its PNG in the workspace.356 if (figureId ? state.figures.some((f) => f.key === figureId) : files?.png && state.figures.some((f) => f.files?.png === files.png)) return state;357 const n = state.counter + 1;358 const key = figureId ?? `f${n}`;359 // The cell that drew it: named by `toolId`; on an older stream, the last cell that ended.360 const owner = (toolId ? state.executions.find((x) => x.toolId === toolId) : undefined) ?? (toolId ? undefined : [...state.executions].reverse().find((x) => x.status !== "running"));361 const figure: Figure = { key, title: str(e.title), caption: str(e.caption), ...lintOf(e), toolId, at, files: files ?? null, url: str(e.url), execKey: owner?.key ?? null, generationId: state.generationId };362 const executions = owner ? state.executions.map((x) => (x.key === owner.key ? { ...x, figureKeys: [...x.figureKeys, key] } : x)) : state.executions;363 return { ...state, counter: n, figures: [...state.figures, figure], executions, timeline: pushTimeline(state, "figure", key, at) };364 }365366 case "custom_python_figures": {367 const urls = (Array.isArray(e.figureUrls) ? e.figureUrls : []).filter((u): u is string => typeof u === "string");368 if (urls.length === 0 || urls.every((u) => state.figures.some((f) => f.url === u))) return state;369 const toolId = str(e.toolId);370 const figures = state.figures.slice();371 // Reports of this cell that have no address yet (a `figure_lint` carries its `url` now; older ones did not):372 // same cell, same order. Without a `toolId` on either side, the latest reports still waiting.373 const waiting = figures.map((f, i) => ({ f, i })).filter(({ f }) => f.url === null && f.status !== null && (toolId ? f.toolId === toolId : true));374 const tail = waiting.slice(Math.max(0, waiting.length - urls.length));375 const known = new Set(figures.map((f) => f.url));376 let counter = state.counter;377 let timeline = state.timeline;378 let executions = state.executions;379 urls.forEach((url, k) => {380 if (known.has(url)) return;381 const slot = tail.length === urls.length ? tail[k] : undefined;382 if (slot) figures[slot.i] = { ...slot.f, url };383 else if (!toolId || !figures.some((f) => f.toolId === toolId)) {384 // A figure the linter did not report (create_plot, or a server without the visual check).385 counter += 1;386 const key = `f${counter}`;387 const owner = (toolId ? executions.find((x) => x.toolId === toolId) : undefined) ?? [...executions].reverse().find((x) => x.status !== "running");388 figures.push({ key, title: str(e.description), caption: null, status: null, fixes: [], findings: [], toolId, at, files: null, url, execKey: owner?.key ?? null, generationId: state.generationId });389 if (owner) executions = executions.map((x) => (x.key === owner.key ? { ...x, figureKeys: [...x.figureKeys, key] } : x));390 timeline = pushTimeline({ ...state, timeline }, "figure", key, at);391 }392 });393 return { ...state, counter, figures, executions, timeline };394 }395396 case "approval_request":397 case "approval_resolved": {398 const raw = obj(e.approval);399 if (!raw || !raw.id) return state;400 const i = state.approvals.findIndex((a) => a.id === raw.id);401 const approval = toApproval(raw, i < 0 ? undefined : state.approvals[i]);402 // A request replayed after its resolution must not reopen it.403 if (i >= 0 && e.type === "approval_request" && state.approvals[i].status !== "pending") return state;404 if (i >= 0 && JSON.stringify(approval) === JSON.stringify(state.approvals[i])) return state;405 return { ...state, approvals: i < 0 ? [...state.approvals, approval] : replaceAt(state.approvals, i, approval), timeline: pushTimeline(state, "approval", approval.id, approval.createdAt ?? at) };406 }407408 case "quality_gate": {409 const findings = (Array.isArray(e.findings) ? e.findings : []).map((x) => obj(x)).filter((x): x is Record<string, unknown> => !!x)410 .map((x) => ({ id: String(x.id ?? ""), severity: String(x.severity ?? "info"), finding: String(x.finding ?? ""), evidence: str(x.evidence) }));411 const gate = { generationId: state.generationId, passed: e.passed === true, findings };412 const i = state.gates.findIndex((g) => g.generationId === gate.generationId);413 if (i >= 0 && JSON.stringify(gate) === JSON.stringify(state.gates[i])) return state;414 return { ...state, gates: i < 0 ? [...state.gates, gate] : replaceAt(state.gates, i, gate), timeline: pushTimeline(state, "gate", gate.generationId ?? "0", at) };415 }416417 case "budget": {418 const hit = { kind: String(e.kind ?? "cost"), spent: Number(e.spent), limit: Number(e.limit) };419 if (state.budgetHits.some((b) => b.kind === hit.kind && b.limit === hit.limit)) return state;420 return { ...state, budgetHits: [...state.budgetHits, hit], timeline: pushTimeline(state, "budget", `${hit.kind}:${hit.limit}`, at) };421 }422423 case "done":424 case "error": {425 if (state.finished) return state;426 // Nothing can still be running in a generation that ended: a cell left open was cut with it.427 const executions = state.executions.some((x) => x.status === "running")428 ? state.executions.map((x) => (x.status === "running" ? { ...x, status: "interrupted" as const, error: x.error ?? "Interrompu avec l'analyse." } : x))429 : state.executions;430 return { ...state, finished: true, executions };431 }432433 default:434 return state;435 }436}437438/** Reduces a list of events from scratch (or on top of `from`). `firstIndex` numbers them like the SSE ids. */439export function replay(events: StreamEvent[], from: ResearchState = initialResearchState(), firstIndex?: number): ResearchState {440 let state = from;441 events.forEach((e, i) => { state = reduceResearch(state, e, firstIndex == null ? undefined : firstIndex + i); });442 return state;443}444445/** Whether there is anything of the research workspace to show for this run. */446export function hasResearch(state: ResearchState): boolean {447 return !!state.workspace || state.executions.length > 0 || state.runs.length > 0 || state.experiments.length > 0 || state.approvals.length > 0 || state.datasets.length > 0;448}449450export interface ResearchCounts { executions: number; failed: number; running: number; runs: number; runsRunning: number; experiments: number; figures: number; installs: number; pendingApprovals: number }451export function countsOf(state: ResearchState): ResearchCounts {452 return {453 executions: state.executions.length + state.runs.length,454 failed: state.executions.filter((x) => x.status !== "ok" && x.status !== "running").length + state.runs.filter((r) => r.status !== "done" && r.status !== "running").length,455 running: state.executions.filter((x) => x.status === "running").length,456 runs: state.runs.length,457 runsRunning: state.runs.filter((r) => r.status === "running").length,458 experiments: state.experiments.length,459 figures: state.figures.length,460 installs: state.installs.length,461 pendingApprovals: state.approvals.filter((a) => a.status === "pending").length,462 };463}464