From b3e5524d39a7e74c9b00566d66601d5316f67954 Mon Sep 17 00:00:00 2001 From: Jay Moran Date: Thu, 19 Nov 2026 14:59:10 -0800 Subject: [PATCH 01/15] feat: streamline experiment package imports and exports Require publication before exporting complete input assets and exclude results. Unify JSON and package creation as editable drafts, recreate persona snapshots, surface resource issues on canvas nodes, and share creation and naming logic. --- docs/experiment-packages.md | 455 +++++------------- docs/experiment-portability-plan.md | 6 + frontend/package-lock.json | 26 - frontend/package.json | 2 - frontend/src/api/client.ts | 4 +- .../CreateExperimentFromFileDialog.test.tsx | 58 +++ .../CreateExperimentFromFileDialog.tsx | 118 ++--- .../protocol/ExperimentDefinitionDownload.tsx | 112 ----- .../ExperimentPackageDownload.test.tsx | 214 ++------ .../protocol/ExperimentPackageDownload.tsx | 184 ++----- .../protocol/ExperimentPackageImport.test.tsx | 194 -------- .../protocol/ExperimentPackageImport.tsx | 278 ----------- .../protocol/ImportedExperimentSetup.test.tsx | 33 -- .../protocol/ImportedExperimentSetup.tsx | 61 --- .../components/protocol/JsonSourceViewer.tsx | 34 -- .../protocol/NodeInspectorDialog.tsx | 3 +- .../protocol/NodeResourceIssues.test.tsx | 57 +++ .../protocol/NodeResourceIssues.tsx | 72 +++ .../components/protocol/ProtocolCanvas.tsx | 15 +- .../protocol/ResultJobFlows.test.tsx | 1 - frontend/src/components/protocol/RunsTab.tsx | 2 - .../components/protocol/nodeConfigIssues.ts | 75 ++- .../protocol/nodeResourceIssuesContext.ts | 14 + .../components/protocol/protocolNodeTypes.ts | 21 +- .../protocol/useProviderModels.test.tsx | 10 +- frontend/src/lib/jsonSource.test.ts | 27 -- frontend/src/lib/jsonSource.ts | 13 - frontend/src/pages/ExperimentsPage.tsx | 2 - frontend/src/pages/ProtocolCanvasPage.tsx | 2 +- frontend/src/types/packageImports.ts | 3 +- src/asaree/api/experiments.py | 72 +-- src/asaree/api/package_imports.py | 39 +- src/asaree/api/result_jobs.py | 4 +- src/asaree/services/experiment_packages.py | 196 +------- src/asaree/services/experiments.py | 23 + src/asaree/services/package_imports.py | 8 +- src/asaree/services/package_reconstruction.py | 96 ++-- src/asaree/services/package_setup.py | 37 +- src/asaree/services/package_validation.py | 47 +- src/asaree/services/personas.py | 20 +- src/asaree/services/protocols.py | 2 + src/asaree/services/resource_names.py | 15 + tests/test_experiment_creation_contract.py | 3 +- tests/test_experiment_package_boundaries.py | 148 ------ tests/test_experiment_package_postgres.py | 25 +- tests/test_experiment_packages.py | 108 ++--- tests/test_package_import_lifecycle.py | 11 +- tests/test_package_import_postgres.py | 193 +++++--- 48 files changed, 928 insertions(+), 2215 deletions(-) create mode 100644 frontend/src/components/CreateExperimentFromFileDialog.test.tsx delete mode 100644 frontend/src/components/protocol/ExperimentDefinitionDownload.tsx delete mode 100644 frontend/src/components/protocol/ExperimentPackageImport.test.tsx delete mode 100644 frontend/src/components/protocol/ExperimentPackageImport.tsx delete mode 100644 frontend/src/components/protocol/ImportedExperimentSetup.test.tsx delete mode 100644 frontend/src/components/protocol/ImportedExperimentSetup.tsx delete mode 100644 frontend/src/components/protocol/JsonSourceViewer.tsx create mode 100644 frontend/src/components/protocol/NodeResourceIssues.test.tsx create mode 100644 frontend/src/components/protocol/NodeResourceIssues.tsx create mode 100644 frontend/src/components/protocol/nodeResourceIssuesContext.ts delete mode 100644 frontend/src/lib/jsonSource.test.ts delete mode 100644 frontend/src/lib/jsonSource.ts create mode 100644 src/asaree/services/resource_names.py diff --git a/docs/experiment-packages.md b/docs/experiment-packages.md index 5ead4177..31faa938 100644 --- a/docs/experiment-packages.md +++ b/docs/experiment-packages.md @@ -1,329 +1,132 @@ -# Published experiment packages - -The canvas top bar offers **Download experiment package**. Select a published -version, including an older version, and optionally include its results. The -separate **Download draft definition JSON** action remains a draft definition -export without dependency files. - -API clients create the same owned export job used by Results CSV downloads: - -```http -POST /api/experiments/{experiment_id}/execution-results/jobs?protocol_id={protocol_id}&protocol_revision_id={publication_id} -Content-Type: application/json - -{"kind":"export","format":"experiment_package","include_results":false,"request_key":"unique-client-request"} -``` - -The publication ID is mandatory. Partial cell, replicate, or row selections are -not supported for a package. Poll the returned job ID through the existing job -endpoint. Completed jobs provide a native `download_url`, a manifest -`schema_url`, and `progress.sha256` for the compressed archive. Links are signed -for five minutes; requesting job status renews the link. Prepared files expire -24 hours after job creation. Cancellation and failure never publish partial -archives as completed downloads. - -## Schema versions and compatibility - -New exports use schema **2**. Imports accept schemas **1 and 2**; other versions -are rejected before confirmation. Version 2 adds structured Skill metadata, -Skill file encodings/order, dataset registration metadata, knowledge registration kinds/empty-tree counts, publication notes and -stable row-slot evidence. These additions close reconstruction gaps found by -auditing the actual version 1 exporter. Version 1 files remain readable and -re-exportable; the importer parses recorded Skill frontmatter, but never claims -to recover omitted source filenames, original resource encodings/order or row -slot facts. Such omissions are explicitly reported in preflight. A v1 binary -Skill resource is represented locally as base64 without claiming that was its -original storage encoding. - -Both versions require canonical UUIDs for typed archive identities. MCP -requirement filenames, their IDs and included knowledge directory names must -agree; inconsistent packages are rejected rather than assigning new meanings to -their paths. Explicit missing/unresolved dependencies remain diagnostics, including -legacy name-only lookups. Only a Skill's exact root `SKILL.md` is its entrypoint; -nested files such as `references/SKILL.md` are ordinary bundled resources. Version -2 retains their recorded encoding/order; version 1 retains their bytes with the -same explicit unknown source metadata as other v1 resources. - -The common archive layout is: - -The `.tar.gz` archive contains: - -| Member | Meaning | +# Experiment packages + +The canvas **Download** action exports the published experiment and all required +input assets as a `.tar.gz` package. Publish the current draft before exporting; +Download does not publish it or offer a publish-and-export shortcut. When browsing +a historical version, Download exports that selected version. + +Packages contain the canvas, experiment settings, measurement plan, design, +datasets and exact split files, scripts, Skills and their bundled files, knowledge +content, and saved persona snapshots as Markdown. Factor alternatives and +sub-agent definitions/wiring are included. Missing, changed, unreadable or +unauthorized required content fails preparation with a diagnostic; an incomplete +archive is never published as a download. Saved destination connections are +requirements rather than bundled assets. Credentials are excluded. + +Results, observations, execution history, execution output artifacts, queues, +workspace resume state, row indexes, caches and scratch are excluded. Package +import does not restore results. Existing Results CSV exports are separate. + +## Create experiment from file + +Use **Create experiment from file** from the existing header menu. It accepts: + +- Legacy `.json` experiment definitions, which have no asset file contents. +- `.tar.gz` packages containing the complete definition and input assets. + +After choosing the file and creating the experiment, package inspection and +reconstruction proceed automatically. There is no preflight acceptance or +connection-acknowledgement step. Progress and failures appear in the same dialog; +failed requests can be retried. Completion opens the new experiment's canvas. +Both formats create an **unpublished editable draft**. A JSON file's source +published snapshot does not create a destination publication. + +Saved provider connections resolve through the destination user's ordinary +provider settings. Trusted built-in MCP registrations match only when their +stable service identity and required tools agree and the match is unique. Custom +MCP connections are never selected automatically. Missing or ambiguous connections +appear as node warnings; choose a compatible saved connection in the affected +node inspector. Missing credentials are repaired in Profile. Normal discovery +and validation handle connectivity; import never starts packaged commands, +executes scripts, invokes tools, tests credentials or runs an experiment. + +## Destination identities and storage + +The imported experiment, protocol and owned resources receive fresh destination +identities. Typed references are remapped, including factor alternatives, +measurement bindings, and ordered dataset/Skill/knowledge selections. Node IDs +remain scoped to the new protocol so edges, sub-agent selections and prompt +references continue to agree. Prompts, scripts and data are opaque content; +hard-coded external addresses or paths inside them are not rewritten. + +Dataset sources and exact split bytes are retained in managed storage. Knowledge +registrations point to destination managed directories. Each distinct saved +persona snapshot becomes a reusable destination Persona; a node combining +multiple personas recreates its exact combined prompt as one entry. Source +persona IDs do not become live destination references. Changing a library persona +does not change an imported node's saved text. + +Normal experiment creation and protocol naming are reused. Experiment names keep +the original when available, otherwise use the existing `Name (2)` convention. +Resource names follow their owning namespace's uniqueness and validation rules; +there is no unconditional import-UUID suffix. Source manifests and typed identity +mappings retain offline provenance without requiring access to the source +installation. + +## Format and integrity + +Packages use `asaree.experiment-package`, schema 2. Payloads contain: + +| Path | Contents | | --- | --- | -| `manifest.json` | Format/version, selected publication, capture window, software requirements, completeness and inventory hashes | -| `files.jsonl` | One record per payload member: relative path, source identity, byte count, SHA-256 and provenance | -| `dependencies.jsonl` | Included, missing, unresolved and intentionally excluded dependencies, with reasons | -| `publication/` | Selected canvas and experiment settings, including factors, bindings and measurements | -| `experiment-metadata.json` | Current name/description, explicitly captured at download time | -| `design/` | Referenced design declaration and generated cell/replicate identities | -| `inputs/` | Pinned dataset bindings, originals, exact split files and split provenance | -| `resources/` | Scripts, rendered stored Skills with all bundled resources, and authorized knowledge content | -| `requirements/` | Model configurations and MCP server/tool requirements without connection secrets | -| `results/` | Optional version-scoped attempts, observations, recorded evidence and retained attributable files | -| `sources/` | Imported source manifests/publications and typed identity mappings; with results selected, the exact original source archive | - -The manifest hashes both inventories. `files.jsonl` hashes dependency inventory -bytes but does not hash itself or the manifest, avoiding circular references. -Dataset artifact UUIDs map to paths through the dependency inventory. Arrays in -pinned bindings preserve their recorded ordering and row projections. Resources -are deduplicated within this export by stable identity, never across owners. - -`publication_pinned` identifies recorded publication/configuration and verified -input identities. `captured_at_download` identifies mutable reusable library or -knowledge content. Skill entry points are rendered from stored metadata/body; -bundled UTF-8 and base64 assets retain their stored content. `recorded_attempt` -identifies an attempt's own facts, rather than a latest-attempt projection. -`legacy.unknown` records history that cannot be established. Missing historical -settings, sources, splits or files never resolve to the current draft or split. - -ASAREE records are read under one repeatable-read snapshot. Motoro resources use -a separate snapshot; filesystem captures verify opened files and detect tree -changes. Mutable external knowledge has no cross-file transaction or historical -snapshot. The manifest records this limitation rather than claiming publication -fidelity. Uploaded bundles and documents use the application's per-owner storage -boundary. An external registration or shared browse access alone does not prove -authority to download the registered directory. Broad roots, other owners' -knowledge, symlinks and ambiguous overlaps are unresolved dependencies. - -### External knowledge export grants - -Operators can authorize a specific external bundle for a user with the -`knowledge_export_grants` setting, supplied as JSON through -`ASAREE_KNOWLEDGE_EXPORT_GRANTS`, for example: - -```json -{"00000000-0000-0000-0000-000000000001":["/srv/research/approved-cohort-bundle"]} -``` - -The key is the application user's UUID. Each absolute path must match the -registered bundle root exactly; there is no implicit grant to descendants or -ancestors. A grant is the operator's assertion that **all content under that -exact root is authorized for that user**. It is not inferred from filesystem -ownership, a registration's owner field, or absence of competing registrations. -Configure only narrow named bundle roots after reviewing their full contents. - -Grants support isolated legacy bundles outside today's browse root without -moving or adopting their files. They do not override rejection of the shared -browse root/its ancestors, platform-storage overlaps, or foreign/ownerless -knowledge registrations and other users' grants that overlap in either direction -or exactly. Missing or malformed grants, unreadable registration evidence and -ambiguous knowledge boundaries are reported as unresolved before content capture; -diagnostics do not expose another owner's identifiers, paths, commands or bytes. - -Set the same configuration on the API and worker processes, particularly -`asaree-results-worker`, which builds packages. In the supplied Compose setup, -the configured environment file is already forwarded to `asaree-app`, -`asaree-worker`, and `asaree-results-worker`; a host-shell variable alone is not -automatically forwarded. Deployment overrides can set the JSON value in those -services' `environment` mappings. External paths must be mounted consistently -in the exporting worker. No grant is required for authorized uploaded bundles -and documents, and this correction changes no database schema or package format. - -Credential/connection fields, including typed fallback and sampling snapshot -fields, and recognized credential files are excluded. Dataset bytes, prompts, -scripts and opaque experimental values are preserved. Known knowledge display -paths become relative archive directories; sampling snapshot keys identify -credential-free explicit input in the archive, rather than executable runtime -resolver requests. Importers must use this schema and restore connections; -the package is not a direct runtime-resume image. - -Optional results include every retained production attempt for the selected -publication and design. They exclude test runs, node previews, other versions, -queues, workspace resume/control state, regenerable row views/indexes, caches -and scratch. UUID-isolated retained outputs include Agent slots and Script -working directories. Shared legacy workspaces and experiment-level artifacts -without publication attribution are not assigned to historical versions; the -dependency inventory records unavailable or unscoped evidence. -AgentRun IDs in node evidence are source provenance; native Motoro step history -and resume/control snapshots are not bundled. -Workspace scratch is recognized structurally at `.scratch/` under the workspace -root or its `dataset=`/`agent=` slots. User artifacts such as -`outputs/working/prediction.csv`, `outputs/cache/`, `outputs/scratch/`, and -`outputs/.scratch/` remain durable content. Temporary preparation names use the -reserved hidden producer naming pattern; an ordinary `results.preparing/` -output directory is preserved. -Materialized Script source exclusions apply only to the producer's immediate -`scripts/` directory (including a recorded standalone Agent's directory). -Row-input CSVs and `row-view.json` are excluded only at the exact -`agents/<64-hex Agent key>/` location inside a row attempt. Nested output files -and whole-workspace artifacts retain their bytes even when their names resemble -these inputs. - -Archive generation streams file bytes and SQL evidence slices, spools inventories -to plain files, and discards tar member metadata after writing. Memory does not -grow with the number of attempts, archive members or dataset rows. Publication -configuration and one bounded Skill/resource record are processed at a time. -Copying/compression run off the event loop; cancellation stops and joins active -writer work before cleanup. No new database or SQLite inventory is introduced. - -A package is a logical export, not a database backup. Resuming workspaces and -reproducing external model/tool outputs are outside its scope. See -[ADR 0003](adr/0003-immutable-dataset-inputs-and-managed-artifacts.md). - -## Import workflow - -On **Experiments**, choose a `.tar.gz` package under **Import experiment -package**. Upload starts inspection only. Review the source version, schema, -file categories, missing dependencies, historical results and local configuration -requirements, then explicitly confirm creating a new experiment. The persistent -request list lets you return after navigation or a browser restart. Cancel before -activation or retry a failed unexpired request. A distinct request creates a -distinct owned experiment even for identical archive bytes. - -The new experiment contains an editable draft and planned cells/replicates. -It has no selected local publication and no fabricated completed executions. -Imported source publications, resolver/sampling snapshots, all retained attempts, -observations and artifacts stay immutable in managed files. **Download experiment -package → Imported source evidence** exposes those files separately from local -Runs/Results projections. It also provides an exact source package re-export. -New local exports retain source manifests/publications and typed mappings under -`sources/`; including results additionally preserves the original source archive -as an opaque nested evidence file. Nested archives are never executed or used -as native runtime state. - -Open the imported experiment's editable draft. Its setup panel reports **Ready to -publish** or **Setup needed**, with links to affected canvas nodes. Select saved -destination provider connections and compatible custom MCP connections there; -multiple compatible connections always require an explicit selection. Missing -credentials can be configured in Profile. Refresh readiness after setup changes. -Normal publication validates the current draft and every factor alternative; -there is no acknowledgement checkbox and no return to the upload screen. -Incomplete drafts remain editable and source evidence remains inspectable. -Readiness checks saved records only; live connection tests are explicit actions. -Normal publication resolves new local sampling/input -snapshots; it does not rewrite the preserved source evidence. Resource names -receive an import-specific suffix to avoid collisions. Canvas node IDs remain -protocol-scoped labels because prompts may address them; new protocol ownership -creates a fresh identity namespace. Only typed resource references, selections -and bound factor alternatives are remapped. Opaque strings, scripts, prompts, -dataset values, observation values and provenance are not searched/replaced. - -Imported content receives fresh owned identities, including imported MCP -requirement identities. Runtime bindings may reference authorized destination -system services or explicitly selected owned connections. These bindings are -recorded separately from source-to-local content mappings. New packages record -stable built-in service identities derived from shipped modules; automatic -matching requires a trusted system registration, the same service identity, -all recorded required tools and exactly one compatible destination. The additive -`service_identity` and `required_tool_names` requirement fields are supported in -schema 2; required tools include the union of factor alternatives and implicit -dataset/Script grants. Older requirements without a required-tool subset use -their recorded full tool list conservatively. Display -names and source owner IDs never establish compatibility or authorization. -Older packages without service identities require explicit selection. Destination -commands, URLs, environment and credentials remain untouched. Scalar MCP identity -factor alternatives become complete configurations so each selected identity -retains its matching destination runtime name. Opaque values remain unchanged. - -Before downloading a prepared export, the dialog separates included dependencies, -destination connection requirements and missing/unresolved content. Incomplete -packages are labelled explicitly and retain actionable dependency diagnostics -(up to 100 in the summary; the full inventory remains in the package). Connection -requirements alone do not make content incomplete. The selected historical -publication remains authoritative; missing history never uses current content. -Use **Publish & prepare package** to download current draft changes instead. - -### API - -All routes below require the importing user's authentication: - -1. `POST /api/experiment-package-imports` with `{"request_key":"client-unique-key"}`. - The same owner/key returns the same durable request. -2. `PUT /api/experiment-package-imports/{id}/upload` with raw gzip archive bytes. - A disconnected upload can be repeated before inspection; no multipart buffering - is required. -3. Poll `GET /api/experiment-package-imports/{id}` for status, progress, diagnostics, - preflight, source SHA-256 and destination experiment ID. -4. `POST .../{id}/confirm` explicitly queues activation. Repeated confirmation is - idempotent. `POST .../{id}/cancel` cancels before completed activation; - `POST .../{id}/retry` re-inspects a failed request before another confirmation. -5. `GET .../{id}/files?offset=0&limit=50` pages source inventory; - `GET .../{id}/source?path=publication/canvas.json` downloads one original file. - Omitting `path` re-exports the original source archive byte-for-byte. - `GET .../{id}/identities?offset=0&limit=50` pages durable typed provenance. -6. `GET .../{id}/readiness` returns read-only readiness issues with `node_id`, - compatible authorized MCP candidates, and saved provider selections. - `POST .../{id}/connections` with `{"kind":"mcp","source_id":"source-uuid", - "destination_id":"destination-uuid"}` explicitly selects an existing - connection. Use `"kind":"provider"` and a provider key such as `"openai"` - as `source_id` to select that user's saved provider setting. These actions - never connect, test credentials, or invoke packaged code. Publish using the - normal protocol publication endpoint. The legacy `/configuration` endpoint - remains compatible but its timestamp does not unlock or gate publication. - -`GET /api/experiment-package-imports?experiment_id={id}` finds an experiment's -source history; omitting the filter returns the newest 50 owned requests. - -### Lifecycle, limits and recovery +| `manifest.json` | Publication identity, capture information, software requirements and inventory hashes | +| `files.jsonl`, `dependencies.jsonl` | Member hashes, sizes, dependency identities and connection requirements | +| `publication/`, `experiment-metadata.json` | Canvas and experiment configuration | +| `design/` | Generated design and pending replicate slots, without results | +| `inputs/` | Pinned datasets, exact originals/splits and provenance | +| `resources/` | Scripts, Skills, knowledge and persona Markdown snapshots | +| `requirements/` | Credential-free provider and MCP requirements | +| `sources/` | Imported source configuration and identity provenance | + +Published configuration and dataset input identities are pinned. Reusable Skills +and knowledge are captured at download time; the manifest records that distinction. +ASAREE and Motoro have separate database snapshots, and mutable files have no +historical transaction guarantee. Packages are logical exports, not database +backups or promises of identical external-model outputs. + +Archive inspection verifies hashes, identity relationships and file counts before +creating records. It enforces compressed/expanded/member/document limits and +rejects traversal paths, links, special files and excluded credential-file names. + +## External knowledge export grants + +Uploaded, owned knowledge is exportable. Registering an external path or allowing +it to be browsed does not authorize packaging its contents. Operators can grant a +user access to one exact external bundle root with `knowledge_export_grants` +(`ASAREE_KNOWLEDGE_EXPORT_GRANTS`), a JSON mapping of user UUIDs to absolute paths. +Grants do not authorize ancestors/descendants, broad roots, platform-storage +overlaps, or another owner's overlapping registrations. Configure the same grants +and mounted paths on the API and results worker. Ambiguous authorization fails +export without including foreign content. + +## API + +Create an owned export job with +`POST /api/experiments/{experiment_id}/execution-results/jobs`, supplying +`protocol_id` and `protocol_revision_id` query parameters and a body such as +`{"kind":"export","format":"experiment_package","request_key":"unique-key"}`. +Results requests are rejected. Poll the existing job endpoint for its native +download URL. Signed links last five minutes and refresh on status reads; +prepared downloads expire after 24 hours. + +Create an import with `POST /api/experiment-package-imports` and +`{"request_key":"unique-key"}`, upload raw gzip bytes through +`PUT /api/experiment-package-imports/{id}/upload`, then poll +`GET /api/experiment-package-imports/{id}`. Validation queues reconstruction +automatically. The owned `cancel` and `retry` actions remain available. The +`readiness` and `connections` routes support canvas warnings and inspector repairs; +they do not constitute a separate setup workflow. Source-file and identity readers +remain authenticated diagnostic interfaces. + +## Lifecycle, limits and recovery The existing results worker relays durable `validating`, `queued` and `activating` -requests. PostgreSQL advisory locks serialize a request across workers. Archive -extraction, inventories and evidence use filesystem staging, not SQLite. Hashes -and references are verified before activation and the archive is re-inspected -before reconstruction. IDs derive from the request and typed source identity; -retry adopts only that request's owned staged resources. Motoro and ASAREE use -separate transactions. Skills stay soft-deleted and MCP registrations stay -disconnected/hidden during resource staging. Native experiment/protocol readers -hide incomplete activation. The relay finishes an interrupted visibility flip; -failures/cancellation compensate only records allocated by that request. - -Uncompleted requests expire after 24 hours; cancellation schedules cleanup on the -next results-worker relay. Cleanup waits for the request's worker lock and removes -only its staging paths and resources. Completed imports are durable evidence and -do not inherit download-export expiry. Include their files and database records -in coordinated backups. The API and results worker must share the same managed -storage configuration. - -Never-validated uploads have no staged resources: cleanup discards their private -files without parsing partially extracted inventories. Each expired request has -its own cleanup transaction. A compensation failure retains that request with -`compensation_required` progress for retry while other requests continue through -cleanup and enqueueing. Staged resources still receive owned deterministic-ID -compensation; their cleanup is not skipped when another upload is malformed. - -Configurable environment limits (positive integers): - -| Setting (`ASAREE_` prefix) | Default | -| --- | --- | -| `PACKAGE_IMPORT_MAX_COMPRESSED` | 1 GiB | -| `PACKAGE_IMPORT_MAX_EXPANDED` | 8 GiB | -| `PACKAGE_IMPORT_MAX_MEMBERS` | 100,000 files | -| `PACKAGE_IMPORT_MAX_DOCUMENT` | 16 MiB per JSON document, JSONL record or Skill resource | - -Files stream in bounded blocks; attempt inventories are disk-backed. JSON canvas, -settings and one evidence document must fit the configured document limit. -Archives exceeding any limit fail inspection with a diagnostic; increase limits -deliberately for larger recorded evidence. Traversal, links, special/sparse files, -duplicate/conflicting members, invalid JSON, unsupported schemas, unlisted files, -incorrect hashes/sizes and inconsistent typed references are rejected. Archive -metadata is bounded before parsing: only the exporter's ordinary files and local -PAX path/size extensions are accepted; global/GNU sparse/nested extensions are -rejected. Resource filename extensions do not turn opaque contents into schema -documents; binary Skill, knowledge and artifact bytes remain opaque. -Archive -ownership fields never confer authorization. No packaged script/tool or server -connection is invoked by inspection or reconstruction. - -### Export-to-import coverage audit - -| Exported component | Local reconstruction / retained evidence | -| --- | --- | -| Manifest, inventories, source version and capture provenance | Immutable exact original files, source archive SHA-256, durable owned request | -| Canvas, Agent configs, model requirements, settings, measurements | Editable sanitized draft; source snapshots retained separately; local publication required | -| Design declarations, cells, planned replicates | New local IDs; typed references and resource-valued factor alternatives remapped | -| Dataset bindings, projections and ordering | Exact source binding evidence; graph wiring/order retained; new owned registrations | -| Original CSVs, pinned split files and split provenance | Exact filesystem bytes/hashes, owned artifact/split records, no row-index import | -| Scripts and inline content | Exact source content; no execution during import | -| Skills, discovery fields, frontmatter and all resource files | Owned Motoro Skills/files; UTF-8/base64 encoding and order from v2 metadata | -| Knowledge trees and MCP requirements | Owned managed copies and disconnected registrations; explicit local configuration | -| Optional attempts, observations, row slots, conversations, node evidence, usage/errors | Source-attributed historical files and identity mappings; no native runtime records or latest-result projection | -| Attributable durable output/artifact files | Exact source files with hashes and attempt attribution; re-exportable source evidence | -| Missing/excluded dependencies and unavailable history | Visible diagnostics and preserved inventories; no same-name substitution | - -The PostgreSQL tests cover isolated source/destination product and resource -schemas, different owners/storage paths/credentials, both dataset modes, exact -CSV/split/binary Skill bytes, publication readiness, built-in compatibility and -ambiguity, explicit custom mapping, factor alternatives, source re-export, -ownership isolation and cross-database crash/retry/cancel boundaries. Archive -tests cover corruption, unsafe members, limits, compatibility and non-execution. -Native Motoro step/resume histories were never exported and cannot be restored. +requests. Advisory locks serialize work on a request. Deterministic identities +within that request permit recovery without duplicating resources; separate +requests create separate experiments. Content is staged before visibility changes, +and incomplete resources remain hidden. Cancellation/failure cleanup removes only +that request's staged resources. Uncompleted requests expire after 24 hours. +Completed input assets and source provenance remain available in managed storage. + +See [managed storage](managed-storage.md) and +[ADR 0003](adr/0003-immutable-dataset-inputs-and-managed-artifacts.md). diff --git a/docs/experiment-portability-plan.md b/docs/experiment-portability-plan.md index 8db71fa8..e18f770a 100644 --- a/docs/experiment-portability-plan.md +++ b/docs/experiment-portability-plan.md @@ -1,5 +1,11 @@ # Experiment portability implementation +Historical implementation notes for the original package workflow. The current +product contract is [experiment packages](experiment-packages.md): publication +before export, configuration/input assets only, automatic draft creation, recreated +persona snapshots, and node-based repairs. The confirmation/setup and results +paths described below have been superseded. + Branch: `fix/package-export-publication-join`; starting HEAD: `f27437d`. Preserve existing ancestry and leave PR #56 (base `develop`) unmerged. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 882442bf..b128c948 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,7 +9,6 @@ "version": "0.0.0", "dependencies": { "@base-ui/react": "^1.7.0", - "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@fontsource-variable/geist": "^5.3.0", @@ -18,7 +17,6 @@ "@xyflow/react": "^12.11.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", - "jsonc-parser": "^3.3.1", "lucide-react": "^1.30.0", "react": "^19.2.8", "react-dom": "^19.2.8", @@ -574,15 +572,6 @@ "@lezer/common": "^1.1.0" } }, - "node_modules/@codemirror/lang-json": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@codemirror/lang-json/-/lang-json-6.0.2.tgz", - "integrity": "sha512-x2OtO+AvwEHrEwR0FyyPtfDUiloG3rnVTSZV1W8UteaLL8/MajQd8DpvUb2YVzC+/T18aSDv0H9mu+xw0EStoQ==", - "dependencies": { - "@codemirror/language": "^6.0.0", - "@lezer/json": "^1.0.0" - } - }, "node_modules/@codemirror/lang-python": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", @@ -1082,16 +1071,6 @@ "@lezer/common": "^1.3.0" } }, - "node_modules/@lezer/json": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@lezer/json/-/json-1.0.3.tgz", - "integrity": "sha512-BP9KzdF9Y35PDpv04r0VeSTKDeox5vVr3efE7eBbx3r4s3oNLfunchejZhjArmeieBH+nVOpgIiBJpEAv8ilqQ==", - "dependencies": { - "@lezer/common": "^1.2.0", - "@lezer/highlight": "^1.0.0", - "@lezer/lr": "^1.0.0" - } - }, "node_modules/@lezer/lr": { "version": "1.4.10", "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.10.tgz", @@ -4529,11 +4508,6 @@ "node": ">=6" } }, - "node_modules/jsonc-parser": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", - "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==" - }, "node_modules/jsonfile": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index a89d8eeb..79dcd1a4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -12,7 +12,6 @@ }, "dependencies": { "@base-ui/react": "^1.7.0", - "@codemirror/lang-json": "^6.0.2", "@codemirror/lang-python": "^6.2.1", "@codemirror/theme-one-dark": "^6.1.3", "@fontsource-variable/geist": "^5.3.0", @@ -21,7 +20,6 @@ "@xyflow/react": "^12.11.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", - "jsonc-parser": "^3.3.1", "lucide-react": "^1.30.0", "react": "^19.2.8", "react-dom": "^19.2.8", diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index c52297f9..edafbf30 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -178,7 +178,7 @@ export const packageImportsApi = { create: (requestKey: string) => request(importBase, { method: 'POST', body: { request_key: requestKey } }), upload: (id: string, file: File, signal?: AbortSignal) => request(`${importBase}/${id}/upload`, { method: 'PUT', body: file, signal }), get: (id: string) => request(`${importBase}/${id}`), - command: (id: string, command: 'confirm' | 'cancel' | 'retry') => request(`${importBase}/${id}/${command}`, { method: 'POST' }), + command: (id: string, command: 'cancel' | 'retry') => request(`${importBase}/${id}/${command}`, { method: 'POST' }), files: (id: string, offset = 0) => request<{ items: PackageFile[]; next_offset: number | null }>(`${importBase}/${id}/files?offset=${offset}`), source: (id: string, path?: string) => requestBlob(`${importBase}/${id}/source${path ? `?path=${encodeURIComponent(path)}` : ''}`), readiness: (id: string) => request(`${importBase}/${id}/readiness`), @@ -253,7 +253,7 @@ export const experimentsApi = { request<{ items: { id: string; sequence: number; iteration: number | null; phase: string; preview: string | null }[]; next_after: number | null }>(`/experiments/${id}/execution-results/attempts/${runId}/nodes/${encodeURIComponent(nodeId)}/trace${resultPageQuery(scope, { after })}`, { signal }), getExecutionStep: (id: string, runId: string, nodeId: string, stepId: string, scope: ResultsScope, offset: number, signal?: AbortSignal) => request<{ text: string; next_offset: number | null }>(`/experiments/${id}/execution-results/attempts/${runId}/nodes/${encodeURIComponent(nodeId)}/trace/${stepId}${resultPageQuery(scope, { offset })}`, { signal }), - createResultJob: (id: string, scope: ResultsScope, command: { kind: ResultJob['kind']; request_key: string; cell_id?: string; replicate_ids?: string[]; row_indices?: number[]; rerun_slot_ids?: string[]; rerun_completed?: boolean; format?: 'analysis_csv' | 'experiment_package'; include_results?: boolean }, signal?: AbortSignal) => + createResultJob: (id: string, scope: ResultsScope, command: { kind: ResultJob['kind']; request_key: string; cell_id?: string; replicate_ids?: string[]; row_indices?: number[]; rerun_slot_ids?: string[]; rerun_completed?: boolean; format?: 'analysis_csv' | 'experiment_package'; include_results?: false }, signal?: AbortSignal) => request(`/experiments/${id}/execution-results/jobs${scopeQuery(scope)}`, { method: 'POST', body: command, signal }), getResultJob: (id: string, jobId: string, signal?: AbortSignal) => request(`/experiments/${id}/execution-results/jobs/${jobId}`, { signal }), diff --git a/frontend/src/components/CreateExperimentFromFileDialog.test.tsx b/frontend/src/components/CreateExperimentFromFileDialog.test.tsx new file mode 100644 index 00000000..82095d46 --- /dev/null +++ b/frontend/src/components/CreateExperimentFromFileDialog.test.tsx @@ -0,0 +1,58 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { experimentsApi, packageImportsApi } from '@/api/client' +import type { Experiment } from '@/types/experiments' +import type { PackageImport } from '@/types/packageImports' +import { CreateExperimentFromFileDialog } from './CreateExperimentFromFileDialog' + +afterEach(() => vi.restoreAllMocks()) + +function show() { + const imported = vi.fn() + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render() + return { imported, client } +} + +it('keeps legacy JSON definitions and creates their draft without restoring a publication', async () => { + const create = vi.spyOn(experimentsApi, 'importDefinition').mockResolvedValue({ id: 'new' } as Experiment) + const { imported } = show() + const definition = { name: 'Old experiment', graph: { nodes: [], edges: [] }, + canvas: { published: { graph: { nodes: [{ id: 'historical' }], edges: [] } } } } + const file = new File([JSON.stringify(definition)], 'experiment.json', { type: 'application/json' }) + fireEvent.change(screen.getByLabelText('Experiment definition'), { target: { files: [file] } }) + fireEvent.click(await screen.findByRole('button', { name: 'Create experiment' })) + await waitFor(() => expect(imported).toHaveBeenCalledWith('new')) + expect(create).toHaveBeenCalledWith(expect.objectContaining({ name: 'Old experiment', graph: definition.graph })) + expect(create.mock.calls[0][0]).not.toHaveProperty('published_graph') +}) + +it('uploads a package and opens its draft automatically without a confirmation or setup step', async () => { + const job = { id: 'import', status: 'completed', experiment_id: 'restored', progress: {}, preflight: {} } as PackageImport + vi.spyOn(packageImportsApi, 'create').mockResolvedValue(job) + const upload = vi.spyOn(packageImportsApi, 'upload').mockResolvedValue(job) + vi.spyOn(packageImportsApi, 'get').mockResolvedValue(job) + const command = vi.spyOn(packageImportsApi, 'command') + const { imported } = show() + const file = new File(['archive bytes'], 'experiment.tar.gz', { type: 'application/gzip' }) + fireEvent.change(screen.getByLabelText('Experiment definition'), { target: { files: [file] } }) + fireEvent.click(screen.getByRole('button', { name: 'Create experiment' })) + await waitFor(() => expect(imported).toHaveBeenCalledWith('restored')) + expect(upload).toHaveBeenCalledWith('import', file) + expect(command).not.toHaveBeenCalled() + expect(screen.queryByText(/Confirm import/)).not.toBeInTheDocument() +}) + +it('reports a failed package import without navigating to a partial experiment', async () => { + const job = { id: 'import', status: 'failed', experiment_id: null, error: 'Hash mismatch', progress: {}, preflight: {} } as PackageImport + vi.spyOn(packageImportsApi, 'create').mockResolvedValue(job) + vi.spyOn(packageImportsApi, 'upload').mockResolvedValue(job) + vi.spyOn(packageImportsApi, 'get').mockResolvedValue(job) + const { imported } = show() + fireEvent.change(screen.getByLabelText('Experiment definition'), { target: { files: [new File(['x'], 'bad.tar.gz')] } }) + fireEvent.click(screen.getByRole('button', { name: 'Create experiment' })) + expect(await screen.findByText('Hash mismatch')).toBeInTheDocument() + expect(imported).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: 'Retry import' })).toBeInTheDocument() +}) diff --git a/frontend/src/components/CreateExperimentFromFileDialog.tsx b/frontend/src/components/CreateExperimentFromFileDialog.tsx index a72f6693..00603a15 100644 --- a/frontend/src/components/CreateExperimentFromFileDialog.tsx +++ b/frontend/src/components/CreateExperimentFromFileDialog.tsx @@ -1,11 +1,12 @@ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Upload } from 'lucide-react' -import { ApiError, experimentsApi } from '@/api/client' +import { experimentsApi, packageImportsApi } from '@/api/client' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' +import { newRequestKey } from '@/lib/requestKey' import { FileDropInput } from '@/components/protocol/FileDropInput' import type { DesignSpec, MeasurementPlan } from '@/types/experiments' import type { ProtocolGraph } from '@/types/protocols' @@ -21,7 +22,6 @@ interface ImportedDefinition { designSpec: DesignSpec | null measurementPlan: MeasurementPlan | null graph: ProtocolGraph - publishedGraph: ProtocolGraph | null protocolDescription: string | null } @@ -44,10 +44,6 @@ function parseDefinition(text: string): ImportedDefinition { // usable, while still creating a new experiment rather than merging them. const experiment = isRecord(parsed.experiment) ? parsed.experiment : parsed const canvas = isRecord(parsed.canvas) ? parsed.canvas : parsed - const published = isRecord(canvas.published) ? canvas.published : null - const publishedGraph = published && isRecord(published.graph) && Array.isArray(published.graph.nodes) && Array.isArray(published.graph.edges) - ? published.graph as unknown as ProtocolGraph - : null const sourceName = optionalString(experiment.name)?.trim() || optionalString(parsed.name)?.trim() || 'Imported Experiment' return { @@ -63,21 +59,10 @@ function parseDefinition(text: string): ImportedDefinition { ? parsed.measurement_plan : null) as unknown as MeasurementPlan | null, graph: parsed.graph as unknown as ProtocolGraph, - publishedGraph, protocolDescription: optionalString(canvas.description) ?? optionalString(parsed.description), } } -function nextAvailableExperimentName(preferredName: string, existingNames: Iterable): string { - const preferred = preferredName.trim() || 'Imported Experiment' - const names = new Set(existingNames) - if (!names.has(preferred)) return preferred - - let number = 2 - while (names.has(`${preferred} (${number})`)) number += 1 - return `${preferred} (${number})` -} - export function CreateExperimentFromFileDialog({ open, onOpenChange, @@ -89,28 +74,31 @@ export function CreateExperimentFromFileDialog({ }) { const [definition, setDefinition] = useState(null) const [name, setName] = useState('') - const [nameEdited, setNameEdited] = useState(false) const [file, setFile] = useState(null) const [fileError, setFileError] = useState(null) const queryClient = useQueryClient() - const experimentsQuery = useQuery({ - queryKey: ['experiments', 'all-for-import'], - queryFn: () => experimentsApi.list({ includeArchived: true }), - enabled: open, - }) - const existingNames = useMemo( - () => experimentsQuery.data?.map((experiment) => experiment.name) ?? [], - [experimentsQuery.data], - ) - + const [packageId, setPackageId] = useState() + const isPackage = file?.name.toLowerCase().endsWith('.tar.gz') ?? false + const packageJob = useQuery({ queryKey: ['package-import', packageId], enabled: !!packageId, + queryFn: () => packageImportsApi.get(packageId!), + refetchInterval: query => ['completed', 'failed', 'cancelled', 'expired'].includes(query.state.data?.status ?? '') ? false : 1000 }) useEffect(() => { - if (!definition || nameEdited || !experimentsQuery.data) return - setName(nextAvailableExperimentName(definition.sourceName, existingNames)) - }, [definition, existingNames, experimentsQuery.data, nameEdited]) + if (packageJob.data?.status !== 'completed' || !packageJob.data.experiment_id) return + void queryClient.invalidateQueries({ queryKey: ['experiments'] }) + setPackageId(undefined) + onOpenChange(false) + onImported(packageJob.data.experiment_id) + }, [packageJob.data, queryClient, onOpenChange, onImported]) const importMutation = useMutation({ - mutationFn: () => { + mutationFn: async () => { + if (isPackage && file) { + const job = await packageImportsApi.create(newRequestKey()) + await packageImportsApi.upload(job.id, file) + setPackageId(job.id) + return null + } if (!definition) throw new Error('Choose an experiment definition first.') return experimentsApi.importDefinition({ name: name.trim(), @@ -121,56 +109,47 @@ export function CreateExperimentFromFileDialog({ design_spec: definition.designSpec, measurement_plan: definition.measurementPlan, graph: definition.graph, - published_graph: definition.publishedGraph, protocol_description: definition.protocolDescription, }) }, onSuccess: (experiment) => { + if (!experiment) return queryClient.invalidateQueries({ queryKey: ['experiments'] }) onOpenChange(false) onImported(experiment.id) }, - onError: async (error) => { - // A second tab may create this same name between the lookup above and - // the atomic insert. Refresh, then offer the next free suffix instead - // of leaving the user to discover and resolve the collision manually. - if (!(error instanceof ApiError) || error.status !== 409 || !definition) return - const experiments = await queryClient.fetchQuery({ - queryKey: ['experiments', 'all-for-import'], - queryFn: () => experimentsApi.list({ includeArchived: true }), - }) - setName(nextAvailableExperimentName(definition.sourceName, experiments.map((experiment) => experiment.name))) - setNameEdited(false) - importMutation.reset() - }, + }) function reset() { importMutation.reset() setDefinition(null) setName('') - setNameEdited(false) setFile(null) setFileError(null) } function handleOpenChange(next: boolean) { - if (next) reset() + if (next && !packageId) reset() onOpenChange(next) } async function handleFileSelected(file: File | null) { if (!file) return + setPackageId(undefined) importMutation.reset() + if (file.name.toLowerCase().endsWith('.tar.gz')) { + setDefinition(null) + setFile(file) + setFileError(null) + return + } setFileError(null) try { const parsed = parseDefinition(await file.text()) setDefinition(parsed) setFile(file) - setNameEdited(false) - // If the names request has not completed yet, the effect above fills in - // the collision-safe name as soon as it does. - setName(nextAvailableExperimentName(parsed.sourceName, existingNames)) + setName(parsed.sourceName) } catch (error) { setDefinition(null) setFile(null) @@ -179,7 +158,8 @@ export function CreateExperimentFromFileDialog({ } } - const collisionResolved = !!definition && name !== definition.sourceName + const packageActive = !!packageId && !['completed', 'failed', 'cancelled', 'expired'].includes(packageJob.data?.status ?? '') + const busy = importMutation.isPending || packageActive const mutationError = importMutation.error instanceof Error ? importMutation.error.message : null return ( @@ -188,7 +168,7 @@ export function CreateExperimentFromFileDialog({ Create experiment from file - Import the canvas and experiment definition into a new, editable experiment. Run history and artifact files are not imported. + Create an unpublished editable draft from JSON, or restore the experiment and its input assets from a package. Results are excluded.
@@ -196,10 +176,11 @@ export function CreateExperimentFromFileDialog({ void handleFileSelected(next)} - placeholder="Drop a JSON file or click to browse" + placeholder="Drop a JSON or .tar.gz file or click to browse" />
{definition && ( @@ -210,30 +191,35 @@ export function CreateExperimentFromFileDialog({ value={name} onChange={(event) => { setName(event.target.value) - setNameEdited(true) importMutation.reset() }} onKeyDown={(event) => { if (event.key === 'Enter' && name.trim()) importMutation.mutate() }} /> - {collisionResolved && ( -

- An experiment named “{definition.sourceName}” already exists, so a new available name was suggested. You can edit it. -

- )} + )} + {packageId &&

{packageJob.data?.status === 'failed' + ? packageJob.data.error : `Creating experiment… ${packageJob.data?.progress.phase ?? 'Uploading'}`}

} + {packageJob.error &&

{packageJob.error.message}

} + {packageJob.data?.status === 'failed' && } {fileError &&

{fileError}

} {importMutation.isError &&

{mutationError ?? 'Could not import this experiment.'}

} - - diff --git a/frontend/src/components/protocol/ExperimentDefinitionDownload.tsx b/frontend/src/components/protocol/ExperimentDefinitionDownload.tsx deleted file mode 100644 index 2017dd90..00000000 --- a/frontend/src/components/protocol/ExperimentDefinitionDownload.tsx +++ /dev/null @@ -1,112 +0,0 @@ -import { useState } from 'react' -import { Download } from 'lucide-react' -import { experimentsApi, protocolsApi } from '@/api/client' -import { Button } from '@/components/ui/button' -import type { Protocol } from '@/types/protocols' - -export function ExperimentDefinitionDownload({ experimentId, protocol }: { experimentId: string; protocol: Protocol }) { - const [downloadingDefinition, setDownloadingDefinition] = useState(false) - const [definitionDownloadError, setDefinitionDownloadError] = useState(null) - async function downloadDefinition() { - if (!protocol) return - setDownloadingDefinition(true) - setDefinitionDownloadError(null) - try { - // Read fresh rather than exporting whichever React Query snapshot - // happens to be on screen. A portable definition should describe one - // coherent point in time, including the currently published canvas. - const [experiment, canvas, designRevisions] = await Promise.all([ - experimentsApi.get(experimentId), - protocolsApi.get(protocol.id), - experimentsApi.listDesignRevisions(experimentId), - ]) - const revisionIds = [...new Set([canvas.published_revision_id, experiment.locked_protocol_revision_id].filter((id): id is string => !!id))] - const revisions = await Promise.all(revisionIds.map((revisionId) => protocolsApi.getRevision(canvas.id, revisionId))) - const revisionById = new Map(revisions.map((revision) => [revision.id, revision])) - const publishedCanvas = canvas.published_revision_id ? revisionById.get(canvas.published_revision_id) ?? null : null - const lockedCanvas = experiment.locked_protocol_revision_id ? revisionById.get(experiment.locked_protocol_revision_id) ?? null : null - const payload = { - format: 'asaree.experiment-definition', - schema_version: 1, - exported_at: new Date().toISOString(), - // The existing canvas importer consumes these two top-level fields. - // Keep them as the current draft while the richer envelope below - // carries immutable published/locked snapshots and provenance. - name: experiment.name, - description: canvas.description, - graph: canvas.graph, - design_spec: experiment.design_spec, - measurement_plan: experiment.measurement_plan, - experiment: { - source_id: experiment.id, - name: experiment.name, - description: experiment.description, - hypothesis: experiment.hypothesis, - design_type: experiment.design_type, - task_brief: experiment.task_brief, - design_spec: experiment.design_spec, - measurement_plan: experiment.measurement_plan, - dataset_ids: experiment.dataset_ids, - archived_at: experiment.archived_at, - created_at: experiment.created_at, - updated_at: experiment.updated_at, - lock: experiment.locked_at ? { - locked_at: experiment.locked_at, - source_protocol_revision_id: experiment.locked_protocol_revision_id, - design_spec: experiment.locked_design_spec, - measurement_plan: experiment.locked_measurement_plan, - canvas_revision: lockedCanvas ? { - source_id: lockedCanvas.id, - revision: lockedCanvas.revision, - published_at: lockedCanvas.published_at, - graph: lockedCanvas.graph, - } : null, - } : null, - }, - canvas: { - source_protocol_id: canvas.id, - name: canvas.name, - description: canvas.description, - draft: { graph: canvas.graph, updated_at: canvas.updated_at }, - published: publishedCanvas ? { - source_id: publishedCanvas.id, - revision: publishedCanvas.revision, - published_at: publishedCanvas.published_at, - graph: publishedCanvas.graph, - } : null, - has_unpublished_changes: canvas.has_unpublished_changes, - }, - design_revisions: designRevisions.map((revision) => ({ - source_id: revision.id, - revision: revision.revision, - superseded_at: revision.superseded_at, - design_spec: revision.design_spec, - cell_count: revision.cell_count, - replicate_count: revision.replicate_count, - scored_replicate_count: revision.scored_replicate_count, - created_at: revision.created_at, - })), - portability: { - excluded: ['provider credential secrets', 'replicate results and run history', 'dataset file contents', 'knowledge bundle/document contents', 'skill file contents'], - note: 'All canvas nodes and their configuration are included. Dataset, Knowledge, and Skill nodes retain their labels and resource IDs as references; recreate or map their external artifacts before importing into another workspace.', - }, - } - const name = experiment.name || canvas.name - const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' }) - const url = URL.createObjectURL(blob) - const link = document.createElement('a') - link.href = url - link.download = `${name.trim().replace(/[^a-z0-9]+/gi, '-').replace(/(^-|-$)/g, '') || 'experiment'}.json` - link.click() - URL.revokeObjectURL(url) - } catch { - setDefinitionDownloadError('Could not prepare the experiment definition. Please try again.') - } finally { - setDownloadingDefinition(false) - } - } - - return <>{definitionDownloadError &&

{definitionDownloadError}

} -} diff --git a/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx b/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx index 173a3c69..3880eaf4 100644 --- a/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx +++ b/frontend/src/components/protocol/ExperimentPackageDownload.test.tsx @@ -1,189 +1,67 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' -import { experimentsApi, protocolsApi, packageImportsApi } from '@/api/client' -import type { Protocol, ProtocolRevision } from '@/types/protocols' +import { experimentsApi, protocolsApi } from '@/api/client' +import type { Protocol } from '@/types/protocols' import { ExperimentPackageDownload } from './ExperimentPackageDownload' -import { protocolForExperimentQueryKey, protocolGraphQueryKey } from '@/lib/protocolGraph' +import { protocolGraphQueryKey } from '@/lib/protocolGraph' afterEach(() => vi.restoreAllMocks()) - const protocol: Protocol = { id: 'p', name: 'Protocol', description: null, experiment_id: 'e', graph: { nodes: [], edges: [] }, published_revision_id: 'current', published_revision: 2, - has_unpublished_changes: true, created_at: '', updated_at: '' } -const versions: ProtocolRevision[] = [ - { id: 'old', protocol_id: 'p', revision: 1, graph: { nodes: [], edges: [] }, published_at: '2026-01-01', experiment_snapshot: null }, - { id: 'current', protocol_id: 'p', revision: 2, graph: { nodes: [], edges: [] }, published_at: '2026-01-02' }, -] - -function show(selectedVersionId?: string, draft = protocol) { - vi.spyOn(packageImportsApi, 'list').mockResolvedValue([]) + has_unpublished_changes: false, created_at: '', updated_at: '' } +function show(draft = protocol, selectedVersionId?: string, draftBusy = false) { + vi.spyOn(protocolsApi, 'get').mockResolvedValue(draft) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) render() + selectedVersionId={selectedVersionId} draftBusy={draftBusy} />) return client } -it('warns about unpublished changes and publishes the live canvas before packaging the returned version', async () => { - const published = { ...protocol, published_revision_id: 'new', published_revision: 3, has_unpublished_changes: false } - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValueOnce(versions) - .mockResolvedValue([...versions, { ...versions[1], id: 'new', revision: 3 }]) - let finishSave!: (value: Protocol) => void - const save = vi.spyOn(protocolsApi, 'update').mockImplementation(() => new Promise(resolve => { finishSave = resolve })) - const publish = vi.spyOn(protocolsApi, 'publish').mockResolvedValue(published) - const prepared = { id: 'new-job', kind: 'export', status: 'completed', protocol_revision_id: 'new', progress: {}, error: null } as const - const prepare = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(prepared) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(prepared) - const client = show('old') - const graph = { nodes: [{ id: 'unsaved', type: 'agent', position: { x: 0, y: 0 }, data: { label: 'Unsaved agent' } }], edges: [] } - client.setQueryData(protocolGraphQueryKey('p'), graph) - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - expect(await screen.findByText('Experiment has unpublished changes')).toBeInTheDocument() - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - fireEvent.click(screen.getByRole('checkbox')) - fireEvent.click(screen.getByRole('button', { name: 'Publish & prepare package' })) - await waitFor(() => expect(save).toHaveBeenCalledWith('p', { graph })) +it.each([ + { ...protocol, has_unpublished_changes: true }, + { ...protocol, published_revision_id: null, published_revision: null }, +])('requires publication and offers no publish shortcut', async draft => { + const create = vi.spyOn(experimentsApi, 'createResultJob') + const publish = vi.spyOn(protocolsApi, 'publish') + show(draft) + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + expect(await screen.findByText('Publish before exporting')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: /Publish/ })).not.toBeInTheDocument() + expect(create).not.toHaveBeenCalled() expect(publish).not.toHaveBeenCalled() - expect(prepare).not.toHaveBeenCalled() - expect(screen.getByRole('combobox')).toBeDisabled() - await act(async () => { finishSave(protocol) }) - await waitFor(() => expect(prepare).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'new' }, expect.objectContaining({ include_results: true }))) - expect(publish).toHaveBeenCalledWith('p') - expect(client.getQueryData(protocolForExperimentQueryKey('e'))).toEqual(published) - expect(screen.getByRole('combobox')).toHaveValue('new') -}) - -it('allows publication and package preparation before the first version exists', async () => { - const published = { ...protocol, has_unpublished_changes: false } - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValueOnce([]).mockResolvedValue([versions[1]]) - vi.spyOn(protocolsApi, 'publish').mockResolvedValue(published) - const prepare = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'fixture' }) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'fixture' }) - show(undefined, { ...protocol, published_revision_id: null, published_revision: null }) - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - expect(await screen.findByText('Experiment has not been published')).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Prepare package' })).toBeDisabled() - fireEvent.click(screen.getByRole('button', { name: 'Publish & prepare package' })) - await waitFor(() => expect(prepare).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'current' }, expect.anything())) -}) - -it('reports publication failure without preparing an older version', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(protocolsApi, 'publish').mockRejectedValue(new Error('Generate cells before publishing.')) - const prepare = vi.spyOn(experimentsApi, 'createResultJob') - show('old') - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - fireEvent.click(await screen.findByRole('button', { name: 'Publish & prepare package' })) - expect(await screen.findByRole('alert')).toHaveTextContent('Generate cells before publishing.') - expect(prepare).not.toHaveBeenCalled() - expect(screen.getByRole('combobox')).toHaveValue('old') -}) - -it('starts from the viewed historical publication and explicitly opts into results', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'pending', - protocol_revision_id: 'old', progress: {}, error: null }) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'completed', - protocol_revision_id: 'old', progress: { completeness: { status: 'incomplete', unresolved_count: 1, - included_dependencies: 4, destination_connections: 2, - issues: [{ kind: 'split', id: 'historical-split', reason: 'Pinned split unavailable' }] } }, - error: null, download_url: '/old-package', schema_url: '/manifest' }) - show('old') - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - expect(screen.getByRole('combobox', { name: 'Published version' })).toHaveValue('old') - expect(screen.getByRole('checkbox')).not.toBeChecked() - fireEvent.click(screen.getByRole('checkbox')) - fireEvent.click(screen.getByRole('button', { name: 'Prepare package' })) - await waitFor(() => expect(experimentsApi.createResultJob).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'old' }, - expect.objectContaining({ kind: 'export', format: 'experiment_package', include_results: true }))) - expect(await screen.findByRole('link', { name: 'Download prepared package' })).toHaveAttribute('href', '/old-package') - expect(screen.getByRole('link', { name: 'Manifest' })).toHaveAttribute('href', '/manifest') - expect(screen.getByText('Incomplete package')).toBeInTheDocument() - expect(screen.getByText('4 included dependencies')).toBeInTheDocument() - expect(screen.getByText(/2 destination connection requirements/)).toBeInTheDocument() - expect(screen.getByText(/Pinned split unavailable/)).toBeInTheDocument() }) -it('does not offer publication for an unchanged published experiment', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - show(undefined, { ...protocol, has_unpublished_changes: false }) - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await screen.findByRole('combobox') - expect(screen.queryByRole('button', { name: 'Publish & prepare package' })).not.toBeInTheDocument() - expect(screen.queryByText('Experiment has unpublished changes')).not.toBeInTheDocument() +it('blocks a canvas edit that has not reached autosave', async () => { + const create = vi.spyOn(experimentsApi, 'createResultJob') + const client = show() + client.setQueryData(protocolGraphQueryKey('p'), { nodes: [{ id: 'new', type: 'agent', position: { x: 0, y: 0 }, data: {} }], edges: [] }) + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + expect(await screen.findByText('Publish before exporting')).toBeInTheDocument() + expect(create).not.toHaveBeenCalled() }) -it('defaults to the published version and sends results excluded', async () => { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'Package unavailable' }) - vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue({ id: 'job', kind: 'export', status: 'failed', - protocol_revision_id: 'current', progress: {}, error: 'Package unavailable' }) +it('exports the published version without a results option and starts the download automatically', async () => { + const job = { id: 'job', kind: 'export', status: 'completed', protocol_revision_id: 'current', + progress: {}, error: null, download_url: '/package' } as const + const create = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(job) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(job) + const download = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) show() - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - expect(screen.getByRole('combobox', { name: 'Published version' })).toHaveValue('current') - fireEvent.click(screen.getByRole('button', { name: 'Prepare package' })) - await waitFor(() => expect(experimentsApi.createResultJob).toHaveBeenCalledWith('e', - { protocol_id: 'p', protocol_revision_id: 'current' }, - expect.objectContaining({ include_results: false }))) - expect(await screen.findByRole('alert')).toHaveTextContent('Package unavailable') -}) - -const completed = { id: 'job', kind: 'export', status: 'completed', protocol_revision_id: 'old', - progress: {}, error: null, download_url: '/package?token=expired', schema_url: '/manifest?token=expired' } as const - -async function prepareCompletedPackage() { - vi.spyOn(protocolsApi, 'listRevisions').mockResolvedValue(versions) - vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(completed) - const status = vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(completed) - show('old') - fireEvent.click(screen.getByRole('button', { name: 'Download experiment package' })) - await waitFor(() => expect(screen.getAllByRole('option')).toHaveLength(2)) - fireEvent.click(screen.getByRole('button', { name: 'Prepare package' })) - await screen.findByRole('link', { name: 'Download prepared package' }) - return status -} - -it('renews stale archive and manifest URLs on activation and uses native navigation', async () => { - const status = await prepareCompletedPackage() - const navigated: string[] = [] - vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { - navigated.push(this.getAttribute('href') ?? '') - }) - status.mockResolvedValue({ ...completed, download_url: '/package?token=fresh', schema_url: '/manifest?token=fresh' }) - fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' })) - await waitFor(() => expect(navigated).toEqual(['/package?token=fresh'])) - fireEvent.click(screen.getByRole('link', { name: 'Manifest' })) - await waitFor(() => expect(navigated).toEqual(['/package?token=fresh', '/manifest?token=fresh'])) - expect(status).toHaveBeenCalledTimes(3) - expect(status).toHaveBeenLastCalledWith('e', 'job', expect.any(AbortSignal)) -}) - -it('reports link renewal failure without navigating to the expired URL', async () => { - const status = await prepareCompletedPackage() - const navigate = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) - status.mockRejectedValue(new Error('Status unavailable')) - fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' })) - expect(await screen.findByRole('alert')).toHaveTextContent('Could not refresh the download link. Try again.') - expect(navigate).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + await waitFor(() => expect(download).toHaveBeenCalledTimes(1)) + expect(create).toHaveBeenCalledWith('e', { protocol_id: 'p', protocol_revision_id: 'current' }, + expect.objectContaining({ kind: 'export', format: 'experiment_package' })) + expect(create.mock.calls[0][2]).not.toHaveProperty('include_results') + expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() }) -it('does not navigate after the selected version changes while renewal is pending', async () => { - const status = await prepareCompletedPackage() - const navigate = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) - let finish!: (value: Awaited>) => void - status.mockImplementation(() => new Promise(resolve => { finish = resolve })) - fireEvent.click(screen.getByRole('link', { name: 'Download prepared package' })) - await waitFor(() => expect(status).toHaveBeenCalledTimes(2)) - fireEvent.change(screen.getByRole('combobox', { name: 'Published version' }), { target: { value: 'current' } }) - await act(async () => { finish({ ...completed, download_url: '/package?token=fresh' }) }) - expect(navigate).not.toHaveBeenCalled() - expect(screen.queryByRole('link', { name: 'Download prepared package' })).not.toBeInTheDocument() +it('exports an explicitly viewed historical publication while the draft has changes', async () => { + const job = { id: 'job', kind: 'export', status: 'failed', protocol_revision_id: 'old', progress: {}, error: 'Missing Skill file' } as const + const create = vi.spyOn(experimentsApi, 'createResultJob').mockResolvedValue(job) + vi.spyOn(experimentsApi, 'getResultJob').mockResolvedValue(job) + show({ ...protocol, has_unpublished_changes: true }, 'old') + fireEvent.click(screen.getByRole('button', { name: 'Download' })) + expect(await screen.findByRole('alert')).toHaveTextContent('Missing Skill file') + expect(create).toHaveBeenCalledWith('e', { protocol_id: 'p', protocol_revision_id: 'old' }, expect.anything()) }) diff --git a/frontend/src/components/protocol/ExperimentPackageDownload.tsx b/frontend/src/components/protocol/ExperimentPackageDownload.tsx index e570597d..2dd629c0 100644 --- a/frontend/src/components/protocol/ExperimentPackageDownload.tsx +++ b/frontend/src/components/protocol/ExperimentPackageDownload.tsx @@ -1,5 +1,5 @@ -import { useEffect, useRef, useState, type MouseEvent } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useEffect, useRef, useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' import type { Edge, Node } from '@xyflow/react' import { Download } from 'lucide-react' import { experimentsApi, protocolsApi } from '@/api/client' @@ -7,150 +7,66 @@ import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { jobActive, useResultJob } from '@/lib/resultJobs' import { newRequestKey } from '@/lib/requestKey' -import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' -import { executionKeys } from '@/lib/executionQueries' +import { protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' import type { Protocol } from '@/types/protocols' -import { ExperimentPackageImport } from './ExperimentPackageImport' -export function ExperimentPackageDownload({ experimentId, protocol, selectedVersionId }: { - experimentId: string; protocol: Protocol; selectedVersionId?: string +export function ExperimentPackageDownload({ experimentId, protocol, selectedVersionId, draftBusy = false }: { + experimentId: string; protocol: Protocol; selectedVersionId?: string; draftBusy?: boolean }) { + const [publicationWarning, setPublicationWarning] = useState(false) const client = useQueryClient() - const [open, setOpen] = useState(false) - const [versionId, setVersionId] = useState('') - const [includeResults, setIncludeResults] = useState(false) const [jobId, setJobId] = useState() - const [linkPending, setLinkPending] = useState(false) - const [linkError, setLinkError] = useState() - const linkScope = useRef('') - linkScope.current = JSON.stringify({ experimentId, protocolId: protocol.id, versionId, includeResults, jobId, open }) - const versions = useQuery({ queryKey: ['protocols', protocol.id, 'revisions'], - queryFn: () => protocolsApi.listRevisions(protocol.id), enabled: open }) + const [revisionId, setRevisionId] = useState() + const [requestScope, setRequestScope] = useState() + const downloaded = useRef(null) + const scope = JSON.stringify({ experimentId, protocolId: protocol.id, version: selectedVersionId || 'draft' }) const job = useResultJob(experimentId, jobId) - useEffect(() => { - if (open && !versionId && versions.data?.length) setVersionId(versions.data[0].id) - }, [open, versionId, versions.data]) - const create = useMutation({ - mutationFn: (revisionId: string) => experimentsApi.createResultJob(experimentId, - { protocol_id: protocol.id, protocol_revision_id: revisionId }, - { kind: 'export', request_key: newRequestKey(), format: 'experiment_package', include_results: includeResults }), - onSuccess: result => setJobId(result.id), - }) - const publish = useMutation({ + const prepare = useMutation({ mutationFn: async () => { + const fresh = await protocolsApi.get(protocol.id) const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(protocol.id)) - if (live) await protocolsApi.update(protocol.id, { graph: toPersistedGraph(live.nodes, live.edges) }) - const published = await protocolsApi.publish(protocol.id) - if (!published.published_revision_id) throw new Error('Publication did not return a downloadable version.') - return published - }, - onSuccess: async published => { - client.setQueryData(protocolForExperimentQueryKey(experimentId), published) - void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) - void client.invalidateQueries({ queryKey: executionKeys.root(experimentId) }) - setVersionId(published.published_revision_id!) - setJobId(undefined) - await client.invalidateQueries({ queryKey: ['protocols', protocol.id, 'revisions'] }) - create.mutate(published.published_revision_id!) + const saved = toPersistedGraph(fresh.graph.nodes as Node[], fresh.graph.edges as Edge[]) + const unsaved = live && JSON.stringify(toPersistedGraph(live.nodes, live.edges)) !== JSON.stringify(saved) + if (!selectedVersionId && (draftBusy || unsaved || fresh.has_unpublished_changes || !fresh.published_revision_id)) { + setPublicationWarning(true) + return null + } + const version = selectedVersionId || fresh.published_revision_id! + setRevisionId(version) + setRequestScope(scope) + return experimentsApi.createResultJob(experimentId, + { protocol_id: protocol.id, protocol_revision_id: version }, + { kind: 'export', request_key: newRequestKey(), format: 'experiment_package' }) }, + onSuccess: result => setJobId(result?.id), }) - const needsPublish = !protocol.published_revision_id || protocol.has_unpublished_changes - const busy = publish.isPending || create.isPending || jobActive(job.data) || (!!jobId && !job.data && !job.error) - const error = linkError ?? publish.error?.message ?? create.error?.message ?? job.error?.message ?? job.data?.error - async function download(event: MouseEvent, metadata: boolean) { - event.preventDefault() - if (linkPending || !jobId) return - const requestedJob = jobId - const requestedScope = linkScope.current - setLinkError(undefined) - setLinkPending(true) - try { - const fresh = (await job.refetch({ throwOnError: true })).data - if (linkScope.current !== requestedScope) return - const url = metadata ? fresh?.schema_url : fresh?.download_url - if (fresh?.id !== requestedJob || fresh.protocol_revision_id !== versionId || fresh.status !== 'completed' || !url) { - setLinkError('This package is no longer available. Prepare a new download.') - return - } - // Keep the server's native Content-Disposition download; only status is - // fetched through the authenticated API, never the archive as a Blob. - const link = document.createElement('a') - link.href = url - link.click() - } catch { - if (linkScope.current === requestedScope) setLinkError('Could not refresh the download link. Try again.') - } finally { - setLinkPending(false) - } - } + useEffect(() => { + const ready = job.data + if (ready?.status !== 'completed' || !ready.download_url || requestScope !== scope + || ready.protocol_revision_id !== revisionId || downloaded.current === ready.id) return + downloaded.current = ready.id + const link = document.createElement('a') + link.href = ready.download_url + link.click() + }, [job.data, revisionId, scope, requestScope]) + const busy = prepare.isPending || jobActive(job.data) || (!!jobId && !job.data && !job.error) + const error = prepare.error?.message || job.error?.message || job.data?.error return <> - - - - Download published experiment - - - -

Includes published configuration and pinned dataset inputs. Reusable skills and knowledge are captured at download time. The manifest identifies missing dependencies and historical evidence.

-

Credentials are excluded. Prepared downloads expire after 24 hours.

- {versions.isError &&

Could not load published versions.

} - {versions.data?.length === 0 &&

Publish the experiment to create its first downloadable version.

} - {needsPublish &&
-

{protocol.published_revision_id ? 'Experiment has unpublished changes' : 'Experiment has not been published'}

-

Publish the draft to include its current canvas, design settings, and dataset inputs in a new package. Preparing a selected published version includes only that version’s recorded configuration and inputs.

-
} - {error &&

{error}

} - {job.data?.status === 'expired' &&

This package expired. Prepare another download.

} - {job.data?.status === 'cancelled' &&

Package preparation cancelled.

} - {busy &&

Preparing package · {job.data?.progress.bytes?.toLocaleString() ?? 0} bytes

} - {linkPending &&

Refreshing download link…

} - {job.data?.status === 'completed' && job.data.progress.completeness &&
-

{job.data.progress.completeness.status === 'incomplete' ? 'Incomplete package' : 'Package content complete'}

-

{job.data.progress.completeness.included_dependencies} included dependencies

-

{job.data.progress.completeness.destination_connections} destination connection requirements · credentials excluded

-

{job.data.progress.completeness.unresolved_count} missing or unresolved dependencies

- {job.data.progress.completeness.issues.map((issue, index) =>

{issue.kind} {issue.id}: {issue.reason}

)} -
} - {job.data?.status === 'completed' && job.data.progress.sha256 &&

SHA-256: {job.data.progress.sha256}

} -
- {needsPublish && } - - {busy && jobId && } - {job.data?.status === 'completed' && <> - { void download(event, false) }}>Download prepared package - { void download(event, true) }}>Manifest - } -
+ if (!selectedVersionId && (draftBusy || protocol.has_unpublished_changes || !protocol.published_revision_id)) { + setPublicationWarning(true) + } else prepare.mutate() + }}>{busy ? 'Preparing download…' : 'Download'} + {busy && Preparing experiment and input assets…} + {error &&

{error}

} + + + Publish before exporting +

Publish your current canvas and design changes using Publish experiment, then download the package.

+

The package includes all required input assets. Results and execution history are excluded.

+
diff --git a/frontend/src/components/protocol/ExperimentPackageImport.test.tsx b/frontend/src/components/protocol/ExperimentPackageImport.test.tsx deleted file mode 100644 index 3a384a13..00000000 --- a/frontend/src/components/protocol/ExperimentPackageImport.test.tsx +++ /dev/null @@ -1,194 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' -import { MemoryRouter } from 'react-router-dom' -import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest' -import { packageImportsApi } from '@/api/client' -import type { PackageImport } from '@/types/packageImports' -import { ExperimentPackageImport } from './ExperimentPackageImport' - -afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) - -// CodeMirror measures text ranges; jsdom provides no layout implementation. -const rangeRect = Object.getOwnPropertyDescriptor(Range.prototype, 'getBoundingClientRect') -const rangeRects = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects') -beforeAll(() => { - Object.defineProperties(Range.prototype, { - getBoundingClientRect: { configurable: true, value: () => new DOMRect() }, - getClientRects: { configurable: true, value: () => [] }, - }) -}) -afterAll(() => { - for (const [name, descriptor] of [['getBoundingClientRect', rangeRect], ['getClientRects', rangeRects]] as const) { - if (descriptor) Object.defineProperty(Range.prototype, name, descriptor) - else Reflect.deleteProperty(Range.prototype, name) - } -}) - -const ready: PackageImport = { id: 'request', status: 'awaiting_confirmation', sha256: 'source-hash', - experiment_id: null, configured_at: null, created_at: '', expires_at: '', error: null, - progress: { phase: 'preflight_ready' }, preflight: { manifest: { schema_version: 2, - experiment_id: 'source', publication: { id: 'publication', version: 7, published_at: '' }, results_included: true }, - categories: { inputs: 4, results: 12 }, unresolved_count: 1, external_requirements: 2, - warnings: ['Configure local credentials before publication.'], - diagnostics: [{ id: 'missing', kind: 'dataset_file', status: 'missing', reason: 'Pinned file unavailable' }] } } - -function show(items: PackageImport[] = []) { - vi.spyOn(packageImportsApi, 'list').mockResolvedValue(items) - vi.spyOn(packageImportsApi, 'get').mockResolvedValue(ready) - vi.spyOn(packageImportsApi, 'files').mockResolvedValue({ items: [], next_offset: null }) - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - render() -} - -it('uploads for inspection and requires an explicit confirmation after showing requirements', async () => { - vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) }) - const create = vi.spyOn(packageImportsApi, 'create').mockResolvedValue({ ...ready, status: 'uploading', preflight: {} }) - const upload = vi.spyOn(packageImportsApi, 'upload').mockResolvedValue({ ...ready, status: 'validating' }) - const command = vi.spyOn(packageImportsApi, 'command').mockResolvedValue({ ...ready, status: 'queued' }) - show() - const file = new File(['archive bytes'], 'package.tar.gz', { type: 'application/gzip' }) - const input = screen.getByLabelText('Experiment package') - expect(input.accept.split(',')).toEqual(expect.arrayContaining(['.gz', 'application/gzip'])) - fireEvent.change(input, { target: { files: [file] } }) - await waitFor(() => expect(upload).toHaveBeenCalledWith('request', file, expect.any(AbortSignal))) - expect(create).toHaveBeenCalledOnce() - expect(command).not.toHaveBeenCalled() - expect(await screen.findByText(/Source version 7/)).toBeInTheDocument() - expect(screen.getByText(/Pinned file unavailable/)).toBeInTheDocument() - expect(screen.getByText(/Configure local credentials/)).toBeInTheDocument() - fireEvent.click(screen.getByRole('button', { name: 'Confirm import into a new experiment' })) - await waitFor(() => expect(command).toHaveBeenCalledWith('request', 'confirm')) -}) - -it('resumes persisted requests and allows cancellation before activation', async () => { - const command = vi.spyOn(packageImportsApi, 'command').mockResolvedValue({ ...ready, status: 'cancelled' }) - show([ready]) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByRole('button', { name: 'Cancel import' })) - await waitFor(() => expect(command).toHaveBeenCalledWith('request', 'cancel')) -}) - -it('drops a package into the existing inspection flow without confirming import', async () => { - const create = vi.spyOn(packageImportsApi, 'create').mockResolvedValue({ ...ready, status: 'uploading', preflight: {} }) - const upload = vi.spyOn(packageImportsApi, 'upload').mockResolvedValue({ ...ready, status: 'validating' }) - const command = vi.spyOn(packageImportsApi, 'command') - show() - const file = new File(['archive bytes'], 'experiment.tgz', { type: 'application/gzip' }) - const target = screen.getByText('Drop a .tar.gz or .tgz package or click to browse').closest('label')! - fireEvent.dragOver(target) - fireEvent.drop(target, { dataTransfer: { files: [file] } }) - await waitFor(() => expect(upload).toHaveBeenCalledWith('request', file, expect.any(AbortSignal))) - expect(create).toHaveBeenCalledOnce() - expect(command).not.toHaveBeenCalled() - expect(screen.getByText('experiment.tgz')).toBeInTheDocument() - expect(await screen.findByText(/Source version 7/)).toBeInTheDocument() -}) - -it('prevents additional drops and file selection while uploading', async () => { - const create = vi.spyOn(packageImportsApi, 'create').mockResolvedValue({ ...ready, status: 'uploading', preflight: {} }) - const upload = vi.spyOn(packageImportsApi, 'upload').mockReturnValue(new Promise(() => {})) - show() - const input = screen.getByLabelText('Experiment package') - const target = input.closest('label')! - const file = new File(['archive bytes'], 'experiment.tar.gz') - fireEvent.drop(target, { dataTransfer: { files: [file] } }) - await waitFor(() => expect(upload).toHaveBeenCalledOnce()) - expect(input).toBeDisabled() - fireEvent.drop(target, { dataTransfer: { files: [new File(['other'], 'other.tgz')] } }) - expect(create).toHaveBeenCalledOnce() - expect(upload).toHaveBeenCalledOnce() -}) - -it('shows readiness and a direct draft link without an acknowledgement gate', async () => { - const complete = { ...ready, status: 'completed', experiment_id: 'local-experiment' } - vi.spyOn(packageImportsApi, 'readiness').mockResolvedValue({ ready: true, issues: [], mcp: [], providers: [] }) - show([complete]) - vi.mocked(packageImportsApi.get).mockResolvedValue(complete) - fireEvent.click(await screen.findByRole('button', { name: /request.*Imported/ })) - expect(await screen.findByText('Ready to publish')).toBeInTheDocument() - expect(screen.getByRole('link', { name: 'Open editable draft' })).toHaveAttribute('href', '/experiments/local-experiment/protocol') - expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() -}) - -it('inspects immutable observation evidence without coercing null or unavailable values', async () => { - show([ready]) - const path = 'results/attempts/source-attempt/attempt_result.json' - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: [{ path, sha256: 'exact-hash', bytes: 200, - source_id: 'source-attempt', provenance: 'recorded_attempt' }], next_offset: null }) - const source = '{"observations":[{"status":"measured","value":null},{"status":"unavailable"}]}' - vi.spyOn(packageImportsApi, 'source').mockResolvedValue(new Blob([source])) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click(await screen.findByRole('button', { name: 'Inspect JSON' })) - const viewer = await screen.findByRole('textbox', { name: 'JSON source' }) - expect(viewer).toHaveAttribute('aria-readonly', 'true') - expect(viewer).toHaveTextContent('"status": "measured"') - expect(viewer).toHaveTextContent('"value": null') - expect(viewer).toHaveTextContent('"status": "unavailable"') - fireEvent.click(screen.getByRole('button', { name: 'Original' })) - await waitFor(() => expect(viewer.textContent).toBe(source)) - expect(packageImportsApi.source).toHaveBeenCalledWith('request', path) -}) - -it('opens JSON inspection immediately while the file request is pending', async () => { - show([ready]) - const path = 'publication/settings.json' - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: [{ path, sha256: 'hash', bytes: 100, - source_id: 'publication', provenance: 'publication_pinned' }], next_offset: null }) - let finish!: (value: Response) => void - const fetchFile = vi.spyOn(globalThis, 'fetch').mockImplementation(() => new Promise(resolve => { finish = resolve })) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click(await screen.findByRole('button', { name: 'Inspect JSON' })) - const dialog = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - expect(within(dialog).getByRole('status')).toHaveTextContent('Loading JSON') - expect(within(dialog).getByText(path)).toBeInTheDocument() - await waitFor(() => expect(fetchFile).toHaveBeenCalledWith( - '/api/experiment-package-imports/request/source?path=publication%2Fsettings.json', expect.anything())) - const source = '{"exact_integer":9007199254740993,"value":null}' - await act(async () => { finish(new Response(source, { headers: { 'Content-Type': 'application/octet-stream' } })) }) - expect(await within(dialog).findByRole('textbox', { name: 'JSON source' })).toHaveTextContent('9007199254740993') -}) - -it('shows source-loading errors in the inspector and allows retry', async () => { - show([ready]) - const path = 'publication/settings.json' - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: [{ path, sha256: 'hash', bytes: 100, - source_id: 'publication', provenance: 'publication_pinned' }], next_offset: null }) - const source = vi.spyOn(packageImportsApi, 'source').mockRejectedValueOnce(new Error('Source file unavailable')) - .mockResolvedValue(new Blob(['{"restored":true}'])) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click(await screen.findByRole('button', { name: 'Inspect JSON' })) - const dialog = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - expect(await within(dialog).findByRole('alert')).toHaveTextContent('Source file unavailable') - fireEvent.click(within(dialog).getByRole('button', { name: 'Retry loading file' })) - expect(await within(dialog).findByRole('textbox', { name: 'JSON source' })).toHaveTextContent('"restored": true') - expect(source).toHaveBeenCalledTimes(2) - expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument() -}) - -it('keeps a late response from reopening a closed inspector or replacing a newer file', async () => { - show([ready]) - vi.mocked(packageImportsApi.files).mockResolvedValue({ items: ['first.json', 'second.json'].map(path => ({ - path, sha256: 'hash', bytes: 100, source_id: path, provenance: 'publication_pinned', - })), next_offset: null }) - let finishFirst!: (value: Blob) => void - vi.spyOn(packageImportsApi, 'source').mockImplementationOnce(() => new Promise(resolve => { finishFirst = resolve })) - .mockResolvedValue(new Blob(['{"file":"second"}'])) - fireEvent.click(await screen.findByRole('button', { name: /request.*Ready to review/ })) - fireEvent.click(await screen.findByText('Inspect source files and historical evidence')) - fireEvent.click((await screen.findAllByRole('button', { name: 'Inspect JSON' }))[0]) - const first = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - fireEvent.click(within(first).getByRole('button', { name: 'Close source inspection' })) - await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) - fireEvent.click(screen.getAllByRole('button', { name: 'Inspect JSON' })[1]) - const second = await screen.findByRole('dialog', { name: 'Inspect JSON' }) - const viewer = await within(second).findByRole('textbox', { name: 'JSON source' }) - expect(viewer).toHaveTextContent('"file": "second"') - await act(async () => { finishFirst(new Blob(['{"file":"first"}'])) }) - expect(within(second).getByText('second.json')).toBeInTheDocument() - expect(viewer).toHaveTextContent('"file": "second"') - fireEvent.click(within(second).getByRole('button', { name: 'Close source inspection' })) - await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) -}) diff --git a/frontend/src/components/protocol/ExperimentPackageImport.tsx b/frontend/src/components/protocol/ExperimentPackageImport.tsx deleted file mode 100644 index f34f5035..00000000 --- a/frontend/src/components/protocol/ExperimentPackageImport.tsx +++ /dev/null @@ -1,278 +0,0 @@ -import { useId, useRef, useState } from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Link } from 'react-router-dom' -import { ChevronDown, Download, File, FileJson, Search } from 'lucide-react' -import { packageImportsApi } from '@/api/client' -import { Button } from '@/components/ui/button' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' -import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' -import { Badge } from '@/components/ui/badge' -import type { PackageImport } from '@/types/packageImports' -import { newRequestKey } from '@/lib/requestKey' -import { FileDropInput } from './FileDropInput' -import { JsonSourceViewer } from './JsonSourceViewer' -import { ImportedExperimentSetup } from './ImportedExperimentSetup' - -const provenanceLabels: Record = { - publication_pinned: 'Published snapshot', - captured_at_download: 'Captured at export', - recorded_attempt: 'Recorded attempt', - retained_attempt_artifact: 'Retained artifact', - 'legacy.unknown': 'Unknown historical source', -} - -function fileSize(bytes: number): string { - if (bytes < 1024) return `${bytes.toLocaleString()} B` - const unit = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), 3) - return `${(bytes / 1024 ** unit).toLocaleString(undefined, { maximumFractionDigits: 1 })} ${['B', 'KiB', 'MiB', 'GiB'][unit]}` -} - -const categoryLabels: Record = { - inputs: 'Dataset files and metadata', - resources: 'Scripts, skills, and knowledge', - publication: 'Published configuration', - requirements: 'Local requirements', - results: 'Historical results', - design: 'Experimental design', - sources: 'Imported source evidence', - 'dependencies.jsonl': 'Dependency inventory', - 'experiment-metadata.json': 'Experiment details', -} - -const statusLabels: Record = { - uploading: 'Uploading package', - validating: 'Checking package', - awaiting_confirmation: 'Ready to review', - queued: 'Import queued', - activating: 'Creating experiment', - completed: 'Imported', - failed: 'Import failed', - cancelled: 'Cancelled', - expired: 'Expired', -} - -function PackageSummary({ current }: { current: PackageImport }) { - const { manifest, categories, unresolved_count: unresolved, external_requirements: external } = current.preflight - if (!manifest) return null - const contents = Object.entries(categories ?? {}) - return
-
-

Package summary

-

{current.status === 'awaiting_confirmation' - ? 'Review the contents, then confirm to create a new editable experiment.' - : 'Contents of the uploaded source package.'}

-
-
-
Published version
Source version {manifest.publication.version}
- {manifest.publication.name &&
{manifest.publication.name}
}
-
Historical results
{manifest.results_included ? 'Included' : 'Not included'}
-
- {contents.length > 0 &&
- - - - {contents.map(([name, count]) => - - - )} - -
Included package files by category
ContentsFiles
{categoryLabels[name] ?? name}{count.toLocaleString()}
Total files{contents.reduce((total, [, count]) => total + count, 0).toLocaleString()}
-
} -
- {unresolved !== undefined &&

0 ? 'text-amber-400' : 'text-muted-foreground'}>{unresolved > 0 - ? `${unresolved.toLocaleString()} unresolved ${unresolved === 1 ? 'dependency needs' : 'dependencies need'} attention` - : 'No unresolved dependencies reported'}

} - {external !== undefined &&

{external.toLocaleString()} external {external === 1 ? 'requirement' : 'requirements'}

} -

After import, configure local connections and resolve missing dependencies in the draft before publishing. Import does not run scripts or tools.

-
-
Package identifiers and format -
Package schema
{manifest.schema_version}
-
Source publication
{manifest.publication.id}
-
Archive SHA-256
{current.sha256 ?? 'Unavailable'}
-
-
-} - -/** Persistent imports can be resumed after navigation or a browser restart. */ -export function ExperimentPackageImport({ experimentId }: { experimentId?: string }) { - const client = useQueryClient() - const fileInputId = useId() - const [file, setFile] = useState(null) - const [selected, setSelected] = useState(null) - const [offset, setOffset] = useState(0) - const [error, setError] = useState(null) - const [uploading, setUploading] = useState(false) - const [preview, setPreview] = useState<{ importId: string; path: string; text?: string; error?: string; loading: boolean } | null>(null) - const previewRequest = useRef(0) - const selectedRef = useRef(selected) - selectedRef.current = selected - const uploadController = useRef(null) - const list = useQuery({ queryKey: ['package-imports', experimentId], queryFn: () => packageImportsApi.list(experimentId), - refetchInterval: (query) => query.state.data?.some((item) => ['uploading', 'validating', 'queued', 'activating'].includes(item.status)) ? 3000 : false }) - const job = useQuery({ queryKey: ['package-import', selected], enabled: selected !== null, - queryFn: () => packageImportsApi.get(selected!), - refetchInterval: (query) => !query.state.data || ['uploading', 'validating', 'queued', 'activating'].includes(query.state.data.status) ? 1000 : false }) - const current = job.data - const files = useQuery({ queryKey: ['package-import-files', selected, offset], - enabled: !!current?.preflight.manifest && !['expired', 'cancelled'].includes(current.status), - queryFn: () => packageImportsApi.files(selected!, offset) }) - const action = useMutation({ - mutationFn: async ({ id, command }: { id: string; command: 'confirm' | 'cancel' | 'retry' }) => packageImportsApi.command(id, command), - onSuccess: () => { - void client.invalidateQueries({ queryKey: ['package-import'] }) - void client.invalidateQueries({ queryKey: ['package-imports'] }) - void client.invalidateQueries({ queryKey: ['experiments'] }) - }, - onError: (cause) => setError(String(cause)), - }) - const upload = async (file: File) => { - setError(null) - setUploading(true) - try { - const created = current && ['uploading', 'failed'].includes(current.status) && !current.preflight.manifest - ? current : await packageImportsApi.create(newRequestKey()) - setSelected(created.id) - setOffset(0) - const controller = new AbortController() - uploadController.current = controller - await packageImportsApi.upload(created.id, file, controller.signal) - void client.invalidateQueries({ queryKey: ['package-imports'] }) - } catch (cause) { - if (!(cause instanceof DOMException && cause.name === 'AbortError')) setError(String(cause)) - } - finally { uploadController.current = null; setUploading(false) } - } - const download = async (id: string, path: string) => { - try { - const fresh = await packageImportsApi.get(id) - if (!fresh.source_url) throw new Error('Source download unavailable during activation or after expiry.') - const anchor = document.createElement('a') - anchor.href = `${fresh.source_url}&path=${encodeURIComponent(path)}` - anchor.click() - } - catch (cause) { setError(String(cause)) } - } - const inspectFile = async (id: string, path: string) => { - const request = ++previewRequest.current - setPreview({ importId: id, path, loading: true }) - try { - const blob = await packageImportsApi.source(id, path) - const text = await blob.text() - if (selectedRef.current === id && previewRequest.current === request) setPreview({ importId: id, path, text, loading: false }) - } catch (cause) { - if (selectedRef.current === id && previewRequest.current === request) { - setPreview({ importId: id, path, error: `Could not load this source file. ${String(cause)}`, loading: false }) - } - } - } - const closePreview = () => { - previewRequest.current += 1 - setPreview(null) - } - const select = (item: PackageImport) => { - setSelected(item.id); setOffset(0); setError(null); closePreview() - } - - return - {experimentId ? 'Imported source evidence' : 'Import experiment package'} - - {!experimentId && <> -

Upload a published experiment package. Review its contents before creating a new editable experiment. Import never runs packaged scripts or tools.

- { - if (picked) { setFile(picked); void upload(picked) } - }} /> - {current?.status === 'uploading' &&

To retry an interrupted upload, choose the package file again.

} - } -
{list.data?.map((item) => )}
- {(error || job.error || list.error) &&

{error ?? String(job.error ?? list.error)}

} - {current &&
-

{statusLabels[current.status] ?? current.status}{current.progress.scanned !== undefined ? ` · ${current.progress.scanned.toLocaleString()} processed` : ''}

- {current.error &&

{current.error}

} - {current.preflight.manifest && <> - - {current.preflight.warnings?.map((warning) =>

{warning}

)} - {current.preflight.compatibility?.map((issue) =>

{issue}

)} - {current.preflight.diagnostics?.map((item, index) =>

{item.kind} {item.id}: {item.reason ?? item.status}

)} -
- - Inspect source files and historical evidence - -

Browse original package files. Inspect JSON in a read-only viewer or download any file. Hover over a filename to see its SHA-256.

-
- - - - - - - - - - {files.isPending && } - {files.isError && } - {files.data?.items.length === 0 && } - {files.data?.items.map((file) => { - const isJson = file.path.endsWith('.json') - const FileIcon = isJson ? FileJson : File - const separator = file.path.lastIndexOf('/') - return - - - - - - })} - -
Source files and historical evidence
FileSizeSourceActions
Loading source files…

Could not load source files. {String(files.error)}

No source files listed.
-
{fileSize(file.bytes)}{provenanceLabels[file.provenance] ?? file.provenance.replaceAll('_', ' ')}
- {isJson && file.bytes <= 16 * 1024 * 1024 && } - -
-
-
-

{files.data?.items.length ? `Showing files ${(offset + 1).toLocaleString()}–${(offset + files.data.items.length).toLocaleString()}` : 'Source file inventory'}

-
-
-
-
- } -
- {current.status === 'awaiting_confirmation' && } - {current.status === 'failed' && } - {!['completed', 'expired', 'cancelled'].includes(current.status) && } - {current.experiment_id && } -
- {current.status === 'completed' && current.experiment_id && !experimentId && } -
} -
- { if (!open) closePreview() }}> - - - Inspect JSON - {preview?.path} - -

Read-only source file from the uploaded package.

- {preview?.loading &&

Loading JSON…

} - {preview?.error &&
-

{preview.error}

- -
} - {preview?.text !== undefined && } - -
-
-
-} diff --git a/frontend/src/components/protocol/ImportedExperimentSetup.test.tsx b/frontend/src/components/protocol/ImportedExperimentSetup.test.tsx deleted file mode 100644 index 7a8c9ec5..00000000 --- a/frontend/src/components/protocol/ImportedExperimentSetup.test.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { MemoryRouter } from 'react-router-dom' -import { afterEach, expect, it, vi } from 'vitest' -import { packageImportsApi } from '@/api/client' -import { ImportedExperimentSetup } from './ImportedExperimentSetup' - -afterEach(() => { cleanup(); vi.restoreAllMocks() }) - -it('keeps incomplete drafts accessible and requires explicit connection selection', async () => { - const options = { ready: false, issues: [{ node_id: 'tool', message: 'Choose a local connection' }], - providers: [{ provider: 'openai', id: 'saved-provider', selected: false }], - mcp: [{ source_id: 'source', name: 'Custom server', selected_id: null, - candidates: [{ id: 'one', name: 'Connection one' }, { id: 'two', name: 'Connection two' }] }] } - vi.spyOn(packageImportsApi, 'readiness').mockResolvedValue(options) - const select = vi.spyOn(packageImportsApi, 'selectConnection').mockResolvedValue(options) - const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - const onSelectNode = vi.fn() - render( - - ) - expect(await screen.findByText('Setup needed')).toBeInTheDocument() - expect(select).not.toHaveBeenCalled() - expect(screen.getByText(/Multiple compatible connections/)).toBeInTheDocument() - fireEvent.click(screen.getByRole('button', { name: 'Choose a local connection' })) - expect(onSelectNode).toHaveBeenCalledWith('tool') - fireEvent.change(screen.getByRole('combobox'), { target: { value: 'two' } }) - await waitFor(() => expect(select).toHaveBeenCalledWith('import', 'mcp', 'source', 'two')) - await waitFor(() => expect(screen.getByRole('button', { name: 'Use my saved connection' })).toBeEnabled()) - fireEvent.click(screen.getByRole('button', { name: 'Use my saved connection' })) - await waitFor(() => expect(select).toHaveBeenCalledWith('import', 'provider', 'openai', 'saved-provider')) - expect(screen.queryByRole('checkbox')).not.toBeInTheDocument() -}) diff --git a/frontend/src/components/protocol/ImportedExperimentSetup.tsx b/frontend/src/components/protocol/ImportedExperimentSetup.tsx deleted file mode 100644 index fda556c2..00000000 --- a/frontend/src/components/protocol/ImportedExperimentSetup.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Link } from 'react-router-dom' -import { packageImportsApi, protocolsApi } from '@/api/client' -import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' -import type { Edge, Node } from '@xyflow/react' -import type { Protocol, ProtocolGraph } from '@/types/protocols' -import { Button } from '@/components/ui/button' - -export function ImportedExperimentSetup({ importId, experimentId, onSelectNode, protocolId, onGraphChange }: { - importId: string; experimentId: string; onSelectNode?: (id: string) => void - protocolId?: string; onGraphChange?: (graph: ProtocolGraph) => void -}) { - const client = useQueryClient() - const effectiveProtocolId = protocolId ?? client.getQueryData(protocolForExperimentQueryKey(experimentId))?.id - const setup = useQuery({ queryKey: ['import-readiness', importId], queryFn: () => packageImportsApi.readiness(importId) }) - const selection = useMutation({ - mutationFn: async ({ kind, source, destination }: { kind: 'mcp' | 'provider'; source: string; destination: string }) => { - if (effectiveProtocolId) { - const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(effectiveProtocolId)) - if (live) await protocolsApi.update(effectiveProtocolId, { graph: toPersistedGraph(live.nodes, live.edges) }) - } - return packageImportsApi.selectConnection(importId, kind, source, destination) - }, - onSuccess: async data => { - client.setQueryData(['import-readiness', importId], data) - if (effectiveProtocolId) { - const fresh = await protocolsApi.get(effectiveProtocolId) - client.setQueryData(protocolForExperimentQueryKey(experimentId), fresh) - onGraphChange?.(fresh.graph) - } - void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) - }, - }) - return
-

{setup.data ? setup.data.ready ? 'Ready to publish' : 'Setup needed' : 'Checking publication readiness…'}

-

Checks saved configuration only. Test live connections explicitly in LLM Settings or MCP Servers. Publish normally when setup is complete.

- Manage destination model credentials - {(setup.error || selection.error) &&

{String(setup.error || selection.error)}

} - {setup.data?.issues.map((issue, index) =>

- {issue.node_id && onSelectNode ? - : {issue.message}} -

)} - {setup.data?.providers.map(provider =>
Model provider: {provider.provider} - -
)} - {setup.data?.mcp.map(requirement => )} - -
-} diff --git a/frontend/src/components/protocol/JsonSourceViewer.tsx b/frontend/src/components/protocol/JsonSourceViewer.tsx deleted file mode 100644 index c73ab177..00000000 --- a/frontend/src/components/protocol/JsonSourceViewer.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { useMemo, useState } from 'react' -import CodeMirror, { EditorView } from '@uiw/react-codemirror' -import { json } from '@codemirror/lang-json' -import { syntaxHighlighting } from '@codemirror/language' -import { oneDarkHighlightStyle } from '@codemirror/theme-one-dark' -import { Button } from '@/components/ui/button' -import { formatJsonSource } from '@/lib/jsonSource' - -const viewerTheme = EditorView.theme({ - '&': { backgroundColor: 'var(--background)', color: 'var(--foreground)', fontSize: '0.75rem' }, - '.cm-content': { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace' }, - '.cm-gutters': { backgroundColor: 'var(--muted)', color: 'var(--muted-foreground)', border: 'none' }, - '&.cm-focused': { outline: 'none' }, -}, { dark: true }) - -const extensions = [json(), syntaxHighlighting(oneDarkHighlightStyle), EditorView.lineWrapping, - EditorView.contentAttributes.of({ role: 'textbox', 'aria-label': 'JSON source', 'aria-readonly': 'true', tabindex: '0' })] - -export function JsonSourceViewer({ source }: { source: string }) { - const formatted = useMemo(() => formatJsonSource(source), [source]) - const [original, setOriginal] = useState(false) - return
-
-

Read-only JSON · expand or collapse sections in the gutter

- {formatted.formatted &&
- - -
} -
- {!formatted.formatted &&

Could not format this file as JSON. Showing the original text.

} - -
-} diff --git a/frontend/src/components/protocol/NodeInspectorDialog.tsx b/frontend/src/components/protocol/NodeInspectorDialog.tsx index eaf91669..82179558 100644 --- a/frontend/src/components/protocol/NodeInspectorDialog.tsx +++ b/frontend/src/components/protocol/NodeInspectorDialog.tsx @@ -5,6 +5,7 @@ import { Dialog, DialogContent } from '@/components/ui/dialog' import { Label } from '@/components/ui/label' import { Slider } from '@/components/ui/slider' import { cardAccent, cn, HUD_ACCENT_RING_CLASSNAME } from '@/lib/utils' +import { NodeInspectorResourceIssues } from './NodeResourceIssues' // Midpoint of the slider's own 20-100 range -- a visible, legible starting // point that still shows the transparency effect is there, rather than @@ -135,7 +136,7 @@ export function NodeInspectorDialog({ -
{children}
+
{children}
) diff --git a/frontend/src/components/protocol/NodeResourceIssues.test.tsx b/frontend/src/components/protocol/NodeResourceIssues.test.tsx new file mode 100644 index 00000000..21adf93c --- /dev/null +++ b/frontend/src/components/protocol/NodeResourceIssues.test.tsx @@ -0,0 +1,57 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { datasetsApi, mcpServersApi, packageImportsApi, protocolsApi } from '@/api/client' +import type { ImportReadiness, PackageImport } from '@/types/packageImports' +import type { Protocol } from '@/types/protocols' +import type { Node } from '@xyflow/react' +import { NodeInspectorResourceIssues, NodeResourceIssuesProvider } from './NodeResourceIssues' +import { withResourceWarnings } from './nodeResourceIssuesContext' +import { protocolGraphQueryKey } from '@/lib/protocolGraph' + +afterEach(() => vi.restoreAllMocks()) +const ResourceNode = withResourceWarnings(({ id }: { id: string }) => {id}) +function show(node: Node) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + render( + + + + + ) + return client +} + +it('uses ordinary registry validation for legacy JSON nodes and clears warnings after repair', async () => { + vi.spyOn(packageImportsApi, 'list').mockResolvedValue([]) + vi.spyOn(datasetsApi, 'list').mockResolvedValue([]) + const client = show({ id: 'dataset', type: 'dataset', position: { x: 0, y: 0 }, + data: { config: { dataset_id: 'missing' } } }) + expect(await screen.findByText('Dataset is no longer registered')).toBeInTheDocument() + act(() => client.setQueryData(['datasets'], [{ id: 'missing', raw_path: '/destination/raw.csv' }])) + await waitFor(() => expect(screen.queryByText('Dataset is no longer registered')).not.toBeInTheDocument()) +}) + +it('leaves a custom connection unselected and repairs it only in its node inspector', async () => { + vi.spyOn(packageImportsApi, 'list').mockResolvedValue([{ id: 'import', status: 'completed' } as PackageImport]) + vi.spyOn(mcpServersApi, 'list').mockResolvedValue([]) + const readiness: ImportReadiness = { ready: false, + issues: [{ node_id: 'tool', resource_id: 'source-tool', message: 'Choose a compatible connection' }], + mcp: [{ source_id: 'source-tool', name: 'Research tools', selected_id: null, + candidates: [{ id: 'destination', name: 'My tools' }] }] } + vi.spyOn(packageImportsApi, 'readiness').mockResolvedValue(readiness) + const select = vi.spyOn(packageImportsApi, 'selectConnection').mockResolvedValue({ ...readiness, ready: true, issues: [] }) + const update = vi.spyOn(protocolsApi, 'update').mockResolvedValue({} as Protocol) + vi.spyOn(protocolsApi, 'get').mockResolvedValue({ graph: { nodes: [], edges: [] } } as unknown as Protocol) + const node = { id: 'tool', type: 'mcp_tool', position: { x: 0, y: 0 }, + data: { config: { server_id: 'placeholder', tool_names: ['score'] } } } + const client = show(node) + client.setQueryData(protocolGraphQueryKey('p'), { nodes: [node], edges: [] }) + const picker = await screen.findByRole('combobox') + expect(picker).toHaveValue('') + expect(select).not.toHaveBeenCalled() + fireEvent.change(picker, { target: { value: 'destination' } }) + await waitFor(() => expect(select).toHaveBeenCalledWith('import', 'mcp', 'source-tool', 'destination')) + expect(update).toHaveBeenCalledWith('p', { graph: expect.objectContaining({ nodes: [node] }) }) +}) diff --git a/frontend/src/components/protocol/NodeResourceIssues.tsx b/frontend/src/components/protocol/NodeResourceIssues.tsx new file mode 100644 index 00000000..13a8c628 --- /dev/null +++ b/frontend/src/components/protocol/NodeResourceIssues.tsx @@ -0,0 +1,72 @@ +import { useContext, type ReactNode } from 'react' +import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query' +import type { Edge, Node } from '@xyflow/react' +import { datasetsApi, skillsApi, mcpServersApi, okfApi, llmSettingsApi, packageImportsApi, protocolsApi } from '@/api/client' +import { protocolForExperimentQueryKey, protocolGraphQueryKey, toPersistedGraph } from '@/lib/protocolGraph' +import type { ProtocolGraph } from '@/types/protocols' +import type { ImportReadiness } from '@/types/packageImports' +import { nodeResourceIssues } from './nodeConfigIssues' +import { ResourceIssues } from './nodeResourceIssuesContext' + +export function NodeResourceIssuesProvider({ experimentId, protocolId, selectedNodeId, onGraphChange, nodes, children }: { + experimentId?: string | null; protocolId: string; selectedNodeId: string | null + onGraphChange: (graph: ProtocolGraph) => void; children: ReactNode + nodes: Node[] +}) { + const client = useQueryClient() + const kinds = new Set(nodes.map(node => node.type)) + const registries = useQueries({ queries: [ + { queryKey: ['datasets'], queryFn: datasetsApi.list, enabled: kinds.has('dataset') }, + { queryKey: ['skills'], queryFn: skillsApi.list, enabled: kinds.has('skill') }, + { queryKey: ['mcp-servers'], queryFn: mcpServersApi.list, enabled: ['mcp_tool', 'mcp_client_tool', 'mcp_scikit_learn'].some(kind => kinds.has(kind)) }, + { queryKey: ['okf-bundles'], queryFn: okfApi.list, enabled: kinds.has('okf_bundle') }, + { queryKey: ['okf-documents'], queryFn: okfApi.listDocuments, enabled: kinds.has('okf_document') }, + { queryKey: ['llm-settings'], queryFn: llmSettingsApi.list, enabled: [...kinds].some(kind => kind?.startsWith('model_') || kind?.startsWith('llm_')) }, + ] }) + // Observe data updates as well as the initial load, including inspector repairs. + const loadedResources = registries.map(registry => registry.data) + const sources = useQuery({ queryKey: ['package-imports', experimentId], enabled: !!experimentId, + queryFn: () => packageImportsApi.list(experimentId!) }) + const source = sources.data?.find(item => item.status === 'completed') + const readiness = useQuery({ queryKey: ['import-readiness', source?.id], enabled: !!source, + queryFn: () => packageImportsApi.readiness(source!.id), refetchInterval: source ? 5000 : false }) + const selection = useMutation({ + mutationFn: async ({ requirement, destination }: { requirement: string; destination: string }) => { + const live = client.getQueryData<{ nodes: Node[]; edges: Edge[] }>(protocolGraphQueryKey(protocolId)) + if (live) await protocolsApi.update(protocolId, { graph: toPersistedGraph(live.nodes, live.edges) }) + return packageImportsApi.selectConnection(source!.id, 'mcp', requirement, destination) + }, + onSuccess: async result => { + client.setQueryData(['import-readiness', source!.id], result) + const fresh = await protocolsApi.get(protocolId) + client.setQueryData(protocolForExperimentQueryKey(experimentId!), fresh) + onGraphChange(fresh.graph) + void client.invalidateQueries({ queryKey: ['experiments', experimentId] }) + }, + }) + const localIssues = loadedResources.some(Boolean) ? nodes.flatMap(node => nodeResourceIssues(node, client) + .map(message => ({ node_id: node.id, message }))) : [] + const issues: ImportReadiness['issues'] = [...(readiness.data?.issues ?? []), ...localIssues] + const selectedIssues = issues.filter(issue => issue.node_id === selectedNodeId) + const requirements = readiness.data?.mcp.filter(requirement => selectedIssues.some(issue => issue.resource_id === requirement.source_id)) ?? [] + const inspector = <> + {selectedIssues.map((issue, index) =>

{issue.message}

)} + {requirements.map(requirement => )} + {(readiness.error || selection.error) &&

{(readiness.error || selection.error)?.message}

} + + return {children} +} + +export function NodeInspectorResourceIssues() { + return useContext(ResourceIssues).inspector +} diff --git a/frontend/src/components/protocol/ProtocolCanvas.tsx b/frontend/src/components/protocol/ProtocolCanvas.tsx index e9bc8971..07a26124 100644 --- a/frontend/src/components/protocol/ProtocolCanvas.tsx +++ b/frontend/src/components/protocol/ProtocolCanvas.tsx @@ -60,8 +60,8 @@ import { import '@xyflow/react/dist/style.css' import { Lock, Play, Plus, Square, X } from 'lucide-react' import { Button } from '@/components/ui/button' -import { ApiError, experimentsApi, protocolsApi, packageImportsApi } from '@/api/client' -import { ImportedExperimentSetup } from './ImportedExperimentSetup' +import { ApiError, experimentsApi, protocolsApi } from '@/api/client' +import { NodeResourceIssuesProvider } from './NodeResourceIssues' import { CONNECTOR_HANDLES } from '@/lib/coordinationStrategy' import { graphWithFactorBaseline, reconcileFactorBaselines, type FactorBindingDiscrepancy } from '@/lib/factorBindings' import { newNodeId } from '@/lib/nodeId' @@ -419,8 +419,7 @@ export const ProtocolCanvas = forwardRef(migrateLegacyNodes(initialGraph)) const [edges, setEdges, onEdgesChange] = useEdgesState(migrateLegacyHandles(initialGraph)) const queryClient = useQueryClient() - const importedSources = useQuery({ queryKey: ['package-imports', experimentId], enabled: !!experimentId, - queryFn: () => packageImportsApi.list(experimentId!) }) + // Mirrors the canvas's own live state into the shared query cache on // every change -- immediate, not debounced like autosave below, since @@ -2308,13 +2307,10 @@ export const ProtocolCanvas = forwardRef + { setNodes(migrateLegacyNodes(graph)); setEdges(migrateLegacyHandles(graph)) }}>
- {experimentId && !experimentLocked && importedSources.data?.filter(source => source.status === 'completed').map(source => -
- { setNodes(migrateLegacyNodes(graph)); setEdges(migrateLegacyHandles(graph)) }} /> -
)} editFactorMutation.mutateAsync({ oldName: editingFactor.name, next })} /> )} + ) }) diff --git a/frontend/src/components/protocol/ResultJobFlows.test.tsx b/frontend/src/components/protocol/ResultJobFlows.test.tsx index 351fe05a..b1aea02b 100644 --- a/frontend/src/components/protocol/ResultJobFlows.test.tsx +++ b/frontend/src/components/protocol/ResultJobFlows.test.tsx @@ -12,7 +12,6 @@ vi.mock('./RunConfirmDialog', () => ({ RunConfirmDialog: ({ additionalContent, o additionalContent: React.ReactNode; onConfirm: () => void; onPublishAndRun: () => void; onCancel: () => void confirmDisabled: boolean; publishDisabled: boolean; publishLabel?: string; publishError?: string }) =>
{additionalContent}{publishError &&

{publishError}

}
})) -vi.mock('./ExperimentDefinitionDownload', () => ({ ExperimentDefinitionDownload: () => null })) const row: ExecutionSlot = { slot_id: 'stable-slot', cell_id: 'cell', cell_label: 'model=a', factor_values: {}, replicate_id: 'parent', replicate_label: 'ambiguous-label', replicate_number: 1, row_result_id: null, row_index: null, dataset_id: null, raw_sha256: null, run_id: 'attempt', status: 'completed', updated_at: null, error: null, result: {}, usage: null } diff --git a/frontend/src/components/protocol/RunsTab.tsx b/frontend/src/components/protocol/RunsTab.tsx index 77c11a11..bce74f49 100644 --- a/frontend/src/components/protocol/RunsTab.tsx +++ b/frontend/src/components/protocol/RunsTab.tsx @@ -17,7 +17,6 @@ import type { ExecutionSlot } from '@/types/executionResults' import { ExecutionBrowser, ExecutionRows } from './ExecutionBrowser' import { runsAgainOnlyOnRequest } from '@/lib/protocolRun' import { newRequestKey } from '@/lib/requestKey' -import { ExperimentDefinitionDownload } from './ExperimentDefinitionDownload' import { RunConfirmDialog } from './RunConfirmDialog' import { ReplicateRunAction } from './CellPresentation' import type { ResultsSelection } from './ResultsTab' @@ -86,7 +85,6 @@ export function RunAllCellsButton({ protocol, experimentId, regenerationRequired {summary.error &&

{summary.error.message}

} {summary.data?.unit === 'row' &&

{summary.data.expected ?? '?'} expected rows across {summary.data.replicate_count ?? 0} replicates.

} {!experiment.data?.locked_at && } -

Completed {summary.data?.unit === 'row' ? 'rows' : 'replicates'}, including ones that hit their iteration limit, are skipped unless selected to run again.

{}} actions={row => runsAgainOnlyOnRequest(row.status) && = 100} onCheckedChange={checked => setReruns(current => { const next = new Set(current); if (checked) next.add(row.slot_id); else next.delete(row.slot_id); return next })} />} /> diff --git a/frontend/src/components/protocol/nodeConfigIssues.ts b/frontend/src/components/protocol/nodeConfigIssues.ts index 016ceaa0..df0bd9f3 100644 --- a/frontend/src/components/protocol/nodeConfigIssues.ts +++ b/frontend/src/components/protocol/nodeConfigIssues.ts @@ -6,6 +6,9 @@ import { isUnderIterated, raiseForTruncation, suggestedMaxIterations } from '@/l import type { LLMSettingModelsResponse, ModelCapabilities } from '@/types/llmSettings' import type { OkfBundle, OkfDocument } from '@/types/okf' import type { Skill } from '@/types/skills' +import type { Dataset } from '@/types/datasets' +import type { McpServer } from '@/types/mcpServers' +import type { LLMSetting } from '@/types/llmSettings' import type { DatasetNodeData, ModelNodeData, @@ -26,6 +29,52 @@ export interface NodeConfigIssue { issues: string[] } +// Registry checks are shared by canvas warnings and Run's preflight. They read +// normal application caches and never connect to external providers or tools. +export function nodeResourceIssues(node: Node, client: QueryClient): string[] { + const config = (node.data.config ?? {}) as Record + if (config.enabled === false || node.data.active === false) return [] + const issues: string[] = [] + if (node.type === 'dataset' && config.dataset_id) { + const datasets = client.getQueryData(['datasets']) + const dataset = datasets?.find(item => item.id === config.dataset_id) + if (datasets && !dataset) issues.push('Dataset is no longer registered') + else if (dataset && !dataset.raw_path) issues.push('Dataset source file is unavailable') + } + if (node.type === 'skill' && config.skill_id) { + const skills = client.getQueryData(['skills']) + if (skills && !skills.some(item => item.id === config.skill_id)) issues.push('Skill no longer exists') + } + if (node.type === 'okf_bundle' && config.bundle_id) { + const bundles = client.getQueryData(['okf-bundles']) + if (bundles && !bundles.some(item => item.id === config.bundle_id)) issues.push('OKF bundle is no longer registered') + } + if (node.type === 'okf_document' && config.document_id) { + const documents = client.getQueryData(['okf-documents']) + if (documents && !documents.some(item => item.id === config.document_id)) issues.push('OKF document is no longer stored') + } + if (['mcp_tool', 'mcp_client_tool', 'mcp_scikit_learn'].includes(node.type ?? '')) { + const servers = client.getQueryData(['mcp-servers']) + const server = servers?.find(item => item.id === config.server_id) + if (servers && !server) issues.push('MCP Server is unavailable; select a destination connection') + else if (server) { + if (!server.command && !server.url) issues.push('MCP Server connection is not configured') + if (server.error_message) issues.push(server.error_message) + const available = new Set(server.capabilities?.tools?.map(tool => tool.name) ?? []) + const required = Array.isArray(config.tool_names) ? config.tool_names : [] + if (required.some(tool => !available.has(tool))) issues.push('MCP Server lacks required tools') + } + } + if (node.type?.startsWith('model_') || node.type?.startsWith('llm_')) { + const provider = config.provider || node.type.replace(/^(model_|llm_)/, '') + const settings = client.getQueryData(['llm-settings']) + if (settings && !settings.some(setting => setting.provider === provider)) { + issues.push(`Configure your ${provider} connection in Profile`) + } + } + return issues +} + // A pre-flight scan run right before a real Run fires, so an obviously // misconfigured node (no model, no dataset or skill picked, no script code, an // agent with nothing wired into its required Model connector) surfaces as an @@ -64,7 +113,7 @@ export function findNodeConfigIssues( for (const node of nodes) { const data = node.data as { label?: string } | undefined const label = data?.label || node.type || 'node' - const issues: string[] = [] + const issues: string[] = nodeResourceIssues(node, queryClient) switch (node.type) { case 'agent': @@ -145,15 +194,6 @@ export function findNodeConfigIssues( // Same wording as SkillNode's own badge. if (!config?.skill_id) { issues.push('No skill selected') - } else { - // A set id can still resolve to nothing -- a skill deleted from the - // library, or a graph imported from another account, both leave the - // id (and its cached skill_name) behind. Cache-only, same contract - // as the model check above: a miss means "can't tell," not an issue. - const cached = queryClient.getQueryData(['skills']) - if (cached && !cached.some((s) => s.id === config.skill_id)) { - issues.push(`Skill no longer exists${config.skill_name ? ` ("${config.skill_name}")` : ''}`) - } } break } @@ -169,14 +209,6 @@ export function findNodeConfigIssues( // always a server that failed to spawn. The agent would get nothing // from the bundle, silently, so it's worth flagging up front. issues.push('No tools discovered -- the bundle server may have failed to start') - } else { - // A set id can still resolve to nothing -- deregistered, or a graph - // imported from another account. Cache-only, same contract as the - // skill check above: a miss means "can't tell," not an issue. - const cached = queryClient.getQueryData(['okf-bundles']) - if (cached && !cached.some((b) => b.id === config.bundle_id)) { - issues.push(`OKF bundle is no longer registered${config.bundle_path ? ` ("${config.bundle_path}")` : ''}`) - } } break } @@ -188,13 +220,6 @@ export function findNodeConfigIssues( issues.push('No document selected') } else if ((config.tool_names?.length ?? 0) === 0) { issues.push('No tools discovered -- the document server may have failed to start') - } else { - const cached = queryClient.getQueryData(['okf-documents']) - if (cached && !cached.some((d) => d.id === config.document_id)) { - issues.push( - `OKF document is no longer stored${config.document_title ? ` ("${config.document_title}")` : ''}`, - ) - } } break } diff --git a/frontend/src/components/protocol/nodeResourceIssuesContext.ts b/frontend/src/components/protocol/nodeResourceIssuesContext.ts new file mode 100644 index 00000000..b3703523 --- /dev/null +++ b/frontend/src/components/protocol/nodeResourceIssuesContext.ts @@ -0,0 +1,14 @@ +import { createContext, createElement, useContext, type ComponentType, type ReactNode } from 'react' +import type { ImportReadiness } from '@/types/packageImports' +import { WarningBadge } from './nodes/WarningBadge' + +export const ResourceIssues = createContext<{ issues: ImportReadiness['issues']; inspector: ReactNode }>({ issues: [], inspector: null }) + +// One wrapper applies resource warnings to every registered node renderer. +export function withResourceWarnings

(Renderer: ComponentType

) { + return function ResourceNode(props: P) { + const issues = useContext(ResourceIssues).issues.filter(issue => issue.node_id === props.id).map(issue => issue.message) + return createElement('div', { className: 'relative' }, createElement(Renderer, props), + issues.length ? createElement(WarningBadge, { issues, className: 'absolute -left-1 -top-1 z-10' }) : null) + } +} diff --git a/frontend/src/components/protocol/protocolNodeTypes.ts b/frontend/src/components/protocol/protocolNodeTypes.ts index ad9fe727..f930c9e2 100644 --- a/frontend/src/components/protocol/protocolNodeTypes.ts +++ b/frontend/src/components/protocol/protocolNodeTypes.ts @@ -14,16 +14,17 @@ import { SingleAgentBaselinePatternNode } from './nodes/SingleAgentBaselinePatte import { OkfBundleNode } from './nodes/OkfBundleNode' import { OkfDocumentNode } from './nodes/OkfDocumentNode' import { SkillNode } from './nodes/SkillNode' +import { withResourceWarnings } from './nodeResourceIssuesContext' export const NODE_TYPES = { - agent: AgentNode, sub_agent: AgentNode, - mcp_tool: McpToolNode, mcp_scikit_learn: McpToolNode, mcp_client_tool: McpClientToolNode, - critic_gate: CriticGateNode, tool_step: ToolStepNode, - model_anthropic: ModelNode, model_openai: ModelNode, model_azure_foundry: ModelNode, - model_openrouter: ModelNode, model_local: ModelNode, - memory: MemoryNode, output_parser: OutputParserNode, dataset: DatasetNode, - persona: PersonaNode, - skill: SkillNode, okf_bundle: OkfBundleNode, okf_document: OkfDocumentNode, - script: ScriptNode, pattern_reason_act: ReasonActPatternNode, - pattern_single_agent_baseline: SingleAgentBaselinePatternNode, + agent: withResourceWarnings(AgentNode), sub_agent: withResourceWarnings(AgentNode), + mcp_tool: withResourceWarnings(McpToolNode), mcp_scikit_learn: withResourceWarnings(McpToolNode), mcp_client_tool: withResourceWarnings(McpClientToolNode), + critic_gate: withResourceWarnings(CriticGateNode), tool_step: withResourceWarnings(ToolStepNode), + model_anthropic: withResourceWarnings(ModelNode), model_openai: withResourceWarnings(ModelNode), model_azure_foundry: withResourceWarnings(ModelNode), + model_openrouter: withResourceWarnings(ModelNode), model_local: withResourceWarnings(ModelNode), + memory: withResourceWarnings(MemoryNode), output_parser: withResourceWarnings(OutputParserNode), dataset: withResourceWarnings(DatasetNode), + persona: withResourceWarnings(PersonaNode), + skill: withResourceWarnings(SkillNode), okf_bundle: withResourceWarnings(OkfBundleNode), okf_document: withResourceWarnings(OkfDocumentNode), + script: withResourceWarnings(ScriptNode), pattern_reason_act: withResourceWarnings(ReasonActPatternNode), + pattern_single_agent_baseline: withResourceWarnings(SingleAgentBaselinePatternNode), } diff --git a/frontend/src/components/protocol/useProviderModels.test.tsx b/frontend/src/components/protocol/useProviderModels.test.tsx index ace0d3dc..35347912 100644 --- a/frontend/src/components/protocol/useProviderModels.test.tsx +++ b/frontend/src/components/protocol/useProviderModels.test.tsx @@ -12,7 +12,7 @@ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() }) it('automatically refreshes a mounted provider model list without navigation', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) const response = (id: string): LLMSettingModelsResponse => ({ models: [{ id, label: id, supports_temperature: true, supports_effort: false, effort_levels: [], supports_tool_calling: true }], source: 'api', @@ -38,7 +38,7 @@ it.each([ ['truly-unknown', false, true, 'medium'], ] as const)('uses backend capabilities for off-catalog %s and run warnings', async (model, temperature, effort, defaultEffort) => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) const metadata = { supports_temperature: temperature, supports_effort: effort, effort_levels: effort ? ['low', 'medium', 'high'] : [], default_effort: defaultEffort } const resolve = vi.spyOn(llmSettingsApi, 'modelCapabilities').mockResolvedValue(metadata) @@ -62,7 +62,7 @@ it.each([ it('debounces changed custom IDs and never displays the previous model capabilities', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) const metadata = { supports_temperature: false, supports_effort: true, effort_levels: ['medium'], default_effort: 'medium' } const resolve = vi.spyOn(llmSettingsApi, 'modelCapabilities').mockResolvedValue(metadata) @@ -85,7 +85,7 @@ it('debounces changed custom IDs and never displays the previous model capabilit it('does not resolve custom capabilities when an explicit override is present', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) const resolve = vi.spyOn(llmSettingsApi, 'modelCapabilities') const override = { supports_temperature: true, supports_effort: false, effort_levels: [], default_effort: null } @@ -101,7 +101,7 @@ it('does not resolve custom capabilities when an explicit override is present', it('reports a failed custom lookup instead of guessing effort', async () => { vi.useFakeTimers() - vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([]) + vi.spyOn(llmSettingsApi, 'list').mockResolvedValue([{ provider: 'openai', api_base: null, azure_project_endpoint: null }]) vi.spyOn(llmSettingsApi, 'listModels').mockResolvedValue({ models: [], source: 'static', note: null }) vi.spyOn(llmSettingsApi, 'modelCapabilities').mockRejectedValue(new Error('offline')) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) diff --git a/frontend/src/lib/jsonSource.test.ts b/frontend/src/lib/jsonSource.test.ts deleted file mode 100644 index 3f5b242f..00000000 --- a/frontend/src/lib/jsonSource.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { expect, it } from 'vitest' -import { formatJsonSource } from './jsonSource' - -it('indents JSON without changing exact numbers, string escapes, duplicate keys, or opaque values', () => { - const source = '{"large":9007199254740993,"decimal":1.2300e+30,"value":null,"value":false,"escaped":"a\\nb","list":[1,2]}' - const result = formatJsonSource(source) - expect(result.formatted).toBe(true) - expect(result.text).toBe([ - '{', - ' "large": 9007199254740993,', - ' "decimal": 1.2300e+30,', - ' "value": null,', - ' "value": false,', - ' "escaped": "a\\nb",', - ' "list": [', - ' 1,', - ' 2', - ' ]', - '}', - ].join('\n')) -}) - -it('retains malformed or non-JSON source text for inspection', () => { - for (const source of ['{"missing":', '{"trailing":true,}', 'not JSON', '']) { - expect(formatJsonSource(source)).toEqual({ text: source, formatted: false }) - } -}) diff --git a/frontend/src/lib/jsonSource.ts b/frontend/src/lib/jsonSource.ts deleted file mode 100644 index d6462684..00000000 --- a/frontend/src/lib/jsonSource.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { applyEdits, format, visit } from 'jsonc-parser' - -/** Format whitespace without reserializing numbers, strings, or duplicate keys. */ -export function formatJsonSource(source: string): { text: string; formatted: boolean } { - try { - let valid = true - visit(source, { onError: () => { valid = false } }, { disallowComments: true, allowTrailingComma: false }) - if (!valid) return { text: source, formatted: false } - return { text: applyEdits(source, format(source, undefined, { tabSize: 2, insertSpaces: true, eol: '\n' })), formatted: true } - } catch { - return { text: source, formatted: false } - } -} diff --git a/frontend/src/pages/ExperimentsPage.tsx b/frontend/src/pages/ExperimentsPage.tsx index eac4d2f2..db276c24 100644 --- a/frontend/src/pages/ExperimentsPage.tsx +++ b/frontend/src/pages/ExperimentsPage.tsx @@ -14,7 +14,6 @@ import { } from 'lucide-react' import { useNavigate } from 'react-router-dom' import { AppHeader } from '@/components/AppHeader' -import { ExperimentPackageImport } from '@/components/protocol/ExperimentPackageImport' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' @@ -141,7 +140,6 @@ export function ExperimentsPage() {

-
)} - {packageId &&

{packageJob.data?.status === 'failed' + {packageId &&

{packageJob.data?.status === 'failed' ? packageJob.data.error : `Creating experiment… ${packageJob.data?.progress.phase ?? 'Uploading'}`}

} {packageJob.error &&

{packageJob.error.message}

} {packageJob.data?.status === 'failed' &&